Cryptography and host interfaces
The cryptography and host-interface layer connects Rust contract code to NEAR runtime services. It gives SDK code stable hash values and digest traits while routing work to NEAR host functions on-chain and to matching local code off-chain. It also defines the low-level ABI boundary used by higher SDK layers for execution, storage, promises, signature checks, and other runtime services.
System boundary
The layer has four roles. near-crypto-hash defines the common 32-byte CryptoHash value. near-digest exposes contract-friendly hashers. near-sdk-env gives safe, target-aware access to selected host services. near-sys is the raw ABI surface that declares the runtime imports.
| Layer | System role | Main downstream use |
|---|---|---|
near-crypto-hash | Defines the fixed-size hash value used by SDK features. | Code hashes, identifiers, and lookup keys |
near-digest | Provides standard digest traits over supported hash families. | Generic hashing code that must work on-chain and off-chain |
near-sdk-env | Presents common environment calls with the same results across targets. | Hashing, signature checks, and runtime-facing helpers |
near-sys | Declares the direct NEAR host ABI. | SDK wrappers that need direct runtime access |
These layers form a boundary rather than a separate application feature. Higher SDK code uses typed environment operations, while the environment layer selects either a runtime service or a local equivalent for the current execution target.
Execution model
Contract code runs as Wasm inside the NEAR runtime. A host function is a runtime service imported by that Wasm module. The low-level crates keep the contract-facing API close to normal Rust while preserving a separate path for local tests and tools.
This diagram shows how a contract call reaches the runtime and how off-chain code gets an equivalent result.
flowchart LR
A[SDK or contract code] --> B[NEAR SDK environment API]
B --> C{Execution target}
C -->|NEAR contract| D[near-sdk-env]
D --> E[near-sys host ABI]
E --> F[NEAR runtime]
C -->|Tests or local tools| G[Local environment backend]
G --> H[Pure Rust result]
F --> I[Runtime result]
H --> J[Common SDK-facing result]
I --> J
The near configuration identifies code built for the NEAR contract path. The local path is used for native builds and tests. near-sdk-env rejects a near build that is not Wasm unless the SDK unit-test path supplies a mock environment, which prevents code from silently calling unavailable imports. The raw declarations use an unwind-compatible foreign-function boundary because the native unit-test mock can panic, while Wasm contracts use the same host ABI with aborting panics. References: near-sdk-env/…/lib.rs• L1-20, near-sdk-env/…/macros.rs• L1-24, near-sys/…/lib.rs• L1-12
Hash value model
near-crypto-hash defines CryptoHash as exactly 32 bytes. The SDK uses this value where a compact hash identifies data such as contract code or a derived account input. The type is deliberately small and has no dependency on a hashing engine.
The environment API keeps two naming patterns for hash results. Older helpers such as sha256 and keccak256 have both a byte-vector form and an _array fixed-size form. Hashes added later use the bare name for a fixed-size array, such as sha3_256, so callers can see the result shape from the API. References: near-sdk/…/env.rs• L10-16, near-sdk/…/env.rs• L37-41
The hash value is not the same as every digest result. SHA-256 and Keccak-256 produce 32 bytes, while Keccak-512 produces 64 bytes and RIPEMD-160 produces 20 bytes. Callers must choose the result shape that matches the runtime contract or data format. See Cryptographic hash utilities for the value-level API. References: near-crypto-hash/…/lib.rs• L1-2, near-sdk-env/…/lib.rs• L26-29, near-sdk-env/…/hash.rs• L68-72, near-sdk-env/…/hash.rs• L135-172
Digest portability
near-digest provides hashers that implement the standard digest traits. This lets contract code use one hashing interface for one-shot and incremental input without selecting a backend in application code.
The backend depends on the build target. On-chain SHA-256, Keccak-256, Keccak-512, SHA3-256, SHA3-384, SHA3-512, and RIPEMD-160 use the matching NEAR host service. Native builds and tests use pure Rust implementations of the same algorithms. The crate keeps these implementations optional by algorithm feature, while its docs.rs build enables all features for API coverage. The shared output lets the same contract logic produce matching values in both settings. See Digest algorithm implementations for the supported families and feature boundaries. References: near-digest/Cargo.toml• L14-41, near-digest/…/lib.rs• L1-21, near-digest/…/lib.rs• L39-67, near-digest/…/mod.rs• L5-65, near-digest/…/near.rs• L1-71
The NEAR host functions are one-shot. The on-chain digest types still support incremental Update calls by buffering input until finalization. This preserves the common digest interface while using one host call for the completed message.
Signature operations
Signature operations let contract code check signed data or recover a key through the same environment boundary used for hashing. On-chain calls use NEAR host services. Native builds use local cryptographic code so tests and tools can exercise the same SDK-facing contract.
The SDK exposes Ed25519 verification, P-256 verification, ML-DSA-65 verification, and ECDSA key recovery. P-256 verification receives a prehashed 32-byte message, so the caller's protocol remains responsible for choosing and applying the required digest before verification. P-256 signatures can also be checked for low-S form when a protocol needs a unique signature encoding. ML-DSA verifies the message as supplied and depends on host support for the required protocol version. Its fixed-size key and signature inputs make malformed values a contract error on the host path. The raw host ABI exposes the same signature services for low-level integrations. References: near-sdk/…/env.rs• L584-641, near-sdk/…/env.rs• L643-723, near-sdk/…/env.rs• L725-964, near-sys/…/lib.rs• L47-83
Host ABI boundary
near-sys is the direct ABI layer for NEAR runtime imports. ABI means the exact function names, argument shapes, return values, and shared-register rules used between Wasm and the host. The crate is no_std and contains declarations rather than a high-level contract API. Its foreign-function declarations support controlled unwinding for native test mocks, while Wasm links them as imports from the env module.
Its surface covers the main runtime groups:
- Registers and returned byte data
- Account, block, chain, and execution context
- Balances, deposits, gas, and storage
- Hashing and signature verification
- Promise creation, actions, results, and yield flow
- Curve and pairing operations, including BLS12-381 support
- Logs, panics, and returned values
The binding follows the runtime ABI as that ABI grows. The cryptographic part exposes SHA-256, Keccak, SHA-3, and RIPEMD-160 hashing. It also exposes signature checks, key recovery, and curve and pairing services. Optional host groups are kept behind crate features; in particular, the universal-accounts feature gates universal-account state-initialization imports. These additions remain low-level capabilities for higher SDK wrappers rather than direct application APIs. See NEAR host ABI bindings for the direct binding contract and its wrapper boundary. References: near-sys/Cargo.toml• L15-23, near-sys/…/lib.rs• L1-12, near-sys/…/lib.rs• L29-83, near-sys/…/lib.rs• L84-92, near-sys/…/lib.rs• L250-264, near-sys/…/lib.rs• L330-342
Higher layers should normally use near_sdk::env instead of calling near_sys directly. The SDK re-exports near_sys only for unstable use. This keeps raw ABI details behind a typed environment boundary while still allowing advanced integrations to reach the host surface when required. References: near-sys/…/lib.rs• L1-12, near-sys/…/lib.rs• L29-83, near-sdk/…/env.rs• L1-8, near-sdk/…/lib.rs• L1600-1606
BLS12-381 operations
BLS12-381 operations extend the host boundary for pairing-based cryptography. They give contracts access to curve arithmetic and pairing checks that are costly to run in contract Wasm but can be provided as NEAR runtime services.
The SDK environment exposes sums, multiexponentiation, field-to-curve mapping, point decompression, and pairing checks through the broader ABI. These operations use encoded curve inputs and host-managed results. Sum and decompression accept points on the whole curve, while multiexponentiation and pairing checks also require subgroup membership. Invalid encodings return a rejected result for the operations that report status. Wrong input lengths abort execution. See BLS12-381 cryptography for the supported operations and constraints. References: near-sdk/…/env.rs• L1004-1165, near-sys/…/lib.rs• L330-342
Runtime service flow
The SDK environment layer turns raw host calls into operations with useful Rust values. For a host-backed hash, it passes the input to the runtime and reads the fixed-size result from a runtime register. For a local build, it calls a pure Rust hash implementation instead. The same boundary exposes signature checks and other runtime services without making contract authors manage raw pointers and registers.
This diagram shows the common hash path and the separate path for signature checks.
flowchart TD
A[Byte input] --> B[SDK environment function]
B --> C{Host-backed operation?}
C -->|Hash on contract| D[NEAR host hash function]
D --> E[Fixed result in register]
E --> F[Typed Rust result]
C -->|Hash off-chain| G[Pure Rust hash]
G --> F
H[Signature input] --> I[SDK verification wrapper]
I --> J[NEAR host verifier or local crypto library]
J --> K[Boolean or recovered key]
This boundary is broader than hashing. It lets the SDK expose cryptographic checks while keeping runtime-only work inside the host and local-only work inside native code. References: near-sdk-env/…/hash.rs• L83-97, near-sdk-env/…/hash.rs• L115-168, near-sdk/…/env.rs• L584-964
SDK integration
The public SDK uses these crates as infrastructure for contract behavior. near_sdk::env re-exports common hash helpers and signature operations. The optional near_sdk::digest module re-exports near-digest, while low-level near_sys access remains unstable. SDK storage-key generation and deterministic account initialization rely on the same host-backed hash path.
Use the child pages according to the question you need to answer:
- Cryptographic hash utilities explains hash values and contract-oriented hash helpers.
- Digest algorithm implementations explains digest families and their on-chain and off-chain backends.
- BLS12-381 cryptography explains pairing-based cryptography exposed through the NEAR runtime.
- NEAR host ABI bindings explains raw host imports and their relationship to safer SDK wrappers.
- Runtime environment and context explains the broader execution context exposed through the environment layer.
References: near-sdk/…/env.rs• L37-41 near-sdk/…/lib.rs• L1600-1634 near-sdk/…/key.rs• L14-59 near-sdk/…/state_init.rs• L1-13
Change checklist
When these files or sections are changed, remember to consider these:
- Keep host function names and argument or result shapes aligned between
near-sys,near-sdk-env, and thenear_sdk::envwrappers. - Keep the foreign-function ABI compatible with both Wasm host imports and native unit-test mocks when changing panic or unwind behavior.
- Keep on-chain and local hash backends byte-for-byte equivalent when adding or changing a digest family.
- Check every use of
CryptoHashwhen changing hash size or conversion rules. It is a fixed 32-byte contract value. - Preserve the established hash helper naming pattern when adding a new fixed-size hash API.
- Recheck target and feature gates when changing
near,unit-testing,digest,non-contract-usage, orunstablebehavior. - Update the SDK consumers of hash output when a host service is added or removed. Storage keys and deterministic account derivation depend on the selected hash.
- Keep signature prehash rules, signature encoding checks, and host version requirements aligned between the SDK wrapper and the raw host service.
- Keep BLS12-381 input encoding, subgroup rules, output handling, and runtime limits aligned between the host binding and its SDK-facing wrapper.
- Keep feature-gated host imports aligned with the SDK feature that exposes them, especially for universal-account state initialization.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
near is set for a non-Wasm build without the unit-test environment | The build cannot use NEAR imports and is rejected. | Build contracts through the NEAR Wasm path or use the supported mock environment for tests. |
| A native mock panic crosses a non-unwind-compatible foreign-function boundary | Native tests can invoke undefined behavior instead of catching the mock panic. | Keep the raw declarations compatible with the mock's unwind behavior. |
| A host-backed digest and its local fallback use different algorithms or output sizes | Tests and off-chain tools produce values that do not match contract execution. | Preserve the algorithm mapping and fixed output types in near-digest and near-sdk-env. |
A caller treats a 20-byte or 64-byte digest as CryptoHash | A type or protocol boundary receives the wrong hash shape. | Use CryptoHash only for 32-byte values and use the digest-specific array type elsewhere. |
| A caller assumes every bare hash helper returns a byte vector | Code uses the wrong result type or adds an unnecessary conversion at a protocol boundary. | Check the helper's documented result shape, especially for hashes added after the older Vec/_array pairs. |
| A P-256 caller passes raw message bytes instead of the required 32-byte prehash | Valid signatures fail or a protocol hashes data at the wrong stage. | Hash the message according to the signing protocol before p256_verify. |
| A protocol accepts both high-S and low-S P-256 signatures as distinct values | The same valid signature can have two byte encodings. | Require p256_signature_is_low_s when signature bytes must be unique. |
| ML-DSA is used on a host without the required runtime support or with malformed fixed-size input | The operation is unavailable or the contract aborts on invalid input. | Check the supported protocol version and use the required signature and key sizes. |
| Direct ABI declarations drift from the runtime host contract | Calls can return invalid data or fail at the Wasm boundary. | Change the raw binding and each wrapper as one ABI change, then verify the target-specific path. |
A feature-gated host import is used without enabling its matching near-sys feature | The required symbol is not part of the ABI surface for that build. | Enable the feature through the supported SDK path and keep feature names aligned across crates. |
| BLS12-381 inputs use the wrong encoding, omit required subgroup checks, or exceed runtime limits | Curve or pairing operations fail at the host boundary or accept a point outside the protocol's required subgroup. | Follow the operation-specific encoding, subgroup, and execution constraints in the BLS12-381 interface. |
Key files
| File | Why to read it |
|---|---|
| near-crypto-hash/…/lib.rs | Defines the shared 32-byte CryptoHash value. |
| near-digest/Cargo.toml | Shows digest feature selection and the split between host-backed and native dependencies. |
| near-digest/…/lib.rs | Shows the common digest interface and target-dependent backend model. |
| near-digest/…/mod.rs | Shows a digest family with a NEAR host implementation and a local implementation. |
| near-digest/…/mod.rs | Shows the host-backed Keccak and SHA-3 variants. |
| near-digest/…/near.rs | Shows the SHA-3 family mapped to NEAR environment hash services. |
| near-sdk-env/…/hash.rs | Shows the stable hash helpers and their host or local execution paths. |
| near-sdk-env/…/lib.rs | Defines the low-level environment boundary and its target constraints. |
| near-sys/…/lib.rs | Declares the direct NEAR runtime ABI, including cryptographic host services, feature-gated imports, and its Wasm/native foreign-function boundary. |
| near-sys/Cargo.toml | Shows the crate's feature gates, including optional universal-account bindings. |
| near-sdk/…/env.rs | Shows how the SDK turns raw host functions into contract-facing hashing, signature, and curve operations. |
| near-sdk/…/key.rs | Shows how SDK storage keys use host-backed hashing. |
| near-sdk/…/lib.rs | Shows which low-level crates the public SDK re-exports and under which features. |