ark-core 0.9.3

Core types and utilities for Ark
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use crate::ark_address::ArkAddress;
use crate::script::csv_sig_script;
use crate::script::multisig_3_of_3_script;
use crate::script::multisig_script;
use crate::script::tr_script_pubkey;
use crate::Error;
use crate::ErrorContext;
use crate::ExitDelayKind;
use crate::UNSPENDABLE_KEY;
use bitcoin::key::PublicKey;
use bitcoin::key::Secp256k1;
use bitcoin::key::Verification;
use bitcoin::taproot;
use bitcoin::taproot::LeafVersion;
use bitcoin::taproot::TaprootBuilder;
use bitcoin::taproot::TaprootSpendInfo;
use bitcoin::Address;
use bitcoin::Network;
use bitcoin::ScriptBuf;
use bitcoin::XOnlyPublicKey;
use std::time::Duration;

/// All the information needed to _spend_ a VTXO.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Vtxo {
    server_forfeit: XOnlyPublicKey,
    owner: XOnlyPublicKey,
    owner_unilateral_exit: XOnlyPublicKey,
    /// The delegator's public key, if this VTXO has a delegate spending path.
    delegator: Option<XOnlyPublicKey>,
    spend_info: TaprootSpendInfo,
    /// All the scripts in this VTXO's Taproot tree.
    tapscripts: Vec<ScriptBuf>,
    address: Address,
    exit_delay: bitcoin::Sequence,
    exit_delay_kind: ExitDelayKind,
    network: Network,
}

impl Vtxo {
    /// Build a VTXO, by providing all the scripts to be included in the Taproot tree.
    ///
    /// The provided `scripts` must follow the following rules:
    ///
    /// - All unilateral spend paths MUST be timelocked.
    /// - All other spend paths MUST involve the Ark server's signature.
    pub fn new_with_custom_scripts<C>(
        secp: &Secp256k1<C>,
        server_forfeit: XOnlyPublicKey,
        owner: XOnlyPublicKey,
        // TODO: Verify the validity of these scripts before constructing the `Vtxo`.
        scripts: Vec<ScriptBuf>,
        exit_delay: bitcoin::Sequence,
        network: Network,
    ) -> Result<Self, Error>
    where
        C: Verification,
    {
        let vtxo = Self::new_with_custom_scripts_and_split_owner_keys(
            secp,
            server_forfeit,
            owner,
            owner,
            scripts,
            exit_delay,
            network,
        )?;

        Ok(vtxo)
    }

    pub fn new_with_custom_scripts_and_split_owner_keys<C>(
        secp: &Secp256k1<C>,
        server_forfeit: XOnlyPublicKey,
        owner: XOnlyPublicKey,
        owner_unilateral_exit: XOnlyPublicKey,
        scripts: Vec<ScriptBuf>,
        exit_delay: bitcoin::Sequence,
        network: Network,
    ) -> Result<Self, Error>
    where
        C: Verification,
    {
        let unspendable_key: PublicKey = UNSPENDABLE_KEY
            .parse()
            .map_err(|e| Error::ad_hoc(format!("invalid unspendable key: {e}")))?;
        let (unspendable_key, _) = unspendable_key.inner.x_only_public_key();

        let leaf_distribution = calculate_leaf_depths(scripts.len());

        let mut builder = TaprootBuilder::new();
        for (script, depth) in scripts.iter().zip(leaf_distribution.iter()) {
            builder = builder
                .add_leaf(*depth as u8, script.clone())
                .map_err(Error::ad_hoc)?;
        }

        let spend_info = builder
            .finalize(secp, unspendable_key)
            .map_err(|_| Error::ad_hoc("failed to finalize Taproot tree"))?;

        let exit_delay_kind = ExitDelayKind::from_sequence(exit_delay)?;

        let script_pubkey = tr_script_pubkey(&spend_info);
        let address = Address::from_script(&script_pubkey, network)
            .map_err(|e| Error::ad_hoc(format!("invalid script: {e}")))?;

        Ok(Self {
            server_forfeit,
            owner,
            owner_unilateral_exit,
            delegator: None,
            spend_info,
            tapscripts: scripts,
            address,
            exit_delay,
            exit_delay_kind,
            network,
        })
    }

    /// Build a default VTXO.
    pub fn new_default<C>(
        secp: &Secp256k1<C>,
        server_signer: XOnlyPublicKey,
        owner: XOnlyPublicKey,
        exit_delay: bitcoin::Sequence,
        network: Network,
    ) -> Result<Self, Error>
    where
        C: Verification,
    {
        let forfeit_script = multisig_script(server_signer, owner);
        let redeem_script = csv_sig_script(exit_delay, owner);

        Self::new_with_custom_scripts(
            secp,
            server_signer,
            owner,
            vec![forfeit_script, redeem_script],
            exit_delay,
            network,
        )
    }

    /// Build a VTXO with a delegate spending path.
    ///
    /// This creates a 3-leaf Taproot tree:
    /// 1. **Forfeit**: 2-of-2 multisig (server + owner)
    /// 2. **Exit**: CSV-timelocked owner signature
    /// 3. **Delegate**: 3-of-3 multisig (owner + delegator + server)
    ///
    /// The delegate path allows a third-party delegator service to cooperate with the owner and
    /// the server to renew VTXOs before they expire.
    pub fn new_with_delegator<C>(
        secp: &Secp256k1<C>,
        server_signer: XOnlyPublicKey,
        owner: XOnlyPublicKey,
        delegator: XOnlyPublicKey,
        exit_delay: bitcoin::Sequence,
        network: Network,
    ) -> Result<Self, Error>
    where
        C: Verification,
    {
        let forfeit_script = multisig_script(server_signer, owner);
        let redeem_script = csv_sig_script(exit_delay, owner);
        let delegate_script = multisig_3_of_3_script(owner, delegator, server_signer);

        let mut vtxo = Self::new_with_custom_scripts(
            secp,
            server_signer,
            owner,
            vec![forfeit_script, redeem_script, delegate_script],
            exit_delay,
            network,
        )?;

        vtxo.delegator = Some(delegator);

        Ok(vtxo)
    }

    pub fn script_pubkey(&self) -> ScriptBuf {
        self.address.script_pubkey()
    }

    pub fn address(&self) -> &Address {
        &self.address
    }

    pub fn owner_pk(&self) -> XOnlyPublicKey {
        self.owner
    }

    pub fn server_pk(&self) -> XOnlyPublicKey {
        self.server_forfeit
    }

    pub fn delegator_pk(&self) -> Option<XOnlyPublicKey> {
        self.delegator
    }

    pub fn exit_delay(&self) -> bitcoin::Sequence {
        self.exit_delay
    }

    pub fn to_ark_address(&self) -> ArkAddress {
        let vtxo_tap_key = self.spend_info.output_key();
        ArkAddress::new(self.network, self.server_forfeit, vtxo_tap_key)
    }

    /// The spend info of an arbitrary branch of a VTXO.
    pub fn get_spend_info(&self, script: ScriptBuf) -> Result<taproot::ControlBlock, Error> {
        let control_block = self
            .spend_info
            .control_block(&(script, LeafVersion::TapScript))
            .ok_or(Error::ad_hoc("could not build control block for script"))?;

        Ok(control_block)
    }

    /// The spend info for the forfeit branch of a _default_ VTXO.
    ///
    /// This method can fail because [`Vtxo`]s constructed with the method
    /// [`Vtxo::new_with_custom_scripts`] may not contain this script exactly.
    pub fn forfeit_spend_info(&self) -> Result<(ScriptBuf, taproot::ControlBlock), Error> {
        let forfeit_script = multisig_script(self.server_forfeit, self.owner);

        let control_block = self
            .get_spend_info(forfeit_script.clone())
            .context("missing default forfeit script")?;

        Ok((forfeit_script, control_block))
    }

    /// The spend info for the unilateral exit branch of a _default_ VTXO.
    ///
    /// This method can fail because [`Vtxo`]s constructed with the method
    /// [`Vtxo::new_with_custom_scripts`] may not contain this script exactly.
    pub fn exit_spend_info(&self) -> Result<(ScriptBuf, taproot::ControlBlock), Error> {
        let exit_script = csv_sig_script(self.exit_delay, self.owner_unilateral_exit);

        let control_block = self
            .get_spend_info(exit_script.clone())
            .context("missing default exit script")?;

        Ok((exit_script, control_block))
    }

    /// The spend info for the delegate branch of a VTXO constructed with
    /// [`Vtxo::new_with_delegator`].
    ///
    /// Returns an error if the VTXO was not built with a delegator.
    pub fn delegate_spend_info(&self) -> Result<(ScriptBuf, taproot::ControlBlock), Error> {
        let delegator = self
            .delegator
            .ok_or(Error::ad_hoc("VTXO has no delegate path"))?;

        let delegate_script = multisig_3_of_3_script(self.owner, delegator, self.server_forfeit);

        let control_block = self
            .get_spend_info(delegate_script.clone())
            .context("missing delegate script")?;

        Ok((delegate_script, control_block))
    }

    pub fn tapscripts(&self) -> Vec<ScriptBuf> {
        self.tapscripts.clone()
    }

    /// Whether the VTXO can be claimed unilaterally by the owner or not, given the
    /// `confirmation_blocktime` of the transaction that included this VTXO as an output.
    pub fn can_be_claimed_unilaterally_by_owner(
        &self,
        now: Duration,
        confirmation_blocktime: Duration,
        confirmations: u64,
    ) -> bool {
        match self.exit_delay_kind {
            ExitDelayKind::Time(seconds) => {
                let exit_path_time = confirmation_blocktime + seconds;

                now > exit_path_time
            }
            ExitDelayKind::Blocks(confirmations_required) => {
                confirmations >= confirmations_required
            }
        }
    }
}

fn calculate_leaf_depths(n: usize) -> Vec<usize> {
    // Handle edge cases
    if n == 0 {
        return vec![];
    }
    if n == 1 {
        return vec![0]; // A single node has depth 0
    }
    if n == 2 {
        return vec![1, 1];
    }

    // Calculate the minimum depth required for n leaves
    let min_depth = (n as f64).log2().ceil() as usize;

    // Calculate the number of nodes at the deepest level
    let nodes_at_max_depth = n - (1 << (min_depth - 1)) + 1;
    let nodes_at_min_depth = (1 << min_depth) - nodes_at_max_depth;

    // Create the result vector with the appropriate depths
    let mut result = Vec::with_capacity(n);

    // Add the deeper nodes first
    for _ in 0..nodes_at_max_depth {
        result.push(min_depth);
    }

    // Add the less deep nodes
    for _ in 0..nodes_at_min_depth {
        result.push(min_depth - 1);
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use bitcoin::secp256k1::Secp256k1;
    use std::str::FromStr;

    fn test_keys() -> (XOnlyPublicKey, XOnlyPublicKey, XOnlyPublicKey) {
        let server = XOnlyPublicKey::from_str(
            "18845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166",
        )
        .unwrap();
        let owner = XOnlyPublicKey::from_str(
            "28845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166",
        )
        .unwrap();
        let delegator = XOnlyPublicKey::from_str(
            "38845781f631c48f1c9709e23092067d06837f30aa0cd0544ac887fe91ddd166",
        )
        .unwrap();
        (server, owner, delegator)
    }

    #[test]
    fn new_with_delegator_has_three_tapscripts() {
        let secp = Secp256k1::new();
        let (server, owner, delegator) = test_keys();
        let exit_delay = bitcoin::Sequence::from_seconds_ceil(86400).unwrap();

        let vtxo = Vtxo::new_with_delegator(
            &secp,
            server,
            owner,
            delegator,
            exit_delay,
            Network::Regtest,
        )
        .unwrap();

        assert_eq!(vtxo.tapscripts().len(), 3);
        assert_eq!(vtxo.delegator_pk(), Some(delegator));
    }

    #[test]
    fn delegator_vtxo_all_spend_paths_resolve() {
        let secp = Secp256k1::new();
        let (server, owner, delegator) = test_keys();
        let exit_delay = bitcoin::Sequence::from_seconds_ceil(86400).unwrap();

        let vtxo = Vtxo::new_with_delegator(
            &secp,
            server,
            owner,
            delegator,
            exit_delay,
            Network::Regtest,
        )
        .unwrap();

        // All three spend paths should produce valid spend info.
        let (forfeit_script, _cb) = vtxo.forfeit_spend_info().unwrap();
        let (exit_script, _cb) = vtxo.exit_spend_info().unwrap();
        let (delegate_script, _cb) = vtxo.delegate_spend_info().unwrap();

        // Scripts should be distinct.
        assert_ne!(forfeit_script, exit_script);
        assert_ne!(forfeit_script, delegate_script);
        assert_ne!(exit_script, delegate_script);
    }

    #[test]
    fn default_vtxo_has_no_delegate_path() {
        let secp = Secp256k1::new();
        let (server, owner, _) = test_keys();
        let exit_delay = bitcoin::Sequence::from_seconds_ceil(86400).unwrap();

        let vtxo = Vtxo::new_default(&secp, server, owner, exit_delay, Network::Regtest).unwrap();

        assert!(vtxo.delegator_pk().is_none());
        assert!(vtxo.delegate_spend_info().is_err());
    }

    #[test]
    fn delegator_vtxo_address_differs_from_default() {
        let secp = Secp256k1::new();
        let (server, owner, delegator) = test_keys();
        let exit_delay = bitcoin::Sequence::from_seconds_ceil(86400).unwrap();

        let default =
            Vtxo::new_default(&secp, server, owner, exit_delay, Network::Regtest).unwrap();
        let with_delegator = Vtxo::new_with_delegator(
            &secp,
            server,
            owner,
            delegator,
            exit_delay,
            Network::Regtest,
        )
        .unwrap();

        // Different taproot trees should produce different addresses.
        assert_ne!(default.address(), with_delegator.address());
    }
}