# 🎯 nostr-tools v1.3.0 - Enhanced Validation & Documentation

**Release Date:** November 2, 2025
**Tag:** v1.3.0
**Commit:** TBD

---

## 🚀 Overview

This release significantly enhances the validation system across all core classes with comprehensive type checking, improved error messages, and extensive documentation improvements. The update strengthens the library's robustness and developer experience while maintaining full backward compatibility.

## ✨ What's New in v1.3.0

### 🔒 Enhanced Validation System

**Comprehensive Validation Methods**
- **Filter.validate()** - Enhanced with thorough type checking for all attributes and tag validation
- **Relay.validate()** - Improved WebSocket URL validation and network type consistency checks
- **Client.validate()** - Strengthened with internal state validation (_session, _ws, _subscriptions)
- **RelayMetadata.validate()** - Enhanced with lazy loading compatibility and nested object validation
- **Consistent Error Messages** - Detailed, actionable error messages across all validation failures

**New is_valid Properties**
- **Filter.is_valid** - Safe validation check without raising exceptions
- **Relay.is_valid** - Non-throwing validation for conditional checks
- **Client.is_valid** - Exception-free validation for client instances
- **RelayMetadata.is_valid** - Safe metadata validation checks

### 📚 Documentation Enhancements

**Comprehensive Docstring Updates**
- **Filter Class** - Complete docstring overhaul with detailed examples for all methods
- **Relay Class** - Enhanced documentation with usage examples and validation scenarios
- **Client Class** - Improved method documentation and subscription management examples
- **RelayMetadata Class** - Detailed NIP-11 and NIP-66 documentation with examples
- **Utility Functions** - Internal function documentation including `count_leading_zero_bits()`

**Improved Examples**
- Added practical usage examples to all public APIs
- Enhanced error handling examples
- Better integration examples for common workflows
- Comprehensive validation examples

### 🛠️ Technical Improvements

**Type Safety**
- Lazy loading compatibility with class name comparison
- Enhanced type hints throughout validation methods
- Better type error messages for debugging

**Code Quality**
- Consistent validation patterns across all core classes
- Improved error message clarity and actionability
- Better separation of concerns in validation logic

## 🔧 Technical Details

### Enhanced Validation Implementation

**Filter Validation ([filter.py:198-277](src/nostr_tools/core/filter.py#L198-L277))**
```python
# Enhanced type checking
type_checks: list[tuple[str, Any, tuple[type, ...]]] = [
    ("ids", self.ids, (list, type(None))),
    ("authors", self.authors, (list, type(None))),
    ("kinds", self.kinds, (list, type(None))),
    ("since", self.since, (int, type(None))),
    ("until", self.until, (int, type(None))),
    ("limit", self.limit, (int, type(None))),
    ("tags", self.tags, (dict, type(None))),
]
```

**Client Validation ([client.py:140-198](src/nostr_tools/core/client.py#L140-L198))**
```python
# Internal state validation
if not isinstance(self._subscriptions, dict):
    raise ClientValidationError(
        f"_subscriptions must be dict, got {type(self._subscriptions)}"
    )
for sub_id, sub_data in self._subscriptions.items():
    if not isinstance(sub_id, str):
        raise ClientValidationError(f"Subscription ID must be str, got {type(sub_id)}")
    if not sub_data["filter"].is_valid:
        raise ClientValidationError(f"Subscription filter is invalid: {sub_data['filter']}")
```

**RelayMetadata Validation ([relay_metadata.py:54-84](src/nostr_tools/core/relay_metadata.py#L54-L84))**
```python
# Lazy loading compatibility
if not (isinstance(self.relay, Relay) or type(self.relay).__name__ == "Relay"):
    raise RelayMetadataValidationError(f"relay must be Relay, got {type(self.relay)}")

# Nested object validation
if self.nip11 is not None and not self.nip11.is_valid:
    raise RelayMetadataValidationError(f"nip11 is invalid: {self.nip11}")
```

### New is_valid Properties

**Consistent Implementation Pattern**
```python
@property
def is_valid(self) -> bool:
    """
    Check if the object is valid without raising exceptions.

    Returns:
        bool: True if validation passes, False otherwise.
    """
    try:
        self.validate()
        return True
    except ValidationError:
        return False
```

**Usage Examples**
```python
from nostr_tools import Filter, Relay, Client

# Safe validation checks
filter = Filter(kinds=[1], limit=10)
if filter.is_valid:
    events = await fetch_events(client, filter)

relay = Relay("wss://relay.damus.io")
if relay.is_valid:
    client = Client(relay)

# Conditional processing
if not metadata.is_valid:
    logger.warning(f"Invalid metadata for {metadata.relay.url}")
```

### Documentation Improvements

**Enhanced Method Documentation**
- All public methods have comprehensive docstrings
- Google-style formatting with Args, Returns, Raises, Examples
- Practical usage examples for common scenarios
- Error handling examples

**Internal Function Documentation**
- `count_leading_zero_bits()` - Proof-of-work validation helper
- Clear examples and explanations for internal utilities

## 📋 Breaking Changes

**None** - This is a fully backward-compatible release. All existing code continues to work without modification.

### API Compatibility

- All existing validation methods remain unchanged
- New `is_valid` properties are additions, not replacements
- Enhanced error messages are more descriptive but maintain exception types
- Improved documentation does not affect runtime behavior

## 🎯 Migration Guide

### From v1.2.1

**No Changes Required** - v1.3.0 is fully compatible with v1.2.1. Simply upgrade:

```bash
pip install --upgrade nostr-tools==1.3.0
```

### Using New Features

**1. Safe Validation with is_valid**

**Before (still works):**
```python
try:
    filter.validate()
    # Use filter
except FilterValidationError as e:
    print(f"Invalid filter: {e}")
```

**After (new option):**
```python
if filter.is_valid:
    # Use filter
else:
    print("Invalid filter")
```

**2. Better Error Messages**

**Before:**
```python
# Generic error messages
FilterValidationError: "Invalid filter"
```

**After:**
```python
# Detailed, actionable error messages
FilterValidationError: "ids must be (list, type(None)), got <class 'str'>"
ClientValidationError: "Subscription filter is invalid: <Filter object>"
```

**3. Comprehensive Documentation**

```python
from nostr_tools import Filter

# All methods now have detailed examples in docstrings
help(Filter.from_subscription_filter)
help(Filter.is_valid)
help(Filter.validate)
```

## 🧪 Testing & Quality

**Test Coverage**
- ✅ 541 total tests (all passing)
- ✅ 80%+ code coverage maintained
- ✅ Type checking with MyPy (strict mode)
- ✅ Linting with Ruff
- ✅ Security scanning (Bandit, Safety, pip-audit)
- ✅ All validation paths tested

**Quality Improvements**
- Enhanced validation test coverage
- Better error message validation
- Comprehensive edge case testing
- Integration test validation

## 📊 Changes Summary

**Modified Files (9 files, +396/-95 lines)**
- [src/nostr_tools/core/filter.py](src/nostr_tools/core/filter.py) - Enhanced validation and documentation
- [src/nostr_tools/core/relay.py](src/nostr_tools/core/relay.py) - Improved validation
- [src/nostr_tools/core/client.py](src/nostr_tools/core/client.py) - Strengthened client validation
- [src/nostr_tools/core/relay_metadata.py](src/nostr_tools/core/relay_metadata.py) - Comprehensive metadata validation
- [src/nostr_tools/core/event.py](src/nostr_tools/core/event.py) - Minor validation improvements
- [src/nostr_tools/utils/utils.py](src/nostr_tools/utils/utils.py) - Documentation enhancements
- Test files updated for validation coverage

## 📋 Dependencies

**No Changes**
- All dependencies remain the same as v1.2.1
- No new dependencies added
- No dependency updates required

**Runtime Dependencies**
- secp256k1 >=0.14.0, <1.0.0
- bech32 >=1.2.0, <2.0.0
- aiohttp >=3.8.0, <4.0.0
- aiohttp-socks >=0.8.0, <1.0.0

## 🚀 Development Experience

**Improved Developer Workflow**
- Better error messages for faster debugging
- Safe validation with `is_valid` properties
- Comprehensive documentation in IDE tooltips
- Consistent validation patterns across codebase

**Documentation Updates**
- Updated CHANGELOG.md with v1.3.0 details
- Updated SECURITY.md supported versions (v1.3.0 only)
- Updated releases/README.md
- All previous versions (v1.2.1, v1.2.0, v1.1.x, v1.0.x) marked as EOL

## ⚠️ Version Support Policy

**Important: All Previous Versions Are Now EOL**

| Version | Support Status | End of Life |
|---------|----------------|-------------|
| 1.3.0   | ✅ **Only Supported** | TBD |
| 1.2.1   | ❌ End of Life | 2025-11-02 |
| 1.2.0   | ❌ End of Life | 2025-10-05 |
| 1.1.x   | ❌ End of Life | 2025-10-04 |
| 1.0.x   | ❌ End of Life | 2025-10-04 |
| 0.x.x   | ❌ End of Life | 2025-09-14 |

**Migration Required**: All users must upgrade to v1.3.0 for continued support, security updates, and bug fixes.

## 🤝 Contributing

We welcome contributions and feedback from the community. v1.3.0 is now the only supported version.

**Getting Started**
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Run `make check-all` to verify quality
5. Submit a pull request

**Development Commands**
```bash
# Install development dependencies
make install-dev

# Run tests
make test

# Run quality checks
make check-all

# Build documentation
make docs-build
```

## 🔐 Security

**No Security Vulnerabilities Fixed**
- This release focuses on validation improvements and documentation
- All security best practices from v1.2.1 continue to apply
- For security issues, email: security@bigbrotr.com

**Enhanced Security Through Validation**
- Stronger type checking prevents invalid data
- Better error messages aid in security debugging
- Comprehensive validation reduces attack surface

## 📄 License

This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.

## 🙏 Acknowledgments

- **Contributors** - All contributors to this project
- **Community** - Feedback and suggestions from the Nostr community
- **Python Ecosystem** - The amazing tools and libraries that make this possible

## 🔗 Links

- **[PyPI Package](https://pypi.org/project/nostr-tools/)** - Install from PyPI
- **[GitHub Repository](https://github.com/bigbrotr/nostr-tools)** - Source code and issues
- **[Documentation](https://bigbrotr.github.io/nostr-tools/)** - Complete API reference
- **[Changelog](../CHANGELOG.md)** - Detailed changelog
- **[Security Policy](../SECURITY.md)** - Security information

---

**🎯 This release significantly enhances validation robustness and documentation quality while maintaining full backward compatibility. All previous versions are now end-of-life.**
