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 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	/// Global secp context.
46	pub static ref SECP: secp256k1::Secp256k1<secp256k1::All> = secp256k1::Secp256k1::new();
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub struct ArkInfo {
51	/// The bitcoin network the server operates on
52	pub network: Network,
53	/// The Ark server pubkey
54	pub server_pubkey: PublicKey,
55	/// The interval between each round
56	pub round_interval: Duration,
57	/// Number of nonces per round
58	pub nb_round_nonces: usize,
59	/// Delta between exit confirmation and coins becoming spendable
60	pub vtxo_exit_delta: BlockDelta,
61	/// Expiration delta of the VTXO
62	pub vtxo_expiry_delta: BlockDelta,
63	/// The number of blocks after which an HTLC-send VTXO expires once granted.
64	pub htlc_send_expiry_delta: BlockDelta,
65	/// The number of blocks to keep between Lightning and Ark HTLCs expiries
66	pub htlc_expiry_delta: BlockDelta,
67	/// Maximum amount of a VTXO
68	pub max_vtxo_amount: Option<Amount>,
69	/// The number of confirmations required to register a board vtxo
70	pub required_board_confirmations: usize,
71	/// Maximum CLTV delta server will allow clients to request an
72	/// invoice generation with.
73	pub max_user_invoice_cltv_delta: u16,
74	/// Minimum amount for a board the server will cosign
75	pub min_board_amount: Amount,
76
77	//TODO(stevenroose) move elsewhere eith other temp fields
78	pub offboard_feerate: FeeRate,
79	/// Indicates whether the Ark server requires clients to either
80	/// provide a VTXO ownership proof, or a lightning receive token
81	/// when preparing a lightning claim.
82	pub ln_receive_anti_dos_required: bool,
83}
84
85/// Input of a round
86#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
87pub struct VtxoIdInput {
88	pub vtxo_id: VtxoId,
89	/// A schnorr signature over a message containing a static prefix,
90	/// a random challenge generated by the server and the VTXO's id.
91	/// See [`challenges::RoundAttemptChallenge`].
92	///
93	/// Should be produced using VTXO's private key
94	pub ownership_proof: schnorr::Signature,
95}
96
97/// Request for the creation of an vtxo.
98#[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	/// The actual VTXO request.
108	pub vtxo: VtxoRequest,
109	/// The public key used by the client to cosign the transaction tree
110	/// The client SHOULD forget this key after signing it
111	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	/// Calculate the fee we have to charge for adding an output
130	/// with the given scriptPubkey to a transaction.
131	///
132	/// Returns an error if the output type is non-standard.
133	pub fn calculate_fee(
134		script_pubkey: &Script,
135		fee_rate: FeeRate,
136	) -> Result<Amount, InvalidOffboardRequestError> {
137		// NB We calculate the required extra fee as the "dust" fee for the given feerate.
138		// We take Bitcoin's dust amounts, which are calculated at 3 sat/vb, but then
139		// calculated for the given feerate. For more on dust, see:
140		// https://bitcoin.stackexchange.com/questions/10986/what-is-meant-by-bitcoin-dust
141
142		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  // output amount
159					// the input data (scriptSig and witness length fields included)
160					+ 36 // input prevout
161					+ 4  // sequence
162					+ 1  // 0 length scriptsig
163					+ 1  // 0 length witness
164			}
165		} else {
166			return Err(InvalidOffboardRequestError("non-standard scriptPubkey"));
167		};
168		Ok(fee_rate * Weight::from_vb(vb).expect("no overflow"))
169	}
170
171	/// Validate that the offboard has a valid script.
172	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	/// Convert into a tx output.
181	pub fn to_txout(&self) -> TxOut {
182		TxOut {
183			script_pubkey: self.script_pubkey.clone(),
184			value: self.amount,
185		}
186	}
187
188	/// Returns the fee charged for the user to make this offboard given the fee rate.
189	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	/// Create a tapscript that is a checksig and a relative timelock.
204	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	/// Create a tapscript that is a checksig and an absolute timelock.
216	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	/// Create a tapscript
228	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	/// Fill in the signatures into the unsigned transaction.
272	///
273	/// Panics if the nb of inputs and signatures doesn't match or if some input
274	/// witnesses are not empty.
275	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	/// Verify a partial signature from either of the two parties cosigning a tx.
285	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}