diff --git a/examples/django_server/.gitignore b/examples/django_server/.gitignore new file mode 100644 index 0000000..6061583 --- /dev/null +++ b/examples/django_server/.gitignore @@ -0,0 +1 @@ +*.sqlite3 diff --git a/examples/django_server/README.md b/examples/django_server/README.md new file mode 100644 index 0000000..4340abf --- /dev/null +++ b/examples/django_server/README.md @@ -0,0 +1,168 @@ +# Django JSON-RPC Server for py-wallet-toolbox + +This Django project provides a JSON-RPC HTTP server for BRC-100 wallet operations using py-wallet-toolbox. + +## Features + +- **JSON-RPC 2.0 API**: Standard JSON-RPC protocol for wallet operations +- **StorageProvider Integration**: Auto-registered StorageProvider methods (28 methods) +- **TypeScript Compatibility**: Compatible with ts-wallet-toolbox StorageClient +- **Django Integration**: Full Django middleware and configuration support + +## Quick Start + +### 1. Install Dependencies + +```bash +# Install core dependencies +pip install -r requirements.txt + +# Optional: Install development dependencies +pip install -r requirements-dev.txt + +# Optional: Install database backends +pip install -r requirements-db.txt +``` + +### 2. Run Migrations + +```bash +python manage.py migrate +``` + +### 3. Start Development Server + +```bash +python manage.py runserver +``` + +The server will start at `http://127.0.0.1:8000/` + +## API Endpoints + +### JSON-RPC Endpoint +- **URL**: `POST /` (TypeScript StorageServer parity) +- **Content-Type**: `application/json` +- **Protocol**: JSON-RPC 2.0 +- **Admin**: `GET /admin/` (Django admin interface) + +### Available Methods + +The server exposes all StorageProvider methods as JSON-RPC endpoints: + +- `createAction`, `internalizeAction`, `findCertificatesAuth` +- `setActive`, `getSyncChunk`, `processSyncChunk` +- And 22 other StorageProvider methods + +## Usage Examples + +### Create Action + +```bash +curl -X POST http://127.0.0.1:8000/ \ + -H "Content-Type: application/json" \ + -d '{ + "jsonrpc": "2.0", + "method": "createAction", + "params": { + "auth": {"identityKey": "your-identity-key"}, + "args": { + "description": "Test transaction", + "outputs": [ + { + "satoshis": 1000, + "lockingScript": "76a914000000000000000000000000000000000000000088ac" + } + ], + "options": { + "returnTXIDOnly": false + } + } + }, + "id": 1 + }' +``` + +### Available Methods + +The server exposes all StorageProvider methods as JSON-RPC endpoints: + +- `createAction`, `internalizeAction`, `findCertificatesAuth` +- `setActive`, `getSyncChunk`, `processSyncChunk` +- And 22 other StorageProvider methods + +Note: BRC-100 Wallet methods like `getVersion` are not available via JSON-RPC. +They are implemented in the Wallet class but not exposed through the StorageProvider interface. + +## Configuration + +### Settings + +The Django settings are configured in `wallet_server/settings.py`: + +- **DEBUG**: Development mode enabled +- **ALLOWED_HOSTS**: Localhost access allowed +- **INSTALLED_APPS**: `wallet_app` and `rest_framework` included +- **REST_FRAMEWORK**: JSON-only configuration + +### CORS Support + +For cross-origin requests, install `django-cors-headers`: + +```bash +pip install django-cors-headers +``` + +Then uncomment CORS settings in `settings.py`. + +## Development + +### Running Tests + +```bash +# Install test dependencies +pip install -r requirements-dev.txt + +# Run Django tests +python manage.py test + +# Run with pytest +pytest +``` + +### Code Quality + +```bash +# Format code +black . + +# Lint code +ruff check . + +# Type check +mypy . +``` + +## Architecture + +``` +wallet_server/ +├── wallet_app/ +│ ├── views.py # JSON-RPC endpoint +│ ├── services.py # JsonRpcServer integration +│ └── urls.py # URL configuration +├── settings.py # Django configuration +└── urls.py # Main URL routing +``` + +## TypeScript Compatibility + +This server is designed to be compatible with `ts-wallet-toolbox` StorageClient: + +- Same JSON-RPC method names (camelCase) +- Compatible request/response formats +- TypeScript StorageServer.ts equivalent functionality + +## License + +Same as py-wallet-toolbox project. diff --git a/examples/django_server/manage.py b/examples/django_server/manage.py new file mode 100755 index 0000000..832665e --- /dev/null +++ b/examples/django_server/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wallet_server.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/examples/django_server/requirements-db.txt b/examples/django_server/requirements-db.txt new file mode 100644 index 0000000..31a7927 --- /dev/null +++ b/examples/django_server/requirements-db.txt @@ -0,0 +1,8 @@ +# Database backends for Django JSON-RPC server +# SQLite is included with Python by default + +# PostgreSQL +psycopg2-binary>=2.9.0 + +# MySQL +pymysql>=1.1.0 diff --git a/examples/django_server/requirements-dev.txt b/examples/django_server/requirements-dev.txt new file mode 100644 index 0000000..c9d36d5 --- /dev/null +++ b/examples/django_server/requirements-dev.txt @@ -0,0 +1,11 @@ +# Development dependencies for Django JSON-RPC server +# Install with: pip install -r requirements-dev.txt + +# Testing +pytest>=7.0.0 +pytest-django>=4.5.0 + +# Code quality +black>=23.0.0 +ruff>=0.1.0 +mypy>=1.0.0 diff --git a/examples/django_server/requirements.txt b/examples/django_server/requirements.txt new file mode 100644 index 0000000..e595bb6 --- /dev/null +++ b/examples/django_server/requirements.txt @@ -0,0 +1,9 @@ +# Django JSON-RPC HTTP Server for py-wallet-toolbox +# Requirements for Django project providing JSON-RPC endpoints for BRC-100 wallet operations + +# Core dependencies +Django>=4.2.0 +djangorestframework>=3.14.0 + +# Local py-wallet-toolbox (with PushDrop fix) +-e ../.. diff --git a/examples/django_server/wallet_app/__init__.py b/examples/django_server/wallet_app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/examples/django_server/wallet_app/admin.py b/examples/django_server/wallet_app/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/examples/django_server/wallet_app/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/examples/django_server/wallet_app/apps.py b/examples/django_server/wallet_app/apps.py new file mode 100644 index 0000000..2bd9cbf --- /dev/null +++ b/examples/django_server/wallet_app/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class WalletAppConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'wallet_app' diff --git a/examples/django_server/wallet_app/migrations/__init__.py b/examples/django_server/wallet_app/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/examples/django_server/wallet_app/models.py b/examples/django_server/wallet_app/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/examples/django_server/wallet_app/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/examples/django_server/wallet_app/services.py b/examples/django_server/wallet_app/services.py new file mode 100644 index 0000000..feb6462 --- /dev/null +++ b/examples/django_server/wallet_app/services.py @@ -0,0 +1,76 @@ +""" +Services for wallet_app. + +This module provides service layer integration with py-wallet-toolbox, +specifically the JsonRpcServer for handling JSON-RPC requests. +""" + +import logging +import os +from typing import Optional + +from sqlalchemy import create_engine +from bsv_wallet_toolbox.rpc import JsonRpcServer +from bsv_wallet_toolbox.storage import StorageProvider + +logger = logging.getLogger(__name__) + +# Global JsonRpcServer instance +_json_rpc_server: Optional[JsonRpcServer] = None + + +def get_json_rpc_server() -> JsonRpcServer: + """ + Get or create the global JsonRpcServer instance. + + This function ensures we have a single JsonRpcServer instance + that is configured with StorageProvider methods. + + Returns: + JsonRpcServer: Configured JSON-RPC server instance + """ + global _json_rpc_server + + if _json_rpc_server is None: + logger.info("Initializing JsonRpcServer with StorageProvider") + + # Initialize StorageProvider with SQLite database + # Create database file in the project directory + db_path = os.path.join(os.path.dirname(__file__), '..', 'wallet_storage.sqlite3') + db_url = f'sqlite:///{db_path}' + + # Create SQLAlchemy engine for SQLite + engine = create_engine(db_url, echo=False) # Set echo=True for SQL logging in development + + # Initialize StorageProvider with SQLite configuration + storage_provider = StorageProvider( + engine=engine, + chain='test', # Use testnet for development + storage_identity_key='django-wallet-server' + ) + + # Initialize the database by calling make_available + # This creates tables and sets up the storage + try: + storage_provider.make_available() + logger.info("StorageProvider database initialized successfully") + except Exception as e: + logger.warning(f"StorageProvider make_available failed (may already be initialized): {e}") + + # Create JsonRpcServer with StorageProvider auto-registration + _json_rpc_server = JsonRpcServer(storage_provider=storage_provider) + + logger.info(f"JsonRpcServer initialized with SQLite database: {db_path}") + + return _json_rpc_server + + +def reset_json_rpc_server(): + """ + Reset the global JsonRpcServer instance. + + Useful for testing or reconfiguration. + """ + global _json_rpc_server + _json_rpc_server = None + logger.info("JsonRpcServer instance reset") diff --git a/examples/django_server/wallet_app/tests.py b/examples/django_server/wallet_app/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/examples/django_server/wallet_app/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/examples/django_server/wallet_app/urls.py b/examples/django_server/wallet_app/urls.py new file mode 100644 index 0000000..e154bd9 --- /dev/null +++ b/examples/django_server/wallet_app/urls.py @@ -0,0 +1,11 @@ +""" +URL configuration for wallet_app. + +Note: JSON-RPC endpoint is now configured at the root URL (/) in the main urls.py +for TypeScript StorageServer parity. This file is kept for future extensions. +""" + +# JSON-RPC endpoint moved to root URL in main urls.py +# urlpatterns = [ +# path('json-rpc/', views.json_rpc_endpoint, name='json_rpc'), +# ] diff --git a/examples/django_server/wallet_app/views.py b/examples/django_server/wallet_app/views.py new file mode 100644 index 0000000..221560c --- /dev/null +++ b/examples/django_server/wallet_app/views.py @@ -0,0 +1,75 @@ +""" +Views for wallet_app. + +This module provides JSON-RPC endpoints for BRC-100 wallet operations. +""" + +import json +import logging +from django.http import JsonResponse +from django.views.decorators.http import require_http_methods +from django.views.decorators.csrf import csrf_exempt +from django.core.exceptions import BadRequest + +from .services import get_json_rpc_server + +logger = logging.getLogger(__name__) + + +@csrf_exempt +@require_http_methods(["POST"]) +def json_rpc_endpoint(request): + """ + JSON-RPC 2.0 endpoint for wallet operations. + + Accepts JSON-RPC requests and forwards them to the JsonRpcServer. + + Request format: + { + "jsonrpc": "2.0", + "method": "createAction", + "params": {"auth": {...}, "args": {...}}, + "id": 1 + } + + Response format: + { + "jsonrpc": "2.0", + "result": {...}, + "id": 1 + } + """ + try: + # Parse JSON request body + try: + request_data = json.loads(request.body) + except json.JSONDecodeError as e: + logger.warning(f"Invalid JSON in request: {e}") + return JsonResponse({ + "jsonrpc": "2.0", + "error": { + "code": -32700, + "message": "Parse error" + }, + "id": None + }, status=400) + + # Get JsonRpcServer instance + server = get_json_rpc_server() + + # Process JSON-RPC request + response_data = server.handle_json_rpc_request(request_data) + + # Return JSON response + return JsonResponse(response_data, status=200) + + except Exception as e: + logger.error(f"Unexpected error in JSON-RPC endpoint: {e}", exc_info=True) + return JsonResponse({ + "jsonrpc": "2.0", + "error": { + "code": -32603, + "message": "Internal error" + }, + "id": None + }, status=500) diff --git a/examples/django_server/wallet_server/__init__.py b/examples/django_server/wallet_server/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/examples/django_server/wallet_server/asgi.py b/examples/django_server/wallet_server/asgi.py new file mode 100644 index 0000000..e044abd --- /dev/null +++ b/examples/django_server/wallet_server/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for wallet_server project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wallet_server.settings') + +application = get_asgi_application() diff --git a/examples/django_server/wallet_server/settings.py b/examples/django_server/wallet_server/settings.py new file mode 100644 index 0000000..ddcf6ef --- /dev/null +++ b/examples/django_server/wallet_server/settings.py @@ -0,0 +1,144 @@ +""" +Django settings for wallet_server project. + +Generated by 'django-admin startproject' using Django 5.2.8. + +For more information on this file, see +https://docs.djangoproject.com/en/5.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/5.2/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-yavde1#iud62ylvl=-twwg4!(2fyyfpkbea142bbg2ml67vs8l' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +# Allow localhost for development +ALLOWED_HOSTS = ['localhost', '127.0.0.1'] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + # Project apps + 'wallet_app', + # Third-party apps + 'rest_framework', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'wallet_server.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'wallet_server.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/5.2/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'django_admin.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/5.2/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/5.2/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' + +# REST Framework configuration +REST_FRAMEWORK = { + 'DEFAULT_RENDERER_CLASSES': [ + 'rest_framework.renderers.JSONRenderer', + ], + 'DEFAULT_PARSER_CLASSES': [ + 'rest_framework.parsers.JSONParser', + ], +} + +# CORS configuration for JSON-RPC API +# Install django-cors-headers if needed: pip install django-cors-headers +# CORS_ALLOWED_ORIGINS = [ +# "http://localhost:3000", # React dev server +# "http://127.0.0.1:3000", +# ] diff --git a/examples/django_server/wallet_server/urls.py b/examples/django_server/wallet_server/urls.py new file mode 100644 index 0000000..d634a07 --- /dev/null +++ b/examples/django_server/wallet_server/urls.py @@ -0,0 +1,26 @@ +""" +URL configuration for wallet_server project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/5.2/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path +from wallet_app import views + +urlpatterns = [ + # JSON-RPC endpoint at root (TypeScript StorageServer parity) + path('', views.json_rpc_endpoint, name='json_rpc'), + # Admin interface + path('admin/', admin.site.urls), +] diff --git a/examples/django_server/wallet_server/wsgi.py b/examples/django_server/wallet_server/wsgi.py new file mode 100644 index 0000000..e017cab --- /dev/null +++ b/examples/django_server/wallet_server/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for wallet_server project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wallet_server.settings') + +application = get_wsgi_application() diff --git a/src/bsv_wallet_toolbox/rpc/json_rpc_server.py b/src/bsv_wallet_toolbox/rpc/json_rpc_server.py index 46758a4..f37d39e 100644 --- a/src/bsv_wallet_toolbox/rpc/json_rpc_server.py +++ b/src/bsv_wallet_toolbox/rpc/json_rpc_server.py @@ -64,41 +64,6 @@ logger = logging.getLogger(__name__) -class JsonRpcParseError(Exception): - """JSON parse error (-32700).""" - - code = -32700 - message = "Parse error" - - -class JsonRpcInvalidRequestError(Exception): - """Invalid JSON-RPC request (-32600).""" - - code = -32600 - message = "Invalid Request" - - -class JsonRpcMethodNotFoundError(Exception): - """Method not found in registry (-32601).""" - - code = -32601 - message = "Method not found" - - -class JsonRpcInvalidParamsError(Exception): - """Invalid JSON-RPC parameters (-32602).""" - - code = -32602 - message = "Invalid params" - - -class JsonRpcInternalError(Exception): - """Internal server error (-32603).""" - - code = -32603 - message = "Internal error" - - class JsonRpcError(Exception): """Base class for JSON-RPC protocol errors. @@ -132,6 +97,41 @@ def to_dict(self) -> dict[str, Any]: } +class JsonRpcParseError(JsonRpcError): + """JSON parse error (-32700).""" + + code = -32700 + message = "Parse error" + + +class JsonRpcInvalidRequestError(JsonRpcError): + """Invalid JSON-RPC request (-32600).""" + + code = -32600 + message = "Invalid Request" + + +class JsonRpcMethodNotFoundError(JsonRpcError): + """Method not found in registry (-32601).""" + + code = -32601 + message = "Method not found" + + +class JsonRpcInvalidParamsError(JsonRpcError): + """Invalid JSON-RPC parameters (-32602).""" + + code = -32602 + message = "Invalid params" + + +class JsonRpcInternalError(JsonRpcError): + """Internal server error (-32603).""" + + code = -32603 + message = "Internal error" + + class JsonRpcServer: """JSON-RPC 2.0 server base class. @@ -324,40 +324,19 @@ def register_storage_provider_methods(self, storage_provider: StorageProvider) - if hasattr(storage_provider, python_method): method = getattr(storage_provider, python_method) if callable(method): - # Create wrapper that handles auth and args parameters - # Use partial to avoid closure issues with loop variables + # Create wrapper that passes params directly to storage method + # TS parity: Mirrors StorageServer.ts behavior: (this.storage as any)[method](...(params || [])) + # JSON-RPC params are passed as *args array, matching TypeScript spread operator def create_method_wrapper( storage_method: Callable[..., Any], python_method: str, - auth: dict[str, Any], - args: dict[str, Any], + *params: Any, ) -> Any: try: - # TS parity: Call storage method based on parameter requirements - if python_method in ["destroy"]: - # Methods that take no parameters or just auth - return storage_method() - elif python_method in [ - "is_storage_provider", - "is_available", - "get_services", - "get_settings", - ]: - # Methods that take only auth - return storage_method(auth) - elif python_method in ["make_available", "migrate", "set_services"]: - # Methods that take auth + config - return storage_method(auth, args) - elif python_method in [ - "find_or_insert_user", - "find_or_insert_sync_state_auth", - "set_active", - ]: - # Methods that take auth + specific args - return storage_method(auth, **args) - else: - # Default: auth + args - return storage_method(auth, args) + # TS parity: Pass params directly to storage method (same as TS spread operator) + # TypeScript: (this.storage as any)[method](...(params || [])) + # Python: storage_method(*params) + return storage_method(*params) except Exception as e: logger.error(f"Error in storage method ({python_method}): {e}") raise diff --git a/src/bsv_wallet_toolbox/storage/provider.py b/src/bsv_wallet_toolbox/storage/provider.py index 80255b8..648c626 100644 --- a/src/bsv_wallet_toolbox/storage/provider.py +++ b/src/bsv_wallet_toolbox/storage/provider.py @@ -244,11 +244,11 @@ def migrate(self) -> None: def is_storage_provider(self) -> bool: """Check if this is a StorageProvider (not StorageClient). - Returns False for StorageProvider instances. - StorageClient returns false, StorageProvider returns false. + Returns True for StorageProvider instances. + StorageClient returns false, StorageProvider returns true. Returns: - bool: Always False for StorageProvider + bool: Always True for StorageProvider Raises: N/A @@ -257,7 +257,7 @@ def is_storage_provider(self) -> bool: toolbox/ts-wallet-toolbox/src/storage/StorageProvider.ts toolbox/ts-wallet-toolbox/src/storage/remoting/StorageClient.ts """ - return False + return True def is_available(self) -> bool: """Return True if storage is initialized. diff --git a/src/bsv_wallet_toolbox/utils/identity_utils.py b/src/bsv_wallet_toolbox/utils/identity_utils.py index c5a4174..aeb1d0e 100644 --- a/src/bsv_wallet_toolbox/utils/identity_utils.py +++ b/src/bsv_wallet_toolbox/utils/identity_utils.py @@ -10,9 +10,9 @@ from typing import Any, TypedDict from bsv.auth.verifiable_certificate import VerifiableCertificate as BsvVerifiableCertificate -from bsv.script.push_drop import PushDrop -from bsv.transaction.transaction import Transaction -from bsv.utils import Utils +from bsv.transaction.pushdrop import PushDrop +from bsv.transaction import Transaction +from bsv.utils import to_utf8 class IdentityCertifier(TypedDict, total=False): @@ -252,7 +252,7 @@ async def parse_results(lookup_result: dict[str, Any]) -> list[VerifiableCertifi decoded_output = PushDrop.decode(locking_script) # Parse certificate JSON from first field - cert_json_str = Utils.to_utf8(decoded_output.fields[0]) + cert_json_str = to_utf8(decoded_output["fields"][0]) certificate_data = json.loads(cert_json_str) # Create BsvVerifiableCertificate instance using py-sdk