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 challenges;
12pub mod connectors;
13pub mod encode;
14pub mod error;
15pub mod forfeit;
16pub mod lightning;
17pub mod mailbox;
18pub mod musig;
19pub mod board;
20pub mod rounds;
21pub mod tree;
22pub mod vtxo;
23pub mod integration;
24
25pub use crate::address::Address;
26pub use crate::encode::{ProtocolEncoding, WriteExt, ReadExt, ProtocolDecodingError};
27pub use crate::vtxo::{Vtxo, VtxoId, VtxoPolicy};
28
29#[cfg(test)]
30mod napkin;
31#[cfg(any(test, feature = "test-util"))]
32pub mod test;
33
34
35use std::time::Duration;
36
37use bitcoin::{Amount, FeeRate, Network, Script, ScriptBuf, TxOut, Weight};
38use bitcoin::secp256k1::{self, schnorr, PublicKey};
39
40use bitcoin_ext::{
41 BlockDelta, TxOutExt, P2PKH_DUST_VB, P2SH_DUST_VB, P2TR_DUST_VB, P2WPKH_DUST_VB, P2WSH_DUST_VB
42};
43
44lazy_static! {
45 pub static ref SECP: secp256k1::Secp256k1<secp256k1::All> = secp256k1::Secp256k1::new();
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub struct ArkInfo {
51 pub network: Network,
53 pub server_pubkey: PublicKey,
55 pub round_interval: Duration,
57 pub nb_round_nonces: usize,
59 pub vtxo_exit_delta: BlockDelta,
61 pub vtxo_expiry_delta: BlockDelta,
63 pub htlc_send_expiry_delta: BlockDelta,
65 pub htlc_expiry_delta: BlockDelta,
67 pub max_vtxo_amount: Option<Amount>,
69 pub required_board_confirmations: usize,
71 pub max_user_invoice_cltv_delta: u16,
74 pub min_board_amount: Amount,
76
77 pub offboard_feerate: FeeRate,
79 pub ln_receive_anti_dos_required: bool,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
87pub struct VtxoIdInput {
88 pub vtxo_id: VtxoId,
89 pub ownership_proof: schnorr::Signature,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
99pub struct VtxoRequest {
100 pub amount: Amount,
101 #[serde(with = "crate::encode::serde")]
102 pub policy: VtxoPolicy,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
106pub struct SignedVtxoRequest {
107 pub vtxo: VtxoRequest,
109 pub cosign_pubkey: Option<PublicKey>,
112}
113
114
115#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
116#[error("invalid offboard request: {0}")]
117pub struct InvalidOffboardRequestError(&'static str);
118
119
120#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
121pub struct OffboardRequest {
122 #[serde(with = "bitcoin_ext::serde::encodable")]
123 pub script_pubkey: ScriptBuf,
124 #[serde(rename = "amount_sat", with = "bitcoin::amount::serde::as_sat")]
125 pub amount: Amount,
126}
127
128impl OffboardRequest {
129 pub fn calculate_fee(
134 script_pubkey: &Script,
135 fee_rate: FeeRate,
136 ) -> Result<Amount, InvalidOffboardRequestError> {
137 let vb = if script_pubkey.is_p2pkh() {
143 P2PKH_DUST_VB
144 } else if script_pubkey.is_p2sh() {
145 P2SH_DUST_VB
146 } else if script_pubkey.is_p2wpkh() {
147 P2WPKH_DUST_VB
148 } else if script_pubkey.is_p2wsh() {
149 P2WSH_DUST_VB
150 } else if script_pubkey.is_p2tr() {
151 P2TR_DUST_VB
152 } else if script_pubkey.is_op_return() {
153 if script_pubkey.len() > 83 {
154 return Err(InvalidOffboardRequestError("OP_RETURN over 83 bytes"));
155 } else {
156 bitcoin::consensus::encode::VarInt(script_pubkey.len() as u64).size() as u64
157 + script_pubkey.len() as u64
158 + 8 + 36 + 4 + 1 + 1 }
165 } else {
166 return Err(InvalidOffboardRequestError("non-standard scriptPubkey"));
167 };
168 Ok(fee_rate * Weight::from_vb(vb).expect("no overflow"))
169 }
170
171 pub fn validate(&self) -> Result<(), InvalidOffboardRequestError> {
173 if self.to_txout().is_standard() {
174 Ok(())
175 } else {
176 Err(InvalidOffboardRequestError("non-standard output"))
177 }
178 }
179
180 pub fn to_txout(&self) -> TxOut {
182 TxOut {
183 script_pubkey: self.script_pubkey.clone(),
184 value: self.amount,
185 }
186 }
187
188 pub fn fee(&self, fee_rate: FeeRate) -> Result<Amount, InvalidOffboardRequestError> {
190 Ok(Self::calculate_fee(&self.script_pubkey, fee_rate)?)
191 }
192}
193
194pub mod scripts {
195 use bitcoin::{opcodes, ScriptBuf, TapSighash, TapTweakHash, Transaction};
196 use bitcoin::hashes::{sha256, ripemd160, Hash};
197 use bitcoin::secp256k1::{schnorr, PublicKey, XOnlyPublicKey};
198
199 use bitcoin_ext::{BlockDelta, BlockHeight, TAPROOT_KEYSPEND_WEIGHT};
200
201 use crate::musig;
202
203 pub fn delayed_sign(delay_blocks: BlockDelta, pubkey: XOnlyPublicKey) -> ScriptBuf {
205 let csv = bitcoin::Sequence::from_height(delay_blocks);
206 bitcoin::Script::builder()
207 .push_int(csv.to_consensus_u32() as i64)
208 .push_opcode(opcodes::all::OP_CSV)
209 .push_opcode(opcodes::all::OP_DROP)
210 .push_x_only_key(&pubkey)
211 .push_opcode(opcodes::all::OP_CHECKSIG)
212 .into_script()
213 }
214
215 pub fn timelock_sign(timelock_height: BlockHeight, pubkey: XOnlyPublicKey) -> ScriptBuf {
217 let lt = bitcoin::absolute::LockTime::from_height(timelock_height).unwrap();
218 bitcoin::Script::builder()
219 .push_int(lt.to_consensus_u32() as i64)
220 .push_opcode(opcodes::all::OP_CLTV)
221 .push_opcode(opcodes::all::OP_DROP)
222 .push_x_only_key(&pubkey)
223 .push_opcode(opcodes::all::OP_CHECKSIG)
224 .into_script()
225 }
226
227 pub fn delay_timelock_sign(delay_blocks: BlockDelta, timelock_height: BlockHeight, pubkey: XOnlyPublicKey) -> ScriptBuf {
229 let csv = bitcoin::Sequence::from_height(delay_blocks);
230 let lt = bitcoin::absolute::LockTime::from_height(timelock_height).unwrap();
231 bitcoin::Script::builder()
232 .push_int(lt.to_consensus_u32().try_into().unwrap())
233 .push_opcode(opcodes::all::OP_CLTV)
234 .push_opcode(opcodes::all::OP_DROP)
235 .push_int(csv.to_consensus_u32().try_into().unwrap())
236 .push_opcode(opcodes::all::OP_CSV)
237 .push_opcode(opcodes::all::OP_DROP)
238 .push_x_only_key(&pubkey)
239 .push_opcode(opcodes::all::OP_CHECKSIG)
240 .into_script()
241 }
242
243 pub fn hash_and_sign(hash: sha256::Hash, pubkey: XOnlyPublicKey) -> ScriptBuf {
244 let hash_160 = ripemd160::Hash::hash(&hash[..]);
245
246 bitcoin::Script::builder()
247 .push_opcode(opcodes::all::OP_HASH160)
248 .push_slice(hash_160.as_byte_array())
249 .push_opcode(opcodes::all::OP_EQUALVERIFY)
250 .push_x_only_key(&pubkey)
251 .push_opcode(opcodes::all::OP_CHECKSIG)
252 .into_script()
253 }
254
255 pub fn hash_delay_sign(hash: sha256::Hash, delay_blocks: BlockDelta, pubkey: XOnlyPublicKey) -> ScriptBuf {
256 let hash_160 = ripemd160::Hash::hash(&hash[..]);
257 let csv = bitcoin::Sequence::from_height(delay_blocks);
258
259 bitcoin::Script::builder()
260 .push_int(csv.to_consensus_u32().try_into().unwrap())
261 .push_opcode(opcodes::all::OP_CSV)
262 .push_opcode(opcodes::all::OP_DROP)
263 .push_opcode(opcodes::all::OP_HASH160)
264 .push_slice(hash_160.as_byte_array())
265 .push_opcode(opcodes::all::OP_EQUALVERIFY)
266 .push_x_only_key(&pubkey)
267 .push_opcode(opcodes::all::OP_CHECKSIG)
268 .into_script()
269 }
270
271 pub fn fill_taproot_sigs(tx: &mut Transaction, sigs: &[schnorr::Signature]) {
276 assert_eq!(tx.input.len(), sigs.len());
277 for (input, sig) in tx.input.iter_mut().zip(sigs.iter()) {
278 assert!(input.witness.is_empty());
279 input.witness.push(&sig[..]);
280 debug_assert_eq!(TAPROOT_KEYSPEND_WEIGHT, input.witness.size());
281 }
282 }
283
284 pub fn verify_partial_sig(
286 sighash: TapSighash,
287 tweak: TapTweakHash,
288 signer: (PublicKey, &musig::PublicNonce),
289 other: (PublicKey, &musig::PublicNonce),
290 partial_signature: &musig::PartialSignature,
291 ) -> bool {
292 let agg_nonce = musig::nonce_agg(&[&signer.1, &other.1]);
293 let agg_pk = musig::tweaked_key_agg([signer.0, other.0], tweak.to_byte_array()).0;
294
295 let session = musig::Session::new(&agg_pk, agg_nonce, &sighash.to_byte_array());
296 session.partial_verify(
297 &agg_pk, partial_signature, signer.1, musig::pubkey_to(signer.0),
298 )
299 }
300}