Skip to main content

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] pub mod util;
8
9pub mod address;
10pub mod arkoor;
11pub mod attestations;
12pub mod board;
13pub mod connectors;
14pub mod encode;
15pub mod error;
16pub mod fees;
17pub mod forfeit;
18pub mod lightning;
19pub mod mailbox;
20pub mod musig;
21pub mod offboard;
22pub mod rounds;
23pub mod time;
24pub mod tree;
25pub mod vtxo;
26pub mod integration;
27
28pub use crate::address::Address;
29pub use crate::encode::{ProtocolEncoding, WriteExt, ReadExt, ProtocolDecodingError};
30pub use crate::vtxo::{Vtxo, VtxoId, VtxoPolicy, ServerVtxoPolicy, ServerVtxo};
31
32#[cfg(test)]
33mod napkin;
34#[cfg(any(test, feature = "test-util"))]
35pub mod test_util;
36
37
38use std::time::Duration;
39
40use bitcoin::{Amount, FeeRate, Network};
41use bitcoin::secp256k1::{self, PublicKey};
42
43use bitcoin_ext::BlockDelta;
44
45use crate::fees::FeeSchedule;
46
47lazy_static! {
48	/// Global secp context.
49	pub static ref SECP: secp256k1::Secp256k1<secp256k1::All> = secp256k1::Secp256k1::new();
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct ArkInfo {
54	/// The bitcoin network the server operates on
55	pub network: Network,
56	/// The Ark server pubkey
57	pub server_pubkey: PublicKey,
58	/// The pubkey used for blinding unified mailbox IDs
59	pub mailbox_pubkey: PublicKey,
60	/// The interval between each round
61	pub round_interval: Duration,
62	/// Number of nonces per round
63	pub nb_round_nonces: usize,
64	/// Delta between exit confirmation and coins becoming spendable
65	pub vtxo_exit_delta: BlockDelta,
66	/// Expiration delta of the VTXO
67	pub vtxo_expiry_delta: BlockDelta,
68	/// The number of blocks after which an HTLC-send VTXO expires once granted.
69	pub htlc_send_expiry_delta: BlockDelta,
70	/// The number of blocks to keep between Lightning and Ark HTLCs expiries
71	pub htlc_expiry_delta: BlockDelta,
72	/// Maximum amount of a VTXO
73	pub max_vtxo_amount: Option<Amount>,
74	/// The number of confirmations required to register a board vtxo
75	pub required_board_confirmations: usize,
76	/// Maximum CLTV delta server will allow clients to request an
77	/// invoice generation with.
78	pub max_user_invoice_cltv_delta: u16,
79	/// Minimum amount for a board the server will cosign
80	pub min_board_amount: Amount,
81
82	//TODO(stevenroose) move elsewhere eith other temp fields
83
84	/// The feerate for offboards
85	pub offboard_feerate: FeeRate,
86
87	/// Indicates whether the Ark server requires clients to either
88	/// provide a VTXO ownership proof, or a lightning receive token
89	/// when preparing a lightning claim.
90	pub ln_receive_anti_dos_required: bool,
91
92	/// Fee schedule for all Ark operations
93	pub fees: FeeSchedule,
94}
95
96/// Request for the creation of an vtxo.
97#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
98pub struct VtxoRequest {
99	pub amount: Amount,
100	#[serde(with = "crate::encode::serde")]
101	pub policy: VtxoPolicy,
102}
103
104impl AsRef<VtxoRequest> for VtxoRequest {
105	fn as_ref(&self) -> &VtxoRequest {
106	    self
107	}
108}
109
110/// Request for the creation of an vtxo in a signed round
111#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
112pub struct SignedVtxoRequest {
113	/// The actual VTXO request.
114	pub vtxo: VtxoRequest,
115	/// The public key used by the client to cosign the transaction tree
116	/// The client SHOULD forget this key after signing it
117	pub cosign_pubkey: PublicKey,
118	/// The public cosign nonces for the cosign pubkey
119	pub nonces: Vec<musig::PublicNonce>,
120}
121
122impl AsRef<VtxoRequest> for SignedVtxoRequest {
123	fn as_ref(&self) -> &VtxoRequest {
124	    &self.vtxo
125	}
126}
127
128pub mod scripts {
129	use bitcoin::{opcodes, ScriptBuf, TapSighash, TapTweakHash, Transaction};
130	use bitcoin::hashes::{sha256, ripemd160, Hash};
131	use bitcoin::secp256k1::{schnorr, PublicKey, XOnlyPublicKey};
132
133	use bitcoin_ext::{BlockDelta, BlockHeight, TAPROOT_KEYSPEND_WEIGHT};
134
135	use crate::musig;
136
137	/// Create a tapscript that is a checksig and a relative timelock.
138	pub fn delayed_sign(delay_blocks: BlockDelta, pubkey: XOnlyPublicKey) -> ScriptBuf {
139		let csv = bitcoin::Sequence::from_height(delay_blocks);
140		bitcoin::Script::builder()
141			.push_int(csv.to_consensus_u32() as i64)
142			.push_opcode(opcodes::all::OP_CSV)
143			.push_opcode(opcodes::all::OP_DROP)
144			.push_x_only_key(&pubkey)
145			.push_opcode(opcodes::all::OP_CHECKSIG)
146			.into_script()
147	}
148
149	/// Create a tapscript that is a checksig and an absolute timelock.
150	pub fn timelock_sign(timelock_height: BlockHeight, pubkey: XOnlyPublicKey) -> ScriptBuf {
151		let lt = bitcoin::absolute::LockTime::from_height(timelock_height).unwrap();
152		bitcoin::Script::builder()
153			.push_int(lt.to_consensus_u32() as i64)
154			.push_opcode(opcodes::all::OP_CLTV)
155			.push_opcode(opcodes::all::OP_DROP)
156			.push_x_only_key(&pubkey)
157			.push_opcode(opcodes::all::OP_CHECKSIG)
158			.into_script()
159	}
160
161	/// Create a tapscript
162	pub fn delay_timelock_sign(
163		delay_blocks: BlockDelta,
164		timelock_height: BlockHeight,
165		pubkey: XOnlyPublicKey,
166	) -> ScriptBuf {
167		let csv = bitcoin::Sequence::from_height(delay_blocks);
168		let lt = bitcoin::absolute::LockTime::from_height(timelock_height).unwrap();
169		bitcoin::Script::builder()
170			.push_int(lt.to_consensus_u32().try_into().unwrap())
171			.push_opcode(opcodes::all::OP_CLTV)
172			.push_opcode(opcodes::all::OP_DROP)
173			.push_int(csv.to_consensus_u32().try_into().unwrap())
174			.push_opcode(opcodes::all::OP_CSV)
175			.push_opcode(opcodes::all::OP_DROP)
176			.push_x_only_key(&pubkey)
177			.push_opcode(opcodes::all::OP_CHECKSIG)
178			.into_script()
179	}
180
181	/// Contract that requires revealing the preimage to the given hash
182	/// and a signature using the given (aggregate) pubkey
183	///
184	/// The expected spending script witness is the preimage followed by
185	/// the signature.
186	pub fn hash_and_sign(hash: sha256::Hash, pubkey: XOnlyPublicKey) -> ScriptBuf {
187		let hash_160 = ripemd160::Hash::hash(&hash[..]);
188
189		bitcoin::Script::builder()
190			.push_opcode(opcodes::all::OP_HASH160)
191			.push_slice(hash_160.as_byte_array())
192			.push_opcode(opcodes::all::OP_EQUALVERIFY)
193			.push_x_only_key(&pubkey)
194			.push_opcode(opcodes::all::OP_CHECKSIG)
195			.into_script()
196	}
197
198	pub fn hash_delay_sign(
199		hash: sha256::Hash,
200		delay_blocks: BlockDelta,
201		pubkey: XOnlyPublicKey,
202	) -> ScriptBuf {
203		let hash_160 = ripemd160::Hash::hash(&hash[..]);
204		let csv = bitcoin::Sequence::from_height(delay_blocks);
205
206		bitcoin::Script::builder()
207			.push_int(csv.to_consensus_u32().try_into().unwrap())
208			.push_opcode(opcodes::all::OP_CSV)
209			.push_opcode(opcodes::all::OP_DROP)
210			.push_opcode(opcodes::all::OP_HASH160)
211			.push_slice(hash_160.as_byte_array())
212			.push_opcode(opcodes::all::OP_EQUALVERIFY)
213			.push_x_only_key(&pubkey)
214			.push_opcode(opcodes::all::OP_CHECKSIG)
215			.into_script()
216	}
217
218	/// Fill in the signatures into the unsigned transaction.
219	///
220	/// Panics if the nb of inputs and signatures doesn't match or if some input
221	/// witnesses are not empty.
222	pub fn fill_taproot_sigs(tx: &mut Transaction, sigs: &[schnorr::Signature]) {
223		assert_eq!(tx.input.len(), sigs.len());
224		for (input, sig) in tx.input.iter_mut().zip(sigs.iter()) {
225			assert!(input.witness.is_empty());
226			input.witness.push(&sig[..]);
227			debug_assert_eq!(TAPROOT_KEYSPEND_WEIGHT, input.witness.size());
228		}
229	}
230
231	/// Verify a partial signature from either of the two parties cosigning a tx.
232	pub fn verify_partial_sig(
233		sighash: TapSighash,
234		tweak: TapTweakHash,
235		signer: (PublicKey, &musig::PublicNonce),
236		other: (PublicKey, &musig::PublicNonce),
237		partial_signature: &musig::PartialSignature,
238	) -> bool {
239		let agg_nonce = musig::nonce_agg(&[&signer.1, &other.1]);
240		let agg_pk = musig::tweaked_key_agg([signer.0, other.0], tweak.to_byte_array()).0;
241
242		let session = musig::Session::new(&agg_pk, agg_nonce, &sighash.to_byte_array());
243		session.partial_verify(
244			&agg_pk, partial_signature, signer.1, musig::pubkey_to(signer.0),
245		)
246	}
247}