Module serde

Source
Expand description

Serde support

§Default serialization format

By default, serialization format is excessive. Points are serialized without compression. Points and scalars have an extra field “curve” that specifies which curve this point/scalar belongs to.

use generic_ec::{Curve, Point, Scalar, curves::Secp256k1};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
#[serde(bound = "")]
pub struct ZkProof<E: Curve> {
    some_point: Point<E>,
    some_scalar: Scalar<E>,
}

let proof = ZkProof::<Secp256k1> {
    some_point: Point::generator().to_point(),
    some_scalar: Scalar::one(),
};
assert_eq!(serde_json::to_string_pretty(&proof)?, r#"{
  "some_point": {
    "curve": "secp256k1",
    "point": "0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
  },
  "some_scalar": {
    "curve": "secp256k1",
    "scalar": "0000000000000000000000000000000000000000000000000000000000000001"
  }
}"#);

Excessive serialization format enables better security as it makes it harder to misuse the library. E.g. if by some mistake you parse a point that was initially generated on another curve, you’ll get instant error. Without this field, behavior is uncertain and difficult to debug: point from one curve can happen to be a valid point on another curve.

§Compact serialization format

You may opt for compact serialization format. If you do that, points are seialized in compressed form, and extra “curve” field is dropped.

Compact serialization format can be enabled using serde_with crate and Compact helper struct:

use generic_ec::{Curve, Point, Scalar, curves::Secp256k1};
use serde::{Serialize, Deserialize};
use serde_with::serde_as;

#[serde_as]
#[derive(Serialize, Deserialize)]
#[serde(bound = "")]
pub struct ZkProof<E: Curve> {
    #[serde_as(as = "generic_ec::serde::Compact")]
    some_point: Point<E>,
    #[serde_as(as = "generic_ec::serde::Compact")]
    some_scalar: Scalar<E>,
}

let proof = ZkProof::<Secp256k1> {
    some_point: Point::generator().to_point(),
    some_scalar: Scalar::one(),
};
assert_eq!(serde_json::to_string_pretty(&proof)?, r#"{
  "some_point": "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
  "some_scalar": "0000000000000000000000000000000000000000000000000000000000000001"
}"#);

Structs§

Compactserde
Compact serialization format
CurveName
A guard type asserting that deserialized value belongs to curve E
PreferCompactserde
Serializes point/scalar compactly. Deserializes both compact and non-compact points/scalars.