clvmr 0.19.0

Implementation of `clvm` for Chia Network's cryptocurrency
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
use crate::allocator::{Allocator, Atom, NodePtr};
use crate::chia_dialect::ClvmFlags;
use crate::cost::{Cost, check_cost};
use crate::error::EvalErr;
use crate::op_utils::{
    MALLOC_COST_PER_BYTE, atom, first, get_args, get_varargs, int_atom, mod_group_order,
    new_atom_and_cost, nilp, rest,
};
use crate::reduction::{Reduction, Response};
use chia_bls::{
    G1Element, G2Element, PublicKey, aggregate_pairing, aggregate_verify, hash_to_g1_with_dst,
    hash_to_g2_with_dst,
};

// the same cost as point_add (aka g1_add)
const BLS_G1_SUBTRACT_BASE_COST: Cost = 101094;
const BLS_G1_SUBTRACT_COST_PER_ARG: Cost = 1343980;

const BLS_G1_MULTIPLY_BASE_COST: Cost = 705500;
const BLS_G1_MULTIPLY_COST_PER_BYTE: Cost = 10;
const NEW_BLS_G1_MULTIPLY_BASE_COST: Cost = 1_900_000;
const NEW_BLS_G1_MULTIPLY_COST_PER_BYTE: Cost = 24;

// this is the same cost as XORing the top bit (minus the heap allocation of the
// return value, which the operator is adding back)
const BLS_G1_NEGATE_BASE_COST: Cost = 1396 - 480;

// g2_add and g2_subtract have the same cost
const BLS_G2_ADD_BASE_COST: Cost = 80000;
const BLS_G2_ADD_COST_PER_ARG: Cost = 1950000;
const BLS_G2_SUBTRACT_BASE_COST: Cost = 80000;
const BLS_G2_SUBTRACT_COST_PER_ARG: Cost = 1950000;

const BLS_G2_MULTIPLY_BASE_COST: Cost = 2100000;
const BLS_G2_MULTIPLY_COST_PER_BYTE: Cost = 5;
const NEW_BLS_G2_MULTIPLY_BASE_COST: Cost = 3_000_000;
const NEW_BLS_G2_MULTIPLY_COST_PER_BYTE: Cost = 23;

// this is the same cost as XORing the top bit (minus the heap allocation of the
// return value, which the operator is adding back)
const BLS_G2_NEGATE_BASE_COST: Cost = 2164 - 960;

const BLS_MAP_TO_G1_BASE_COST: Cost = 195000;
const BLS_MAP_TO_G1_COST_PER_BYTE: Cost = 4;
const BLS_MAP_TO_G1_COST_PER_DST_BYTE: Cost = 4;
const NEW_BLS_MAP_TO_G1_COST_PER_BYTE: Cost = 3;
const NEW_BLS_MAP_TO_G1_COST_PER_DST_BYTE: Cost = 2;
const NEW_BLS_MAP_TO_G1_BASE_COST: Cost = 700_000;

const BLS_MAP_TO_G2_BASE_COST: Cost = 815000;
const BLS_MAP_TO_G2_COST_PER_BYTE: Cost = 4;
const BLS_MAP_TO_G2_COST_PER_DST_BYTE: Cost = 4;
const NEW_BLS_MAP_TO_G2_COST_PER_BYTE: Cost = 3;
const NEW_BLS_MAP_TO_G2_COST_PER_DST_BYTE: Cost = 2;
const NEW_BLS_MAP_TO_G2_BASE_COST: Cost = 2_700_000;

const BLS_PAIRING_BASE_COST: Cost = 3000000;
const BLS_PAIRING_COST_PER_ARG: Cost = 1200000;
const NEW_BLS_PAIRING_BASE_COST: Cost = 1_000_000;
const NEW_BLS_PAIRING_COST_PER_ARG: Cost = 5_000_000;

const DST_G2: &[u8; 43] = b"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_AUG_";

pub fn op_bls_g1_subtract(
    a: &mut Allocator,
    mut input: NodePtr,
    max_cost: Cost,
    _flags: ClvmFlags,
) -> Response {
    let mut cost = BLS_G1_SUBTRACT_BASE_COST;
    check_cost(cost, max_cost)?;
    let mut total = G1Element::default();
    let mut is_first = true;
    while let Some((arg, rest)) = a.next(input) {
        input = rest;
        let point = a.g1(arg)?;
        cost += BLS_G1_SUBTRACT_COST_PER_ARG;
        check_cost(cost, max_cost)?;
        if is_first {
            total = point;
        } else {
            total -= &point;
        };
        is_first = false;
    }
    Ok(Reduction(
        cost + 48 * MALLOC_COST_PER_BYTE,
        a.new_g1(total)?,
    ))
}

pub fn op_bls_g1_multiply(
    a: &mut Allocator,
    input: NodePtr,
    max_cost: Cost,
    flags: ClvmFlags,
) -> Response {
    let [point, scalar] = get_args::<2>(a, input, "g1_multiply")?;

    let mut cost = if flags.contains(ClvmFlags::NEW_COST_MODEL) {
        NEW_BLS_G1_MULTIPLY_BASE_COST
    } else {
        BLS_G1_MULTIPLY_BASE_COST
    };
    check_cost(cost, max_cost)?;

    let mut total = a.g1(point)?;
    let (scalar, scalar_len) = int_atom(a, scalar, "g1_multiply")?;
    if flags.contains(ClvmFlags::LIMITS)
        && !flags.contains(ClvmFlags::NEW_COST_MODEL)
        && scalar_len > 1024
    {
        return Err(EvalErr::InvalidOpArg(input, "g1_multiply".to_string()));
    }
    let cost_per_byte = if flags.contains(ClvmFlags::NEW_COST_MODEL) {
        NEW_BLS_G1_MULTIPLY_COST_PER_BYTE
    } else {
        BLS_G1_MULTIPLY_COST_PER_BYTE
    };
    cost += scalar_len as Cost * cost_per_byte;
    check_cost(cost, max_cost)?;

    let scalar = mod_group_order(scalar);
    total.scalar_multiply(scalar.to_bytes_be().1.as_slice());

    Ok(Reduction(
        cost + 48 * MALLOC_COST_PER_BYTE,
        a.new_g1(total)?,
    ))
}

pub fn op_bls_g1_negate(
    a: &mut Allocator,
    input: NodePtr,
    _max_cost: Cost,
    flags: ClvmFlags,
) -> Response {
    let strict = !flags.contains(ClvmFlags::RELAXED_BLS);
    let [point] = get_args::<1>(a, input, "g1_negate")?;

    let mut blob: [u8; 48] = atom(a, point, "G1 atom").and_then(|blob| {
        blob.as_ref().try_into().map_err(|_| {
            EvalErr::InvalidOpArg(point, "atom is not a G1 size, 48 bytes".to_string())
        })
    })?;
    if strict {
        a.validate_g1(point, blob)?;
    }

    if (blob[0] & 0xe0) == 0xc0 {
        // This is compressed infinity. negating it is a no-op
        // we can just pass through the same atom as we received. We'll charge
        // the allocation cost anyway, for consistency
        Ok(Reduction(
            BLS_G1_NEGATE_BASE_COST + 48 * MALLOC_COST_PER_BYTE,
            point,
        ))
    } else {
        blob[0] ^= 0x20;
        if strict {
            a.add_validated_g1(blob);
        }
        new_atom_and_cost(a, BLS_G1_NEGATE_BASE_COST, &blob)
    }
}

pub fn op_bls_g2_add(
    a: &mut Allocator,
    mut input: NodePtr,
    max_cost: Cost,
    _flags: ClvmFlags,
) -> Response {
    let mut cost = BLS_G2_ADD_BASE_COST;
    check_cost(cost, max_cost)?;
    let mut total = G2Element::default();
    while let Some((arg, rest)) = a.next(input) {
        input = rest;
        let point = a.g2(arg)?;
        cost += BLS_G2_ADD_COST_PER_ARG;
        check_cost(cost, max_cost)?;
        total += &point;
    }
    Ok(Reduction(
        cost + 96 * MALLOC_COST_PER_BYTE,
        a.new_g2(total)?,
    ))
}

pub fn op_bls_g2_subtract(
    a: &mut Allocator,
    mut input: NodePtr,
    max_cost: Cost,
    _flags: ClvmFlags,
) -> Response {
    let mut cost = BLS_G2_SUBTRACT_BASE_COST;
    check_cost(cost, max_cost)?;
    let mut total = G2Element::default();
    let mut is_first = true;
    while let Some((arg, rest)) = a.next(input) {
        input = rest;
        let point = a.g2(arg)?;
        cost += BLS_G2_SUBTRACT_COST_PER_ARG;
        check_cost(cost, max_cost)?;
        if is_first {
            total = point;
        } else {
            total -= &point;
        };
        is_first = false;
    }
    Ok(Reduction(
        cost + 96 * MALLOC_COST_PER_BYTE,
        a.new_g2(total)?,
    ))
}

pub fn op_bls_g2_multiply(
    a: &mut Allocator,
    input: NodePtr,
    max_cost: Cost,
    flags: ClvmFlags,
) -> Response {
    let [point, scalar] = get_args::<2>(a, input, "g2_multiply")?;

    let mut cost = if flags.contains(ClvmFlags::NEW_COST_MODEL) {
        NEW_BLS_G2_MULTIPLY_BASE_COST
    } else {
        BLS_G2_MULTIPLY_BASE_COST
    };
    check_cost(cost, max_cost)?;

    let mut total = a.g2(point)?;
    let (scalar, scalar_len) = int_atom(a, scalar, "g2_multiply")?;
    if flags.contains(ClvmFlags::LIMITS)
        && !flags.contains(ClvmFlags::NEW_COST_MODEL)
        && scalar_len > 1024
    {
        return Err(EvalErr::InvalidOpArg(input, "g2_multiply".to_string()));
    }
    let cost_per_byte = if flags.contains(ClvmFlags::NEW_COST_MODEL) {
        NEW_BLS_G2_MULTIPLY_COST_PER_BYTE
    } else {
        BLS_G2_MULTIPLY_COST_PER_BYTE
    };
    cost += scalar_len as Cost * cost_per_byte;
    check_cost(cost, max_cost)?;

    let scalar = mod_group_order(scalar);
    total.scalar_multiply(scalar.to_bytes_be().1.as_slice());

    Ok(Reduction(
        cost + 96 * MALLOC_COST_PER_BYTE,
        a.new_g2(total)?,
    ))
}

pub fn op_bls_g2_negate(
    a: &mut Allocator,
    input: NodePtr,
    _max_cost: Cost,
    flags: ClvmFlags,
) -> Response {
    let strict = !flags.contains(ClvmFlags::RELAXED_BLS);
    let [point] = get_args::<1>(a, input, "g2_negate")?;

    let mut blob: [u8; 96] = atom(a, point, "G2 atom").and_then(|blob| {
        blob.as_ref()
            .try_into()
            .map_err(|_| EvalErr::InvalidOpArg(point, "atom is not G2 size, 96 bytes".to_string()))
    })?;
    if strict {
        a.validate_g2(point, blob)?;
    }

    if (blob[0] & 0xe0) == 0xc0 {
        // This is compressed infinity. negating it is a no-op
        // we can just pass through the same atom as we received. We'll charge
        // the allocation cost anyway, for consistency
        Ok(Reduction(
            BLS_G2_NEGATE_BASE_COST + 96 * MALLOC_COST_PER_BYTE,
            point,
        ))
    } else {
        blob[0] ^= 0x20;
        if strict {
            a.add_validated_g2(blob);
        }
        new_atom_and_cost(a, BLS_G2_NEGATE_BASE_COST, &blob)
    }
}

pub fn op_bls_map_to_g1(
    a: &mut Allocator,
    input: NodePtr,
    max_cost: Cost,
    flags: ClvmFlags,
) -> Response {
    let ([msg, dst], argc) = get_varargs::<2>(a, input, "g1_map")?;
    if !(1..=2).contains(&argc) {
        Err(EvalErr::InvalidOpArg(
            input,
            format!("g1_map takes exactly 1 or 2 arguments, got {argc}"),
        ))?;
    }
    let (mut cost, cost_per_byte, cost_per_dst_byte) = if flags.contains(ClvmFlags::NEW_COST_MODEL)
    {
        (
            NEW_BLS_MAP_TO_G1_BASE_COST,
            NEW_BLS_MAP_TO_G1_COST_PER_BYTE,
            NEW_BLS_MAP_TO_G1_COST_PER_DST_BYTE,
        )
    } else {
        (
            BLS_MAP_TO_G1_BASE_COST,
            BLS_MAP_TO_G1_COST_PER_BYTE,
            BLS_MAP_TO_G1_COST_PER_DST_BYTE,
        )
    };
    check_cost(cost, max_cost)?;

    let msg = atom(a, msg, "g1_map")?;
    cost += msg.as_ref().len() as Cost * cost_per_byte;
    check_cost(cost, max_cost)?;

    let dst = if argc == 2 {
        atom(a, dst, "g1_map")?
    } else {
        Atom::Borrowed(b"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_AUG_".as_slice())
    };

    cost += dst.as_ref().len() as Cost * cost_per_dst_byte;
    check_cost(cost, max_cost)?;

    let point = hash_to_g1_with_dst(msg.as_ref(), dst.as_ref());
    Ok(Reduction(
        cost + 48 * MALLOC_COST_PER_BYTE,
        a.new_g1(point)?,
    ))
}

pub fn op_bls_map_to_g2(
    a: &mut Allocator,
    input: NodePtr,
    max_cost: Cost,
    flags: ClvmFlags,
) -> Response {
    let ([msg, dst], argc) = get_varargs::<2>(a, input, "g2_map")?;
    if !(1..=2).contains(&argc) {
        Err(EvalErr::InvalidOpArg(
            input,
            format!("g2_map takes exactly 1 or 2 arguments, got {argc}"),
        ))?;
    }
    let (mut cost, cost_per_byte, cost_per_dst_byte) = if flags.contains(ClvmFlags::NEW_COST_MODEL)
    {
        (
            NEW_BLS_MAP_TO_G2_BASE_COST,
            NEW_BLS_MAP_TO_G2_COST_PER_BYTE,
            NEW_BLS_MAP_TO_G2_COST_PER_DST_BYTE,
        )
    } else {
        (
            BLS_MAP_TO_G2_BASE_COST,
            BLS_MAP_TO_G2_COST_PER_BYTE,
            BLS_MAP_TO_G2_COST_PER_DST_BYTE,
        )
    };
    check_cost(cost, max_cost)?;

    let msg = atom(a, msg, "g2_map")?;
    cost += msg.as_ref().len() as Cost * cost_per_byte;

    let dst = if argc == 2 {
        atom(a, dst, "g2_map")?
    } else {
        Atom::Borrowed(DST_G2.as_slice())
    };

    cost += dst.as_ref().len() as Cost * cost_per_dst_byte;
    check_cost(cost, max_cost)?;

    let point = hash_to_g2_with_dst(msg.as_ref(), dst.as_ref());
    Ok(Reduction(
        cost + 96 * MALLOC_COST_PER_BYTE,
        a.new_g2(point)?,
    ))
}

// This operator takes a variable number of G1 and G2 points. The points must
// come in pairs (as a "flat" argument list).
// It performs a low-level pairing operation of the (G1, G2)-pairs
// and returns if the resulting Gt point is the
// identity, otherwise terminates the program with a validation error.
pub fn op_bls_pairing_identity(
    a: &mut Allocator,
    input: NodePtr,
    max_cost: Cost,
    flags: ClvmFlags,
) -> Response {
    let (mut cost, cost_per_arg) = if flags.contains(ClvmFlags::NEW_COST_MODEL) {
        (NEW_BLS_PAIRING_BASE_COST, NEW_BLS_PAIRING_COST_PER_ARG)
    } else {
        (BLS_PAIRING_BASE_COST, BLS_PAIRING_COST_PER_ARG)
    };
    check_cost(cost, max_cost)?;
    let mut items = Vec::<(G1Element, G2Element)>::new();

    let mut args = input;
    while !nilp(a, args) {
        cost += cost_per_arg;
        check_cost(cost, max_cost)?;
        let g1 = a.g1(first(a, args)?)?;
        args = rest(a, args)?;
        let g2 = a.g2(first(a, args)?)?;
        args = rest(a, args)?;
        items.push((g1, g2));
    }

    if !aggregate_pairing(items) {
        Err(EvalErr::BLSPairingIdentityFailed(input))?
    } else {
        Ok(Reduction(cost, a.nil()))
    }
}

// expects: G2 G1 msg G1 msg ...
// G2 is the signature
// G1 is a public key
// the G1 and its corresponding message must be passed in pairs.
pub fn op_bls_verify(
    a: &mut Allocator,
    input: NodePtr,
    max_cost: Cost,
    flags: ClvmFlags,
) -> Response {
    let (mut cost, cost_per_arg, cost_per_byte, cost_per_dst_byte) =
        if flags.contains(ClvmFlags::NEW_COST_MODEL) {
            (
                NEW_BLS_PAIRING_BASE_COST,
                NEW_BLS_PAIRING_COST_PER_ARG,
                NEW_BLS_MAP_TO_G2_COST_PER_BYTE,
                NEW_BLS_MAP_TO_G2_COST_PER_DST_BYTE,
            )
        } else {
            (
                BLS_PAIRING_BASE_COST,
                BLS_PAIRING_COST_PER_ARG,
                BLS_MAP_TO_G2_COST_PER_BYTE,
                BLS_MAP_TO_G2_COST_PER_DST_BYTE,
            )
        };
    check_cost(cost, max_cost)?;

    let mut args = input;

    // the first argument is the signature
    let signature = a.g2(first(a, args)?)?;

    // followed by a variable number of (G1, msg)-pairs (as a flat list)
    args = rest(a, args)?;

    let mut items = Vec::<(PublicKey, Atom)>::new();
    while !nilp(a, args) {
        let pk = a.g1(first(a, args)?)?;
        args = rest(a, args)?;
        let msg = atom(a, first(a, args)?, "bls_verify message")?;
        args = rest(a, args)?;

        cost += cost_per_arg;
        cost += msg.as_ref().len() as Cost * cost_per_byte;
        cost += DST_G2.len() as Cost * cost_per_dst_byte;
        check_cost(cost, max_cost)?;

        items.push((pk, msg));
    }

    if !aggregate_verify(&signature, items) {
        Err(EvalErr::BLSVerifyFailed(input))?
    } else {
        Ok(Reduction(cost, a.nil()))
    }
}