Consensys / gnark-crypto

gnark-crypto provides elliptic curve and pairing-based cryptography on BN, BLS12, BLS24 and BW6 curves. It also provides various algorithms (algebra, crypto) of particular interest to zero knowledge proof systems.
Apache License 2.0
495 stars 160 forks source link

perf: add kzg.UnsafeToBytes and kzg.UnsafeFromBytes methods #499

Closed gbotrel closed 5 months ago

gbotrel commented 5 months ago

Description

TLDR; adds a method (no breaking changes) to kzg.SRS object that quickly dumps a binary representation without doing any checks, and optionally, enables to truncate the SRS at writing / reading time. UnsafeFromBytes is 6x time faster than UnsafeReadFrom

godoc:

// UnsafeToBytes returns the binary encoding of the entire SRS memory representation
// It is meant to be use to achieve fast serialization/deserialization and
// is not compatible with WriteTo / ReadFrom. It does not do any validation
// and doesn't encode points in a canonical form.
// @unstable: the format may change in the future
// If maxPkPoints is provided, the number of points in the ProvingKey will be limited to maxPkPoints
func (srs *SRS) UnsafeToBytes(maxPkPoints ...int) ([]byte, error) {

benchmark, 1 <<24 points bls12377

BenchmarkSerializeSRS/WriteTo-10                       1        1183526917 ns/op        2147545088 B/op      550 allocs/op
BenchmarkSerializeSRS/WriteRawTo-10                    1        1249923583 ns/op        4295028640 B/op      542 allocs/op
BenchmarkSerializeSRS/UnsafeToBytes-10                 4         287003656 ns/op        1610821252 B/op      522 allocs/op
BenchmarkDeserializeSRS/UnsafeReadFrom-10                      1        2677718292 ns/op        5922632568 B/op     1597 allocs/op
BenchmarkDeserializeSRS/UnsafeFromBytes-10                     3         419717778 ns/op        2147761242 B/op     1205 allocs/op

Checklist: