API Reference¶
This section provides comprehensive API documentation for all Nostress modules, automatically generated from docstrings in the source code.
Overview¶
Nostress is organized into several main modules:
nostress.core- Core cryptographic functionality and data modelsnostress.cli- Command-line interface implementationsnostress.utils- Utility functions for validation, output, and configurationnostress.exceptions- Custom exception classes
Core Module¶
The core module contains the fundamental cryptographic operations and data models.
Core business logic for Nostr cryptographic operations.
This module contains the fundamental cryptographic functionality and data models that power nostress. It provides secure key generation, format conversion, and validation capabilities for the Nostr protocol.
- Modules:
crypto: Low-level cryptographic operations using the cryptography library models: Pydantic data models for keys and validation
- Key Features:
Secure key generation using cryptographically secure random numbers
Support for both hexadecimal and bech32 key formats
Comprehensive input validation and error handling
Type-safe data models with automatic validation
Example
from nostress.core.models import NostrKeypair
# Generate a new keypair keypair = NostrKeypair.generate()
# Access keys in different formats private_hex = keypair.private_key.hex public_bech32 = keypair.public_key.bech32
Cryptographic Operations¶
Cryptographic operations for Nostr key generation.
- nostress.core.crypto.generate_private_key()[source]¶
Generate a secure 32-byte private key.
- Returns:
A secure random 32-byte private key
- Return type:
- nostress.core.crypto.derive_public_key(private_key)[source]¶
Derive public key from private key using secp256k1.
- Parameters:
private_key (
bytes) – 32-byte private key- Returns:
32-byte public key (x-coordinate only)
- Return type:
- Raises:
CryptographicError – If key derivation fails
- nostress.core.crypto.private_key_to_bech32(private_key)[source]¶
Convert private key to bech32 nsec format (NIP-19).
- Parameters:
private_key (
bytes) – 32-byte private key- Returns:
Bech32-encoded private key with nsec prefix
- Return type:
- Raises:
CryptographicError – If encoding fails
- nostress.core.crypto.public_key_to_bech32(public_key)[source]¶
Convert public key to bech32 npub format (NIP-19).
- Parameters:
public_key (
bytes) – 32-byte public key- Returns:
Bech32-encoded public key with npub prefix
- Return type:
- Raises:
CryptographicError – If encoding fails
Data Models¶
Data models for keys and validation.
- class nostress.core.models.KeyFormat(*values)[source]¶
-
Supported key formats.
- HEX = 'hex'¶
- BECH32 = 'bech32'¶
- BOTH = 'both'¶
- class nostress.core.models.NostrPrivateKey(**data)[source]¶
Bases:
BaseModelNostr private key with format validation.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod from_hex(hex_key)[source]¶
Create private key from hex string.
- Parameters:
hex_key (
str) – Hex-encoded private key- Return type:
- Returns:
NostrPrivateKey instance
- Raises:
KeyFormatError – If hex key is invalid
- classmethod from_bech32(bech32_key)[source]¶
Create private key from bech32 string.
- Parameters:
bech32_key (
str) – Bech32-encoded private key (nsec…)- Return type:
- Returns:
NostrPrivateKey instance
- Raises:
KeyFormatError – If bech32 key is invalid
- class nostress.core.models.NostrPublicKey(**data)[source]¶
Bases:
BaseModelNostr public key with format validation.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod from_hex(hex_key)[source]¶
Create public key from hex string.
- Parameters:
hex_key (
str) – Hex-encoded public key- Return type:
- Returns:
NostrPublicKey instance
- Raises:
KeyFormatError – If hex key is invalid
- classmethod from_bech32(bech32_key)[source]¶
Create public key from bech32 string.
- Parameters:
bech32_key (
str) – Bech32-encoded public key (npub…)- Return type:
- Returns:
NostrPublicKey instance
- Raises:
KeyFormatError – If bech32 key is invalid
- class nostress.core.models.NostrKeypair(**data)[source]¶
Bases:
BaseModelComplete Nostr keypair with private and public keys.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- private_key: NostrPrivateKey¶
- public_key: NostrPublicKey¶
- classmethod validate_keypair_consistency(public_key, info)[source]¶
Ensure public key matches private key.
CLI Module¶
The CLI module contains the command-line interface implementations.
Command-line interface implementations for nostress.
This package contains all CLI command implementations and utilities that provide the user-facing interface for nostress. Built using Typer for modern, type-safe command-line interface development.
- Modules:
base: Common CLI utilities and helper functions keys: Key management commands (generate, validate, convert)
- Features:
Rich terminal output with tables and formatting
Type-safe command arguments and options
Comprehensive help and error messages
File input/output operations
Verbose mode support
Example
from nostress.cli.keys import generate_command
# Commands are typically invoked through the main CLI app # but can also be used programmatically
Base CLI Utilities¶
Common CLI utilities and base functionality.
- nostress.cli.base.get_password(prompt='Password: ', confirm=False)[source]¶
Securely get password from user input.
- nostress.cli.base.handle_exception(exc, verbose=False)[source]¶
Handle and display exceptions appropriately.
- nostress.cli.base.validate_output_path(path)[source]¶
Validate and return output file path.
- Parameters:
path (
str) – File path to validate- Returns:
Validated path object
- Return type:
Path
- Raises:
typer.BadParameter – If path is invalid
- nostress.cli.base.create_key_panel(title, content, style='blue')[source]¶
Create a formatted panel for displaying key information.
Key Management Commands¶
Key generation and management commands.
- nostress.cli.keys.generate(format=<typer.models.OptionInfo object>, output=<typer.models.OptionInfo object>, encrypt=<typer.models.OptionInfo object>, json_output=<typer.models.OptionInfo object>)[source]¶
Generate a new Nostr keypair.
Generates a cryptographically secure keypair for use with the Nostr protocol. Private keys are 32 bytes of entropy, public keys are derived using secp256k1.
- Return type:
Examples
nostress keys generate nostress keys generate –format bech32 nostress keys generate –format both –output keypair.txt nostress keys generate –encrypt –output encrypted_key.txt
- nostress.cli.keys.validate(key=<typer.models.ArgumentInfo object>, key_type=<typer.models.OptionInfo object>)[source]¶
Validate a Nostr key format.
Validates that a key string is in correct format and potentially valid for use with the Nostr protocol.
- Return type:
Examples
nostress keys validate abc123…def nostress keys validate nsec1… –type nsec nostress keys validate npub1… –type npub
- nostress.cli.keys.convert(key=<typer.models.ArgumentInfo object>, target_format=<typer.models.OptionInfo object>, key_type=<typer.models.OptionInfo object>, output=<typer.models.OptionInfo object>, json_output=<typer.models.OptionInfo object>)[source]¶
Convert key between hex and bech32 formats.
Converts keys between hexadecimal and bech32 (nsec/npub) formats. Bech32 keys (nsec/npub prefixed) are automatically detected. Hex keys require –type flag to specify private or public.
- Return type:
Examples
nostress keys convert abc123…def –to bech32 –type private nostress keys convert nsec1… –to hex nostress keys convert npub1… –to hex –json nostress keys convert nsec1… –to hex –output converted.txt
Utilities Module¶
The utils module provides supporting functionality for validation, output formatting, and configuration management.
Utilities and helper functions for nostress.
This package contains utility modules that provide supporting functionality across the nostress application, including validation, output formatting, and configuration management.
- Modules:
config: Configuration management with XDG Base Directory compliance output: Rich formatting utilities for tables, JSON, and console output validation: Input validation functions with Typer integration
- Features:
Type-safe input validation with clear error messages
Rich terminal formatting with tables and colors
JSON output support for automation and scripting
XDG-compliant configuration directory management
Cross-platform file system utilities
Example
from nostress.utils.output import format_keypair_table from nostress.utils.validation import validate_key_format
# Format keypair for display table = format_keypair_table(private_key, public_key, “hex”)
# Validate user input format = validate_key_format(“hex”)
Output Formatting¶
Output formatting utilities.
- nostress.utils.output.format_keypair_table(private_key, public_key, format_type)[source]¶
Create a formatted table for keypair display.
- nostress.utils.output.create_info_panel(title, content, style='blue')[source]¶
Create an information panel.
Input Validation¶
Input validation utilities.
- nostress.utils.validation.validate_file_path(path, must_exist=False, must_not_exist=False)[source]¶
Validate file path.
- Parameters:
- Returns:
Validated path object
- Return type:
Path
- Raises:
ValidationError – If validation fails
- nostress.utils.validation.validate_key_format(format_str)[source]¶
Validate key format string.
- Parameters:
format_str (
str) – Format string to validate- Returns:
Validated format string
- Return type:
- Raises:
ValidationError – If format is invalid
- nostress.utils.validation.validate_hex_string(hex_str, expected_length=None)[source]¶
Validate hexadecimal string.
- Parameters:
- Returns:
Validated hex string
- Return type:
- Raises:
ValidationError – If validation fails
- nostress.utils.validation.validate_bech32_string(bech32_str, expected_prefix=None)[source]¶
Validate bech32 string.
- Parameters:
- Returns:
Validated bech32 string
- Return type:
- Raises:
ValidationError – If validation fails
- nostress.utils.validation.create_validator(validation_func)[source]¶
Create a typer-compatible validator function.
- nostress.utils.validation.validate_password_strength(password, min_length=8)[source]¶
Validate password strength.
- Parameters:
- Returns:
Validated password
- Return type:
- Raises:
ValidationError – If password is too weak
Configuration Management¶
Configuration management.
- class nostress.utils.config.NostressConfig(default_key_format='hex', verbose=False, color_output=True, require_password_confirmation=True, min_password_length=8, default_output_dir=None)[source]¶
Bases:
objectConfiguration for nostress CLI.
- classmethod default()[source]¶
Create default configuration.
- Returns:
Default configuration
- Return type:
- classmethod from_dict(data)[source]¶
Create from dictionary.
- Parameters:
- Returns:
Configuration instance
- Return type:
- __init__(default_key_format='hex', verbose=False, color_output=True, require_password_confirmation=True, min_password_length=8, default_output_dir=None)¶
- nostress.utils.config.get_config_dir()[source]¶
Get configuration directory path.
- Returns:
Configuration directory
- Return type:
Path
- nostress.utils.config.get_config_file_path()[source]¶
Get configuration file path.
- Returns:
Configuration file path
- Return type:
Path
- nostress.utils.config.load_config()[source]¶
Load configuration from file.
- Returns:
Loaded configuration or default if file doesn’t exist
- Return type:
- Raises:
ConfigurationError – If configuration file is invalid
- nostress.utils.config.save_config(config)[source]¶
Save configuration to file.
- Parameters:
config (
NostressConfig) – Configuration to save- Raises:
ConfigurationError – If saving fails
- Return type:
Exception Classes¶
Custom exceptions for nostress.
This module defines the exception hierarchy used throughout nostress for consistent error handling and user feedback.
- Exception Hierarchy:
NostressError ├── CryptographicError ├── KeyFormatError ├── ValidationError └── ConfigurationError
- exception nostress.exceptions.NostressError[source]¶
Bases:
ExceptionBase exception for all nostress-specific errors.
This is the root exception class from which all other nostress exceptions inherit. It provides a common base for catching any nostress-related error.
Example
- try:
keypair = NostrKeypair.generate()
- except NostressError as e:
print(f”Nostress error occurred: {e}”)
- exception nostress.exceptions.CryptographicError[source]¶
Bases:
NostressErrorError in cryptographic operations.
Raised when cryptographic operations fail, such as: - Key generation failures - Invalid cryptographic parameters - Elliptic curve operation errors - Encoding/decoding failures in crypto contexts
Example
- try:
public_key = derive_public_key(invalid_private_key)
- except CryptographicError as e:
print(f”Crypto operation failed: {e}”)
- exception nostress.exceptions.KeyFormatError[source]¶
Bases:
NostressErrorError in key format validation.
Raised when key strings are not properly formatted, such as: - Invalid hexadecimal characters in hex keys - Wrong key length (not 64 characters for hex) - Invalid bech32 prefixes (not nsec1…/npub1…) - Malformed bech32 encoding
Example
- try:
key = NostrPrivateKey.from_hex(“invalid_hex”)
- except KeyFormatError as e:
print(f”Invalid key format: {e}”)
- exception nostress.exceptions.ValidationError[source]¶
Bases:
NostressErrorError in input validation.
Raised when user inputs fail validation, such as: - Invalid command-line arguments - File path validation failures - Parameter constraint violations - Type validation errors
Example
- try:
validate_output_path(“/invalid/path”)
- except ValidationError as e:
print(f”Validation failed: {e}”)
- exception nostress.exceptions.ConfigurationError[source]¶
Bases:
NostressErrorError in configuration management.
Raised when configuration-related operations fail, such as: - Invalid configuration file format - Missing required configuration values - File system permission errors for config directories - XDG directory creation failures
Example
- try:
config = load_config()
- except ConfigurationError as e:
print(f”Configuration error: {e}”)
Main Entry Point¶
Main CLI application entry point.
- nostress.main.main_callback(version=<typer.models.OptionInfo object>, verbose=<typer.models.OptionInfo object>)[source]¶
Modern Python CLI for Nostr interactions.
This CLI provides tools for: • Generating and managing Nostr keypairs • Creating and signing Nostr events • Interacting with Nostr relays
- Return type:
Examples¶
Basic Usage Examples¶
Generate a keypair programmatically:
from nostress.core.models import NostrKeypair
# Generate a new keypair
keypair = NostrKeypair.generate()
# Access the keys
private_hex = keypair.private_key.hex
public_hex = keypair.public_key.hex
private_bech32 = keypair.private_key.bech32
public_bech32 = keypair.public_key.bech32
print(f"Private (hex): {private_hex}")
print(f"Public (bech32): {public_bech32}")
Validate keys:
from nostress.core.models import NostrPrivateKey, NostrPublicKey
from nostress.exceptions import KeyFormatError
try:
# Validate a hex private key
private_key = NostrPrivateKey.from_hex("a1b2c3d4...")
print("Private key is valid")
# Validate a bech32 public key
public_key = NostrPublicKey.from_bech32("npub1...")
print("Public key is valid")
except KeyFormatError as e:
print(f"Key validation failed: {e}")
Advanced Cryptographic Operations¶
Use low-level crypto functions:
from nostress.core import crypto
# Generate raw private key bytes
private_bytes = crypto.generate_private_key()
# Derive public key
public_bytes = crypto.derive_public_key(private_bytes)
# Convert to different formats
hex_key = crypto.bytes_to_hex(private_bytes)
bech32_key = crypto.encode_bech32("nsec", private_bytes)
print(f"Generated key: {hex_key}")
print(f"Bech32 format: {bech32_key}")
Configuration Management¶
Work with configuration:
from nostress.utils.config import load_config, get_data_dir
# Load user configuration
config = load_config()
# Get data directory
data_dir = get_data_dir()
print(f"Data directory: {data_dir}")
Output Formatting¶
Use Rich formatting utilities:
from nostress.utils.output import create_keypair_table, output_json
from nostress.core.models import NostrKeypair
from rich.console import Console
# Create a keypair
keypair = NostrKeypair.generate()
# Display as Rich table
console = Console()
table = create_keypair_table(keypair)
console.print(table)
# Output as JSON
json_str = output_json(keypair)
print(json_str)
Type Information¶
Nostress extensively uses type hints for better development experience:
Key Types¶
from typing import Union
from nostress.core.models import NostrPrivateKey, NostrPublicKey
# Union type for any key
AnyKey = Union[NostrPrivateKey, NostrPublicKey]
# Function with type hints
def process_key(key: AnyKey) -> str:
return key.hex
Error Handling¶
from nostress.exceptions import (
NostrError,
CryptographicError,
KeyFormatError,
ValidationError
)
try:
# Some operation that might fail
result = some_crypto_operation()
except CryptographicError as e:
print(f"Crypto error: {e}")
except KeyFormatError as e:
print(f"Key format error: {e}")
except ValidationError as e:
print(f"Validation error: {e}")
except NostrError as e:
print(f"General Nostress error: {e}")
Testing Integration¶
Example of using Nostress in tests:
import pytest
from nostress.core.models import NostrKeypair
from nostress.exceptions import KeyFormatError
def test_keypair_generation():
"""Test that keypair generation works correctly."""
keypair = NostrKeypair.generate()
# Verify keys are properly formatted
assert len(keypair.private_key.hex) == 64
assert len(keypair.public_key.hex) == 64
assert keypair.private_key.bech32.startswith("nsec1")
assert keypair.public_key.bech32.startswith("npub1")
def test_invalid_key_format():
"""Test that invalid keys raise appropriate errors."""
with pytest.raises(KeyFormatError):
NostrPrivateKey.from_hex("invalid")
Integration Examples¶
Web Application Integration:
from fastapi import FastAPI, HTTPException
from nostress.core.models import NostrKeypair
from nostress.exceptions import NostrError
app = FastAPI()
@app.post("/generate-keypair")
async def generate_keypair():
try:
keypair = NostrKeypair.generate()
return {
"private_key": keypair.private_key.bech32,
"public_key": keypair.public_key.bech32
}
except NostrError as e:
raise HTTPException(status_code=500, detail=str(e))
Performance Considerations¶
For high-performance applications:
import time
from nostress.core.models import NostrKeypair
# Benchmark key generation
start_time = time.time()
keypairs = []
for _ in range(1000):
keypair = NostrKeypair.generate()
keypairs.append(keypair)
end_time = time.time()
print(f"Generated 1000 keypairs in {end_time - start_time:.2f} seconds")
Development Utilities¶
For development and debugging:
import os
from nostress.core.models import NostrKeypair
from nostress.utils.output import create_keypair_table
from rich.console import Console
# Enable verbose mode
os.environ["NOSTRESS_VERBOSE"] = "1"
# Generate and display keypair with full information
keypair = NostrKeypair.generate()
console = Console()
table = create_keypair_table(keypair)
console.print(table)
# Display internal properties
print(f"Private key bytes length: {len(keypair.private_key._private_bytes)}")
print(f"Public key bytes length: {len(keypair.public_key._public_bytes)}")