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.
| Operation | Contract purpose | Result shape |
|---|---|---|
p1_sum and p2_sum | Add or subtract signed points in G1 or G2 | One point or Error::InvalidInput |
g1_multiexp and g2_multiexp | Combine point-and-scalar terms | One point or Error::InvalidInput |
map_fp_to_g1 and map_fp2_to_g2 | Map field elements to one curve point per input | A point list or Error::InvalidInput |
p1_decompress and p2_decompress | Expand compressed G1 or G2 points | A point list or Error::InvalidInput |
pairing_check | Test whether the product of pairings is the identity | Ok(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 group | Record size | Output |
|---|---|---|
| G1 sum | 97 bytes per signed point | One 96-byte G1 point |
| G2 sum | 193 bytes per signed point | One 192-byte G2 point |
| G1 multiexponentiation | 128 bytes per point and scalar | One 96-byte G1 point |
| G2 multiexponentiation | 224 bytes per point and scalar | One 192-byte G2 point |
| Fp to G1 mapping | 48 bytes per field element | One 96-byte G1 point per input |
| Fp2 to G2 mapping | 96 bytes per field element | One 192-byte G2 point per input |
| Pairing check | 288 bytes per G1/G2 pair | Some(true) or Some(false) |
| Point decompression | 48 bytes for G1 or 96 bytes for G2 | One 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.
| Value | Size | Encoding rule |
|---|---|---|
G1 | 96 bytes | Uncompressed point with big-endian x then y |
G2 | 192 bytes | Uncompressed point over Fp2 |
G1Compressed | 48 bytes | Compressed point with flag bits in the top three bits |
G2Compressed | 96 bytes | Compressed point over Fp2 |
Fp | 48 bytes | Big-endian canonical field value below the modulus |
Fp2 | 96 bytes | c1 followed by c0 |
Scalar | 32 bytes | Little-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
Related cryptography surfaces
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.
- Crypto and host interfaces — parent view of SDK cryptography and runtime interfaces.
- Crypto hash utilities — host-backed hash operations.
- Digest algorithms — digest support for contract code.
- NEAR host ABI bindings — low-level host function declarations.
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_sysdeclarations 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
| Trigger | Consequence | Guard |
|---|---|---|
| Raw input length is not a whole number of records | NEAR aborts contract execution | Build buffers from complete records or use the typed API |
| Point or field bytes are malformed | Typed calls return Error::InvalidInput; raw calls return None | Check the fallible result before using it |
| Pairing relation is false | The 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 subgroup | A later security check can use an unsafe point | Use subgroup-enforcing operations before security decisions |
| Ethereum EIP-2537 bytes are passed as NEAR BLS bytes | The host rejects or interprets the data incorrectly | Convert to the NEAR ZCash-compatible encoding |
| Scalar byte order is treated as big-endian | Multiexponentiation uses the wrong scalar | Encode Scalar values as little-endian bytes |
Key files
| File | Why to read it |
|---|---|
| near-sdk/…/bls12381.rs | Main typed BLS12-381 API, encodings, result states, and usage example |
| near-sdk/…/env.rs | Raw contract-facing host functions, shared result handling, and input-shape constraints |
| near-sys/…/lib.rs | NEAR host ABI declarations for all BLS12-381 operations |
| near-sdk/…/mocked_blockchain.rs | Unit-test bridge for the BLS12-381 host entry points |
| near-sdk/…/lib.rs | Public export of the near_sdk::bls12381 module |