Introducing a new way to review your PRs.

Read the announcement

near / near-sdk-rs

Rust library for writing NEAR smart contracts

View on GitHub

20 documents · Updated Nov 20, 2026

docs / bls12381-cryptography

BLS12-381 cryptography

The SDK exposes NEAR host support for BLS12-381 curve work from Rust contracts. It lets a contract decode points, map field values to curve points, combine points, compute multiexponentiations, and check pairings without shipping a full curve engine in the contract. The surface has both a typed API for safer use and a byte-buffer API for callers that already use the NEAR host format.

SDK surface

The public module is near_sdk::bls12381. It sits above the lower-level near_sdk::env functions and the near_sys host declarations. The typed module is the main contract-facing choice when the caller can work with fixed-size values because it makes sizes and invalid input visible in the Rust types. See the related NEAR host ABI bindings page for the lower host layer and crypto and host interfaces for the wider SDK context.

Typed operations

The typed API represents curve points and field values as fixed-size byte-array types. It sends one batch to the NEAR host for each operation and returns Result, so malformed input is separate from a valid operation result.

OperationContract purposeResult shape
p1_sum and p2_sumAdd or subtract signed points in G1 or G2One point or Error::InvalidInput
g1_multiexp and g2_multiexpCombine point-and-scalar termsOne point or Error::InvalidInput
map_fp_to_g1 and map_fp2_to_g2Map field elements to one curve point per inputA point list or Error::InvalidInput
p1_decompress and p2_decompressExpand compressed G1 or G2 pointsA point list or Error::InvalidInput
pairing_checkTest whether the product of pairings is the identityOk(true), Ok(false), or Error::InvalidInput

pairing_check has three states. Ok(false) means the points were valid but the pairing relation did not hold. Err(Error::InvalidInput) means the host rejected the input. This distinction is important for signature and proof checks.

References: near-sdk/…/bls12381.rs• L1-11 near-sdk/…/bls12381.rs• L255-410 near-sdk/…/lib.rs• L1633-1637

Byte-buffer operations

The near_sdk::env::bls12381_* functions expose the same host capabilities for code that already owns packed byte buffers. They return Option<Vec<u8>> for point-producing operations and Option<bool> for pairing checks. A None value means that the host rejected the input. For pairing checks, Some(false) remains a valid negative result.

The byte API requires each input buffer to contain whole records. A buffer with a length that is not a multiple of the operation's record size aborts contract execution rather than returning None.

Function groupRecord sizeOutput
G1 sum97 bytes per signed pointOne 96-byte G1 point
G2 sum193 bytes per signed pointOne 192-byte G2 point
G1 multiexponentiation128 bytes per point and scalarOne 96-byte G1 point
G2 multiexponentiation224 bytes per point and scalarOne 192-byte G2 point
Fp to G1 mapping48 bytes per field elementOne 96-byte G1 point per input
Fp2 to G2 mapping96 bytes per field elementOne 192-byte G2 point per input
Pairing check288 bytes per G1/G2 pairSome(true) or Some(false)
Point decompression48 bytes for G1 or 96 bytes for G2One uncompressed point per input

References: near-sdk/…/env.rs• L1008-1020 near-sdk/…/env.rs• L1022-1165

Curve data contract

The SDK uses the encoding defined by the NEAR protocol host. This encoding is compatible with the ZCash BLS12-381 layout and the serialization used by the zkcrypto BLS12-381 crate. It is not the EIP-2537 encoding used by Ethereum precompiles, so external curve data must be converted before it crosses the contract boundary.

Encodings

The fixed sizes and byte order are part of the contract between the SDK and the host. The wrapper types check array length at conversion time, while the host checks whether the bytes describe a valid curve or field value.

ValueSizeEncoding rule
G196 bytesUncompressed point with big-endian x then y
G2192 bytesUncompressed point over Fp2
G1Compressed48 bytesCompressed point with flag bits in the top three bits
G2Compressed96 bytesCompressed point over Fp2
Fp48 bytesBig-endian canonical field value below the modulus
Fp296 bytesc1 followed by c0
Scalar32 bytesLittle-endian 256-bit value

The point at infinity uses the infinity flag in the first byte. All-zero bytes do not represent that point. A fixed-size wrapper can hold arbitrary bytes until an operation sends them to the host, so construction alone does not prove curve validity.

References: near-sdk/…/bls12381.rs• L13-37 near-sdk/…/bls12381.rs• L71-96 near-sdk/…/bls12381.rs• L130-228

Subgroup checks

The host does not apply the same validation to every operation. Point addition and decompression follow the whole-curve rules from NEP-488. They can accept points outside the G1 or G2 subgroup. Multiexponentiation and pairing checks require subgroup membership.

This difference affects how a contract validates untrusted points. Decompression is a format and curve check, not a complete subgroup check. A contract that needs subgroup-safe points must use an operation that enforces the subgroup rule or perform a separate check before using the point in a security decision.

References: near-sdk/…/env.rs• L1022-1059 near-sdk/…/env.rs• L1062-1085 near-sdk/…/env.rs• L1129-1165

Contract verification flow

BLS signature verification is a common use of this surface. The contract prepares valid public-key and signature points, obtains the message point through its chosen hash-to-curve process, then reduces the relation to one batched pairing check.

The diagram shows the high-level path from encoded inputs to a verification decision.

flowchart LR
    A[Encoded public key and signature] --> B[Decompress points]
    C[Message bytes] --> D[Hash-to-curve preparation]
    D --> E[Message curve point]
    B --> F[Valid G1 and G2 points]
    E --> G[Pairing pairs]
    F --> G
    G --> H{Pairing check}
    H -->|Ok true| I[Relation holds]
    H -->|Ok false| J[Relation does not hold]
    H -->|Invalid input| K[Reject input]

The typed example in near-sdk/…/bls12381.rs uses two pairs so the signature equation becomes one product-of-pairings check. The curve host primitives do not by themselves define a complete BLS signature scheme. The contract remains responsible for the message encoding, hash-to-curve rules, key and signature policy, and treatment of invalid input.

References: near-sdk/…/bls12381.rs• L39-63 near-sdk/…/bls12381.rs• L391-410

Batch behavior

The operations are batch primitives. A single call can sum many points, process many point-and-scalar terms, map many field elements, or decompress many points. This keeps the contract-to-host boundary at the batch level instead of requiring one host call per item.

Empty batches have defined host results. For example, an empty sum produces the group identity and an empty pairing product passes. A contract should use these cases deliberately because an empty input is not automatically a rejected input.

References: near-sdk/…/bls12381.rs• L39-40 near-sdk/…/bls12381.rs• L240-253 near-sdk/…/bls12381.rs• L521-529 near-sdk/…/bls12381.rs• L582-602

NEAR runtime boundary

These primitives execute in the NEAR runtime through host functions. The contract passes input bytes and receives point output through the host interface. The SDK exposes the low-level declarations in near_sys and binds them to both the environment API and the typed BLS module. The runtime environment and context page explains the broader execution boundary around these calls.

Host results

The raw environment wrappers and the typed module use the same success-only register contract. A point-producing host call writes its result only when it accepts the input, and the shared environment helper makes that result available to the typed wrapper after a successful status. On rejection, the SDK returns an error or None instead of reading old register data. This preserves the difference between a failed input and a valid result.

The same host entry points are available to the unit-test mock interface. This allows SDK-level tests to exercise the contract-facing calls without changing the public operation model.

References: near-sdk/…/env.rs• L68-92 near-sdk/…/env.rs• L1008-1020 near-sdk/…/mocked_blockchain.rs• L896-958 near-sys/…/lib.rs• L332-343

Execution constraints

Contract code must treat input shape and host status as separate checks. Use fixed-size typed values when possible. When using raw buffers, build complete records and check the returned Option before using output bytes. Do not convert None into a failed cryptographic relation because that would accept malformed data as a valid negative result.

For high-volume work, group inputs into one operation where the protocol rules allow it. The host calls are designed for batches, but the contract still pays for the work and must fit within the transaction's gas and memory limits.

References: near-sdk/…/env.rs• L1022-1127 near-sdk/…/bls12381.rs• L255-410 near-sdk/…/bls12381.rs• L448-609

BLS12-381 operations are one part of the SDK's cryptography and host interface layer. Hash helpers produce message digests but do not replace the BLS-specific hash-to-curve step. Digest algorithms provide configurable digest support for application data. The host ABI page explains how low-level runtime functions connect to safer SDK wrappers.

Responsibility boundaries

The BLS12-381 surface supplies curve operations and input validation that the NEAR host defines. It does not choose an application protocol or decide how a contract handles keys, messages, proof statements, or authorization. Those rules belong to the contract or to a higher-level cryptography library.

References: near-sdk/…/bls12381.rs• L1-11 near-sdk/…/env.rs• L1-8 near-sdk/Cargo.toml• L21-55

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the typed value sizes and byte-buffer record sizes aligned with the host ABI.
  • Preserve the three-state meaning of pairing results: valid pass, valid failure, and rejected input.
  • Recheck subgroup guarantees when host validation rules change for sum or decompression operations.
  • Keep the typed wrappers, raw environment functions, and their shared register-result helper aligned when a host operation is added, renamed, or moved.
  • Keep the mock host entry points aligned with the near_sys declarations so unit tests use the same contract surface.
  • Recheck external serialization adapters when the NEAR encoding or flag rules change. EIP-2537 data is a separate format.

Important failure modes

TriggerConsequenceGuard
Raw input length is not a whole number of recordsNEAR aborts contract executionBuild buffers from complete records or use the typed API
Point or field bytes are malformedTyped calls return Error::InvalidInput; raw calls return NoneCheck the fallible result before using it
Pairing relation is falseThe call returns Ok(false) or Some(false)Treat it as a valid failed check, not as malformed input
Decompressed or summed point is outside the required subgroupA later security check can use an unsafe pointUse subgroup-enforcing operations before security decisions
Ethereum EIP-2537 bytes are passed as NEAR BLS bytesThe host rejects or interprets the data incorrectlyConvert to the NEAR ZCash-compatible encoding
Scalar byte order is treated as big-endianMultiexponentiation uses the wrong scalarEncode Scalar values as little-endian bytes

Key files

FileWhy to read it
near-sdk/…/bls12381.rsMain typed BLS12-381 API, encodings, result states, and usage example
near-sdk/…/env.rsRaw contract-facing host functions, shared result handling, and input-shape constraints
near-sys/…/lib.rsNEAR host ABI declarations for all BLS12-381 operations
near-sdk/…/mocked_blockchain.rsUnit-test bridge for the BLS12-381 host entry points
near-sdk/…/lib.rsPublic export of the near_sdk::bls12381 module