Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Modules

obscura

Obscura - Privacy-Preserving Smart ContractThis module contains the main implementation of the Obscura privacy-preserving smart contract. Obscura enables private transactions on Starknet using zero-knowledge proofs and Merkle trees. ## OverviewThe Obscura contract implements a privacy-preserving transaction system that allows users to: - Deposit and withdraw tokens privately - Transfer tokens between accounts without revealing transaction details - Use zero-knowledge proofs to prove transaction validity - Maintain privacy through commitment schemes and nullifiers ## ArchitectureThe contract is organized into several modules: - constants: System-wide constants and configuration values - custom_type: Custom data types including signed integers - errors: Error messages and constants - events: Event definitions for contract interactions - interface: External interface definitions - obscura: Main contract implementation - structs: Data structure definitions

Fully qualified path: obscura

Modules

constants

Constants ModuleThis module defines system-wide constants used throughout the Obscura privacy-preserving contract. These constants establish the mathematical foundations and operational limits of the system.

Fully qualified path: obscura::constants

Constants

custom_type

Custom Types ModuleThis module provides custom data types that extend Cairo's built-in types for specific use cases in the Obscura privacy-preserving system. ## Available TypesI256: A signed 256-bit integer implementation for handling negative amounts - U1024: A 1024-bit unsigned integer for cryptographic operations ## UsageThese custom types are used throughout the Obscura system to handle: - Negative amounts in deposits and withdrawals - Large cryptographic values that exceed standard integer limits - Mathematical operations requiring extended precision

Fully qualified path: obscura::custom_type

Modules

errors

Errors ModuleThis module defines error constants used throughout the Obscura privacy-preserving smart contract. These error messages provide clear feedback when operations fail, helping users understand what went wrong and how to fix it. ## Error CategoriesThe errors are organized into several categories: - Access Control Errors: Authorization and permission issues - Validation Errors: Input validation and constraint violations - Cryptographic Errors: Proof verification and security issues - System Errors: Operational and state-related issues

Fully qualified path: obscura::errors

Constants

events

Events ModuleThis module defines the events emitted by the Obscura privacy-preserving smart contract. These events provide transparency and allow external systems to track the state of the privacy system while maintaining the privacy of individual transactions. ## Event CategoriesThe events are organized into several categories: - Commitment Events: Track new commitments added to the Merkle tree - Nullifier Events: Track spent inputs to prevent double-spending - Account Events: Track user registration and key management

Fully qualified path: obscura::events

Structs

interface

Interface ModuleThis module defines the external interface for the Obscura privacy-preserving smart contract. The interface provides the public API that users and other contracts can interact with to perform privacy-preserving transactions and manage the system. ## Core FunctionsThe interface is organized into several categories: - Account Management: User registration and key management - Transaction Processing: Privacy-preserving transaction execution - System Configuration: Administrative functions for system parameters - Query Functions: Read-only functions for system state and limits

Fully qualified path: obscura::interface

Structs

Traits

obscura

Obscura - Privacy-Preserving Smart Contract ImplementationThis module contains the main implementation of the Obscura privacy-preserving smart contract for Starknet. The contract enables private transactions using zero-knowledge proofs and Merkle trees, allowing users to transfer tokens without revealing transaction details. ## OverviewThe Obscura contract implements a privacy-preserving transaction system that provides: - Private Deposits: Users can deposit tokens without revealing their identity - Private Withdrawals: Users can withdraw tokens to specific addresses - Private Transfers: Internal transfers between users remain completely private - Zero-Knowledge Proofs: Cryptographic proofs ensure transaction validity - Merkle Tree Management: Efficient commitment storage and verification ## ArchitectureThe contract uses several key cryptographic primitives: - Commitments: Cryptographic commitments to transaction outputs - Nullifiers: One-time use values that prevent double-spending - Merkle Trees: Efficient storage and verification of commitments - Zero-Knowledge Proofs: Prove transaction validity without revealing details ## Security ModelThe system maintains privacy through: - Cryptographic commitments that hide transaction amounts - Nullifiers that prevent double-spending without revealing inputs - Zero-knowledge proofs that validate transactions cryptographically - Encrypted outputs that only recipients can decrypt ## Usage FlowRegistration: Users register their public key for encrypted communication 2. Deposits: Users deposit tokens and receive commitments 3. Transfers: Users transfer tokens privately using zero-knowledge proofs 4. Withdrawals: Users withdraw tokens to external addresses ## DependenciesThe contract integrates with: - OpenZeppelin Cairo contracts for access control - External zero-knowledge proof verifier - STRK token contract for token transfers

Fully qualified path: obscura::obscura

Modules

structs

Data Structures ModuleThis module defines the core data structures used throughout the Obscura privacy-preserving contract. These structures represent the fundamental components of the privacy system including Merkle trees, transaction proofs, and account information.

Fully qualified path: obscura::structs

Structs

i256

I256 - Signed 256-bit Integer ImplementationThis module provides a custom implementation of a signed 256-bit integer type for the Obscura privacy-preserving system. Since Cairo doesn't have native signed integers, this implementation provides the necessary functionality for handling negative amounts in deposits and withdrawals. ## Implementation DetailsThe I256 type is implemented as a struct containing: - value: An unsigned 256-bit integer representing the absolute value - is_negative: A boolean flag indicating the sign ## Mathematical OperationsThe implementation provides standard arithmetic operations: - Addition and subtraction with proper sign handling - Negation for sign changes - Comparison operations (less than, greater than, etc.) - Conversion to and from u256 ## Usage in ObscuraI256 is primarily used for: - Representing external amounts (positive for deposits, negative for withdrawals) - Fee calculations and public amount computations - Maintaining mathematical consistency in zero-knowledge proofs

Fully qualified path: obscura::custom_type::i256

Structs

Traits

u1024

U1024 - 1024-bit Unsigned Integer ImplementationThis module provides a custom implementation of a 1024-bit unsigned integer type for cryptographic operations in the Obscura privacy-preserving system. ## Implementation DetailsThe U1024 type is implemented as a struct containing eight 128-bit limbs: - limb0 through limb7: Individual 128-bit components - Total size: 8 × 128 = 1024 bits ## UsageU1024 is designed for cryptographic operations that require: - Extended precision beyond standard 256-bit integers - Large number arithmetic for zero-knowledge proofs - Cryptographic calculations requiring 1024-bit precision ## NoteThis is a basic structure definition. Full arithmetic operations would need to be implemented for complete functionality.

Fully qualified path: obscura::custom_type::u1024

Structs

Obscura

Fully qualified path: obscura::obscura::Obscura

Modules

Free functions

Structs

Enums

__external

Fully qualified path: obscura::obscura::Obscura::__external

__l1_handler

Fully qualified path: obscura::obscura::Obscura::__l1_handler

__constructor

Fully qualified path: obscura::obscura::Obscura::__constructor

Constants

FIELD_SIZE

The finite field size used in the cryptographic operations. This is the prime field size for the BN254 curve used in zero-knowledge proofs. # Mathematical Properties - Prime number: 21888242871839275222246405745257275088548364400416034343698204186575808495617 - Used for modular arithmetic in zero-knowledge proof verification - Ensures cryptographic security of the commitment scheme

Fully qualified path: obscura::constants::FIELD_SIZE

pub const FIELD_SIZE: u256 =
    21888242871839275222246405745257275088548364400416034343698204186575808495617;

MAX_EXT_AMOUNT

Maximum allowed external amount for deposits and withdrawals. This limit prevents overflow attacks and ensures system stability. # Value - 2^248 (approximately 4.5 × 10^74) - Provides sufficient range for practical transaction amounts - Prevents arithmetic overflow in calculations

Fully qualified path: obscura::constants::MAX_EXT_AMOUNT

pub const MAX_EXT_AMOUNT: u256 = 2_u256.pow(248);

MAX_FEE

Maximum allowed fee amount for transactions. This limit prevents excessive fee extraction and ensures fair pricing. # Value - 2^248 (same as MAX_EXT_AMOUNT) - Allows for high-value transactions with reasonable fees - Prevents economic attacks through excessive fees

Fully qualified path: obscura::constants::MAX_FEE

pub const MAX_FEE: u256 = 2_u256.pow(248);

MIN_EXT_AMOUNT

Minimum allowed external amount for deposits and withdrawals. This ensures transactions have meaningful economic value. # Value - 5 × 10^17 (0.5 tokens in wei units) - Prevents dust attacks and spam transactions - Ensures gas costs are justified by transaction value

Fully qualified path: obscura::constants::MIN_EXT_AMOUNT

pub const MIN_EXT_AMOUNT: u256 = 5 * 10_u256.pow(17);

VERIFIER_CLASSHASH

The class hash of the zero-knowledge proof verifier contract. This contract is responsible for verifying the cryptographic proofs that validate private transactions. # Usage - Used in library calls to verify transaction proofs - Ensures only valid cryptographic proofs are accepted - Critical for maintaining the privacy and security of the system

Fully qualified path: obscura::constants::VERIFIER_CLASSHASH

pub const VERIFIER_CLASSHASH: felt252 =
    0x01b5fbe104c033025dbb7fb37011781cc9344e881b4828cdaa023a80fecafde4;

ROOT_HISTORY_SIZE

The number of past Merkle roots stored for history verification. This allows the system to verify that transactions are based on recent, valid state while maintaining privacy. # Value - 100 historical roots - Balances privacy (not too many roots) with security (not too few) - Allows for reasonable transaction finality periods

Fully qualified path: obscura::constants::ROOT_HISTORY_SIZE

pub const ROOT_HISTORY_SIZE: u32 = 100;

FELT_STRK_CONTRACT

The contract address of the STRK token on Starknet mainnet. This is the native token used for deposits, withdrawals, and fee payments. # Address - Mainnet STRK token contract - Used for all token transfers in the privacy system - Ensures compatibility with Starknet's native token ecosystem

Fully qualified path: obscura::constants::FELT_STRK_CONTRACT

pub const FELT_STRK_CONTRACT: felt252 =
    0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d;

ERROR_ONLY_OWNER_CAN_BE_REGISTERED

Error message for unauthorized account registration attempts.This error is thrown when someone tries to register an account that doesn't belong to them. Only the account owner can register their own account. # When Thrown - Caller address doesn't match the account owner address - Attempting to register someone else's account # Resolution - Ensure the caller is the account owner - Use the correct account address for registration

Fully qualified path: obscura::errors::ERROR_ONLY_OWNER_CAN_BE_REGISTERED

pub const ERROR_ONLY_OWNER_CAN_BE_REGISTERED: felt252 = 'Only owner can be registered';

ERROR_INVALID_MERKLE_ROOT

Error message for invalid Merkle root in transaction proofs.This error is thrown when a transaction proof references a Merkle root that is not in the recent history of valid roots. # When Thrown - The root in the proof is not found in the recent history - The root is zero (invalid) - The root is too old and has been rotated out # Resolution - Use a recent, valid Merkle root - Ensure the proof is based on current state

Fully qualified path: obscura::errors::ERROR_INVALID_MERKLE_ROOT

pub const ERROR_INVALID_MERKLE_ROOT: felt252 = 'Invalid merkle root';

ERROR_INPUT_ALREADY_SPENT

Error message for attempting to spend already spent inputs.This error is thrown when a transaction tries to use a nullifier that has already been used in a previous transaction. # When Thrown - Input nullifier has already been spent - Attempting to double-spend an input - Nullifier is already in the spent set # Resolution - Use fresh, unspent inputs for new transactions - Check input status before creating proofs

Fully qualified path: obscura::errors::ERROR_INPUT_ALREADY_SPENT

pub const ERROR_INPUT_ALREADY_SPENT: felt252 = 'Input is already spent';

ERROR_ZERO_ADDRESS

Error message for invalid recipient addresses.This error is thrown when a withdrawal transaction specifies a zero address as the recipient. # When Thrown - Recipient address is zero (0x0) - Attempting to withdraw to an invalid address # Resolution - Use a valid, non-zero recipient address - Ensure the recipient address is properly formatted

Fully qualified path: obscura::errors::ERROR_ZERO_ADDRESS

pub const ERROR_ZERO_ADDRESS: felt252 = 'Invalid cannot be address';

ERROR_INVALID_FEE

Error message for invalid fee amounts.This error is thrown when a transaction fee exceeds the maximum allowed fee or is otherwise invalid. # When Thrown - Fee amount exceeds MAX_FEE - Fee calculation results in overflow - Fee is negative or invalid # Resolution - Use a fee amount within the system limits - Ensure fee calculation is correct

Fully qualified path: obscura::errors::ERROR_INVALID_FEE

pub const ERROR_INVALID_FEE: felt252 = 'Invalid fee';

ERROR_INVALID_EXT_AMOUNT

Error message for invalid external amounts.This error is thrown when the external amount (deposit/withdrawal) is outside the allowed range or invalid. # When Thrown - Amount exceeds MAX_EXT_AMOUNT - Amount is below MIN_EXT_AMOUNT - Amount calculation results in overflow # Resolution - Use an amount within the system limits - Ensure amount calculation is correct

Fully qualified path: obscura::errors::ERROR_INVALID_EXT_AMOUNT

pub const ERROR_INVALID_EXT_AMOUNT: felt252 = 'Invalid ext amount';

ERROR_INVALID_TREE_DEPTH

Error message for invalid Merkle tree depth.This error is thrown when attempting to create a Merkle tree with an invalid depth (too shallow or too deep). # When Thrown - Tree depth is 0 (too shallow) - Tree depth is >= 32 (too deep) - Invalid depth parameter during initialization # Resolution - Use a depth between 1 and 31 - Consider gas costs and storage requirements

Fully qualified path: obscura::errors::ERROR_INVALID_TREE_DEPTH

pub const ERROR_INVALID_TREE_DEPTH: felt252 = 'Invalid tree depth';

ERROR_MERKLE_TREE_IS_FULL

Error message for attempting to insert into a full Merkle tree.This error is thrown when the Merkle tree has reached its maximum capacity and cannot accept new commitments. # When Thrown - Tree has 2^levels commitments (maximum capacity) - No more space available for new commitments # Resolution - Wait for commitments to be spent (creating space) - Consider upgrading to a larger tree if needed

Fully qualified path: obscura::errors::ERROR_MERKLE_TREE_IS_FULL

pub const ERROR_MERKLE_TREE_IS_FULL: felt252 = 'Merkle tree is full';

ERROR_INCORRECT_EXT_HASH

Error message for incorrect external data hash.This error is thrown when the hash of the external data doesn't match the hash provided in the zero-knowledge proof. # When Thrown - External data hash mismatch - Proof was generated with different external data - Data tampering or corruption detected # Resolution - Ensure external data matches the proof - Regenerate proof with correct external data

Fully qualified path: obscura::errors::ERROR_INCORRECT_EXT_HASH

pub const ERROR_INCORRECT_EXT_HASH: felt252 = 'Incorrect external data hash';

ERROR_INVALID_PUBLIC_AMOUNT

Error message for invalid public amount in proof.This error is thrown when the public amount in the zero-knowledge proof doesn't match the calculated public amount from external data. # When Thrown - Public amount mismatch between proof and calculation - Proof was generated with incorrect amounts - Fee calculation error # Resolution - Ensure amounts are calculated correctly - Regenerate proof with correct amounts

Fully qualified path: obscura::errors::ERROR_INVALID_PUBLIC_AMOUNT

pub const ERROR_INVALID_PUBLIC_AMOUNT: felt252 = 'Invalid public amount';

ERROR_INVALID_TRANSACTION_PROOF

Error message for invalid transaction proof.This error is thrown when the zero-knowledge proof fails verification by the external proof verifier contract. # When Thrown - Cryptographic proof verification fails - Proof is malformed or invalid - Proof was generated with incorrect inputs # Resolution - Regenerate proof with correct inputs - Ensure all proof components are valid

Fully qualified path: obscura::errors::ERROR_INVALID_TRANSACTION_PROOF

pub const ERROR_INVALID_TRANSACTION_PROOF: felt252 = 'Invalid transaction proof';

ERROR_AMOUNT_LARGER_THAN_MAXIMUM_DEPOSIT

Error message for deposit amounts exceeding the maximum limit.This error is thrown when a deposit amount exceeds the configured maximum deposit amount for the system. # When Thrown - Deposit amount > maximum_deposit_amount - Attempting to deposit more than allowed # Resolution - Reduce deposit amount to within limits - Split large deposits into smaller transactions

Fully qualified path: obscura::errors::ERROR_AMOUNT_LARGER_THAN_MAXIMUM_DEPOSIT

pub const ERROR_AMOUNT_LARGER_THAN_MAXIMUM_DEPOSIT: felt252 = 'Deposit amount is too large';

Free functions

constructor

Constructor function for initializing the Obscura contract.This function sets up the initial state of the privacy system, including the Merkle tree and system parameters. # Arguments * levels - The depth of the Merkle tree (number of levels) * maximum_deposit_amount - The maximum amount allowed for deposits # Initialization Steps 1. Sets the contract owner to the caller 2. Initializes the Merkle tree with the specified depth 3. Configures the maximum deposit amount # Security - Only callable during contract deployment - Sets up the foundational privacy infrastructure

Fully qualified path: obscura::obscura::Obscura::constructor

pub fn constructor(ref self: ContractState, levels: u32, maximum_deposit_amount: u256)

unsafe_new_contract_state

Fully qualified path: obscura::obscura::Obscura::unsafe_new_contract_state

pub fn unsafe_new_contract_state() -> ContractState

Structs

I256

A signed 256-bit integer implementation for handling negative amounts.This struct represents a signed integer by storing the absolute value and a sign flag, enabling arithmetic operations with negative numbers. # Fields - value: The absolute value as an unsigned 256-bit integer - is_negative: Boolean flag indicating if the value is negative # Examples

// Positive number: 100
let positive = I256 { value: 100, is_negative: false };

// Negative number: -100
let negative = I256 { value: 100, is_negative: true };

// Zero (always positive)
let zero = I256 { value: 0, is_negative: false };

Fully qualified path: obscura::custom_type::i256::I256

#[derive(Debug, Drop, Clone, Copy, PartialEq, Serde)]
pub struct I256 {
    pub value: u256,
    pub is_negative: bool,
}

Members

value

The absolute value of the integer. This field stores the magnitude regardless of sign.

Fully qualified path: obscura::custom_type::i256::I256::value

pub value: u256

is_negative

Flag indicating whether the value is negative. When true, the actual value is -value; when false, it's +value.

Fully qualified path: obscura::custom_type::i256::I256::is_negative

pub is_negative: bool

U1024

A 1024-bit unsigned integer implementation for cryptographic operations.This struct represents a large integer by storing it as eight 128-bit limbs, enabling operations on values that exceed the standard 256-bit limit. # Fields - limb0 through limb7: Individual 128-bit components of the number # Structure The number is stored in little-endian format: - limb0: Least significant 128 bits - limb7: Most significant 128 bits # Usage This type is primarily used for: - Cryptographic operations requiring extended precision - Zero-knowledge proof calculations - Large number arithmetic in privacy-preserving systems

Fully qualified path: obscura::custom_type::u1024::U1024

#[derive(Debug, Drop, Clone, Copy, PartialEq, Serde)]
pub struct U1024 {
    limb0: u128,
    limb1: u128,
    limb2: u128,
    limb3: u128,
    limb4: u128,
    limb5: u128,
    limb6: u128,
    limb7: u128,
}

NewCommitment

Event emitted when a new commitment is added to the Merkle tree.This event is emitted for each new commitment created during a privacy-preserving transaction. It provides the commitment hash, its index in the tree, and the encrypted output data for the recipient. # Privacy Considerations - The commitment hash reveals no information about the transaction amount - The encrypted output can only be decrypted by the intended recipient - The index provides ordering information without revealing transaction details # Usage - External systems can track the growth of the Merkle tree - Recipients can scan for their encrypted outputs using their private key - Provides transparency while maintaining transaction privacy

Fully qualified path: obscura::events::NewCommitment

#[derive(Drop, starknet::Event)]
pub struct NewCommitment {
    pub commitment: u256,
    pub index: u32,
    pub encrypted_output: ByteArray,
}

Members

commitment

The commitment hash that was added to the Merkle tree. This is a cryptographic commitment to the transaction output.

Fully qualified path: obscura::events::NewCommitment::commitment

pub commitment: u256

index

The index of the commitment in the Merkle tree. Provides ordering information for tree construction.

Fully qualified path: obscura::events::NewCommitment::index

pub index: u32

encrypted_output

The encrypted output data for the transaction recipient. Contains private transaction details encrypted with the recipient's public key.

Fully qualified path: obscura::events::NewCommitment::encrypted_output

pub encrypted_output: ByteArray

NewNullifier

Event emitted when a nullifier is used to spend an input.This event is emitted for each input nullifier used in a privacy-preserving transaction. It ensures that each input can only be spent once, preventing double-spending attacks. # Security Purpose - Prevents double-spending by tracking spent inputs - The nullifier reveals no information about the original input - Provides cryptographic proof of input ownership and spending # Usage - External systems can track spent inputs - Enables efficient double-spending detection - Maintains privacy while ensuring transaction validity

Fully qualified path: obscura::events::NewNullifier

#[derive(Drop, starknet::Event)]
pub struct NewNullifier {
    pub nullifier: u256,
}

Members

nullifier

The nullifier hash that was used to spend an input. This is a cryptographic proof that the input was owned and spent.

Fully qualified path: obscura::events::NewNullifier::nullifier

pub nullifier: u256

PublicKey

Event emitted when a user registers their public key.This event is emitted when a user registers their account in the privacy system. It provides transparency about user registration while maintaining the privacy of their transactions. # Registration Process - Users must register before they can receive encrypted outputs - The public key is used for encrypted communication - Only the account owner can register their own account # Privacy Features - The public key is necessary for encrypted communication - Registration does not reveal transaction history or balances - Enables privacy-preserving communication between users

Fully qualified path: obscura::events::PublicKey

#[derive(Drop, starknet::Event)]
pub struct PublicKey {
    #[key]
    pub owner: ContractAddress,
    pub key: ByteArray,
}

Members

owner

The owner's contract address that controls this account. This is the key field used for indexing and querying events.

Fully qualified path: obscura::events::PublicKey::owner

pub owner: ContractAddress

key

The public key used for encrypted communication. Used to encrypt transaction outputs and verify transaction signatures.

Fully qualified path: obscura::events::PublicKey::key

pub key: ByteArray

IObscuraDispatcher

Fully qualified path: obscura::interface::IObscuraDispatcher

#[derive(Copy, Drop, starknet::Store, Serde)]
pub struct IObscuraDispatcher {
    pub contract_address: starknet::ContractAddress,
}

Members

contract_address

Fully qualified path: obscura::interface::IObscuraDispatcher::contract_address

pub contract_address: starknet::ContractAddress

IObscuraLibraryDispatcher

Fully qualified path: obscura::interface::IObscuraLibraryDispatcher

#[derive(Copy, Drop, starknet::Store, Serde)]
pub struct IObscuraLibraryDispatcher {
    pub class_hash: starknet::ClassHash,
}

Members

class_hash

Fully qualified path: obscura::interface::IObscuraLibraryDispatcher::class_hash

pub class_hash: starknet::ClassHash

IObscuraSafeLibraryDispatcher

Fully qualified path: obscura::interface::IObscuraSafeLibraryDispatcher

#[derive(Copy, Drop, starknet::Store, Serde)]
pub struct IObscuraSafeLibraryDispatcher {
    pub class_hash: starknet::ClassHash,
}

Members

class_hash

Fully qualified path: obscura::interface::IObscuraSafeLibraryDispatcher::class_hash

pub class_hash: starknet::ClassHash

IObscuraSafeDispatcher

Fully qualified path: obscura::interface::IObscuraSafeDispatcher

#[derive(Copy, Drop, starknet::Store, Serde)]
pub struct IObscuraSafeDispatcher {
    pub contract_address: starknet::ContractAddress,
}

Members

contract_address

Fully qualified path: obscura::interface::IObscuraSafeDispatcher::contract_address

pub contract_address: starknet::ContractAddress

ContractState

Fully qualified path: obscura::obscura::Obscura::ContractState

pub struct ContractState {
    #[substorage(v0)]
    ownable: OwnableComponent::ComponentState<ContractState>,
}

MerkleTreeWithHistory

A Merkle tree with history for storing and managing commitments in the privacy system.This structure implements a sparse Merkle tree that maintains a history of recent roots to enable privacy-preserving transaction verification while preventing double-spending. # Components - levels: The depth of the Merkle tree (number of levels) - filled_subtrees: Intermediate hashes of subtree roots at each level - roots: Historical Merkle roots for verification - current_root_index: Index of the current active root - next_index: Next available index for inserting new leaves - zeros: Precomputed zero hashes for empty nodes at each level # Privacy Features - Maintains commitment history without revealing individual transactions - Enables zero-knowledge proof verification against recent state - Prevents double-spending through nullifier tracking

Fully qualified path: obscura::structs::MerkleTreeWithHistory

#[starknet::storage_node]
pub struct MerkleTreeWithHistory {
    pub levels: u32,
    pub filled_subtrees: Vec<u256>,
    pub roots: Vec<u256>,
    pub current_root_index: u32,
    pub next_index: u32,
    pub zeros: Vec<u256>,
}

Members

levels

The depth of the Merkle tree (number of levels). Determines the maximum number of commitments that can be stored.

Fully qualified path: obscura::structs::MerkleTreeWithHistory::levels

pub levels: u32

filled_subtrees

Stores intermediate hashes of subtree roots at each level. Used for efficient Merkle tree updates and proof generation.

Fully qualified path: obscura::structs::MerkleTreeWithHistory::filled_subtrees

pub filled_subtrees: Vec<u256>

roots

Stores the historical Merkle roots for transaction verification. Allows verification against recent state while maintaining privacy.

Fully qualified path: obscura::structs::MerkleTreeWithHistory::roots

pub roots: Vec<u256>

current_root_index

Tracks the index of the current Merkle root in the circular buffer. Used for efficient root rotation and history management.

Fully qualified path: obscura::structs::MerkleTreeWithHistory::current_root_index

pub current_root_index: u32

next_index

Tracks the next available index for inserting a new leaf. Ensures sequential insertion and proper tree structure.

Fully qualified path: obscura::structs::MerkleTreeWithHistory::next_index

pub next_index: u32

zeros

Precomputed zero hashes for empty nodes at each level. Optimizes Merkle tree operations by avoiding repeated hash calculations.

Fully qualified path: obscura::structs::MerkleTreeWithHistory::zeros

pub zeros: Vec<u256>

ExtData

External data associated with a privacy-preserving transaction.This structure contains the public information that must be revealed for a transaction to be processed, while keeping the actual amounts and recipients private through zero-knowledge proofs. # Privacy Model - recipient and ext_amount are public for deposit/withdrawal operations - Internal transfers remain completely private - encrypted_output contains private transaction details

Fully qualified path: obscura::structs::ExtData

#[derive(Debug, Drop, PartialEq, Serde)]
pub struct ExtData {
    pub recipient: ContractAddress,
    pub ext_amount: I256,
    pub relayer: ContractAddress,
    pub fee: u256,
    pub encrypted_output1: ByteArray,
    pub encrypted_output2: ByteArray,
}

Members

recipient

The recipient address for withdrawals or the contract address for deposits. Must be a valid Starknet contract address.

Fully qualified path: obscura::structs::ExtData::recipient

pub recipient: ContractAddress

ext_amount

The external amount for deposit (positive) or withdrawal (negative). This value is public and used for token transfers.

Fully qualified path: obscura::structs::ExtData::ext_amount

pub ext_amount: I256

relayer

The relayer address that will receive the transaction fee. Incentivizes transaction processing and network maintenance.

Fully qualified path: obscura::structs::ExtData::relayer

pub relayer: ContractAddress

fee

The fee amount paid to the relayer for processing the transaction. Must be within the system's fee limits.

Fully qualified path: obscura::structs::ExtData::fee

pub fee: u256

encrypted_output1

Encrypted output data for the first commitment. Contains private transaction details that only the recipient can decrypt.

Fully qualified path: obscura::structs::ExtData::encrypted_output1

pub encrypted_output1: ByteArray

encrypted_output2

Encrypted output data for the second commitment. Contains private transaction details that only the recipient can decrypt.

Fully qualified path: obscura::structs::ExtData::encrypted_output2

pub encrypted_output2: ByteArray

Proof

Zero-knowledge proof data for validating a privacy-preserving transaction.This structure contains all the cryptographic proof elements needed to verify that a transaction is valid without revealing private information. # Cryptographic Components - proof: The zero-knowledge proof demonstrating transaction validity - root: The Merkle root that the transaction is based on - input_nullifiers: Nullifiers proving input ownership and preventing double-spending - output_commitments: New commitments for the transaction outputs - public_amount: The public amount that must be consistent with external data - ext_data_hash: Hash of external data for consistency verification

Fully qualified path: obscura::structs::Proof

#[derive(Debug, Drop, PartialEq, Serde)]
pub struct Proof {
    pub proof: Span<felt252>,
    pub root: u256,
    pub input_nullifiers: Array<u256>,
    pub output_commitments: Array<u256>,
    pub public_amount: u256,
    pub ext_data_hash: u256,
}

Members

proof

The zero-knowledge proof demonstrating the validity of the transaction. Verified by the external proof verifier contract.

Fully qualified path: obscura::structs::Proof::proof

pub proof: Span<felt252>

root

The Merkle root that the transaction inputs are based on. Must be a known root from the recent history.

Fully qualified path: obscura::structs::Proof::root

pub root: u256

input_nullifiers

Nullifiers for the input commitments, proving ownership and preventing double-spending. Each nullifier can only be used once and reveals no information about the input.

Fully qualified path: obscura::structs::Proof::input_nullifiers

pub input_nullifiers: Array<u256>

output_commitments

New commitments for the transaction outputs. These will be inserted into the Merkle tree after verification.

Fully qualified path: obscura::structs::Proof::output_commitments

pub output_commitments: Array<u256>

public_amount

The public amount that must be consistent with the external data. Calculated as ext_amount - fee and used for zero-knowledge proof verification.

Fully qualified path: obscura::structs::Proof::public_amount

pub public_amount: u256

ext_data_hash

Hash of the external data for consistency verification. Ensures the proof corresponds to the provided external data.

Fully qualified path: obscura::structs::Proof::ext_data_hash

pub ext_data_hash: u256

Account

Account information for user registration in the privacy system.This structure contains the public information needed to identify and communicate with users in the privacy-preserving system. # Registration Process - Users register their public key with the contract - The public key is used for encrypted communication - Only the owner can register their own account

Fully qualified path: obscura::structs::Account

#[derive(Debug, Drop, PartialEq, Serde)]
pub struct Account {
    pub owner: ContractAddress,
    pub public_key: ByteArray,
}

Members

owner

The owner's contract address that controls this account. Must match the caller's address during registration.

Fully qualified path: obscura::structs::Account::owner

pub owner: ContractAddress

public_key

The public key used for encrypted communication and transaction verification. Used to encrypt transaction outputs and verify transaction signatures.

Fully qualified path: obscura::structs::Account::public_key

pub public_key: ByteArray

Enums

Event

Event definitions for the Obscura contract.These events provide transparency about contract operations while maintaining the privacy of individual transactions.

Fully qualified path: obscura::obscura::Obscura::Event

#[event]
#[derive(Drop, starknet::Event)]
pub enum Event {
    NewCommitment: NewCommitment,
    NewNullifier: NewNullifier,
    PublicKey: PublicKey,
    #[flat]
    OwnableEvent: OwnableComponent::Event,
}

Variants

NewCommitment

Emitted when a new commitment is added to the Merkle tree.

Fully qualified path: obscura::obscura::Obscura::Event::NewCommitment

NewCommitment : NewCommitment

NewNullifier

Emitted when a nullifier is used to spend an input.

Fully qualified path: obscura::obscura::Obscura::Event::NewNullifier

NewNullifier : NewNullifier

PublicKey

Emitted when a user registers their public key.

Fully qualified path: obscura::obscura::Obscura::Event::PublicKey

PublicKey : PublicKey

OwnableEvent

Ownable component events for access control.

Fully qualified path: obscura::obscura::Obscura::Event::OwnableEvent

#[flat]
OwnableEvent : OwnableComponent :: Event

Traits

I256Trait

Trait providing common operations for I256 values.This trait defines basic operations like creating a zero value and can be extended with additional utility functions.

Fully qualified path: obscura::custom_type::i256::I256Trait

pub trait I256Trait

Trait functions

zero

Creates a new I256 representing zero. # Returns * An I256 with value 0 and is_negative = false # Note Zero is always represented as positive to maintain consistency.

Fully qualified path: obscura::custom_type::i256::I256Trait::zero

fn zero() -> I256

IObscura

External interface for the Obscura privacy-preserving smart contract.This trait defines all the public functions that can be called on the Obscura contract. It provides a complete API for privacy-preserving transactions, account management, and system configuration.

Fully qualified path: obscura::interface::IObscura

pub trait IObscura<TContractState>

Trait functions

register

Registers a new account in the privacy system.This function allows users to register their public key for encrypted communication. Only the owner of the account can register it, ensuring proper key management. # Arguments * account - The account information containing owner address and public key # Events Emits a PublicKey event with the registered account information. # Security - Only the account owner can register their own account - Public key is stored for encrypted communication

Fully qualified path: obscura::interface::IObscura::register

fn register(ref self: TContractState, account: Account)

transact

Executes a privacy-preserving transaction using zero-knowledge proofs.This is the core function for privacy-preserving transactions. It verifies zero-knowledge proofs, processes token transfers, and updates the Merkle tree. # Arguments * args - The zero-knowledge proof and transaction data * ext_data - External data for deposits/withdrawals and fee handling # Process 1. Verifies the zero-knowledge proof is valid 2. Checks that input nullifiers haven't been spent 3. Processes external token transfers (deposits/withdrawals) 4. Updates the Merkle tree with new commitments 5. Emits events for commitments and nullifiers # Security - All cryptographic proofs are verified externally - Double-spending is prevented through nullifier tracking - External data consistency is enforced

Fully qualified path: obscura::interface::IObscura::transact

fn transact(ref self: TContractState, args: Proof, ext_data: ExtData)

register_and_transact

Combines account registration and transaction execution in a single call.This convenience function allows new users to register and immediately perform their first privacy-preserving transaction. # Arguments * account - The account information to register * args - The zero-knowledge proof and transaction data * ext_data - External data for deposits/withdrawals and fee handling # Process 1. Registers the account (equivalent to calling register) 2. Executes the transaction (equivalent to calling transact) # Use Case - Optimizes gas usage for new users - Reduces the number of required transactions

Fully qualified path: obscura::interface::IObscura::register_and_transact

fn register_and_transact(ref self: TContractState, account: Account, args: Proof, ext_data: ExtData)

configure_limits

Configures system limits and parameters (owner-only function).This administrative function allows the contract owner to update system parameters such as maximum deposit amounts. # Arguments * maximum_deposit_amount - The new maximum amount allowed for deposits # Access Control - Only the contract owner can call this function - Used for system maintenance and parameter updates

Fully qualified path: obscura::interface::IObscura::configure_limits

fn configure_limits(ref self: TContractState, maximum_deposit_amount: u256)

calculate_public_amount

Calculates the public amount for zero-knowledge proof verification.This function computes the public amount that must be consistent with the external data and zero-knowledge proof for transaction validation. # Arguments * ext_amount - The external amount (positive for deposits, negative for withdrawals) * fee - The transaction fee paid to the relayer # Returns * The calculated public amount for proof verification # Formula public_amount = ext_amount - fee (with proper field arithmetic)

Fully qualified path: obscura::interface::IObscura::calculate_public_amount

fn calculate_public_amount(self: @TContractState, ext_amount: I256, fee: u256) -> u256

is_spent

Checks if a nullifier has already been spent.This function verifies whether a specific nullifier has been used in a previous transaction, preventing double-spending. # Arguments * nullifier_hash - The nullifier hash to check # Returns * true if the nullifier has been spent, false otherwise # Security - Critical for preventing double-spending attacks - Used during transaction verification

Fully qualified path: obscura::interface::IObscura::is_spent

fn is_spent(self: @TContractState, nullifier_hash: u256) -> bool

field_size

Returns the finite field size used in cryptographic operations.This function provides access to the system's mathematical foundation for external verification and compatibility checks. # Returns * The field size constant used in zero-knowledge proofs

Fully qualified path: obscura::interface::IObscura::field_size

fn field_size(self: @TContractState) -> u256

max_ext_amount

Returns the maximum allowed external amount for transactions.This function provides the current system limit for deposits and withdrawals to ensure compliance. # Returns * The maximum external amount constant

Fully qualified path: obscura::interface::IObscura::max_ext_amount

fn max_ext_amount(self: @TContractState) -> u256

min_ext_amount

Returns the minimum allowed external amount for transactions.This function provides the current system minimum for deposits and withdrawals to prevent dust attacks. # Returns * The minimum external amount constant

Fully qualified path: obscura::interface::IObscura::min_ext_amount

fn min_ext_amount(self: @TContractState) -> u256

max_fee

Returns the maximum allowed fee amount for transactions.This function provides the current system limit for transaction fees to prevent economic attacks. # Returns * The maximum fee constant

Fully qualified path: obscura::interface::IObscura::max_fee

fn max_fee(self: @TContractState) -> u256

IObscuraDispatcherTrait

Fully qualified path: obscura::interface::IObscuraDispatcherTrait

pub trait IObscuraDispatcherTrait<T>

Trait functions

register

Registers a new account in the privacy system.This function allows users to register their public key for encrypted communication. Only the owner of the account can register it, ensuring proper key management. # Arguments * account - The account information containing owner address and public key # Events Emits a PublicKey event with the registered account information. # Security - Only the account owner can register their own account - Public key is stored for encrypted communication

Fully qualified path: obscura::interface::IObscuraDispatcherTrait::register

fn register(self: T, account: Account)

transact

Executes a privacy-preserving transaction using zero-knowledge proofs.This is the core function for privacy-preserving transactions. It verifies zero-knowledge proofs, processes token transfers, and updates the Merkle tree. # Arguments * args - The zero-knowledge proof and transaction data * ext_data - External data for deposits/withdrawals and fee handling # Process 1. Verifies the zero-knowledge proof is valid 2. Checks that input nullifiers haven't been spent 3. Processes external token transfers (deposits/withdrawals) 4. Updates the Merkle tree with new commitments 5. Emits events for commitments and nullifiers # Security - All cryptographic proofs are verified externally - Double-spending is prevented through nullifier tracking - External data consistency is enforced

Fully qualified path: obscura::interface::IObscuraDispatcherTrait::transact

fn transact(self: T, args: Proof, ext_data: ExtData)

register_and_transact

Combines account registration and transaction execution in a single call.This convenience function allows new users to register and immediately perform their first privacy-preserving transaction. # Arguments * account - The account information to register * args - The zero-knowledge proof and transaction data * ext_data - External data for deposits/withdrawals and fee handling # Process 1. Registers the account (equivalent to calling register) 2. Executes the transaction (equivalent to calling transact) # Use Case - Optimizes gas usage for new users - Reduces the number of required transactions

Fully qualified path: obscura::interface::IObscuraDispatcherTrait::register_and_transact

fn register_and_transact(self: T, account: Account, args: Proof, ext_data: ExtData)

configure_limits

Configures system limits and parameters (owner-only function).This administrative function allows the contract owner to update system parameters such as maximum deposit amounts. # Arguments * maximum_deposit_amount - The new maximum amount allowed for deposits # Access Control - Only the contract owner can call this function - Used for system maintenance and parameter updates

Fully qualified path: obscura::interface::IObscuraDispatcherTrait::configure_limits

fn configure_limits(self: T, maximum_deposit_amount: u256)

calculate_public_amount

Calculates the public amount for zero-knowledge proof verification.This function computes the public amount that must be consistent with the external data and zero-knowledge proof for transaction validation. # Arguments * ext_amount - The external amount (positive for deposits, negative for withdrawals) * fee - The transaction fee paid to the relayer # Returns * The calculated public amount for proof verification # Formula public_amount = ext_amount - fee (with proper field arithmetic)

Fully qualified path: obscura::interface::IObscuraDispatcherTrait::calculate_public_amount

fn calculate_public_amount(self: T, ext_amount: I256, fee: u256) -> u256

is_spent

Checks if a nullifier has already been spent.This function verifies whether a specific nullifier has been used in a previous transaction, preventing double-spending. # Arguments * nullifier_hash - The nullifier hash to check # Returns * true if the nullifier has been spent, false otherwise # Security - Critical for preventing double-spending attacks - Used during transaction verification

Fully qualified path: obscura::interface::IObscuraDispatcherTrait::is_spent

fn is_spent(self: T, nullifier_hash: u256) -> bool

field_size

Returns the finite field size used in cryptographic operations.This function provides access to the system's mathematical foundation for external verification and compatibility checks. # Returns * The field size constant used in zero-knowledge proofs

Fully qualified path: obscura::interface::IObscuraDispatcherTrait::field_size

fn field_size(self: T) -> u256

max_ext_amount

Returns the maximum allowed external amount for transactions.This function provides the current system limit for deposits and withdrawals to ensure compliance. # Returns * The maximum external amount constant

Fully qualified path: obscura::interface::IObscuraDispatcherTrait::max_ext_amount

fn max_ext_amount(self: T) -> u256

min_ext_amount

Returns the minimum allowed external amount for transactions.This function provides the current system minimum for deposits and withdrawals to prevent dust attacks. # Returns * The minimum external amount constant

Fully qualified path: obscura::interface::IObscuraDispatcherTrait::min_ext_amount

fn min_ext_amount(self: T) -> u256

max_fee

Returns the maximum allowed fee amount for transactions.This function provides the current system limit for transaction fees to prevent economic attacks. # Returns * The maximum fee constant

Fully qualified path: obscura::interface::IObscuraDispatcherTrait::max_fee

fn max_fee(self: T) -> u256

IObscuraSafeDispatcherTrait

Fully qualified path: obscura::interface::IObscuraSafeDispatcherTrait

pub trait IObscuraSafeDispatcherTrait<T>

Trait functions

register

Registers a new account in the privacy system.This function allows users to register their public key for encrypted communication. Only the owner of the account can register it, ensuring proper key management. # Arguments * account - The account information containing owner address and public key # Events Emits a PublicKey event with the registered account information. # Security - Only the account owner can register their own account - Public key is stored for encrypted communication

Fully qualified path: obscura::interface::IObscuraSafeDispatcherTrait::register

fn register(self: T, account: Account) -> starknet::SyscallResult<()>

transact

Executes a privacy-preserving transaction using zero-knowledge proofs.This is the core function for privacy-preserving transactions. It verifies zero-knowledge proofs, processes token transfers, and updates the Merkle tree. # Arguments * args - The zero-knowledge proof and transaction data * ext_data - External data for deposits/withdrawals and fee handling # Process 1. Verifies the zero-knowledge proof is valid 2. Checks that input nullifiers haven't been spent 3. Processes external token transfers (deposits/withdrawals) 4. Updates the Merkle tree with new commitments 5. Emits events for commitments and nullifiers # Security - All cryptographic proofs are verified externally - Double-spending is prevented through nullifier tracking - External data consistency is enforced

Fully qualified path: obscura::interface::IObscuraSafeDispatcherTrait::transact

fn transact(self: T, args: Proof, ext_data: ExtData) -> starknet::SyscallResult<()>

register_and_transact

Combines account registration and transaction execution in a single call.This convenience function allows new users to register and immediately perform their first privacy-preserving transaction. # Arguments * account - The account information to register * args - The zero-knowledge proof and transaction data * ext_data - External data for deposits/withdrawals and fee handling # Process 1. Registers the account (equivalent to calling register) 2. Executes the transaction (equivalent to calling transact) # Use Case - Optimizes gas usage for new users - Reduces the number of required transactions

Fully qualified path: obscura::interface::IObscuraSafeDispatcherTrait::register_and_transact

fn register_and_transact(
    self: T, account: Account, args: Proof, ext_data: ExtData,
) -> starknet::SyscallResult<()>

configure_limits

Configures system limits and parameters (owner-only function).This administrative function allows the contract owner to update system parameters such as maximum deposit amounts. # Arguments * maximum_deposit_amount - The new maximum amount allowed for deposits # Access Control - Only the contract owner can call this function - Used for system maintenance and parameter updates

Fully qualified path: obscura::interface::IObscuraSafeDispatcherTrait::configure_limits

fn configure_limits(self: T, maximum_deposit_amount: u256) -> starknet::SyscallResult<()>

calculate_public_amount

Calculates the public amount for zero-knowledge proof verification.This function computes the public amount that must be consistent with the external data and zero-knowledge proof for transaction validation. # Arguments * ext_amount - The external amount (positive for deposits, negative for withdrawals) * fee - The transaction fee paid to the relayer # Returns * The calculated public amount for proof verification # Formula public_amount = ext_amount - fee (with proper field arithmetic)

Fully qualified path: obscura::interface::IObscuraSafeDispatcherTrait::calculate_public_amount

fn calculate_public_amount(self: T, ext_amount: I256, fee: u256) -> starknet::SyscallResult<u256>

is_spent

Checks if a nullifier has already been spent.This function verifies whether a specific nullifier has been used in a previous transaction, preventing double-spending. # Arguments * nullifier_hash - The nullifier hash to check # Returns * true if the nullifier has been spent, false otherwise # Security - Critical for preventing double-spending attacks - Used during transaction verification

Fully qualified path: obscura::interface::IObscuraSafeDispatcherTrait::is_spent

fn is_spent(self: T, nullifier_hash: u256) -> starknet::SyscallResult<bool>

field_size

Returns the finite field size used in cryptographic operations.This function provides access to the system's mathematical foundation for external verification and compatibility checks. # Returns * The field size constant used in zero-knowledge proofs

Fully qualified path: obscura::interface::IObscuraSafeDispatcherTrait::field_size

fn field_size(self: T) -> starknet::SyscallResult<u256>

max_ext_amount

Returns the maximum allowed external amount for transactions.This function provides the current system limit for deposits and withdrawals to ensure compliance. # Returns * The maximum external amount constant

Fully qualified path: obscura::interface::IObscuraSafeDispatcherTrait::max_ext_amount

fn max_ext_amount(self: T) -> starknet::SyscallResult<u256>

min_ext_amount

Returns the minimum allowed external amount for transactions.This function provides the current system minimum for deposits and withdrawals to prevent dust attacks. # Returns * The minimum external amount constant

Fully qualified path: obscura::interface::IObscuraSafeDispatcherTrait::min_ext_amount

fn min_ext_amount(self: T) -> starknet::SyscallResult<u256>

max_fee

Returns the maximum allowed fee amount for transactions.This function provides the current system limit for transaction fees to prevent economic attacks. # Returns * The maximum fee constant

Fully qualified path: obscura::interface::IObscuraSafeDispatcherTrait::max_fee

fn max_fee(self: T) -> starknet::SyscallResult<u256>