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
//! # CLVM Traits
//! This is a library for encoding and decoding Rust values using a CLVM allocator.
//! It provides implementations for every fixed-width signed and unsigned integer type,
//! as well as many other values in the standard library that would be common to encode.

#![cfg_attr(feature = "derive", doc = "\n\n")]
#![cfg_attr(feature = "derive", doc = include_str!("../docs/derive_macros.md"))]

#[cfg(feature = "derive")]
pub use clvm_derive::*;

mod clvm_decoder;
mod clvm_encoder;
mod error;
mod from_clvm;
mod int_encoding;
mod macros;
mod match_byte;
mod to_clvm;
mod wrappers;

pub use clvm_decoder::*;
pub use clvm_encoder::*;
pub use error::*;
pub use from_clvm::*;
pub use int_encoding::*;
pub use match_byte::*;
pub use to_clvm::*;
pub use wrappers::*;

pub use clvmr::Atom;

#[cfg(test)]
#[cfg(feature = "derive")]
mod derive_tests {
    extern crate self as clvm_traits;

    use super::*;

    use std::fmt::Debug;

    use clvmr::{serde::node_to_bytes, Allocator};

    fn check<T>(value: &T, expected: &str)
    where
        T: Debug + PartialEq + ToClvm<Allocator> + FromClvm<Allocator>,
    {
        let a = &mut Allocator::new();

        let ptr = value.to_clvm(a).unwrap();

        let actual = node_to_bytes(a, ptr).unwrap();
        assert_eq!(expected, hex::encode(actual));

        let round_trip = T::from_clvm(a, ptr).unwrap();
        assert_eq!(value, &round_trip);
    }

    fn coerce_into<A, B>(value: A) -> B
    where
        A: ToClvm<Allocator>,
        B: FromClvm<Allocator>,
    {
        let a = &mut Allocator::new();
        let ptr = value.to_clvm(a).unwrap();
        B::from_clvm(a, ptr).unwrap()
    }

    #[test]
    fn test_list_struct() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(list)]
        struct Struct {
            a: u64,
            b: i32,
        }

        // Includes the nil terminator.
        check(&Struct { a: 52, b: -32 }, "ff34ff81e080");
    }

    #[test]
    fn test_list_struct_with_rest() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(list)]
        struct Struct {
            a: u64,
            #[clvm(rest)]
            b: i32,
        }

        // Does not include the nil terminator.
        check(&Struct { a: 52, b: -32 }, "ff3481e0");
    }

    #[test]
    fn test_solution_struct() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(solution)]
        struct Struct {
            a: u64,
            b: i32,
        }

        // Includes the nil terminator.
        check(&Struct { a: 52, b: -32 }, "ff34ff81e080");

        // Allows additional parameters.
        let mut allocator = Allocator::new();
        let ptr = clvm_list!(100, 200, 300, 400)
            .to_clvm(&mut allocator)
            .unwrap();
        let value = Struct::from_clvm(&allocator, ptr).unwrap();
        assert_eq!(value, Struct { a: 100, b: 200 });

        // Doesn't allow differing types for the actual solution parameters.
        let mut allocator = Allocator::new();
        let ptr = clvm_list!([1, 2, 3], 200, 300)
            .to_clvm(&mut allocator)
            .unwrap();
        Struct::from_clvm(&allocator, ptr).unwrap_err();
    }

    #[test]
    fn test_solution_struct_with_rest() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(solution)]
        struct Struct {
            a: u64,
            #[clvm(rest)]
            b: i32,
        }

        // Does not include the nil terminator.
        check(&Struct { a: 52, b: -32 }, "ff3481e0");

        // Does not allow additional parameters, since it consumes the rest.
        let mut allocator = Allocator::new();
        let ptr = clvm_list!(100, 200, 300, 400)
            .to_clvm(&mut allocator)
            .unwrap();
        Struct::from_clvm(&allocator, ptr).unwrap_err();
    }

    #[test]
    fn test_curry_struct() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(curry)]
        struct Struct {
            a: u64,
            b: i32,
        }

        check(
            &Struct { a: 52, b: -32 },
            "ff04ffff0134ffff04ffff0181e0ff018080",
        );
    }

    #[test]
    fn test_curry_struct_with_rest() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(curry)]
        struct Struct {
            a: u64,
            #[clvm(rest)]
            b: i32,
        }

        check(&Struct { a: 52, b: -32 }, "ff04ffff0134ff81e080");
    }

    #[test]
    fn test_tuple_struct() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(list)]
        struct Struct(String, String);

        check(&Struct("A".to_string(), "B".to_string()), "ff41ff4280");
    }

    #[test]
    fn test_newtype_struct() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(list)]
        struct Struct(#[clvm(rest)] String);

        check(&Struct("XYZ".to_string()), "8358595a");
    }

    #[test]
    fn test_optional() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(list)]
        struct Struct {
            a: u64,
            #[clvm(default)]
            b: Option<i32>,
        }

        check(
            &Struct {
                a: 52,
                b: Some(-32),
            },
            "ff34ff81e080",
        );
        check(&Struct { a: 52, b: None }, "ff3480");
    }

    #[test]
    fn test_default() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(list)]
        struct Struct {
            a: u64,
            #[clvm(default = 42)]
            b: i32,
        }

        check(&Struct { a: 52, b: 32 }, "ff34ff2080");
        check(&Struct { a: 52, b: 42 }, "ff3480");
    }

    #[test]
    fn test_default_owned() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(list)]
        struct Struct {
            a: u64,
            #[clvm(default = "Hello".to_string())]
            b: String,
        }

        check(
            &Struct {
                a: 52,
                b: "World".to_string(),
            },
            "ff34ff85576f726c6480",
        );
        check(
            &Struct {
                a: 52,
                b: "Hello".to_string(),
            },
            "ff3480",
        );
    }

    #[test]
    fn test_constants() {
        #[derive(ToClvm, FromClvm)]
        #[apply_constants]
        #[derive(Debug, PartialEq)]
        #[clvm(list)]
        struct RunTailCondition<P, S> {
            #[clvm(constant = 51)]
            opcode: u8,
            #[clvm(constant = ())]
            blank_puzzle_hash: (),
            #[clvm(constant = -113)]
            magic_amount: i8,
            puzzle: P,
            solution: S,
        }

        check(
            &RunTailCondition {
                puzzle: "puzzle".to_string(),
                solution: "solution".to_string(),
            },
            "ff33ff80ff818fff8670757a7a6c65ff88736f6c7574696f6e80",
        );
    }

    #[test]
    fn test_enum() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(list)]
        enum Enum {
            A(i32),
            B { x: i32 },
            C,
        }

        check(&Enum::A(32), "ff80ff2080");
        check(&Enum::B { x: -72 }, "ff01ff81b880");
        check(&Enum::C, "ff0280");
    }

    #[test]
    fn test_explicit_discriminant() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(list)]
        #[repr(u8)]
        enum Enum {
            A(i32) = 42,
            B { x: i32 } = 34,
            C = 11,
        }

        check(&Enum::A(32), "ff2aff2080");
        check(&Enum::B { x: -72 }, "ff22ff81b880");
        check(&Enum::C, "ff0b80");
    }

    #[test]
    fn test_untagged_enum() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(list, untagged)]
        enum Enum {
            A(i32),
            B {
                x: i32,
                y: i32,
            },
            #[clvm(curry)]
            C {
                curried_value: String,
            },
        }

        check(&Enum::A(32), "ff2080");
        check(&Enum::B { x: -72, y: 94 }, "ff81b8ff5e80");
        check(
            &Enum::C {
                curried_value: "Hello".to_string(),
            },
            "ff04ffff018548656c6c6fff0180",
        );
    }

    #[test]
    fn test_untagged_enum_parsing_order() {
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(list, untagged)]
        enum Enum {
            // This variant is parsed first, so `B` will never be deserialized.
            A(i32),
            // When `B` is serialized, it will round trip as `A` instead.
            B(i32),
            // `C` will be deserialized as a fallback when the bytes don't deserialize to a valid `i32`.
            C(String),
        }

        // This round trips to the same value, since `A` is parsed first.
        assert_eq!(coerce_into::<Enum, Enum>(Enum::A(32)), Enum::A(32));

        // This round trips to `A` instead of `B`, since `A` is parsed first.
        assert_eq!(coerce_into::<Enum, Enum>(Enum::B(32)), Enum::A(32));

        // This round trips to `A` instead of `C`, since the bytes used to represent
        // this string are also a valid `i32` value.
        assert_eq!(
            coerce_into::<Enum, Enum>(Enum::C("Hi".into())),
            Enum::A(18537)
        );

        // This round trips to `C` instead of `A`, since the bytes used to represent
        // this string exceed the size of `i32`.
        assert_eq!(
            coerce_into::<Enum, Enum>(Enum::C("Hello, world!".into())),
            Enum::C("Hello, world!".into())
        );
    }

    #[test]
    fn test_custom_crate_name() {
        use clvm_traits as clvm_traits2;
        #[derive(Debug, ToClvm, FromClvm, PartialEq)]
        #[clvm(list, crate_name = clvm_traits2)]
        struct Struct {
            a: u64,
            b: i32,
        }

        check(&Struct { a: 52, b: -32 }, "ff34ff81e080");
    }
}