torvyon-core 0.1.3

Keys, addresses, post-quantum signing and transaction building for the Torvyon blockchain
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
//! Deterministic v4 spending conditions.

use crate::{hash::sha256, Error, PublicKey, Result};

/// Maximum encoded condition size in bytes.
pub const MAX_ENCODED: usize = 1024;
/// Maximum tree depth.
pub const MAX_DEPTH: usize = 4;
/// Maximum nodes in one condition tree.
pub const MAX_NODES: usize = 32;
/// Maximum public keys counted across one condition tree.
pub const MAX_KEYS: usize = 32;
/// Maximum keys in one multisig node.
pub const MAX_MULTISIG_N: usize = 16;
/// Maximum hashlock preimage length in bytes.
pub const MAX_PREIMAGE_LEN: usize = 64;

const TAG_SIG: u8 = 0x01;
const TAG_MULTISIG: u8 = 0x02;
const TAG_HEIGHT: u8 = 0x03;
const TAG_RELATIVE: u8 = 0x04;
const TAG_HASHLOCK: u8 = 0x05;
const TAG_AND: u8 = 0x10;
const TAG_OR: u8 = 0x11;

/// One deterministic spending-condition node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Condition {
    /// CHECK_SIGNATURE for one public key.
    Signature(PublicKey),
    /// CHECK_MULTISIG M-of-N. Keys are canonicalized into ascending order.
    Multisig {
        /// Number of signatures required.
        required: u8,
        /// Authorized public keys.
        keys: Vec<PublicKey>,
    },
    /// CHECK_BLOCK_HEIGHT.
    AbsoluteHeight(u64),
    /// CHECK_RELATIVE_LOCK in blocks.
    RelativeBlocks(u32),
    /// CHECK_HASHLOCK: stores SHA-256(secret), never the secret.
    Hashlock([u8; 32]),
    /// Safe AND.
    And(Vec<Condition>),
    /// Safe OR.
    Or(Vec<Condition>),
}

/// Parameters for an escrow/release path with a timed refund path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EscrowRefundTemplate {
    /// Number of signatures required for the cooperative release path.
    pub release_required: u8,
    /// Public keys authorized for the cooperative release path.
    pub release_keys: Vec<PublicKey>,
    /// Public key that can take the refund path after [`refund_height`](Self::refund_height).
    pub refund_key: PublicKey,
    /// Absolute block height at which the refund path opens.
    pub refund_height: u64,
}

/// Parameters for a hash-time-locked contract.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HtlcTemplate {
    /// Recipient public key for the claim path.
    pub recipient_key: PublicKey,
    /// Refund public key for the timeout path.
    pub refund_key: PublicKey,
    /// SHA-256(secret), never the secret itself.
    pub secret_hash: [u8; 32],
    /// Absolute block height at which the refund path opens.
    pub refund_height: u64,
}

/// Parameters for a simple two-party payment-channel style lock.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PaymentChannelTemplate {
    /// Public keys authorized for the cooperative multisig path.
    pub participant_keys: Vec<PublicKey>,
    /// Required signatures for the cooperative path. If zero, all
    /// participants are required.
    pub required: u8,
    /// Relative block age before the timeout path can be used.
    pub relative_blocks: u32,
}

/// Higher-level condition templates built only from deterministic v4
/// primitives. These are convenience constructors, not extra consensus rules.
#[derive(Debug, Clone, Copy)]
pub struct ConditionTemplates;

impl ConditionTemplates {
    /// Foundation/business treasury: M-of-N multisig.
    pub fn treasury_multisig(required: u8, keys: Vec<PublicKey>) -> Condition {
        Condition::multisig(required, keys)
    }

    /// Vesting/delayed payment: owner signature plus absolute block height.
    pub fn vesting(owner_key: PublicKey, unlock_height: u64) -> Condition {
        Condition::all(vec![
            Condition::signature(owner_key),
            Condition::absolute_height(unlock_height),
        ])
    }

    /// Escrow/refund: cooperative multisig release, or refund key after height.
    pub fn escrow_refund(p: EscrowRefundTemplate) -> Condition {
        Condition::any(vec![
            Condition::multisig(p.release_required, p.release_keys),
            Condition::all(vec![
                Condition::signature(p.refund_key),
                Condition::absolute_height(p.refund_height),
            ]),
        ])
    }

    /// HTLC: recipient can claim with the secret, refund key can recover after height.
    pub fn htlc(p: HtlcTemplate) -> Condition {
        Condition::any(vec![
            Condition::all(vec![
                Condition::signature(p.recipient_key),
                Condition::hashlock(p.secret_hash),
            ]),
            Condition::all(vec![
                Condition::signature(p.refund_key),
                Condition::absolute_height(p.refund_height),
            ]),
        ])
    }

    /// Payment-channel style lock: cooperative multisig plus a relative-lock path.
    pub fn payment_channel(p: PaymentChannelTemplate) -> Condition {
        let required = if p.required == 0 {
            p.participant_keys.len() as u8
        } else {
            p.required
        };
        Condition::all(vec![
            Condition::multisig(required, p.participant_keys),
            Condition::relative_blocks(p.relative_blocks),
        ])
    }
}

impl Condition {
    /// Decode a canonical condition encoding.
    pub fn decode(bytes: &[u8]) -> Result<Self> {
        let c = Self::decode_fragment(bytes)?;
        if !c.requires_signature() {
            return Err(Error::InvalidCondition(
                "a spending path does not require any signature".into(),
            ));
        }
        Ok(c)
    }

    /// Decode a canonical condition fragment. Fragments are useful while
    /// building AND/OR trees; the final top-level condition must still require
    /// a signature on every spending path.
    pub fn decode_fragment(bytes: &[u8]) -> Result<Self> {
        if bytes.is_empty() || bytes.len() > MAX_ENCODED {
            return Err(Error::InvalidCondition(format!(
                "encoding is {} bytes, must be 1..{MAX_ENCODED}",
                bytes.len()
            )));
        }
        let mut d = Decoder {
            bytes,
            pos: 0,
            nodes: 0,
        };
        let c = d.node(1)?;
        if d.pos != bytes.len() {
            return Err(Error::InvalidCondition(format!(
                "{} trailing bytes",
                bytes.len() - d.pos
            )));
        }
        c.validate_structure()?;
        if c.encode()? != bytes {
            return Err(Error::InvalidCondition("non-canonical encoding".into()));
        }
        Ok(c)
    }

    /// Decode from canonical condition hex.
    pub fn decode_hex(hex_text: &str) -> Result<Self> {
        let bytes =
            hex::decode(hex_text).map_err(|_| Error::InvalidCondition("invalid condition hex".into()))?;
        Self::decode(&bytes)
    }

    /// Decode a canonical condition fragment from hex.
    pub fn decode_fragment_hex(hex_text: &str) -> Result<Self> {
        let bytes =
            hex::decode(hex_text).map_err(|_| Error::InvalidCondition("invalid condition hex".into()))?;
        Self::decode_fragment(&bytes)
    }

    /// Build CHECK_SIGNATURE.
    pub fn signature(public_key: PublicKey) -> Self {
        Self::Signature(public_key)
    }

    /// Build CHECK_MULTISIG.
    pub fn multisig(required: u8, keys: Vec<PublicKey>) -> Self {
        Self::Multisig { required, keys }
    }

    /// Build CHECK_BLOCK_HEIGHT.
    pub fn absolute_height(height: u64) -> Self {
        Self::AbsoluteHeight(height)
    }

    /// Build CHECK_RELATIVE_LOCK.
    pub fn relative_blocks(blocks: u32) -> Self {
        Self::RelativeBlocks(blocks)
    }

    /// Build CHECK_HASHLOCK from an already-computed SHA-256 hash.
    pub fn hashlock(hash: [u8; 32]) -> Self {
        Self::Hashlock(hash)
    }

    /// Build CHECK_HASHLOCK from a secret preimage.
    pub fn hashlock_secret(secret: &[u8]) -> Result<Self> {
        if secret.is_empty() || secret.len() > MAX_PREIMAGE_LEN {
            return Err(Error::InvalidCondition("invalid hashlock preimage length".into()));
        }
        Ok(Self::Hashlock(sha256(secret)))
    }

    /// Build AND.
    pub fn all(children: Vec<Condition>) -> Self {
        Self::And(children)
    }

    /// Build OR.
    pub fn any(children: Vec<Condition>) -> Self {
        Self::Or(children)
    }

    /// Canonical binary encoding, byte-for-byte with the Go node.
    pub fn encode(&self) -> Result<Vec<u8>> {
        let c = self.canonicalized();
        c.validate_structure()?;
        let mut out = Vec::new();
        c.encode_into(&mut out);
        if out.len() > MAX_ENCODED {
            return Err(Error::InvalidCondition(format!(
                "encoding larger than {MAX_ENCODED} bytes"
            )));
        }
        Ok(out)
    }

    /// Hex of the canonical binary encoding.
    pub fn encode_hex(&self) -> Result<String> {
        Ok(hex::encode(self.encode()?))
    }

    /// SHA-256 of the canonical binary encoding.
    pub fn condition_hash(&self) -> Result<[u8; 32]> {
        Ok(sha256(&self.encode()?))
    }

    fn canonicalized(&self) -> Self {
        match self {
            Self::Multisig { required, keys } => {
                let mut keys = keys.clone();
                keys.sort_by_key(|k| k.to_bytes());
                Self::Multisig {
                    required: *required,
                    keys,
                }
            }
            Self::And(children) => Self::And(children.iter().map(Self::canonicalized).collect()),
            Self::Or(children) => Self::Or(children.iter().map(Self::canonicalized).collect()),
            other => other.clone(),
        }
    }

    fn encode_into(&self, out: &mut Vec<u8>) {
        match self {
            Self::Signature(key) => {
                out.push(TAG_SIG);
                out.extend_from_slice(&key.to_bytes());
            }
            Self::Multisig { required, keys } => {
                out.push(TAG_MULTISIG);
                out.push(*required);
                out.push(keys.len() as u8);
                for key in keys {
                    out.extend_from_slice(&key.to_bytes());
                }
            }
            Self::AbsoluteHeight(height) => {
                out.push(TAG_HEIGHT);
                out.extend_from_slice(&height.to_be_bytes());
            }
            Self::RelativeBlocks(blocks) => {
                out.push(TAG_RELATIVE);
                out.extend_from_slice(&blocks.to_be_bytes());
            }
            Self::Hashlock(hash) => {
                out.push(TAG_HASHLOCK);
                out.extend_from_slice(hash);
            }
            Self::And(children) => {
                out.push(TAG_AND);
                out.push(children.len() as u8);
                for child in children {
                    child.encode_into(out);
                }
            }
            Self::Or(children) => {
                out.push(TAG_OR);
                out.push(children.len() as u8);
                for child in children {
                    child.encode_into(out);
                }
            }
        }
    }

    fn validate_structure(&self) -> Result<()> {
        let mut stats = Stats::default();
        self.validate_inner(1, &mut stats)?;
        Ok(())
    }

    fn validate_inner(&self, depth: usize, stats: &mut Stats) -> Result<()> {
        if depth > MAX_DEPTH {
            return Err(Error::InvalidCondition(format!("deeper than {MAX_DEPTH}")));
        }
        stats.nodes += 1;
        if stats.nodes > MAX_NODES {
            return Err(Error::InvalidCondition(format!("more than {MAX_NODES} nodes")));
        }
        match self {
            Self::Signature(_) => {
                stats.keys += 1;
            }
            Self::Multisig { required, keys } => {
                if keys.is_empty()
                    || keys.len() > MAX_MULTISIG_N
                    || *required == 0
                    || *required as usize > keys.len()
                {
                    return Err(Error::InvalidCondition("invalid multisig threshold".into()));
                }
                stats.keys += keys.len();
                for pair in keys.windows(2) {
                    if pair[0].to_bytes() >= pair[1].to_bytes() {
                        return Err(Error::InvalidCondition(
                            "multisig keys must be strictly ascending".into(),
                        ));
                    }
                }
            }
            Self::AbsoluteHeight(_) | Self::Hashlock(_) => {}
            Self::RelativeBlocks(blocks) => {
                if *blocks == 0 || *blocks > 1_000_000 {
                    return Err(Error::InvalidCondition("invalid relative lock".into()));
                }
            }
            Self::And(children) | Self::Or(children) => {
                if children.len() < 2 || children.len() > 8 {
                    return Err(Error::InvalidCondition("invalid child count".into()));
                }
                for child in children {
                    child.validate_inner(depth + 1, stats)?;
                }
            }
        }
        if stats.keys > MAX_KEYS {
            return Err(Error::InvalidCondition(format!("more than {MAX_KEYS} keys")));
        }
        Ok(())
    }

    fn requires_signature(&self) -> bool {
        match self {
            Self::Signature(_) | Self::Multisig { .. } => true,
            Self::AbsoluteHeight(_) | Self::RelativeBlocks(_) | Self::Hashlock(_) => false,
            Self::And(children) => children.iter().any(Self::requires_signature),
            Self::Or(children) => children.iter().all(Self::requires_signature),
        }
    }
}

#[derive(Default)]
struct Stats {
    nodes: usize,
    keys: usize,
}

struct Decoder<'a> {
    bytes: &'a [u8],
    pos: usize,
    nodes: usize,
}

impl<'a> Decoder<'a> {
    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
        if self.pos + n > self.bytes.len() {
            return Err(Error::InvalidCondition("truncated".into()));
        }
        let out = &self.bytes[self.pos..self.pos + n];
        self.pos += n;
        Ok(out)
    }

    fn node(&mut self, depth: usize) -> Result<Condition> {
        if depth > MAX_DEPTH {
            return Err(Error::InvalidCondition(format!("deeper than {MAX_DEPTH}")));
        }
        self.nodes += 1;
        if self.nodes > MAX_NODES {
            return Err(Error::InvalidCondition(format!("more than {MAX_NODES} nodes")));
        }
        let tag = self.take(1)?[0];
        match tag {
            TAG_SIG => Ok(Condition::Signature(
                PublicKey::from_bytes(self.take(32)?)
                    .map_err(|_| Error::InvalidCondition("invalid public key".into()))?,
            )),
            TAG_MULTISIG => {
                let required = self.take(1)?[0];
                let count = self.take(1)?[0] as usize;
                let mut keys = Vec::with_capacity(count);
                for _ in 0..count {
                    keys.push(
                        PublicKey::from_bytes(self.take(32)?)
                            .map_err(|_| Error::InvalidCondition("invalid public key".into()))?,
                    );
                }
                Ok(Condition::Multisig { required, keys })
            }
            TAG_HEIGHT => {
                let mut b = [0u8; 8];
                b.copy_from_slice(self.take(8)?);
                Ok(Condition::AbsoluteHeight(u64::from_be_bytes(b)))
            }
            TAG_RELATIVE => {
                let mut b = [0u8; 4];
                b.copy_from_slice(self.take(4)?);
                Ok(Condition::RelativeBlocks(u32::from_be_bytes(b)))
            }
            TAG_HASHLOCK => {
                let mut h = [0u8; 32];
                h.copy_from_slice(self.take(32)?);
                Ok(Condition::Hashlock(h))
            }
            TAG_AND | TAG_OR => {
                let count = self.take(1)?[0] as usize;
                let mut children = Vec::with_capacity(count);
                for _ in 0..count {
                    children.push(self.node(depth + 1)?);
                }
                if tag == TAG_AND {
                    Ok(Condition::And(children))
                } else {
                    Ok(Condition::Or(children))
                }
            }
            other => Err(Error::InvalidCondition(format!("unknown tag 0x{other:02x}"))),
        }
    }
}