Metadata-Version: 2.1
Name: pycftools
Version: 0.1.0
Summary: Additional tools for python-plugins in Cellframe ecosystem
Author-email: Demlabs <support@demlabs.net>
License: MIT License
        
        Copyright (c) 2024 Demlabs
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE. 
Project-URL: Homepage, https://gitlab.demlabs.net/cellframe/python-cellframe-modules/pycftools
Project-URL: Repository, https://gitlab.demlabs.net/cellframe/python-cellframe-modules/pycftools.git
Project-URL: Documentation, https://gitlab.demlabs.net/cellframe/python-cellframe-modules/pycftools/-/blob/main/README.md
Project-URL: Bug Tracker, https://gitlab.demlabs.net/cellframe/python-cellframe-modules/pycftools/-/issues
Keywords: cellframe,blockchain,database,orm,serialization
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Database
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
Requires-Python: >=3.7
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic <2.0.0,>=1.10.0
Requires-Dist: SQLAlchemy <2.0.0,>=1.4.0
Requires-Dist: psycopg2-binary >=2.8.0
Requires-Dist: typing-extensions >=4.0.0 ; python_version < "3.9"
Provides-Extra: dev
Requires-Dist: pytest >=7.0.0 ; extra == 'dev'
Requires-Dist: pytest-cov >=4.0.0 ; extra == 'dev'
Requires-Dist: black >=23.0.0 ; extra == 'dev'
Requires-Dist: isort >=5.12.0 ; extra == 'dev'
Requires-Dist: flake8 >=6.0.0 ; extra == 'dev'
Requires-Dist: mypy >=1.0.0 ; extra == 'dev'
Requires-Dist: pre-commit >=3.0.0 ; extra == 'dev'
Provides-Extra: test
Requires-Dist: pytest >=7.0.0 ; extra == 'test'
Requires-Dist: pytest-cov >=4.0.0 ; extra == 'test'
Requires-Dist: pytest-asyncio >=0.21.0 ; extra == 'test'

# pycftools

[![Python Version](https://img.shields.io/badge/python-3.7+-blue.svg)](https://python.org)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Build Status](https://gitlab.demlabs.net/cellframe/python-cellframe-modules/pycftools/badges/main/pipeline.svg)](https://gitlab.demlabs.net/cellframe/python-cellframe-modules/pycftools/-/pipelines)

**Additional tools for python-plugins in Cellframe ecosystem**

`pycftools` provides essential database ORM models and serialization schemas for Python plugins in the Cellframe blockchain ecosystem. It offers seamless integration with Cellframe node databases and objects while maintaining compatibility both inside and outside the Cellframe environment.

## ✨ Features

- **🗄️ Database Models**: SQLAlchemy ORM models for Cellframe PostgreSQL database
- **🔄 Serialization Schemas**: Pydantic schemas for Cellframe objects (blocks, chains, events, datums)
- **🔧 Type Definitions**: Comprehensive Enums for Cellframe data types
- **🌐 Environment Flexibility**: Works both in Cellframe node and standalone environments
- **⚡ Graceful Fallback**: Automatic detection of Cellframe availability with warning system
- **🐍 Python 3.7+ Support**: Compatible with older Python versions used in Cellframe nodes

## 📦 Installation

### For Cellframe Node Environment

```bash
/opt/cellframe-node/python/bin/pip install pycftools-0.1.0-py3-none-any.whl
```

### For Development Environment

```bash
pip install pycftools
```

## 🚀 Quick Start

```python
import pycftools

print(f"pycftools version: {pycftools.__version__}")

# Check if running in Cellframe environment
from pycftools.schemas.shortcuts import CELLFRAME_AVAILABLE
print(f"Cellframe available: {CELLFRAME_AVAILABLE}")
```

## 📚 Usage

### Database Models

Work with Cellframe database using SQLAlchemy ORM:

```python
from pycftools.database import Base, Chain, Net, Block, Event, Datum
from pycftools.config import get_database_url
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# Create database connection
engine = create_engine(get_database_url())
Session = sessionmaker(bind=engine)
session = Session()

# Query chains
chains = session.query(Chain).all()
for chain in chains:
    print(f"Chain: {chain.name}, ID: {chain.id}")

# Query recent blocks
recent_blocks = session.query(Block).order_by(Block.ts_created.desc()).limit(10).all()
```

### Serialization Schemas

Serialize Cellframe objects to dictionaries:

```python
from pycftools.schemas.serializers import Net, Chain, Block, Event, Datum

# Serialize a chain object (when running in Cellframe environment)
if CELLFRAME_AVAILABLE:
    from pycftools.schemas.shortcuts import dump
    
    # Assuming you have a CFChain object
    chain_dict = dump(cf_chain_object)
    print(chain_dict)
```

### Type Definitions

Use predefined Cellframe types:

```python
from pycftools._types import DatumTypes, ChainTypes, EventTypes

# Check datum types
if datum.type == DatumTypes.DATUM_TX:
    print("This is a transaction datum")

# Work with chain types
if chain.type == ChainTypes.esbocs:
    print("This is an esbocs chain")
```

### Configuration

Configure database connection via environment variables:

```python
from pycftools.config import DB_HOST, DB_PORT, POSTGRES_DB

print(f"Database: {POSTGRES_DB}@{DB_HOST}:{DB_PORT}")
```

## 🏗️ Project Structure

```
pycftools/
├── database/                 # SQLAlchemy ORM models
│   ├── __init__.py          # Database base and session management
│   └── models.py            # Chain, Net, Block, Event, Datum models
├── schemas/                 # Pydantic serialization schemas
│   ├── serializers/         # Object serializers
│   │   ├── block.py        # Block serialization schema
│   │   ├── chain.py        # Chain serialization schema
│   │   ├── datums.py       # Datum/Transaction serialization schema
│   │   ├── event.py        # Event serialization schema
│   │   ├── net.py          # Network serialization schema
│   │   └── sign.py         # Signature serialization schema
│   ├── deserializers/      # Object deserializers (extensible)
│   └── shortcuts.py        # Helper functions and utilities
├── _types.py               # Cellframe type definitions and Enums
└── config.py              # Configuration management
```

## ⚙️ Configuration

Set environment variables for database connection:

```bash
export POSTGRES_HOST="localhost"
export POSTGRES_PORT="5432"  
export POSTGRES_DB="cellframe"
export POSTGRES_USER="cellframe"
export POSTGRES_PASSWORD="your_password"
```

## 🌍 Environment Compatibility

### In Cellframe Node Environment

When running inside a Cellframe node, `pycftools` provides full functionality:

- ✅ Direct access to Cellframe objects (CFNet, CFChain, CFBlock, etc.)
- ✅ Full serialization/deserialization capabilities
- ✅ Database integration with node's PostgreSQL instance

### Outside Cellframe Node Environment

When running in a standalone environment:

- ✅ Database models work independently
- ✅ Schemas can be used for data validation
- ✅ Type definitions available for development
- ⚠️ Cellframe object serialization shows graceful warnings

```python
# The library automatically detects the environment
from pycftools.schemas.shortcuts import CELLFRAME_AVAILABLE

if CELLFRAME_AVAILABLE:
    print("Running in Cellframe node - full functionality available")
else:
    print("Running standalone - limited functionality with graceful fallback")
```

## 🧪 Development

### Requirements

- Python 3.7+
- SQLAlchemy 1.4+
- Pydantic 1.10+
- psycopg2-binary

### Installation for Development

```bash
git clone https://gitlab.demlabs.net/cellframe/python-cellframe-modules/pycftools.git
cd pycftools
pip install -e .
```

### Running Tests

```bash
python -m pytest tests/
```

## 📖 API Reference

### Database Models

- **`Chain`**: Blockchain chain representation
- **`Net`**: Network configuration and state
- **`Block`**: Block data and metadata
- **`Event`**: Network and consensus events
- **`Datum`**: Transaction and datum data

### Serializers

- **`schemas.serializers.Net`**: Network object serialization
- **`schemas.serializers.Chain`**: Chain object serialization  
- **`schemas.serializers.Block`**: Block object serialization
- **`schemas.serializers.Event`**: Event object serialization
- **`schemas.serializers.Datum`**: Datum/Transaction serialization

### Types

- **`DatumTypes`**: Enum for datum/transaction types
- **`ChainTypes`**: Enum for blockchain types
- **`EventTypes`**: Enum for network event types

## 🔧 Advanced Usage

### Custom Database Session

```python
from pycftools.database import Base
from pycftools.config import get_database_url
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# Custom engine with connection pooling
engine = create_engine(
    get_database_url(),
    pool_size=10,
    max_overflow=20,
    pool_recycle=3600
)

# Create custom session
CustomSession = sessionmaker(bind=engine)

with CustomSession() as session:
    # Your database operations here
    pass
```

### Schema Validation

```python
from pycftools.schemas.serializers import Block
from pydantic import ValidationError

try:
    # Validate block data
    block_data = {
        "hash": "0x123...",
        "size": 1024,
        "tx_count": 5
    }
    
    validated_block = Block(**block_data)
    print(f"Valid block: {validated_block}")
    
except ValidationError as e:
    print(f"Validation error: {e}")
```

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## 📝 License

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

## 🏢 About Demlabs

`pycftools` is developed and maintained by [Demlabs](https://demlabs.net/) as part of the Cellframe blockchain ecosystem.

- **Website**: https://demlabs.net/
- **Cellframe**: https://cellframe.net/
- **Documentation**: https://doc.cellframe.net/

## 📞 Support

- **Issues**: [GitLab Issues](https://gitlab.demlabs.net/cellframe/python-cellframe-modules/pycftools/-/issues)
- **Email**: support@demlabs.net
- **Cellframe Community**: [Telegram](https://t.me/cellframe_chain)

---

<div align="center">
  <strong>Built with ❤️ for the Cellframe ecosystem</strong>
</div>
