diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..36e674b --- /dev/null +++ b/.env.example @@ -0,0 +1,20 @@ +DATABASE_URL=sqlite+aiosqlite:///./plm_lottery.db + +ELECTRUM_HOST=santantonio.sytes.net +ELECTRUM_PORT=50002 +ELECTRUM_USE_SSL=true + +# Fernet key protecting the master xprv at rest. Generate with: +# python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())" +XPRV_ENCRYPTION_KEY= +MASTER_KEY_PATH=./master.xprv.enc + +# Random secret for JWT session signing. Generate with: +# python -c "import secrets; print(secrets.token_urlsafe(32))" +JWT_SECRET= + +# Bearer token required on the admin endpoints (X-Admin-Token header). Generate with: +# python -c "import secrets; print(secrets.token_urlsafe(32))" +ADMIN_TOKEN= + +ROUND_DURATION_SECONDS=600 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ac30ea9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.venv/ +__pycache__/ +*.pyc +.env +*.db +master.xprv.enc +.pytest_cache/ +*.egg-info/ diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..6a15082 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,149 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts. +# this is typically a path given in POSIX (e.g. forward slashes) +# format, relative to the token %(here)s which refers to the location of this +# ini file +script_location = %(here)s/migrations + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s +# Or organize into date-based subdirectories (requires recursive_version_locations = true) +# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. for multiple paths, the path separator +# is defined by "path_separator" below. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the tzdata library which can be installed by adding +# `alembic[tz]` to the pip requirements. +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to /versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "path_separator" +# below. +# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions + +# path_separator; This indicates what character is used to split lists of file +# paths, including version_locations and prepend_sys_path within configparser +# files such as alembic.ini. +# The default rendered in new alembic.ini files is "os", which uses os.pathsep +# to provide os-dependent path splitting. +# +# Note that in order to support legacy alembic.ini files, this default does NOT +# take place if path_separator is not present in alembic.ini. If this +# option is omitted entirely, fallback logic is as follows: +# +# 1. Parsing of the version_locations option falls back to using the legacy +# "version_path_separator" key, which if absent then falls back to the legacy +# behavior of splitting on spaces and/or commas. +# 2. Parsing of the prepend_sys_path option falls back to the legacy +# behavior of splitting on spaces, commas, or colons. +# +# Valid values for path_separator are: +# +# path_separator = : +# path_separator = ; +# path_separator = space +# path_separator = newline +# +# Use os.pathsep. Default configuration used for new projects. +path_separator = os + + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# database URL. This is consumed by the user-maintained env.py script only. +# other means of configuring database URLs may be customized within the env.py +# file. +sqlalchemy.url = driver://user:pass@localhost/dbname + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module +# hooks = ruff +# ruff.type = module +# ruff.module = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Alternatively, use the exec runner to execute a binary found on your PATH +# hooks = ruff +# ruff.type = exec +# ruff.executable = ruff +# ruff.options = check --fix REVISION_SCRIPT_FILENAME + +# Logging configuration. This is also consumed by the user-maintained +# env.py script only. +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/routes/__init__.py b/app/api/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000..f1bbf52 --- /dev/null +++ b/app/config.py @@ -0,0 +1,29 @@ +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + model_config = SettingsConfigDict(env_file=".env", extra="ignore") + + database_url: str = "sqlite+aiosqlite:///./plm_lottery.db" + + electrum_host: str = "santantonio.sytes.net" + electrum_port: int = 50002 + electrum_use_ssl: bool = True + + xprv_encryption_key: str = "" + master_key_path: str = "./master.xprv.enc" + jwt_secret: str = "" + jwt_algorithm: str = "HS256" + jwt_expire_minutes: int = 60 * 24 + admin_token: str = "" + + round_duration_seconds: int = 600 + + bet_amount_sats: int = 10 * 100_000_000 + min_amount_sats: int = 1 * 100_000_000 + confirmations_required: int = 1 + fee_rate_sat_vb: int = 1 + rbf_timeout_seconds: int = 900 + + +settings = Settings() diff --git a/app/db/__init__.py b/app/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000..cac5738 --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,11 @@ +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine +from sqlalchemy.orm import DeclarativeBase + +from app.config import settings + +engine = create_async_engine(settings.database_url) +AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False) + + +class Base(DeclarativeBase): + pass diff --git a/app/db/models.py b/app/db/models.py new file mode 100644 index 0000000..12790ba --- /dev/null +++ b/app/db/models.py @@ -0,0 +1,131 @@ +from datetime import datetime, timezone + +from sqlalchemy import BigInteger, ForeignKey, String, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column + +from app.db.base import Base + + +def utcnow() -> datetime: + return datetime.now(timezone.utc) + + +class User(Base): + __tablename__ = "users" + + id: Mapped[int] = mapped_column(primary_key=True) + username: Mapped[str] = mapped_column(String(64), unique=True, index=True) + password_hash: Mapped[str] = mapped_column(String(256)) + derivation_index: Mapped[int] = mapped_column(unique=True) + address: Mapped[str] = mapped_column(String(128), unique=True) + # Read cache only; must always be written in the same transaction as the + # utxo_events rows it summarizes. Source of truth is utxo_events. + cached_balance_sats: Mapped[int] = mapped_column(BigInteger, default=0) + created_at: Mapped[datetime] = mapped_column(default=utcnow) + + +class UtxoEvent(Base): + __tablename__ = "utxo_events" + __table_args__ = (UniqueConstraint("txid", "vout"),) + + id: Mapped[int] = mapped_column(primary_key=True) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True) + txid: Mapped[str] = mapped_column(String(64)) + vout: Mapped[int] + amount_sats: Mapped[int] = mapped_column(BigInteger) + confirmed_height: Mapped[int] + confirmed_at: Mapped[datetime] = mapped_column(default=utcnow) + # Set once this UTXO is consumed by an outgoing bet/withdrawal build. + spent_txid: Mapped[str | None] = mapped_column(String(64), default=None) + + +class Round(Base): + __tablename__ = "rounds" + + id: Mapped[int] = mapped_column(primary_key=True) + status: Mapped[str] = mapped_column(String(16), default="open") + opened_at: Mapped[datetime] = mapped_column(default=utcnow) + closed_at: Mapped[datetime | None] = mapped_column(default=None) + draw_block_height: Mapped[int | None] = mapped_column(default=None) + draw_block_hash: Mapped[str | None] = mapped_column(String(64), default=None) + seed_int: Mapped[str | None] = mapped_column(String(128), default=None) + winner_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), default=None) + pool_amount_sats: Mapped[int | None] = mapped_column(BigInteger, default=None) + winner_amount_sats: Mapped[int | None] = mapped_column(BigInteger, default=None) + fee_amount_sats: Mapped[int | None] = mapped_column(BigInteger, default=None) + payout_txid: Mapped[str | None] = mapped_column(String(64), default=None) + + +class RoundParticipant(Base): + __tablename__ = "round_participants" + __table_args__ = (UniqueConstraint("round_id", "user_id"),) + + id: Mapped[int] = mapped_column(primary_key=True) + round_id: Mapped[int] = mapped_column(ForeignKey("rounds.id"), index=True) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True) + bet_amount_sats: Mapped[int] = mapped_column(BigInteger) + bet_txid: Mapped[str] = mapped_column(String(64)) + # Ordering / tie-break field per spec: broadcast time, not confirmation time. + broadcast_at: Mapped[datetime] = mapped_column(default=utcnow) + confirmed_at: Mapped[datetime | None] = mapped_column(default=None) + status: Mapped[str] = mapped_column(String(16), default="broadcast") + + +class RoundConfig(Base): + """Single-row operational config, DB-backed so it's editable without a redeploy. + + round_duration is intentionally NOT here: it stays env-var-driven per spec. + Don't move it here without an explicit decision to change that. + """ + + __tablename__ = "round_config" + + id: Mapped[int] = mapped_column(primary_key=True) + fee_address: Mapped[str] = mapped_column(String(128)) + bet_amount_sats: Mapped[int] = mapped_column(BigInteger) + updated_at: Mapped[datetime] = mapped_column(default=utcnow, onupdate=utcnow) + + +class PendingTransaction(Base): + """Single source of truth for the RBF timeout->bump->rebroadcast loop.""" + + __tablename__ = "pending_transactions" + + id: Mapped[int] = mapped_column(primary_key=True) + kind: Mapped[str] = mapped_column(String(16)) # bet | payout | withdrawal + round_id: Mapped[int | None] = mapped_column(ForeignKey("rounds.id"), default=None) + withdrawal_id: Mapped[int | None] = mapped_column(ForeignKey("withdrawals.id"), default=None) + user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), default=None) + current_txid: Mapped[str] = mapped_column(String(64)) + fee_rate_sat_vb: Mapped[int] + raw_tx_hex: Mapped[str] = mapped_column(String) + broadcast_at: Mapped[datetime] = mapped_column(default=utcnow) + status: Mapped[str] = mapped_column(String(16), default="pending") + replaced_by_txid: Mapped[str | None] = mapped_column(String(64), default=None) + attempt_count: Mapped[int] = mapped_column(default=1) + updated_at: Mapped[datetime] = mapped_column(default=utcnow, onupdate=utcnow) + + +class Withdrawal(Base): + __tablename__ = "withdrawals" + + id: Mapped[int] = mapped_column(primary_key=True) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True) + external_address: Mapped[str] = mapped_column(String(128)) + amount_requested_sats: Mapped[int] = mapped_column(BigInteger) + amount_sent_sats: Mapped[int | None] = mapped_column(BigInteger, default=None) + txid: Mapped[str | None] = mapped_column(String(64), default=None) + status: Mapped[str] = mapped_column(String(16), default="pending") + created_at: Mapped[datetime] = mapped_column(default=utcnow) + confirmed_at: Mapped[datetime | None] = mapped_column(default=None) + + +class AuditLog(Base): + __tablename__ = "audit_log" + + id: Mapped[int] = mapped_column(primary_key=True) + event_type: Mapped[str] = mapped_column(String(32)) + payload_json: Mapped[str] = mapped_column(String) + user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), default=None) + round_id: Mapped[int | None] = mapped_column(ForeignKey("rounds.id"), default=None) + created_at: Mapped[datetime] = mapped_column(default=utcnow) diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..46a5245 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,10 @@ +from collections.abc import AsyncGenerator + +from sqlalchemy.ext.asyncio import AsyncSession + +from app.db.base import AsyncSessionLocal + + +async def get_session() -> AsyncGenerator[AsyncSession, None]: + async with AsyncSessionLocal() as session: + yield session diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..e0d0858 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration with an async dbapi. \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..0df7a1f --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,85 @@ +import asyncio +from logging.config import fileConfig + +from sqlalchemy import pool +from sqlalchemy.engine import Connection +from sqlalchemy.ext.asyncio import async_engine_from_config + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +from app.config import settings +from app.db.base import Base +from app.db import models # noqa: F401 (registers models on Base.metadata) + +target_metadata = Base.metadata +config.set_main_option("sqlalchemy.url", settings.database_url) + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def do_run_migrations(connection: Connection) -> None: + context.configure(connection=connection, target_metadata=target_metadata) + + with context.begin_transaction(): + context.run_migrations() + + +async def run_async_migrations() -> None: + """In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + connectable = async_engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + async with connectable.connect() as connection: + await connection.run_sync(do_run_migrations) + + await connectable.dispose() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode.""" + + asyncio.run(run_async_migrations()) + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..1101630 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,28 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + """Upgrade schema.""" + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + """Downgrade schema.""" + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/274efdcbfbcc_initial_schema.py b/migrations/versions/274efdcbfbcc_initial_schema.py new file mode 100644 index 0000000..0a48d2e --- /dev/null +++ b/migrations/versions/274efdcbfbcc_initial_schema.py @@ -0,0 +1,153 @@ +"""initial schema + +Revision ID: 274efdcbfbcc +Revises: +Create Date: 2026-07-20 22:11:47.766165 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '274efdcbfbcc' +down_revision: Union[str, Sequence[str], None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('round_config', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('fee_address', sa.String(length=128), nullable=False), + sa.Column('bet_amount_sats', sa.BigInteger(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('users', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('username', sa.String(length=64), nullable=False), + sa.Column('password_hash', sa.String(length=256), nullable=False), + sa.Column('derivation_index', sa.Integer(), nullable=False), + sa.Column('address', sa.String(length=128), nullable=False), + sa.Column('cached_balance_sats', sa.BigInteger(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('address'), + sa.UniqueConstraint('derivation_index') + ) + op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True) + op.create_table('rounds', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('status', sa.String(length=16), nullable=False), + sa.Column('opened_at', sa.DateTime(), nullable=False), + sa.Column('closed_at', sa.DateTime(), nullable=True), + sa.Column('draw_block_height', sa.Integer(), nullable=True), + sa.Column('draw_block_hash', sa.String(length=64), nullable=True), + sa.Column('seed_int', sa.String(length=128), nullable=True), + sa.Column('winner_user_id', sa.Integer(), nullable=True), + sa.Column('pool_amount_sats', sa.BigInteger(), nullable=True), + sa.Column('winner_amount_sats', sa.BigInteger(), nullable=True), + sa.Column('fee_amount_sats', sa.BigInteger(), nullable=True), + sa.Column('payout_txid', sa.String(length=64), nullable=True), + sa.ForeignKeyConstraint(['winner_user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('utxo_events', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('txid', sa.String(length=64), nullable=False), + sa.Column('vout', sa.Integer(), nullable=False), + sa.Column('amount_sats', sa.BigInteger(), nullable=False), + sa.Column('confirmed_height', sa.Integer(), nullable=False), + sa.Column('confirmed_at', sa.DateTime(), nullable=False), + sa.Column('spent_txid', sa.String(length=64), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('txid', 'vout') + ) + op.create_index(op.f('ix_utxo_events_user_id'), 'utxo_events', ['user_id'], unique=False) + op.create_table('withdrawals', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('external_address', sa.String(length=128), nullable=False), + sa.Column('amount_requested_sats', sa.BigInteger(), nullable=False), + sa.Column('amount_sent_sats', sa.BigInteger(), nullable=True), + sa.Column('txid', sa.String(length=64), nullable=True), + sa.Column('status', sa.String(length=16), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('confirmed_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_withdrawals_user_id'), 'withdrawals', ['user_id'], unique=False) + op.create_table('audit_log', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('event_type', sa.String(length=32), nullable=False), + sa.Column('payload_json', sa.String(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('round_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['round_id'], ['rounds.id'], ), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('pending_transactions', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('kind', sa.String(length=16), nullable=False), + sa.Column('round_id', sa.Integer(), nullable=True), + sa.Column('withdrawal_id', sa.Integer(), nullable=True), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('current_txid', sa.String(length=64), nullable=False), + sa.Column('fee_rate_sat_vb', sa.Integer(), nullable=False), + sa.Column('raw_tx_hex', sa.String(), nullable=False), + sa.Column('broadcast_at', sa.DateTime(), nullable=False), + sa.Column('status', sa.String(length=16), nullable=False), + sa.Column('replaced_by_txid', sa.String(length=64), nullable=True), + sa.Column('attempt_count', sa.Integer(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['round_id'], ['rounds.id'], ), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['withdrawal_id'], ['withdrawals.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('round_participants', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('round_id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('bet_amount_sats', sa.BigInteger(), nullable=False), + sa.Column('bet_txid', sa.String(length=64), nullable=False), + sa.Column('broadcast_at', sa.DateTime(), nullable=False), + sa.Column('confirmed_at', sa.DateTime(), nullable=True), + sa.Column('status', sa.String(length=16), nullable=False), + sa.ForeignKeyConstraint(['round_id'], ['rounds.id'], ), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('round_id', 'user_id') + ) + op.create_index(op.f('ix_round_participants_round_id'), 'round_participants', ['round_id'], unique=False) + op.create_index(op.f('ix_round_participants_user_id'), 'round_participants', ['user_id'], unique=False) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_round_participants_user_id'), table_name='round_participants') + op.drop_index(op.f('ix_round_participants_round_id'), table_name='round_participants') + op.drop_table('round_participants') + op.drop_table('pending_transactions') + op.drop_table('audit_log') + op.drop_index(op.f('ix_withdrawals_user_id'), table_name='withdrawals') + op.drop_table('withdrawals') + op.drop_index(op.f('ix_utxo_events_user_id'), table_name='utxo_events') + op.drop_table('utxo_events') + op.drop_table('rounds') + op.drop_index(op.f('ix_users_username'), table_name='users') + op.drop_table('users') + op.drop_table('round_config') + # ### end Alembic commands ### diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..2fc3b83 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,30 @@ +[project] +name = "plm-lottery" +version = "0.1.0" +requires-python = ">=3.12" +dependencies = [ + "fastapi>=0.115", + "uvicorn[standard]>=0.32", + "sqlalchemy>=2.0", + "aiosqlite>=0.20", + "alembic>=1.13", + "pydantic-settings>=2.6", + "argon2-cffi>=23.1", + "pyjwt>=2.7", + "cryptography>=43.0", + "embit>=0.7", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.3", + "pytest-asyncio>=0.24", + "httpx>=0.27", +] + +[tool.pytest.ini_options] +asyncio_mode = "auto" +testpaths = ["tests"] + +[tool.setuptools.packages.find] +include = ["app*"] diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000..e69de29