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:

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:

bytes

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:

bytes

Raises:

CryptographicError – If key derivation fails

nostress.core.crypto.private_key_to_hex(private_key)[source]

Convert private key to hex format.

Parameters:

private_key (bytes) – 32-byte private key

Returns:

Hex-encoded private key

Return type:

str

nostress.core.crypto.public_key_to_hex(public_key)[source]

Convert public key to hex format.

Parameters:

public_key (bytes) – 32-byte public key

Returns:

Hex-encoded public key

Return type:

str

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:

str

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:

str

Raises:

CryptographicError – If encoding fails

nostress.core.crypto.generate_keypair()[source]

Generate a complete Nostr keypair.

Returns:

(private_key, public_key)

Return type:

Tuple[bytes, bytes]

nostress.core.crypto.validate_private_key_hex(hex_key)[source]

Validate a hex-encoded private key.

Parameters:

hex_key (str) – Hex string to validate

Returns:

True if valid, False otherwise

Return type:

bool

nostress.core.crypto.validate_public_key_hex(hex_key)[source]

Validate a hex-encoded public key.

Parameters:

hex_key (str) – Hex string to validate

Returns:

True if valid, False otherwise

Return type:

bool

nostress.core.crypto.validate_bech32_key(bech32_key, expected_prefix)[source]

Validate a bech32-encoded key.

Parameters:
  • bech32_key (str) – Bech32 string to validate

  • expected_prefix (str) – Expected prefix (nsec or npub)

Returns:

True if valid, False otherwise

Return type:

bool

Data Models

Data models for keys and validation.

class nostress.core.models.KeyFormat(*values)[source]

Bases: str, Enum

Supported key formats.

HEX = 'hex'
BECH32 = 'bech32'
BOTH = 'both'
class nostress.core.models.NostrPrivateKey(**data)[source]

Bases: BaseModel

Nostr 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].

raw: bytes
classmethod validate_raw_key(v)[source]
property hex: str

Get private key in hex format.

property bech32: str

Get private key in bech32 nsec format.

to_format(format)[source]

Convert key to specified format.

Parameters:

format (KeyFormat) – Target format (hex, bech32)

Returns:

Formatted key

Return type:

str

classmethod from_hex(hex_key)[source]

Create private key from hex string.

Parameters:

hex_key (str) – Hex-encoded private key

Return type:

NostrPrivateKey

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:

NostrPrivateKey

Returns:

NostrPrivateKey instance

Raises:

KeyFormatError – If bech32 key is invalid

class nostress.core.models.NostrPublicKey(**data)[source]

Bases: BaseModel

Nostr 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].

raw: bytes
classmethod validate_raw_key(v)[source]
property hex: str

Get public key in hex format.

property bech32: str

Get public key in bech32 npub format.

to_format(format)[source]

Convert key to specified format.

Parameters:

format (KeyFormat) – Target format (hex, bech32)

Returns:

Formatted key

Return type:

str

classmethod from_hex(hex_key)[source]

Create public key from hex string.

Parameters:

hex_key (str) – Hex-encoded public key

Return type:

NostrPublicKey

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:

NostrPublicKey

Returns:

NostrPublicKey instance

Raises:

KeyFormatError – If bech32 key is invalid

class nostress.core.models.NostrKeypair(**data)[source]

Bases: BaseModel

Complete 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.

to_format(format)[source]

Convert both keys to specified format.

Parameters:

format (KeyFormat) – Target format (hex, bech32)

Returns:

Keys in specified format

Return type:

dict

classmethod generate()[source]

Generate a new random keypair.

Returns:

New random keypair

Return type:

NostrKeypair

class nostress.core.models.KeyGenerationOptions(**data)[source]

Bases: BaseModel

Options for key generation.

model_config: ClassVar[ConfigDict] = {'use_enum_values': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

format: KeyFormat
output_file: str | None
encrypt: bool
password: str | None
verbose: bool

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.echo_info(message)[source]

Print info message to stdout.

Parameters:

message (str) – Message to display

Return type:

None

nostress.cli.base.echo_success(message)[source]

Print success message to stdout.

Parameters:

message (str) – Message to display

Return type:

None

nostress.cli.base.echo_warning(message)[source]

Print warning message to stderr.

Parameters:

message (str) – Message to display

Return type:

None

nostress.cli.base.echo_error(message)[source]

Print error message to stderr.

Parameters:

message (str) – Message to display

Return type:

None

nostress.cli.base.confirm_action(message, default=False)[source]

Prompt user for confirmation.

Parameters:
  • message (str) – Confirmation message

  • default (bool) – Default value if user presses enter

Returns:

True if confirmed

Return type:

bool

nostress.cli.base.get_password(prompt='Password: ', confirm=False)[source]

Securely get password from user input.

Parameters:
  • prompt (str) – Password prompt

  • confirm (bool) – Whether to ask for confirmation

Returns:

Password entered by user

Return type:

str

nostress.cli.base.handle_exception(exc, verbose=False)[source]

Handle and display exceptions appropriately.

Parameters:
  • exc (Exception) – Exception to handle

  • verbose (bool) – Whether to show detailed error info

Return type:

None

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.write_output(content, output_path=None)[source]

Write content to file or stdout.

Parameters:
  • content (str) – Content to write

  • output_path (Path | None) – Optional file path, stdout if None

Return type:

None

nostress.cli.base.create_key_panel(title, content, style='blue')[source]

Create a formatted panel for displaying key information.

Parameters:
  • title (str) – Panel title

  • content (dict[str, Any]) – Key-value pairs to display

  • style (str) – Panel border style

Returns:

Formatted panel

Return type:

Panel

nostress.cli.base.format_keypair_output(private_key, public_key, format_name, verbose=False)[source]

Format keypair for output.

Parameters:
  • private_key (str) – Private key string

  • public_key (str) – Public key string

  • format_name (str) – Format name (hex, bech32)

  • verbose (bool) – Whether to include verbose info

Returns:

Formatted output

Return type:

str

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:

None

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:

None

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:

None

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_as_json(data, pretty=True)[source]

Format data as JSON string.

Parameters:
  • data (dict[str, Any]) – Data to format

  • pretty (bool) – Whether to pretty-print

Returns:

JSON formatted string

Return type:

str

nostress.utils.output.format_as_table(data, title=None)[source]

Format data as Rich table.

Parameters:
  • data (dict[str, Any]) – Data to format as key-value pairs

  • title (str | None) – Optional table title

Returns:

Rich table object

Return type:

Table

nostress.utils.output.format_keypair_table(private_key, public_key, format_type)[source]

Create a formatted table for keypair display.

Parameters:
  • private_key (str) – Private key string

  • public_key (str) – Public key string

  • format_type (str) – Key format (hex, bech32)

Returns:

Formatted keypair table

Return type:

Table

nostress.utils.output.create_info_panel(title, content, style='blue')[source]

Create an information panel.

Parameters:
  • title (str) – Panel title

  • content (str) – Panel content

  • style (str) – Border style

Returns:

Rich panel object

Return type:

Panel

nostress.utils.output.print_json_pretty(data, console=None)[source]

Print JSON data with syntax highlighting.

Parameters:
Return type:

None

nostress.utils.output.truncate_string(text, max_length=50, suffix='...')[source]

Truncate string to specified length.

Parameters:
  • text (str) – Text to truncate

  • max_length (int) – Maximum length

  • suffix (str) – Suffix to append if truncated

Returns:

Truncated string

Return type:

str

Input Validation

Input validation utilities.

nostress.utils.validation.validate_file_path(path, must_exist=False, must_not_exist=False)[source]

Validate file path.

Parameters:
  • path (str) – File path to validate

  • must_exist (bool) – Whether file must exist

  • must_not_exist (bool) – Whether file must not exist

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:

str

Raises:

ValidationError – If format is invalid

nostress.utils.validation.validate_hex_string(hex_str, expected_length=None)[source]

Validate hexadecimal string.

Parameters:
  • hex_str (str) – Hex string to validate

  • expected_length (int | None) – Expected length in characters

Returns:

Validated hex string

Return type:

str

Raises:

ValidationError – If validation fails

nostress.utils.validation.validate_bech32_string(bech32_str, expected_prefix=None)[source]

Validate bech32 string.

Parameters:
  • bech32_str (str) – Bech32 string to validate

  • expected_prefix (str | None) – Expected prefix (nsec, npub)

Returns:

Validated bech32 string

Return type:

str

Raises:

ValidationError – If validation fails

nostress.utils.validation.create_validator(validation_func)[source]

Create a typer-compatible validator function.

Parameters:

validation_func (Callable[[str], Any]) – Function that validates and returns the value

Returns:

Typer-compatible validator

Return type:

Callable

nostress.utils.validation.validate_hex_private_key(value)
Return type:

Any

nostress.utils.validation.validate_hex_public_key(value)
Return type:

Any

nostress.utils.validation.validate_bech32_private_key(value)
Return type:

Any

nostress.utils.validation.validate_bech32_public_key(value)
Return type:

Any

nostress.utils.validation.validate_output_file(value)
Return type:

Any

nostress.utils.validation.validate_password_strength(password, min_length=8)[source]

Validate password strength.

Parameters:
  • password (str) – Password to validate

  • min_length (int) – Minimum required length

Returns:

Validated password

Return type:

str

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: object

Configuration for nostress CLI.

default_key_format: str = 'hex'
verbose: bool = False
color_output: bool = True
require_password_confirmation: bool = True
min_password_length: int = 8
default_output_dir: str | None = None
classmethod default()[source]

Create default configuration.

Returns:

Default configuration

Return type:

NostressConfig

to_dict()[source]

Convert to dictionary.

Returns:

Configuration as dictionary

Return type:

dict

classmethod from_dict(data)[source]

Create from dictionary.

Parameters:

data (dict[str, Any]) – Configuration dictionary

Returns:

Configuration instance

Return type:

NostressConfig

__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:

NostressConfig

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:

None

nostress.utils.config.get_setting(key, default=None)[source]

Get a specific configuration setting.

Parameters:
  • key (str) – Setting key

  • default (Any) – Default value if setting not found

Returns:

Setting value or default

Return type:

Any

nostress.utils.config.set_setting(key, value)[source]

Set a specific configuration setting.

Parameters:
  • key (str) – Setting key

  • value (Any) – Setting value

Raises:

ConfigurationError – If setting cannot be saved

Return type:

None

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: Exception

Base 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: NostressError

Error 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: NostressError

Error 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: NostressError

Error 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: NostressError

Error 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.version_callback(value)[source]

Show version and exit.

nostress.main.verbose_callback(value)[source]

Set verbose mode.

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:

None

nostress.main.main()[source]

Entry point for the CLI application.

Return type:

None

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)}")