kroma-network / tachyon

Modular ZK(Zero Knowledge) backend accelerated by GPU
MIT License
7.78k stars 226 forks source link

(De)serialize values without any modificaiton for `PrimeField` #421

Open chokobole opened 2 months ago

chokobole commented 2 months ago

Issue type

Performance

Current behavior?

For the prime fields that supports montgomery reduction, it is serialized with a call ToBigInt(), which causes not only montgomery reductions but also uses the size than the required size of prime field.

Expected Behavior?

(De)serializes the value using value().

template <typename T>
class Copyable<
    T, std::enable_if_t<std::is_base_of_v<math::PrimeFieldBase<T>, T>>> {
 public:
  static bool WriteTo(const T& prime_field, Buffer* buffer) {
    return buffer->Write(prime_field.value());
  }

  static bool ReadFrom(const ReadOnlyBuffer& buffer, T* prime_field) {
    using value_type = typename T::value_type;
    value_type v;
    if (!buffer.Read(&v)) return false;
    if constexpr (T::Config::kUseMontgomery) {
      *prime_field = T::FromMontgomery(v);
    } else {
      *prime_field = T(v);
    }
    return true;
  }

  static size_t EstimateSize(const T& prime_field) {
    using value_type = typename T::value_type;
    return sizeof(value_type);
  }
};