sidestr-hitch 0.2.1

Hitch-compatible payment-channel kernel for Bitcoin BLAKE2b testnet4
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! The opening handshake: `open`, `accept`, `commit`, `ready`.

use bitcoin::secp256k1::{SecretKey, XOnlyPublicKey};
use bitcoin::{Amount, OutPoint};
use sidestr_core::sighash::SighashRules;

use super::machine::{ChannelMachine, Keys, ProtocolState};
use super::{
    pop_context, public, AcceptMessage, AcceptTag, ChannelId, CommitMessage, CommitTag,
    FundingOffer, NodeId, OpenMessage, OpenTag, PopPlace, ProtocolError, ReadyMessage, ReadyTag,
    RevocationProofs, SyncMessage, SyncTag, WireSide, MAX_HUB_FEE, MAX_SATS, MIN_OPEN,
};
use crate::{
    pop_sign, pop_verify, revocation_pub, Balances, Channel, ChannelState, RevocationKeys, Side,
    DUST,
};

/// Secret material generated by one peer for the opening handshake.
pub struct OpeningKeys {
    /// Static channel signing key, whose public half is the node id.
    pub channel: SecretKey,
    /// Revocation basepoint secret: the half of the counterparty's revocation
    /// keys this peer holds for the life of the channel.
    pub revocation_base: SecretKey,
    /// Per-state revocation secrets for states zero and one.
    pub revocation: [SecretKey; 2],
}

/// Parameters chosen by the funder after its wallet builds the funding
/// transaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OpenParams {
    /// Funding transaction output.
    pub funding: OutPoint,
    /// Value in the funding output.
    pub funding_value: Amount,
    /// Value assigned to B in state zero.
    pub push: Amount,
    /// Relative delay for commitment-owner claims.
    pub delay: u16,
    /// Fixed per-transaction channel fee.
    pub fee: Amount,
    /// Optional routing fee advertised by a hub.
    pub hub_fee: Option<u64>,
}

/// Receiver policy applied before it signs an opening proposal. Hitch's
/// `io.acceptOpen` admission hook stays with the host, which decides before
/// calling [`ReceiverOpening::accept`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AcceptPolicy {
    /// Smallest CSV delay this receiver accepts.
    pub min_delay: u16,
    /// Optional routing fee advertised by this receiver when it is a hub.
    pub hub_fee: Option<u64>,
}

impl Default for AcceptPolicy {
    fn default() -> Self {
        Self {
            min_delay: crate::MIN_DELAY,
            hub_fee: None,
        }
    }
}

/// Funder state after it proposed and before B's acceptance is checked
/// (Hitch's `proposed`).
#[derive(Clone)]
pub struct FunderOpening {
    id: ChannelId,
    channel: Channel,
    keys: Keys,
    initial_state: ProtocolState,
    message: OpenMessage,
    rules: SighashRules,
}

/// Funder state after it has verified B's initial signature and sent its own
/// (Hitch's `funding`, before B's `ready`).
#[derive(Clone)]
pub struct AcceptedFunder {
    opening: FunderOpening,
    their_revocation: [XOnlyPublicKey; 2],
    their_revocation_base: XOnlyPublicKey,
    their_signature_zero: crate::LeafSignature,
    peer_hub_fee: Option<u64>,
    commit: CommitMessage,
}

/// Receiver state after it has signed A's initial commitment (Hitch's
/// `accepted`).
#[derive(Clone)]
pub struct ReceiverOpening {
    id: ChannelId,
    channel: Channel,
    keys: Keys,
    initial_state: ProtocolState,
    their_revocation: [XOnlyPublicKey; 2],
    their_revocation_base: XOnlyPublicKey,
    peer_hub_fee: Option<u64>,
    message: AcceptMessage,
    rules: SighashRules,
}

/// What a funder still waiting for `ready` does with the receiver's sync.
pub enum FunderSync {
    /// The receiver never saw `commit`: send it again and keep waiting.
    ResendCommit(CommitMessage),
    /// The receiver is past `commit`, so its `ready` was lost: the channel
    /// is ready, exactly as on [`AcceptedFunder::ready`].
    Ready(Box<ChannelMachine>),
    /// Nothing to do yet.
    Waiting,
}

fn proofs(id: ChannelId, role: WireSide, keys: &Keys, aux: &[u8; 32]) -> RevocationProofs {
    RevocationProofs {
        base: pop_sign(
            &keys.revocation_base,
            &pop_context(id, role, PopPlace::Base),
            aux,
        ),
        rev: [
            pop_sign(
                &keys.revocation[0],
                &pop_context(id, role, PopPlace::State(0)),
                aux,
            ),
            pop_sign(
                &keys.revocation[1],
                &pop_context(id, role, PopPlace::State(1)),
                aux,
            ),
        ],
    }
}

fn proofs_hold(
    id: ChannelId,
    role: WireSide,
    base: &NodeId,
    rev: &[NodeId; 2],
    pop: &RevocationProofs,
) -> bool {
    pop_verify(&base.0, &pop.base, &pop_context(id, role, PopPlace::Base))
        && pop_verify(
            &rev[0].0,
            &pop.rev[0],
            &pop_context(id, role, PopPlace::State(0)),
        )
        && pop_verify(
            &rev[1].0,
            &pop.rev[1],
            &pop_context(id, role, PopPlace::State(1)),
        )
}

/// The state-zero channel state with both sides' two-party revocation keys.
fn opening_state(
    state: &ProtocolState,
    a_view: XOnlyPublicKey,
    b_view: XOnlyPublicKey,
) -> ChannelState {
    ChannelState {
        balances: Balances {
            a: Amount::from_sat(state.balance_a),
            b: Amount::from_sat(state.balance_b),
        },
        revocation: RevocationKeys {
            a: a_view,
            b: b_view,
        },
        htlcs: vec![],
    }
}

impl FunderOpening {
    /// Construct and validate an `open` message from a wallet-selected funding
    /// outpoint, with proofs of possession for the announced points. The
    /// wallet remains responsible for broadcasting and watching the funding
    /// transaction.
    pub fn propose(
        params: OpenParams,
        keys: OpeningKeys,
        peer: XOnlyPublicKey,
        rules: SighashRules,
        aux: &[u8; 32],
    ) -> Result<(Self, OpenMessage), ProtocolError> {
        validate_hub_fee(params.hub_fee)?;
        if params.funding.vout > u32::from(u16::MAX) {
            return Err(ProtocolError::FundingVout);
        }
        if !(MIN_OPEN..=MAX_SATS).contains(&params.funding_value.to_sat()) {
            return Err(ProtocolError::FundingValue);
        }
        let mine = public(&keys.channel);
        if mine == peer {
            return Err(ProtocolError::SamePeer);
        }
        validate_push(params.funding_value, params.push, params.fee)?;
        let channel = Channel::new(
            mine,
            peer,
            params.funding,
            params.funding_value,
            params.fee,
            params.delay,
        )?;
        let id = ChannelId::from_txid(params.funding.txid);
        let initial_state = initial_state(params.funding_value, params.push)?;
        let keys = Keys::from(keys);
        let message = OpenMessage {
            t: OpenTag::Open,
            id,
            funding: FundingOffer {
                txid: params.funding.txid,
                vout: params.funding.vout,
                value: params.funding_value.to_sat(),
            },
            push: params.push.to_sat(),
            delay: params.delay,
            fee: params.fee.to_sat(),
            a: NodeId(mine),
            b: NodeId(peer),
            rev: [
                NodeId(public(&keys.revocation[0])),
                NodeId(public(&keys.revocation[1])),
            ],
            rev_base: NodeId(public(&keys.revocation_base)),
            pop: proofs(id, WireSide::A, &keys, aux),
            hub_fee: params.hub_fee,
        };
        Ok((
            Self {
                id,
                channel,
                keys,
                initial_state,
                message: message.clone(),
                rules,
            },
            message,
        ))
    }

    /// The channel id.
    pub fn id(&self) -> ChannelId {
        self.id
    }

    /// The `open` to send again when no `accept` came (Hitch resends the
    /// proposal every 90 seconds).
    pub fn message(&self) -> &OpenMessage {
        &self.message
    }

    /// Verify B's proofs of possession and its signature on A's initial
    /// commitment, then sign B's matching commitment. On an error the
    /// proposal stands and a later `accept` may still be taken.
    pub fn accept(
        &self,
        message: AcceptMessage,
        aux: &[u8; 32],
    ) -> Result<(AcceptedFunder, CommitMessage), ProtocolError> {
        message.well_formed()?;
        if message.id != self.id {
            return Err(ProtocolError::WrongChannel);
        }
        if !proofs_hold(
            self.id,
            WireSide::B,
            &message.rev_base,
            &message.rev,
            &message.pop,
        ) {
            return Err(ProtocolError::MissingProof);
        }
        let their_base = message.rev_base.0;
        let theirs = [message.rev[0].0, message.rev[1].0];
        let state = opening_state(
            &self.initial_state,
            revocation_pub(their_base, &self.keys.revocation[0])?,
            revocation_pub(theirs[0], &self.keys.revocation_base)?,
        );
        let mine = self.channel.commitment(0, Side::A, &state)?;
        if !self.channel.verify_funding(
            &mine.tx,
            &self.channel.key(Side::B),
            &message.sig,
            self.rules,
        ) {
            return Err(ProtocolError::BadSignature);
        }
        let theirs_commitment = self.channel.commitment(0, Side::B, &state)?;
        let signature = self.channel.sign_funding(
            &theirs_commitment.tx,
            &self.keys.channel,
            self.rules,
            aux,
        )?;
        let commit = CommitMessage {
            t: CommitTag::Commit,
            id: self.id,
            sig: signature,
        };
        Ok((
            AcceptedFunder {
                opening: self.clone(),
                their_revocation: theirs,
                their_revocation_base: their_base,
                their_signature_zero: message.sig,
                peer_hub_fee: message.hub_fee,
                commit: commit.clone(),
            },
            commit,
        ))
    }
}

impl AcceptedFunder {
    /// The channel id.
    pub fn id(&self) -> ChannelId {
        self.opening.id
    }

    /// The `commit` already sent, for a resend.
    pub fn commit_message(&self) -> &CommitMessage {
        &self.commit
    }

    /// This peer's position for a resync while it waits for `ready`.
    pub fn sync_message(&self) -> SyncMessage {
        SyncMessage {
            t: SyncTag::Sync,
            id: self.opening.id,
            n: 0,
            status: Some(super::ChannelStatus::Funding.as_str().into()),
            pending_n: None,
            reveal: None,
            missing: vec![],
            reveals: None,
        }
    }

    /// Take B's readiness and enter the update state machine in
    /// [`ChannelStatus::Funding`](super::ChannelStatus::Funding). The host may
    /// now broadcast the funding transaction.
    pub fn ready(&self, message: ReadyMessage) -> Result<ChannelMachine, ProtocolError> {
        if message.id != self.opening.id {
            return Err(ProtocolError::WrongChannel);
        }
        self.machine()
    }

    /// Hitch's reconcile while funding: a receiver reporting `accepted`
    /// never got `commit`; one reporting `funding` or `open` sent a `ready`
    /// that was lost.
    pub fn receive_sync(&self, message: &SyncMessage) -> Result<FunderSync, ProtocolError> {
        message.well_formed()?;
        if message.id != self.opening.id {
            return Err(ProtocolError::WrongChannel);
        }
        match message.status.as_deref() {
            Some("accepted") => Ok(FunderSync::ResendCommit(self.commit.clone())),
            Some("funding" | "open") => Ok(FunderSync::Ready(Box::new(self.machine()?))),
            _ => Ok(FunderSync::Waiting),
        }
    }

    fn machine(&self) -> Result<ChannelMachine, ProtocolError> {
        ChannelMachine::new(
            self.opening.id,
            Side::A,
            self.opening.channel.clone(),
            self.opening.initial_state.clone(),
            self.opening.keys.clone(),
            self.their_revocation_base,
            self.their_revocation,
            self.their_signature_zero,
            self.peer_hub_fee,
            self.opening.rules,
        )
    }
}

impl ReceiverOpening {
    /// Validate A's authenticated proposal, including the proofs of
    /// possession of every announced revocation point, and return B's
    /// signature on A's initial commitment with B's own points and proofs.
    pub fn accept(
        message: OpenMessage,
        authenticated_sender: XOnlyPublicKey,
        keys: OpeningKeys,
        rules: SighashRules,
        policy: AcceptPolicy,
        aux: &[u8; 32],
    ) -> Result<(Self, AcceptMessage), ProtocolError> {
        validate_open(
            &message,
            authenticated_sender,
            public(&keys.channel),
            policy,
        )?;
        let id = message.id;
        if !proofs_hold(
            id,
            WireSide::A,
            &message.rev_base,
            &message.rev,
            &message.pop,
        ) {
            return Err(ProtocolError::MissingProof);
        }
        let outpoint = OutPoint {
            txid: message.funding.txid,
            vout: message.funding.vout,
        };
        let value = Amount::from_sat(message.funding.value);
        let channel = Channel::new(
            message.a.0,
            message.b.0,
            outpoint,
            value,
            Amount::from_sat(message.fee),
            message.delay,
        )?;
        let state = initial_state(value, Amount::from_sat(message.push))?;
        let keys = Keys::from(keys);
        let their_base = message.rev_base.0;
        let theirs = [message.rev[0].0, message.rev[1].0];
        let full = opening_state(
            &state,
            revocation_pub(theirs[0], &keys.revocation_base)?,
            revocation_pub(their_base, &keys.revocation[0])?,
        );
        let commitment = channel.commitment(0, Side::A, &full)?;
        let signature = channel.sign_funding(&commitment.tx, &keys.channel, rules, aux)?;
        let response = AcceptMessage {
            t: AcceptTag::Accept,
            id,
            rev: [
                NodeId(public(&keys.revocation[0])),
                NodeId(public(&keys.revocation[1])),
            ],
            rev_base: NodeId(public(&keys.revocation_base)),
            pop: proofs(id, WireSide::B, &keys, aux),
            sig: signature,
            hub_fee: policy.hub_fee,
        };
        Ok((
            Self {
                id,
                channel,
                keys,
                initial_state: state,
                their_revocation: theirs,
                their_revocation_base: their_base,
                peer_hub_fee: message.hub_fee,
                message: response.clone(),
                rules,
            },
            response,
        ))
    }

    /// The channel id.
    pub fn id(&self) -> ChannelId {
        self.id
    }

    /// The `accept` to send again when the same `open` arrives again (its
    /// first answer was lost) or a sync reports the funder still `proposed`.
    pub fn message(&self) -> &AcceptMessage {
        &self.message
    }

    /// Verify A's signature on B's initial commitment and enter the update
    /// state machine in [`ChannelStatus::Funding`](super::ChannelStatus::Funding).
    /// On an error the acceptance stands.
    pub fn commit(
        &self,
        message: CommitMessage,
    ) -> Result<(ChannelMachine, ReadyMessage), ProtocolError> {
        if message.id != self.id {
            return Err(ProtocolError::WrongChannel);
        }
        let ready = ReadyMessage {
            t: ReadyTag::Ready,
            id: self.id,
        };
        let machine = ChannelMachine::new(
            self.id,
            Side::B,
            self.channel.clone(),
            self.initial_state.clone(),
            self.keys.clone(),
            self.their_revocation_base,
            self.their_revocation,
            message.sig,
            self.peer_hub_fee,
            self.rules,
        )?;
        Ok((machine, ready))
    }
}

fn validate_open(
    message: &OpenMessage,
    sender: XOnlyPublicKey,
    receiver: XOnlyPublicKey,
    policy: AcceptPolicy,
) -> Result<(), ProtocolError> {
    message.well_formed()?;
    if message.a.0 != sender || message.b.0 != receiver {
        return Err(ProtocolError::WrongPeer);
    }
    if message.delay < policy.min_delay {
        return Err(ProtocolError::DelayBelowPolicy);
    }
    validate_hub_fee(policy.hub_fee)?;
    validate_push(
        Amount::from_sat(message.funding.value),
        Amount::from_sat(message.push),
        Amount::from_sat(message.fee),
    )
}

fn validate_hub_fee(fee: Option<u64>) -> Result<(), ProtocolError> {
    if fee.is_some_and(|value| value > MAX_HUB_FEE) {
        return Err(ProtocolError::HubFee);
    }
    Ok(())
}

fn validate_push(funding: Amount, push: Amount, fee: Amount) -> Result<(), ProtocolError> {
    let minimum = fee
        .to_sat()
        .checked_add(DUST)
        .ok_or(ProtocolError::BadPush)?;
    let maximum = funding
        .to_sat()
        .checked_sub(minimum)
        .ok_or(ProtocolError::BadPush)?;
    if push.to_sat() > maximum {
        return Err(ProtocolError::BadPush);
    }
    Ok(())
}

fn initial_state(funding: Amount, push: Amount) -> Result<ProtocolState, ProtocolError> {
    let balance_a = funding
        .to_sat()
        .checked_sub(push.to_sat())
        .ok_or(ProtocolError::BadPush)?;
    Ok(ProtocolState {
        balance_a,
        balance_b: push.to_sat(),
        htlcs: vec![],
    })
}