Skip to main content

sui_move_natives_latest/crypto/
group_ops.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3use crate::object_runtime::ObjectRuntime;
4use crate::{NativesCostTable, get_extension};
5use fastcrypto::error::{FastCryptoError, FastCryptoResult};
6use fastcrypto::groups::{
7    FromTrustedByteArray, GroupElement, HashToGroupElement, MultiScalarMul, Pairing,
8    bls12381 as bls, ristretto255 as ristretto,
9};
10use fastcrypto::serde_helpers::ToFromByteArray;
11use move_binary_format::errors::PartialVMResult;
12use move_binary_format::partial_vm_error;
13use move_binary_format::{safe_assert, safe_assert_eq, safe_unwrap};
14use move_core_types::gas_algebra::InternalGas;
15use move_vm_runtime::native_charge_gas_early_exit;
16use move_vm_runtime::natives::functions::NativeContext;
17use move_vm_runtime::{
18    execution::{
19        Type,
20        values::{Value, VectorRef},
21    },
22    natives::functions::NativeResult,
23    pop_arg,
24};
25use smallvec::smallvec;
26use std::collections::VecDeque;
27
28pub const NOT_SUPPORTED_ERROR: u64 = 0;
29pub const INVALID_INPUT_ERROR: u64 = 1;
30pub const INPUT_TOO_LONG_ERROR: u64 = 2;
31
32fn is_msm_supported(context: &NativeContext) -> PartialVMResult<bool> {
33    Ok(get_extension!(context, ObjectRuntime)?
34        .protocol_config
35        .enable_group_ops_native_function_msm())
36}
37
38fn is_ristretto_supported(context: &NativeContext) -> PartialVMResult<bool> {
39    Ok(get_extension!(context, ObjectRuntime)?
40        .protocol_config
41        .enable_ristretto255_group_ops())
42}
43
44fn map_op_result(
45    context: &NativeContext,
46    result: FastCryptoResult<Vec<u8>>,
47) -> PartialVMResult<NativeResult> {
48    match result {
49        Ok(bytes) => Ok(NativeResult::ok(
50            context.gas_used(),
51            smallvec![Value::vector_u8(bytes)],
52        )),
53        // Since all Element<G> are validated on construction, this error should never happen unless the requested type is wrong or inputs are invalid.
54        Err(_) => Ok(NativeResult::err(context.gas_used(), INVALID_INPUT_ERROR)),
55    }
56}
57
58// Gas related structs and functions.
59
60#[derive(Clone)]
61pub struct GroupOpsCostParams {
62    // costs for decode and validate
63    pub bls12381_decode_scalar_cost: Option<InternalGas>,
64    pub bls12381_decode_g1_cost: Option<InternalGas>,
65    pub bls12381_decode_g2_cost: Option<InternalGas>,
66    pub bls12381_decode_gt_cost: Option<InternalGas>,
67    // costs for decode, add, and encode output
68    pub bls12381_scalar_add_cost: Option<InternalGas>,
69    pub bls12381_g1_add_cost: Option<InternalGas>,
70    pub bls12381_g2_add_cost: Option<InternalGas>,
71    pub bls12381_gt_add_cost: Option<InternalGas>,
72    // costs for decode, sub, and encode output
73    pub bls12381_scalar_sub_cost: Option<InternalGas>,
74    pub bls12381_g1_sub_cost: Option<InternalGas>,
75    pub bls12381_g2_sub_cost: Option<InternalGas>,
76    pub bls12381_gt_sub_cost: Option<InternalGas>,
77    // costs for decode, mul, and encode output
78    pub bls12381_scalar_mul_cost: Option<InternalGas>,
79    pub bls12381_g1_mul_cost: Option<InternalGas>,
80    pub bls12381_g2_mul_cost: Option<InternalGas>,
81    pub bls12381_gt_mul_cost: Option<InternalGas>,
82    // costs for decode, div, and encode output
83    pub bls12381_scalar_div_cost: Option<InternalGas>,
84    pub bls12381_g1_div_cost: Option<InternalGas>,
85    pub bls12381_g2_div_cost: Option<InternalGas>,
86    pub bls12381_gt_div_cost: Option<InternalGas>,
87    // costs for hashing
88    pub bls12381_g1_hash_to_base_cost: Option<InternalGas>,
89    pub bls12381_g2_hash_to_base_cost: Option<InternalGas>,
90    pub bls12381_g1_hash_to_cost_per_byte: Option<InternalGas>,
91    pub bls12381_g2_hash_to_cost_per_byte: Option<InternalGas>,
92    // costs for encoding the output + base cost for MSM (the |q| doublings) but not decoding
93    pub bls12381_g1_msm_base_cost: Option<InternalGas>,
94    pub bls12381_g2_msm_base_cost: Option<InternalGas>,
95    // cost that is multiplied with the approximated number of additions
96    pub bls12381_g1_msm_base_cost_per_input: Option<InternalGas>,
97    pub bls12381_g2_msm_base_cost_per_input: Option<InternalGas>,
98    // limit the length of the input vectors for MSM
99    pub bls12381_msm_max_len: Option<u32>,
100    // costs for decode, pairing, and encode output
101    pub bls12381_pairing_cost: Option<InternalGas>,
102    // costs for conversion to and from uncompressed form
103    pub bls12381_g1_to_uncompressed_g1_cost: Option<InternalGas>,
104    pub bls12381_uncompressed_g1_to_g1_cost: Option<InternalGas>,
105    // costs for sum of elements uncompressed form
106    pub bls12381_uncompressed_g1_sum_base_cost: Option<InternalGas>,
107    pub bls12381_uncompressed_g1_sum_cost_per_term: Option<InternalGas>,
108    // limit the number of terms in a sum
109    pub bls12381_uncompressed_g1_sum_max_terms: Option<u64>,
110    pub ristretto_decode_scalar_cost: Option<InternalGas>,
111    pub ristretto_decode_point_cost: Option<InternalGas>,
112    // costs for decode, add, and encode output
113    pub ristretto_scalar_add_cost: Option<InternalGas>,
114    pub ristretto_point_add_cost: Option<InternalGas>,
115    // costs for decode, sub, and encode output
116    pub ristretto_scalar_sub_cost: Option<InternalGas>,
117    pub ristretto_point_sub_cost: Option<InternalGas>,
118    // costs for decode, mul, and encode output
119    pub ristretto_scalar_mul_cost: Option<InternalGas>,
120    pub ristretto_point_mul_cost: Option<InternalGas>,
121    // costs for decode, div, and encode output
122    pub ristretto_scalar_div_cost: Option<InternalGas>,
123    pub ristretto_point_div_cost: Option<InternalGas>,
124}
125
126macro_rules! native_charge_gas_early_exit_option {
127    ($native_context:ident, $cost:expr) => {{
128        native_charge_gas_early_exit!(
129            $native_context,
130            $cost.ok_or_else(|| {
131                partial_vm_error!(
132                    UNKNOWN_INVARIANT_VIOLATION_ERROR,
133                    "Gas cost for group ops is missing"
134                )
135            })?
136        );
137    }};
138}
139
140// Next should be aligned with the related Move modules.
141#[repr(u8)]
142enum Groups {
143    BLS12381Scalar = 0,
144    BLS12381G1 = 1,
145    BLS12381G2 = 2,
146    BLS12381GT = 3,
147    BLS12381UncompressedG1 = 4,
148    RistrettoScalar = 5,
149    RistrettoPoint = 6,
150}
151
152impl Groups {
153    fn from_u8(value: u8) -> Option<Self> {
154        match value {
155            0 => Some(Groups::BLS12381Scalar),
156            1 => Some(Groups::BLS12381G1),
157            2 => Some(Groups::BLS12381G2),
158            3 => Some(Groups::BLS12381GT),
159            4 => Some(Groups::BLS12381UncompressedG1),
160            5 => Some(Groups::RistrettoScalar),
161            6 => Some(Groups::RistrettoPoint),
162            _ => None,
163        }
164    }
165}
166
167fn parse_untrusted<G: ToFromByteArray<S> + FromTrustedByteArray<S>, const S: usize>(
168    e: &[u8],
169) -> FastCryptoResult<G> {
170    G::from_byte_array(e.try_into().map_err(|_| FastCryptoError::InvalidInput)?)
171}
172
173fn parse_trusted<G: ToFromByteArray<S> + FromTrustedByteArray<S>, const S: usize>(
174    e: &[u8],
175) -> FastCryptoResult<G> {
176    G::from_trusted_byte_array(e.try_into().map_err(|_| FastCryptoError::InvalidInput)?)
177}
178
179// Binary operations with 2 different types.
180fn binary_op_diff<
181    G1: ToFromByteArray<S1> + FromTrustedByteArray<S1>,
182    G2: ToFromByteArray<S2> + FromTrustedByteArray<S2>,
183    const S1: usize,
184    const S2: usize,
185>(
186    op: impl Fn(G1, G2) -> FastCryptoResult<G2>,
187    a1: &[u8],
188    a2: &[u8],
189) -> FastCryptoResult<Vec<u8>> {
190    let e1 = parse_trusted::<G1, S1>(a1)?;
191    let e2 = parse_trusted::<G2, S2>(a2)?;
192    let result = op(e1, e2)?;
193    Ok(result.to_byte_array().to_vec())
194}
195
196// Binary operations with the same type.
197fn binary_op<G: ToFromByteArray<S> + FromTrustedByteArray<S>, const S: usize>(
198    op: impl Fn(G, G) -> FastCryptoResult<G>,
199    a1: &[u8],
200    a2: &[u8],
201) -> FastCryptoResult<Vec<u8>> {
202    binary_op_diff::<G, G, S, S>(op, a1, a2)
203}
204
205// TODO: Since in many cases more than one group operation will be performed in a single
206// transaction, it might be worth caching the affine representation of the group elements and use
207// them to save conversions.
208
209/***************************************************************************************************
210 * native fun internal_validate
211 * Implementation of the Move native function `internal_validate(type: u8, bytes: &vector<u8>): bool`
212 *   gas cost: group_ops_decode_bls12381_X_cost where X is the requested type
213 **************************************************************************************************/
214
215pub fn internal_validate(
216    context: &mut NativeContext,
217    ty_args: Vec<Type>,
218    mut args: VecDeque<Value>,
219) -> PartialVMResult<NativeResult> {
220    safe_assert!(ty_args.is_empty());
221    safe_assert_eq!(args.len(), 2);
222
223    let cost = context.gas_used();
224    let bytes_ref = pop_arg!(args, VectorRef);
225    let bytes = bytes_ref.as_bytes_ref()?;
226    let group_type = pop_arg!(args, u8);
227
228    let cost_params = get_extension!(context, NativesCostTable)?
229        .group_ops_cost_params
230        .clone();
231
232    let result = match Groups::from_u8(group_type) {
233        Some(Groups::BLS12381Scalar) => {
234            native_charge_gas_early_exit_option!(context, cost_params.bls12381_decode_scalar_cost);
235            parse_untrusted::<bls::Scalar, { bls::Scalar::BYTE_LENGTH }>(&bytes).is_ok()
236        }
237        Some(Groups::BLS12381G1) => {
238            native_charge_gas_early_exit_option!(context, cost_params.bls12381_decode_g1_cost);
239            parse_untrusted::<bls::G1Element, { bls::G1Element::BYTE_LENGTH }>(&bytes).is_ok()
240        }
241        Some(Groups::BLS12381G2) => {
242            native_charge_gas_early_exit_option!(context, cost_params.bls12381_decode_g2_cost);
243            parse_untrusted::<bls::G2Element, { bls::G2Element::BYTE_LENGTH }>(&bytes).is_ok()
244        }
245        Some(Groups::RistrettoScalar) => {
246            if !is_ristretto_supported(context)? {
247                return Ok(NativeResult::err(cost, NOT_SUPPORTED_ERROR));
248            }
249            native_charge_gas_early_exit_option!(context, cost_params.ristretto_decode_scalar_cost);
250            parse_untrusted::<ristretto::RistrettoScalar, { ristretto::RISTRETTO_SCALAR_BYTE_LENGTH }>(&bytes).is_ok()
251        }
252        Some(Groups::RistrettoPoint) => {
253            if !is_ristretto_supported(context)? {
254                return Ok(NativeResult::err(cost, NOT_SUPPORTED_ERROR));
255            }
256            native_charge_gas_early_exit_option!(context, cost_params.ristretto_decode_point_cost);
257            parse_untrusted::<ristretto::RistrettoPoint, { ristretto::RISTRETTO_POINT_BYTE_LENGTH }>(&bytes).is_ok()
258        }
259        _ => false,
260    };
261
262    Ok(NativeResult::ok(
263        context.gas_used(),
264        smallvec![Value::bool(result)],
265    ))
266}
267
268/***************************************************************************************************
269 * native fun internal_add
270 * Implementation of the Move native function `internal_add(type: u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>`
271 *   gas cost: group_ops_bls12381_X_add_cost where X is the requested type
272 **************************************************************************************************/
273pub fn internal_add(
274    context: &mut NativeContext,
275    ty_args: Vec<Type>,
276    mut args: VecDeque<Value>,
277) -> PartialVMResult<NativeResult> {
278    safe_assert!(ty_args.is_empty());
279    safe_assert_eq!(args.len(), 3);
280
281    let cost = context.gas_used();
282    let e2_ref = pop_arg!(args, VectorRef);
283    let e2 = e2_ref.as_bytes_ref()?;
284    let e1_ref = pop_arg!(args, VectorRef);
285    let e1 = e1_ref.as_bytes_ref()?;
286    let group_type = pop_arg!(args, u8);
287
288    let cost_params = get_extension!(context, NativesCostTable)?
289        .group_ops_cost_params
290        .clone();
291
292    let result = match Groups::from_u8(group_type) {
293        Some(Groups::BLS12381Scalar) => {
294            native_charge_gas_early_exit_option!(context, cost_params.bls12381_scalar_add_cost);
295            binary_op::<bls::Scalar, { bls::Scalar::BYTE_LENGTH }>(|a, b| Ok(a + b), &e1, &e2)
296        }
297        Some(Groups::BLS12381G1) => {
298            native_charge_gas_early_exit_option!(context, cost_params.bls12381_g1_add_cost);
299            binary_op::<bls::G1Element, { bls::G1Element::BYTE_LENGTH }>(|a, b| Ok(a + b), &e1, &e2)
300        }
301        Some(Groups::BLS12381G2) => {
302            native_charge_gas_early_exit_option!(context, cost_params.bls12381_g2_add_cost);
303            binary_op::<bls::G2Element, { bls::G2Element::BYTE_LENGTH }>(|a, b| Ok(a + b), &e1, &e2)
304        }
305        Some(Groups::BLS12381GT) => {
306            native_charge_gas_early_exit_option!(context, cost_params.bls12381_gt_add_cost);
307            binary_op::<bls::GTElement, { bls::GTElement::BYTE_LENGTH }>(|a, b| Ok(a + b), &e1, &e2)
308        }
309        Some(Groups::RistrettoScalar) => {
310            if !is_ristretto_supported(context)? {
311                return Ok(NativeResult::err(cost, NOT_SUPPORTED_ERROR));
312            }
313            native_charge_gas_early_exit_option!(context, cost_params.ristretto_scalar_add_cost);
314            binary_op::<ristretto::RistrettoScalar, { ristretto::RISTRETTO_SCALAR_BYTE_LENGTH }>(
315                |a, b| Ok(a + b),
316                &e1,
317                &e2,
318            )
319        }
320        Some(Groups::RistrettoPoint) => {
321            if !is_ristretto_supported(context)? {
322                return Ok(NativeResult::err(cost, NOT_SUPPORTED_ERROR));
323            }
324            native_charge_gas_early_exit_option!(context, cost_params.ristretto_point_add_cost);
325            binary_op::<ristretto::RistrettoPoint, { ristretto::RISTRETTO_POINT_BYTE_LENGTH }>(
326                |a, b| Ok(a + b),
327                &e1,
328                &e2,
329            )
330        }
331        _ => Err(FastCryptoError::InvalidInput),
332    };
333
334    map_op_result(context, result)
335}
336
337/***************************************************************************************************
338 * native fun internal_sub
339 * Implementation of the Move native function `internal_sub(type: u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>`
340 *   gas cost: group_ops_bls12381_X_sub_cost where X is the requested type
341 **************************************************************************************************/
342pub fn internal_sub(
343    context: &mut NativeContext,
344    ty_args: Vec<Type>,
345    mut args: VecDeque<Value>,
346) -> PartialVMResult<NativeResult> {
347    safe_assert!(ty_args.is_empty());
348    safe_assert_eq!(args.len(), 3);
349
350    let cost = context.gas_used();
351    let e2_ref = pop_arg!(args, VectorRef);
352    let e2 = e2_ref.as_bytes_ref()?;
353    let e1_ref = pop_arg!(args, VectorRef);
354    let e1 = e1_ref.as_bytes_ref()?;
355    let group_type = pop_arg!(args, u8);
356
357    let cost_params = get_extension!(context, NativesCostTable)?
358        .group_ops_cost_params
359        .clone();
360
361    let result = match Groups::from_u8(group_type) {
362        Some(Groups::BLS12381Scalar) => {
363            native_charge_gas_early_exit_option!(context, cost_params.bls12381_scalar_sub_cost);
364            binary_op::<bls::Scalar, { bls::Scalar::BYTE_LENGTH }>(|a, b| Ok(a - b), &e1, &e2)
365        }
366        Some(Groups::BLS12381G1) => {
367            native_charge_gas_early_exit_option!(context, cost_params.bls12381_g1_sub_cost);
368            binary_op::<bls::G1Element, { bls::G1Element::BYTE_LENGTH }>(|a, b| Ok(a - b), &e1, &e2)
369        }
370        Some(Groups::BLS12381G2) => {
371            native_charge_gas_early_exit_option!(context, cost_params.bls12381_g2_sub_cost);
372            binary_op::<bls::G2Element, { bls::G2Element::BYTE_LENGTH }>(|a, b| Ok(a - b), &e1, &e2)
373        }
374        Some(Groups::BLS12381GT) => {
375            native_charge_gas_early_exit_option!(context, cost_params.bls12381_gt_sub_cost);
376            binary_op::<bls::GTElement, { bls::GTElement::BYTE_LENGTH }>(|a, b| Ok(a - b), &e1, &e2)
377        }
378        Some(Groups::RistrettoScalar) => {
379            if !is_ristretto_supported(context)? {
380                return Ok(NativeResult::err(cost, NOT_SUPPORTED_ERROR));
381            }
382            native_charge_gas_early_exit_option!(context, cost_params.ristretto_scalar_sub_cost);
383            binary_op::<ristretto::RistrettoScalar, { ristretto::RISTRETTO_SCALAR_BYTE_LENGTH }>(
384                |a, b| Ok(a - b),
385                &e1,
386                &e2,
387            )
388        }
389        Some(Groups::RistrettoPoint) => {
390            if !is_ristretto_supported(context)? {
391                return Ok(NativeResult::err(cost, NOT_SUPPORTED_ERROR));
392            }
393            native_charge_gas_early_exit_option!(context, cost_params.ristretto_point_sub_cost);
394            binary_op::<ristretto::RistrettoPoint, { ristretto::RISTRETTO_POINT_BYTE_LENGTH }>(
395                |a, b| Ok(a - b),
396                &e1,
397                &e2,
398            )
399        }
400        _ => Err(FastCryptoError::InvalidInput),
401    };
402
403    map_op_result(context, result)
404}
405
406/***************************************************************************************************
407 * native fun internal_mul
408 * Implementation of the Move native function `internal_mul(type: u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>`
409 *   gas cost: group_ops_bls12381_X_mul_cost where X is the requested type
410 **************************************************************************************************/
411pub fn internal_mul(
412    context: &mut NativeContext,
413    ty_args: Vec<Type>,
414    mut args: VecDeque<Value>,
415) -> PartialVMResult<NativeResult> {
416    safe_assert!(ty_args.is_empty());
417    safe_assert_eq!(args.len(), 3);
418
419    let cost = context.gas_used();
420    let e2_ref = pop_arg!(args, VectorRef);
421    let e2 = e2_ref.as_bytes_ref()?;
422    let e1_ref = pop_arg!(args, VectorRef);
423    let e1 = e1_ref.as_bytes_ref()?;
424    let group_type = pop_arg!(args, u8);
425
426    let cost_params = get_extension!(context, NativesCostTable)?
427        .group_ops_cost_params
428        .clone();
429
430    let result = match Groups::from_u8(group_type) {
431        Some(Groups::BLS12381Scalar) => {
432            native_charge_gas_early_exit_option!(context, cost_params.bls12381_scalar_mul_cost);
433            binary_op::<bls::Scalar, { bls::Scalar::BYTE_LENGTH }>(|a, b| Ok(b * a), &e1, &e2)
434        }
435        Some(Groups::BLS12381G1) => {
436            native_charge_gas_early_exit_option!(context, cost_params.bls12381_g1_mul_cost);
437            binary_op_diff::<
438                bls::Scalar,
439                bls::G1Element,
440                { bls::Scalar::BYTE_LENGTH },
441                { bls::G1Element::BYTE_LENGTH },
442            >(|a, b| Ok(b * a), &e1, &e2)
443        }
444        Some(Groups::BLS12381G2) => {
445            native_charge_gas_early_exit_option!(context, cost_params.bls12381_g2_mul_cost);
446            binary_op_diff::<
447                bls::Scalar,
448                bls::G2Element,
449                { bls::Scalar::BYTE_LENGTH },
450                { bls::G2Element::BYTE_LENGTH },
451            >(|a, b| Ok(b * a), &e1, &e2)
452        }
453        Some(Groups::BLS12381GT) => {
454            native_charge_gas_early_exit_option!(context, cost_params.bls12381_gt_mul_cost);
455            binary_op_diff::<
456                bls::Scalar,
457                bls::GTElement,
458                { bls::Scalar::BYTE_LENGTH },
459                { bls::GTElement::BYTE_LENGTH },
460            >(|a, b| Ok(b * a), &e1, &e2)
461        }
462        Some(Groups::RistrettoScalar) => {
463            if !is_ristretto_supported(context)? {
464                return Ok(NativeResult::err(cost, NOT_SUPPORTED_ERROR));
465            }
466            native_charge_gas_early_exit_option!(context, cost_params.ristretto_scalar_mul_cost);
467            binary_op::<ristretto::RistrettoScalar, { ristretto::RISTRETTO_SCALAR_BYTE_LENGTH }>(
468                |a, b| Ok(b * a),
469                &e1,
470                &e2,
471            )
472        }
473        Some(Groups::RistrettoPoint) => {
474            if !is_ristretto_supported(context)? {
475                return Ok(NativeResult::err(cost, NOT_SUPPORTED_ERROR));
476            }
477            native_charge_gas_early_exit_option!(context, cost_params.ristretto_point_mul_cost);
478            binary_op_diff::<
479                ristretto::RistrettoScalar,
480                ristretto::RistrettoPoint,
481                { ristretto::RISTRETTO_SCALAR_BYTE_LENGTH },
482                { ristretto::RISTRETTO_POINT_BYTE_LENGTH },
483            >(|a, b| Ok(b * a), &e1, &e2)
484        }
485        _ => Err(FastCryptoError::InvalidInput),
486    };
487
488    map_op_result(context, result)
489}
490
491/***************************************************************************************************
492 * native fun internal_div
493 * Implementation of the Move native function `internal_div(type: u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>`
494 *   gas cost: group_ops_bls12381_X_div_cost where X is the requested type
495 **************************************************************************************************/
496pub fn internal_div(
497    context: &mut NativeContext,
498    ty_args: Vec<Type>,
499    mut args: VecDeque<Value>,
500) -> PartialVMResult<NativeResult> {
501    safe_assert!(ty_args.is_empty());
502    safe_assert_eq!(args.len(), 3);
503
504    let cost = context.gas_used();
505    let e2_ref = pop_arg!(args, VectorRef);
506    let e2 = e2_ref.as_bytes_ref()?;
507    let e1_ref = pop_arg!(args, VectorRef);
508    let e1 = e1_ref.as_bytes_ref()?;
509    let group_type = pop_arg!(args, u8);
510
511    let cost_params = get_extension!(context, NativesCostTable)?
512        .group_ops_cost_params
513        .clone();
514
515    let result = match Groups::from_u8(group_type) {
516        Some(Groups::BLS12381Scalar) => {
517            native_charge_gas_early_exit_option!(context, cost_params.bls12381_scalar_div_cost);
518            binary_op::<bls::Scalar, { bls::Scalar::BYTE_LENGTH }>(|a, b| b / a, &e1, &e2)
519        }
520        Some(Groups::BLS12381G1) => {
521            native_charge_gas_early_exit_option!(context, cost_params.bls12381_g1_div_cost);
522            binary_op_diff::<
523                bls::Scalar,
524                bls::G1Element,
525                { bls::Scalar::BYTE_LENGTH },
526                { bls::G1Element::BYTE_LENGTH },
527            >(|a, b| b / a, &e1, &e2)
528        }
529        Some(Groups::BLS12381G2) => {
530            native_charge_gas_early_exit_option!(context, cost_params.bls12381_g2_div_cost);
531            binary_op_diff::<
532                bls::Scalar,
533                bls::G2Element,
534                { bls::Scalar::BYTE_LENGTH },
535                { bls::G2Element::BYTE_LENGTH },
536            >(|a, b| b / a, &e1, &e2)
537        }
538        Some(Groups::BLS12381GT) => {
539            native_charge_gas_early_exit_option!(context, cost_params.bls12381_gt_div_cost);
540            binary_op_diff::<
541                bls::Scalar,
542                bls::GTElement,
543                { bls::Scalar::BYTE_LENGTH },
544                { bls::GTElement::BYTE_LENGTH },
545            >(|a, b| b / a, &e1, &e2)
546        }
547        Some(Groups::RistrettoScalar) => {
548            if !is_ristretto_supported(context)? {
549                return Ok(NativeResult::err(cost, NOT_SUPPORTED_ERROR));
550            }
551            native_charge_gas_early_exit_option!(context, cost_params.ristretto_scalar_div_cost);
552            binary_op::<ristretto::RistrettoScalar, { ristretto::RISTRETTO_SCALAR_BYTE_LENGTH }>(
553                |a, b| b / a,
554                &e1,
555                &e2,
556            )
557        }
558        Some(Groups::RistrettoPoint) => {
559            if !is_ristretto_supported(context)? {
560                return Ok(NativeResult::err(cost, NOT_SUPPORTED_ERROR));
561            }
562            native_charge_gas_early_exit_option!(context, cost_params.ristretto_point_div_cost);
563            binary_op_diff::<
564                ristretto::RistrettoScalar,
565                ristretto::RistrettoPoint,
566                { ristretto::RISTRETTO_SCALAR_BYTE_LENGTH },
567                { ristretto::RISTRETTO_POINT_BYTE_LENGTH },
568            >(|a, b| b / a, &e1, &e2)
569        }
570        _ => Err(FastCryptoError::InvalidInput),
571    };
572
573    map_op_result(context, result)
574}
575
576/***************************************************************************************************
577 * native fun internal_hash_to
578 * Implementation of the Move native function `internal_hash_to(type: u8, m: &vector<u8>): vector<u8>`
579 *   gas cost: group_ops_bls12381_X_hash_to_base_cost + group_ops_bls12381_X_hash_to_cost_per_byte * |input|
580 *             where X is the requested type
581 **************************************************************************************************/
582pub fn internal_hash_to(
583    context: &mut NativeContext,
584    ty_args: Vec<Type>,
585    mut args: VecDeque<Value>,
586) -> PartialVMResult<NativeResult> {
587    safe_assert!(ty_args.is_empty());
588    safe_assert_eq!(args.len(), 2);
589
590    let cost = context.gas_used();
591    let m_ref = pop_arg!(args, VectorRef);
592    let m = m_ref.as_bytes_ref()?;
593    let group_type = pop_arg!(args, u8);
594
595    if m.is_empty() {
596        return Ok(NativeResult::err(cost, INVALID_INPUT_ERROR));
597    }
598
599    let cost_params = get_extension!(context, NativesCostTable)?
600        .group_ops_cost_params
601        .clone();
602
603    let result = match Groups::from_u8(group_type) {
604        Some(Groups::BLS12381G1) => {
605            native_charge_gas_early_exit_option!(
606                context,
607                cost_params
608                    .bls12381_g1_hash_to_base_cost
609                    .and_then(|base_cost| cost_params
610                        .bls12381_g1_hash_to_cost_per_byte
611                        .map(|per_byte| base_cost + per_byte.saturating_mul(m.len() as u64)))
612            );
613            Ok(bls::G1Element::hash_to_group_element(&m)
614                .to_byte_array()
615                .to_vec())
616        }
617        Some(Groups::BLS12381G2) => {
618            native_charge_gas_early_exit_option!(
619                context,
620                cost_params
621                    .bls12381_g2_hash_to_base_cost
622                    .and_then(|base_cost| cost_params
623                        .bls12381_g2_hash_to_cost_per_byte
624                        .map(|per_byte| base_cost + per_byte.saturating_mul(m.len() as u64)))
625            );
626            Ok(bls::G2Element::hash_to_group_element(&m)
627                .to_byte_array()
628                .to_vec())
629        }
630        _ => Err(FastCryptoError::InvalidInput),
631    };
632
633    map_op_result(context, result)
634}
635
636// Based on calculation from https://github.com/supranational/blst/blob/master/src/multi_scalar.c#L270
637fn msm_num_of_additions(n: u64) -> u64 {
638    debug_assert!(n > 0);
639    let wbits = (64 - n.leading_zeros() - 1) as u64;
640    let window_size = match wbits {
641        0 => 1,
642        1..=4 => 2,
643        5..=12 => wbits - 2,
644        _ => wbits - 3,
645    };
646    let num_of_windows = 255 / window_size + if 255 % window_size == 0 { 0 } else { 1 };
647    num_of_windows * (n + (1 << window_size) + 1)
648}
649
650#[test]
651fn test_msm_factor() {
652    assert_eq!(msm_num_of_additions(1), 1020);
653    assert_eq!(msm_num_of_additions(2), 896);
654    assert_eq!(msm_num_of_additions(3), 1024);
655    assert_eq!(msm_num_of_additions(4), 1152);
656    assert_eq!(msm_num_of_additions(32), 3485);
657}
658
659fn multi_scalar_mul<G, const SCALAR_SIZE: usize, const POINT_SIZE: usize>(
660    context: &mut NativeContext,
661    scalar_decode_cost: Option<InternalGas>,
662    point_decode_cost: Option<InternalGas>,
663    base_cost: Option<InternalGas>,
664    base_cost_per_addition: Option<InternalGas>,
665    max_len: u32,
666    scalars: &[u8],
667    points: &[u8],
668) -> PartialVMResult<NativeResult>
669where
670    G: GroupElement
671        + ToFromByteArray<POINT_SIZE>
672        + FromTrustedByteArray<POINT_SIZE>
673        + MultiScalarMul,
674    G::ScalarType: ToFromByteArray<SCALAR_SIZE> + FromTrustedByteArray<SCALAR_SIZE>,
675{
676    if points.is_empty()
677        || scalars.is_empty()
678        || !scalars.len().is_multiple_of(SCALAR_SIZE)
679        || !points.len().is_multiple_of(POINT_SIZE)
680        || points.len() / POINT_SIZE != scalars.len() / SCALAR_SIZE
681    {
682        return Ok(NativeResult::err(context.gas_used(), INVALID_INPUT_ERROR));
683    }
684
685    if points.len() / POINT_SIZE > max_len as usize {
686        return Ok(NativeResult::err(context.gas_used(), INPUT_TOO_LONG_ERROR));
687    }
688
689    native_charge_gas_early_exit_option!(
690        context,
691        scalar_decode_cost.map(|cost| cost.saturating_mul((scalars.len() / SCALAR_SIZE) as u64))
692    );
693    let scalars = scalars
694        .chunks(SCALAR_SIZE)
695        .map(parse_trusted::<G::ScalarType, { SCALAR_SIZE }>)
696        .collect::<Result<Vec<_>, _>>();
697
698    native_charge_gas_early_exit_option!(
699        context,
700        point_decode_cost.map(|cost| cost.saturating_mul((points.len() / POINT_SIZE) as u64))
701    );
702    let points = points
703        .chunks(POINT_SIZE)
704        .map(parse_trusted::<G, { POINT_SIZE }>)
705        .collect::<Result<Vec<_>, _>>();
706
707    if let (Ok(scalars), Ok(points)) = (scalars, points) {
708        // Checked above that len()>0
709        let num_of_additions = msm_num_of_additions(scalars.len() as u64);
710        native_charge_gas_early_exit_option!(
711            context,
712            base_cost.and_then(|base| base_cost_per_addition
713                .map(|per_addition| base + per_addition.saturating_mul(num_of_additions)))
714        );
715
716        let r = safe_unwrap!(G::multi_scalar_mul(&scalars, &points));
717        Ok(NativeResult::ok(
718            context.gas_used(),
719            smallvec![Value::vector_u8(r.to_byte_array().to_vec())],
720        ))
721    } else {
722        Ok(NativeResult::err(context.gas_used(), INVALID_INPUT_ERROR))
723    }
724}
725
726/***************************************************************************************************
727 * native fun internal_multi_scalar_mul
728 * Implementation of the Move native function `internal_multi_scalar_mul(type: u8, scalars: &vector<u8>, elements: &vector<u8>): vector<u8>`
729 *   gas cost: (bls12381_decode_scalar_cost + bls12381_decode_X_cost) * N + bls12381_X_msm_base_cost +
730 *             bls12381_X_msm_base_cost_per_input * num_of_additions(N)
731 **************************************************************************************************/
732pub fn internal_multi_scalar_mul(
733    context: &mut NativeContext,
734    ty_args: Vec<Type>,
735    mut args: VecDeque<Value>,
736) -> PartialVMResult<NativeResult> {
737    safe_assert!(ty_args.is_empty());
738    safe_assert_eq!(args.len(), 3);
739
740    let cost = context.gas_used();
741    if !is_msm_supported(context)? {
742        return Ok(NativeResult::err(cost, NOT_SUPPORTED_ERROR));
743    }
744
745    let elements_ref = pop_arg!(args, VectorRef);
746    let elements = elements_ref.as_bytes_ref()?;
747    let scalars_ref = pop_arg!(args, VectorRef);
748    let scalars = scalars_ref.as_bytes_ref()?;
749    let group_type = pop_arg!(args, u8);
750
751    let cost_params = get_extension!(context, NativesCostTable)?
752        .group_ops_cost_params
753        .clone();
754
755    let max_len = cost_params.bls12381_msm_max_len.ok_or_else(|| {
756        partial_vm_error!(
757            UNKNOWN_INVARIANT_VIOLATION_ERROR,
758            "Max len for MSM is not set"
759        )
760    })?;
761
762    // TODO: can potentially improve performance when some of the points are the generator.
763    match Groups::from_u8(group_type) {
764        Some(Groups::BLS12381G1) => multi_scalar_mul::<
765            bls::G1Element,
766            { bls::Scalar::BYTE_LENGTH },
767            { bls::G1Element::BYTE_LENGTH },
768        >(
769            context,
770            cost_params.bls12381_decode_scalar_cost,
771            cost_params.bls12381_decode_g1_cost,
772            cost_params.bls12381_g1_msm_base_cost,
773            cost_params.bls12381_g1_msm_base_cost_per_input,
774            max_len,
775            scalars.as_ref(),
776            elements.as_ref(),
777        ),
778        Some(Groups::BLS12381G2) => multi_scalar_mul::<
779            bls::G2Element,
780            { bls::Scalar::BYTE_LENGTH },
781            { bls::G2Element::BYTE_LENGTH },
782        >(
783            context,
784            cost_params.bls12381_decode_scalar_cost,
785            cost_params.bls12381_decode_g2_cost,
786            cost_params.bls12381_g2_msm_base_cost,
787            cost_params.bls12381_g2_msm_base_cost_per_input,
788            max_len,
789            scalars.as_ref(),
790            elements.as_ref(),
791        ),
792        _ => Ok(NativeResult::err(context.gas_used(), INVALID_INPUT_ERROR)),
793    }
794}
795
796/***************************************************************************************************
797 * native fun internal_pairing
798 * Implementation of the Move native function `internal_pairing(type:u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>`
799 *   gas cost: group_ops_bls12381_pairing_cost
800 **************************************************************************************************/
801pub fn internal_pairing(
802    context: &mut NativeContext,
803    ty_args: Vec<Type>,
804    mut args: VecDeque<Value>,
805) -> PartialVMResult<NativeResult> {
806    safe_assert!(ty_args.is_empty());
807    safe_assert_eq!(args.len(), 3);
808
809    let e2_ref = pop_arg!(args, VectorRef);
810    let e2 = e2_ref.as_bytes_ref()?;
811    let e1_ref = pop_arg!(args, VectorRef);
812    let e1 = e1_ref.as_bytes_ref()?;
813    let group_type = pop_arg!(args, u8);
814
815    let cost_params = get_extension!(context, NativesCostTable)?
816        .group_ops_cost_params
817        .clone();
818
819    let result = match Groups::from_u8(group_type) {
820        Some(Groups::BLS12381G1) => {
821            native_charge_gas_early_exit_option!(context, cost_params.bls12381_pairing_cost);
822            parse_trusted::<bls::G1Element, { bls::G1Element::BYTE_LENGTH }>(&e1).and_then(|e1| {
823                parse_trusted::<bls::G2Element, { bls::G2Element::BYTE_LENGTH }>(&e2).map(|e2| {
824                    let e3 = e1.pairing(&e2);
825                    e3.to_byte_array().to_vec()
826                })
827            })
828        }
829        _ => Err(FastCryptoError::InvalidInput),
830    };
831
832    map_op_result(context, result)
833}
834
835/***************************************************************************************************
836 * native fun internal_convert
837 * Implementation of the Move native function `internal_convert(from_type:u8, to_type: u8, e: &vector<u8>): vector<u8>`
838 *   gas cost: group_ops_bls12381_g1_from_uncompressed_cost / group_ops_bls12381_g1_from_compressed_cost
839 **************************************************************************************************/
840pub fn internal_convert(
841    context: &mut NativeContext,
842    ty_args: Vec<Type>,
843    mut args: VecDeque<Value>,
844) -> PartialVMResult<NativeResult> {
845    safe_assert!(ty_args.is_empty());
846    safe_assert_eq!(args.len(), 3);
847
848    let e_ref = pop_arg!(args, VectorRef);
849    let e = e_ref.as_bytes_ref()?;
850    let to_type = pop_arg!(args, u8);
851    let from_type = pop_arg!(args, u8);
852
853    let cost_params = get_extension!(context, NativesCostTable)?
854        .group_ops_cost_params
855        .clone();
856
857    let result = match (Groups::from_u8(from_type), Groups::from_u8(to_type)) {
858        (Some(Groups::BLS12381UncompressedG1), Some(Groups::BLS12381G1)) => {
859            native_charge_gas_early_exit_option!(
860                context,
861                cost_params.bls12381_uncompressed_g1_to_g1_cost
862            );
863            e.to_vec()
864                .try_into()
865                .map_err(|_| FastCryptoError::InvalidInput)
866                .map(bls::G1ElementUncompressed::from_trusted_byte_array)
867                .and_then(|e| bls::G1Element::try_from(&e))
868                .map(|e| e.to_byte_array().to_vec())
869        }
870        (Some(Groups::BLS12381G1), Some(Groups::BLS12381UncompressedG1)) => {
871            native_charge_gas_early_exit_option!(
872                context,
873                cost_params.bls12381_g1_to_uncompressed_g1_cost
874            );
875            parse_trusted::<bls::G1Element, { bls::G1Element::BYTE_LENGTH }>(&e)
876                .map(|e| bls::G1ElementUncompressed::from(&e))
877                .map(|e| e.into_byte_array().to_vec())
878        }
879        _ => Err(FastCryptoError::InvalidInput),
880    };
881
882    map_op_result(context, result)
883}
884
885/***************************************************************************************************
886 * native fun internal_sum
887 * Implementation of the Move native function `internal_sum(type:u8, terms: &vector<vector<u8>>): vector<u8>`
888 *   gas cost: group_ops_bls12381_g1_sum_of_uncompressed_base_cost + len(terms) * group_ops_bls12381_g1_sum_of_uncompressed_cost_per_term
889 **************************************************************************************************/
890pub fn internal_sum(
891    context: &mut NativeContext,
892    ty_args: Vec<Type>,
893    mut args: VecDeque<Value>,
894) -> PartialVMResult<NativeResult> {
895    safe_assert!(ty_args.is_empty());
896    safe_assert_eq!(args.len(), 2);
897
898    let cost = context.gas_used();
899
900    let cost_params = get_extension!(context, NativesCostTable)?
901        .group_ops_cost_params
902        .clone();
903
904    // The input is a reference to a vector of vector<u8>'s
905    let inputs = pop_arg!(args, VectorRef);
906    let group_type = pop_arg!(args, u8);
907
908    let length = inputs
909        .len(&Type::Vector(Box::new(Type::U8)))?
910        .value_as::<u64>()?;
911
912    let result = match Groups::from_u8(group_type) {
913        Some(Groups::BLS12381UncompressedG1) => {
914            let max_terms = cost_params
915                .bls12381_uncompressed_g1_sum_max_terms
916                .ok_or_else(|| {
917                    partial_vm_error!(
918                        UNKNOWN_INVARIANT_VIOLATION_ERROR,
919                        "Max number of terms is not set"
920                    )
921                })?;
922
923            if length > max_terms {
924                return Ok(NativeResult::err(cost, INPUT_TOO_LONG_ERROR));
925            }
926
927            native_charge_gas_early_exit_option!(
928                context,
929                cost_params
930                    .bls12381_uncompressed_g1_sum_base_cost
931                    .and_then(|base| cost_params
932                        .bls12381_uncompressed_g1_sum_cost_per_term
933                        .map(|per_term| base + per_term.saturating_mul(length)))
934            );
935
936            // Read the input vector
937            let input_values: Vec<Vec<u8>> = (0..length)
938                .map(|i| {
939                    inputs
940                        .borrow_elem(i as usize, &Type::Vector(Box::new(Type::U8)))
941                        .and_then(Value::value_as::<VectorRef>)
942                        .and_then(|v| Ok(v.as_bytes_ref()?.to_vec()))
943                })
944                .collect::<PartialVMResult<Vec<_>>>()?;
945
946            input_values
947                .into_iter()
948                .map(|v| {
949                    v.try_into()
950                        .map_err(|_| FastCryptoError::InvalidInput)
951                        .map(bls::G1ElementUncompressed::from_trusted_byte_array)
952                })
953                .collect::<FastCryptoResult<Vec<_>>>()
954                .and_then(|e| bls::G1ElementUncompressed::sum(&e))
955                .map(|e| bls::G1ElementUncompressed::from(&e))
956                .map(|e| e.into_byte_array().to_vec())
957        }
958        _ => Err(FastCryptoError::InvalidInput),
959    };
960
961    map_op_result(context, result)
962}