Endless
  • 🚀README
  • Discovery
    • 🚀Endless Web3 Genesis Cloud
    • 💎Business Model
    • 🎯Vision
    • ✈️Roadmap
    • 🪙Economics
    • 👤Team
      • Yu Xiong
      • Amit Kumar Jaiswal
      • Ned
      • 0xfun
      • Scott Trowbridge
      • Neeraj Sharma LLB
      • Amjad Suleman
      • Binu Paul
      • Eduard Romulus GOEAN
    • ❤️Developer Community
  • Endless Chain
    • Tech Docs
      • Account Address Format
      • Endless Account
      • Endless Coin(EDS)
      • Sponsored Transaction
      • On-Chain Multisig
      • Randomness
      • Safety Transaction
      • Token Locking & Distribution
    • Start
      • Learn about Endless
        • Accounts
        • Resources
        • Events
        • Transactions and States
        • Gas and Storage Fees
        • Computing Transaction Gas
        • Blocks
        • Staking
          • Delegated Staking
        • Governance
        • Endless Blockchain Deep Dive
          • Validator Nodes Overview
          • Fullnodes Overview
          • Node Networks and Synchronization
        • Move - A Web3 Language and Runtime
      • Explore Endless
      • Latest Endless Releases
      • Networks
    • Build
      • Tutorials
        • Your First Transaction
        • Your First Fungible Asset
        • Your First NFT
        • Your First Move Module
        • Your First Multisig
      • Learn the Move Language
        • The Move Book
          • Getting Started
            • Introduction
            • Modules and Scripts
          • Primitive Types
            • Move Tutorial
            • Integers
            • Bool
            • Address
            • Vector
            • Signer
            • References
            • Tuples and Unit
          • Basic Concepts
            • Local Variables and Scope
            • Equality
            • Abort and Assert
            • Conditionals
            • While, For, and Loop
            • Functions
            • Structs and Resources
            • Constants
            • Generics
            • Abilities
            • Uses and Aliases
            • Friends
            • Packages
            • Package Upgrades
            • Unit Tests
          • Global Storage
            • Global Storage - Structure
            • Global Storage - Operators
          • Reference
            • Libraries
            • Move Coding Conventions
        • Advanced Move Guides
          • Objects
            • Creating Objects
            • Configuring objects
            • Using objects
          • Move Scripts
            • Writing Move Scripts
            • Compiling Move Scripts
            • Running Move Scripts
            • Move Scripts Tutorial
          • Resource Accounts
          • Modules on Endless
          • Cryptography
          • Gas Profiling
          • Security
      • Endless Standards
        • Object
        • Endless Fungible Asset Standard
        • Endless Digital Asset Standard
        • Endless Wallet Standard
      • Endless APIs
        • Fullnode Rest API
        • Indexer Restful API
          • Indexer Installation
        • GRPC Transaction Stream
          • Running Locally
          • Custom Processors
            • End-to-End Tutorial
            • Parsing Transactions
          • Self-Hosted Transaction Stream Service
      • Endless SDKs
        • TypeScript SDK
          • Account
          • SDK Configuration
          • Fetch data from chain
          • Transaction Builder
          • HTTP Client
          • Move Types
          • Testing
          • Typescript
        • Rust SDK
        • Go SDK
      • Endless CLI
        • Install the Endless CLI
          • Install On Mac
          • Install On Alibaba Cloud
          • Install On Linux
          • Install On Windows
        • CLI Configuration
        • Use Endless CLI
          • Working With Move Contracts
            • Arguments in JSON Tutorial
          • Trying Things On-Chain
            • Look Up On-Chain Account Info
            • Create Test Accounts
          • Running A Local Network
            • Running a Public Network
          • Managing a Network Node
      • Integrate with Endless
        • Endless Token Overview
        • Application Integration Guide
      • Endless VSCode extension
      • Advanced Builder Guides
        • Develop Locally
          • Running a Local Network
          • Run a Localnet with Validator
    • Nodes
      • Learn about Nodes
      • Run a Validator and VFN
        • Node Requirements
        • Deploy Nodes
          • Using Docker
          • Using AWS
          • Using Azure
          • Using GCP
        • Connect Nodes
          • Connect to a Network
        • Verify Nodes
          • Node Health
          • Validator Leaderboard
      • Run a Public Fullnode
        • PFN Requirements
        • Deploy a PFN
          • Using Pre-compiled Binary
          • Using Docker
          • Using GCP 🚧 (under_construction)
        • Verify a PFN
        • Modify a PFN
          • Upgrade your PFN
          • Generate a PFN Identity
          • Customize PFN Networks
      • Bootstrap a Node
        • Bootstrap from a Snapshot
        • Bootstrap from a Backup
      • Configure a Node
        • State Synchronization
        • Data Pruning
        • Telemetry
        • Locating Node Files
          • Files For Mainnet
          • Files For Testnet
          • Files For Devnet
      • Monitor a Node
        • Node Inspection Service
        • Important Node Metrics
        • Node Health Checker
    • Reference
      • Endless Error Codes
      • Move Reference Documentation
      • Endless Glossary
    • FAQs
  • Endless Bridge
    • Intro to Endless Bridge
    • How to use bridge
    • Liquidity Management
    • Faucet
    • Developer Integration
      • Contract Integration
        • Message Contract
        • Execute Contract
      • Server-Side Integration
        • Message Sender
        • Example of Message Listener Service (Rust)
        • Example of Token Cross-Chain (JS)
  • Endless Wallet
    • User Guide
    • Basic Tutorial
    • FAQs
    • MultiAccount
    • SDK
      • Functions
      • Events
  • GameFi
    • Intro
    • GameFi & Endless
  • Endless Modules
    • Stacks
    • Storage
    • Module List
  • Endless Ecosystem
    • Intro
    • Show Cases
    • App Demo
  • Whitepaper
  • Endless SCAN
    • User Guide
  • MULTI-SIGNATURE
    • Multi-Signature User Guide
  • Regulations
    • Privacy Policy
    • Terms of Service
    • Funding Terms - Disclaimer
Powered by GitBook
On this page
  • Cryptography in Move
  • Cryptographic primitives
  • Cryptographic hash functions
  • Digital signature verification
  • Elliptic curve arithmetic
  • Building powerful cryptographic applications
Export as PDF
  1. Endless Chain
  2. Build
  3. Learn the Move Language
  4. Advanced Move Guides

Cryptography

PreviousModules on EndlessNextGas Profiling

Last updated 5 months ago

Cryptography in Move

Cryptography plays an integral role in ensuring the security, integrity, confidentiality, and immutability of data in blockchain systems. The Endless adapter for Move provides developers with an array of cryptographic primitives to cater to this need. This document delves into the cryptographic functionalities offered by Move on Endless and elucidates the principles that drive their design.

Cryptographic primitives

Move, through the Endless adapter, encompasses several fundamental cryptographic tools:

  1. Cryptographic Hash Functions – Algorithms that produce a fixed-size output (hash) from variable-sized input data. Supported functions include SHA2-256, SHA3-256, Keccak256, and Blake2b-256.

  2. Digital Signature Verification – Algorithms for signing a message to ensure its integrity, authenticate its sender, ensure non-repudiation, or any combination thereof. Supported signature schemes include Ed25519, ECDSA, and BLS.

  3. Elliptic Curve Arithmetic – Elliptic curves are one of the building blocks of advanced cryptographic primitives, such as digital signatures, public-key encryption or verifiable secret sharing. Supported curves include Ristretto255 and BLS12-381.

  4. Zero-Knowledge Proofs (ZKP) – These cryptographic techniques enable a party to prove that a relation $R(x; w)$ is satisfied on a public statement $x$ without leaking the secret witness $w$ that makes it hold. Currently, we support Groth16 ZKP verification and Bulletproofs ZK range proof verification.

Three fundamental principles guide the design and integration of the Endless cryptographic extensions into Move:

  1. Economic Gas Usage – Striving to minimize gas costs for Move developers by implementing key primitives as Move native functions. For example, see the module for .

  2. Type-Safe APIs – Ensuring that APIs are resistant to common mistakes, type-safety enhances code reliability and promotes an efficient development process. For an example, see the .

  3. Empowerment of Developers – In instances where native functions are unavailable, we empower developers to build their own cryptographic primitives on top of abstract cryptographic building blocks such as finite fields and Abelian groups. Refer to the module for more insights.

Continue reading to delve a bit deeper and uncover some of the intricacies behind these extensions, as well as the range of applications they empower. For the most comprehensive understanding of this subject, refer to the .

Cryptographic hash functions

Developers can now use more cryptographic hash functions in Move via the module:

Hash function
Hash size (bits)
Cost for hashing 1KiB (in internal gas units)
Collision-resistance security (bits)

Keccak256

256

1,001,600

128

SHA2-256

256

1,084,000

128

SHA2-512

512

1,293,600

256

SHA3-256

256

1,001,600

128

SHA3-512

512

1,114,000

256

RIPEMD160

160

1,084,000

80 (weak)

Blake2b-256

256

342,200

128

All hash functions have the same security properties (e.g., one-wayness, collision resistance, etc.), but their security levels are different.

RIPEMD160 should be avoided as a collision-resistant function due to its 80-bit security level. It is mainly supported for backward-compatibility reasons: e.g., Bitcoin address derivation relies on RIPEMD160.

Digital signature verification

Developers can now use a type-safe API for verifying many kinds of digital signatures in Move:

Signature scheme
Curve
Sig. size (bytes)
PK size (bytes)
Malleability
Assumptions
Pros
Cons

secp256k1

64

64

Yes

GGM

Wide adoption

Security proof

Edwards 25519

64

32

No

DLA, ROM

Fast

Subtleties

Edwards 25519

$4 + t \cdot 64$

$n \cdot 32$

No

DLA, ROM

Easy-to-adopt

Large sig. size

BLS12-381

96

48

No

CDH, ROM

Versatile

Slower verification

BLS12-381

48

96

No

CDH, ROM

Versatile

Slower verification

note

  • CDH stands for the "Computational Diffie-Hellman Assumption"

  • DLA stands for the "Discrete Log Assumption"

  • GGM stands for the "Generic Group Model"

  • ROM stands for the "Random Oracle Model"

The digital signature modules above can be used to build smart contract-based wallets, secure claiming mechanisms for airdrops, or any digital-signature-based access-control mechanism for dapps.

The right choice of a signature scheme in your dapp could depend on many factors:

  1. Backwards-compatibility

    • If your dapp's user base predominantly uses a particular signing mechanism, it would be prudent to support that mechanism for ease of transition and adoption.

      • Example: If users mainly sign using Ed25519, it becomes a logical choice.

  2. Ease-of-implementation

    • While theoretically sound, complex protocols may be challenging to implement in practice.

      • Example: Even though $t$-out-of-$n$ threshold protocols for Ed25519 exist, their intricacy on the signer's side might push developers toward MultiEd25519 due to its more straightforward signing implementation.

  3. Efficiency

    • Depending on the dapp's requirements, you might prioritize one aspect of efficiency over another.

      • Signature size vs. public key size: Some applications might prioritize a smaller signature footprint, while others might emphasize a compact PK.

      • Signing time vs. verification time: For certain dapps, the signing speed might be more crucial, while for others, rapid signature verification could be the priority.

  4. Security analysis

    • It is essential to consider the underlying assumptions and potential vulnerabilities of a signature scheme.

      • Example: ECDSA's security is proven under strong assumptions such as the Generic Group Model (GGM).

      • Malleability concerns: Some signature schemes are susceptible to malleability, where a valid signature, $\sigma$, can be mauled into a different yet still valid signature, $\sigma$, for the same message $m$.

  5. Versatility

    • The adaptability and flexibility of signature schemes are important to consider, so you may properly accommodate the cryptographic needs of your dapp.

      • Example: $t$-out-of-$n$ threshold BLS signatures are very simple to implement.

Despite its careful, principled , Ed25519 has known implementation subtleties. For example, different implementations could easily disagree on the validity of signatures, especially when batch verification is $^,$.

Elliptic curve arithmetic

While the hash function and digital signature modules should provide enough functionality for most applications, some applications will require more powerful cryptography. Normally, developers of such applications would have to wait until their desired cryptographic functionality is implemented efficiently as a Move native function in the Endless Move framework. Instead, we expose basic building blocks that developers can use to implement their own cryptographic primitives directly in the Move language and do so efficiently.

Specifically, we currently expose low-level arithmetic operations on two popular elliptic curve groups and their associated finite fields:

These modules support low-level operations such as:

  • scalar multiplication of elliptic curve points

  • multi-scalar multiplications (MSMs)

  • pairings

  • scalar addition, multiplication, inversion

  • hashing to a scalar or to a point

  • and many more

Examples of powerful applications that can be built on top include:

  1. Validity rollups – See the groth16 zkSNARK verifier example.

  2. Randomness-based games – See the drand verifier example.

  3. Privacy-preserving applications – See the veiled_coin example.

Ristretto255 arithmetic

This module has proven useful for implementing several cryptographic primitives:

  1. Zero-knowledge $\Sigma$-protocols – See the veiled_coin example.

Generic elliptic curve arithmetic

What is better than one curve? More curves!

As an example, a Move developer can implement the popular Boneh-Lynn-Shacham (BLS) signature scheme generically over any curve by using type arguments for the curve type in their implementation:

use std::option;
use endless_std::crypto_algebra::{eq, pairing, one, deserialize, hash_to};

/// Example of a BLS signature verification function that works over any pairing-friendly
/// group triple `Gr1`, `Gr2`, `GrT` where signatures are in `Gr1` and PKs in `Gr2`.
/// Points are serialized using the format in `FormatG1` and `FormatG2` and the hashing
/// method is `HashMethod`.
///
/// WARNING: This example is type-unsafe and probably not a great fit for production code.
public fun bls_verify_sig<Gr1, Gr2, GrT, FormatG1, FormatG2, HashMethod>(
    dst:        vector<u8>,
    signature:  vector<u8>,
    message:    vector<u8>,
    public_key: vector<u8>): bool
{
    let sig  = option::extract(&mut deserialize<Gr1, FormatG1>(&signature));
    let pk   = option::extract(&mut deserialize<Gr2, FormatG2>(&public_key));
    let hash = hash_to<Gr1, HashMethod>(&dst, &message);

    // Checks if $e(H(m), pk) = e(sig, g_2)$, where $g_2$ generates $\mathbb{G}_2$
    eq(
        &pairing<Gr1, Gr2, GrT>(&hash, &pk),
        &pairing<Gr1, Gr2, GrT>(&sig, &one<Gr2>())
    )
}
use endless_std::bls12381_algebra::{
    G1, G2, Gt, FormatG1Compr, FormatG2Compr, HashG1XmdSha256SswuRo
};

// Aborts with code 1 if the MinSig BLS signature over the BLS12-381 curve fails to verify.
assert(
    bls_verify_sig<G1, G2, Gt, FormatG1Compr, FormatG2Compr, HashG1XmdSha256SswuRo>(
        dst, signature, message, public_key
    ),
    1
);

For more use cases of the crypto_algebra module, check out some Move examples:

  1. Verifying Groth16 zkSNARK proofs over any curve

  2. Verifying randomness from the drand beacon

Building powerful cryptographic applications

Veiled coins

Specifically, users can veil their balance, keeping it hidden from everyone, including validators. Furthermore, a user can send a veiled transaction that hides the transaction amount from everybody, including validators. An important caveat is that veiled transactions do not hide the identities of the sender or the recipient.

This module is educational. It is not production-ready. Using it could lead to loss of funds.

Groth16 zkSNARK verifier

This code has not been audited by a third-party organization. If using it in a production system, proceed at your own risk.

Verifying randomness from the drand beacon

This code has not been audited by a third-party organization. If using it in a production system, proceed at your own risk.

Another application that can be built on top of drand is time-lock , which allows users to encrypt information such that it can only be decrypted in a future block. We do not currently have an implementation but the reader is encouraged to write one!

Some of these functions can be used for interoperability with other chains (e.g., verifying Ethereum Merkle proofs via ). Others, have lower gas costs, such as . In general, a wider variety of hash functions give developers additional freedom in terms of both security and interoperability with other off-chain cryptographic systems.

Our module for supports verification of individual signatures, multi-signatures, aggregate signatures and threshold signatures.

Ristretto255, via

BLS12-381, via and

The module provides support for elliptic curve arithmetic on the popular . One of the main advantages of Ristretto255 is that it is a prime order group (unlike the Edwards 25519 curve), which obviates small-subgroup attacks on higher-level cryptosystems built on top of it. Furthermore, Ristretto255 serialization is canonical and deserialization only accepts canonical encodings, which obviates malleability issues in higher-level protocols.

ElGamal encryption – See

Pedersen commitments – See

Bulletproofs ZK range – See

Need ideas for a cryptosystem to build on top of ristretto255? A popular primitive that you could easily build would be the signature scheme, which is a hardened version of Schnorr signatures over Ristretto255 groups.

The provides elliptic curve arithmetic operations for any supported elliptic curve, including pairing-friendly curves. As a consequence, Move developers can implement a cryptosystem generically over any curve that is or will be supported in the future. Compared to fixing a particular curve in the code (e.g., by implementing against the Ristretto255 module), this approach provides more flexibility and lowers development time when migrating to a different curve.

Although currently the crypto_algebra module only supports arithmetic over BLS12-381 curves (via the marker types declared in ), more curves will be supported into the future (e.g., BN254, Ristretto255, BLS12-377, BW6-761, secp256k1, secp256r1).

Using the bls_verify_sig generic function from above, developers can verify BLS signatures over any of the supported (pairing-friendly) curves. For example, one can verify signatures over BLS12-381 curves by calling the function above with the right BLS12-381 marker types as its type arguments:

The demonstrates how to use the Ristretto255 modules from above to add a reasonable layer of confidentiality to coin balances and transactions.

The demonstrates how to verify Groth16 zkSNARK , which are the shortest, fastest-to-verify, general-purpose zero-knowledge proofs. Importantly, as explained above, this implementation is generic over any curve, making it very easy for Move developers to use it with their favorite (supported) curves.

The shows how to verify public randomness from the randomness beacon. This randomness can be used in games or any other chance-based smart contract. We give a simple example of a lottery implemented on top of drand randomness in .

BLS signatures over BLS12-381 elliptic curves
Ed25519 signature module
endless_std::crypto_algebra
cryptography Move modules code
endless_std::endless_hash
endless_std::endless_hash::keccak256
endless_std::endless_hash::blake2b_256
endless_std::bls12381
MinPK BLS
endless_std::ristretto255
endless_std::crypto_algebra
endless_std::bls12381_algebra
endless_std::ristretto255
Ristretto255 curve
endless_std::ristretto255_elgamal
endless_std::ristretto255_pedersen
endless_std::ristretto255_bulletproofs
schnorrkel
endless_std::crypto_algebra
endless_std::bls12381_algebra
MinSig BLS
veiled_coin example
groth16 example
drand example
drand
lottery.move
ECDSA
Ed25519
MultiEd25519
MinPK BLS
MinSig BLS