ark/
lib.rs

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	/// Global secp context.
45	pub static ref SECP: secp256k1::Secp256k1<secp256k1::All> = secp256k1::Secp256k1::new();
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub struct ArkInfo {
50	/// The bitcoin network the server operates on
51	pub network: Network,
52	/// The Ark server pubkey
53	pub server_pubkey: PublicKey,
54	/// The interval between each round
55	pub round_interval: Duration,
56	/// Number of nonces per round
57	pub nb_round_nonces: usize,
58	/// Delta between exit confirmation and coins becoming spendable
59	pub vtxo_exit_delta: BlockDelta,
60	/// Expiration delta of the VTXO
61	pub vtxo_expiry_delta: BlockDelta,
62	/// The number of blocks after which an HTLC-send VTXO expires once granted.
63	pub htlc_send_expiry_delta: BlockDelta,
64	/// The number of blocks to keep between Lightning and Ark HTLCs expiries
65	pub htlc_expiry_delta: BlockDelta,
66	/// Maximum amount of a VTXO
67	pub max_vtxo_amount: Option<Amount>,
68	/// Maximum number of OOR transition after VTXO tree leaf
69	pub max_arkoor_depth: u16,
70	/// The number of confirmations required to register a board vtxo
71	pub required_board_confirmations: usize,
72	/// Maximum CLTV delta server will allow clients to request an
73	/// invoice generation with.
74	pub max_user_invoice_cltv_delta: u16,
75	/// Minimum amount for a board the server will cosign
76	pub min_board_amount: Amount,
77}
78
79/// Input of a round
80#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
81pub struct VtxoIdInput {
82	pub vtxo_id: VtxoId,
83	/// A schnorr signature over a message containing a static prefix,
84	/// a random challenge generated by the server and the VTXO's id.
85	/// See [`rounds::VtxoOwnershipChallenge`].
86	///
87	/// Should be produced using VTXO's private key
88	pub ownership_proof: schnorr::Signature,
89}
90
91/// Request for the creation of an vtxo.
92#[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	/// The actual VTXO request.
102	pub vtxo: VtxoRequest,
103	/// The public key used by the client to cosign the transaction tree
104	/// The client SHOULD forget this key after signing it
105	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	/// Calculate the fee we have to charge for adding an output
123	/// with the given scriptPubkey to a transaction.
124	///
125	/// Returns an error if the output type is non-standard.
126	pub fn calculate_fee(
127		script_pubkey: &Script,
128		fee_rate: FeeRate,
129	) -> Result<Amount, InvalidOffboardRequestError> {
130		// NB We calculate the required extra fee as the "dust" fee for the given feerate.
131		// We take Bitcoin's dust amounts, which are calculated at 3 sat/vb, but then
132		// calculated for the given feerate. For more on dust, see:
133		// https://bitcoin.stackexchange.com/questions/10986/what-is-meant-by-bitcoin-dust
134
135		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  // output amount
152					// the input data (scriptSig and witness length fields included)
153					+ 36 // input prevout
154					+ 4  // sequence
155					+ 1  // 0 length scriptsig
156					+ 1  // 0 length witness
157			}
158		} else {
159			return Err(InvalidOffboardRequestError("non-standard scriptPubkey"));
160		};
161		Ok(fee_rate * Weight::from_vb(vb).expect("no overflow"))
162	}
163
164	/// Validate that the offboard has a valid script.
165	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	/// Convert into a tx output.
174	pub fn to_txout(&self) -> TxOut {
175		TxOut {
176			script_pubkey: self.script_pubkey.clone(),
177			value: self.amount,
178		}
179	}
180
181	/// Returns the fee charged for the user to make this offboard given the fee rate.
182	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	/// Create a tapscript that is a checksig and a relative timelock.
197	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	/// Create a tapscript that is a checksig and an absolute timelock.
209	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	/// Create a tapscript
221	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	/// Fill in the signatures into the unsigned transaction.
265	///
266	/// Panics if the nb of inputs and signatures doesn't match or if some input
267	/// witnesses are not empty.
268	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	/// Verify a partial signature from either of the two parties cosigning a tx.
278	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}