sidestr-core 0.3.3

sidestr user-activated sidechains beside a Bitcoin-family parent: the chain document, the parents table, signed blocks generic over the header family (BIP-325 challenge, no subsidy), the peg-in claim and peg-out burn rules, Knots' unified sighash, the block file and an in-memory validating chain. A port of siding by Melvin Carvalho.
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
//! The signature hashes a spend on a sidestr chain is judged by, and the
//! taproot key-path verifier over them.
//!
//! On a stock chain a spend signs BIP 341's taproot sighash and nothing
//! else. Beside a BLAKE2b parent the chain inherits Bitcoin Knots' **unified
//! opt-in signature hash** (`doc/unified-sighash.md` in Knots
//! v29.4.1.knots20260508): one message layout for every script type,
//! selected per signature by bit `0x20` in the hash-type byte, active from
//! the chain's `unifiedSighashParam` height — which `siding/lib/overlay.mjs`
//! sets to `blake2bHeight: 0`, so on a sidestr chain beside `xbt` or
//! `txbt4` it applies from the genesis. Every spend on the live
//! `sidestr:txbt4-siding` chain carries hash type `0x21`
//! (`SIGHASH_ALL | SIGHASH_UNIFIED`); the message is ported from the
//! reference kernel's `codec/interpreter.js sighashUnified` (Melvin
//! Carvalho, AGPL-3.0) and proven by replaying that chain.
//!
//! A signature *without* the bit reads as plain BIP 341 on both families; a
//! signature *with* it on a stock chain is an invalid hash type, as BIP 341
//! says. Which reading applies is [`HeaderFamily::sighash_rules`]'s answer.
//!
//! [`HeaderFamily::sighash_rules`]: crate::block::HeaderFamily::sighash_rules

use bitcoin::consensus::encode::serialize;
use bitcoin::hashes::{sha256, Hash, HashEngine};
use bitcoin::sighash::{Annex, Prevouts, SighashCache, TapSighashType};
use bitcoin::{Transaction, TxOut};

use crate::block::{annex_of, schnorr_verify};
use crate::parents::Family;

/// Knots' opt-in bit in the hash-type byte (`SIGHASH_UNIFIED` in the
/// reference interpreter).
pub const SIGHASH_UNIFIED: u8 = 0x20;

/// Which signature-hash rules a spend is judged by.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SighashRules {
    /// BIP 341 only: the stock family, and any family before its fork height.
    #[default]
    Bip341,
    /// Knots' unified sighash is in force: a signature whose hash type carries
    /// [`SIGHASH_UNIFIED`] is verified over the unified message; one without
    /// it over BIP 341's, as before.
    KnotsUnified,
}

/// The taproot half of a unified message: which spend path, and for the
/// script path the leaf hash and code-separator position.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnifiedTaproot<'a> {
    /// Script type 2: the key path.
    KeyPath,
    /// Script type 3: a tapscript leaf, key version 0.
    ScriptPath {
        /// The TapLeaf hash of the leaf being executed.
        leaf_hash: &'a [u8; 32],
        /// The position of the last executed `OP_CODESEPARATOR`, `0xffffffff` for none.
        codesep_pos: u32,
    },
}

fn sha(parts: &[&[u8]]) -> [u8; 32] {
    let mut e = sha256::Hash::engine();
    for p in parts {
        e.input(p);
    }
    sha256::Hash::from_engine(e).to_byte_array()
}

fn compact_size(n: usize) -> Vec<u8> {
    match n {
        0..=0xfc => vec![n as u8],
        0xfd..=0xffff => vec![0xfd, (n & 0xff) as u8, (n >> 8) as u8],
        _ => {
            let mut v = vec![0xfe];
            v.extend((n as u32).to_le_bytes());
            v
        }
    }
}

/// Knots' unified sighash for a taproot spend (`interpreter.js
/// sighashUnified`, script types 2 and 3): BIP 341's layout with a script-type
/// byte in place of the spend type, single SHA-256 aggregates, under
/// `TaggedHash("UnifiedSighash")`. `hash_type` must carry
/// [`SIGHASH_UNIFIED`], no undefined bits, and an output type of 1 to 3;
/// `prevouts` is every input's, in order, since the message commits to all
/// spent amounts and scripts.
///
/// ```text
/// 0x00 ‖ hash_type ‖ version ‖ lock_time ‖ 0x00
/// [sha_prevouts ‖ sha_amounts ‖ sha_scriptpubkeys ‖ sha_sequences]   unless ANYONECANPAY
/// [sha_outputs]                                                      unless NONE or SINGLE
/// script_type
/// ANYONECANPAY ? outpoint ‖ prevout ‖ sequence : input index
/// annex present ‖ [sha(compact(annex) ‖ annex)]
/// [sha(this output)]                                                 SINGLE
/// [leaf_hash ‖ 0x00 ‖ codesep_pos]                                   script path
/// ```
pub fn unified_taproot_sighash(
    tx: &Transaction,
    index: usize,
    prevouts: &[TxOut],
    hash_type: u8,
    annex: Option<&[u8]>,
    path: UnifiedTaproot,
) -> Result<[u8; 32], &'static str> {
    if hash_type & SIGHASH_UNIFIED == 0 {
        return Err("unified sighash without SIGHASH_UNIFIED");
    }
    if hash_type & !(0x1f | 0x80 | SIGHASH_UNIFIED) != 0 {
        return Err("invalid taproot sighash type");
    }
    let output_type = hash_type & 0x1f;
    if !(1..=3).contains(&output_type) {
        return Err("invalid taproot sighash type");
    }
    if prevouts.len() != tx.input.len() {
        return Err("unified sighash needs every input prevout");
    }
    let input = tx.input.get(index).ok_or("no such input")?;
    let anyone = hash_type & 0x80 != 0;
    let outpoint = |i: &bitcoin::TxIn| serialize(&i.previous_output);
    let mut msg: Vec<u8> = vec![0x00, hash_type];
    msg.extend((tx.version.0 as u32).to_le_bytes());
    msg.extend(tx.lock_time.to_consensus_u32().to_le_bytes());
    msg.push(0x00);
    if !anyone {
        let prev: Vec<u8> = tx.input.iter().flat_map(outpoint).collect();
        let amounts: Vec<u8> = prevouts
            .iter()
            .flat_map(|p| p.value.to_sat().to_le_bytes())
            .collect();
        let spks: Vec<u8> = prevouts
            .iter()
            .flat_map(|p| serialize(&p.script_pubkey))
            .collect();
        let seqs: Vec<u8> = tx
            .input
            .iter()
            .flat_map(|i| i.sequence.0.to_le_bytes())
            .collect();
        msg.extend(sha(&[&prev]));
        msg.extend(sha(&[&amounts]));
        msg.extend(sha(&[&spks]));
        msg.extend(sha(&[&seqs]));
    }
    if output_type != 2 && output_type != 3 {
        let outs: Vec<u8> = tx.output.iter().flat_map(serialize).collect();
        msg.extend(sha(&[&outs]));
    }
    msg.push(match path {
        UnifiedTaproot::KeyPath => 2,
        UnifiedTaproot::ScriptPath { .. } => 3,
    });
    if anyone {
        msg.extend(outpoint(input));
        msg.extend(serialize(&prevouts[index]));
        msg.extend(input.sequence.0.to_le_bytes());
    } else {
        msg.extend((index as u32).to_le_bytes());
    }
    match annex {
        Some(a) => {
            msg.push(1);
            msg.extend(sha(&[&compact_size(a.len()), a]));
        }
        None => msg.push(0),
    }
    if output_type == 3 {
        let out = tx
            .output
            .get(index)
            .ok_or("sighash single without matching output")?;
        msg.extend(sha(&[&serialize(out)]));
    }
    if let UnifiedTaproot::ScriptPath {
        leaf_hash,
        codesep_pos,
    } = path
    {
        msg.extend(leaf_hash);
        msg.push(0x00);
        msg.extend(codesep_pos.to_le_bytes());
    }
    let tag = sha256::Hash::hash(b"UnifiedSighash").to_byte_array();
    Ok(sha(&[&tag, &tag, &msg]))
}

/// Verify one input as a taproot key-path spend under `rules`: one Schnorr
/// signature, 64 bytes for `SIGHASH_DEFAULT` or 65 with an explicit type, an
/// annex allowed, over BIP 341's sighash — or, under
/// [`SighashRules::KnotsUnified`] with the [`SIGHASH_UNIFIED`] bit set,
/// over the unified message. Any other script type and the script path are
/// refused, never skipped (`interpreter.js #verifyTaproot`, key path).
pub fn verify_taproot_key_path(
    tx: &Transaction,
    index: usize,
    prevouts: &[TxOut],
    rules: SighashRules,
) -> Result<(), &'static str> {
    let prevout = prevouts.get(index).ok_or("no prevout for the input")?;
    let input = tx.input.get(index).ok_or("no such input")?;
    if !prevout.script_pubkey.is_p2tr() {
        return Err("unsupported script type: sidestr-core verifies taproot spends only");
    }
    if !input.script_sig.is_empty() {
        return Err("WITNESS_MALLEATED");
    }
    let mut items: Vec<&[u8]> = input.witness.iter().collect();
    if items.is_empty() {
        return Err("empty taproot witness");
    }
    let annex = annex_of(&mut items)?;
    if items.len() != 1 {
        return Err("taproot script path: not a key-path spend");
    }
    let raw = items[0];
    let (sig, hash_type) = match raw.len() {
        64 => (raw, 0u8),
        65 => {
            if raw[64] == 0 {
                return Err("explicit SIGHASH_DEFAULT in 65-byte signature");
            }
            (&raw[..64], raw[64])
        }
        _ => return Err("bad key-path signature size"),
    };
    let msg = if rules == SighashRules::KnotsUnified && hash_type & SIGHASH_UNIFIED != 0 {
        unified_taproot_sighash(
            tx,
            index,
            prevouts,
            hash_type,
            annex.as_ref().map(Annex::as_bytes),
            UnifiedTaproot::KeyPath,
        )?
    } else {
        let ty = TapSighashType::from_consensus_u8(hash_type)
            .map_err(|_| "invalid taproot sighash type")?;
        if prevouts.len() != tx.input.len() {
            return Err("taproot sighash needs every input prevout");
        }
        SighashCache::new(tx)
            .taproot_signature_hash(index, &Prevouts::All(prevouts), annex, None, ty)
            .map_err(|_| "sighash failed")?
            .to_byte_array()
    };
    if schnorr_verify(&msg, sig, &prevout.script_pubkey.as_bytes()[2..34]) {
        Ok(())
    } else {
        Err("invalid key-path schnorr signature")
    }
}

/// The signature-hash rules a chain inherits from its parent's family (SPEC
/// 3, 0.0.3): Knots' unified sighash beside a BLAKE2b parent, BIP 341
/// beside stock Bitcoin. The same answer [`HeaderFamily::sighash_rules`]
/// gives for a sidestr chain of that family, whose fork height is 0, for a
/// caller — a wallet — that holds a chain document and no family type
/// (`siding/lib/txsign.mjs usesUnifiedSighash`).
///
/// ```
/// use sidestr_core::parents::{resolve_parent, Family};
/// use sidestr_core::sighash::{rules_for, SighashRules};
///
/// assert_eq!(rules_for(resolve_parent("tbtc4").unwrap().family), SighashRules::Bip341);
/// assert_eq!(rules_for(Family::Blake2b), SighashRules::KnotsUnified);
/// ```
///
/// [`HeaderFamily::sighash_rules`]: crate::block::HeaderFamily::sighash_rules
pub fn rules_for(family: Family) -> SighashRules {
    match family {
        Family::Stock => SighashRules::Bip341,
        Family::Blake2b => SighashRules::KnotsUnified,
    }
}

/// The hash type a key-path signature carries under `rules`
/// (`txsign.mjs keyPathSighash`): `0x21` (`SIGHASH_ALL | SIGHASH_UNIFIED`)
/// where the unified sighash is in force, `0x01` (`SIGHASH_ALL`) under BIP
/// 341. Always explicit, so every witness is 65 bytes and names its rule.
pub fn key_path_hash_type(rules: SighashRules) -> u8 {
    match rules {
        SighashRules::KnotsUnified => 0x01 | SIGHASH_UNIFIED,
        SighashRules::Bip341 => 0x01,
    }
}

/// The message input `index`'s key-path signature commits to under `rules`,
/// and the hash-type byte appended to that signature (`txsign.mjs
/// keyPathSighash`). `prevouts` is every input's, in order. The signer's
/// witness is the 64-byte BIP 340 signature over the message followed by
/// the byte: exactly what [`verify_taproot_key_path`] checks under the same
/// rules, and what the reference producer checks before a transaction enters
/// its mempool.
///
/// ```
/// use bitcoin::hashes::Hash;
/// use bitcoin::secp256k1::{Keypair, Message, SecretKey};
/// use bitcoin::{absolute::LockTime, transaction::Version, Amount, OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Txid, Witness};
/// use sidestr_core::block::{challenge_for, secp};
/// use sidestr_core::sighash::{key_path_sighash, verify_taproot_key_path, SighashRules};
///
/// let kp = Keypair::from_secret_key(secp(), &SecretKey::from_slice(&[0x11; 32]).unwrap());
/// let me = challenge_for(&kp.x_only_public_key().0);
/// let prevouts = vec![TxOut { value: Amount::from_sat(50_000), script_pubkey: me.clone() }];
/// let mut tx = Transaction { version: Version::TWO, lock_time: LockTime::ZERO,
///     input: vec![TxIn { previous_output: OutPoint { txid: Txid::all_zeros(), vout: 0 }, script_sig: ScriptBuf::new(),
///                        sequence: Sequence(0xffff_fffd), witness: Witness::new() }],
///     output: vec![TxOut { value: Amount::from_sat(49_000), script_pubkey: me }] };
///
/// // beside a BLAKE2b parent: hash type 0x21, refused beside stock Bitcoin (txsign-test.mjs)
/// let (msg, ht) = key_path_sighash(&tx, 0, &prevouts, SighashRules::KnotsUnified).unwrap();
/// let sig = secp().sign_schnorr_with_aux_rand(&Message::from_digest(msg), &kp, &[0; 32]);
/// tx.input[0].witness = Witness::from_slice(&[[sig.serialize().as_slice(), &[ht]].concat()]);
/// assert_eq!(ht, 0x21);
/// assert!(verify_taproot_key_path(&tx, 0, &prevouts, SighashRules::KnotsUnified).is_ok());
/// assert!(verify_taproot_key_path(&tx, 0, &prevouts, SighashRules::Bip341).is_err());
/// ```
pub fn key_path_sighash(
    tx: &Transaction,
    index: usize,
    prevouts: &[TxOut],
    rules: SighashRules,
) -> Result<([u8; 32], u8), &'static str> {
    let hash_type = key_path_hash_type(rules);
    let msg = match rules {
        SighashRules::KnotsUnified => unified_taproot_sighash(
            tx,
            index,
            prevouts,
            hash_type,
            None,
            UnifiedTaproot::KeyPath,
        )?,
        SighashRules::Bip341 => {
            if prevouts.len() != tx.input.len() {
                return Err("taproot sighash needs every input prevout");
            }
            if index >= tx.input.len() {
                return Err("no such input");
            }
            SighashCache::new(tx)
                .taproot_key_spend_signature_hash(
                    index,
                    &Prevouts::All(prevouts),
                    TapSighashType::All,
                )
                .map_err(|_| "sighash failed")?
                .to_byte_array()
        }
    };
    Ok((msg, hash_type))
}

#[cfg(test)]
mod tests {
    use super::*;
    use bitcoin::secp256k1::{Keypair, Message, SecretKey};
    use bitcoin::transaction::Version;
    use bitcoin::{absolute::LockTime, Amount, OutPoint, ScriptBuf, Sequence, TxIn, Witness};

    fn spend(hash_type: u8, rules: SighashRules) -> (Transaction, Vec<TxOut>) {
        let key = SecretKey::from_slice(&[3u8; 32]).unwrap();
        let kp = Keypair::from_secret_key(crate::block::secp(), &key);
        let me = crate::block::challenge_for(&kp.x_only_public_key().0);
        let prevouts = vec![TxOut {
            value: Amount::from_sat(10_000),
            script_pubkey: me.clone(),
        }];
        let mut tx = Transaction {
            version: Version::TWO,
            lock_time: LockTime::ZERO,
            input: vec![TxIn {
                previous_output: OutPoint {
                    txid: bitcoin::Txid::all_zeros(),
                    vout: 1,
                },
                script_sig: ScriptBuf::new(),
                sequence: Sequence(0xffff_fffd),
                witness: Witness::new(),
            }],
            output: vec![TxOut {
                value: Amount::from_sat(9_000),
                script_pubkey: me,
            }],
        };
        let msg = match rules {
            SighashRules::KnotsUnified if hash_type & SIGHASH_UNIFIED != 0 => {
                unified_taproot_sighash(&tx, 0, &prevouts, hash_type, None, UnifiedTaproot::KeyPath)
                    .unwrap()
            }
            _ => SighashCache::new(&tx)
                .taproot_key_spend_signature_hash(
                    0,
                    &Prevouts::All(&prevouts),
                    TapSighashType::from_consensus_u8(hash_type & !SIGHASH_UNIFIED).unwrap(),
                )
                .unwrap()
                .to_byte_array(),
        };
        let sig = crate::block::secp()
            .sign_schnorr_with_aux_rand(&Message::from_digest(msg), &kp, &[0u8; 32])
            .serialize()
            .to_vec();
        let item = if hash_type == 0 {
            sig
        } else {
            [sig, vec![hash_type]].concat()
        };
        tx.input[0].witness = Witness::from_slice(&[item]);
        (tx, prevouts)
    }

    #[test]
    fn unified_bit_is_read_only_where_the_rules_say() {
        let (tx, p) = spend(0x21, SighashRules::KnotsUnified);
        assert!(verify_taproot_key_path(&tx, 0, &p, SighashRules::KnotsUnified).is_ok());
        assert_eq!(
            verify_taproot_key_path(&tx, 0, &p, SighashRules::Bip341),
            Err("invalid taproot sighash type")
        );
        let (tx, p) = spend(0x00, SighashRules::KnotsUnified);
        assert!(verify_taproot_key_path(&tx, 0, &p, SighashRules::KnotsUnified).is_ok());
        assert!(verify_taproot_key_path(&tx, 0, &p, SighashRules::Bip341).is_ok());
        let (tx, p) = spend(0x01, SighashRules::Bip341);
        assert!(verify_taproot_key_path(&tx, 0, &p, SighashRules::KnotsUnified).is_ok());
        // a unified message is not a BIP 341 message
        let (tx, p) = spend(0x21, SighashRules::Bip341);
        assert!(verify_taproot_key_path(&tx, 0, &p, SighashRules::KnotsUnified).is_err());
    }

    #[test]
    fn unified_message_refuses_undefined_types() {
        let (tx, p) = spend(0x00, SighashRules::Bip341);
        for bad in [0x20u8, 0x24, 0x60, 0xa0] {
            assert!(
                unified_taproot_sighash(&tx, 0, &p, bad, None, UnifiedTaproot::KeyPath).is_err(),
                "{bad:#x}"
            );
        }
        assert!(unified_taproot_sighash(&tx, 0, &p, 0x01, None, UnifiedTaproot::KeyPath).is_err());
        assert!(unified_taproot_sighash(&tx, 0, &[], 0x21, None, UnifiedTaproot::KeyPath).is_err());
        let a = unified_taproot_sighash(&tx, 0, &p, 0x21, None, UnifiedTaproot::KeyPath).unwrap();
        let b = unified_taproot_sighash(&tx, 0, &p, 0x21, Some(&[0x50]), UnifiedTaproot::KeyPath)
            .unwrap();
        let c = unified_taproot_sighash(
            &tx,
            0,
            &p,
            0x21,
            None,
            UnifiedTaproot::ScriptPath {
                leaf_hash: &[9u8; 32],
                codesep_pos: 0xffff_ffff,
            },
        )
        .unwrap();
        let d = unified_taproot_sighash(&tx, 0, &p, 0xa1, None, UnifiedTaproot::KeyPath).unwrap();
        assert!(a != b && a != c && a != d && b != c);
    }
}