ark/
connectors.rs

1
2
3use std::iter;
4use std::borrow::Cow;
5
6use bitcoin::{
7	Address, Amount, Network, OutPoint, Script, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Weight, Witness
8};
9use bitcoin::secp256k1::{Keypair, PublicKey};
10use bitcoin::sighash::{self, SighashCache, TapSighashType};
11use bitcoin_ext::{fee, KeypairExt, P2TR_DUST};
12
13use crate::SECP;
14
15/// The output index of the connector chain continuation in the connector tx.
16///
17/// In the last item of the chain, it is a connector output along with
18/// output at index 1.
19pub const CONNECTOR_TX_CHAIN_VOUT: u32 = 0;
20/// The output index of the connector output in the connector tx.
21pub const CONNECTOR_TX_CONNECTOR_VOUT: u32 = 1;
22
23/// The weight of each connector tx.
24const TX_WEIGHT: Weight = Weight::from_vb_unchecked(167);
25
26/// The witness weight of a connector input.
27pub const INPUT_WEIGHT: Weight = Weight::from_wu(66);
28
29
30/// Construct a tx that breaks up a single connector output into N connectors
31pub fn construct_multi_connector_tx(
32	prev: OutPoint,
33	nb_outputs: usize,
34	connector_spk: &Script,
35) -> Transaction {
36	assert_ne!(nb_outputs, 0);
37	Transaction {
38		version: bitcoin::transaction::Version(3),
39		lock_time: bitcoin::absolute::LockTime::ZERO,
40		input: vec![TxIn {
41			previous_output: prev,
42			script_sig: ScriptBuf::new(),
43			sequence: Sequence::MAX,
44			witness: Witness::new(),
45		}],
46		output: (0..nb_outputs)
47			.map(|_| TxOut { script_pubkey: connector_spk.to_owned(), value: P2TR_DUST })
48			.chain([fee::fee_anchor()])
49			.collect(),
50	}
51}
52
53/// A chain of connector outputs.
54///
55/// Each connector is a p2tr keyspend output for the provided key.
56/// Each connector has the p2tr dust value.
57#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct ConnectorChain {
59	/// The total number of connectors in the connector chain.
60	len: usize,
61
62	/// The scriptPubkey used by all connector outputs.
63	spk: ScriptBuf,
64
65	/// The prevout from where the chain starts.
66	///
67	/// This should be an output of the round transaction.
68	utxo: OutPoint,
69}
70
71impl ConnectorChain {
72	/// The total size in vbytes of the connector tree.
73	pub fn total_weight(len: usize) -> Weight {
74		assert_ne!(len, 0);
75		(len - 1) as u64 * TX_WEIGHT
76	}
77
78	/// The budget needed for a chain of length `len` to pay for
79	/// one dust for the connector output per tx
80	pub fn required_budget(len: usize) -> Amount {
81		assert_ne!(len, 0);
82
83		// Each tx of the chain will hold one output to continue the
84		// chain + one output for the connector + one fee anchor output
85		// So the required budget is 1 dust per connector
86		P2TR_DUST * len as u64
87	}
88
89	/// Create the scriptPubkey to create a connector chain using the given publick key.
90	pub fn output_script(pubkey: PublicKey) -> ScriptBuf {
91		ScriptBuf::new_p2tr(&SECP, pubkey.x_only_public_key().0, None)
92	}
93
94	/// Create the address to create a connector chain using the given publick key.
95	pub fn address(network: Network, pubkey: PublicKey) -> Address {
96		Address::from_script(&Self::output_script(pubkey), network).unwrap()
97	}
98
99	/// Create a connector output.
100	pub fn output(len: usize, pubkey: PublicKey) -> TxOut {
101		TxOut {
102			script_pubkey: Self::output_script(pubkey),
103			value: Self::required_budget(len),
104		}
105	}
106
107	/// Create a new connector tree.
108	///
109	/// Before calling this method, a utxo should be created with a scriptPubkey
110	/// as specified by [ConnectorChain::output_script] or [ConnectorChain::address].
111	/// The amount in this output is expected to be exaclty equal to
112	/// [ConnectorChain::required_budget] for the given length.
113	pub fn new(len: usize, utxo: OutPoint, pubkey: PublicKey) -> ConnectorChain {
114		assert_ne!(len, 0);
115		let spk = Self::output_script(pubkey);
116
117		ConnectorChain { len, spk, utxo }
118	}
119
120	pub fn len(&self) -> usize {
121		self.len
122	}
123
124	fn tx(&self, prev: OutPoint, idx: usize) -> Transaction {
125		Transaction {
126			version: bitcoin::transaction::Version(3),
127			lock_time: bitcoin::absolute::LockTime::ZERO,
128			input: vec![TxIn {
129				previous_output: prev,
130				script_sig: ScriptBuf::new(),
131				sequence: Sequence::MAX,
132				witness: Witness::new(),
133			}],
134			output: vec![
135				// this is the continuation of the chain
136				// (or a connector output if the last tx)
137				TxOut {
138					script_pubkey: self.spk.to_owned(),
139					value: ConnectorChain::required_budget(self.len - idx - 1),
140				},
141				// this is the connector output
142				// (or the second one if the last tx)
143				TxOut {
144					script_pubkey: self.spk.to_owned(),
145					value: P2TR_DUST,
146				},
147				// this is the fee anchor output
148				fee::fee_anchor(),
149			],
150		}
151	}
152
153	/// NB we expect the output key here, not the internal key
154	fn sign_tx(&self, tx: &mut Transaction, idx: usize, keypair: &Keypair) {
155		let prevout = TxOut {
156			script_pubkey: self.spk.to_owned(),
157			value: ConnectorChain::required_budget(self.len - idx),
158		};
159		let mut shc = SighashCache::new(&*tx);
160		let sighash = shc.taproot_key_spend_signature_hash(
161			0, &sighash::Prevouts::All(&[prevout]), TapSighashType::Default,
162		).expect("sighash error");
163		let sig = SECP.sign_schnorr_with_aux_rand(&sighash.into(), &keypair, &rand::random());
164		tx.input[0].witness = Witness::from_slice(&[&sig[..]]);
165	}
166
167	/// Iterator over the signed transactions in this chain.
168	///
169	/// We expect the internal key here, not the output key.
170	pub fn iter_signed_txs(
171		&self,
172		sign_key: &Keypair,
173	) -> Result<ConnectorTxIter<'_>, InvalidSigningKeyError> {
174		if self.spk == ConnectorChain::output_script(sign_key.public_key()) {
175			Ok(ConnectorTxIter {
176				chain: Cow::Borrowed(self),
177				sign_key: Some(sign_key.for_keyspend(&*SECP)),
178				prev: self.utxo,
179				idx: 0,
180			})
181		} else {
182			Err(InvalidSigningKeyError)
183		}
184	}
185
186	/// Iterator over the transactions in this chain.
187	pub fn iter_unsigned_txs(&self) -> ConnectorTxIter<'_> {
188		ConnectorTxIter {
189			chain: Cow::Borrowed(self),
190			sign_key: None,
191			prev: self.utxo,
192			idx: 0,
193		}
194	}
195
196	/// Iterator over the connector outpoints and unsigned txs in this chain.
197	pub fn connectors(&self) -> ConnectorIter<'_> {
198		ConnectorIter {
199			txs: self.iter_unsigned_txs(),
200			maybe_last: Some((self.utxo, None)),
201		}
202	}
203
204	/// Iterator over the connector outpoints and signed txs in this chain.
205	///
206	/// We expect the internal key here, not the output key.
207	pub fn connectors_signed(
208		&self,
209		sign_key: &Keypair,
210	) -> Result<ConnectorIter<'_>, InvalidSigningKeyError> {
211		Ok(ConnectorIter {
212			txs: self.iter_signed_txs(sign_key)?,
213			maybe_last: Some((self.utxo, None)),
214		})
215	}
216}
217
218/// An iterator over transactions in a [ConnectorChain].
219///
220/// See [ConnectorChain::iter_unsigned_txs] and
221/// [ConnectorChain::iter_signed_txs] for more info.
222pub struct ConnectorTxIter<'a> {
223	chain: Cow<'a, ConnectorChain>,
224	sign_key: Option<Keypair>,
225
226	prev: OutPoint,
227	idx: usize,
228}
229
230impl<'a> ConnectorTxIter<'a> {
231	/// Upgrade this iterator to a signing iterator.
232	pub fn signing(&mut self, sign_key: Keypair) {
233		self.sign_key = Some(sign_key);
234	}
235
236	/// Convert into owned iterator.
237	pub fn into_owned(self) -> ConnectorTxIter<'static> {
238		ConnectorTxIter {
239			chain: Cow::Owned(self.chain.into_owned()),
240			sign_key: self.sign_key,
241			prev: self.prev,
242			idx: self.idx,
243		}
244	}
245}
246
247impl<'a> iter::Iterator for ConnectorTxIter<'a> {
248	type Item = Transaction;
249
250	fn next(&mut self) -> Option<Self::Item> {
251		if self.idx >= self.chain.len - 1 {
252			return None;
253		}
254
255		let mut ret = self.chain.tx(self.prev, self.idx);
256		if let Some(ref keypair) = self.sign_key {
257			self.chain.sign_tx(&mut ret, self.idx, keypair);
258		}
259
260		self.idx += 1;
261		self.prev = OutPoint::new(ret.compute_txid(), CONNECTOR_TX_CHAIN_VOUT);
262		Some(ret)
263	}
264
265	fn size_hint(&self) -> (usize, Option<usize>) {
266		let len = (self.chain.len - 1).saturating_sub(self.idx);
267		(len, Some(len))
268	}
269}
270
271/// An iterator over the connectors in a [ConnectorChain].
272///
273/// See [ConnectorChain::connectors] and [ConnectorChain::connectors_signed]
274/// for more info.
275pub struct ConnectorIter<'a> {
276	txs: ConnectorTxIter<'a>,
277	// On all intermediate txs, only the second output is a connector and
278	// the first output continues the chain. On the very last tx, both
279	// outputs are connectors. We will keep this variable updated to contain
280	// the first output of the last tx we say, so that we can return it once
281	// the tx iterator does no longer yield new txs (hence we reached the
282	// last tx).
283	maybe_last: Option<<Self as Iterator>::Item>,
284}
285
286impl<'a> ConnectorIter<'a> {
287	/// Upgrade this iterator to a signing iterator.
288	pub fn signing(&mut self, sign_key: Keypair) {
289		self.txs.signing(sign_key)
290	}
291
292	/// Convert into owned iterator.
293	pub fn into_owned(self) -> ConnectorIter<'static> {
294		ConnectorIter {
295			txs: self.txs.into_owned(),
296			maybe_last: self.maybe_last,
297		}
298	}
299}
300
301impl<'a> iter::Iterator for ConnectorIter<'a> {
302	type Item = (OutPoint, Option<Transaction>);
303
304	fn next(&mut self) -> Option<Self::Item> {
305		if self.maybe_last.is_none() {
306			return None;
307		}
308
309		if let Some(tx) = self.txs.next() {
310			let txid = tx.compute_txid();
311			self.maybe_last = Some((OutPoint::new(txid, CONNECTOR_TX_CHAIN_VOUT), Some(tx.clone())));
312			Some((OutPoint::new(txid, CONNECTOR_TX_CONNECTOR_VOUT), Some(tx)))
313		} else {
314			Some(self.maybe_last.take().expect("broken"))
315		}
316	}
317
318	fn size_hint(&self) -> (usize, Option<usize>) {
319		let len = self.txs.size_hint().0 + 1;
320		(len, Some(len))
321	}
322}
323
324impl<'a> iter::ExactSizeIterator for ConnectorTxIter<'a> {}
325impl<'a> iter::FusedIterator for ConnectorTxIter<'a> {}
326
327
328/// The signing key passed into [ConnectorChain::iter_signed_txs] or
329/// [ConnectorChain::connectors_signed] is incorrect.
330#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
331#[error("signing key doesn't match connector chain")]
332pub struct InvalidSigningKeyError;
333
334
335#[cfg(test)]
336mod test {
337	use bitcoin::Txid;
338	use bitcoin::hashes::Hash;
339	use bitcoin_ext::TransactionExt;
340	use crate::test::verify_tx;
341	use super::*;
342
343	#[test]
344	fn test_budget() {
345		let key = Keypair::new(&SECP, &mut bitcoin::secp256k1::rand::thread_rng());
346		let utxo = OutPoint::new(Txid::all_zeros(), 3);
347
348		let chain = ConnectorChain::new(1, utxo, key.public_key());
349		assert_eq!(chain.connectors().count(), 1);
350		assert_eq!(chain.iter_unsigned_txs().count(), 0);
351		assert_eq!(chain.connectors().next().unwrap().0, utxo);
352
353		let chain = ConnectorChain::new(2, utxo, key.public_key());
354		assert_eq!(chain.connectors().count(), 2);
355		assert_eq!(chain.iter_unsigned_txs().count(), 1);
356		assert_eq!(chain.iter_signed_txs(&key).unwrap().count(), 1);
357		let tx = chain.iter_signed_txs(&key).unwrap().next().unwrap();
358		assert_eq!(TX_WEIGHT, tx.weight());
359		assert_eq!(tx.output_value(), ConnectorChain::required_budget(2));
360
361		let chain = ConnectorChain::new(3, utxo, key.public_key());
362		assert_eq!(chain.connectors().count(), 3);
363		assert_eq!(chain.iter_unsigned_txs().count(), 2);
364		let mut txs = chain.iter_signed_txs(&key).unwrap();
365		let tx = txs.next().unwrap();
366		assert_eq!(TX_WEIGHT, tx.weight());
367		assert_eq!(tx.output_value(), ConnectorChain::required_budget(3));
368		let tx = txs.next().unwrap();
369		assert_eq!(TX_WEIGHT, tx.weight());
370		assert_eq!(tx.output_value(), ConnectorChain::required_budget(2));
371		assert!(txs.next().is_none());
372
373		let chain = ConnectorChain::new(100, utxo, key.public_key());
374		assert_eq!(chain.connectors().count(), 100);
375		assert_eq!(chain.iter_unsigned_txs().count(), 99);
376		assert_eq!(chain.iter_signed_txs(&key).unwrap().count(), 99);
377		let tx = chain.iter_signed_txs(&key).unwrap().next().unwrap();
378		assert_eq!(TX_WEIGHT, tx.weight());
379		assert_eq!(tx.output_value(), ConnectorChain::required_budget(100));
380		for tx in chain.iter_signed_txs(&key).unwrap() {
381			assert_eq!(tx.weight(), TX_WEIGHT);
382			assert_eq!(tx.input[0].witness.size(), INPUT_WEIGHT.to_wu() as usize);
383		}
384		let weight = chain.iter_signed_txs(&key).unwrap().map(|t| t.weight()).sum::<Weight>();
385		assert_eq!(weight, ConnectorChain::total_weight(100));
386		chain.iter_unsigned_txs().for_each(|t| assert_eq!(t.output[1].value, P2TR_DUST));
387		assert_eq!(P2TR_DUST, chain.iter_unsigned_txs().last().unwrap().output[0].value);
388	}
389
390	#[test]
391	fn test_signatures() {
392		let key = Keypair::new(&SECP, &mut bitcoin::secp256k1::rand::thread_rng());
393		let utxo = OutPoint::new(Txid::all_zeros(), 3);
394		let spk = ConnectorChain::output_script(key.public_key());
395
396		let chain = ConnectorChain::new(10, utxo, key.public_key());
397		for (i, tx) in chain.iter_signed_txs(&key).unwrap().enumerate() {
398			let amount = ConnectorChain::required_budget(chain.len - i);
399			let input = TxOut {
400				script_pubkey: spk.clone(),
401				value: amount,
402			};
403			verify_tx(&[input], 0, &tx).expect(&format!("invalid connector tx idx {}", i));
404		}
405	}
406}