charms_data/
lib.rs

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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
use anyhow::{anyhow, ensure, Result};
use ark_std::{
    cmp::Ordering,
    collections::BTreeMap,
    format,
    string::{String, ToString},
    vec::Vec,
};
use ciborium::Value;
use core::{convert::TryInto, fmt};
use serde::{
    de,
    de::{DeserializeOwned, SeqAccess, Visitor},
    ser::SerializeTuple,
    Deserialize, Deserializer, Serialize, Serializer,
};
pub mod util;

/// Macro to check a condition and return false (early) if it does not hold.
/// This is useful for checking pre-requisite conditions in predicate-type functions.
/// Inspired by the `ensure!` macro from the `anyhow` crate.
/// The function must return a boolean.
/// Example:
/// ```rust
/// use charms_data::check;
///
/// fn b_is_multiple_of_a(a: u32, b: u32) -> bool {
///     check!(a <= b && a != 0);    // returns false early if `a` is greater than `b` or `a` is zero
///     match b % a {
///         0 => true,
///         _ => false,
///     }
/// }
#[macro_export]
macro_rules! check {
    ($condition:expr) => {
        if !$condition {
            eprintln!("condition does not hold: {}", stringify!($condition));
            return false;
        }
    };
}

/// Represents a transaction involving Charms.
/// A Charms transaction sits on top of a Bitcoin transaction. Therefore, it transforms a set of
/// input UTXOs into a set of output UTXOs.
/// A Charms transaction may also reference other valid UTXOs that are not being spent or created.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Transaction {
    /// Input UTXOs.
    pub ins: BTreeMap<UtxoId, Charms>,
    /// Reference UTXOs.
    pub refs: BTreeMap<UtxoId, Charms>,
    /// Output charms.
    pub outs: Vec<Charms>,
}

/// Charms are tokens, NFTs or instances of arbitrary app state.
/// This type alias represents a collection of charms.
/// Structurally it is a map of `app -> data`.
pub type Charms = BTreeMap<App, Data>;

/// ID of a UTXO (Unspent Transaction Output) in the underlying ledger system (e.g. Bitcoin).
/// A UTXO ID is a pair of `(transaction ID, index of the output)`.
#[cfg_attr(test, derive(test_strategy::Arbitrary))]
#[derive(Clone, Default, Eq, Ord, PartialEq, PartialOrd)]
pub struct UtxoId(pub TxId, pub u32);

impl UtxoId {
    /// Convert to a byte array (of 36 bytes).
    pub fn to_bytes(&self) -> [u8; 36] {
        let mut bytes = [0u8; 36];
        bytes[..32].copy_from_slice(&self.0 .0); // Copy TxId
        bytes[32..].copy_from_slice(&self.1.to_le_bytes()); // Copy index as little-endian
        bytes
    }

    /// Create `UtxoId` from a byte array (of 36 bytes).
    pub fn from_bytes(bytes: [u8; 36]) -> Self {
        let mut txid_bytes = [0u8; 32];
        txid_bytes.copy_from_slice(&bytes[..32]);
        let index = u32::from_le_bytes(bytes[32..].try_into().unwrap());
        UtxoId(TxId(txid_bytes), index)
    }

    /// Try to create `UtxoId` from a string in the format `txid_hex:index`.
    /// Example:
    /// ```
    /// use charms_data::UtxoId;
    /// let utxo_id = UtxoId::from_str("92077a14998b31367efeec5203a00f1080facdb270cbf055f09b66ae0a273c7d:3").unwrap();
    /// ```
    pub fn from_str(s: &str) -> Result<Self> {
        let parts: Vec<&str> = s.split(':').collect();
        if parts.len() != 2 {
            return Err(anyhow!("expected format: txid_hex:index"));
        }

        let txid = TxId::from_str(parts[0])?;

        let index = parts[1]
            .parse::<u32>()
            .map_err(|e| anyhow!("invalid index: {}", e))?;

        Ok(UtxoId(txid, index))
    }

    fn to_string_internal(&self) -> String {
        format!("{}:{}", self.0.to_string(), self.1)
    }
}

impl fmt::Display for UtxoId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.to_string_internal().fmt(f)
    }
}

impl fmt::Debug for UtxoId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "UtxoId({})", self.to_string_internal())
    }
}

impl Serialize for UtxoId {
    fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if serializer.is_human_readable() {
            serializer.serialize_str(&self.to_string())
        } else {
            serializer.serialize_bytes(self.to_bytes().as_ref())
        }
    }
}

impl<'de> Deserialize<'de> for UtxoId {
    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct UtxoIdVisitor;

        impl<'de> Visitor<'de> for UtxoIdVisitor {
            type Value = UtxoId;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a string in format 'txid_hex:index' or a tuple (TxId, u32)")
            }

            // Handle human-readable format ("txid_hex:index")
            fn visit_str<E>(self, value: &str) -> Result<UtxoId, E>
            where
                E: de::Error,
            {
                UtxoId::from_str(value).map_err(E::custom)
            }

            // Handle non-human-readable byte format [u8; 36]
            fn visit_bytes<E>(self, v: &[u8]) -> core::result::Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(UtxoId::from_bytes(v.try_into().map_err(|e| {
                    E::custom(format!("invalid utxo_id bytes: {}", e))
                })?))
            }
        }

        if deserializer.is_human_readable() {
            deserializer.deserialize_str(UtxoIdVisitor)
        } else {
            deserializer.deserialize_bytes(UtxoIdVisitor)
        }
    }
}

/// App represents an application that can be used to create, transform or destroy charms (tokens,
/// NFTs and other instances of app data).
///
/// An app is identified by a single character `tag`, a 32-byte `identity` and a 32-byte `vk`
/// (verification key).
/// The `tag` is a single character that represents the type of the app, with two special values:
/// - `TOKEN` (tag `t`) for tokens,
/// - `NFT` (tag `n`) for NFTs.
///
/// Other values of `tag` are perfectly legal. The above ones are special: tokens and NFTs can be
/// transferred without providing the app's implementation (RISC-V binary).
///
/// The `vk` is a 32-byte byte string (hash) that is used to verify proofs that the app's contract
/// is satisfied (against the certain transaction, additional public input and private input).
///
/// The `identity` is a 32-byte byte string (hash) that uniquely identifies the app among other apps
/// implemented using the same code.
#[cfg_attr(test, derive(proptest_derive::Arbitrary))]
#[derive(Clone, Default, Eq, Ord, PartialEq, PartialOrd)]
pub struct App {
    pub tag: char,
    pub identity: B32,
    pub vk: B32,
}

impl fmt::Display for App {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}/{}/{}", self.tag, self.identity, self.vk)
    }
}

impl fmt::Debug for App {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "App({}/{}/{})", self.tag, self.identity, self.vk)
    }
}

impl Serialize for App {
    fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if serializer.is_human_readable() {
            serializer.serialize_str(&self.to_string())
        } else {
            let mut s = serializer.serialize_tuple(3)?;
            s.serialize_element(&self.tag)?;
            s.serialize_element(&self.identity)?;
            s.serialize_element(&self.vk)?;
            s.end()
        }
    }
}

impl<'de> Deserialize<'de> for App {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct AppVisitor;

        impl<'de> Visitor<'de> for AppVisitor {
            type Value = App;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a string in format 'tag_char/identity_hex/vk_hex' or a struct with tag, identity and vk fields")
            }

            // Handle human-readable format ("tag_char/identity_hex/vk_hex")
            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                // Split the string at '/'
                let parts: Vec<&str> = value.split('/').collect();
                if parts.len() != 3 {
                    return Err(E::custom("expected format: tag_char/identity_hex/vk_hex"));
                }

                // Decode the hex strings
                let tag: char = {
                    let mut chars = parts[0].chars();
                    let Some(tag) = chars.next() else {
                        return Err(E::custom("expected tag"));
                    };
                    let None = chars.next() else {
                        return Err(E::custom("tag must be a single character"));
                    };
                    tag
                };

                let identity = B32::from_str(parts[1]).map_err(E::custom)?;

                let vk = B32::from_str(parts[2]).map_err(E::custom)?;

                Ok(App { tag, identity, vk })
            }

            fn visit_seq<A>(self, mut seq: A) -> core::result::Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let tag = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::missing_field("tag"))?;
                let id = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::missing_field("id"))?;
                let vk_hash = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::missing_field("vk_hash"))?;

                Ok(App {
                    tag,
                    identity: id,
                    vk: vk_hash,
                })
            }
        }

        if deserializer.is_human_readable() {
            deserializer.deserialize_str(AppVisitor)
        } else {
            deserializer.deserialize_tuple(3, AppVisitor)
        }
    }
}

/// ID (hash) of a transaction in the underlying ledger (Bitcoin).
#[cfg_attr(test, derive(proptest_derive::Arbitrary))]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub struct TxId(pub [u8; 32]);

impl TxId {
    /// Try to create `TxId` from a string of 64 hex characters.
    /// Note that string representation of transaction IDs in Bitcoin is reversed, and so is ours
    /// (for compatibility).
    ///
    /// Example:
    /// ```
    /// use charms_data::TxId;
    /// let tx_id = TxId::from_str("92077a14998b31367efeec5203a00f1080facdb270cbf055f09b66ae0a273c7d").unwrap();
    /// ```
    pub fn from_str(s: &str) -> Result<Self> {
        ensure!(s.len() == 64, "expected 64 hex characters");
        let bytes = hex::decode(s).map_err(|e| anyhow!("invalid txid hex: {}", e))?;
        let mut txid: [u8; 32] = bytes.try_into().unwrap();
        txid.reverse();
        Ok(TxId(txid))
    }

    fn to_string_internal(&self) -> String {
        let mut txid = self.0;
        txid.reverse();
        hex::encode(&txid)
    }
}

impl fmt::Display for TxId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.to_string_internal().fmt(f)
    }
}

impl fmt::Debug for TxId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "TxId({})", self.to_string_internal())
    }
}

impl Serialize for TxId {
    fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if serializer.is_human_readable() {
            serializer.serialize_str(&self.to_string())
        } else {
            serializer.serialize_bytes(&self.0)
        }
    }
}

impl<'de> Deserialize<'de> for TxId {
    fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct TxIdVisitor;

        impl<'de> Visitor<'de> for TxIdVisitor {
            type Value = TxId;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a string of 64 hex characters or a byte array of 32 bytes")
            }

            // Handle human-readable format ("txid_hex")
            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                TxId::from_str(value).map_err(E::custom)
            }

            // Handle non-human-readable byte format [u8; 32]
            fn visit_bytes<E>(self, v: &[u8]) -> core::result::Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(TxId(v.try_into().map_err(|e| {
                    E::custom(format!("invalid txid bytes: {}", e))
                })?))
            }
        }

        if deserializer.is_human_readable() {
            deserializer.deserialize_str(TxIdVisitor)
        } else {
            deserializer.deserialize_bytes(TxIdVisitor)
        }
    }
}

/// 32-byte byte string (e.g. a hash, like SHA256).
#[cfg_attr(test, derive(proptest_derive::Arbitrary))]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)]
pub struct B32(pub [u8; 32]);

impl B32 {
    /// Try to create `B32` from a string of 64 hex characters.
    pub fn from_str(s: &str) -> Result<Self> {
        ensure!(s.len() == 64, "expected 64 hex characters");
        let bytes = hex::decode(s).map_err(|e| anyhow!("invalid hex: {}", e))?;
        let hash: [u8; 32] = bytes.try_into().unwrap();
        Ok(B32(hash))
    }
}

impl AsRef<[u8]> for B32 {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl fmt::Display for B32 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        hex::encode(&self.0).fmt(f)
    }
}

impl fmt::Debug for B32 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "VkHash({})", hex::encode(&self.0))
    }
}

/// Represents a data value that is guaranteed to be serialized/deserialized to/from CBOR.
#[derive(Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct Data(Value);

impl Eq for Data {}

impl Ord for Data {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0
            .partial_cmp(&other.0)
            .expect("Value comparison should have succeeded")
    }
}

impl Data {
    /// Create an empty data value.
    pub fn empty() -> Self {
        Self(Value::Null)
    }

    /// Check if the data value is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_null()
    }

    /// Try to cast to a value of a deserializable type (implementing
    /// `serde::de::DeserializeOwned`).
    pub fn value<T: DeserializeOwned>(&self) -> Result<T> {
        self.0
            .deserialized()
            .map_err(|e| anyhow!("deserialization error: {}", e))
    }

    /// Serialize to bytes.
    pub fn bytes(&self) -> Vec<u8> {
        util::write(&self).expect("serialization should have succeeded")
    }
}

impl<T> From<&T> for Data
where
    T: Serialize,
{
    fn from(value: &T) -> Self {
        Self(Value::serialized(value).expect("casting to a CBOR Value should have succeeded"))
    }
}

impl Default for Data {
    fn default() -> Self {
        Self::empty()
    }
}

impl fmt::Debug for Data {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Data({})", format!("{:?}", &self.0))
    }
}

/// Special `App.tag` value for fungible tokens. See [`App`] for more details.
pub const TOKEN: char = 't';
/// Special `App.tag` value for non-fungible tokens (NFTs). See [`App`] for more details.
pub const NFT: char = 'n';

/// Check if the provided app's token amounts are balanced in the transaction. This means that the
/// sum of the token amounts in the `tx` inputs is equal to the sum of the token amounts in the `tx`
/// outputs.
pub fn token_amounts_balanced(app: &App, tx: &Transaction) -> bool {
    match (
        sum_token_amount(app, tx.ins.values()),
        sum_token_amount(app, tx.outs.iter()),
    ) {
        (Ok(amount_in), Ok(amount_out)) => amount_in == amount_out,
        (..) => false,
    }
}

/// Check if the NFT states are preserved in the transaction. This means that the NFTs (created by
/// the provided `app`) in the `tx` inputs are the same as the NFTs in the `tx` outputs.
pub fn nft_state_preserved(app: &App, tx: &Transaction) -> bool {
    let nft_states_in = app_state_multiset(app, tx.ins.values());
    let nft_states_out = app_state_multiset(app, tx.outs.iter());

    nft_states_in == nft_states_out
}

fn app_state_multiset<'a>(
    app: &App,
    strings_of_charms: impl Iterator<Item = &'a Charms>,
) -> BTreeMap<&'a Data, usize> {
    strings_of_charms
        .filter_map(|charms| charms.get(app))
        .fold(BTreeMap::new(), |mut r, s| {
            match r.get_mut(&s) {
                Some(count) => *count += 1,
                None => {
                    r.insert(s, 1);
                }
            }
            r
        })
}

/// Sum the token amounts in the provided `strings_of_charms`.
pub fn sum_token_amount<'a>(
    app: &App,
    strings_of_charms: impl Iterator<Item = &'a Charms>,
) -> Result<u64> {
    ensure!(app.tag == TOKEN);
    strings_of_charms.fold(Ok(0u64), |amount, charms| match charms.get(app) {
        Some(state) => Ok(amount? + state.value::<u64>()?),
        None => amount,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use ciborium::Value;
    use proptest::prelude::*;
    use test_strategy::proptest;

    #[proptest]
    fn doesnt_crash(s: String) {
        let _ = TxId::from_str(&s);
    }

    #[proptest]
    fn txid_roundtrip(txid: TxId) {
        let s = txid.to_string();
        let txid2 = TxId::from_str(&s).unwrap();
        prop_assert_eq!(txid, txid2);
    }

    #[proptest]
    fn vk_serde_roundtrip(vk: B32) {
        let bytes = util::write(&vk).unwrap();
        let vk2 = util::read(bytes.as_slice()).unwrap();
        prop_assert_eq!(vk, vk2);
    }

    #[proptest]
    fn app_serde_roundtrip(app: App) {
        let bytes = util::write(&app).unwrap();
        let app2 = util::read(bytes.as_slice()).unwrap();
        prop_assert_eq!(app, app2);
    }

    #[proptest]
    fn utxo_id_serde_roundtrip(utxo_id: UtxoId) {
        let bytes = util::write(&utxo_id).unwrap();
        let utxo_id2 = util::read(bytes.as_slice()).unwrap();
        prop_assert_eq!(utxo_id, utxo_id2);
    }

    #[proptest]
    fn tx_id_serde_roundtrip(tx_id: TxId) {
        let bytes = util::write(&tx_id).unwrap();
        let tx_id2 = util::read(bytes.as_slice()).unwrap();
        prop_assert_eq!(tx_id, tx_id2);
    }

    #[test]
    fn minimal_txid() {
        let tx_id_bytes: [u8; 32] = [&[1u8], [0u8; 31].as_ref()].concat().try_into().unwrap();
        let tx_id = TxId(tx_id_bytes);
        let tx_id_str = tx_id.to_string();
        let tx_id_str_expected = "0000000000000000000000000000000000000000000000000000000000000001";
        assert_eq!(tx_id_str, tx_id_str_expected);
    }

    #[test]
    fn data_dbg() {
        let v = 42u64;
        let data: Data = Data::from(&v);
        assert_eq!(format!("{:?}", data), format!("Data({:?})", Value::from(v)));

        let data = Data::empty();
        assert_eq!(format!("{:?}", data), "Data(Null)");

        let vec1: Vec<u64> = vec![];
        let data: Data = Data::from(&vec1);
        assert_eq!(format!("{:?}", data), "Data(Array([]))");
    }

    #[test]
    fn data_bytes() {
        let v = ("42u64", 42u64);
        let data = Data::from(&v);
        let value = Value::serialized(&v).expect("serialization should have succeeded");

        let buf = util::write(&value).expect("serialization should have succeeded");

        assert_eq!(data.bytes(), buf);
    }

    #[test]
    fn dummy() {}
}