From 2b87df9ed24992c29a1639ac5287cd072fc255e6 Mon Sep 17 00:00:00 2001 From: BitmapAsset Date: Thu, 3 Sep 2026 03:00:03 -0700 Subject: [PATCH] chore: archive legacy/taproot-assets-era to a tag and remove it from main The pre-RuneBolt Taproot-Assets prototype (Next.js frontend, Node backend, SDK, Docker/k8s deploy scripts) carried three checked-in package-lock.json files that generated 63 Dependabot alerts (1 critical, 25 high, 30 moderate, 7 low) on a codebase that ships nowhere. That noise buried the one real alert on the live tree. Verified dead before removal: - git grep taproot-assets-era -- ':!legacy/' -> no hits - pnpm-workspace.yaml is 'packages/*' only -> pnpm -r never enters legacy/ - .github/workflows/ci.yml is the only workflow and runs only workspace scripts - tools/check-boundaries.mjs explicitly skips 'legacy' - every Dockerfile/compose/k8s/deploy script in the repo lives INSIDE legacy/ - README.md and docs/ARCHITECTURE.md already document it as not maintained Preserved at annotated tag legacy/taproot-assets-era-final (f8eebe3). Recover with: git checkout legacy/taproot-assets-era-final -- legacy/taproot-assets-era legacy/README.md keeps its full historical write-up and gains the tag pointer. legacy/ci/ci-cd.yml (parked, non-running) is retained. Verified after removal: pnpm install --frozen-lockfile, pnpm run verify (boundaries OK, typecheck clean, 170 tests passed / 3 skipped). --- legacy/README.md | 25 + .../.env.production.example | 84 - legacy/taproot-assets-era/DEPLOYMENT.md | 119 - legacy/taproot-assets-era/Dockerfile | 114 - legacy/taproot-assets-era/INFRASTRUCTURE.md | 454 -- .../taproot-assets-era/INTEGRATION_GUIDE.md | 298 -- .../taproot-assets-era/PERFORMANCE_ROADMAP.md | 338 -- .../taproot-assets-era/PERFORMANCE_SUMMARY.md | 88 - .../taproot-assets-era/PROTOCOL_RESEARCH.md | 303 -- legacy/taproot-assets-era/README.md | 126 - .../RESEARCH_AGENT_1_FINDINGS.md | 1292 ------ .../RESEARCH_AGENT_2_FINDINGS.md | 1240 ------ legacy/taproot-assets-era/SECURITY_AUDIT.md | 320 -- legacy/taproot-assets-era/SECURITY_FIXES.md | 262 -- .../SECURITY_FIXES_FINAL.md | 403 -- .../SECURITY_FIXES_SUMMARY.md | 282 -- .../taproot-assets-era/SPECS_BITVM_BRIDGE.md | 441 -- .../UX_COMPLETION_SUMMARY.md | 164 - .../taproot-assets-era/UX_ERROR_MESSAGES.md | 389 -- .../UX_IMPLEMENTATION_SUMMARY.md | 150 - legacy/taproot-assets-era/UX_JOURNEY_MAPS.md | 436 -- legacy/taproot-assets-era/UX_MASS_ADOPTION.md | 271 -- .../taproot-assets-era/UX_ONBOARDING_GUIDE.md | 530 --- .../taproot-assets-era/UX_TRUST_RESEARCH.md | 152 - .../taproot-assets-era/backend/.env.example | 41 - .../backend/.env.production.template | 75 - legacy/taproot-assets-era/backend/.gitignore | 6 - .../taproot-assets-era/backend/PERFORMANCE.md | 209 - .../backend/SIMULATION_REPORT.md | 223 - .../taproot-assets-era/backend/fix-async.sh | 29 - .../migrations/001_postgres_schema.sql | 141 - .../backend/migrations/005_multi_asset.sql | 73 - .../backend/package-lock.json | 3825 ----------------- .../taproot-assets-era/backend/package.json | 45 - .../backend/scripts/deploy-production.sh | 131 - .../backend/scripts/run-simulation.sh | 44 - .../backend/scripts/setup-mainnet-env.sh | 77 - .../backend/scripts/smoke-test.sh | 86 - .../backend/src/__tests__/e2e-simulation.ts | 959 ----- .../backend/src/__tests__/integration.test.ts | 474 -- .../src/__tests__/rune-encoding.test.ts | 431 -- .../backend/src/__tests__/simulation.test.ts | 645 --- .../backend/src/__tests__/test-helpers.ts | 139 - .../backend/src/api/auth.ts | 385 -- .../backend/src/api/routes/assetRoutes.ts | 294 -- .../backend/src/api/routes/authRoutes.ts | 137 - .../backend/src/api/routes/channelRoutes.ts | 253 -- .../backend/src/api/routes/claimRoutes.ts | 260 -- .../backend/src/api/routes/feeRoutes.ts | 85 - .../backend/src/api/routes/statsRoutes.ts | 77 - .../backend/src/api/routes/transferRoutes.ts | 292 -- .../backend/src/api/routes/userRoutes.ts | 145 - .../backend/src/api/routes/wellKnownRoutes.ts | 65 - .../backend/src/assets/AssetRegistry.ts | 145 - .../backend/src/assets/BRC20Manager.ts | 237 - .../backend/src/assets/BitmapEscrow.ts | 357 -- .../backend/src/auth/AuthMiddleware.ts | 153 - .../backend/src/auth/ChallengeManager.ts | 114 - .../backend/src/bitcoin/BitcoinClient.ts | 313 -- .../backend/src/bitcoin/MempoolClient.ts | 208 - .../backend/src/bitcoin/TaprootUtils.ts | 196 - .../backend/src/cache/RedisCache.ts | 482 --- .../backend/src/channels/ChannelManager.ts | 193 - .../backend/src/channels/ChannelReserves.ts | 46 - .../backend/src/channels/ChannelState.ts | 115 - .../backend/src/channels/CommitmentManager.ts | 290 -- .../backend/src/channels/DisputeManager.ts | 225 - .../backend/src/channels/PenaltyManager.ts | 235 - .../backend/src/config/mainnet-checks.ts | 162 - .../backend/src/config/security.ts | 24 - .../backend/src/db/Database.ts | 947 ---- .../src/db/migrations/001_security_fixes.sql | 66 - .../migrations/002_username_social_auth.sql | 49 - .../src/db/migrations/003_fee_tracking.sql | 31 - .../src/db/migrations/004_security_tables.sql | 51 - .../src/db/migrations/005_multi_asset.sql | 73 - .../src/db/migrations/006_missing_tables.sql | 141 - .../backend/src/db/schema.sql | 113 - .../backend/src/fees/FeeManager.ts | 161 - .../taproot-assets-era/backend/src/index.ts | 191 - .../backend/src/ledger/RuneLedger.ts | 452 -- .../backend/src/ledger/Transfer.ts | 64 - .../backend/src/monitoring/metrics.ts | 201 - .../backend/src/rune/RuneBuilder.ts | 223 - .../backend/src/rune/RuneConstants.ts | 71 - .../backend/src/rune/RuneParser.ts | 341 -- .../backend/src/usernames/index.ts | 2 - .../backend/src/usernames/usernameRoutes.ts | 206 - .../backend/src/usernames/usernameUtils.ts | 122 - .../backend/src/watchtower/Watchtower.ts | 261 -- .../backend/src/workers/TransferWorker.ts | 463 -- .../src/ws/TransactionStatusHandler.ts | 225 - .../backend/src/ws/WebSocketServer.ts | 440 -- .../taproot-assets-era/backend/tsconfig.json | 26 - .../docker-compose.prod.yml | 479 --- legacy/taproot-assets-era/docker-compose.yml | 338 -- legacy/taproot-assets-era/frontend/.gitignore | 5 - .../frontend/app/app/channels/page.tsx | 407 -- .../frontend/app/app/history/page.tsx | 218 - .../frontend/app/app/layout.tsx | 12 - .../frontend/app/app/page.tsx | 267 -- .../frontend/app/app/receive/page.tsx | 234 - .../frontend/app/app/send/page.tsx | 402 -- .../app/claim/[id]/ClaimPageClient.tsx | 266 -- .../frontend/app/claim/[id]/page.tsx | 13 - .../frontend/app/globals.css | 113 - .../frontend/app/layout.tsx | 19 - .../taproot-assets-era/frontend/app/page.tsx | 400 -- .../frontend/components/AddressInput.tsx | 102 - .../frontend/components/AppHeader.tsx | 89 - .../frontend/components/BalanceCard.tsx | 98 - .../frontend/components/ChannelCard.tsx | 77 - .../frontend/components/ClaimLink.tsx | 365 -- .../frontend/components/Confetti.tsx | 98 - .../frontend/components/ErrorMessage.tsx | 426 -- .../frontend/components/GlassCard.tsx | 30 - .../frontend/components/LoadingSpinner.tsx | 47 - .../frontend/components/Navbar.tsx | 118 - .../frontend/components/OnboardingFlow.tsx | 361 -- .../frontend/components/SendModal.tsx | 277 -- .../frontend/components/ShibaInu.tsx | 137 - .../frontend/components/StatCard.tsx | 27 - .../frontend/components/StatusBadge.tsx | 79 - .../frontend/components/TransactionStatus.tsx | 298 -- .../frontend/components/TransferList.tsx | 115 - .../frontend/components/WalletConnect.tsx | 120 - .../frontend/components/index.ts | 12 - .../frontend/hooks/useApi.ts | 108 - .../frontend/hooks/useUnisat.ts | 149 - .../frontend/hooks/useWebSocket.ts | 107 - legacy/taproot-assets-era/frontend/lib/api.ts | 147 - .../frontend/lib/constants.ts | 11 - .../frontend/lib/demo-data.ts | 155 - .../taproot-assets-era/frontend/lib/format.ts | 34 - .../taproot-assets-era/frontend/lib/types.ts | 70 - .../taproot-assets-era/frontend/lib/wallet.ts | 54 - .../frontend/next.config.js | 17 - .../frontend/package-lock.json | 1682 -------- .../taproot-assets-era/frontend/package.json | 28 - .../frontend/postcss.config.js | 6 - .../frontend/tailwind.config.ts | 75 - .../taproot-assets-era/frontend/tsconfig.json | 27 - .../infrastructure/README.md | 72 - .../infrastructure/configs/haproxy.cfg | 78 - .../infrastructure/haproxy/haproxy.cfg | 138 - .../k8s/backend-deployment.yaml | 70 - .../infrastructure/k8s/ingress.yaml | 36 - .../infrastructure/k8s/namespace.yaml | 20 - .../infrastructure/pgbouncer/pgbouncer.ini | 44 - .../runbooks/01-service-restart.md | 48 - .../runbooks/02-database-restore.md | 46 - .../runbooks/03-scale-infrastructure.md | 27 - .../runbooks/04-vault-unseal.md | 29 - .../runbooks/05-incident-response.md | 36 - .../infrastructure/scripts/backup.sh | 36 - .../infrastructure/scripts/deploy.sh | 18 - .../infrastructure/terraform/main.tf | 281 -- .../infrastructure/terraform/outputs.tf | 15 - .../infrastructure/terraform/variables.tf | 23 - .../infrastructure/vault/config/vault.hcl | 26 - .../migrations/001_postgres_schema.sql | 297 -- .../migrations/002_fees_and_tiers.sql | 55 - .../migrations/005_multi_asset.sql | 73 - .../monitoring/alerts/alerts.yml | 309 -- .../monitoring/dashboard-specs.json | 109 - .../grafana/dashboards/dashboards.yml | 12 - .../grafana/dashboards/overview.json | 327 -- .../grafana/datasources/datasources.yml | 51 - .../monitoring/loki/loki.yml | 61 - .../monitoring/prometheus.yml | 223 - .../monitoring/promtail/promtail.yml | 67 - legacy/taproot-assets-era/scripts/backup.sh | 335 -- legacy/taproot-assets-era/scripts/deploy.sh | 426 -- legacy/taproot-assets-era/sdk/.gitignore | 2 - .../taproot-assets-era/sdk/package-lock.json | 83 - legacy/taproot-assets-era/sdk/package.json | 21 - .../sdk/src/RuneBoltClient.ts | 202 - legacy/taproot-assets-era/sdk/src/index.ts | 2 - legacy/taproot-assets-era/sdk/src/types.ts | 57 - legacy/taproot-assets-era/sdk/tsconfig.json | 18 - 180 files changed, 25 insertions(+), 38809 deletions(-) delete mode 100644 legacy/taproot-assets-era/.env.production.example delete mode 100644 legacy/taproot-assets-era/DEPLOYMENT.md delete mode 100644 legacy/taproot-assets-era/Dockerfile delete mode 100644 legacy/taproot-assets-era/INFRASTRUCTURE.md delete mode 100644 legacy/taproot-assets-era/INTEGRATION_GUIDE.md delete mode 100644 legacy/taproot-assets-era/PERFORMANCE_ROADMAP.md delete mode 100644 legacy/taproot-assets-era/PERFORMANCE_SUMMARY.md delete mode 100644 legacy/taproot-assets-era/PROTOCOL_RESEARCH.md delete mode 100644 legacy/taproot-assets-era/README.md delete mode 100644 legacy/taproot-assets-era/RESEARCH_AGENT_1_FINDINGS.md delete mode 100644 legacy/taproot-assets-era/RESEARCH_AGENT_2_FINDINGS.md delete mode 100644 legacy/taproot-assets-era/SECURITY_AUDIT.md delete mode 100644 legacy/taproot-assets-era/SECURITY_FIXES.md delete mode 100644 legacy/taproot-assets-era/SECURITY_FIXES_FINAL.md delete mode 100644 legacy/taproot-assets-era/SECURITY_FIXES_SUMMARY.md delete mode 100644 legacy/taproot-assets-era/SPECS_BITVM_BRIDGE.md delete mode 100644 legacy/taproot-assets-era/UX_COMPLETION_SUMMARY.md delete mode 100644 legacy/taproot-assets-era/UX_ERROR_MESSAGES.md delete mode 100644 legacy/taproot-assets-era/UX_IMPLEMENTATION_SUMMARY.md delete mode 100644 legacy/taproot-assets-era/UX_JOURNEY_MAPS.md delete mode 100644 legacy/taproot-assets-era/UX_MASS_ADOPTION.md delete mode 100644 legacy/taproot-assets-era/UX_ONBOARDING_GUIDE.md delete mode 100644 legacy/taproot-assets-era/UX_TRUST_RESEARCH.md delete mode 100644 legacy/taproot-assets-era/backend/.env.example delete mode 100644 legacy/taproot-assets-era/backend/.env.production.template delete mode 100644 legacy/taproot-assets-era/backend/.gitignore delete mode 100644 legacy/taproot-assets-era/backend/PERFORMANCE.md delete mode 100644 legacy/taproot-assets-era/backend/SIMULATION_REPORT.md delete mode 100644 legacy/taproot-assets-era/backend/fix-async.sh delete mode 100644 legacy/taproot-assets-era/backend/migrations/001_postgres_schema.sql delete mode 100644 legacy/taproot-assets-era/backend/migrations/005_multi_asset.sql delete mode 100644 legacy/taproot-assets-era/backend/package-lock.json delete mode 100644 legacy/taproot-assets-era/backend/package.json delete mode 100755 legacy/taproot-assets-era/backend/scripts/deploy-production.sh delete mode 100755 legacy/taproot-assets-era/backend/scripts/run-simulation.sh delete mode 100755 legacy/taproot-assets-era/backend/scripts/setup-mainnet-env.sh delete mode 100755 legacy/taproot-assets-era/backend/scripts/smoke-test.sh delete mode 100644 legacy/taproot-assets-era/backend/src/__tests__/e2e-simulation.ts delete mode 100644 legacy/taproot-assets-era/backend/src/__tests__/integration.test.ts delete mode 100644 legacy/taproot-assets-era/backend/src/__tests__/rune-encoding.test.ts delete mode 100644 legacy/taproot-assets-era/backend/src/__tests__/simulation.test.ts delete mode 100644 legacy/taproot-assets-era/backend/src/__tests__/test-helpers.ts delete mode 100644 legacy/taproot-assets-era/backend/src/api/auth.ts delete mode 100644 legacy/taproot-assets-era/backend/src/api/routes/assetRoutes.ts delete mode 100644 legacy/taproot-assets-era/backend/src/api/routes/authRoutes.ts delete mode 100644 legacy/taproot-assets-era/backend/src/api/routes/channelRoutes.ts delete mode 100644 legacy/taproot-assets-era/backend/src/api/routes/claimRoutes.ts delete mode 100644 legacy/taproot-assets-era/backend/src/api/routes/feeRoutes.ts delete mode 100644 legacy/taproot-assets-era/backend/src/api/routes/statsRoutes.ts delete mode 100644 legacy/taproot-assets-era/backend/src/api/routes/transferRoutes.ts delete mode 100644 legacy/taproot-assets-era/backend/src/api/routes/userRoutes.ts delete mode 100644 legacy/taproot-assets-era/backend/src/api/routes/wellKnownRoutes.ts delete mode 100644 legacy/taproot-assets-era/backend/src/assets/AssetRegistry.ts delete mode 100644 legacy/taproot-assets-era/backend/src/assets/BRC20Manager.ts delete mode 100644 legacy/taproot-assets-era/backend/src/assets/BitmapEscrow.ts delete mode 100644 legacy/taproot-assets-era/backend/src/auth/AuthMiddleware.ts delete mode 100644 legacy/taproot-assets-era/backend/src/auth/ChallengeManager.ts delete mode 100644 legacy/taproot-assets-era/backend/src/bitcoin/BitcoinClient.ts delete mode 100644 legacy/taproot-assets-era/backend/src/bitcoin/MempoolClient.ts delete mode 100644 legacy/taproot-assets-era/backend/src/bitcoin/TaprootUtils.ts delete mode 100644 legacy/taproot-assets-era/backend/src/cache/RedisCache.ts delete mode 100644 legacy/taproot-assets-era/backend/src/channels/ChannelManager.ts delete mode 100644 legacy/taproot-assets-era/backend/src/channels/ChannelReserves.ts delete mode 100644 legacy/taproot-assets-era/backend/src/channels/ChannelState.ts delete mode 100644 legacy/taproot-assets-era/backend/src/channels/CommitmentManager.ts delete mode 100644 legacy/taproot-assets-era/backend/src/channels/DisputeManager.ts delete mode 100644 legacy/taproot-assets-era/backend/src/channels/PenaltyManager.ts delete mode 100644 legacy/taproot-assets-era/backend/src/config/mainnet-checks.ts delete mode 100644 legacy/taproot-assets-era/backend/src/config/security.ts delete mode 100644 legacy/taproot-assets-era/backend/src/db/Database.ts delete mode 100644 legacy/taproot-assets-era/backend/src/db/migrations/001_security_fixes.sql delete mode 100644 legacy/taproot-assets-era/backend/src/db/migrations/002_username_social_auth.sql delete mode 100644 legacy/taproot-assets-era/backend/src/db/migrations/003_fee_tracking.sql delete mode 100644 legacy/taproot-assets-era/backend/src/db/migrations/004_security_tables.sql delete mode 100644 legacy/taproot-assets-era/backend/src/db/migrations/005_multi_asset.sql delete mode 100644 legacy/taproot-assets-era/backend/src/db/migrations/006_missing_tables.sql delete mode 100644 legacy/taproot-assets-era/backend/src/db/schema.sql delete mode 100644 legacy/taproot-assets-era/backend/src/fees/FeeManager.ts delete mode 100644 legacy/taproot-assets-era/backend/src/index.ts delete mode 100644 legacy/taproot-assets-era/backend/src/ledger/RuneLedger.ts delete mode 100644 legacy/taproot-assets-era/backend/src/ledger/Transfer.ts delete mode 100644 legacy/taproot-assets-era/backend/src/monitoring/metrics.ts delete mode 100644 legacy/taproot-assets-era/backend/src/rune/RuneBuilder.ts delete mode 100644 legacy/taproot-assets-era/backend/src/rune/RuneConstants.ts delete mode 100644 legacy/taproot-assets-era/backend/src/rune/RuneParser.ts delete mode 100644 legacy/taproot-assets-era/backend/src/usernames/index.ts delete mode 100644 legacy/taproot-assets-era/backend/src/usernames/usernameRoutes.ts delete mode 100644 legacy/taproot-assets-era/backend/src/usernames/usernameUtils.ts delete mode 100644 legacy/taproot-assets-era/backend/src/watchtower/Watchtower.ts delete mode 100644 legacy/taproot-assets-era/backend/src/workers/TransferWorker.ts delete mode 100644 legacy/taproot-assets-era/backend/src/ws/TransactionStatusHandler.ts delete mode 100644 legacy/taproot-assets-era/backend/src/ws/WebSocketServer.ts delete mode 100644 legacy/taproot-assets-era/backend/tsconfig.json delete mode 100644 legacy/taproot-assets-era/docker-compose.prod.yml delete mode 100644 legacy/taproot-assets-era/docker-compose.yml delete mode 100644 legacy/taproot-assets-era/frontend/.gitignore delete mode 100644 legacy/taproot-assets-era/frontend/app/app/channels/page.tsx delete mode 100644 legacy/taproot-assets-era/frontend/app/app/history/page.tsx delete mode 100644 legacy/taproot-assets-era/frontend/app/app/layout.tsx delete mode 100644 legacy/taproot-assets-era/frontend/app/app/page.tsx delete mode 100644 legacy/taproot-assets-era/frontend/app/app/receive/page.tsx delete mode 100644 legacy/taproot-assets-era/frontend/app/app/send/page.tsx delete mode 100644 legacy/taproot-assets-era/frontend/app/claim/[id]/ClaimPageClient.tsx delete mode 100644 legacy/taproot-assets-era/frontend/app/claim/[id]/page.tsx delete mode 100644 legacy/taproot-assets-era/frontend/app/globals.css delete mode 100644 legacy/taproot-assets-era/frontend/app/layout.tsx delete mode 100644 legacy/taproot-assets-era/frontend/app/page.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/AddressInput.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/AppHeader.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/BalanceCard.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/ChannelCard.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/ClaimLink.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/Confetti.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/ErrorMessage.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/GlassCard.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/LoadingSpinner.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/Navbar.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/OnboardingFlow.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/SendModal.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/ShibaInu.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/StatCard.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/StatusBadge.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/TransactionStatus.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/TransferList.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/WalletConnect.tsx delete mode 100644 legacy/taproot-assets-era/frontend/components/index.ts delete mode 100644 legacy/taproot-assets-era/frontend/hooks/useApi.ts delete mode 100644 legacy/taproot-assets-era/frontend/hooks/useUnisat.ts delete mode 100644 legacy/taproot-assets-era/frontend/hooks/useWebSocket.ts delete mode 100644 legacy/taproot-assets-era/frontend/lib/api.ts delete mode 100644 legacy/taproot-assets-era/frontend/lib/constants.ts delete mode 100644 legacy/taproot-assets-era/frontend/lib/demo-data.ts delete mode 100644 legacy/taproot-assets-era/frontend/lib/format.ts delete mode 100644 legacy/taproot-assets-era/frontend/lib/types.ts delete mode 100644 legacy/taproot-assets-era/frontend/lib/wallet.ts delete mode 100644 legacy/taproot-assets-era/frontend/next.config.js delete mode 100644 legacy/taproot-assets-era/frontend/package-lock.json delete mode 100644 legacy/taproot-assets-era/frontend/package.json delete mode 100644 legacy/taproot-assets-era/frontend/postcss.config.js delete mode 100644 legacy/taproot-assets-era/frontend/tailwind.config.ts delete mode 100644 legacy/taproot-assets-era/frontend/tsconfig.json delete mode 100644 legacy/taproot-assets-era/infrastructure/README.md delete mode 100644 legacy/taproot-assets-era/infrastructure/configs/haproxy.cfg delete mode 100644 legacy/taproot-assets-era/infrastructure/haproxy/haproxy.cfg delete mode 100644 legacy/taproot-assets-era/infrastructure/k8s/backend-deployment.yaml delete mode 100644 legacy/taproot-assets-era/infrastructure/k8s/ingress.yaml delete mode 100644 legacy/taproot-assets-era/infrastructure/k8s/namespace.yaml delete mode 100644 legacy/taproot-assets-era/infrastructure/pgbouncer/pgbouncer.ini delete mode 100644 legacy/taproot-assets-era/infrastructure/runbooks/01-service-restart.md delete mode 100644 legacy/taproot-assets-era/infrastructure/runbooks/02-database-restore.md delete mode 100644 legacy/taproot-assets-era/infrastructure/runbooks/03-scale-infrastructure.md delete mode 100644 legacy/taproot-assets-era/infrastructure/runbooks/04-vault-unseal.md delete mode 100644 legacy/taproot-assets-era/infrastructure/runbooks/05-incident-response.md delete mode 100755 legacy/taproot-assets-era/infrastructure/scripts/backup.sh delete mode 100755 legacy/taproot-assets-era/infrastructure/scripts/deploy.sh delete mode 100644 legacy/taproot-assets-era/infrastructure/terraform/main.tf delete mode 100644 legacy/taproot-assets-era/infrastructure/terraform/outputs.tf delete mode 100644 legacy/taproot-assets-era/infrastructure/terraform/variables.tf delete mode 100644 legacy/taproot-assets-era/infrastructure/vault/config/vault.hcl delete mode 100644 legacy/taproot-assets-era/migrations/001_postgres_schema.sql delete mode 100644 legacy/taproot-assets-era/migrations/002_fees_and_tiers.sql delete mode 100644 legacy/taproot-assets-era/migrations/005_multi_asset.sql delete mode 100644 legacy/taproot-assets-era/monitoring/alerts/alerts.yml delete mode 100644 legacy/taproot-assets-era/monitoring/dashboard-specs.json delete mode 100644 legacy/taproot-assets-era/monitoring/grafana/dashboards/dashboards.yml delete mode 100644 legacy/taproot-assets-era/monitoring/grafana/dashboards/overview.json delete mode 100644 legacy/taproot-assets-era/monitoring/grafana/datasources/datasources.yml delete mode 100644 legacy/taproot-assets-era/monitoring/loki/loki.yml delete mode 100644 legacy/taproot-assets-era/monitoring/prometheus.yml delete mode 100644 legacy/taproot-assets-era/monitoring/promtail/promtail.yml delete mode 100755 legacy/taproot-assets-era/scripts/backup.sh delete mode 100755 legacy/taproot-assets-era/scripts/deploy.sh delete mode 100644 legacy/taproot-assets-era/sdk/.gitignore delete mode 100644 legacy/taproot-assets-era/sdk/package-lock.json delete mode 100644 legacy/taproot-assets-era/sdk/package.json delete mode 100644 legacy/taproot-assets-era/sdk/src/RuneBoltClient.ts delete mode 100644 legacy/taproot-assets-era/sdk/src/index.ts delete mode 100644 legacy/taproot-assets-era/sdk/src/types.ts delete mode 100644 legacy/taproot-assets-era/sdk/tsconfig.json diff --git a/legacy/README.md b/legacy/README.md index b8793e8..3350efa 100644 --- a/legacy/README.md +++ b/legacy/README.md @@ -1,5 +1,29 @@ # Legacy — Taproot Assets era (March 2026) +> **The code is no longer checked out on `main`.** `taproot-assets-era/` was removed and +> preserved in history under the annotated tag **`legacy/taproot-assets-era-final`** +> (commit `f8eebe3`). Recover it with: +> +> ```sh +> git checkout legacy/taproot-assets-era-final -- legacy/taproot-assets-era +> ``` +> +> **Why it was removed:** its three checked-in `package-lock.json` files generated +> **63 Dependabot alerts** (1 critical, 25 high, 30 moderate, 7 low) against a frozen +> prototype that is never built, tested or deployed. That noise buried real alerts on the +> live tree. Deleting the directory retires those alerts at the source instead of +> dismissing 63 of them one at a time. Nothing on `main` referenced it — verified by +> `git grep taproot-assets-era` (no hits outside `legacy/`), by `pnpm-workspace.yaml` +> (`packages/*` only), and by `.github/workflows/ci.yml` (the sole workflow, which runs +> only workspace scripts). +> +> Browse it without checking anything out: +> +> ```sh +> git ls-tree -r --name-only legacy/taproot-assets-era-final legacy/taproot-assets-era +> git show legacy/taproot-assets-era-final:legacy/taproot-assets-era/README.md +> ``` + Everything under `taproot-assets-era/` is the **first** RuneBolt design. It is kept for history. It is not built, tested, deployed, or maintained. Do not import from it. @@ -11,6 +35,7 @@ off-chain against a hub-operated ledger. Backend (Express + SQLite + WebSocket), `@runebolt/sdk`, Docker/Vault/Grafana infrastructure, and a large body of UX and security research. `legacy/ci/ci-cd.yml` is the old GitHub Actions workflow, parked here so it no longer runs. +It is retained; the code it built now lives only under the tag above. ## Why it was superseded diff --git a/legacy/taproot-assets-era/.env.production.example b/legacy/taproot-assets-era/.env.production.example deleted file mode 100644 index 3bb86c1..0000000 --- a/legacy/taproot-assets-era/.env.production.example +++ /dev/null @@ -1,84 +0,0 @@ -# RuneBolt Production Environment Configuration -# Copy to .env.production and fill in actual values -# NEVER commit this file to version control! - -# ============================================ -# Application Settings -# ============================================ -NODE_ENV=production -NETWORK=mainnet -VERSION=latest - -# ============================================ -# API Configuration -# ============================================ -NEXT_PUBLIC_API_URL=https://api.runebolt.io -NEXT_PUBLIC_WS_URL=wss://ws.runebolt.io - -# ============================================ -# Security (CRITICAL - Change these!) -# ============================================ -JWT_SECRET=change_me_to_a_secure_random_string_min_32_chars -POSTGRES_PASSWORD=change_me_to_a_secure_random_password -GRAFANA_ADMIN_PASSWORD=change_me_to_a_secure_password -VAULT_DEV_ROOT_TOKEN_ID=change_me_to_a_secure_token - -# Bitcoin Keys (Handle with extreme care!) -RUNEBOLT_XPUB=your_xpub_here -RUNEBOLT_PRIVKEY=your_private_key_here_or_use_vault - -# ============================================ -# Database Configuration -# ============================================ -POSTGRES_HOST=postgres -POSTGRES_PORT=5432 -POSTGRES_DB=runebolt -POSTGRES_USER=runebolt - -# ============================================ -# Redis Configuration -# ============================================ -REDIS_HOST=redis -REDIS_PORT=6379 -REDIS_PASSWORD= - -# ============================================ -# Vault Configuration -# ============================================ -VAULT_ADDR=http://vault:8200 -VAULT_TOKEN= - -# ============================================ -# External Services -# ============================================ -MEMPOOL_API=https://mempool.space/api - -# ============================================ -# S3 Backup Configuration -# ============================================ -S3_BUCKET=runebolt-backups -S3_REGION=us-east-1 -S3_ENDPOINT= -AWS_ACCESS_KEY_ID= -AWS_SECRET_ACCESS_KEY= - -# ============================================ -# SMTP Configuration (for Grafana alerts) -# ============================================ -GF_SMTP_ENABLED=false -GF_SMTP_HOST=smtp.gmail.com:587 -GF_SMTP_USER=your-email@gmail.com -GF_SMTP_PASSWORD=your-app-password -GF_SMTP_FROM_ADDRESS=alerts@runebolt.io - -# ============================================ -# Notification Webhooks -# ============================================ -SLACK_WEBHOOK_URL=https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK - -# ============================================ -# Deployment Configuration -# ============================================ -DEPLOY_HOST=your-server-ip-or-hostname -DEPLOY_USER=runebolt -DEPLOY_PATH=/opt/runebolt diff --git a/legacy/taproot-assets-era/DEPLOYMENT.md b/legacy/taproot-assets-era/DEPLOYMENT.md deleted file mode 100644 index 7da74e6..0000000 --- a/legacy/taproot-assets-era/DEPLOYMENT.md +++ /dev/null @@ -1,119 +0,0 @@ -# ============================================ -# RuneBolt Production Deployment Checklist -# ============================================ - -## Pre-Deployment - -- [ ] Review INFRASTRUCTURE.md for architecture details -- [ ] Ensure all secrets are configured in .env.production -- [ ] Verify SSL certificates are in place -- [ ] Check that backup S3 bucket is accessible -- [ ] Test database connectivity -- [ ] Review recent changes in CHANGELOG.md - -## Initial Setup (First Time Only) - -1. Copy environment file: - ```bash - cp .env.production.example .env.production - # Edit and fill in all values - ``` - -2. Create required directories: - ```bash - mkdir -p logs/backend logs/worker backups/{postgres,redis,sqlite,vault} - mkdir -p infrastructure/ssl/{certs,private} - mkdir -p infrastructure/postgres/init-scripts - ``` - -3. Place SSL certificates: - ```bash - # Place your SSL certificate and key - cp your-cert.pem infrastructure/ssl/certs/runebolt.pem - cp your-key.pem infrastructure/ssl/private/runebolt.key - ``` - -4. Initialize Vault (first run only): - ```bash - docker compose -f docker-compose.prod.yml up -d vault - # Follow Vault initialization procedures - # Save unseal keys and root token securely - ``` - -5. Run database migrations: - ```bash - docker compose -f docker-compose.prod.yml up -d postgres - # Wait for postgres to be healthy - # Run migrations - ``` - -## Deployment - -### Using the deploy script: -```bash -./scripts/deploy.sh production v1.0.0 -``` - -### Manual deployment: -```bash -# 1. Set version -export VERSION=v1.0.0 - -# 2. Pull latest images -docker compose -f docker-compose.prod.yml pull - -# 3. Deploy -docker compose -f docker-compose.prod.yml up -d --remove-orphans - -# 4. Verify health -curl http://localhost:3001/health -curl http://localhost:3000/health -``` - -## Post-Deployment - -- [ ] Verify all services are running: `docker compose ps` -- [ ] Check application logs: `docker compose logs -f backend-api` -- [ ] Run smoke tests -- [ ] Verify metrics in Grafana -- [ ] Check Prometheus targets: http://localhost:9090/targets -- [ ] Confirm backups are working -- [ ] Update deployment log - -## Monitoring URLs - -- Grafana: http://localhost:3003 (or https://grafana.runebolt.io) -- Prometheus: http://localhost:9090 -- HAProxy Stats: http://localhost:8404/stats -- Vault UI: http://localhost:8200 - -## Backup Verification - -Run a test backup: -```bash -./scripts/backup.sh full --dry-run # Preview -./scripts/backup.sh full # Actual backup -``` - -## Rollback Procedure - -If deployment fails: -```bash -./scripts/deploy.sh production --rollback -``` - -Or manually: -```bash -# Stop current version -docker compose -f docker-compose.prod.yml down - -# Start previous version -export VERSION=previous-version -docker compose -f docker-compose.prod.yml up -d -``` - -## Emergency Contacts - -- Primary On-Call: [Your phone/email] -- Secondary: [Backup contact] -- Escalation: [Manager contact] diff --git a/legacy/taproot-assets-era/Dockerfile b/legacy/taproot-assets-era/Dockerfile deleted file mode 100644 index 9d715ae..0000000 --- a/legacy/taproot-assets-era/Dockerfile +++ /dev/null @@ -1,114 +0,0 @@ -# RuneBolt Production Dockerfile -# Multi-stage build for optimized production image -# Version: 1.0.0 - -# ============================================ -# Stage 1: Dependencies -# ============================================ -FROM node:20-alpine AS deps - -# Install build dependencies for native modules -RUN apk add --no-cache python3 make g++ \ - && npm install -g npm@latest - -WORKDIR /app - -# Copy package files first (better layer caching) -COPY package*.json ./ - -# Install production dependencies only -RUN npm ci --only=production --ignore-scripts && npm cache clean --force - -# ============================================ -# Stage 2: Builder (TypeScript compilation) -# ============================================ -FROM node:20-alpine AS builder - -WORKDIR /app - -# Install TypeScript -RUN npm install -g typescript - -# Copy package files -COPY package*.json ./ -COPY tsconfig.json ./ - -# Install all dependencies (including dev) -RUN npm ci --ignore-scripts - -# Copy source code -COPY src ./src - -# Build TypeScript -RUN tsc --build - -# ============================================ -# Stage 3: Production -# ============================================ -FROM node:20-alpine AS production - -# Security: Create non-root user -RUN addgroup -g 1001 -S runebolt && \ - adduser -S runebolt -u 1001 - -# Install security updates and required packages -RUN apk update && \ - apk upgrade && \ - apk add --no-cache \ - dumb-init \ - wget \ - ca-certificates && \ - rm -rf /var/cache/apk/* - -# Set working directory -WORKDIR /app - -# Copy production dependencies from deps stage -COPY --from=deps /app/node_modules ./node_modules -COPY --from=deps /app/package*.json ./ - -# Copy compiled JavaScript from builder stage -COPY --from=builder /app/dist ./dist - -# Create data directory for SQLite with proper permissions -RUN mkdir -p /data && \ - chown -R runebolt:runebolt /data /app - -# Switch to non-root user -USER runebolt - -# Environment variables -ENV NODE_ENV=production \ - PORT=3001 \ - DATABASE_PATH=/data/runebolt.db \ - UV_THREADPOOL_SIZE=128 - -# Expose port -EXPOSE 3001 - -# Health check -HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \ - CMD wget --quiet --tries=1 --spider http://localhost:3001/health || exit 1 - -# Use dumb-init for proper signal handling -ENTRYPOINT ["dumb-init", "--"] - -# Default command (can be overridden for workers) -CMD ["node", "dist/index.js"] - -# ============================================ -# Stage 4: Worker (alternative target) -# ============================================ -FROM production AS worker - -CMD ["node", "dist/worker.js"] - -# ============================================ -# Metadata -# ============================================ -LABEL org.opencontainers.image.title="RuneBolt Backend" \ - org.opencontainers.image.description="Bitcoin Layer 2 Payment Channel Hub" \ - org.opencontainers.image.version="1.0.0" \ - org.opencontainers.image.vendor="Bitmap Asset" \ - org.opencontainers.image.source="https://github.com/bitmap-asset/runebolt" \ - org.opencontainers.image.licenses="MIT" diff --git a/legacy/taproot-assets-era/INFRASTRUCTURE.md b/legacy/taproot-assets-era/INFRASTRUCTURE.md deleted file mode 100644 index 15122fe..0000000 --- a/legacy/taproot-assets-era/INFRASTRUCTURE.md +++ /dev/null @@ -1,454 +0,0 @@ -# RuneBolt Production Infrastructure Architecture - -**Version:** 1.0.0 -**Last Updated:** 2026-03-14 -**Target Uptime:** 99.99% (52.6 minutes downtime/year) -**RTO (Recovery Time Objective):** 15 minutes -**RPO (Recovery Point Objective):** 5 minutes - ---- - -## Executive Summary - -RuneBolt is a Bitcoin Layer 2 payment channel hub for DOG•GO•TO•THE•MOON Runes. This infrastructure is designed to handle financial transactions with bank-grade reliability, security, and compliance. - -### Key Design Principles - -1. **Defense in Depth** — Multiple security layers at every level -2. **Zero Trust** — No implicit trust between services or networks -3. **Immutable Infrastructure** — Version-controlled, reproducible deployments -4. **Observability First** — Every component emits metrics, logs, and traces -5. **Disaster Recovery** — Automated backups with tested restore procedures - ---- - -## System Architecture - -``` -┌─────────────────────────────────────────────────────────────────────────────┐ -│ CDN Layer (CloudFlare) │ -│ DDoS Protection • WAF • SSL Termination │ -└─────────────────────────────────────────────────────────────────────────────┘ - │ -┌─────────────────────────────────────────────────────────────────────────────┐ -│ Load Balancer (HAProxy) │ -│ Health Checks • Rate Limiting • SSL │ -└─────────────────────────────────────────────────────────────────────────────┘ - │ - ┌──────────────────────────────┼──────────────────────────────┐ - │ │ │ -┌───────▼────────┐ ┌─────────▼────────┐ ┌────────▼───────┐ -│ Primary DC │◄─────────►│ Vault Cluster │◄─────────►│ DR Region │ -│ (NYC - do nyc1)│ Replicate│ (Consul Backend)│ │(SF - do sfo3) │ -└────────────────┘ └──────────────────┘ └────────────────┘ - │ - │ ┌──────────────────────────────────────────────────────┐ - │ │ Docker Swarm Cluster │ - │ ├─────────────┬─────────────┬─────────────┬─────────────┤ - │ │ API Nodes │ Web Nodes │ WS Nodes │ Worker Nodes│ - │ │ (3x) │ (3x) │ (3x) │ (2x) │ - │ └─────────────┴─────────────┴─────────────┴─────────────┘ - │ - │ ┌──────────────────────────────────────────────────────┐ - │ │ Data Layer │ - │ ├─────────────┬─────────────┬─────────────┬─────────────┤ - │ │ PostgreSQL │ Redis │ SQLite │ MinIO │ - │ │ (Primary) │ (Cluster) │ (Per-Node) │ (Backups) │ - │ └─────────────┴─────────────┴─────────────┴─────────────┘ -``` - ---- - -## Component Breakdown - -### 1. Frontend (Next.js) - -| Aspect | Configuration | -|--------|---------------| -| Runtime | Node.js 20 LTS | -| Scaling | Horizontal (3 replicas minimum) | -| Memory | 512MB per container | -| CPU | 0.5 vCPU per container | -| Health Check | `/health` endpoint | - -**Services:** -- Static asset serving (CDN cached) -- Server-side rendering for SEO -- API proxying to backend - -### 2. Backend API (Node.js + Express) - -| Aspect | Configuration | -|--------|---------------| -| Runtime | Node.js 20 LTS | -| Scaling | Horizontal (3 replicas minimum) | -| Memory | 1GB per container | -| CPU | 1 vCPU per container | -| Health Check | `/health` endpoint | - -**Services:** -- REST API endpoints -- WebSocket real-time connections -- Channel management -- Bitcoin transaction coordination - -### 3. Database Layer - -#### PostgreSQL (Primary) -- **Version:** 15+ -- **Mode:** Primary + 2 Standby replicas (synchronous replication) -- **Backup:** Continuous WAL archiving to S3 -- **Connection Pooling:** PgBouncer (max 1000 connections) -- **Encryption:** At-rest (LUKS) + in-transit (TLS) - -#### Redis (Cache + Sessions + PubSub) -- **Mode:** Redis Cluster (6 nodes: 3 masters, 3 replicas) -- **Persistence:** AOF + RDB snapshots -- **Memory:** 2GB per node -- **Use Cases:** - - Session storage - - Rate limiting counters - - WebSocket pub/sub - - Cache layer - -#### SQLite (Per-Node) -- **Use:** Channel state machine persistence -- **Backup:** Hourly snapshots to object storage -- **Replication:** Application-level replication to standby - -### 4. Message Queue (NATS) - -- **Mode:** Cluster (3 nodes) -- **Persistence:** JetStream enabled -- **Use Cases:** - - Async transaction processing - - Bitcoin block notifications - - Inter-service communication - ---- - -## Security Architecture - -### Network Security - -``` -Internet → CloudFlare → WAF → HAProxy → Internal Network - │ - ┌─────────────────────────┼─────────────────────────┐ - │ │ │ - DMZ Network Application Network Data Network - (Public) (Private) (Isolated) - ───────────── ────────────── ──────────── - HAProxy nodes API containers Databases - VPN gateway Web containers Vault - Bastion host Worker nodes Redis -``` - -### Secrets Management (HashiCorp Vault) - -| Secret Type | Storage | Rotation | Access Pattern | -|-------------|---------|----------|----------------| -| API Keys | KV v2 | 90 days | AppRole + Kubernetes auth | -| DB Credentials | Database dynamic | 24 hours | Dynamic leases | -| Bitcoin Keys | Transit encryption | Manual | HSM-backed signing | -| TLS Certificates | PKI engine | 60 days | Auto-rotation | -| JWT Secrets | KV v2 | 30 days | AppRole | - -### HSM Integration - -For production Bitcoin key storage: -- **Option 1:** CloudHSM (AWS) or Cloud KMS (GCP) -- **Option 2:** Dedicated HSM (YubiHSM 2, Securosys Primus) -- **Integration:** Vault PKCS#11 provider - ---- - -## Monitoring & Observability - -### Metrics (Prometheus + Grafana) - -| Metric Category | Examples | -|-----------------|----------| -| Application | Request rate, latency p95/p99, error rate | -| Business | Active channels, transfer volume, fees collected | -| Infrastructure | CPU, memory, disk I/O, network | -| Bitcoin | Mempool size, confirmation times, fee rates | - -### Logging (Loki + Grafana) - -- **Retention:** 30 days hot, 1 year cold (S3) -- **Levels:** ERROR, WARN, INFO, DEBUG -- **Fields:** `service`, `trace_id`, `user_id`, `channel_id`, `amount` -- **Alerting:** ERROR logs → PagerDuty - -### Distributed Tracing (Jaeger) - -- **Sampling:** 1% production, 100% canary -- **Spans:** All API calls, database queries, Bitcoin RPC - -### Alerting Rules - -```yaml -Critical (P1 - Page): - - API error rate > 1% - - Database replication lag > 30s - - Bitcoin node sync > 10 blocks behind - - Vault sealed/unavailable - -High (P2 - Slack): - - CPU > 80% for 5 minutes - - Memory > 85% for 5 minutes - - Disk > 80% full - - SSL cert expires < 7 days - -Medium (P3 - Email): - - API latency p99 > 500ms - - Backup failure - - Rate limiting triggered -``` - ---- - -## Backup Strategy - -### Backup Schedule - -| Data Type | Frequency | Retention | Storage | -|-----------|-----------|-----------|---------| -| PostgreSQL | Continuous WAL + Daily full | 30 days hot, 1 year cold | S3 + Glacier | -| SQLite | Hourly snapshots | 7 days | S3 Standard | -| Redis | Daily RDB | 7 days | S3 Standard | -| Vault | Daily snapshot | 30 days | S3 + encrypted | -| Config/Terraform | Every change | Forever | Git + S3 | - -### Disaster Recovery - -**Scenario 1: Database Corruption** -1. Promote standby replica (RTO: 2 minutes) -2. Restore from WAL to point-in-time (RPO: <5 minutes) -3. Verify data integrity - -**Scenario 2: Complete Region Failure** -1. DNS failover to DR region (RTO: 5 minutes) -2. Restore databases from cross-region backups -3. Rebuild containers from immutable images - -**Scenario 3: Bitcoin Key Compromise** -1. Emergency channel closures -2. Rotate all keys via Vault -3. Audit all transactions - ---- - -## Deployment Pipeline - -### GitHub Actions Workflow - -``` -Push/PR - │ - ▼ -┌──────────────┐ -│ Lint/Test │ ← Unit tests, ESLint, TypeScript check -└──────┬───────┘ - │ - ▼ -┌──────────────┐ -│ Build Image │ ← Docker build, push to registry -└──────┬───────┘ - │ - ▼ -┌──────────────┐ -│ Security │ ← Trivy scan, Snyk dependency check -└──────┬───────┘ - │ - ▼ -┌──────────────┐ -│ Staging │ ← Deploy to staging, integration tests -└──────┬───────┘ - │ - ▼ -┌──────────────┐ -│ Production │ ← Canary → 25% → 50% → 100% -└──────────────┘ -``` - -### Deployment Strategy: Canary - -1. Deploy to 5% of traffic -2. Monitor error rates, latency for 10 minutes -3. If healthy, increase to 25%, 50%, 100% -4. Automatic rollback on error rate > 0.1% - ---- - -## Infrastructure as Code - -### Terraform Structure - -``` -terraform/ -├── environments/ -│ ├── production/ -│ │ ├── main.tf -│ │ ├── variables.tf -│ │ └── terraform.tfvars -│ └── staging/ -├── modules/ -│ ├── networking/ -│ ├── compute/ -│ ├── database/ -│ ├── vault/ -│ └── monitoring/ -└── backend.tf # S3 state with DynamoDB locking -``` - -### State Management - -- **Backend:** S3 with versioning -- **Locking:** DynamoDB -- **Encryption:** AES-256 -- **Backup:** Daily to separate bucket - ---- - -## SSL/TLS Architecture - -### Certificate Management - -| Layer | Certificate | Provider | Rotation | -|-------|-------------|----------|----------| -| CDN | Wildcard | Let's Encrypt (via Certbot) | 60 days | -| Load Balancer | Wildcard | Vault PKI | 90 days | -| Service-to-Service | mTLS | Vault PKI | 30 days | -| Database | Server + Client | Vault PKI | 90 days | - -### Certificate Rotation Process - -1. Vault generates new certificate -2. Deploy to service (rolling restart) -3. Verify connectivity -4. Revoke old certificate - ---- - -## Multi-Region Strategy - -### Primary Region: NYC (do-nyc1) -- Full deployment (API, Web, DB, Workers) -- Active traffic -- Real-time replication to DR - -### DR Region: SF (do-sfo3) -- Standby databases (async replication) -- Pre-warmed container registry -- Vault replica cluster -- DNS failover ready - -### Failover Process - -1. Detect failure (monitoring alert) -2. Update DNS (Route53 health checks) -3. Promote DR database to primary -4. Scale up DR containers -5. Verify functionality -6. Traffic redirects automatically - ---- - -## Capacity Planning - -### Current Capacity (Per Region) - -| Resource | Provisioned | Peak Usage | Headroom | -|----------|-------------|------------|----------| -| API Containers | 6 | 40% | 150% | -| Database CPU | 4 cores | 25% | 300% | -| Database Storage | 500GB | 15% | 550% | -| Redis Memory | 6GB | 30% | 200% | -| Bandwidth | 10Gbps | 10% | 900% | - -### Scaling Triggers - -- **Horizontal:** CPU > 70% for 5 minutes → +2 containers -- **Vertical:** DB connections > 80% → Upgrade instance -- **Storage:** > 70% full → Expand volume + notify - ---- - -## Compliance & Auditing - -### Audit Log Retention - -| Event Type | Retention | Storage | -|------------|-----------|---------| -| Authentication | 7 years | Immutable S3 | -| Channel operations | 7 years | Immutable S3 | -| Transfers | 7 years | Immutable S3 | -| Admin actions | 3 years | S3 Glacier | -| System events | 1 year | S3 Standard | - -### Security Scanning - -- **Container Images:** Trivy on every build -- **Dependencies:** Snyk weekly -- **Infrastructure:** Terraform compliance (tfsec) -- **Penetration Testing:** Quarterly - ---- - -## Cost Optimization - -### Reserved Capacity - -| Resource | Strategy | Savings | -|----------|----------|---------| -| Droplets | 1-year reserved | ~20% | -| Databases | 1-year reserved | ~15% | -| S3 | Intelligent tiering | ~40% | -| Bandwidth | CloudFlare caching | ~60% | - -### Right-sizing - -- Review resource usage weekly -- Auto-scale down during low traffic -- Use spot instances for batch workers - ---- - -## Runbook Index - -1. [Restart Services](./runbooks/01-restart-services.md) -2. [Database Restore](./runbooks/02-database-restore.md) -3. [Scale Infrastructure](./runbooks/03-scale-infrastructure.md) -4. [Vault Unseal](./runbooks/04-vault-unseal.md) -5. [SSL Certificate Rotation](./runbooks/05-ssl-rotation.md) -6. [Incident Response](./runbooks/06-incident-response.md) -7. [Bitcoin Node Recovery](./runbooks/07-bitcoin-recovery.md) - ---- - -## Architecture Decision Records (ADRs) - -| ADR | Decision | Status | -|-----|----------|--------| -| ADR-001 | Docker Swarm over Kubernetes (simpler ops) | Accepted | -| ADR-002 | SQLite for channel state (speed + portability) | Accepted | -| ADR-003 | HashiCorp Vault for secrets | Accepted | -| ADR-004 | DigitalOcean over AWS (cost + simplicity) | Accepted | -| ADR-005 | Loki over ELK (lower resource usage) | Accepted | - ---- - -## References - -- [Lightning Labs LND Docker Setup](https://github.com/lightningnetwork/lnd/tree/master/docker) -- [Cash App Platform Resilience](https://aws.amazon.com/blogs/architecture/improving-platform-resilience-at-cash-app) -- [HashiCorp Vault HSM Integration](https://developer.hashicorp.com/vault/docs/enterprise/hsm) -- [Bitcoin Financial Infrastructure Best Practices](https://www.sec.gov/files/cft-written-input-daniel-bruno-corvelo-costa-090325.pdf) - ---- - -**Document Owner:** Infrastructure Team -**Review Cycle:** Quarterly -**Next Review:** 2026-06-14 diff --git a/legacy/taproot-assets-era/INTEGRATION_GUIDE.md b/legacy/taproot-assets-era/INTEGRATION_GUIDE.md deleted file mode 100644 index b075434..0000000 --- a/legacy/taproot-assets-era/INTEGRATION_GUIDE.md +++ /dev/null @@ -1,298 +0,0 @@ -# RuneBolt UX Components - Integration Guide - -## Quick Start - -### 1. Using the Onboarding Flow - -```tsx -import { OnboardingFlow } from '@/components'; -import { useState } from 'react'; - -export default function HomePage() { - const [showOnboarding, setShowOnboarding] = useState(false); - - return ( - <> - - - setShowOnboarding(false)} - onComplete={(data) => { - console.log('User onboarded:', data); - // Redirect to dashboard or app - }} - /> - - ); -} -``` - -### 2. Using Error Messages - -```tsx -import { ErrorMessage, mapErrorToType } from '@/components'; - -// In your component -const [error, setError] = useState(null); - -// When an error occurs -const handleError = (err: Error) => { - const errorType = mapErrorToType(err.message); - setError(errorType); -}; - -// Render -{error && ( - { - if (action === 'retry') { - // Retry the operation - } else if (action === 'add_funds') { - // Navigate to deposit page - } - }} - /> -)} -``` - -### 3. Using Transaction Status - -```tsx -import { - useTransactionStatus, - TransactionToastContainer, - TransactionStatusIndicator -} from '@/components'; - -export default function SendPage() { - const { transactions, addTransaction, dismissTransaction } = useTransactionStatus(); - const [currentTx, setCurrentTx] = useState(null); - - const handleSend = async () => { - const txId = crypto.randomUUID(); - - // Add transaction to tracking - addTransaction({ - id: txId, - type: 'send', - status: 'pending', - amount: 1000, - recipient: '@alice', - }); - - setCurrentTx(txId); - - // Call your API - const response = await fetch('/api/v1/transfers', { ... }); - - if (response.ok) { - // WebSocket will update the status - } else { - // Handle error - } - }; - - return ( - <> - {/* Toast notifications */} - - - {/* Inline status indicator */} - {currentTx && ( - t.id === currentTx)!} - onClose={() => setCurrentTx(null)} - /> - )} - - - - ); -} -``` - -### 4. Using Claim Links - -```tsx -import { ClaimLink } from '@/components'; -import { useState } from 'react'; - -export default function GiftPage() { - const [showClaimLink, setShowClaimLink] = useState(false); - - return ( - <> - - - setShowClaimLink(false)} - maxBalance={125000} - userPubkey="user_pubkey_here" - /> - - ); -} -``` - -### 5. Using Username Resolution - -```tsx -// Resolve username to pubkey -const resolveUsername = async (username: string) => { - const response = await fetch(`/api/v1/usernames/${username}`); - const data = await response.json(); - - if (data.success) { - return data.data.pubkey; - } else { - // Handle user-friendly error - console.log(data.userFriendly); - } -}; - -// Check username availability -const checkUsername = async (username: string) => { - const response = await fetch(`/api/v1/usernames/check/${username}`); - const data = await response.json(); - return data.data.available; -}; - -// Register username -const registerUsername = async (username: string, token: string) => { - const response = await fetch('/api/v1/usernames/register', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${token}`, - }, - body: JSON.stringify({ username }), - }); - return response.json(); -}; -``` - -### 6. WebSocket Setup for Transaction Status - -```tsx -import { useEffect, useRef } from 'react'; - -export default function App() { - const wsRef = useRef(null); - - useEffect(() => { - const ws = new WebSocket('wss://api.runebolt.io/ws'); - wsRef.current = ws; - - ws.onopen = () => { - console.log('Connected to RuneBolt'); - - // Subscribe to transaction updates - ws.send(JSON.stringify({ - type: 'subscribe_transactions', - pubkey: 'your_pubkey', - })); - }; - - ws.onmessage = (event) => { - const message = JSON.parse(event.data); - - if (message.type === 'transaction_update') { - const tx = message.data; - - // Update your UI - console.log(`Transaction ${tx.id} is now ${tx.status}`); - - if (tx.status === 'confirmed') { - // Show success notification - } else if (tx.status === 'failed') { - // Show error notification - } - } - }; - - return () => { - ws.close(); - }; - }, []); - - return
Your App
; -} -``` - -## Component Props Reference - -### OnboardingFlow -| Prop | Type | Description | -|------|------|-------------| -| isOpen | boolean | Controls modal visibility | -| onClose | () => void | Called when modal closes | -| onComplete | (data) => void | Called when onboarding completes | - -### ErrorMessage -| Prop | Type | Description | -|------|------|-------------| -| error | ErrorType \| string | The error type or message | -| context | 'toast' \| 'inline' \| 'page' | Display style | -| onAction | (action: string) => void | Called when user clicks action | -| technicalError | string | Technical details (optional) | - -### TransactionStatusIndicator -| Prop | Type | Description | -|------|------|-------------| -| transaction | TransactionState | The transaction to display | -| onClose | () => void | Called when closed | -| showDetails | boolean | Show detailed info | -| context | 'inline' \| 'modal' \| 'page' | Display style | - -### ClaimLink -| Prop | Type | Description | -|------|------|-------------| -| isOpen | boolean | Controls modal visibility | -| onClose | () => void | Called when modal closes | -| maxBalance | number | User's available balance | -| userPubkey | string | User's public key | - -## Error Types - -Available error types for `mapErrorToType()`: - -- `wallet_not_connected` -- `connection_rejected` -- `wallet_locked` -- `network_mismatch` -- `insufficient_funds` -- `no_active_account` -- `transfer_failed` -- `recipient_not_found` -- `amount_too_small` -- `funding_pending` -- `mempool_congestion` -- `service_unavailable` -- `unknown` - -## Transaction Status Types - -Transaction statuses: -- `pending` - Transaction submitted, waiting for processing -- `confirming` - On-chain transaction waiting for confirmations -- `confirmed` - Transaction complete -- `failed` - Transaction failed - -## Tips - -1. **Error Handling**: Always use `mapErrorToType()` to convert technical errors to user-friendly ones -2. **WebSocket**: Subscribe to transaction updates as early as possible in your app lifecycle -3. **Claim Links**: Store generated claim link IDs locally so users can track them -4. **Username Validation**: Use the same regex (`/^[a-zA-Z0-9_]{3,20}$/`) on client and server -5. **Mobile**: The ClaimLink component uses native share sheets on mobile devices diff --git a/legacy/taproot-assets-era/PERFORMANCE_ROADMAP.md b/legacy/taproot-assets-era/PERFORMANCE_ROADMAP.md deleted file mode 100644 index c264b62..0000000 --- a/legacy/taproot-assets-era/PERFORMANCE_ROADMAP.md +++ /dev/null @@ -1,338 +0,0 @@ -# RuneBolt Performance Roadmap - -## Executive Summary - -Current RuneBolt architecture analyzed and optimized for mass adoption (millions of users, billions of transactions). - -## Current State Bottlenecks - -### 1. Database Layer (SQLite) -- **Write contention**: Database-level locking serializes concurrent writes -- **No connection pooling**: Each connection is isolated -- **Single-node constraint**: Cannot scale horizontally -- **Query issues**: OR conditions prevent index usage in transfer lookups - -### 2. Architecture Issues -- Synchronous operations block event loop -- No worker thread utilization -- In-memory commitment storage (lost on restart) -- No rate limiting or DDoS protection -- Single WebSocket server (no horizontal scaling) - -### 3. Resource Management -- Unbounded data growth (no pruning) -- No caching layer -- No connection limits -- Memory leaks possible in WebSocket manager - -## Performance Targets - -| Metric | Current | 12-Month | 24-Month | -|--------|---------|----------|----------| -| TPS | ~100 | 2,000 | 10,000+ | -| Users | ~1,000 | 50,000 | 500,000+ | -| Latency p99 | ~50ms | <20ms | <10ms | -| Availability | Single point | 99.9% | 99.99% | - -## Migration Path: SQLite → PostgreSQL - -### Schema Optimizations - -```sql --- Partitioned transfers table for time-series data -CREATE TABLE transfers ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - from_channel UUID NOT NULL REFERENCES channels(id), - to_channel UUID NOT NULL REFERENCES channels(id), - amount BIGINT NOT NULL CHECK (amount > 0), - memo VARCHAR(256), - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -) PARTITION BY RANGE (created_at); - --- Monthly partitions -CREATE TABLE transfers_2026_03 PARTITION OF transfers - FOR VALUES FROM ('2026-03-01') TO ('2026-04-01'); - --- Optimized indexes (no OR conditions) -CREATE INDEX idx_transfers_sender ON transfers(from_channel, created_at DESC) - INCLUDE (id, to_channel, amount, memo); -CREATE INDEX idx_transfers_recipient ON transfers(to_channel, created_at DESC) - INCLUDE (id, from_channel, amount, memo); - --- Partial index for hot data only -CREATE INDEX idx_channels_active ON channels(user_pubkey, state) - WHERE state = 'OPEN'; -``` - -## Critical Path Optimizations - -### 1. Transfer Execution (Hot Path) - -**Current Issues:** -- Synchronous database transaction -- Balance updates are blocking -- No caching of channel state -- Commitment manager uses in-memory store - -**Optimized Transfer Flow:** -```typescript -// Optimized transfer with caching and worker threads -class OptimizedRuneLedger { - async transfer(fromId: string, toId: string, amount: bigint): Promise { - // 1. Check cache first (sub-millisecond) - const fromBalance = await this.cache.getChannelBalance(fromId); - const toBalance = await this.cache.getChannelBalance(toId); - - // 2. Validate without DB hit - if (!fromBalance || fromBalance.local < amount) { - throw new Error('Insufficient balance'); - } - - // 3. Execute in worker thread (non-blocking) - return this.workerPool.execute('transfer', { - fromId, toId, amount, - fromBalance, toBalance - }); - } -} -``` - -### 2. WebSocket Scaling - -```typescript -// Redis-backed WebSocket for horizontal scaling -class ScalableWebSocketManager { - private redis: Redis; - - async broadcastToChannel(channelId: string, event: string, data: unknown) { - // Publish to Redis pub/sub - await this.redis.publish(`channel:${channelId}`, JSON.stringify({event, data})); - } -} -``` - -### 3. Rate Limiting - -```typescript -// Token bucket rate limiter per user -class RateLimiter { - async checkLimit(pubkey: string, action: string): Promise { - const key = `ratelimit:${pubkey}:${action}`; - const current = await this.redis.incr(key); - - if (current === 1) { - await this.redis.expire(key, 60); // 1 minute window - } - - return current <= 100; // 100 requests per minute - } -} -``` - -## Monitoring Dashboard Specs - -### Metrics to Track - -| Metric | Type | Alert Threshold | -|--------|------|-----------------| -| transfer_latency_p99 | Histogram | > 50ms | -| transfer_rate | Counter | - | -| active_channels | Gauge | - | -| ws_connections | Gauge | > 10,000 | -| db_pool_wait_time | Histogram | > 10ms | -| redis_hit_rate | Gauge | < 90% | -| error_rate | Counter | > 1% | - -### Grafana Dashboard Panels -1. Real-time TPS graph -2. Latency percentiles (p50, p95, p99) -3. Database connection pool status -4. Cache hit/miss rates -5. Channel state distribution -6. Error rate by endpoint -7. WebSocket connection count -8. Bitcoin mempool fee estimates - -## Implementation Roadmap - -### Phase 1 (Weeks 1-4): Foundation -- [ ] PostgreSQL migration scripts -- [ ] Connection pooling setup -- [ ] Basic Redis caching (channel balances) -- [ ] Rate limiting middleware - -### Phase 2 (Weeks 5-8): Scaling -- [ ] Worker thread pool for transfers -- [ ] Database partitioning for transfers -- [ ] WebSocket Redis pub/sub -- [ ] Health checks and graceful shutdown - -### Phase 3 (Weeks 9-12): Production -- [ ] Horizontal scaling support (stateless nodes) -- [ ] Comprehensive monitoring -- [ ] Load testing and optimization -- [ ] Data retention policies - -### Phase 4 (Months 4-6): Advanced -- [ ] Multi-region deployment -- [ ] Automatic failover -- [ ] Advanced caching strategies -- [ ] Channel pruning and archival - -## Lightning Network Research Findings - -### LND vs CLN Insights -- LND: Better payment success rate, optimized pathfinding -- CLN: More modular, better for custom implementations -- Both use similar channel state machine patterns - -### Key Scalability Lessons -1. **Batch operations**: Process multiple HTLCs in single commitment -2. **Routing optimization**: Use channel liquidity hints for pathfinding -3. **Gossip pruning**: Limit network topology updates -4. **State compaction**: Periodic cleanup of old channel states - -### Bitcoin L2 Throughput Limits -- Lightning: Theoretical 1M+ TPS (limited by channel capacity) -- Practical: 100-1000 TPS per node -- RuneBolt hub model: Can batch many user transfers off-chain - -## Code Samples - -### Optimized Database Queries - -```typescript -// BEFORE: Slow OR query -const query = ` - SELECT t.* FROM transfers t - JOIN channels c ON (t.from_channel = c.id OR t.to_channel = c.id) - WHERE c.user_pubkey = $1 - ORDER BY t.created_at DESC LIMIT $2 OFFSET $3 -`; - -// AFTER: Two fast queries merged -const sent = await db.query( - `SELECT * FROM transfers WHERE from_channel = ANY($1) - ORDER BY created_at DESC LIMIT $2`, - [channelIds, limit] -); -const received = await db.query( - `SELECT * FROM transfers WHERE to_channel = ANY($1) - ORDER BY created_at DESC LIMIT $2`, - [channelIds, limit] -); -// Merge and sort in memory -``` - -### Connection Pool Configuration - -```typescript -const pool = new Pool({ - connectionString: process.env.DATABASE_URL, - max: 50, // Max connections - min: 10, // Min connections - idleTimeoutMillis: 30000, // Close idle connections - connectionTimeoutMillis: 5000, - statement_timeout: 10000, // Kill slow queries -}); -``` - -### Batch Transfer Processing - -```typescript -class BatchTransferProcessor { - private batch: TransferRequest[] = []; - private batchSize = 100; - private flushInterval = 100; // ms - - async addTransfer(request: TransferRequest): Promise { - return new Promise((resolve, reject) => { - this.batch.push({ ...request, resolve, reject }); - - if (this.batch.length >= this.batchSize) { - this.flush(); - } - }); - } - - private async flush(): Promise { - const toProcess = this.batch.splice(0, this.batchSize); - - // Single transaction for all transfers - await this.db.transaction(async (client) => { - for (const transfer of toProcess) { - try { - const result = await this.executeTransfer(client, transfer); - transfer.resolve(result); - } catch (err) { - transfer.reject(err); - } - } - }); - } -} -``` - -## Memory Leak Prevention - -```typescript -// Fixed WebSocket manager with cleanup -class MemorySafeWebSocketManager { - private clients = new Map(); - private heartbeatInterval: NodeJS.Timeout; - - constructor() { - // Periodic cleanup of stale connections - this.heartbeatInterval = setInterval(() => { - this.cleanupStaleConnections(); - }, 30000); - } - - private cleanupStaleConnections(): void { - const now = Date.now(); - for (const [id, client] of this.clients) { - if (now - client.lastPong > 60000) { - client.ws.terminate(); // Force close - this.clients.delete(id); - } - } - } -} -``` - -## DDoS Protection - -```typescript -// Multi-layer protection -class DDoSProtection { - // Layer 1: IP-based rate limiting - async checkIPLimit(ip: string): Promise { - const key = `ip:${ip}`; - const count = await this.redis.incr(key); - if (count === 1) await this.redis.expire(key, 1); - return count <= 100; // 100 req/sec per IP - } - - // Layer 2: User-based rate limiting - async checkUserLimit(pubkey: string): Promise { - const key = `user:${pubkey}`; - const count = await this.redis.incr(key); - if (count === 1) await this.redis.expire(key, 60); - return count <= 60; // 60 req/min per user - } - - // Layer 3: Global rate limiting - async checkGlobalLimit(): Promise { - const key = 'global:requests'; - const count = await this.redis.incr(key); - if (count === 1) await this.redis.expire(key, 1); - return count <= 10000; // 10k req/sec globally - } -} -``` - ---- - -*Document Version: 1.0* -*Analysis Date: March 14, 2026* -*Target: Mass adoption scalability* \ No newline at end of file diff --git a/legacy/taproot-assets-era/PERFORMANCE_SUMMARY.md b/legacy/taproot-assets-era/PERFORMANCE_SUMMARY.md deleted file mode 100644 index 4deae11..0000000 --- a/legacy/taproot-assets-era/PERFORMANCE_SUMMARY.md +++ /dev/null @@ -1,88 +0,0 @@ -# RuneBolt Performance Analysis - Summary - -## Analysis Completed - -### Key Findings - -1. **Database Layer (Critical)** - - SQLite limits concurrent writes (database-level locking) - - No connection pooling currently implemented - - Query using OR condition prevents index usage - - Solution: Migrate to PostgreSQL with partitioning - -2. **Architecture Issues (High)** - - In-memory commitment storage (data loss on restart) - - No worker threads for CPU-intensive operations - - Synchronous operations block event loop - - Solution: Implement Redis + worker pools - -3. **Scalability Blockers (High)** - - No rate limiting or DDoS protection - - Unbounded data growth (no pruning) - - Single WebSocket server (no horizontal scaling) - - Solution: Multi-layer rate limiting + Redis pub/sub - -### Deliverables Created - -1. ✅ `/Users/gravity/projects/runebolt/PERFORMANCE_ROADMAP.md` - - Comprehensive performance roadmap - - Target metrics for 12/24 months - - Implementation phases - -2. ✅ `/Users/gravity/projects/runebolt/migrations/001_postgres_schema.sql` - - PostgreSQL schema with partitions - - Optimized indexes (no OR conditions) - - Stored procedures for atomic operations - - Maintenance functions - -3. ✅ `/Users/gravity/projects/runebolt/monitoring/dashboard-specs.json` - - Grafana dashboard specification - - 8 panels covering all critical metrics - - 3 alert definitions - -4. ✅ `/Users/gravity/projects/runebolt/optimized/` (code samples) - - OptimizedDatabase class with pooling - - RuneBoltCache with Redis + local cache - - RateLimiter with multi-layer protection - - BatchTransferProcessor for throughput - -### Performance Targets - -| Metric | Now | 12 Months | 24 Months | -|--------|-----|-----------|-----------| -| TPS | 100 | 2,000 | 10,000+ | -| Users | 1,000 | 50,000 | 500,000+ | -| Latency p99 | 50ms | <20ms | <10ms | -| Availability | SPoF | 99.9% | 99.99% | - -### Critical Path Optimizations - -1. **Transfer Hot Path** - - Cache channel balances locally + Redis - - Use PostgreSQL stored procedure for atomic updates - - Batch transfers when possible - -2. **Database Queries** - - Replace OR condition with two indexed queries - - Use covering indexes for common lookups - - Partition transfers table by month - -3. **WebSocket Scaling** - - Add Redis pub/sub for multi-node broadcasting - - Implement heartbeat and stale connection cleanup - -### Lightning Network Research Insights - -- LND optimized pathfinding > CLN for success rate -- Both use similar channel state machine patterns -- Hub model allows batching (RuneBolt advantage) -- Key lessons: batch HTLCs, gossip pruning, state compaction - -### Recommended Next Steps - -1. Week 1: Set up PostgreSQL + run migration scripts -2. Week 2: Implement Redis caching layer -3. Week 3: Add rate limiting middleware -4. Week 4: Deploy monitoring dashboard -5. Month 2: Worker thread pool + batch processing -6. Month 3: Load testing + optimization diff --git a/legacy/taproot-assets-era/PROTOCOL_RESEARCH.md b/legacy/taproot-assets-era/PROTOCOL_RESEARCH.md deleted file mode 100644 index b235817..0000000 --- a/legacy/taproot-assets-era/PROTOCOL_RESEARCH.md +++ /dev/null @@ -1,303 +0,0 @@ -# RuneBolt Protocol Research - -**Research Date:** March 14, 2026 -**Scope:** Cutting-edge Bitcoin L2 technologies for competitive advantage - ---- - -## Executive Summary - -This research analyzes Bitcoin Layer 2 technologies and innovations that RuneBolt can adopt. Key findings: - -1. **OP_CAT/OP_CTV activation likely 2025-2027** - enables covenants and vaults -2. **BitVM bridges** - trust-minimized cross-chain interoperability -3. **Taproot Assets v0.6** - live on mainnet with Lightning support -4. **BOLT 12 + Trampoline routing** - reusable offers and mobile payments -5. **Fedimint** - privacy-preserving federated custody - ---- - -## Top 5 Features to Implement - -1. **BitVM-based Bridge Architecture** - Trust-minimized Runes bridging without waiting for soft forks -2. **BOLT 12 Payment Offers** - Static, reusable payment codes for merchants -3. **DLC Oracle Contracts** - Derivatives and prediction markets for Runes -4. **Fedimint Integration** - Community custody with Chaumian e-cash privacy -5. **Trampoline Routing** - Mobile-friendly Lightning without full graph - ---- - -## 1. Lightning Network Developments - -### 1.1 Taproot Channels -- Uses Schnorr signatures for key aggregation -- MAST hides unexecuted script branches -- Reduces on-chain footprint - -**RuneBolt Action:** Use Taproot channels for all Lightning integrations - -### 1.2 BOLT 12 (Offers) -| Feature | BOLT 11 | BOLT 12 | -|---------|---------|---------| -| Reusability | Single-use | Multi-use | -| Privacy | Reveals node ID | Blinded paths | -| UX | Complex QR | Human-readable | - -**Status:** CLN ready, LDK implementing, LND planned - -### 1.3 Trampoline Routing -Outsources pathfinding to intermediate nodes: -- Mobile clients don't need full graph -- Multiple hops for privacy -- LDK #3446, #3670; Eclair #2811 - ---- - -## 2. Runes Protocol Improvements - -**Current State:** Etching + minting + transferring via OP_RETURN - -**Identified Improvements:** -1. Batch etching (multiple runes in one tx) -2. Commit-reveal optimization -3. Cross-input aggregation -4. Atomic swap standards -5. Lightning integration (opportunity!) - -**Competitive Gap:** No major player does Runes over Lightning yet - ---- - -## 3. State Channel Innovations - -### 3.1 Eltoo (LN-Symmetry) -- Requires BIP-118 (SIGHASH_ANYPREVOUT) -- Simpler watchtowers (O(1) storage) -- No penalty, just correction - -### 3.2 Watchtowers -- **PISA:** Accountable watchtowers with slashing -- **Cerberus:** No collateral required -- **Sleepy Channels:** Remove fees entirely - -### 3.3 Statechains (Mercury Layer) -- Off-chain transfers without channels -- Blind MuSig2 signing -- Production ready - ---- - -## 4. Cross-Chain Bridges - -### 4.1 BitVM Architecture -- Fraud proof-based verification -- 1-of-n honesty assumption -- No soft fork required -- Challenge period: ~2 weeks - -**2025 Developments:** -- StarkWare verified STARK on Signet -- Bitlayer building bridges to major L2s -- Collider-script: covenants without OP_CAT - -### 4.2 Bridge Security Patterns -- **Federated:** Liquid, WBTC -- **Optimistic:** BitVM -- **ZK-verified:** Future with OP_CAT - ---- - -## 5. ZK Proofs for Bitcoin - -### 5.1 StarkNet on Bitcoin -- First L2 settling on both BTC and ETH -- Requires OP_CAT activation -- Estimated mainnet: 2025-2026 - -### 5.2 BitcoinOS -- Graviton ZK-proof system -- BitSNARK verifier -- General-purpose smart contracts - ---- - -## 6. Federated Custody (Fedimint) - -**Status:** Open source (January 2026) - -**Architecture:** -- 4+ guardians in federation -- Chaumian e-cash notes -- Blind signatures for privacy -- Offline capable - -**RuneBolt Integration:** -- Fedimint module for Runes -- Community mints -- Privacy layer for transactions - ---- - -## 7. Discreet Log Contracts (DLCs) - -**Mechanism:** Oracle signatures enable conditional payments - -**2025 Developments:** -- DLC Factories (options, futures) -- Off-chain DLC channels -- Chainlink oracle integration - -**Use Cases:** -- Runes price derivatives -- Stablecoins backed by BTC -- Prediction markets -- Insurance contracts - ---- - -## 8. Bitcoin Upgrade Timeline - -| BIP | Purpose | Status | ETA | -|-----|---------|--------|-----| -| BIP 347 | OP_CAT | Assigned | 2026-2027 | -| BIP 119 | OP_CTV | Assigned | 2026-2027 | -| BIP 118 | ANYPREVOUT | Proposed | Unknown | -| BIP 345 | OP_VAULT | Proposed | Unknown | - -**Strategy:** Build without covenants now (BitVM, DLCs), upgrade later - ---- - -## 9. Competitor Analysis - -### Taproot Assets (Lightning Labs) -- **Status:** Mainnet v0.6 (June 2025) -- **Focus:** Stablecoins (USDT, USDC) -- **Strength:** Production ready, Tether partnership -- **Gap:** No Runes support - -### RGB Protocol -- **Status:** Development -- **Focus:** Client-side validation, privacy -- **Gap:** Complex, limited adoption - -### Liquid Network -- **Status:** Production -- **Focus:** Sidechain for exchanges -- **Gap:** Federated, not trustless - -### ROL (Rune Open Ledger) -- **Status:** Emerging -- **Focus:** Runes-specific L2 - -**RuneBolt Differentiation:** -- First Runes-native Lightning integration -- BitVM bridges vs federated custody -- DLC-powered derivatives - ---- - -## 10. Technical Specification: BitVM Bridge for Runes - -### Overview -Implement a trust-minimized bridge allowing Runes to move between Bitcoin L1 and RuneBolt L2. - -### Architecture - -``` -┌─────────────┐ ┌──────────────┐ ┌─────────────┐ -│ Bitcoin L1 │────▶│ BitVM Bridge│────▶│ RuneBolt L2 │ -│ (Runes) │◀────│ (1-of-n) │◀────│ (Fast TX) │ -└─────────────┘ └──────────────┘ └─────────────┘ -``` - -### Components - -1. **Operators (n = 5-15)** - - Run full nodes for both chains - - Lock collateral in multisig - - Execute honest withdrawals - -2. **BitVM Circuit** - - Validates withdrawal requests - - Enforces consensus rules - - Generates fraud proofs - -3. **Challenge Period (14 days)** - - Operators can challenge invalid withdrawals - - Fraud proof submitted to Bitcoin - - Slash malicious operators - -### Security Model -- **Honest majority:** 1-of-n operators honest = funds safe -- **Collateral:** Operators stake 150% of bridged value -- **Insurance pool:** Shared risk for large withdrawals -- **Time delays:** 24hr for <10 BTC, 14 days for >100 BTC - -### Implementation Phases - -**Phase 1: Federated (Q2 2026)** -- 5-of-9 multisig -- No BitVM yet -- Fast deployment - -**Phase 2: Optimistic (Q4 2026)** -- Add BitVM fraud proofs -- Challenge period enabled -- Gradual decentralization - -**Phase 3: ZK-Verified (2027+)** -- OP_CAT activated -- STARK proof verification -- Minimal trust assumptions - -### Code Structure -``` -/contracts - /bridge - Bridge.sol # L2 bridge contract - Vault.sol # L1 vault contract - /bitvm - Verifier.ts # Fraud proof verifier - Challenge.ts # Challenge protocol - /runes - Indexer.ts # Runes UTXO tracking - Transfer.ts # Runes transfer logic -``` - ---- - -## 11. Protocol Upgrade Mechanism - -### Version Negotiation -- Nodes announce supported features via P2P handshake -- Soft fork detection via block version bits -- Graceful degradation for unsupported features - -### Soft Fork Strategy -1. **Signal readiness** (80% hashrate threshold) -2. **Activate** (2-week grace period) -3. **Enforce** (new rules mandatory) - -### Emergency Updates -- Federation can pause bridge (2-of-5 multisig) -- 48-hour timelock for critical fixes -- User exit always available - ---- - -## Research Sources - -- Bitcoin Optech Newsletters (#386-#396) -- Lightning BOLTs specifications -- StarkWare Bitcoin research -- Galaxy Research OP_CAT/CTV analysis -- BitVM whitepaper (Aumayr et al.) -- Fedimint documentation -- MIT DCI DLC research -- Lightning Labs Taproot Assets v0.6 release notes - ---- - -*Research completed: March 14, 2026* -*Next review: June 2026* \ No newline at end of file diff --git a/legacy/taproot-assets-era/README.md b/legacy/taproot-assets-era/README.md deleted file mode 100644 index a9a2278..0000000 --- a/legacy/taproot-assets-era/README.md +++ /dev/null @@ -1,126 +0,0 @@ -# RuneBolt - -Instant $DOG (Rune) transfers using off-chain payment channels on Bitcoin. - -RuneBolt is a hub-based Rune Channel system. Users open channels with RuneBolt (locking DOG in 2-of-2 Taproot multisig on Bitcoin L1), then transfer DOG instantly off-chain. Think "Lightning Network for Runes." - -## Architecture - -``` -runebolt/ -├── backend/ # Node.js + Express + TypeScript API server -├── frontend/ # Next.js 14 + Tailwind CSS web app -└── sdk/ # @runebolt/sdk — npm package for integrations -``` - -### Backend -- **Channel Manager** — Open/close/state management with 2-of-2 Taproot multisig -- **Rune Ledger** — Off-chain double-entry balance tracking -- **Rune Protocol** — Parse and build Runestones for DOG transfers -- **Bitcoin Integration** — mempool.space API for UTXOs and broadcasting -- **WebSocket** — Real-time balance update notifications -- **Auth** — Bitcoin-native authentication (sign challenge with Taproot key) -- **SQLite** — Persistent storage with better-sqlite3 - -### Frontend -- Premium dark fintech UI (Phantom wallet meets Bloomberg terminal) -- Landing page, Dashboard, Send/Receive, Channel Management, History, Claim Links -- Unisat wallet integration -- Framer Motion animations throughout - -### SDK -- `RuneBoltClient` — Simple API for games and apps -- Methods: `initChannel()`, `sendDOG()`, `getBalance()`, `onTransfer(callback)` -- WebSocket real-time balance subscriptions - -## Quick Start - -### Prerequisites -- Node.js 18+ -- npm - -### Backend - -```bash -cd backend -cp .env.example .env -npm install -npm run dev -``` - -Server starts on `http://localhost:3001` - -### Frontend - -```bash -cd frontend -npm install -npm run dev -``` - -App starts on `http://localhost:3000` - -### SDK - -```bash -cd sdk -npm install -npm run build -``` - -## API Endpoints - -| Method | Path | Description | -|--------|------|-------------| -| POST | `/api/v1/auth/challenge` | Generate auth challenge | -| POST | `/api/v1/auth/verify` | Verify signed challenge, get JWT | -| POST | `/api/v1/channel/open` | Initiate channel open | -| POST | `/api/v1/channel/activate` | Submit signed funding PSBT | -| POST | `/api/v1/channel/close` | Cooperative channel close | -| GET | `/api/v1/channel/:id` | Get channel state | -| POST | `/api/v1/transfer` | Send DOG transfer | -| GET | `/api/v1/user/:pubkey` | Get user info + channels | -| GET | `/api/v1/history/:pubkey` | Transfer history | -| POST | `/api/v1/claim/create` | Create claim link | -| GET | `/api/v1/claim/:id` | Get claim link details | -| GET | `/.well-known/rune-address/:username` | Resolve RuneBolt address | - -## SDK Usage - -```typescript -import { RuneBoltClient } from '@runebolt/sdk'; - -const client = new RuneBoltClient({ - apiUrl: 'https://api.runebolt.io', - authToken: 'your-jwt-token', -}); - -// Send DOG instantly -await client.sendDOG({ - fromChannelId: 'channel-123', - recipientPubkey: '02abc...', - amount: '100000', - memo: 'Payment for services', -}); - -// Subscribe to incoming transfers -const unsubscribe = client.onTransfer((event) => { - console.log(`Received ${event.transfer.amount} DOG`); - console.log(`New balance: ${event.newBalance.available}`); -}); -``` - -## DOG Rune Details -- **Rune**: DOG•GO•TO•THE•MOON -- **Rune ID**: `1:0` -- **Network**: Bitcoin Mainnet - -## Tech Stack -- **Backend**: Node.js, Express, TypeScript, SQLite, WebSocket -- **Frontend**: Next.js 14, React 18, Tailwind CSS, Framer Motion -- **SDK**: TypeScript, WebSocket -- **Bitcoin**: bitcoinjs-lib, mempool.space API, Taproot/MuSig2 - -## License - -MIT diff --git a/legacy/taproot-assets-era/RESEARCH_AGENT_1_FINDINGS.md b/legacy/taproot-assets-era/RESEARCH_AGENT_1_FINDINGS.md deleted file mode 100644 index ee77bdf..0000000 --- a/legacy/taproot-assets-era/RESEARCH_AGENT_1_FINDINGS.md +++ /dev/null @@ -1,1292 +0,0 @@ -# Block Genomics + RuneBolt Deep Research Findings - -**Research Agent:** Subagent 1 (Auto-Research Methodology) -**Date:** March 14, 2026 -**Objective:** Analyze Block Genomics + Nexus platform and provide comprehensive improvement recommendations -**Status:** ITERATION 1 — Initial Deep Analysis - ---- - -## Executive Summary - -After deep analysis of the RuneBolt codebase, competitive landscape, and emerging Bitcoin L2 ecosystem, I've identified **the single biggest opportunity in Bitcoin**: - -**Block Genomics + RuneBolt has the potential to become the definitive platform for AI agent verification AND instant Rune transfers — but only if it executes on four critical areas:** - -1. **AI Agent Identity Layer** — First-mover advantage in Bitcoin-native agent verification -2. **Taproot Assets Integration** — Add stablecoin support (USDT on Lightning is LIVE) -3. **UX Simplification** — Hide the channel complexity entirely -4. **Security Hardening** — The security audit reveals 14 vulnerabilities that must be fixed - ---- - -## Part 1: What RuneBolt Does Well - -### ✅ Strengths Identified - -| Area | Assessment | Score | -|------|------------|-------| -| **Protocol Design** | Hub-based channel model is simpler than full Lightning Network routing | 8/10 | -| **Code Quality** | TypeScript, clean architecture, separation of concerns | 7/10 | -| **Documentation** | Exceptional — INFRASTRUCTURE.md, PROTOCOL_RESEARCH.md show deep thought | 9/10 | -| **UX Vision** | UX_MASS_ADOPTION.md demonstrates understanding of consumer needs | 8/10 | -| **SDK** | Clean API, WebSocket real-time events, good developer ergonomics | 8/10 | -| **BitVM Research** | SPECS_BITVM_BRIDGE.md shows forward-thinking bridge architecture | 9/10 | - -### Key Technical Wins: - -1. **2-of-2 Taproot Multisig** — Proper use of Taproot for channel funding -2. **Hub-based Model** — Eliminates routing complexity (unlike Lightning) -3. **Redis Caching** — Sub-millisecond balance lookups -4. **Worker Thread Pool** — Non-blocking transfer execution -5. **Batch Processing** — 100-transfer batches for high throughput -6. **Commitment Manager** — State machine for channel lifecycle - ---- - -## Part 2: Critical Security Gaps (MUST FIX BEFORE LAUNCH) - -The security audit reveals **14 vulnerabilities**. These are BLOCKERS: - -### 🔴 CRITICAL (Fix Immediately) - -| ID | Issue | Risk | Solution | -|----|-------|------|----------| -| C1 | Mock signature verification accepts ANY signature | Auth bypass — anyone can impersonate any user | Implement BIP-322 signature verification with @noble/secp256k1 | -| C2 | No replay attack protection (no nonces) | Double-spend — replay transfers 100x | Add UUID nonce with UNIQUE constraint in database | -| C3 | In-memory commitment storage | State loss — old channel state broadcast after restart | Persist commitments to SQLite | -| C4 | No rate limiting | DoS — brute force attack | Add express-rate-limit (5 req/min on auth) | -| C5 | Weak JWT secret fallback | Token forgery | Require 32+ char JWT_SECRET at startup | - -### 🟠 HIGH Priority - -| ID | Issue | Risk | Solution | -|----|-------|------|----------| -| H1 | No amount bounds checking | Integer overflow | Add MIN/MAX_CHANNEL_CAPACITY validation | -| H2 | BigInt→Number conversion | Precision loss above 2^53 | Store balances as TEXT in SQLite | -| H3 | No tx confirmation verification | Fake funding attacks | Wait for 1+ confirmations before activating | -| H4 | No WebSocket message validation | Message injection | Add Zod schema validation | -| H5 | CORS allows all origins | Security bypass | Configure strict CORS + HSTS headers | - -**Recommendation:** Halt any mainnet plans until these are fixed. Estimated effort: 2-3 weeks focused security sprint. - ---- - -## Part 3: Competitive Landscape Analysis - -### The Bitcoin L2 Space (March 2026) - -| Protocol | Status | Focus | Threat Level | -|----------|--------|-------|--------------| -| **Lightning Network** | Production | BTC payments | LOW (doesn't do Runes) | -| **Taproot Assets v0.6** | Production | Stablecoins (USDT!) | HIGH — could add Runes | -| **Ark Protocol** | Seed Stage ($5.2M Tether backing) | VTXOs, no channels | MEDIUM — different model | -| **Stacks** | Production | Smart contracts, DeFi | LOW (not payment-focused) | -| **Liquid Network** | Production | Exchanges, federated | LOW (federated, not trustless) | -| **RGB Protocol** | Development | Client-side validation | LOW (complex, slow adoption) | - -### Key Competitive Intelligence - -#### 1. **USDT on Lightning is LIVE** (January 2025) -- Tether launched USDT via Taproot Assets -- This is HUGE — $140B market cap stablecoin now on Lightning -- **RuneBolt should support Taproot Assets stablecoins immediately** -- Users want to send USDT, not just DOG - -#### 2. **Ark Protocol Just Raised $5.2M** (March 2026) -- Tether and Tim Draper invested -- Uses VTXOs (Virtual UTXOs) — no channel management -- Competing for "simpler than Lightning" narrative -- **Key differentiator:** Ark requires periodic VTXO refresh (4-week expiry) - -#### 3. **AI Agent Wallets are Exploding** -- Coinbase launched Agentic Wallets (Feb 2026) -- x402 protocol for machine-to-machine payments -- ERC-8004 standard for agent identity on BNB Chain -- MoonPay Agents with Ledger integration -- **No one is doing this on Bitcoin-native** — MASSIVE opportunity - ---- - -## Part 4: The Block Genomics Vision — AI Agent Verification - -### The Problem Block Genomics Solves - -**AI agents cannot open bank accounts.** They can't KYC. They can't prove identity. - -But they CAN: -- Own Bitcoin -- Own Bitmap blocks -- Have unique "genome fingerprints" -- Make instant payments via RuneBolt - -### The "Nexus" Concept - -> "A decentralized internet built on Bitcoin where each block is sovereign digital land." - -**Translation:** Every Bitmap block is like a domain name. Own block 720143? That's your digital real estate. You control what gets built on it. - -### My Analysis: This is DNS for Bitcoin Blocks - -| DNS | Bitmap/Nexus | -|-----|--------------| -| Domain name → IP address | Block number → Owner pubkey | -| WHOIS lookup | On-chain verification | -| Registrar | Ordinals inscription | -| Hosting provider | Block Genomics services | - -### The AI Agent Identity Stack - -I propose this architecture: - -``` -┌─────────────────────────────────────────────────────────────────┐ -│ AI AGENT IDENTITY LAYER │ -├─────────────────────────────────────────────────────────────────┤ -│ 1. Bitmap Ownership (bc1p... address owns block 720143) │ -│ 2. Genome Fingerprint (unique AI model signature) │ -│ 3. RuneBolt Channel (payment identity) │ -│ 4. Guardian API (personality, soul, behavior rules) │ -└─────────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ VERIFICATION PROTOCOL │ -├─────────────────────────────────────────────────────────────────┤ -│ - Prove: "I am the AI agent that controls block 720143" │ -│ - Prove: "My genome fingerprint is [hash]" │ -│ - Prove: "I have capacity to pay [amount] DOG" │ -│ - Prove: "My behavior rules are signed by [guardian]" │ -└─────────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ PAYMENT LAYER (RuneBolt) │ -├─────────────────────────────────────────────────────────────────┤ -│ - Instant DOG transfers between verified agents │ -│ - Stablecoin support (USDT via Taproot Assets) │ -│ - API usage payments (agent-to-agent) │ -│ - Micro-transactions for AI services │ -└─────────────────────────────────────────────────────────────────┘ -``` - ---- - -## Part 5: Product Recommendations - -### 🎯 Priority 1: Security (Week 1-3) - -Fix all CRITICAL and HIGH security issues. No shortcuts. - -### 🎯 Priority 2: Taproot Assets Support (Week 4-8) - -**Why:** USDT on Lightning is live. Users want stablecoins. - -**Implementation:** -1. Add Taproot Assets node alongside RuneBolt -2. Support USDT/USDC channels (not just DOG) -3. Enable cross-asset swaps (DOG ↔ USDT) -4. Integrate with Lightning Labs' TAP Daemon - -**Business Impact:** 100x larger addressable market - -### 🎯 Priority 3: Hide the Channel (Week 4-6) - -**Current UX:** -> "Open a channel" → "Fund the channel" → "Wait for confirmation" → "Now you can send" - -**Target UX:** -> "Deposit DOG" → "Send to @username" - -**Implementation:** -1. Auto-open channels on first deposit -2. Abstract channel management into "balance" -3. Username resolution via .well-known endpoint -4. Never show "channel" to users — only developers - -### 🎯 Priority 4: AI Agent SDK (Week 6-10) - -**Goal:** Make it trivial for AI agents to use RuneBolt. - -```typescript -// Proposed API -import { RuneBoltAgent } from '@runebolt/agent-sdk'; - -const agent = new RuneBoltAgent({ - bitmapBlock: 720143, - genomeFingerpring: 'sha256:abc123...', - guardianApi: 'https://blockgenomics.io/api/v1/guardian', -}); - -// Pay for API access -await agent.pay('api.openai.com', { amount: '100', asset: 'USDT' }); - -// Receive payment for services -agent.onPayment((payment) => { - console.log(`Received ${payment.amount} ${payment.asset} from ${payment.sender}`); -}); - -// Verify another agent -const isVerified = await agent.verify('another-agent-pubkey'); -``` - -### 🎯 Priority 5: BitVM Bridge (Q4 2026) - -The SPECS_BITVM_BRIDGE.md is excellent. Execute on Phase 1 (federated) to get trust-minimized bridging. - ---- - -## Part 6: Monetization Strategy - -### Revenue Streams - -| Stream | Model | Estimated TAM | -|--------|-------|---------------| -| **Transaction Fees** | 0.1% per transfer | $10M/year at $10B volume | -| **Channel Fees** | 0.5% on open/close | $5M/year | -| **Enterprise API** | Subscription + usage | $20M/year | -| **Agent Identity** | Per-agent monthly fee | $50M/year (100k agents @ $500/yr) | -| **Premium Blocks** | Marketplace fees | $10M/year | -| **Stablecoin Float** | Interest on deposits | $5M/year | - -**Total Potential:** $100M ARR within 3 years - -### The Killer Business Model: Agent Identity as a Service - -> "Block Genomics charges $10/month per verified AI agent." -> -> 1 million agents = $120M ARR -> -> 10 million agents = $1.2B ARR - -**Why they'll pay:** -- Agents need payment identity -- Agents need reputation -- Agents need to prove they're not scams -- Enterprises need audit trails - ---- - -## Part 7: Technical Recommendations - -### 1. Upgrade to Ark-Style VTXOs (Long-term) - -The Ark protocol's VTXO model eliminates channel management. Consider hybrid: -- Use channels for frequent traders -- Use VTXOs for occasional users -- Auto-select based on usage pattern - -### 2. Implement BOLT 12 Offers - -BOLT 12 enables: -- Reusable payment codes (no invoice per payment) -- Blinded paths for privacy -- Human-readable addresses - -### 3. Add DLC Support - -Discreet Log Contracts enable: -- Runes derivatives -- Price hedging -- Prediction markets -- Insurance products - -### 4. Fedimint Integration - -For community-managed custody: -- Each Bitmap "community" can run a Fedimint -- Chaumian e-cash for privacy -- Federated trust model - ---- - -## Part 8: Missing Features That Would Be World-Changing - -### 1. **Bitcoin-Native AI Agent Identity Standard** -- ERC-8004 is on BNB Chain -- x402 is on Base/Ethereum -- **No one owns the Bitcoin-native standard yet** -- Block Genomics could define it - -### 2. **Agent-to-Agent Payment Protocol** -- HTTP 402 but for Bitcoin -- Machine-readable payment requests -- Automatic top-up via RuneBolt - -### 3. **Bitmap-as-Identity** -- "I am verified by Block 720143" -- Proof-of-ownership via signature -- Reputation staked to block - -### 4. **Multi-Asset Channels** -- DOG + USDT + any Rune in one channel -- Atomic swaps inside channel -- No rebalancing needed - -### 5. **Mobile SDK (React Native / Flutter)** -- Most Bitcoin wallets are mobile-first -- Partner with Unisat, Xverse, Leather - -### 6. **Merchant Tools** -- Point-of-sale for Runes -- Invoicing system -- Accounting integrations - -### 7. **Cross-Platform Agent Verification** -- Verify Telegram bots -- Verify Discord bots -- Verify API endpoints - ---- - -## Part 9: Competitive Moat Analysis - -### What Creates Defensibility - -| Moat Type | RuneBolt | Competitors | -|-----------|----------|-------------| -| **Network Effects** | First hub = all users | ❌ Fragmented | -| **Developer Ecosystem** | SDK + docs | ⚠️ Lightning is complex | -| **Brand/Trust** | Block Genomics = verification | ❌ No identity layer | -| **Data Advantage** | Transaction history | ⚠️ On-chain is public | -| **Switching Costs** | Channels lock-in | ⚠️ Ark has 4-week expiry | - -### Sustainable Competitive Advantages - -1. **AI Agent Verification** — No one else is doing this on Bitcoin -2. **Runes-First** — Lightning does BTC, Taproot Assets does stablecoins -3. **UX Focus** — Documentation shows commitment to mass adoption -4. **Technical Depth** — BitVM bridge research is ahead of market - ---- - -## Part 10: Go-To-Market Strategy - -### Phase 1: Developer Adoption (Now - Q2 2026) -- Fix security issues -- Launch mainnet beta -- SDK documentation -- Developer grants program - -### Phase 2: Consumer App (Q3 2026) -- Mobile app (iOS/Android) -- Username-based payments -- Social features -- Claim links for onboarding - -### Phase 3: AI Agent Platform (Q4 2026) -- Agent SDK launch -- Block Genomics verification API -- Enterprise partnerships -- API monetization - -### Phase 4: Ecosystem (2027) -- BitVM bridge live -- Multi-asset support -- Fedimint modules -- DeFi primitives - ---- - -## Part 11: Risk Assessment - -### High Risks - -| Risk | Probability | Impact | Mitigation | -|------|-------------|--------|------------| -| Security breach | Medium | Critical | Complete audit, bug bounty | -| Regulatory action | Low | High | Decentralize operations | -| Lightning competes | Medium | Medium | Differentiate on Runes + AI | -| Key person risk | Medium | High | Document everything, decentralize | - -### Medium Risks - -| Risk | Probability | Impact | Mitigation | -|------|-------------|--------|------------| -| Slow adoption | Medium | Medium | Focus on UX, partnerships | -| Technical debt | Medium | Medium | Refactor as you go | -| Competitor copies | High | Low | Move fast, build moat | - ---- - -## Part 12: Immediate Action Items - -### This Week - -1. [ ] **Security Sprint Kickoff** — Assign owners to each critical issue -2. [ ] **Taproot Assets Research** — Deep dive on integration path -3. [ ] **AI Agent SDK Spec** — Draft API design -4. [ ] **Block Genomics API Audit** — Assess current capabilities - -### This Month - -1. [ ] **Fix C1-C5** — All critical security issues -2. [ ] **Prototype Taproot Assets channel** — Proof of concept -3. [ ] **Username system live** — .well-known resolution -4. [ ] **Testnet launch** — Public beta - -### This Quarter - -1. [ ] **Mainnet launch** — With stablecoins -2. [ ] **Agent SDK beta** — For developers -3. [ ] **Mobile app alpha** — iOS TestFlight -4. [ ] **Enterprise pilot** — First paying customer - ---- - -## Conclusion - -**Block Genomics + RuneBolt is sitting on a $100B+ opportunity.** - -The convergence of: -- AI agents needing payment identity -- Bitcoin's security and decentralization -- Runes bringing tokenization -- Bitmap providing digital real estate -- Payment channels enabling instant transfers - -...creates a perfect storm for a new category: **Bitcoin-Native AI Infrastructure**. - -The technology is 70% there. The vision is 100% clear. The market timing is perfect. - -**What's needed:** -1. Fix security (non-negotiable) -2. Add stablecoins (10x market) -3. Simplify UX (100x users) -4. Launch AI agent SDK (1000x opportunity) - -This could be the most innovative product in the Bitcoin ecosystem. - ---- - -*Research Agent 1 — Iteration 1 Complete* -*Next: Deep dive on Block Genomics codebase (when available)* -*Next: Competitor technical analysis* -*Next: User research synthesis* - ---- - -## Appendix A: Code Quality Observations - -### Backend Structure -``` -backend/ -├── api/routes/ # Clean route separation -├── auth/ # Challenge-based auth (needs crypto fix) -├── bitcoin/ # Taproot utils, Mempool client -├── cache/ # Redis integration -├── channels/ # State machine (good design) -├── db/ # SQLite (consider PostgreSQL for scale) -├── ledger/ # Double-entry balance tracking -├── rune/ # Protocol parsing -├── usernames/ # .well-known resolution -├── workers/ # Thread pool (smart!) -└── ws/ # WebSocket server -``` - -### Code Quality Score: 7/10 -- ✅ TypeScript throughout -- ✅ Clean separation of concerns -- ✅ Good use of async/await -- ❌ Security shortcuts for prototyping -- ❌ No formal test suite -- ❌ Missing input validation - -### Recommendations -1. Add Vitest for unit tests -2. Add Zod for runtime validation -3. Add proper logging (Winston/Pino) -4. Add OpenTelemetry tracing - ---- - -## Appendix B: Market Size Data - -### Bitcoin L2 Market -- Lightning Network capacity: ~5,000 BTC (~$500M) -- Stacks TVL: ~$100M -- Total Bitcoin L2 market: ~$2B - -### Runes Market -- Total Runes market cap: ~$1B -- DOG•GO•TO•THE•MOON: ~$300M -- Daily trading volume: ~$10M - -### AI Agent Economy (Projected) -- 2026: 10M agents with wallets -- 2027: 100M agents -- 2028: 1B agents -- Transaction volume: $100B+ annually - -### Total Addressable Market -- Bitcoin payments: $500B/year -- AI agent transactions: $100B/year -- Digital identity: $50B/year - ---- - -## Appendix C: Technical Glossary - -| Term | Definition | -|------|------------| -| **Bitmap** | Protocol for claiming ownership of Bitcoin blocks | -| **Runes** | Fungible token protocol on Bitcoin (by Casey Rodarmor) | -| **Taproot** | Bitcoin upgrade enabling Schnorr signatures and MAST | -| **BitVM** | Fraud proof-based computation on Bitcoin | -| **VTXO** | Virtual UTXO (Ark protocol concept) | -| **Channel** | 2-of-2 multisig for off-chain payments | -| **Genome Fingerprint** | Unique identifier for an AI agent model | -| **The Nexus** | Decentralized internet built on Bitcoin blocks | - ---- - ---- - -# ITERATION 2: AI Agent Identity Deep Dive - -## The x402 and ERC-8004 Competitive Analysis - -### x402 Protocol (Coinbase) - -**Status:** Production (100M+ payments processed) -**Chain:** Base (Ethereum L2) -**Core Innovation:** HTTP-native payments - -**Technical Architecture:** -``` -Client → HTTP Request → 402 Payment Required - ↓ -Client → Signs Payment Header → Server - ↓ -Server → Verifies → Returns Resource -``` - -**Key Features:** -- Stateless (no sessions) -- HTTP-native (standard libraries work) -- Pay-per-request model -- USDC on Base - -**Limitations:** -- Ethereum/Base only -- No Bitcoin support -- No native identity layer -- Relies on wallet address only - -### ERC-8004 Standard (Ethereum) - -**Status:** Draft (deployed on BNB Chain mainnet/testnet) -**Purpose:** On-chain AI agent identity, reputation, validation - -**Three Registries:** -1. **Identity Registry** — ERC-721 token → agent identity -2. **Reputation Registry** — Feedback scores, history -3. **Validation Registry** — Third-party attestations - -**Key Innovation:** -- Portable identity across chains -- On-chain reputation -- Verifiable behavior claims - -**Limitations:** -- EVM chains only -- No Bitcoin support -- No payment integration -- Complex (3 contracts) - ---- - -## The Bitcoin-Native Agent Identity Opportunity - -### Why No One Has Done This Yet - -1. **Bitcoin = "just money"** — No smart contracts mindset -2. **Lightning = complex** — Focus on payments, not identity -3. **Ordinals = new** — Still exploring use cases -4. **Bitmap = unknown** — Low awareness outside Bitcoin Twitter - -### Block Genomics' Unique Position - -**What Block Genomics Can Offer That Others Can't:** - -| Feature | x402 | ERC-8004 | Block Genomics | -|---------|------|----------|----------------| -| Payment protocol | ✅ USDC | ❌ None | ✅ DOG + USDT | -| Identity layer | ❌ Address only | ✅ NFT-based | ✅ Bitmap + Genome | -| Reputation | ❌ None | ✅ On-chain | ✅ Guardian API | -| Bitcoin-native | ❌ Base L2 | ❌ EVM only | ✅ Native | -| Non-custodial | ⚠️ Depends | ✅ Yes | ✅ Yes | -| Real estate analogy | ❌ None | ❌ None | ✅ Bitmap blocks | - ---- - -## Proposed: BIP-XXXX Bitcoin Agent Identity Standard - -### Overview - -A Bitcoin-native standard for AI agent identity, combining: -- Bitmap ownership (digital real estate) -- Taproot signature proofs (cryptographic identity) -- Runestone inscriptions (metadata storage) -- Payment channel linkage (economic identity) - -### Technical Specification - -``` -┌──────────────────────────────────────────────────────────────┐ -│ BIP-XXXX: Agent Identity │ -├──────────────────────────────────────────────────────────────┤ -│ │ -│ Identity Proof: │ -│ ┌─────────────────────────────────────────────────────┐ │ -│ │ agent_id: sha256(bitmap_block || genome_hash) │ │ -│ │ bitmap_block: 720143 │ │ -│ │ owner_pubkey: bc1p... │ │ -│ │ genome_fingerprint: sha256(model_weights) │ │ -│ │ registration_inscription: ord://inscription_id │ │ -│ │ payment_channel: runebolt://channel_id │ │ -│ │ guardian_url: https://blockgenomics.io/api/... │ │ -│ └─────────────────────────────────────────────────────┘ │ -│ │ -│ Verification Protocol: │ -│ 1. Verify bitmap ownership via Ordinals indexer │ -│ 2. Verify genome hash matches registered fingerprint │ -│ 3. Verify signature with owner_pubkey │ -│ 4. Query guardian_url for behavior rules │ -│ 5. Confirm payment channel capacity │ -│ │ -└──────────────────────────────────────────────────────────────┘ -``` - -### Agent Registration Flow - -``` -Step 1: Acquire Bitmap block - └─▶ Inscribe "720143.bitmap" on sat - -Step 2: Generate genome fingerprint - └─▶ Hash of model weights/config - -Step 3: Inscribe agent metadata - └─▶ JSON-encoded identity proof - -Step 4: Open RuneBolt channel - └─▶ Economic identity established - -Step 5: Register with Block Genomics Guardian - └─▶ Behavior rules, personality, soul -``` - -### Agent Verification Flow - -```typescript -interface AgentVerification { - // Step 1: Bitmap ownership - async verifyBitmapOwnership( - block: number, - pubkey: string - ): Promise; - - // Step 2: Genome fingerprint - async verifyGenome( - agentId: string, - claimedHash: string - ): Promise; - - // Step 3: Signature proof - async verifySignature( - message: string, - signature: string, - pubkey: string - ): Promise; - - // Step 4: Payment capacity - async verifyPaymentCapacity( - channelId: string, - minimumBalance: bigint - ): Promise; - - // Step 5: Guardian rules - async getGuardianRules( - guardianUrl: string - ): Promise; -} -``` - ---- - -## Integration Architecture - -### How It All Fits Together - -``` -┌─────────────────────────────────────────────────────────────────────┐ -│ THE NEXUS │ -│ "A decentralized internet built on Bitcoin" │ -├─────────────────────────────────────────────────────────────────────┤ -│ │ -│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ -│ │ BITMAP │ │ BLOCK │ │ RUNEBOLT │ │ -│ │ BLOCKS │ │ GENOMICS │ │ PAYMENTS │ │ -│ │ │ │ │ │ │ │ -│ │ "Land" │ │ "Identity" │ │ "Economy" │ │ -│ │ ownership │ │ verification│ │ instant $ │ │ -│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ -│ │ │ │ │ -│ └─────────────────┼─────────────────┘ │ -│ │ │ -│ ▼ │ -│ ┌─────────────────────────────────────────────────────────────┐ │ -│ │ AI AGENTS │ │ -│ │ │ │ -│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ -│ │ │ Agent 1 │ │ Agent 2 │ │ Agent 3 │ │ Agent N │ │ │ -│ │ │ │ │ │ │ │ │ │ │ │ -│ │ │ Block │ │ Block │ │ Block │ │ Block │ │ │ -│ │ │ 720143 │ │ 500000 │ │ 800000 │ │ XXXXXX │ │ │ -│ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ │ -│ │ │ │ -│ │ Each agent has: │ │ -│ │ • Bitmap block ownership (sovereign territory) │ │ -│ │ • Genome fingerprint (unique identity) │ │ -│ │ • RuneBolt channel (payment capacity) │ │ -│ │ • Guardian rules (behavior constraints) │ │ -│ │ │ │ -│ └─────────────────────────────────────────────────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────┘ -``` - ---- - -## Revenue Model: Agent-as-a-Service - -### Pricing Tiers - -| Tier | Monthly | Features | -|------|---------|----------| -| **Free** | $0 | 1 agent, basic verification, 100 API calls/day | -| **Pro** | $50/agent | Unlimited API, priority routing, analytics | -| **Enterprise** | $500/agent | SLA, dedicated support, custom integrations | -| **Network** | Custom | Multi-agent management, fleet tools | - -### Revenue Projections - -| Year | Agents | ARPU | ARR | -|------|--------|------|-----| -| 2026 | 10,000 | $100 | $12M | -| 2027 | 100,000 | $150 | $180M | -| 2028 | 1,000,000 | $200 | $2.4B | - ---- - -## Technical Implementation Plan - -### Phase 1: Foundation (4 weeks) - -**Week 1-2: Security Sprint** -- [ ] Fix C1-C5 critical issues -- [ ] Add rate limiting -- [ ] Implement BIP-322 signatures - -**Week 3-4: Agent SDK Alpha** -- [ ] Define agent identity schema -- [ ] Implement verification flow -- [ ] Create SDK skeleton - -### Phase 2: Integration (4 weeks) - -**Week 5-6: Bitmap Integration** -- [ ] Connect to Ordinals indexer -- [ ] Implement ownership verification -- [ ] Add inscription parsing - -**Week 7-8: Guardian API** -- [ ] Deploy Guardian API -- [ ] Implement behavior rules -- [ ] Add personality storage - -### Phase 3: Launch (4 weeks) - -**Week 9-10: Testing** -- [ ] Integration tests -- [ ] Security audit -- [ ] Testnet deployment - -**Week 11-12: Production** -- [ ] Mainnet launch -- [ ] Documentation -- [ ] Developer onboarding - ---- - -## Key Partnerships to Pursue - -### Tier 1: Essential - -| Partner | Value | Effort | -|---------|-------|--------| -| **Unisat** | Wallet integration, 10M+ users | Medium | -| **Magic Eden** | Marketplace, Ordinals expertise | Medium | -| **Lightning Labs** | Taproot Assets, technical collab | High | - -### Tier 2: Strategic - -| Partner | Value | Effort | -|---------|-------|--------| -| **OpenAI** | AI agent partnerships | Very High | -| **Anthropic** | Claude agent verification | Very High | -| **Coinbase** | x402 interop, legitimacy | High | - -### Tier 3: Ecosystem - -| Partner | Value | Effort | -|---------|-------|--------| -| **Bitcoin Optech** | Standards legitimacy | Low | -| **Ordinals Wallet** | Distribution | Low | -| **Hiro (Stacks)** | Cross-L2 interop | Medium | - ---- - -## Competitive Response Scenarios - -### If Lightning Labs adds agent identity... - -**Risk:** High -**Response:** -- Emphasize Runes-native (they focus on stablecoins) -- Emphasize Bitmap integration (they don't have this) -- Move faster on UX - -### If Ethereum AI agents dominate... - -**Risk:** Medium -**Response:** -- Position as "Bitcoin-secured" vs ETH -- Emphasize censorship resistance -- Target Bitcoin maximalist builders - -### If Ark Protocol scales first... - -**Risk:** Medium -**Response:** -- Integrate VTXO model alongside channels -- Emphasize agent identity (they do payments only) -- Consider technical collaboration - ---- - -## Final Recommendations - -### Do This First -1. **Fix security issues** — Non-negotiable -2. **Ship agent SDK** — First mover advantage -3. **Partner with Unisat** — Distribution - -### Do This Next -4. **Add Taproot Assets** — Stablecoin support -5. **Submit BIP proposal** — Standards legitimacy -6. **Launch on mainnet** — Real users, real feedback - -### Do This Later -7. **BitVM bridge** — Trust-minimized -8. **Multi-chain identity** — EVM interop -9. **Enterprise sales** — $$$ - ---- - -*Research Agent 1 — Iteration 2 Complete* -*Total research time: ~30 minutes* -*Files analyzed: 15+* -*Web searches: 10+* -*Lines of code reviewed: 2000+* - ---- - ---- - -# ITERATION 3: Code-Level Recommendations - -## Immediate Security Fixes (Copy-Paste Ready) - -### Fix C1: Implement Real Bitcoin Signature Verification - -**File:** `backend/src/auth/ChallengeManager.ts` - -```typescript -// REPLACE the mock verification with this: -import * as secp256k1 from '@noble/secp256k1'; -import { sha256 } from '@noble/hashes/sha256'; - -async verifyChallenge( - challengeId: string, - signature: string, - pubkey: string -): Promise<{ valid: boolean; token?: string }> { - const challenge = this.challenges.get(challengeId); - if (!challenge) { - return { valid: false }; - } - - // Real BIP-340 Schnorr signature verification - const messageHash = sha256( - Buffer.from(`RuneBolt Authentication: ${challenge.nonce}`) - ); - - try { - // Parse x-only pubkey (32 bytes for Taproot) - const pubkeyBytes = Buffer.from(pubkey, 'hex'); - const sigBytes = Buffer.from(signature, 'hex'); - - const isValid = secp256k1.schnorr.verify(sigBytes, messageHash, pubkeyBytes); - - if (!isValid) { - return { valid: false }; - } - - // Clean up and generate JWT - this.challenges.delete(challengeId); - const token = this.generateJWT(pubkey); - - return { valid: true, token }; - } catch (err) { - console.error('[ChallengeManager] Signature verification failed:', err); - return { valid: false }; - } -} -``` - -### Fix C2: Add Replay Protection (Nonces) - -**File:** `backend/src/ledger/RuneLedger.ts` - -```typescript -// Add to transfer method: -async transfer( - fromChannelId: string, - toChannelId: string, - amount: bigint, - memo: string | undefined, - nonce: string, // NEW: Required nonce - clientSignature: string, - senderPubkey: string, - options: TransferOptions = {} -): Promise { - // Validate nonce is UUID format - if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(nonce)) { - throw new Error('Invalid nonce format (must be UUIDv4)'); - } - - // Check nonce hasn't been used (database constraint) - const nonceExists = await this.db.checkNonceExists(nonce); - if (nonceExists) { - throw new Error('Nonce already used (replay attack prevented)'); - } - - // ... rest of transfer logic -} -``` - -**Database migration:** -```sql -ALTER TABLE transfers ADD COLUMN nonce TEXT UNIQUE NOT NULL; -CREATE INDEX idx_transfers_nonce ON transfers(nonce); -``` - -### Fix C4: Add Rate Limiting - -**File:** `backend/src/index.ts` - -```typescript -import rateLimit from 'express-rate-limit'; - -// Add before routes: - -// Auth endpoint: strict limiting -const authLimiter = rateLimit({ - windowMs: 60 * 1000, // 1 minute - max: 5, // 5 requests per minute - message: { error: 'Too many authentication attempts, try again later' }, - standardHeaders: true, - legacyHeaders: false, -}); - -// API endpoints: moderate limiting -const apiLimiter = rateLimit({ - windowMs: 60 * 1000, - max: 100, - message: { error: 'Rate limit exceeded' }, -}); - -// Apply limiters -app.use('/api/v1/auth', authLimiter); -app.use('/api/v1', apiLimiter); -``` - -### Fix C5: Require Strong JWT Secret - -**File:** `backend/src/auth/AuthMiddleware.ts` - -```typescript -// At module initialization: -const JWT_SECRET = process.env.JWT_SECRET; - -if (!JWT_SECRET || JWT_SECRET.length < 32) { - console.error('[FATAL] JWT_SECRET must be at least 32 characters'); - process.exit(1); -} - -// Also check for weak defaults -const WEAK_SECRETS = ['secret', 'jwt-secret', 'changeme', 'development']; -if (WEAK_SECRETS.some(weak => JWT_SECRET.toLowerCase().includes(weak))) { - console.error('[FATAL] JWT_SECRET appears to be a weak/default value'); - process.exit(1); -} -``` - ---- - -## Agent SDK Design - -### Proposed `@blockgenomics/agent-sdk` API - -```typescript -// agent-sdk/src/index.ts - -export interface AgentConfig { - // Identity - bitmapBlock: number; - genomeFingerprint: string; - - // Payment - runeboltApiUrl: string; - runeboltAuthToken?: string; - - // Guardian - guardianApiUrl?: string; - guardianToken?: string; - - // Signing - privateKey?: string; // Or use external signer - signer?: ExternalSigner; -} - -export interface ExternalSigner { - sign(message: Uint8Array): Promise; - getPublicKey(): Promise; -} - -export class BlockGenomicsAgent { - private config: AgentConfig; - private runebolt: RuneBoltClient; - private identity: AgentIdentity; - - constructor(config: AgentConfig) { - this.config = config; - this.runebolt = new RuneBoltClient({ - apiUrl: config.runeboltApiUrl, - authToken: config.runeboltAuthToken, - }); - } - - /** - * Register this agent on-chain - */ - async register(): Promise { - // 1. Verify bitmap ownership - const ownsBlock = await this.verifyBitmapOwnership(); - if (!ownsBlock) { - throw new Error(`Agent does not own Bitmap block ${this.config.bitmapBlock}`); - } - - // 2. Create inscription with agent metadata - const inscription = await this.createAgentInscription(); - - // 3. Register with Guardian API - if (this.config.guardianApiUrl) { - await this.registerWithGuardian(); - } - - // 4. Initialize RuneBolt channel - const channel = await this.initializePaymentChannel(); - - return { - agentId: this.getAgentId(), - bitmapBlock: this.config.bitmapBlock, - inscriptionId: inscription.id, - channelId: channel.channelId, - }; - } - - /** - * Get unique agent ID (deterministic) - */ - getAgentId(): string { - return sha256( - `${this.config.bitmapBlock}:${this.config.genomeFingerprint}` - ).toString('hex'); - } - - /** - * Verify another agent's identity - */ - async verify(targetAgentId: string): Promise { - // 1. Query Ordinals indexer for bitmap ownership - const bitmapOwner = await this.queryBitmapOwner(targetAgentId); - - // 2. Verify genome fingerprint matches - const genomeValid = await this.verifyGenome(targetAgentId); - - // 3. Check payment channel status - const hasCapacity = await this.checkPaymentCapacity(targetAgentId); - - // 4. Query Guardian for behavior rules - const guardianRules = await this.queryGuardian(targetAgentId); - - return { - verified: bitmapOwner && genomeValid, - hasPaymentCapacity: hasCapacity, - guardianRules, - }; - } - - /** - * Pay another agent for services - */ - async pay( - targetAgentId: string, - amount: string, - asset: 'DOG' | 'USDT' = 'DOG', - memo?: string - ): Promise { - // Resolve target's RuneBolt channel - const targetChannel = await this.resolveAgentChannel(targetAgentId); - - // Execute payment - const transfer = await this.runebolt.sendDOG({ - toChannelId: targetChannel.channelId, - amount, - memo: memo || `Payment from agent ${this.getAgentId().slice(0, 8)}`, - }); - - return { - transferId: transfer.id, - amount, - asset, - fromAgent: this.getAgentId(), - toAgent: targetAgentId, - timestamp: new Date().toISOString(), - }; - } - - /** - * Listen for incoming payments - */ - onPayment(callback: (payment: IncomingPayment) => void): () => void { - return this.runebolt.onTransfer((event) => { - callback({ - transferId: event.transfer.id, - amount: event.transfer.amount.toString(), - fromChannel: event.transfer.fromChannel, - memo: event.transfer.memo, - newBalance: event.newBalance.available, - }); - }); - } - - /** - * Sign a message proving agent identity - */ - async signIdentityProof(message: string): Promise { - const toSign = { - agentId: this.getAgentId(), - bitmapBlock: this.config.bitmapBlock, - message, - timestamp: Date.now(), - }; - - const messageHash = sha256(JSON.stringify(toSign)); - const signature = await this.sign(messageHash); - - return { - ...toSign, - signature: signature.toString('hex'), - }; - } -} - -// Usage example: -const agent = new BlockGenomicsAgent({ - bitmapBlock: 720143, - genomeFingerprint: 'sha256:abc123...', - runeboltApiUrl: 'https://api.runebolt.io', - guardianApiUrl: 'https://blockgenomics.io/api/v1/guardian', - signer: ledgerSigner, // Use hardware wallet -}); - -// Register agent -await agent.register(); - -// Pay for API access -await agent.pay('target-agent-id', '1000', 'DOG', 'API access fee'); - -// Listen for payments -agent.onPayment((payment) => { - console.log(`Received ${payment.amount} DOG`); -}); -``` - ---- - -## Strategic Summary - -### The 30-Second Pitch - -> "Block Genomics is building the DNS for AI agents on Bitcoin. -> -> Every agent owns a Bitmap block — their sovereign digital territory. -> Every agent has a genome fingerprint — their unique, verifiable identity. -> Every agent uses RuneBolt — instant payments without the Lightning complexity. -> -> We're the only Bitcoin-native solution for AI agent identity. -> x402 is Ethereum. ERC-8004 is Ethereum. We're Bitcoin. -> -> $100M ARR potential in 3 years. $1B+ in 5 years. -> First mover advantage. No direct competitors on Bitcoin. -> -> Ship the agent SDK. Own the standard. Win the market." - -### The One Thing To Remember - -**The AI agent economy is coming. It's not if, it's when.** - -Agents will need: -- Payment identity (can't use banks) -- Verifiable reputation (can't trust randomly) -- Instant settlement (can't wait for confirmations) - -Block Genomics + RuneBolt can provide ALL THREE on Bitcoin. - -No one else is doing this. **Move fast.** - ---- - -*End of Research Agent 1 Findings — Iteration 3 (FINAL)* - ---- - -## Change Log - -| Date | Iteration | Focus | -|------|-----------|-------| -| 2026-03-14 21:14 | 1 | Initial deep analysis of RuneBolt codebase | -| 2026-03-14 21:30 | 2 | AI agent identity competitive analysis | -| 2026-03-14 21:45 | 3 | Code-level recommendations, SDK design, strategy | - ---- - -**Total document length:** ~25,000 words -**Research sources:** Code analysis, web search, competitive intelligence -**Confidence level:** HIGH for technical recommendations, MEDIUM for market projections - -*End of Research Document* diff --git a/legacy/taproot-assets-era/RESEARCH_AGENT_2_FINDINGS.md b/legacy/taproot-assets-era/RESEARCH_AGENT_2_FINDINGS.md deleted file mode 100644 index cdde023..0000000 --- a/legacy/taproot-assets-era/RESEARCH_AGENT_2_FINDINGS.md +++ /dev/null @@ -1,1240 +0,0 @@ -# RuneBolt Deep Research Findings - -**Research Agent:** Kimi K2.5 (Deep Research) -**Date:** March 14, 2026 -**Scope:** Comprehensive analysis for production readiness -**Classification:** Strategic — Internal Use Only - ---- - -## Executive Summary - -RuneBolt has a solid technical foundation but is **NOT PRODUCTION READY**. After deep analysis of the codebase, competitor landscape, and market dynamics, I've identified: - -- **14 security vulnerabilities** (5 CRITICAL) that must be fixed before mainnet -- **8 architectural gaps** that limit scalability and security -- **6 key features** missing for competitive parity with Taproot Assets/Ark -- **3 fundamental UX problems** preventing mass adoption - -**The Good:** Clean TypeScript architecture, proper channel state machine, Redis caching infrastructure, PostgreSQL persistence, WebSocket real-time updates. The vision is sound. - -**The Bad:** Mock cryptographic primitives, no watchtower infrastructure, centralized hub with single point of failure, incomplete settlement flow. - -**The Ugly:** If deployed today with mock signature verification, users could lose all funds within hours. - -**Recommendation:** 6-8 week sprint to reach MVP, 4-6 months to production. - ---- - -## Table of Contents - -1. [Architecture Analysis](#1-architecture-analysis) -2. [Security Deep Dive](#2-security-deep-dive) -3. [Performance Analysis](#3-performance-analysis) -4. [Competitive Landscape](#4-competitive-landscape) -5. [UX/Product Analysis](#5-uxproduct-analysis) -6. [Missing Pieces](#6-missing-pieces) -7. [Business Model & Moat](#7-business-model--moat) -8. [Prioritized Recommendations](#8-prioritized-recommendations) -9. [Implementation Roadmap](#9-implementation-roadmap) -10. [Appendix: Code-Level Fixes](#10-appendix-code-level-fixes) - ---- - -## 1. Architecture Analysis - -### 1.1 Current Architecture - -``` -┌─────────────────────────────────────────────────────────────────┐ -│ FRONTEND (Next.js) │ -│ ┌──────────┐ ┌─────────┐ ┌──────────┐ ┌───────────────┐ │ -│ │Dashboard │ │ Send │ │ Receive │ │ Channels │ │ -│ └────┬─────┘ └────┬────┘ └────┬─────┘ └───────┬───────┘ │ -└────────┼─────────────┼───────────┼─────────────────┼───────────┘ - │ │ │ │ - ▼ ▼ ▼ ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ API GATEWAY (Express) │ -│ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ -│ │ authRoutes │ │transferRts │ │channelRts │ │ -│ └─────┬──────┘ └─────┬──────┘ └─────┬──────┘ │ -└─────────┼───────────────┼───────────────┼───────────────────────┘ - │ │ │ - ▼ ▼ ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ CORE SERVICES │ -│ │ -│ ┌───────────────┐ ┌───────────────┐ ┌───────────────────┐ │ -│ │ChallengeManager│ │ RuneLedger │ │ ChannelManager │ │ -│ │ (BIP-322 Auth) │ │ (Off-chain) │ │ (Lifecycle) │ │ -│ └───────┬───────┘ └───────┬───────┘ └─────────┬─────────┘ │ -│ │ │ │ │ -│ ▼ ▼ ▼ │ -│ ┌───────────────────────────────────────────────────────────┐ │ -│ │ CommitmentManager │ │ -│ │ (Off-chain state snapshots) │ │ -│ └───────────────────────────────────────────────────────────┘ │ -└─────────────────────────────────────────────────────────────────┘ - │ │ │ - ▼ ▼ ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ DATA / INFRASTRUCTURE │ -│ │ -│ ┌────────────┐ ┌────────────┐ ┌────────────────────┐ │ -│ │ PostgreSQL │ │ Redis │ │ TransferWorkerPool│ │ -│ │ (Persist) │ │ (Cache) │ │ (Worker Threads) │ │ -│ └────────────┘ └────────────┘ └────────────────────┘ │ -│ │ -│ ┌────────────────────────────────────────────────────────────┐ │ -│ │ WebSocketManager │ │ -│ │ (Real-time Updates) │ │ -│ └────────────────────────────────────────────────────────────┘ │ -└─────────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ BITCOIN INTEGRATION │ -│ │ -│ ┌────────────────┐ ┌─────────────────┐ │ -│ │ BitcoinClient │ │ TaprootUtils │ │ -│ │ (Mempool API) │ │ (Mock Schnorr) │ ← CRITICAL GAP! │ -│ └────────────────┘ └─────────────────┘ │ -└─────────────────────────────────────────────────────────────────┘ -``` - -### 1.2 Architecture Strengths - -1. **Clean Module Separation:** Each concern (auth, ledger, channels) is isolated -2. **Type-Safe:** Full TypeScript with proper interfaces -3. **State Machine:** Proper channel state transitions (PENDING_OPEN → OPEN → CLOSING → CLOSED) -4. **Caching Layer:** Redis for sub-millisecond balance lookups -5. **Worker Threads:** Offloads computation from main event loop -6. **Database Design:** PostgreSQL with proper indexing, prepared for partitioning -7. **Real-time:** WebSocket infrastructure for instant notifications - -### 1.3 Architecture Weaknesses - -| Issue | Severity | Description | -|-------|----------|-------------| -| **Single Hub** | HIGH | No federation, single point of failure | -| **Mock Crypto** | CRITICAL | TaprootUtils uses fake signatures | -| **No Watchtowers** | HIGH | Users can't detect fraud when offline | -| **No Penalty Transactions** | CRITICAL | Old state broadcasts aren't punished | -| **No HTLCs** | MEDIUM | Can't do atomic multi-hop payments | -| **No On-chain Verification** | CRITICAL | Funding txs not verified on L1 | -| **Centralized Sequencing** | MEDIUM | Transfer ordering is hub-controlled | -| **No Backup/Recovery** | HIGH | Users can't restore channels from seed | - -### 1.4 Architecture vs Competitors - -| Feature | RuneBolt | Lightning | Ark | Taproot Assets | -|---------|----------|-----------|-----|----------------| -| Channel-less Receiving | ❌ | ❌ | ✅ | ✅ | -| Multi-hop Routing | ❌ | ✅ | ⚠️ | ✅ | -| Penalty Transactions | ❌ | ✅ | N/A | ✅ | -| Watchtowers | ❌ | ✅ | ⚠️ | ✅ | -| Federation | ❌ | N/A | ⚠️ | ❌ | -| Asset Support | Runes | BTC | BTC | Multi-asset | -| Production Ready | ❌ | ✅ | ⚠️ | ✅ | - ---- - -## 2. Security Deep Dive - -### 2.1 CRITICAL Vulnerabilities (Must Fix Before Any Deployment) - -#### C1: Mock Signature Verification — AUTHENTICATION BYPASS - -**File:** `src/auth/ChallengeManager.ts` (fixed), `src/bitcoin/TaprootUtils.ts` (STILL MOCK) - -**Current State:** ChallengeManager now uses `@noble/secp256k1` for Schnorr verification. HOWEVER, `TaprootUtils.verifySchnorrSignature()` still returns `true` for ANY signature: - -```typescript -// TaprootUtils.ts line 74-85 — STILL VULNERABLE -static verifySchnorrSignature( - publicKey: string, - _message: string, - signature: string -): boolean { - // Mock: In production, implement BIP-340 verification - // For development, accept any non-empty signature - if (!signature || signature.length === 0) { - return false; - } - return true; // ← ACCEPTS ANY SIGNATURE! -} -``` - -**Attack:** Commitment signatures aren't verified. Attacker can forge channel state updates. - -**Fix:** -```typescript -import * as secp256k1 from '@noble/secp256k1'; -import { sha256 } from '@noble/hashes/sha2.js'; - -static verifySchnorrSignature( - publicKey: string, - message: string, - signature: string -): boolean { - try { - const messageHash = sha256(new TextEncoder().encode(message)); - const sigBytes = new Uint8Array(Buffer.from(signature, 'hex')); - const pubkeyBytes = new Uint8Array(Buffer.from(publicKey, 'hex')); - - if (sigBytes.length !== 64 || pubkeyBytes.length !== 32) { - return false; - } - - return secp256k1.schnorr.verify(sigBytes, messageHash, pubkeyBytes); - } catch { - return false; - } -} -``` - -#### C2: No On-Chain Funding Verification - -**File:** `src/channels/ChannelManager.ts` - -**Current State:** `activateChannel()` accepts any signed PSBT and immediately marks channel as OPEN without verifying: -1. The transaction was actually broadcast -2. The transaction is in the mempool or confirmed -3. The output matches the expected multisig address -4. The Rune transfer was correctly encoded - -**Attack:** User submits fake PSBT, gets credited with balance they never funded. - -**Fix:** Add mempool/electrum verification: - -```typescript -async activateChannel(channelId: string, signedPsbt: string): Promise { - const txid = await this.bitcoin.signAndBroadcastFundingTx(signedPsbt, 'hub_signature'); - - // VERIFY the transaction exists and has 1+ confirmations - const confirmations = await this.mempool.waitForConfirmations(txid, 1, { - timeoutMs: 3600000, // 1 hour max wait - pollIntervalMs: 30000, - }); - - if (confirmations < 1) { - throw new Error('Funding transaction not confirmed'); - } - - // VERIFY the output matches our expected multisig - const tx = await this.mempool.getTransaction(txid); - const expectedAddress = TaprootUtils.createMultisigAddress( - channel.userPubkey, channel.runeboltPubkey - ).address; - - const fundingOutput = tx.vout.find( - (out) => out.scriptpubkey_address === expectedAddress - ); - - if (!fundingOutput) { - throw new Error('Funding transaction missing expected output'); - } - - // Continue with activation... -} -``` - -#### C3: No Penalty Transaction Infrastructure - -**File:** MISSING — `src/channels/PenaltyManager.ts` doesn't exist - -**Lightning Context:** When someone broadcasts an old channel state, the counterparty has a "revocation secret" that lets them claim ALL funds as penalty. - -**RuneBolt Gap:** No revocation secrets, no penalty transactions. A malicious user can: -1. Open channel with 100 DOG -2. Send 50 DOG to someone -3. Close channel broadcasting the OLD state (100 DOG to them) -4. Steal 50 DOG - -**Fix:** Implement revocation secret scheme: - -```typescript -// CommitmentManager.ts — Add revocation support - -interface RevocationData { - channelId: string; - sequence: number; - revocationSecret: string; // 32 bytes hex - revocationHash: string; // SHA256(secret) -} - -static async revokeCommitment( - channelId: string, - sequence: number, - revocationSecret: string -): Promise { - // Verify the secret matches the stored hash - const commitment = await this.getCommitmentBySequence(channelId, sequence); - const hash = sha256(Buffer.from(revocationSecret, 'hex')).toString('hex'); - - if (hash !== commitment.revocationHash) { - throw new Error('Invalid revocation secret'); - } - - // Mark as revoked - await this.db.revokeCommitment(channelId, sequence); - - // Store revocation secret for penalty tx creation - await this.db.storeRevocationSecret(channelId, sequence, revocationSecret); -} -``` - -#### C4: Transfer Replay Protection Incomplete - -**File:** `src/ledger/RuneLedger.ts`, `src/api/routes/transferRoutes.ts` - -**Current State:** The API requires a `nonce` parameter, but the database doesn't have a UNIQUE constraint on it, and verification isn't enforced: - -```typescript -// transferRoutes.ts — nonce is received but not enforced -const { nonce, signature } = parsed.data; - -// RuneLedger.ts — nonce is passed through but not checked -async transfer( - fromChannelId: string, - toChannelId: string, - amount: bigint, - memo: string | undefined, - nonce: string, // ← Not verified against database! - clientSignature: string, - _senderPubkey: string, - ... -``` - -**Fix:** Add UNIQUE constraint and check: - -```sql --- Migration -ALTER TABLE transfers ADD CONSTRAINT transfers_nonce_unique UNIQUE (nonce); -``` - -```typescript -// RuneLedger.ts -async transfer(...) { - // Check for replay BEFORE any state changes - const existing = await this.db.getTransferByNonce(nonce); - if (existing) { - throw new Error('Transfer nonce already used (replay attack prevented)'); - } - - // ... rest of transfer logic -} -``` - -#### C5: JWT Secret Fallback - -**File:** `src/auth/AuthMiddleware.ts` - -**Current State:** -```typescript -const JWT_SECRET = process.env.JWT_SECRET || 'runebolt-dev-secret-change-me'; -``` - -**Fix:** -```typescript -const JWT_SECRET = process.env.JWT_SECRET; -if (!JWT_SECRET || JWT_SECRET.length < 32) { - throw new Error('JWT_SECRET must be set and at least 32 characters'); -} -``` - -### 2.2 HIGH Severity Vulnerabilities - -#### H1: Integer Overflow with BigInt/Number - -**Problem:** SQLite/PostgreSQL stores balances as NUMBER/INTEGER, but JavaScript BigInt can exceed 2^53-1. - -**Impact:** A channel with > 9 quadrillion atomic units could overflow. - -**Fix:** Store as TEXT in DB, parse with BigInt in application. - -#### H2: No Channel Reserve - -**Lightning Pattern:** Each party keeps a "reserve" (typically 1% of capacity) that they can't spend. This ensures they always have something to lose if they try to cheat. - -**RuneBolt Gap:** Users can drain channels to zero, meaning no penalty is possible. - -**Fix:** -```typescript -const CHANNEL_RESERVE_PERCENT = 1n; // 1% -const MIN_RESERVE = 1000n; // 0.01 DOG - -function calculateReserve(capacity: bigint): bigint { - const percent = (capacity * CHANNEL_RESERVE_PERCENT) / 100n; - return percent > MIN_RESERVE ? percent : MIN_RESERVE; -} - -// In transfer validation: -if (newLocalBalance < reserve) { - throw new Error('Cannot reduce balance below channel reserve'); -} -``` - -#### H3: WebSocket Message Injection - -**File:** `src/ws/WebSocketServer.ts` - -**Problem:** No Zod validation on incoming messages. Malformed JSON could crash the server or cause unexpected behavior. - -**Fix:** -```typescript -import { z } from 'zod'; - -const wsMessageSchema = z.discriminatedUnion('event', [ - z.object({ event: z.literal('subscribe'), data: z.object({ channelId: z.string().uuid() }) }), - z.object({ event: z.literal('unsubscribe'), data: z.object({ channelId: z.string().uuid() }) }), - z.object({ event: z.literal('ping'), data: z.object({}) }), -]); - -private handleMessage(clientId: string, raw: string): void { - const parsed = wsMessageSchema.safeParse(JSON.parse(raw)); - if (!parsed.success) { - client.ws.send(JSON.stringify({ event: 'error', data: { message: 'Invalid message format' } })); - return; - } - // ... handle validated message -} -``` - -#### H4: No Rate Limiting - -**Impact:** DDoS, brute force attacks on auth. - -**Fix:** -```typescript -import rateLimit from 'express-rate-limit'; - -const authLimiter = rateLimit({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 10, // 10 attempts per window - message: { error: 'Too many authentication attempts' }, -}); - -const transferLimiter = rateLimit({ - windowMs: 60 * 1000, // 1 minute - max: 100, // 100 transfers per minute -}); - -app.use('/api/v1/auth', authLimiter); -app.use('/api/v1/transfers', transferLimiter); -``` - -### 2.3 Security Architecture Recommendations - -1. **Implement Watchtower Protocol** - - Allow third parties to monitor channels - - Encrypt penalty data per-state - - Use PISA or Cerberus design patterns - -2. **Add Fraud Proof System** - - Store all commitment signatures - - Implement challenge-response for disputed closes - - 14-day challenge period before funds release - -3. **Hardware Security Module (HSM) for Hub Keys** - - Hub's private key should never touch application memory - - Use AWS CloudHSM or YubiHSM for signing - -4. **Implement Channel Backups** - - Encrypted channel state backups to user - - Static Channel Backup (SCB) format - - Cloud backup option with user-controlled encryption - ---- - -## 3. Performance Analysis - -### 3.1 Current Throughput - -Based on code analysis: - -| Metric | Current Estimate | Target (Mass Adoption) | -|--------|-----------------|------------------------| -| Transfers/second | ~100-500 TPS | 10,000+ TPS | -| Concurrent channels | ~10,000 | 1,000,000+ | -| Balance lookup latency | ~1-5ms (Redis) | <1ms | -| Transfer latency | ~50-200ms | <50ms | -| WebSocket connections | ~1,000 | 100,000+ | - -### 3.2 Performance Bottlenecks - -1. **PostgreSQL Transaction Serialization** - - Each transfer wraps DB updates in transaction - - Contention on channel rows for high-volume channels - - **Fix:** Implement optimistic locking with version numbers - -2. **Worker Thread Overhead** - - Current batch size of 50 creates artificial delays - - **Fix:** Dynamic batch sizing based on queue depth - -3. **WebSocket Fan-out** - - Single-server design limits broadcast scalability - - **Fix:** Redis Pub/Sub for multi-server WebSocket distribution - -4. **Commitment Storage** - - Every transfer creates new commitment row - - Table will grow to billions of rows - - **Fix:** Implement commitment pruning (keep last 100 per channel) - -### 3.3 Scalability Recommendations - -#### 3.3.1 Database Sharding - -``` -┌─────────────────────────────────────────────────────────┐ -│ Router Layer │ -│ hash(channel_id) % num_shards → shard_id │ -└───────────────┬─────────────────────────────────────────┘ - │ - ┌───────────┼───────────┬───────────┐ - ▼ ▼ ▼ ▼ -┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ -│Shard 0│ │Shard 1│ │Shard 2│ │Shard N│ -│Channels│ │Channels│ │Channels│ │Channels│ -│0-1M │ │1M-2M │ │2M-3M │ │NM+ │ -└───────┘ └───────┘ └───────┘ └───────┘ -``` - -#### 3.3.2 Event Sourcing - -Instead of mutable channel state, append-only transfer events: - -```typescript -interface ChannelEvent { - id: string; - channelId: string; - type: 'OPEN' | 'TRANSFER' | 'COMMITMENT' | 'CLOSE'; - payload: Record; - sequence: number; - timestamp: string; -} - -// Reconstruct channel state from events -function replayEvents(events: ChannelEvent[]): ChannelState { - return events.reduce((state, event) => { - switch (event.type) { - case 'TRANSFER': - return applyTransfer(state, event.payload); - // ... - } - }, initialState); -} -``` - -#### 3.3.3 CQRS (Command Query Responsibility Segregation) - -- **Command side:** Write to primary DB, publish to Kafka -- **Query side:** Materialize read models in Redis/Elasticsearch -- Enables independent scaling of reads vs writes - -### 3.4 Load Testing Plan - -```bash -# Install k6 -brew install k6 - -# Create load test script -cat > load_test.js << 'EOF' -import http from 'k6/http'; -import ws from 'k6/ws'; -import { check, sleep } from 'k6'; - -export const options = { - stages: [ - { duration: '2m', target: 100 }, // Ramp up - { duration: '5m', target: 1000 }, // Sustained load - { duration: '2m', target: 0 }, // Ramp down - ], -}; - -export default function() { - const res = http.post('http://localhost:3141/api/v1/transfers/transfer', JSON.stringify({ - fromChannelId: 'test-channel-1', - toChannelId: 'test-channel-2', - amount: '1000', - nonce: crypto.randomUUID(), - signature: 'mock-signature', - }), { headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer xxx' } }); - - check(res, { 'status is 201': (r) => r.status === 201 }); - sleep(0.1); -} -EOF - -k6 run load_test.js -``` - ---- - -## 4. Competitive Landscape - -### 4.1 Direct Competitors - -#### Taproot Assets (Lightning Labs) - -**Status:** Production (v0.7 as of December 2025) - -**Strengths:** -- Tether partnership (USDT on Lightning) -- Multi-asset support (stablecoins, synthetic assets) -- Lightning Network integration (multi-hop routing) -- Reusable addresses (BOLT 12) -- Battle-tested Lightning infrastructure - -**Weaknesses:** -- Complex setup (full Lightning node required) -- No native Runes support (would require etching) -- Liquidity management burden - -**Threat Level:** 🔴 HIGH — If Lightning Labs adds Runes support, they could obsolete RuneBolt - -#### Ark Protocol - -**Status:** Public Beta (Arkade, October 2025) - -**Strengths:** -- No channel management required -- Instant receiving without inbound liquidity -- vTXO model preserves UTXO semantics -- Tether investment ($5.2M, March 2026) -- Interoperable with Lightning via Boltz - -**Weaknesses:** -- Requires always-online ASP -- 4-week UTXO expiry (refresh burden) -- BTC-only (no Runes support yet) - -**Threat Level:** 🟡 MEDIUM — Could add Runes support, but focused on BTC - -#### RGB Protocol - -**Status:** Development - -**Strengths:** -- Client-side validation (privacy) -- Smart contract capabilities -- Complex asset schemas - -**Weaknesses:** -- Complex, slow development -- Limited tooling -- No Lightning integration yet - -**Threat Level:** 🟢 LOW — Too complex for mainstream adoption - -### 4.2 Competitive Advantages for RuneBolt - -1. **Runes-Native:** First mover in Runes payment channels -2. **Simpler Model:** Hub-spoke vs mesh network -3. **Developer-Friendly:** Clean TypeScript SDK potential -4. **Username System:** @username payments vs long addresses -5. **Claim Links:** Shareable payment links for onboarding - -### 4.3 Competitive Risks - -| Risk | Probability | Impact | Mitigation | -|------|-------------|--------|------------| -| Lightning Labs adds Runes | 40% | Severe | Ship fast, build moat with UX | -| Ark adds Runes support | 30% | High | Differentiate on simplicity | -| New L2 emerges | 20% | Medium | Stay informed, be adaptable | -| Runes lose popularity | 15% | Severe | Support multiple assets | - ---- - -## 5. UX/Product Analysis - -### 5.1 Current UX Flow - -``` -User Journey: First Payment - -1. Visit runebolt.io ─────────────────────────────────────────────┐ -2. Connect wallet (Unisat/Xverse) │ -3. Sign challenge message │ -4. Create channel ← FRICTION POINT: What's a channel? │ -5. Fund channel with on-chain tx ← FRICTION: 10+ min wait │ -6. Wait for confirmation │ -7. NOW can send ← Finally! │ - │ -Total time: 15-30 minutes ← UNACCEPTABLE for Venmo comparison │ -``` - -### 5.2 Target UX (Venmo Model) - -``` -User Journey: First Payment (Target) - -1. Download RuneBolt app -2. Sign in with X/Twitter (or Bitcoin wallet) -3. "@username send 1000 DOG" ← Natural language -4. Confirm biometric -5. Done in 2 seconds - -Background (invisible to user): -- Auto-channel creation if needed -- LSP provides inbound liquidity -- Batched settlement to L1 -``` - -### 5.3 UX Improvements Required - -#### 5.3.1 Zero-Knowledge Channel Opening - -Users shouldn't know channels exist. Implement: - -```typescript -// AutoChannelService.ts -class AutoChannelService { - async ensureUserHasChannel(pubkey: string): Promise { - const existing = await this.ledger.findOpenChannelForPubkey(pubkey); - if (existing) return existing; - - // Auto-create with hub-funded inbound liquidity - const channel = await this.channelManager.openChannelWithInboundLiquidity( - pubkey, - DEFAULT_INBOUND_LIQUIDITY - ); - - // Background funding, user doesn't wait - this.fundChannelAsync(channel.id); - - return channel.id; - } -} -``` - -#### 5.3.2 Instant Onboarding with Claims - -``` -User A (has RuneBolt) → creates claim link → shares on X -User B (new to RuneBolt) → clicks link → auto-creates account + channel -→ User B immediately has funds, zero wait time -``` - -#### 5.3.3 Social Login - -```typescript -// Auth options (prioritized) -1. Bitcoin wallet (Unisat, Xverse, Leather) -2. Lightning Login (LNURL-auth) -3. X/Twitter OAuth → derive deterministic keypair -4. Email magic link → derive keypair from hash(email + secret) -``` - -#### 5.3.4 Natural Language Commands - -```typescript -// ParsedIntent.ts -type Intent = - | { type: 'send', to: string, amount: bigint, rune: string } - | { type: 'request', from: string, amount: bigint } - | { type: 'balance' } - | { type: 'history' }; - -function parseCommand(input: string): Intent { - // "@alice send 1000 dog" - // "send 50 dog to alice" - // "request 100 dog from bob" - // Use simple regex or LLM for parsing -} -``` - -### 5.4 Mobile-First Design - -Current frontend is web-only. Need: - -1. **React Native app** (iOS + Android) -2. **Push notifications** for incoming payments -3. **Biometric auth** (Face ID, fingerprint) -4. **Widget** for quick balance check -5. **Apple Pay / Google Pay** for onramps - ---- - -## 6. Missing Pieces - -### 6.1 MUST HAVE Before Launch - -| Feature | Complexity | Time Estimate | Priority | -|---------|------------|---------------|----------| -| Real signature verification | Medium | 1 week | P0 | -| On-chain funding verification | Medium | 1 week | P0 | -| Penalty transactions | High | 3 weeks | P0 | -| Rate limiting | Low | 2 days | P0 | -| Nonce enforcement | Low | 1 day | P0 | -| Channel backups | Medium | 2 weeks | P0 | - -### 6.2 SHOULD HAVE for MVP - -| Feature | Complexity | Time Estimate | Priority | -|---------|------------|---------------|----------| -| Watchtower integration | High | 4 weeks | P1 | -| Multi-hop routing | High | 6 weeks | P1 | -| HTLC support | High | 4 weeks | P1 | -| Batch settlement | Medium | 2 weeks | P1 | -| LSP (Liquidity Service Provider) | High | 4 weeks | P1 | -| Mobile app | High | 8 weeks | P1 | - -### 6.3 NICE TO HAVE for Growth - -| Feature | Complexity | Time Estimate | Priority | -|---------|------------|---------------|----------| -| Federated hubs | Very High | 12 weeks | P2 | -| BitVM bridge | Very High | 16 weeks | P2 | -| Multi-rune support | Medium | 3 weeks | P2 | -| DLC oracles | High | 6 weeks | P2 | -| Fiat onramp | High | 8 weeks | P2 | -| SDK/API for developers | Medium | 4 weeks | P2 | - ---- - -## 7. Business Model & Moat - -### 7.1 Revenue Opportunities - -#### 7.1.1 Transaction Fees - -| Tier | Fee | Description | -|------|-----|-------------| -| Off-chain (RuneBolt→RuneBolt) | 0.1% | Internal transfers | -| Settlement (L2→L1) | 0.5% + miner fee | On-chain settlement | -| Cross-hub | 0.3% | Federation routing (future) | - -**Projection:** At 100K daily active users, 10 transfers/user/day, avg 10,000 DOG ($5): -- Daily volume: $5M -- Daily fees (0.1%): $5,000 -- Annual: $1.8M - -#### 7.1.2 LSP (Liquidity Service Provider) - -Charge for providing inbound liquidity: -- **Channel rental:** 1% APR for inbound capacity -- **Just-in-time liquidity:** 0.5% fee for instant channel creation - -#### 7.1.3 Premium Features - -- **Verified usernames:** $1/month -- **Analytics dashboard:** $10/month -- **API access:** $50-500/month based on volume -- **White-label solution:** Custom pricing - -#### 7.1.4 B2B/Enterprise - -- **Exchange integration:** Revenue share on deposits/withdrawals -- **dApp SDK licensing:** Per-install fee -- **Custom deployment:** Consulting fees - -### 7.2 Competitive Moat - -#### 7.2.1 Network Effects - -More users → more receivers → more senders → more users - -``` - ┌─────────────┐ - │ Users │ - │ (Senders) │ - └──────┬──────┘ - │ - ┌────────────┼────────────┐ - │ │ │ - ▼ ▼ ▼ - ┌──────────┐ ┌──────────┐ ┌──────────┐ - │Merchants │ │Influencers│ │ dApps │ - │(Receivers)│ │(Receivers)│ │(Receivers)│ - └──────────┘ └──────────┘ └──────────┘ - │ │ │ - └────────────┼────────────┘ - │ - ┌──────▼──────┐ - │ More Users │ - │ (Senders) │ - └─────────────┘ -``` - -#### 7.2.2 Username Registry - -Once people claim @usernames, they're locked in. Switching costs are high. - -#### 7.2.3 Developer Ecosystem - -SDK + documentation + tutorials → developer adoption → more integrations → user growth - -#### 7.2.4 Liquidity Depth - -More liquidity in channels → faster/cheaper payments → better UX → more users → more liquidity - -### 7.3 Go-to-Market Strategy - -**Phase 1: Crypto Natives (0-6 months)** -- Target DOG•GO•TO•THE•MOON community -- Influencer partnerships -- Telegram/Discord tipping bots - -**Phase 2: Creator Economy (6-12 months)** -- Twitch/YouTube tipping integration -- "Support me on RuneBolt" buttons -- NFT artist payouts - -**Phase 3: Commerce (12-24 months)** -- Merchant point-of-sale -- E-commerce plugins (Shopify, WooCommerce) -- Invoice system for freelancers - -**Phase 4: Mass Market (24+ months)** -- Fiat onramps (MoonPay, Ramp) -- Mobile-first marketing -- "Bitcoin for everyone" positioning - ---- - -## 8. Prioritized Recommendations - -### 8.1 Immediate (This Week) - -1. **Fix TaprootUtils signature verification** — 2 hours -2. **Add rate limiting** — 2 hours -3. **Enforce transfer nonce uniqueness** — 1 hour -4. **Fix JWT secret requirement** — 30 minutes -5. **Add input validation bounds** — 2 hours - -### 8.2 Short-Term (Next 2 Weeks) - -1. **Implement on-chain funding verification** — 3 days -2. **Add channel reserve requirement** — 1 day -3. **WebSocket message validation** — 1 day -4. **PostgreSQL UNIQUE constraints** — 1 day -5. **Basic monitoring/alerting** — 2 days -6. **Security headers (helmet.js)** — 1 day - -### 8.3 Medium-Term (Next 2 Months) - -1. **Penalty transaction infrastructure** — 3 weeks -2. **Revocation secret scheme** — 2 weeks -3. **Channel backup/recovery** — 2 weeks -4. **Basic watchtower** — 2 weeks -5. **LSP for zero-friction onboarding** — 3 weeks -6. **Mobile app MVP** — 4 weeks - -### 8.4 Long-Term (Next 6 Months) - -1. **Federation protocol** — 8 weeks -2. **Multi-hop routing (HTLC)** — 6 weeks -3. **BitVM bridge research** — 4 weeks -4. **SDK for developers** — 4 weeks -5. **Regulatory compliance framework** — 6 weeks - ---- - -## 9. Implementation Roadmap - -### Phase 1: Security Hardening (Weeks 1-3) - -``` -Week 1: -├── Day 1-2: Fix all CRITICAL security issues (C1-C5) -├── Day 3-4: Implement on-chain verification -├── Day 5: Rate limiting + input validation -└── Weekend: Security audit by external party - -Week 2: -├── Day 1-3: Penalty transaction infrastructure -├── Day 4-5: Revocation secret scheme -└── Weekend: Integration testing - -Week 3: -├── Day 1-2: Channel backup system -├── Day 3-4: Basic watchtower (internal) -├── Day 5: Documentation + runbooks -└── Weekend: Bug bounty launch -``` - -### Phase 2: Scalability (Weeks 4-6) - -``` -Week 4: -├── Database optimization + indexing -├── Redis cluster setup -├── Worker pool tuning -└── Load testing - -Week 5: -├── PostgreSQL read replicas -├── Connection pooling optimization -├── Event sourcing migration -└── Performance benchmarking - -Week 6: -├── Multi-server WebSocket distribution -├── CDN setup for frontend -├── Monitoring dashboards -└── Capacity planning documentation -``` - -### Phase 3: UX/Growth (Weeks 7-12) - -``` -Week 7-8: Mobile app foundation -Week 9-10: LSP implementation -Week 11-12: Social login + natural language commands -``` - -### Phase 4: Scale (Months 4-6) - -``` -Month 4: Federation protocol design + prototype -Month 5: Multi-hop routing + HTLC -Month 6: SDK + developer documentation + partnerships -``` - ---- - -## 10. Appendix: Code-Level Fixes - -### A1: Complete TaprootUtils Rewrite - -```typescript -// src/bitcoin/TaprootUtils.ts — COMPLETE REWRITE - -import * as secp256k1 from '@noble/secp256k1'; -import { sha256 } from '@noble/hashes/sha256'; -import { ripemd160 } from '@noble/hashes/ripemd160'; -import { bech32m } from '@scure/base'; -import crypto from 'crypto'; - -export interface KeyPair { - publicKey: string; // x-only pubkey (32 bytes hex) - privateKey: string; // 32 bytes hex -} - -export interface MultisigAddress { - address: string; // bc1p... bech32m address - script: string; // witness program hex - internalPubkey: string; - tweakedPubkey: string; -} - -export class TaprootUtils { - /** - * Generate a new Schnorr key pair using secp256k1. - */ - static generateKeyPair(): KeyPair { - const privateKey = secp256k1.utils.randomPrivateKey(); - const publicKey = secp256k1.schnorr.getPublicKey(privateKey); - - return { - publicKey: Buffer.from(publicKey).toString('hex'), - privateKey: Buffer.from(privateKey).toString('hex'), - }; - } - - /** - * Create a 2-of-2 Taproot multisig address. - * Uses MuSig2 key aggregation. - */ - static createMultisigAddress(pubkey1: string, pubkey2: string): MultisigAddress { - // Sort pubkeys lexicographically (required for MuSig2) - const sortedPubkeys = [pubkey1, pubkey2].sort(); - - // Compute aggregated public key (simplified — full MuSig2 is more complex) - const pk1 = Buffer.from(sortedPubkeys[0], 'hex'); - const pk2 = Buffer.from(sortedPubkeys[1], 'hex'); - - // KeyAgg hash (simplified version) - const keyAggData = Buffer.concat([pk1, pk2]); - const keyAggHash = sha256(keyAggData); - - // Compute aggregated key Q = H(P1||P2) * P1 + P2 - // For simplicity, using hash as "internal pubkey" - const internalPubkey = Buffer.from(keyAggHash).toString('hex'); - - // Tweak the internal pubkey for Taproot - const tweakHash = sha256( - Buffer.concat([ - Buffer.from('TapTweak', 'utf-8'), - Buffer.from(internalPubkey, 'hex'), - ]) - ); - - // For proper implementation, use secp256k1 point addition - // Here we simulate the tweaked pubkey - const tweakedPubkey = sha256( - Buffer.concat([Buffer.from(internalPubkey, 'hex'), tweakHash]) - ); - - // Create bech32m address - const witnessProgram = Buffer.from(tweakedPubkey); - const words = bech32m.toWords(witnessProgram); - words.unshift(1); // witness version 1 - const address = bech32m.encode('bc', words); - - return { - address, - script: `5120${Buffer.from(tweakedPubkey).toString('hex')}`, - internalPubkey, - tweakedPubkey: Buffer.from(tweakedPubkey).toString('hex'), - }; - } - - /** - * Verify a BIP-340 Schnorr signature. - */ - static async verifySchnorrSignature( - publicKey: string, - message: string, - signature: string - ): Promise { - try { - const pubkeyBytes = Buffer.from(publicKey, 'hex'); - const sigBytes = Buffer.from(signature, 'hex'); - const messageHash = sha256(Buffer.from(message, 'utf-8')); - - if (pubkeyBytes.length !== 32) { - console.error('[TaprootUtils] Invalid pubkey length:', pubkeyBytes.length); - return false; - } - - if (sigBytes.length !== 64) { - console.error('[TaprootUtils] Invalid signature length:', sigBytes.length); - return false; - } - - return secp256k1.schnorr.verify(sigBytes, messageHash, pubkeyBytes); - } catch (err) { - console.error('[TaprootUtils] Signature verification error:', err); - return false; - } - } - - /** - * Sign a message with BIP-340 Schnorr. - */ - static async signSchnorr(privateKey: string, message: string): Promise { - const privkeyBytes = Buffer.from(privateKey, 'hex'); - const messageHash = sha256(Buffer.from(message, 'utf-8')); - const signature = await secp256k1.schnorr.sign(messageHash, privkeyBytes); - return Buffer.from(signature).toString('hex'); - } -} -``` - -### A2: Rate Limiting Middleware - -```typescript -// src/middleware/rateLimiter.ts - -import rateLimit from 'express-rate-limit'; -import RedisStore from 'rate-limit-redis'; -import { getCache } from '../cache/RedisCache'; - -const redis = getCache(); - -export const authLimiter = rateLimit({ - store: new RedisStore({ - sendCommand: (...args: string[]) => redis.getClient().call(...args), - }), - windowMs: 15 * 60 * 1000, // 15 minutes - max: 10, // 10 auth attempts - message: { error: 'Too many authentication attempts, try again later' }, - standardHeaders: true, - legacyHeaders: false, -}); - -export const transferLimiter = rateLimit({ - store: new RedisStore({ - sendCommand: (...args: string[]) => redis.getClient().call(...args), - }), - windowMs: 60 * 1000, // 1 minute - max: 100, // 100 transfers - message: { error: 'Transfer rate limit exceeded' }, -}); - -export const apiLimiter = rateLimit({ - store: new RedisStore({ - sendCommand: (...args: string[]) => redis.getClient().call(...args), - }), - windowMs: 60 * 1000, - max: 1000, // 1000 API calls per minute - message: { error: 'API rate limit exceeded' }, -}); -``` - -### A3: Nonce Enforcement Migration - -```sql --- migrations/002_nonce_unique.sql - --- Add nonce column if not exists -ALTER TABLE transfers ADD COLUMN IF NOT EXISTS nonce VARCHAR(64); - --- Create unique index -CREATE UNIQUE INDEX IF NOT EXISTS idx_transfers_nonce ON transfers(nonce) WHERE nonce IS NOT NULL; - --- Add constraint -ALTER TABLE transfers ADD CONSTRAINT transfers_nonce_unique UNIQUE (nonce); -``` - -### A4: Channel Reserve Implementation - -```typescript -// src/channels/ChannelReserve.ts - -import { DOG_MULTIPLIER } from '../rune/RuneConstants'; - -const RESERVE_PERCENT = 1n; // 1% -const MIN_RESERVE = 100000n; // 1 DOG (assuming 5 decimals) - -export function calculateReserve(capacity: bigint): bigint { - const percentReserve = (capacity * RESERVE_PERCENT) / 100n; - return percentReserve > MIN_RESERVE ? percentReserve : MIN_RESERVE; -} - -export function validateTransferWithReserve( - currentBalance: bigint, - transferAmount: bigint, - capacity: bigint -): { valid: boolean; error?: string } { - const reserve = calculateReserve(capacity); - const newBalance = currentBalance - transferAmount; - - if (newBalance < reserve) { - return { - valid: false, - error: `Cannot reduce balance below reserve of ${reserve}. Available: ${currentBalance - reserve}`, - }; - } - - return { valid: true }; -} -``` - ---- - -## Conclusion - -RuneBolt has strong foundational architecture but critical security gaps that must be addressed before any mainnet deployment. The path to production is clear: - -1. **Weeks 1-3:** Fix all security vulnerabilities -2. **Weeks 4-6:** Scale infrastructure -3. **Weeks 7-12:** UX improvements and mobile -4. **Months 4-6:** Advanced features and partnerships - -With focused execution, RuneBolt can become the **dominant payment layer for Runes** — the "Venmo of Bitcoin" that the ecosystem needs. - -**Next Steps:** -1. Share this document with the team -2. Prioritize P0 security fixes -3. Engage external security auditor -4. Begin mobile app planning - ---- - -*Research completed: March 14, 2026* -*Agent: Deep Research (Kimi K2.5)* -*Tokens used: ~150K (research + analysis)* diff --git a/legacy/taproot-assets-era/SECURITY_AUDIT.md b/legacy/taproot-assets-era/SECURITY_AUDIT.md deleted file mode 100644 index f514d60..0000000 --- a/legacy/taproot-assets-era/SECURITY_AUDIT.md +++ /dev/null @@ -1,320 +0,0 @@ -# RuneBolt Protocol Security Audit - -**Audit Date:** 2026-03-14 -**Auditor:** Security Subagent (Kimi K2.5) -**Scope:** `/Users/gravity/projects/runebolt/backend/src/` -**Classification:** CRITICAL — Multiple vulnerabilities requiring immediate remediation - ---- - -## Executive Summary - -This audit reveals **14 security vulnerabilities** across the RuneBolt backend codebase, ranging from **CRITICAL** to **LOW** severity. The most severe issues include: - -1. **Mock signature acceptance in production** — Authentication bypass -2. **Missing replay attack protection** — Double-spend vulnerability -3. **No rate limiting** — DoS attack vector -4. **In-memory commitment storage** — State loss vulnerability -5. **Weak JWT secret fallback** — Token forgery - -**Recommendation:** Do NOT deploy to production until CRITICAL and HIGH severity issues are resolved. - ---- - -## Findings by Severity - -### 🔴 CRITICAL (5) - -#### C1: Mock Signature Verification in Production -**File:** `src/auth/ChallengeManager.ts` (lines 80-90) -**File:** `src/bitcoin/TaprootUtils.ts` (lines 108-125) -**File:** `src/channels/CommitmentManager.ts` (lines 85-105) - -**Issue:** The challenge verification accepts ANY non-empty signature without actual cryptographic verification. - -**Attack Vector:** Attacker can authenticate as ANY user by providing any non-empty string as a signature. - -**Fix:** Implement BIP-322 or Bitcoin message signing verification using @noble/secp256k1. - ---- - -#### C2: No Replay Attack Protection on Transfers -**File:** `src/ledger/RuneLedger.ts` (lines 23-130) - -**Issue:** Transfers lack unique identifiers (nonces) that prevent replay attacks. - -**Attack Scenario:** -1. Alice sends 1000 DOG to Bob -2. Attacker captures the WebSocket/API message -3. Attacker replays the same transfer 100 times - -**Fix:** Add transfer nonces with UNIQUE constraint in database. - ---- - -#### C3: In-Memory Commitment Storage (No Persistence) -**File:** `src/channels/CommitmentManager.ts` (line 18) - -**Issue:** Commitment states stored in JavaScript Map are lost on server restart. - -**Attack:** After restart, user can broadcast old commitment and steal funds. - -**Fix:** Persist commitments to SQLite database. - ---- - -#### C4: No Rate Limiting on Any Endpoint -**File:** `src/index.ts`, all route files - -**Issue:** No rate limiting allows DoS, brute force attacks. - -**Fix:** Implement express-rate-limit with strict auth endpoint limits. - ---- - -#### C5: Weak JWT Secret with Fallback -**File:** `src/auth/AuthMiddleware.ts` (line 6) - -**Issue:** `JWT_SECRET` falls back to predictable default. - -**Fix:** Require JWT_SECRET at startup with minimum 32 characters. - ---- - -### 🟠 HIGH (5) - -#### H1: No Input Validation on Channel Opening Amount -**File:** `src/api/routes/channelRoutes.ts`, `src/channels/ChannelManager.ts` - -**Issue:** No upper bound on channel amounts; risk of integer overflow. - -**Fix:** Use MIN_CHANNEL_CAPACITY and MAX_CHANNEL_CAPACITY from RuneConstants. - ---- - -#### H2: Integer Overflow Risk with BigInt/Number Conversion -**File:** `src/db/Database.ts`, `src/channels/ChannelManager.ts` - -**Issue:** BigInt converted to Number loses precision above 2^53-1. - -**Fix:** Store balances as TEXT in SQLite. - ---- - -#### H3: Missing Transaction Confirmation Verification -**File:** `src/channels/ChannelManager.ts` - -**Issue:** Channel activated without verifying funding tx confirmation. - -**Fix:** Wait for 1+ confirmations before activating channel. - ---- - -#### H4: WebSocket Message Validation Missing -**File:** `src/ws/WebSocketServer.ts` - -**Issue:** No Zod validation on WebSocket messages. - -**Fix:** Add discriminated union schema validation. - ---- - -#### H5: No HTTPS Enforcement / Secure CORS -**File:** `src/index.ts` - -**Issue:** CORS allows all origins; no HTTPS enforcement. - -**Fix:** Configure strict CORS and HSTS headers. - ---- - -### 🟡 MEDIUM (3) - -- M1: Missing Idempotency Keys -- M2: Error Messages Leak Internal Information -- M3: No WebSocket Connection Limits - -### 🟢 LOW (1) - -- L1: Timestamp Precision Issues - ---- - -## Security Best Practices from Lightning Network - -Based on Lightning Network security research: - -1. **Penalty Transactions:** Implement revocation secrets to punish old state broadcasts -2. **HTLC Timeout Handling:** Add timeout mechanisms for in-flight payments -3. **Watchtowers:** Consider third-party monitoring for channel breaches -4. **Channel Reserve:** Maintain minimum balance to prevent channel exhaustion attacks -5. **Max HTLC in Flight:** Limit concurrent pending transfers - ---- - -## Recommended Security Headers - -```typescript -app.use(helmet({ - contentSecurityPolicy: { - directives: { - defaultSrc: ["'self'"], - connectSrc: ["'self'", "wss:", "https:"], - }, - }, - hsts: { - maxAge: 31536000, - includeSubDomains: true, - preload: true, - }, -})); -``` - ---- - -## Security Test Cases - -```typescript -// Test C1: Authentication bypass -describe('ChallengeManager', () => { - it('should reject invalid signatures', async () => { - const result = await challengeManager.verifyChallenge(challengeId, 'invalid'); - expect(result.valid).toBe(false); - }); -}); - -// Test C2: Replay protection -describe('RuneLedger', () => { - it('should reject duplicate nonces', async () => { - const nonce = uuidv4(); - await ledger.transfer(from, to, 100n, 'test', nonce); - await expect(ledger.transfer(from, to, 100n, 'test', nonce)) - .rejects.toThrow('nonce already used'); - }); -}); - -// Test C4: Rate limiting -describe('Rate Limiting', () => { - it('should block excessive auth attempts', async () => { - for (let i = 0; i < 6; i++) { - await request(app).post('/api/v1/auth/challenge').send({ pubkey }); - } - const res = await request(app).post('/api/v1/auth/challenge').send({ pubkey }); - expect(res.status).toBe(429); - }); -}); -``` - ---- - -## Dependencies to Add - -```json -{ - "dependencies": { - "express-rate-limit": "^7.1.0", - "@noble/secp256k1": "^2.0.0", - "@scure/bip32": "^1.3.0", - "bitcoinjs-lib": "^6.1.0" - } -} -``` - ---- - -## Deployment Checklist - -- [ ] JWT_SECRET set to 32+ character random string -- [ ] NODE_ENV=production set -- [ ] HTTPS/WSS only (no HTTP/WS in production) -- [ ] Rate limiting enabled -- [ ] Database permissions restricted -- [ ] Logging configured for security events -- [ ] Secrets rotated (no placeholder values) -- [ ] Penetration testing completed - ---- - -*This audit was conducted as part of the RuneBolt Protocol Security Review. All findings should be addressed before mainnet deployment.* - ---- - -## Quick Reference: Security Checklist - -### Pre-Deployment (MUST FIX) -- [ ] **C1:** Implement real Bitcoin signature verification (BIP-322) -- [ ] **C2:** Add transfer nonce with UNIQUE database constraint -- [ ] **C3:** Persist commitments to database -- [ ] **C4:** Add express-rate-limit to all endpoints -- [ ] **C5:** Enforce JWT_SECRET on startup - -### High Priority (SHOULD FIX) -- [ ] **H1:** Add amount bounds checking (MIN/MAX_CHANNEL_CAPACITY) -- [ ] **H2:** Store balances as TEXT, not INTEGER -- [ ] **H3:** Wait for confirmations before channel activation -- [ ] **H4:** Add Zod validation to WebSocket messages -- [ ] **H5:** Configure strict CORS and security headers - -### Medium Priority (FIX WHEN POSSIBLE) -- [ ] **M1:** Add idempotency-key header support -- [ ] **M2:** Sanitize error messages in production -- [ ] **M3:** Limit WebSocket connections per IP/user - ---- - -## Dependencies to Install - -```bash -# Required for security fixes -npm install express-rate-limit -npm install @noble/secp256k1 -npm install @scure/bip32 -npm install bitcoinjs-lib - -# Dev dependencies for testing -npm install -D vitest supertest @types/supertest -``` - ---- - -## Bitcoin L2 Security Patterns - -### From Lightning Network: -1. **Penalty Transactions:** Store revocation secrets; punish old state broadcasts -2. **CLTV/CSV Timelocks:** Enable unilateral closes with delay -3. **HTLCs:** Hash-locked contracts for multi-hop payments -4. **Channel Reserve:** Keep minimum balance to prevent exhaustion - -### From RGB Protocol: -1. **Client-side validation:** State verified by clients, not just servers -2. **Single-use seals:** Prevent double-spends via Bitcoin anchoring -3. **Schema validation:** Strict type checking for state transitions - -### From Taproot Assets: -1. **Merkle-Sum Trees:** Prove solvency without revealing details -2. **Script-level controls:** Use Taproot for complex spending conditions -3. **Asset-aware transactions:** Encode rune transfers in witness data - ---- - -## Attack Scenarios Mitigated - -| Attack | Severity | Status | Fix | -|--------|----------|--------|-----| -| Auth Bypass | Critical | ❌ Open | C1 | -| Replay Attack | Critical | ❌ Open | C2 | -| State Loss | Critical | ❌ Open | C3 | -| DoS/Brute Force | Critical | ❌ Open | C4 | -| Token Forgery | Critical | ❌ Open | C5 | -| Integer Overflow | High | ❌ Open | H1, H2 | -| Fake Funding | High | ❌ Open | H3 | -| Message Injection | High | ❌ Open | H4 | -| CORS Exploit | High | ❌ Open | H5 | -| Race Condition | Medium | ❌ Open | M1 | -| Info Leakage | Medium | ❌ Open | M2 | -| Resource Exhaustion | Medium | ❌ Open | M3 | - ---- - -*Report generated: 2026-03-14* -*Next audit recommended after critical fixes deployed* diff --git a/legacy/taproot-assets-era/SECURITY_FIXES.md b/legacy/taproot-assets-era/SECURITY_FIXES.md deleted file mode 100644 index 67022c4..0000000 --- a/legacy/taproot-assets-era/SECURITY_FIXES.md +++ /dev/null @@ -1,262 +0,0 @@ -# RuneBolt Security Fixes - Implementation Guide - -This document provides specific code fixes for each security vulnerability identified in the audit. - ---- - -## CRITICAL FIXES - -### C1: Fix Mock Signature Verification - -**File:** `src/auth/ChallengeManager.ts` - -Replace lines 80-90 with: - -```typescript -import * as secp256k1 from '@noble/secp256k1'; -import { sha256 } from '@noble/hashes/sha256'; -import { bytesToHex } from '@noble/hashes/utils'; - -async verifyChallenge(challengeId: string, signature: string): Promise<{ valid: boolean; pubkey: string | null }> { - const challenge = this.db.getChallenge(challengeId); - if (!challenge) { - console.log(`[ChallengeManager] Challenge ${challengeId} not found`); - return { valid: false, pubkey: null }; - } - - // Check expiry - const expiresAt = new Date(challenge.expires_at).getTime(); - if (Date.now() > expiresAt) { - console.log(`[ChallengeManager] Challenge ${challengeId} expired`); - this.db.deleteChallenge(challengeId); - return { valid: false, pubkey: null }; - } - - // CRITICAL: Actually verify the signature - try { - const messageHash = sha256(challenge.challenge); - const sigBytes = Buffer.from(signature, 'hex'); - const pubkeyBytes = Buffer.from(challenge.pubkey, 'hex'); - - if (sigBytes.length !== 64) { - console.log(`[ChallengeManager] Invalid signature length: ${sigBytes.length}`); - return { valid: false, pubkey: null }; - } - - const isValid = await secp256k1.schnorr.verify(sigBytes, messageHash, pubkeyBytes); - - if (!isValid) { - console.log(`[ChallengeManager] Signature verification failed for ${challenge.pubkey.slice(0, 16)}...`); - return { valid: false, pubkey: null }; - } - - this.db.deleteChallenge(challengeId); - console.log(`[ChallengeManager] Challenge ${challengeId} verified successfully`); - return { valid: true, pubkey: challenge.pubkey }; - } catch (err) { - console.error('[ChallengeManager] Signature verification error:', err); - return { valid: false, pubkey: null }; - } -} -``` - ---- - -### C2: Add Replay Protection with Nonces - -**1. Update Database Schema** (`src/db/schema.sql`): - -```sql --- Add nonce and signature columns to transfers -ALTER TABLE transfers ADD COLUMN nonce TEXT UNIQUE; -ALTER TABLE transfers ADD COLUMN client_signature TEXT; -ALTER TABLE transfers ADD COLUMN transfer_hash TEXT; - --- Create index for nonce lookups -CREATE INDEX IF NOT EXISTS idx_transfers_nonce ON transfers(nonce); - --- Idempotency table for API requests -CREATE TABLE IF NOT EXISTS idempotent_requests ( - key TEXT PRIMARY KEY, - response TEXT NOT NULL, - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); - -CREATE INDEX IF NOT EXISTS idx_idempotent_requests_created ON idempotent_requests(created_at); -``` - -**2. Update Transfer Interface** (`src/ledger/Transfer.ts`): - -```typescript -export interface Transfer { - id: string; - fromChannel: string; - toChannel: string; - amount: bigint; - memo: string | null; - nonce: string; // REQUIRED - prevents replay - clientSignature: string; // REQUIRED - client signs transfer - transferHash: string; // Hash of transfer details - createdAt: string; -} - -// Zod schema update -export const TransferRequestSchema = z.object({ - fromChannelId: z.string().uuid(), - toChannelId: z.string().uuid().optional(), - recipientPubkey: z.string().min(64).max(66).optional(), - amount: z.string().regex(/^\d+$/), - memo: z.string().max(256).optional(), - nonce: z.string().uuid(), // REQUIRED - signature: z.string().min(128), // REQUIRED - client signature -}).refine((data) => data.toChannelId || data.recipientPubkey, { - message: 'Either toChannelId or recipientPubkey must be provided', -}); -``` - -**3. Update RuneLedger** (`src/ledger/RuneLedger.ts`): - -```typescript -transfer( - fromChannelId: string, - toChannelId: string, - amount: bigint, - memo: string | undefined, - nonce: string, // REQUIRED - clientSignature: string, // REQUIRED -): Transfer { - if (amount <= 0n) { - throw new Error('Transfer amount must be positive'); - } - - if (!nonce || !clientSignature) { - throw new Error('Transfer nonce and signature are required'); - } - - return this.db.transaction(() => { - // CRITICAL: Check for replay attack - const existingTransfer = this.db.prepare( - 'SELECT id FROM transfers WHERE nonce = ?' - ).get(nonce); - - if (existingTransfer) { - throw new Error('Transfer nonce already used - possible replay attack'); - } - - // Verify client signature - const transferHash = this.computeTransferHash(fromChannelId, toChannelId, amount, nonce); - const isValidSignature = this.verifyTransferSignature( - transferHash, - clientSignature, - fromChannelId - ); - - if (!isValidSignature) { - throw new Error('Invalid transfer signature'); - } - - // ... rest of transfer logic ... - - // Store with nonce and signature - this.db.createTransfer({ - id: transferId, - from_channel: fromChannelId, - to_channel: toChannelId, - amount: Number(amount), - memo: memo || null, - nonce, - client_signature: clientSignature, - transfer_hash: transferHash, - }); - - return transfer; - }); -} - -private computeTransferHash( - fromChannel: string, - toChannel: string, - amount: bigint, - nonce: string -): string { - const data = `${fromChannel}:${toChannel}:${amount}:${nonce}`; - return crypto.createHash('sha256').update(data).digest('hex'); -} -``` - ---- - -### C3: Persist Commitments to Database - -**1. Add Commitment Table** (`src/db/schema.sql`): - -```sql -CREATE TABLE IF NOT EXISTS commitments ( - id TEXT PRIMARY KEY, - channel_id TEXT NOT NULL, - sequence INTEGER NOT NULL, - local_balance TEXT NOT NULL, -- Stored as TEXT for BigInt - remote_balance TEXT NOT NULL, - hash TEXT NOT NULL, - local_signature TEXT, - remote_signature TEXT, - revocation_secret TEXT, -- For penalty transactions - revocation_hash TEXT, -- Hash of revocation secret - is_revoked INTEGER DEFAULT 0, -- Boolean flag - created_at TEXT NOT NULL DEFAULT (datetime('now')), - FOREIGN KEY (channel_id) REFERENCES channels(id), - UNIQUE(channel_id, sequence) -); - -CREATE INDEX IF NOT EXISTS idx_commitments_channel ON commitments(channel_id); -CREATE INDEX IF NOT EXISTS idx_commitments_channel_sequence ON commitments(channel_id, sequence); -``` - -**2. Update CommitmentManager** (`src/channels/CommitmentManager.ts`): - -```typescript -import Database from '../db/Database'; - -export class CommitmentManager { - private static db = Database.getInstance(); - - static createCommitment( - channelId: string, - localBalance: bigint, - remoteBalance: bigint, - sequence: number, - revocationSecret?: string - ): CommitmentState { - console.log( - `[CommitmentManager] Creating commitment #${sequence} for channel ${channelId}` - ); - - if (localBalance < 0n || remoteBalance < 0n) { - throw new Error('Commitment balances cannot be negative'); - } - - const preimage = `${channelId}:${sequence}:${localBalance}:${remoteBalance}:${Date.now()}`; - const hash = crypto.createHash('sha256').update(preimage).digest('hex'); - const revocationHash = revocationSecret - ? crypto.createHash('sha256').update(revocationSecret).digest('hex') - : null; - - const commitment: CommitmentState = { - channelId, - sequence, - localBalance, - remoteBalance, - localSignature: null, - remoteSignature: null, - hash, - createdAt: new Date().toISOString(), - }; - - // PERSIST to database - this.db.prepare(` - INSERT INTO commitments - (id, channel_id, sequence, local_balance, remote_balance, hash, revocation_hash, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(channel_id, sequence) DO UPDATE SET - local_balance = excluded.local_balance, - remote \ No newline at end of file diff --git a/legacy/taproot-assets-era/SECURITY_FIXES_FINAL.md b/legacy/taproot-assets-era/SECURITY_FIXES_FINAL.md deleted file mode 100644 index a8c9456..0000000 --- a/legacy/taproot-assets-era/SECURITY_FIXES_FINAL.md +++ /dev/null @@ -1,403 +0,0 @@ -# RuneBolt Security Fixes - FINAL IMPLEMENTATION REPORT - -**Date:** 2026-03-14 -**Status:** ✅ ALL 5 CRITICAL FIXES IMPLEMENTED -**Ready for:** Code review and testing - ---- - -## Executive Summary - -All 5 CRITICAL security vulnerabilities have been successfully implemented. The fixes include: - -1. ✅ **C1 - Real BIP-322 Schnorr Signature Verification** -2. ✅ **C2 - Replay Protection with Nonces** -3. ✅ **C3 - Persistent Commitment Storage** -4. ✅ **C4 - Rate Limiting on All Endpoints** -5. ✅ **C5 - Strong JWT Secret Generation** - ---- - -## Detailed Fix Implementation - -### C1 - Mock Signature → Real BIP-322 Schnorr Verification - -**Files Modified:** -- `src/auth/ChallengeManager.ts` (complete rewrite) - -**Key Changes:** -```typescript -// OLD (INSECURE): -if (isDev) { - return { valid: true, pubkey: challenge.pubkey }; // Bypass! -} - -// NEW (SECURE): -import * as secp256k1 from '@noble/secp256k1'; -import { sha256 } from '@noble/hashes/sha2'; - -const messageHash = sha256(new TextEncoder().encode(challenge.challenge)); -const sigBytes = new Uint8Array(Buffer.from(signature, 'hex')); -const pubkeyBytes = new Uint8Array(Buffer.from(challenge.pubkey, 'hex')); -const isValid = await secp256k1.schnorr.verify(sigBytes, messageHash, pubkeyBytes); -``` - -**Security Impact:** -- Eliminates authentication bypass vulnerability -- Requires valid cryptographic proof of key ownership -- Validates signature format (64 bytes for Schnorr) -- No dev mode bypasses - ---- - -### C2 - Replay Protection - -**Files Modified:** -- `src/ledger/RuneLedger.ts` -- `src/ledger/Transfer.ts` -- `src/db/Database.ts` -- `src/api/routes/transferRoutes.ts` -- `src/db/schema.sql` - -**Key Changes:** - -1. **Database Schema:** -```sql -ALTER TABLE transfers ADD COLUMN nonce TEXT UNIQUE; -ALTER TABLE transfers ADD COLUMN client_signature TEXT; -ALTER TABLE transfers ADD COLUMN transfer_hash TEXT; -CREATE INDEX idx_transfers_nonce ON transfers(nonce); -``` - -2. **Transfer Interface:** -```typescript -export interface Transfer { - id: string; - fromChannel: string; - toChannel: string; - amount: bigint; - memo: string | null; - nonce: string; // REQUIRED - prevents replay - clientSignature: string; // REQUIRED - client signs transfer - transferHash: string; // Hash of transfer details - createdAt: string; -} -``` - -3. **Replay Check in transfer() method:** -```typescript -// CRITICAL: Check for replay attack - nonce must be unique -const existingTransfer = await this.db.getTransferByNonce(nonce); -if (existingTransfer) { - throw new Error('Transfer nonce already used - possible replay attack'); -} - -// Verify client signature -const isValidSignature = this.verifyTransferSignature( - transferHash, - clientSignature, - senderPubkey -); -if (!isValidSignature) { - throw new Error('Invalid transfer signature'); -} -``` - -**Security Impact:** -- Eliminates double-spend vulnerability -- Each transfer requires unique nonce -- Client must cryptographically sign each transfer -- Duplicate nonces are rejected with 409 status - ---- - -### C3 - Persistent Commitments - -**Files Modified:** -- `src/channels/CommitmentManager.ts` (complete rewrite) -- `src/db/Database.ts` -- `src/db/schema.sql` - -**Key Changes:** - -1. **Database Schema:** -```sql -CREATE TABLE commitments ( - id TEXT PRIMARY KEY, - channel_id TEXT NOT NULL, - sequence INTEGER NOT NULL, - local_balance TEXT NOT NULL, - remote_balance TEXT NOT NULL, - hash TEXT NOT NULL, - local_signature TEXT, - remote_signature TEXT, - revocation_secret TEXT, - revocation_hash TEXT, - is_revoked INTEGER DEFAULT 0, - created_at TEXT NOT NULL, - UNIQUE(channel_id, sequence) -); -``` - -2. **Commitment Persistence:** -```typescript -static async createCommitment( - channelId: string, - localBalance: bigint, - remoteBalance: bigint, - sequence: number -): Promise { - // ... create commitment ... - - // PERSIST to database - await this.db.createCommitment({ - id: commitment.id, - channel_id: channelId, - sequence, - local_balance: localBalance.toString(), - remote_balance: remoteBalance.toString(), - hash, - revocation_hash: revocationHash, - created_at: commitment.createdAt, - }); - - return commitment; -} -``` - -**Security Impact:** -- Eliminates data loss on server restart -- Enables long-term dispute resolution -- Supports penalty transactions with revocation secrets -- Full audit trail of all commitment states - ---- - -### C4 - Rate Limiting - -**Files Modified:** -- `src/index.ts` -- `package.json` - -**Key Changes:** - -```typescript -import rateLimit from 'express-rate-limit'; - -// General API: 100 requests per 15 minutes -const generalLimiter = rateLimit({ - windowMs: 15 * 60 * 1000, - max: 100, - standardHeaders: true, - legacyHeaders: false, -}); - -// Authentication: 10 requests per 15 minutes -const authLimiter = rateLimit({ - windowMs: 15 * 60 * 1000, - max: 10, - skipSuccessfulRequests: true, -}); - -// Transfers: 30 per minute per user -const transferLimiter = rateLimit({ - windowMs: 60 * 1000, - max: 30, - keyGenerator: (req) => req.auth?.pubkey || req.ip, -}); - -// Apply to routes -app.use('/api/', generalLimiter); -app.use('/api/v1/transfer', transferLimiter, transferRoutes); -app.use('/api/v1/auth', authLimiter, authRoutes); -``` - -**Security Impact:** -- Prevents brute force attacks on authentication -- Limits transfer abuse -- Protects against DDoS attacks -- Returns standard 429 status codes - ---- - -### C5 - Strong JWT Secret - -**Files Modified:** -- `src/auth/AuthMiddleware.ts` -- `.env.example` - -**Key Changes:** - -```typescript -function getJwtSecret(): string { - const envSecret = process.env.JWT_SECRET; - - if (envSecret && envSecret.length >= 32 && - envSecret !== 'change_me_in_production') { - return envSecret; - } - - if (process.env.NODE_ENV === 'production') { - throw new Error( - 'CRITICAL: JWT_SECRET must be set to a strong secret (min 32 chars)' - ); - } - - // Development: generate temporary secret - return crypto.randomBytes(32).toString('hex'); -} - -const JWT_SECRET = getJwtSecret(); -const JWT_ALGORITHM = 'HS256'; - -export function verifyToken(token: string): AuthPayload { - const decoded = jwt.verify(token, JWT_SECRET, { - algorithms: [JWT_ALGORITHM], - }) as AuthPayload; - - // Validate payload structure - if (!decoded.pubkey || typeof decoded.pubkey !== 'string') { - throw new Error('Invalid token payload'); - } - - return decoded; -} -``` - -**Security Impact:** -- Eliminates weak JWT secret vulnerability -- Prevents JWT algorithm confusion attacks -- Enforces minimum 32-character secret in production -- Validates token structure - ---- - -## Dependencies Added - -```json -{ - "express-rate-limit": "^7.x", - "@noble/secp256k1": "^2.x", - "@noble/hashes": "^1.x" -} -``` - ---- - -## Database Migrations - -**File:** `src/db/migrations/001_security_fixes.sql` - -**Schema Changes:** -1. Added `nonce`, `client_signature`, `transfer_hash` to `transfers` table -2. Created `commitments` table for persistent storage -3. Created `idempotent_requests` table for API idempotency -4. Added indexes for performance - ---- - -## API Changes - -### POST /transfer - -**New Required Fields:** -```json -{ - "fromChannelId": "uuid", - "toChannelId": "uuid (optional)", - "recipientPubkey": "string (optional)", - "amount": "string", - "memo": "string (optional)", - "nonce": "uuid (REQUIRED)", - "signature": "string (REQUIRED - min 128 chars)" -} -``` - -**New Error Responses:** -- `409` - Transfer nonce already used (replay attack) -- `401` - Invalid transfer signature -- `429` - Rate limit exceeded - ---- - -## Testing - -Created comprehensive security test suite: -- **File:** `src/__tests__/security.test.ts` -- Tests all 5 critical fixes -- Validates signature verification, replay protection, and JWT security - ---- - -## Deployment Checklist - -Before deploying to production: - -- [ ] Set strong `JWT_SECRET` (min 32 chars) in environment -- [ ] Run database migration: `001_security_fixes.sql` -- [ ] Test authentication with real Bitcoin signatures -- [ ] Test transfer flow with nonce/signature -- [ ] Verify commitments persist after restart -- [ ] Review rate limit thresholds - ---- - -## Backwards Compatibility - -⚠️ **BREAKING CHANGES:** - -1. **Transfer API**: Now requires `nonce` and `signature` fields -2. **Authentication**: Real signature verification (no dev bypass) -3. **Database**: New columns and tables required - -**Migration Required:** Run `001_security_fixes.sql` before deploying. - ---- - -## Files Modified Summary - -| File | Changes | -|------|---------| -| `src/auth/ChallengeManager.ts` | Complete rewrite - real Schnorr verification | -| `src/auth/AuthMiddleware.ts` | Strong JWT secret, algorithm enforcement | -| `src/ledger/RuneLedger.ts` | Replay protection, signature verification | -| `src/ledger/Transfer.ts` | Added nonce/signature fields | -| `src/channels/CommitmentManager.ts` | Complete rewrite - database persistence | -| `src/db/Database.ts` | Added new tables and methods | -| `src/db/schema.sql` | New columns and tables | -| `src/index.ts` | Rate limiting middleware | -| `src/api/routes/transferRoutes.ts` | Nonce/signature validation | -| `src/api/routes/authRoutes.ts` | Async challenge verification | -| `src/api/routes/claimRoutes.ts` | Async database calls | -| `src/api/routes/channelRoutes.ts` | Async database calls | -| `src/api/routes/userRoutes.ts` | Async database calls | -| `.env.example` | JWT documentation | - ---- - -## Security Audit Result - -| Issue | Status | Risk Level | -|-------|--------|------------| -| C1 - Mock signatures | ✅ Fixed | Critical | -| C2 - Replay protection | ✅ Fixed | Critical | -| C3 - In-memory commitments | ✅ Fixed | Critical | -| C4 - No rate limiting | ✅ Fixed | Critical | -| C5 - Weak JWT fallback | ✅ Fixed | Critical | - -**Overall Status:** 🛡️ **ALL CRITICAL ISSUES RESOLVED** - -The RuneBolt backend is now ready for production deployment with proper security controls in place. - ---- - -## Notes - -The codebase was found to have both SQLite and PostgreSQL implementations. The security fixes have been implemented for both database backends where applicable. The PostgreSQL version is the primary target for production deployment. - -All cryptographic operations use industry-standard libraries: -- `@noble/secp256k1` for Schnorr signatures -- `@noble/hashes` for SHA256 hashing -- `express-rate-limit` for rate limiting - -These libraries are audited, widely-used, and suitable for production financial systems. diff --git a/legacy/taproot-assets-era/SECURITY_FIXES_SUMMARY.md b/legacy/taproot-assets-era/SECURITY_FIXES_SUMMARY.md deleted file mode 100644 index 7948d36..0000000 --- a/legacy/taproot-assets-era/SECURITY_FIXES_SUMMARY.md +++ /dev/null @@ -1,282 +0,0 @@ -# RuneBolt Security Fixes - Implementation Summary - -**Date:** 2026-03-14 -**Status:** ✅ COMPLETE -**Critical Issues Fixed:** 5/5 - ---- - -## Summary - -All 5 CRITICAL security vulnerabilities identified in the audit have been successfully fixed and tested. - ---- - -## Fixes Implemented - -### C1 - Mock Signature Acceptance → Real BIP-322 Schnorr Verification ✅ - -**File:** `src/auth/ChallengeManager.ts` - -**Changes:** -- Replaced mock signature verification with real BIP-322 Schnorr signature verification -- Added imports for `@noble/secp256k1` and `@noble/hashes/sha2` -- Signature verification now uses `secp256k1.schnorr.verify()` -- Validates signature length (must be exactly 64 bytes) -- Converts inputs to proper Uint8Array format - -**Security Impact:** -- Eliminates authentication bypass vulnerability -- Requires valid cryptographic proof of key ownership -- Prevents replay of old challenges - ---- - -### C2 - No Replay Protection → Nonce Tracking & Double-Spend Prevention ✅ - -**Files Modified:** -- `src/ledger/RuneLedger.ts` -- `src/ledger/Transfer.ts` -- `src/db/schema.sql` -- `src/db/Database.ts` -- `src/api/routes/transferRoutes.ts` - -**Changes:** -- Added `nonce`, `client_signature`, `transfer_hash` columns to `transfers` table -- Added unique constraint on `nonce` column -- Updated `Transfer` interface to require nonce and signature fields -- Added `getTransferByNonce()` database method -- Updated `transfer()` method to: - - Check for duplicate nonces (replay attack prevention) - - Compute transfer hash for signature verification - - Verify client signature before processing -- Updated transfer API to accept and validate nonce/signature - -**Security Impact:** -- Eliminates double-spend vulnerability -- Each transfer requires unique nonce -- Client must cryptographically sign each transfer - ---- - -### C3 - In-Memory Commitments → Persistent Database Storage ✅ - -**Files Modified:** -- `src/channels/CommitmentManager.ts` (complete rewrite) -- `src/db/schema.sql` -- `src/db/Database.ts` - -**Changes:** -- Complete rewrite of `CommitmentManager` to use database persistence -- Added `commitments` table with: - - Full commitment state storage - - Signature tracking - - Revocation support - - Audit trail -- Added database methods: - - `createCommitment()` - - `getLatestCommitment()` - - `getCommitmentByChannelAndSequence()` - - `updateCommitmentSignatures()` - - `revokeCommitment()` -- Commitments now survive server restarts -- Enables proper dispute resolution - -**Security Impact:** -- Eliminates data loss on restart -- Enables long-term dispute resolution -- Supports penalty transactions with revocation secrets - ---- - -### C4 - No Rate Limiting → Express-Rate-Limit Implementation ✅ - -**Files Modified:** -- `src/index.ts` -- `package.json` - -**Changes:** -- Added `express-rate-limit` dependency -- Implemented three tiers of rate limiting: - 1. **General API**: 100 requests per 15 minutes per IP - 2. **Authentication**: 10 requests per 15 minutes (skips successful attempts) - 3. **Transfers**: 30 transfers per minute per user -- Rate limits return proper 429 status codes with JSON error messages -- Applied to all `/api/v1/*` routes - -**Security Impact:** -- Prevents brute force attacks on authentication -- Limits transfer abuse -- Protects against DDoS attacks -- Returns standard rate limit headers - ---- - -### C5 - Weak JWT Fallback → Strong Secret Generation ✅ - -**Files Modified:** -- `src/auth/AuthMiddleware.ts` -- `.env.example` - -**Changes:** -- Added secure JWT secret generation logic -- In production: throws error if JWT_SECRET is not set or is weak -- In development: generates temporary cryptographically secure secret -- Validates JWT secret is at least 32 characters -- Enforces HS256 algorithm (no algorithm confusion attacks) -- Validates token payload structure and pubkey format -- Updated `.env.example` with documentation - -**Security Impact:** -- Eliminates weak JWT secret vulnerability -- Prevents JWT algorithm confusion attacks -- Ensures strong secret in production -- Validates token structure to prevent malformed token attacks - ---- - -## Database Schema Changes - -### New Tables - -**commitments** -```sql -id TEXT PRIMARY KEY -channel_id TEXT NOT NULL -sequence INTEGER NOT NULL -local_balance TEXT NOT NULL -remote_balance TEXT NOT NULL -hash TEXT NOT NULL -local_signature TEXT -remote_signature TEXT -revocation_secret TEXT -revocation_hash TEXT -is_revoked INTEGER DEFAULT 0 -created_at TEXT NOT NULL -``` - -**idempotent_requests** -```sql -key TEXT PRIMARY KEY -response TEXT NOT NULL -created_at TEXT NOT NULL -``` - -### Modified Tables - -**transfers** - Added columns: -```sql -nonce TEXT UNIQUE -client_signature TEXT -transfer_hash TEXT -``` - ---- - -## Dependencies Added - -```json -{ - "express-rate-limit": "^7.x", - "@noble/secp256k1": "^2.x", - "@noble/hashes": "^1.x" -} -``` - ---- - -## API Changes - -### POST /transfer - -**New Required Fields:** -```json -{ - "fromChannelId": "uuid", - "toChannelId": "uuid (optional)", - "recipientPubkey": "string (optional)", - "amount": "string", - "memo": "string (optional)", - "nonce": "uuid (REQUIRED)", - "signature": "string (REQUIRED - min 128 chars)" -} -``` - -**Response:** -- Returns `nonce` and `transferHash` in response -- 400 error if nonce missing or invalid -- 401 error if signature invalid -- 409 error if nonce already used (replay attack prevention) -- 429 error if rate limit exceeded - ---- - -## Testing - -Created comprehensive security test suite: -- **File:** `src/__tests__/security.test.ts` -- **Coverage:** - - Schnorr signature verification (C1) - - Replay protection with nonces (C2) - - Persistent commitment storage (C3) - - JWT security validation (C5) - ---- - -## Deployment Checklist - -Before deploying to production: - -- [ ] Set strong `JWT_SECRET` environment variable (min 32 chars) -- [ ] Run database migration: `001_security_fixes.sql` -- [ ] Verify all rate limit environment variables -- [ ] Test authentication with real Bitcoin signatures -- [ ] Test transfer flow with nonce/signature -- [ ] Verify commitments persist after restart -- [ ] Review rate limit thresholds for your use case - ---- - -## Verification Commands - -```bash -# Install dependencies -npm install - -# Type check -npx tsc --noEmit - -# Run security tests -npm test -- security.test.ts - -# Start server -npm run dev -``` - ---- - -## Backwards Compatibility - -⚠️ **BREAKING CHANGES:** - -1. **Transfer API**: Now requires `nonce` and `signature` fields -2. **Authentication**: Real signature verification (no more dev mode bypass) -3. **Database**: New columns and tables required - -**Migration Required:** Run `001_security_fixes.sql` before deploying. - ---- - -## Security Audit Result - -| Issue | Status | Risk Level | -|-------|--------|------------| -| C1 - Mock signatures | ✅ Fixed | Critical | -| C2 - Replay protection | ✅ Fixed | Critical | -| C3 - In-memory commitments | ✅ Fixed | Critical | -| C4 - No rate limiting | ✅ Fixed | Critical | -| C5 - Weak JWT fallback | ✅ Fixed | Critical | - -**Overall Status:** 🛡️ **ALL CRITICAL ISSUES RESOLVED** - -The RuneBolt backend is now ready for production deployment with proper security controls in place. diff --git a/legacy/taproot-assets-era/SPECS_BITVM_BRIDGE.md b/legacy/taproot-assets-era/SPECS_BITVM_BRIDGE.md deleted file mode 100644 index 3ba0b8a..0000000 --- a/legacy/taproot-assets-era/SPECS_BITVM_BRIDGE.md +++ /dev/null @@ -1,441 +0,0 @@ -# Technical Specification: BitVM Bridge for Runes - -**Document Version:** 1.0 -**Date:** March 14, 2026 -**Author:** RuneBolt Protocol Research Team -**Status:** Draft for Review - ---- - -## 1. Executive Summary - -This specification defines a trust-minimized bridge architecture enabling Runes to move between Bitcoin L1 and RuneBolt L2 using BitVM fraud proofs. This approach provides 1-of-n security guarantees without requiring Bitcoin soft forks. - ---- - -## 2. Objectives - -1. Enable fast, cheap Runes transfers on RuneBolt L2 -2. Maintain Bitcoin-level security for deposits/withdrawals -3. No trusted custodians (1-of-n honesty assumption) -4. Upgradeable toward ZK verification post-OP_CAT - ---- - -## 3. Architecture Overview - -### 3.1 High-Level Design - -``` - ┌──────────────────────────────────────────┐ - │ BITCOIN MAINNET │ - │ ┌─────────────────────────────────┐ │ - │ │ Runes Vault Contract │ │ - │ │ (Taproot multisig + BitVM) │ │ - │ └─────────────────────────────────┘ │ - └──────────────────────────────────────────┘ - ▲ - │ Fraud Proofs / Challenges - │ (14-day window) - ▼ -┌──────────────┐ ┌──────────────────────────────────────────┐ -│ Users │ │ OPERATOR SET (n=7) │ -│ │─────▶│ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │ -│ Deposit/ │ │ │ Op1 │ │ Op2 │ │ Op3 │ │... │ │ -│ Withdraw │◀─────│ └──┬──┘ └──┬──┘ └──┬──┘ └──┬──┘ │ -└──────────────┘ │ └───────┴───────┴───────┘ │ - │ │ │ - └──────────────┼───────────────────────────┘ - │ - ▼ State Updates - ┌──────────────────────────────────────────┐ - │ RUNEBOLT L2 │ - │ ┌─────────────────────────────────┐ │ - │ │ Bridge Smart Contract │ │ - │ │ (Runes balances, exits) │ │ - │ └─────────────────────────────────┘ │ - └──────────────────────────────────────────┘ -``` - -### 3.2 Component Breakdown - -| Component | Location | Function | -|-----------|----------|----------| -| Runes Vault | Bitcoin L1 | Holds deposited Runes in Taproot output | -| Bridge Contract | RuneBolt L2 | Manages L2 balances, processes withdrawals | -| Operator Set | Distributed | Validate state, sign withdrawals, watch for fraud | -| BitVM Verifier | Bitcoin L1 | Validates fraud proofs during challenge period | -| Runes Indexer | RuneBolt L2 | Tracks Runes UTXOs and ownership | - ---- - -## 4. Detailed Specifications - -### 4.1 Deposit Flow - -``` -Step 1: User deposits Runes to Vault Address - └─▶ Runes locked in Taproot output - -Step 2: Operators index deposit (6 confirmations) - └─▶ Generate L2 minting transaction - -Step 3: L2 Bridge Contract mints wrapped Runes - └─▶ User receives L2 balance - -Time: ~60 minutes (6 Bitcoin blocks) -``` - -**Bitcoin Script (Vault Output):** -```bitcoin-script -OP_IF - # Normal path: Operators sign withdrawal - OP_5 # 5-of-7 threshold - ... - OP_7 - OP_CHECKMULTISIG -OP_ELSE - # Fraud proof path: BitVM verification - OP_1 - - OP_CHECKSEQUENCEVERIFY - OP_DROP - # User can exit after timeout if fraud proven -OP_ENDIF -``` - -### 4.2 Withdrawal Flow - -``` -Step 1: User initiates withdrawal on L2 - └─▶ Balance locked for 14 days - -Step 2: Operators co-sign withdrawal tx - └─▶ Published to Bitcoin mempool - -Step 3: Challenge period (14 days) - └─▶ Anyone can submit fraud proof - -Step 4: If no challenge: withdrawal completes - └─▶ User receives Runes on L1 - -Step 5: If challenged: BitVM arbitration - └─▶ Honest party wins via fraud proof -``` - -### 4.3 Fraud Proof Mechanism - -**BitVM Circuit Logic:** -```rust -pub struct WithdrawalProof { - pub l2_block_height: u64, - pub l2_state_root: [u8; 32], - pub withdrawal_tx: Transaction, - pub merkle_proof: MerkleProof, - pub user_signature: Signature, -} - -impl BitVMCircuit for WithdrawalProof { - fn verify(&self) -> Result<(), FraudError> { - // 1. Verify L2 state root is valid - verify_state_root(self.l2_block_height, self.l2_state_root)?; - - // 2. Verify withdrawal exists in state - verify_merkle_proof( - self.withdrawal_tx.hash(), - self.l2_state_root, - self.merkle_proof - )?; - - // 3. Verify user authorized withdrawal - verify_signature( - self.user_signature, - self.withdrawal_tx.hash(), - self.withdrawal_tx.from - )?; - - // 4. Verify amount matches L2 balance - verify_sufficient_balance( - self.withdrawal_tx.from, - self.withdrawal_tx.amount, - self.l2_state_root - )?; - - Ok(()) - } -} -``` - -**Challenge Process:** -1. Challenger posts bond (1 BTC) -2. Challenger submits fraud proof within 14 days -3. BitVM verifier checks proof on Bitcoin -4. If valid: operators slashed, challenger rewarded -5. If invalid: challenger loses bond - ---- - -## 5. Security Model - -### 5.1 Threat Scenarios - -| Threat | Mitigation | -|--------|------------| -| Operator theft | 5-of-7 multisig + BitVM challenge | -| Operator collusion | 1-of-7 honest operator prevents theft | -| Invalid state transition | Fraud proofs slash malicious operators | -| Liveness failure | Emergency exit after 30 days | -| Censorship | Anyone can challenge, not just operators | - -### 5.2 Economic Security - -**Collateral Requirements:** -- Each operator stakes: 100 BTC -- Total collateral pool: 700 BTC -- Maximum bridge TVL: 500 BTC (70% collateral ratio) -- Insurance fund: 50 BTC from fees - -**Slashing Conditions:** -- Invalid withdrawal attempt: 100% slash -- Failure to challenge fraud: 50% slash -- Extended downtime (>72 hours): 25% slash - -### 5.3 Emergency Procedures - -**Scenario 1: Mass Operator Exit** -``` -If operators < 5 remain active: - - Bridge pauses new withdrawals - - Users can exit via emergency withdrawal - - 7-day timelock for safety -``` - -**Scenario 2: Critical Bug Discovery** -``` -If critical vulnerability found: - - 2-of-5 multisig pauses bridge - - 48-hour fix window - - If unpatched: emergency exit activates -``` - ---- - -## 6. Runes Integration - -### 6.1 UTXO Tracking - -```typescript -interface RunesUTXO { - txid: string; - vout: number; - runeId: string; - amount: bigint; - divisibility: number; - lockScript: Buffer; -} - -class RunesIndexer { - private utxos: Map; - - async indexBlock(blockHeight: number): Promise { - const block = await this.bitcoin.getBlock(blockHeight); - - for (const tx of block.transactions) { - // Check for Runes protocol in OP_RETURN - const runesData = this.parseRunesData(tx); - if (runesData) { - await this.processRunesTx(tx, runesData); - } - } - } - - private async processRunesTx(tx: Transaction, data: RunesData): Promise { - // Handle etching, minting, transferring - switch (data.opcode) { - case 'ETCH': - this.registerRune(data.rune); - break; - case 'MINT': - this.addToBalance(data.to, data.runeId, data.amount); - break; - case 'TRANSFER': - this.transferBalance(data.from, data.to, data.runeId, data.amount); - break; - } - } -} -``` - -### 6.2 L2 Runes Representation - -```solidity -contract L2Runes is ERC20 { - struct RuneInfo { - bytes32 runeId; - string symbol; - uint8 divisibility; - uint256 l1Supply; - uint256 l2Supply; - } - - mapping(bytes32 => RuneInfo) public runes; - mapping(address => mapping(bytes32 => uint256)) public balances; - - function mint(bytes32 runeId, address to, uint256 amount) external onlyBridge { - balances[to][runeId] += amount; - runes[runeId].l2Supply += amount; - emit Mint(runeId, to, amount); - } - - function burn(bytes32 runeId, uint256 amount) external { - balances[msg.sender][runeId] -= amount; - runes[runeId].l2Supply -= amount; - emit Burn(runeId, msg.sender, amount); - } -} -``` - ---- - -## 7. Implementation Roadmap - -### Phase 1: MVP (Q2 2026) -- [ ] 5-of-9 federated multisig (no BitVM) -- [ ] Basic deposit/withdrawal -- [ ] Runes indexing -- [ ] L2 bridge contract -- **Security:** Federated trust model - -### Phase 2: BitVM Integration (Q4 2026) -- [ ] BitVM verifier implementation -- [ ] Challenge/response protocol -- [ ] Fraud proof generation -- [ ] Operator slashing -- **Security:** 1-of-n honesty assumption - -### Phase 3: Decentralization (2027) -- [ ] Permissionless operator set -- [ ] Dynamic operator rotation -- [ ] OP_CAT optimization (if activated) -- **Security:** Fully trust-minimized - -### Phase 4: ZK Verification (2027+) -- [ ] STARK proof verification -- [ ] Instant withdrawals (no challenge period) -- [ ] Recursive bridging -- **Security:** Cryptographic guarantees - ---- - -## 8. API Specification - -### 8.1 Deposit Endpoint - -```http -POST /api/v1/bridge/deposit -Content-Type: application/json - -{ - "runeId": "AWESOME•RUNE•TOKEN", - "amount": "1000000", - "l2Address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", - "returnAddress": "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh" -} - -Response: -{ - "depositAddress": "bc1q...", - "expiresAt": "2026-03-21T15:30:00Z", - "minConfirmations": 6, - "estimatedTime": "3600" -} -``` - -### 8.2 Withdrawal Endpoint - -```http -POST /api/v1/bridge/withdraw -Content-Type: application/json -Authorization: Bearer {jwt} - -{ - "runeId": "AWESOME•RUNE•TOKEN", - "amount": "500000", - "l1Address": "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh" -} - -Response: -{ - "withdrawalId": "wd_abc123", - "status": "pending", - "challengePeriodEnd": "2026-03-28T15:30:00Z", - "estimatedCompletion": "2026-03-28T15:30:00Z" -} -``` - -### 8.3 Status Endpoint - -```http -GET /api/v1/bridge/status/{withdrawalId} - -Response: -{ - "withdrawalId": "wd_abc123", - "status": "completed", // pending, challenging, completed, failed - "l1Txid": "a1b2c3d4...", - "amount": "500000", - "runeId": "AWESOME•RUNE•TOKEN", - "confirmedAt": "2026-03-28T14:15:00Z" -} -``` - ---- - -## 9. Testing Strategy - -### 9.1 Testnet Deployment -- Bitcoin Signet for L1 testing -- RuneBolt testnet for L2 testing -- Mock BitVM for rapid iteration - -### 9.2 Security Audit Checklist -- [ ] Smart contract audit (OpenZeppelin or Trail of Bits) -- [ ] BitVM circuit formal verification -- [ ] Cryptographic review of fraud proofs -- [ ] Economic attack simulation -- [ ] Stress test with 1000+ concurrent withdrawals - -### 9.3 Bug Bounty Program -- Critical: $500,000 (theft of funds) -- High: $100,000 (denial of service) -- Medium: $25,000 (information disclosure) -- Low: $5,000 (best practices) - ---- - -## 10. References - -1. BitVM: Aanyhr et al. - "BitVM: Quasi-Turing Complete Computation on Bitcoin" (2024) -2. Bitcoin Optech - Taproot Assets documentation -3. StarkWare - Bitcoin scaling research -4. BIP 347 - OP_CAT reactivation proposal -5. BIP 119 - OP_CTV covenant proposal -6. DLC Specifications - Discreet Log Contracts -7. Fedimint Protocol - Federated e-cash - ---- - -## Appendix A: Glossary - -- **BitVM**: Fraud proof-based computation on Bitcoin -- **Runes**: Fungible token protocol on Bitcoin -- **UTXO**: Unspent Transaction Output -- **Taproot**: Bitcoin upgrade enabling Schnorr signatures -- **Fraud Proof**: Cryptographic proof of invalid state transition -- **Challenge Period**: Time window for submitting fraud proofs -- **Operator**: Bridge validator node -- **Vault**: Smart contract holding deposited assets - ---- - -*Specification Version 1.0 - March 14, 2026* \ No newline at end of file diff --git a/legacy/taproot-assets-era/UX_COMPLETION_SUMMARY.md b/legacy/taproot-assets-era/UX_COMPLETION_SUMMARY.md deleted file mode 100644 index ab7ebec..0000000 --- a/legacy/taproot-assets-era/UX_COMPLETION_SUMMARY.md +++ /dev/null @@ -1,164 +0,0 @@ -# RuneBolt UX Improvements - Implementation Complete - -## Summary - -Successfully implemented all 5 major UX improvements for RuneBolt mass adoption: - -### ✅ 1. Redesigned Onboarding Flow -- **File**: `frontend/components/OnboardingFlow.tsx` -- Social login (Google/Apple/Email) as default option -- Wallet connect as secondary option -- 3-step flow: Choose Method → Pick Username → Complete -- Sub-90 second path to first transaction -- Progress bar and smooth animations - -### ✅ 2. @Username System -- **Files**: - - `backend/src/usernames/usernameRoutes.ts` - - `backend/src/usernames/usernameUtils.ts` - - `backend/src/usernames/index.ts` - - `backend/src/db/migrations/002_username_social_auth.sql` -- Username registry contract/table -- Resolve usernames to pubkeys via API -- Human-readable addresses: `runebolt.io/username` -- Validation and auto-generation - -### ✅ 3. User-Friendly Error Messages -- **File**: `frontend/components/ErrorMessage.tsx` -- 12+ error scenarios with friendly copy -- Actionable suggestions on every error -- Three display modes: toast, inline, modal -- Error boundary for React apps -- `mapErrorToType()` helper for automatic error classification - -### ✅ 4. Transaction Status Indicators -- **Files**: - - `frontend/components/TransactionStatus.tsx` - - `backend/src/ws/TransactionStatusHandler.ts` -- Pending → Confirming → Confirmed states -- Animated progress bars with time estimates -- Toast notifications -- WebSocket push notifications -- `useTransactionStatus()` React hook - -### ✅ 5. Claim Link System -- **File**: `frontend/components/ClaimLink.tsx` -- Generate shareable claim URLs -- QR codes for easy sharing -- No-account-needed claiming -- 7-day expiration -- Native share sheet integration - -### ✅ 6. Additional Enhancements -- **Social Login Backend**: `backend/src/api/auth.ts` -- **Updated Landing Page**: `frontend/app/page.tsx` -- **Database Schema**: Added transaction_status table - -## Files Created - -### Frontend Components (4) -1. `/frontend/components/OnboardingFlow.tsx` - 13KB -2. `/frontend/components/ClaimLink.tsx` - 14.7KB -3. `/frontend/components/ErrorMessage.tsx` - 14KB -4. `/frontend/components/TransactionStatus.tsx` - 8.9KB - -### Backend Components (4) -1. `/backend/src/usernames/usernameRoutes.ts` - 5.9KB -2. `/backend/src/usernames/usernameUtils.ts` - 3.8KB -3. `/backend/src/api/auth.ts` - 12.2KB -4. `/backend/src/ws/TransactionStatusHandler.ts` - 5.6KB - -### Configuration & Documentation (4) -1. `/backend/src/usernames/index.ts` - Module exports -2. `/backend/src/db/migrations/002_username_social_auth.sql` - DB migrations -3. `/backend/src/db/schema.sql` - Updated with transaction_status table -4. `/frontend/components/index.ts` - Component exports - -### Modified Files -1. `/backend/src/index.ts` - Added username routes -2. `/backend/src/db/Database.ts` - Added transaction status methods -3. `/frontend/app/page.tsx` - Redesigned landing page - -## API Endpoints Added - -### Username Routes -- `GET /api/v1/usernames/check/:username` - Check availability -- `GET /api/v1/usernames/:username` - Resolve username -- `GET /api/v1/usernames/resolve/:pubkey` - Get username for pubkey -- `POST /api/v1/usernames/register` - Register username (auth required) -- `GET /api/v1/usernames/suggest/:prefix?` - Generate suggestions - -### Auth Routes (Enhanced) -- `POST /api/v1/auth/social/initiate` - Start social login -- `POST /api/v1/auth/social/verify` - Verify social login -- `POST /api/v1/auth/wallet/challenge` - Wallet auth challenge -- `POST /api/v1/auth/wallet/verify` - Verify wallet signature -- `GET /api/v1/auth/me` - Get current user - -### WebSocket Events -- `subscribe_transactions` - Subscribe to tx updates -- `transaction_update` - Receive status updates -- `subscribed` - Subscription confirmation - -## Key Features - -### User Experience -- ✅ Sub-90 second onboarding -- ✅ No technical jargon -- ✅ Clear error messages with actions -- ✅ Real-time transaction status -- ✅ Shareable payment links -- ✅ Mobile-responsive design - -### Technical -- ✅ WebSocket real-time updates -- ✅ Username resolution API -- ✅ Social authentication -- ✅ QR code generation -- ✅ Comprehensive error handling -- ✅ TypeScript throughout - -## Testing Instructions - -```bash -# Install dependencies -cd /Users/gravity/projects/runebolt/frontend -npm install qrcode.react - -# Start backend -cd /Users/gravity/projects/runebolt/backend -npm run dev - -# Start frontend -cd /Users/gravity/projects/runebolt/frontend -npm run dev -``` - -## Next Steps - -1. Configure OAuth credentials in `.env`: - - `GOOGLE_CLIENT_ID` - - `APPLE_CLIENT_ID` - -2. Set up email service for magic links - -3. Configure Redis for distributed WebSocket - -4. Add API key for production - -5. Test all error scenarios - -6. Deploy and monitor - -## Documentation - -- `UX_IMPLEMENTATION_SUMMARY.md` - Full implementation details -- `INTEGRATION_GUIDE.md` - How to use the components -- Inline JSDoc comments throughout code - ---- - -**Implementation Date**: March 14, 2026 -**Total Files Modified**: 12 -**Total New Files**: 13 -**Lines of Code Added**: ~2,500+ diff --git a/legacy/taproot-assets-era/UX_ERROR_MESSAGES.md b/legacy/taproot-assets-era/UX_ERROR_MESSAGES.md deleted file mode 100644 index d40be0d..0000000 --- a/legacy/taproot-assets-era/UX_ERROR_MESSAGES.md +++ /dev/null @@ -1,389 +0,0 @@ -# RuneBolt User-Friendly Error Messages - -*Complete copy library for all error scenarios* - ---- - -## Error Message Principles - -### Voice and Tone -- **Friendly but not apologetic** — "Here's what happened" not "We're sorry" -- **Action-oriented** — Always provide a next step -- **Plain English** — No jargon, no technical terms -- **Reassuring** — When funds are safe, say so clearly - -### Format Template -``` -[Icon] -[Clear Headline] -[Explanation in plain language] -[Primary Action Button] -[Secondary Option (if applicable)] -``` - ---- - -## Connection Errors - -### Wallet Not Detected - -**Before:** -``` -Error: No wallet provider detected -``` - -**After:** -``` -┌─────────────────────────────────────┐ -│ │ -│ 🔌 │ -│ │ -│ Connect your wallet │ -│ │ -│ We need to connect to your │ -│ Bitcoin wallet to continue. │ -│ │ -│ [Connect Wallet] │ -│ │ -│ Don't have a wallet? │ -│ Create an account with email → │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -### Connection Rejected - -**Before:** -``` -User rejected connection request -``` - -**After:** -``` -┌─────────────────────────────────────┐ -│ │ -│ 🚫 │ -│ │ -│ Connection declined │ -│ │ -│ You declined the connection │ -│ in your wallet. That's okay! │ -│ │ -│ [Try Again] │ -│ │ -│ Or create an account with email │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -### Wallet Locked - -**Before:** -``` -Wallet locked or not authorized -``` - -**After:** -``` -┌─────────────────────────────────────┐ -│ │ -│ 🔒 │ -│ │ -│ Unlock your wallet │ -│ │ -│ Your wallet is locked. │ -│ Please unlock it and try again. │ -│ │ -│ [Open Wallet] │ -│ │ -│ Need help? Contact support │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -### Network Mismatch - -**Before:** -``` -Wrong network: expected mainnet -``` - -**After:** -``` -┌─────────────────────────────────────┐ -│ │ -│ 🌐 │ -│ │ -│ Switch to Bitcoin Mainnet │ -│ │ -│ Your wallet is on the wrong │ -│ network. Please switch to │ -│ Bitcoin Mainnet in your wallet │ -│ settings. │ -│ │ -│ [Open Wallet Settings] │ -│ │ -│ Need help switching networks? │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -## Transaction Errors - -### Insufficient Funds - -**Before:** -``` -Insufficient DOG balance -``` - -**After:** -``` -┌─────────────────────────────────────┐ -│ │ -│ 💸 │ -│ │ -│ Not enough DOG │ -│ │ -│ You need 1,500 more DOG │ -│ to complete this send. │ -│ │ -│ Your balance: 500 DOG │ -│ Amount to send: 2,000 DOG │ -│ │ -│ [Add DOG] │ -│ │ -│ Or send 500 DOG instead │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -### No Active Account (Channel Not Open) - -**Before:** -``` -No active channel found -``` - -**After:** -``` -┌─────────────────────────────────────┐ -│ │ -│ 🚀 │ -│ │ -│ Add DOG to start sending │ -│ │ -│ Your account needs DOG to send │ -│ instant payments. Add at least │ -│ 1,000 DOG to get started. │ -│ │ -│ [Add DOG Now] │ -│ │ -│ Why do I need to add DOG? → │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -### Transfer Failed (General) - -**Before:** -``` -Transfer failed: channel state error -``` - -**After:** -``` -┌─────────────────────────────────────┐ -│ │ -│ ⚠️ │ -│ │ -│ Something went wrong │ -│ │ -│ Don't worry — your DOG is safe │ -│ in your account. This sometimes │ -│ happens. Try again in a few │ -│ seconds. │ -│ │ -│ [Try Again] │ -│ │ -│ Still not working? Get help → │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -### Recipient Not Found - -**Before:** -``` -Recipient pubkey not found -``` - -**After:** -``` -┌─────────────────────────────────────┐ -│ │ -│ 🔍 │ -│ │ -│ We couldn't find @username │ -│ │ -│ Check the spelling or ask them │ -│ to join RuneBolt. │ -│ │ -│ [Search Again] │ -│ │ -│ Send a claim link instead → │ -│ │ -│ "Claim links let you send DOG │ -│ to anyone, even if they don't │ -│ have RuneBolt yet." │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -### Amount Too Small - -**Before:** -``` -Amount below dust limit -``` - -**After:** -``` -┌─────────────────────────────────────┐ -│ │ -│ 🪙 │ -│ │ -│ Amount too small │ -│ │ -│ The minimum send is 100 DOG. │ -│ Please enter a larger amount. │ -│ │ -│ [Update Amount] │ -│ │ -│ Why is there a minimum? → │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -## Bitcoin L1 Errors - -### Funding Transaction Pending - -**Before:** -``` -Funding transaction not confirmed -``` - -**After:** -``` -┌─────────────────────────────────────┐ -│ │ -│ ⏳ │ -│ │ -│ Your deposit is on the way! │ -│ │ -│ Bitcoin is processing your │ -│ deposit. It'll be ready in │ -│ about 10 minutes. │ -│ │ -│ [View on Mempool] │ -│ │ -│ Status: 0/1 confirmations │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -### Mempool Congestion - -**Before:** -``` -High fee environment -``` - -**After:** -``` -┌─────────────────────────────────────┐ -│ │ -│ 🐌 │ -│ │ -│ Bitcoin is busy right now │ -│ │ -│ The network is experiencing │ -│ high traffic. Your transaction │ -│ may take longer than usual. │ -│ │ -│ Estimated wait: 30-60 minutes │ -│ │ -│ [Speed Up (Higher Fee)] │ -│ │ -│ I'll wait for the normal fee │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -## API / System Errors - -### Service Unavailable - -**Before:** -``` -500 Internal Server Error -``` - -**After:** -``` -┌─────────────────────────────────────┐ -│ │ -│ 🔧 │ -│ │ -│ We're having trouble │ -│ │ -│ Something went wrong on our │ -│ end. Don't worry — your DOG │ -│ is safe. Please try again in │ -│ a few minutes. │ -│ │ -│ [Try Again] │ -│ │ -│ Status page: status.runebolt.io │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -## Implementation Notes - -### Priority Order -1. **P0:** All transaction errors (most frequent) -2. **P1:** Connection errors (onboarding critical) -3. **P2:** On-chain errors (less frequent) -4. **P3:** Edge cases (expired claims, etc.) - -### Key Principles Applied -- All technical terms replaced with plain English -- Every error provides a clear next action -- Reassurance when funds are safe -- Contextual help where needed \ No newline at end of file diff --git a/legacy/taproot-assets-era/UX_IMPLEMENTATION_SUMMARY.md b/legacy/taproot-assets-era/UX_IMPLEMENTATION_SUMMARY.md deleted file mode 100644 index 3fca9f1..0000000 --- a/legacy/taproot-assets-era/UX_IMPLEMENTATION_SUMMARY.md +++ /dev/null @@ -1,150 +0,0 @@ -# UX Improvements Implementation Summary - -## Changes Made - -### 1. Redesigned Onboarding Flow -**Files Created:** -- `/frontend/components/OnboardingFlow.tsx` - New 3-step onboarding (Method → Username → Complete) - -**Features:** -- Social login (Google/Apple/Email) as primary option -- Wallet connect as secondary option -- @username registration during onboarding -- Sub-90 second path to first transaction -- Progress bar visualization -- Animated transitions - -### 2. @Username System -**Files Created:** -- `/backend/src/usernames/usernameRoutes.ts` - Username API endpoints -- `/backend/src/usernames/usernameUtils.ts` - Username validation and generation -- `/backend/src/usernames/index.ts` - Module exports -- `/backend/src/db/migrations/002_username_social_auth.sql` - Database migrations - -**API Endpoints:** -- `GET /api/v1/usernames/check/:username` - Check availability -- `GET /api/v1/usernames/:username` - Resolve username to pubkey -- `GET /api/v1/usernames/resolve/:pubkey` - Get username for pubkey -- `POST /api/v1/usernames/register` - Register username (authenticated) -- `GET /api/v1/usernames/suggest/:prefix?` - Generate username suggestions - -**Features:** -- 3-20 character usernames (letters, numbers, underscores) -- Reserved username protection -- Auto-generated suggestions for new users -- Profile URLs: runebolt.io/username - -### 3. User-Friendly Error Messages -**Files Created:** -- `/frontend/components/ErrorMessage.tsx` - Error message component library - -**Features:** -- 12+ error scenarios with friendly copy -- Three display modes: toast, inline, modal/page -- Actionable suggestions on every error -- Technical error display for debugging (optional) -- Error boundary for React error catching - -**Error Types Covered:** -- Wallet connection errors -- Transaction failures -- Insufficient funds -- Recipient not found -- Network issues -- Service unavailable - -### 4. Transaction Status Indicators -**Files Created:** -- `/frontend/components/TransactionStatus.tsx` - Real-time status indicators -- `/backend/src/ws/TransactionStatusHandler.ts` - WebSocket push notifications - -**Features:** -- Three-state model: Pending → Confirming → Confirmed -- Animated progress bars with time estimates -- Toast notifications for transaction updates -- WebSocket-based push notifications -- React hook for managing transaction states - -### 5. Claim Link System -**Files Created:** -- `/frontend/components/ClaimLink.tsx` - Gift link generation and sharing - -**Features:** -- Generate shareable claim URLs -- QR code generation for easy mobile sharing -- No-account-needed claiming -- Amount and memo customization -- Native share sheet integration (mobile) -- Downloadable QR codes -- 7-day expiration - -### 6. Enhanced Social Login -**Files Created:** -- `/backend/src/api/auth.ts` - Enhanced auth with social providers - -**Features:** -- Google OAuth integration -- Apple Sign In support -- Email magic links -- Automatic username generation -- Social auth database storage - -### 7. Updated Landing Page -**File Modified:** -- `/frontend/app/page.tsx` - -**Changes:** -- New hero section with "Send DOG like a text" messaging -- Trust badge (non-custodial) -- Social proof elements -- Mobile app preview mockup -- Updated stats -- New feature grid with @usernames and gift links -- 90-second onboarding highlight - -### 8. Database Updates -**Files Modified:** -- `/backend/src/db/schema.sql` - Added transaction_status table -- `/backend/src/db/Database.ts` - Added transaction status methods - -**New Tables:** -- `transaction_status` - Real-time transaction tracking -- `username_registry` - Username to pubkey mapping -- `social_auth` - Social provider authentication - -### 9. Backend Integration -**Files Modified:** -- `/backend/src/index.ts` - Added username routes - -## Next Steps for Production - -1. **Environment Variables** - Set up OAuth credentials: - - `GOOGLE_CLIENT_ID` - - `APPLE_CLIENT_ID` - - `SOCIAL_AUTH_SECRET` - -2. **Email Service** - Configure magic link email provider - -3. **Redis Setup** - For distributed WebSocket pub/sub - -4. **QR Library** - Install `qrcode.react` package: - ```bash - npm install qrcode.react - ``` - -5. **SSL/HTTPS** - Required for WebSocket connections in production - -## Testing Checklist - -- [ ] Onboarding flow completes in < 90 seconds -- [ ] Social login works (Google/Apple) -- [ ] Username registration validates correctly -- [ ] Error messages show for all error scenarios -- [ ] Transaction status updates via WebSocket -- [ ] Claim links generate and can be shared -- [ ] QR codes scan correctly -- [ ] Mobile responsive design works - -## API Documentation - -See inline JSDoc comments in each backend file for detailed API documentation. diff --git a/legacy/taproot-assets-era/UX_JOURNEY_MAPS.md b/legacy/taproot-assets-era/UX_JOURNEY_MAPS.md deleted file mode 100644 index 42f08f8..0000000 --- a/legacy/taproot-assets-era/UX_JOURNEY_MAPS.md +++ /dev/null @@ -1,436 +0,0 @@ -# RuneBolt User Journey Maps - -*Detailed journey maps for key user personas* - ---- - -## Journey A: First-Time Consumer User - -**Persona:** Sarah, 28, discovers DOG at a dinner with friends -**Goal:** Send DOG to split a dinner bill -**Tech Comfort:** Uses Venmo, Cash App, but new to crypto - ---- - -### Stage 1: Discovery - -**Context:** At dinner, friend Mike pays with DOG via RuneBolt. Sarah is intrigued. - -**Touchpoints:** -- Sees Mike tap phone and instantly send DOG -- Hears: "It's like Venmo but for DOG. Just use RuneBolt." -- Mike shares: "My handle is @mike — just search for me" - -**Emotions:** Curious → Intrigued → Slightly skeptical - -**Pain Points:** None yet — positive social proof - -**Opportunities:** -- Word-of-mouth is powerful -- Social context reduces anxiety - ---- - -### Stage 2: Onboarding (Target: 90 seconds) - -**Touchpoint 2.1: Landing Page** -``` -Sarah opens runebolt.io on her phone -→ Sees clean, minimal design -→ Headline: "Send DOG instantly, anywhere" -→ Clear CTA: "Get Started - Free" -→ No overwhelming crypto jargon visible -``` -**Emotion:** Curious → Reassured by simplicity - -**Touchpoint 2.2: Account Creation** -``` -Taps "Get Started" -→ Sees: "Continue with Google / Apple / Email" -→ Chooses Google (familiar, fast) -→ Account created in 3 seconds -``` -**Emotion:** Relieved → This is easy - -**Touchpoint 2.3: Username Selection** -``` -Prompted to choose username -→ Types "sarah" → "Available!" -→ Tooltip: "This is how friends send you DOG" -→ Picks @sarah -``` -**Emotion:** Excited → This feels like Venmo - -**Touchpoint 2.4: First Deposit** -``` -Sees options: -→ [Buy DOG with Card] — "Hmm, not ready for that" -→ Or "Send DOG to: runebolt.io/sarah" -→ Copies address, switches to her wallet app -→ Sends 10,000 DOG (~$50) -→ Sees: "Your deposit is on the way! ~10 minutes" -``` -**Emotion:** Confident → I know how this works - -**Touchpoint 2.5: Success** -``` -Sees: "🎉 You're all set!" -→ [Send DOG to a friend] [Explore] -→ Taps "Send to friend" -``` -**Emotion:** Ready → Let's do this - -**Total Time:** ~90 seconds -**Steps:** 5 (but feels like 3) - ---- - -### Stage 3: First Send - -**Touchpoint 3.1: Send Screen** -``` -Search bar: "Who are you sending to?" -→ Types "mike" -→ Sees @mike with profile picture -→ Taps to select -``` -**Emotion:** Familiar → Just like Venmo - -**Touchpoint 3.2: Amount Entry** -``` -Amount input with numeric keypad -→ Enters 2,500 DOG -→ Sees "$12.50" equivalent below -→ Memo field: "🍕 Dinner split" -``` -**Emotion:** Confident → Clear what I'm sending - -**Touchpoint 3.3: Confirmation** -``` -Review screen: -→ "Send 2,500 DOG ($12.50) to @mike?" -→ Shows memo, confirms details -→ [Send] button prominent -→ Taps Send -``` -**Emotion:** Certain → Double-check feels safe - -**Touchpoint 3.4: Instant Confirmation** -``` -Animation: Sending → Sent! -→ "Mike received 2,500 DOG!" -→ Confetti animation -→ "🍕 Dinner split" shown -→ Back to home with updated balance -``` -**Emotion:** Delighted → That was FAST! - -**Total Time:** ~30 seconds - ---- - -### Stage 4: Regular Use - -**Week 1-2: Exploration** -- Opens app to check balance -- Sends DOG to 2-3 more friends -- Receives DOG from Mike -- Discovers transaction history - -**Week 3-4: Habits Form** -- Uses RuneBolt as default for DOG -- Has 5-10 regular contacts -- Understands "instant" means no waiting -- Shares runebolt.io/sarah on social - -**Touchpoints:** -- Push notification: "You received 1,000 DOG from @alice!" -- Home screen shows recent contacts -- Quick-send from notification -- Balance always visible but not overwhelming - -**Emotion:** Comfortable → This is my default - ---- - -### Stage 5: Advocacy - -**Month 2+:** -- Invites friends via referral code -- Shares RuneBolt handle on Twitter bio -- Suggests merchants accept RuneBolt -- Participates in community Discord - -**Why She Advocates:** -- It just works — no explaining channels -- Her friends can use it easily -- She feels "in the know" about DOG -- Social status from early adoption - ---- - -## Journey B: Merchant Acceptance - -**Persona:** Juan, owns coffee shop, tech-curious -**Goal:** Accept DOG payments easily -**Tech Comfort:** Uses Square, comfortable with apps - ---- - -### Stage 1: Awareness - -**Context:** Regular customer asks "Do you take DOG?" - -**Touchpoints:** -- Customer explains DOG is like Bitcoin but fun -- Customer shows RuneBolt app -- Juan intrigued by instant settlement - -**Emotions:** Curious → Open to trying - ---- - -### Stage 2: Setup (Target: 2 minutes) - -**Touchpoint 2.1: Business Account** -``` -Opens runebolt.io -→ Selects "Business Account" -→ Enters: @juanzcoffee -→ Adds business info -``` - -**Touchpoint 2.2: Payment Link Generated** -``` -Sees: runebolt.io/juanzcoffee -→ QR code generated -→ Options: Print, Save to Photos, Display on tablet -``` - -**Touchpoint 2.3: First Configuration** -``` -Sets: -→ Minimum payment: 500 DOG -→ Auto-convert to USD: Off (for now) -→ Settlement wallet: [his Unisat] -``` - ---- - -### Stage 3: First Payment - -**Touchpoint 3.1: Customer Pays** -``` -Customer scans QR at register -→ Sends 2,500 DOG -→ Juan's tablet shows: "Payment received!" -→ Amount: 2,500 DOG ($12.50) -→ Instant confirmation -``` - -**Touchpoint 3.2: Receipt** -``` -Customer sees: "Paid @juanzcoffee" -→ Optional: Add receipt to email -→ Juan sees transaction in dashboard -``` - ---- - -### Stage 4: Daily Operations - -**Daily Workflow:** -- QR code displayed at register -- Transactions appear on dashboard -- End of day: review sales -- Weekly: withdraw to main wallet - -**Key Features Used:** -- Transaction export for accounting -- Daily settlement summary -- Inventory of DOG holdings -- Customer analytics (repeat vs new) - ---- - -### Stage 5: Scale - -**Month 2+:** -- 10-20% of customers pay with DOG -- Regular DOG community visits -- Featured in local "Bitcoin accepted here" lists -- Considering keeping some DOG as investment - ---- - -## Journey C: Existing Bitcoin User - -**Persona:** Alex, Bitcoiner since 2017, frustrated with Lightning -**Goal:** Send DOG easily without channel management -**Tech Comfort:** High — runs own node - ---- - -### Stage 1: Discovery - -**Context:** Frustrated with Lightning liquidity issues - -**Touchpoints:** -- Tweet about Lightning UX problems -- Reply mentions RuneBolt "just works" -- Skeptical but intrigued - -**Emotions:** Frustrated → Skeptical → Curious - ---- - -### Stage 2: Migration - -**Touchpoint 2.1: Connect Wallet** -``` -Opens RuneBolt -→ Selects "Connect Existing Wallet" -→ Chooses Unisat -→ Signs authentication message -→ Account linked instantly -``` - -**Touchpoint 2.2: Channel Opening** -``` -Prompted to "Activate your account" -→ Sees: "Deposit DOG to enable instant sends" -→ Understands this opens channel -→ Deposits 50,000 DOG -→ Waits for Bitcoin confirmation -``` - -**Touchpoint 2.3: First Transfer** -``` -Sends DOG to friend -→ Instant confirmation -→ No routing issues -→ No liquidity worries -``` - -**Emotion:** Impressed → Why isn't all crypto this easy? - ---- - -### Stage 3: Parallel Use - -**Usage Pattern:** -- Main wallet: Cold storage, large amounts -- RuneBolt: Daily spending, transfers -- Transfers between them as needed - -**Appreciates:** -- Speed vs main wallet -- No channel management -- Can always receive (no inbound liquidity issues) - ---- - -### Stage 4: Full Switch - -**Month 2+:** -- Sets up auto-forwarding from main wallet -- Gives out RuneBolt address for all DOG receives -- Only touches main wallet for large cold storage -- Recommends to other Bitcoiners - -**Why:** -- "It just works" — the highest praise -- No mental overhead -- Bitcoin security with app convenience - ---- - -## Journey D: Claim Link Recipient - -**Persona:** Emma, receives DOG via claim link, no prior crypto -**Goal:** Claim her DOG without setting up complex wallets -**Tech Comfort:** Low — uses apps but no crypto experience - ---- - -### Stage 1: Receiving Link - -**Context:** Friend sends link via text: "runebolt.io/claim/abc123" - -**Touchpoints:** -- Opens link on phone -- Sees: "🎁 You received 5,000 DOG!" -- Amount shown in USD: "~$25" -- "Claim in 30 seconds" - -**Emotion:** Surprised → Curious - ---- - -### Stage 2: Instant Claim - -**Touchpoint 2.1: Quick Setup** -``` -[Claim Your DOG] -→ "Choose your username" (for receiving future sends) -→ @emma selected -→ Optional: Add email for notifications -``` - -**Touchpoint 2.2: Wallet Options** -``` -"How would you like to store your DOG?" -→ [Simple: Keep in RuneBolt] ← Recommended -→ [Advanced: Send to my wallet] -``` - -**Touchpoint 2.3: Success** -``` -"🎉 5,000 DOG claimed!" -→ Balance: 5,000 DOG -→ "You can now send to anyone with @username" -→ [Send DOG] [Learn More] -``` - -**Total Time:** 45 seconds -**Emotion:** Delighted → That was surprisingly easy - ---- - -### Stage 3: First Experience - -**Immediate Actions:** -- Explores the app -- May send some DOG back to friend -- Probably keeps most in RuneBolt - -**Retention Factors:** -- Easy to use -- Can "cash out" to main wallet later -- Friends are on the platform - ---- - -## Key Insights Across All Journeys - -### Universal Friction Points -1. **Channel/liquidity concepts** — Must be hidden -2. **Address complexity** — Use usernames only -3. **Waiting for confirmations** — Set expectations clearly -4. **Recovery phrase anxiety** — Offer social recovery options - -### Universal Delight Factors -1. **Speed** — "Instant" is magical -2. **Simplicity** — Feels like familiar apps -3. **Social** — Username search, memos -4. **Success moments** — Confetti, clear confirmations - -### Conversion Optimization -- **90-second onboarding** — Critical threshold -- **First send within 2 minutes** — Retention correlates -- **Receive capability immediately** — Feel part of network -- **Social proof** — Show friends already using it - ---- - -*Maps created following Karpathy approach: user research → hypothesis → journey mapping* diff --git a/legacy/taproot-assets-era/UX_MASS_ADOPTION.md b/legacy/taproot-assets-era/UX_MASS_ADOPTION.md deleted file mode 100644 index 9763432..0000000 --- a/legacy/taproot-assets-era/UX_MASS_ADOPTION.md +++ /dev/null @@ -1,271 +0,0 @@ -# RuneBolt UX & Mass Adoption Strategy - -*Transforming RuneBolt from a developer tool into a consumer-ready product* - ---- - -## Executive Summary - -RuneBolt is positioned as "Lightning Network for Runes" — a hub-based channel system for instant DOG transfers. This document provides a comprehensive UX transformation strategy. - ---- - -## 1. The Mass Adoption Problem - -### Why Lightning Network Hasn't Gone Mainstream - -| Barrier | Technical Reality | User Experience | -|---------|------------------|-----------------| -| **Channel Management** | Users must open/close channels | "What is a channel?" | -| **Inbound Liquidity** | Need incoming capacity | "Why can't I receive money?" | -| **Path Finding** | Complex routing | "Payment failed - no route found" | -| **Recovery** | Channel state backups | Lost funds due to backup failures | -| **Terminology** | Satoshis, HTLCs | "I just want to send money" | - -### What Successful Apps Get Right - -**Phantom Wallet (15M+ MAU):** -- 4-step signup process (< 1 minute) -- Human-readable usernames instead of addresses -- Social login options alongside seed phrase -- Clean, minimalistic design - -**Cash App (50M+ users):** -- Bold, personality-driven UI -- "You don't need onboarding videos, just a thumb and curiosity" -- Actions streamlined while personality retained - -**Venmo (80M+ users):** -- Social feed makes payments feel natural -- Username search (not account numbers) -- Payment memos humanize transactions - ---- - -## 2. The RuneBolt UX Transformation - -### Mental Model Shift - -**Current (Developer-Focused):** -``` -User → Opens Channel → Manages Liquidity → Sends → Closes Channel -``` - -**Target (Consumer-Focused):** -``` -User → Deposits DOG → Sends to Anyone Instantly → Done -``` - -### Core UX Principles - -1. **Hide the Channel** — Implementation detail, not user-facing -2. **Human Names** — `@username` instead of pubkeys -3. **Instant Feedback** — Every action has immediate visual confirmation -4. **No Crypto Jargon** — Everyday language only -5. **Mobile-First** — Design for thumbs -6. **Progressive Disclosure** — Simple by default, powerful when needed - ---- - -## 3. Onboarding Flow Redesign - -### Proposed State -``` -Landing → Create Account → Add DOG → Start Sending -``` -*Goal: 3 steps, under 90 seconds to first transaction* - -### Onboarding Checklist - -| Requirement | Priority | Implementation | -|-------------|----------|----------------| -| Sub-90 second path to first transaction | P0 | Remove all optional steps | -| Social login (Google/Apple/Email) | P0 | Privy or Magic Link | -| Bitcoin wallet connect | P0 | Unisat, Xverse, Leather | -| Username-based addressing | P0 | RuneBolt DNS | -| Buy DOG with card | P1 | MoonPay/Transak | -| Skip deposit option | P1 | Allow exploration | - ---- - -## 4. User-Friendly Error Messages - -### Principles -1. Explain in plain English -2. Provide next steps -3. Use friendly tone -4. Visual clarity (icon + heading + explanation + action) - -### Error Message Library - -| Scenario | Before | After | -|----------|--------|-------| -| Wallet not connected | "No wallet provider detected" | "Connect your wallet to continue" | -| Insufficient funds | "Insufficient DOG balance" | "You need 1,500 more DOG. Add funds or reduce the amount." | -| Channel not open | "No active channel found" | "Your account needs DOG to send. Add at least 1,000 DOG to get started." | -| Recipient not found | "Recipient pubkey not found" | "We couldn't find @username. Check the spelling or ask them to join RuneBolt." | - ---- - -## 5. Transaction Status Visibility - -### Three-State Model - -| State | Visual | User Message | -|-------|--------|--------------| -| **Sending** | Animated spinner | "Sending to @mike..." | -| **Sent** | Green checkmark | "Sent! @mike received 1,000 DOG" | -| **Received** | Confetti animation | "You received 1,000 DOG from @sarah!" | - ---- - -## 6. Trust-Building UI Elements - -### Security Badges - -| Badge | Placement | Purpose | -|-------|-----------|---------| -| 🔒 Non-Custodial | Footer, settings | Reassures users they control funds | -| ✅ Open Source | About page | Transparency builds trust | -| 🛡️ Audited | Security page | Third-party validation | -| ⚡ Instant | Send/receive screens | Highlights key benefit | - -### Trust Signals to Implement - -1. **Balance Visibility** - - Show DOG balance prominently - - Show USD equivalent (toggleable) - - "Your DOG, your control" microcopy - -2. **Transaction Confirmations** - - "Sent instantly via RuneBolt" on success - - "Secured by Bitcoin" in footer - - "Non-custodial: only you control your keys" - -3. **Educational Tooltips** - - "What is RuneBolt?" explainer - - "How is this instant?" (brief channel explanation) - - "Is my DOG safe?" security overview - ---- - -## 7. Mobile-First Design - -### Key Mobile UX Principles - -1. **Thumb Zones** - - Primary actions in bottom 25% of screen - - Balance and key info in top 50% - - Navigation reachable with one hand - -2. **Touch Targets** - - Minimum 44px touch targets - - Generous spacing between buttons - - Swipe gestures for common actions - -3. **Quick Actions** - - Send/Receive as primary FABs - - Recent contacts on home screen - - Pull-to-refresh for balance - ---- - -## 8. Social Features - -### Contacts System - -``` -┌─────────────────────────────────────┐ -│ Send DOG │ -│ │ -│ [Search @username or name ] │ -│ │ -│ Recent │ -│ ┌────┐ ┌────┐ ┌────┐ │ -│ │ 🧔 │ │ 👩 │ │ 🐶 │ │ -│ │Mike│ │Amy │ │DOG │ │ -│ └────┘ └────┘ └────┘ │ -│ │ -│ Suggestions │ -│ [+] Import from Contacts │ -│ │ -└─────────────────────────────────────┘ -``` - -### Transaction Memos - -- Emoji support in memos -- Preset memo templates ("🍕 Lunch", "🏠 Rent", "💝 Gift") -- Private memos (only sender/receiver see) - -### Shareable Links - -| Link Type | Format | Use Case | -|-----------|--------|----------| -| Profile | runebolt.io/username | Share to receive | -| Payment Request | runebolt.io/pay/username?amount=1000 | Request specific amount | -| Claim Link | runebolt.io/claim/abc123 | Send to non-users | - ---- - -## 9. Implementation Roadmap - -### Phase 1: Foundation (Weeks 1-4) -- [ ] Implement social login (Privy/Magic) -- [ ] Build username system -- [ ] Redesign onboarding flow -- [ ] Rewrite all error messages - -### Phase 2: Polish (Weeks 5-8) -- [ ] Mobile UI overhaul -- [ ] Transaction status redesign -- [ ] Add trust badges and education -- [ ] Implement contacts system - -### Phase 3: Growth (Weeks 9-12) -- [ ] Shareable payment links -- [ ] Claim links for non-users -- [ ] Referral program -- [ ] Merchant tools - ---- - -## 10. Success Metrics - -| Metric | Current | Target | Measurement | -|--------|---------|--------|-------------| -| Time to first transaction | ~5 min | <90 sec | Analytics funnel | -| Onboarding completion | Unknown | >70% | Signup analytics | -| User error rate | Unknown | <5% | Error tracking | -| Support tickets | Unknown | -50% | Support system | -| NPS score | Unknown | >50 | In-app survey | -| DAU/MAU ratio | Unknown | >30% | Engagement tracking | - ---- - -## Research Summary - -### Why Phantom Succeeded -1. Started with Solana (fast, cheap) — reduced complexity -2. Social login reduced friction for new users -3. Human-readable names eliminated address anxiety -4. Clean UI hid blockchain complexity -5. Built for non-technical users first - -### Why Lightning Struggles -1. Channel management is too technical for average users -2. Inbound liquidity confusion -3. "No route found" errors with no clear resolution -4. Recovery is scary and complex -5. Terminology barrier (satoshis, nodes, invoices) - -### What Cash App Proves -1. Personality + simplicity wins Gen Z -2. You don't need to explain how it works -3. Bold, confident design reduces anxiety -4. Actions should be faster than explanations - ---- - -*Document created: March 14, 2026* -*Approach: User research → Hypothesis → Prototype → Test → Iterate* diff --git a/legacy/taproot-assets-era/UX_ONBOARDING_GUIDE.md b/legacy/taproot-assets-era/UX_ONBOARDING_GUIDE.md deleted file mode 100644 index 629b3a0..0000000 --- a/legacy/taproot-assets-era/UX_ONBOARDING_GUIDE.md +++ /dev/null @@ -1,530 +0,0 @@ -# RuneBolt Onboarding Checklist & Tutorial Content - -*Complete implementation guide for user onboarding* - ---- - -## Onboarding Implementation Checklist - -### Phase 1: Critical Path (P0) - -#### Account Creation -- [ ] Social login integration (Google OAuth) -- [ ] Social login integration (Apple Sign-In) -- [ ] Email/password with Magic Link -- [ ] Bitcoin wallet connect (Unisat) -- [ ] Bitcoin wallet connect (Xverse) -- [ ] Bitcoin wallet connect (Leather) -- [ ] Wallet detection and auto-prompt -- [ ] Fallback when no wallet detected - -#### Username System -- [ ] Username availability check API -- [ ] Real-time validation (as-you-type) -- [ ] Reserved username list (admin, support, etc.) -- [ ] Minimum length: 3 characters -- [ ] Maximum length: 20 characters -- [ ] Allowed characters: a-z, 0-9, underscore, hyphen -- [ ] Case-insensitive storage, lowercase display -- [ ] Username change policy (limited free changes) - -#### Core Flow -- [ ] Sub-90 second path to first transaction -- [ ] Progress indicator (Step 1 of 3) -- [ ] Skip deposit option for exploration -- [ ] No mandatory email verification for basic use -- [ ] Persistent session (stay logged in) -- [ ] Biometric auth option (Face ID / Touch ID) - -### Phase 2: Funding & Activation (P1) - -#### Deposit Options -- [ ] Simple address display (runebolt.io/username) -- [ ] QR code generation -- [ ] Copy to clipboard with feedback -- [ ] Share sheet integration -- [ ] Minimum deposit enforcement (1,000 DOG) -- [ ] Deposit status tracking -- [ ] Push notification on deposit arrival - -#### Fiat On-Ramp -- [ ] MoonPay integration -- [ ] Transak integration -- [ ] KYC flow for card purchases -- [ ] Purchase limits clearly displayed -- [ ] Fee transparency upfront -- [ ] Support for major currencies (USD, EUR, GBP) - -#### Channel Activation -- [ ] Auto-open channel on first deposit -- [ ] Hide channel details from user -- [ ] Show "activating" state during setup -- [ ] Clear "ready to send" confirmation - -### Phase 3: Polish (P2) - -#### Education -- [ ] Tooltip system for key concepts -- [ ] Contextual help buttons -- [ ] Video tutorial library (optional) -- [ ] FAQ section accessible from onboarding - -#### Social Features -- [ ] Contact import (optional) -- [ ] Find friends on RuneBolt -- [ ] Referral code system -- [ ] Share referral link - -#### Trust Signals -- [ ] Security badge display -- [ ] Non-custodial explanation -- [ ] Open source link -- [ ] Audit information (when available) - ---- - -## Tutorial Content Library - -### Welcome Modal (First Open) - -``` -┌─────────────────────────────────────┐ -│ │ -│ ⚡ │ -│ │ -│ Welcome to RuneBolt! │ -│ │ -│ Send DOG instantly to anyone, │ -│ anywhere. No fees, no waiting. │ -│ │ -│ [Get Started - Free] │ -│ │ -│ Takes 60 seconds │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -### Username Selection Tooltip - -``` -┌─────────────────────────────────────┐ -│ │ -│ Choose your RuneBolt name │ -│ │ -│ @satoshi │ -│ ✅ Available! │ -│ │ -│ ┌───────────────────────────┐ │ -│ │ 💡 This is like a handle │ │ -│ │ on social media. │ │ -│ │ │ │ -│ │ Friends can send you │ │ -│ │ DOG using just your │ │ -│ │ username — no long │ │ -│ │ addresses needed! │ │ -│ └───────────────────────────┘ │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -### First Deposit Education - -``` -┌─────────────────────────────────────┐ -│ │ -│ Add DOG to your account │ -│ │ -│ Your address: │ -│ runebolt.io/satoshi │ -│ [Copy] │ -│ │ -│ ┌───────────────────────────┐ │ -│ │ 💡 How this works: │ │ -│ │ │ │ -│ │ 1. Send DOG to your │ │ -│ │ address above │ │ -│ │ │ │ -│ │ 2. It arrives in ~10 │ │ -│ │ minutes │ │ -│ │ │ │ -│ │ 3. Then you can send │ │ -│ │ instantly! │ │ -│ └───────────────────────────┘ │ -│ │ -│ Minimum: 1,000 DOG │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -### First Send Tutorial (Overlay) - -``` -┌─────────────────────────────────────┐ -│ ╔═══════════════════════════════╗ │ -│ ║ 👆 Tap here to search for ║ │ -│ ║ friends by username ║ │ -│ ║ ║ │ -│ ║ Try "@mike" or "@sarah" ║ │ -│ ╚═══════════════════════════════╝ │ -│ │ -│ [Search @username or name ] │ -│ │ -│ Recent │ -│ [No recent contacts yet] │ -│ │ -│ [Skip Tutorial] │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -### Send Confirmation Tutorial - -``` -┌─────────────────────────────────────┐ -│ │ -│ Send 1,000 DOG to @mike? │ -│ │ -│ 🍕 Dinner split │ -│ │ -│ ┌───────────────────────────┐ │ -│ │ 💡 What happens next: │ │ -│ │ │ │ -│ │ • Mike receives DOG │ │ -│ │ instantly │ │ -│ │ │ │ -│ │ • No fees, no waiting │ │ -│ │ │ │ -│ │ • You can see it in your │ │ -│ │ history anytime │ │ -│ └───────────────────────────┘ │ -│ │ -│ [Send Instantly] │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -### Success Celebration - -``` -┌─────────────────────────────────────┐ -│ │ -│ 🎉 │ -│ │ -│ Sent! │ -│ │ -│ @mike received │ -│ 1,000 DOG │ -│ instantly │ -│ │ -│ 🍕 Dinner split │ -│ │ -│ ┌───────────────────────────┐ │ -│ │ 💡 That's it! You just │ │ -│ │ sent DOG faster than │ │ -│ │ a bank transfer. │ │ -│ │ │ │ -│ │ Try receiving next: │ │ -│ │ Share runebolt.io/ │ │ -│ │ [your-username] │ │ -│ └───────────────────────────┘ │ -│ │ -│ [Send More] [Share My Link] │ -│ │ -└─────────────────────────────────────┘ -``` - ---- - -## Contextual Tooltips - -### What is RuneBolt? - -``` -💡 RuneBolt lets you send DOG (a Bitcoin token) instantly -to anyone with a username — no complex addresses, -no waiting for confirmations. - -Think Venmo, but for DOG on Bitcoin. -``` - ---- - -### Is My DOG Safe? - -``` -🔒 Yes! RuneBolt is non-custodial, which means: - -• Only YOU control your DOG -• We can't freeze or take your funds -• You can withdraw anytime to any wallet - -Your DOG is secured by Bitcoin's technology. -``` - ---- - -### Why Do I Need to Add DOG First? - -``` -💡 To enable instant sends, we create a "channel" -with your DOG. This is like loading a prepaid card. - -• Your DOG stays in your control -• You can withdraw anytime -• Minimum 1,000 DOG to start - -Without this, you'd wait 10+ minutes per send! -``` - ---- - -### What's the Difference From Regular Bitcoin? - -``` -💡 Regular Bitcoin = slow (10+ min) but works everywhere -RuneBolt = instant but requires both users to have it - -Use RuneBolt when: -• Sending to friends on RuneBolt -• Need instant confirmation -• Small to medium amounts - -Use regular Bitcoin when: -• Sending to any Bitcoin address -• Large amounts -• Don't need instant confirmation -``` - ---- - -### Claim Links Explained - -``` -💡 A claim link lets you send DOG to anyone — -even if they don't have RuneBolt yet! - -They click the link → create account in 30 seconds -→ DOG appears in their wallet - -Great for introducing friends to DOG! -``` - ---- - -## Progressive Disclosure Strategy - -### Beginner Mode (Default) -- Show only essential features -- Hide advanced options -- Use simple terminology -- Show educational tooltips - -### Intermediate Mode (After 5+ transactions) -- Reveal transaction details -- Show fee breakdowns -- Enable advanced settings option -- Reduce tooltip frequency - -### Advanced Mode (User-activated) -- Show channel details -- Enable custom fee selection -- Reveal raw transaction data -- Export functionality - ---- - -## User Onboarding Email Sequence - -### Email 1: Welcome (Immediate) - -**Subject:** Welcome to RuneBolt! Here's how to get started - -``` -Hi [Username], - -Welcome to RuneBolt! You're now part of the instant -DOG payment revolution. - -Your RuneBolt address: runebolt.io/[username] - -Share this with friends so they can send you DOG! - -What's next? -1. Add DOG to your account -2. Send your first payment -3. Invite friends (earn rewards!) - -[Add DOG Now] - -Questions? Reply to this email — we're here to help! - -The RuneBolt Team -``` - ---- - -### Email 2: First Send Tips (Day 2) - -**Subject:** Pro tips for sending DOG instantly - -``` -Hi [Username], - -You've got DOG in your account — awesome! - -Here are some tips for your first send: - -✅ Just search @username (no addresses needed!) -✅ Add a memo so they know what it's for -✅ Claim links work for anyone, even non-users - -Try sending DOG to a friend today! - -[Open RuneBolt] - -Cheers, -The RuneBolt Team -``` - ---- - -### Email 3: Security Check (Day 7) - -**Subject:** Keep your DOG safe — quick security tips - -``` -Hi [Username], - -Your DOG is valuable! Here's how to keep it safe: - -🔒 If you created an email account: - • Use a strong, unique password - • Enable 2FA in settings - -🔐 If you connected a wallet: - • Keep your seed phrase safe - • Never share your private key - -🛡️ General tips: - • Verify usernames before sending - • Check URLs (runebolt.io only!) - -[Review Security Settings] - -Stay safe! -The RuneBolt Team -``` - ---- - -### Email 4: Invite Friends (Day 14) - -**Subject:** Invite friends, earn DOG - -``` -Hi [Username], - -Love using RuneBolt? Invite your friends! - -For each friend who joins and sends their first -payment, you both get 500 DOG. - -Your referral link: -runebolt.io/invite/[code] - -Share it anywhere: -• Twitter/X -• WhatsApp -• Email - -[Share Now] - -Thanks for spreading the word! -The RuneBolt Team -``` - ---- - -## In-App Help System - -### Help Button Placement -- Always visible in header (question mark icon) -- Contextual help on every screen -- Shake to report issue (mobile) - -### Help Categories - -#### Getting Started -- How do I create an account? -- How do I add DOG? -- How do I send DOG? -- How do I receive DOG? - -#### Troubleshooting -- My deposit hasn't arrived -- Transaction failed -- Can't connect wallet -- Forgot password - -#### Security -- Is RuneBolt safe? -- How do I back up my account? -- What if I lose access? -- How to report suspicious activity - -#### Advanced -- How do channels work? -- Can I export my transactions? -- How do fees work? -- API documentation - ---- - -## Success Metrics for Onboarding - -| Metric | Target | Measurement | -|--------|--------|-------------| -| Onboarding completion rate | >70% | % who finish signup | -| Time to first transaction | <90 sec | Analytics funnel | -| Email verification rate | >60% | Email events | -| Deposit completion rate | >50% | % who fund account | -| First send within 24h | >40% | Transaction data | -| Support tickets during onboarding | <5% | Support system | -| User error rate | <10% | Error tracking | -| NPS after first week | >40 | In-app survey | - ---- - -## A/B Testing Ideas - -### Onboarding Flow -- Social login first vs wallet connect first -- Username selection: before vs after deposit -- Progress indicator: steps vs percentage -- Skip deposit: available vs not available - -### Copy Variations -- "Get Started - Free" vs "Create Account" -- "Add DOG" vs "Deposit Funds" -- "Channel" vs "Payment Account" -- Technical vs friendly tone - -### Visual Design -- Light mode vs dark mode default -- Animation complexity -- Button placement -- Success celebration style - ---- - -*Checklist created for RuneBolt UX Mass Adoption initiative* \ No newline at end of file diff --git a/legacy/taproot-assets-era/UX_TRUST_RESEARCH.md b/legacy/taproot-assets-era/UX_TRUST_RESEARCH.md deleted file mode 100644 index 6b79c52..0000000 --- a/legacy/taproot-assets-era/UX_TRUST_RESEARCH.md +++ /dev/null @@ -1,152 +0,0 @@ -# RuneBolt Trust-Building UI Elements & Research Summary - -*Trust signals, security badges, and competitive UX analysis* - ---- - -## Trust-Building UI Elements - -### Core Trust Principles - -1. **Transparency** — Show how things work, don't hide behind complexity -2. **Control** — Users must feel they own their funds -3. **Security** — Reassurance without fear-mongering -4. **Reliability** — Consistent experience builds confidence -5. **Community** — Social proof from real users - ---- - -## Security Badges & Trust Signals - -### Badge Library - -| Badge | Placement | Hover Text | Destination | -|-------|-----------|------------|-------------| -| 🔒 Non-Custodial | Footer, settings | "Only you control your keys" | /security | -| ✅ Open Source | About, footer | "Our code is public" | GitHub | -| 🛡️ Audited | Security page | "Reviewed by [firm]" | Audit report | -| ⚡ Instant | Home, send | "Powered by payment channels" | /how-it-works | -| 🔐 Encrypted | Settings | "End-to-end encrypted" | Encryption details | - ---- - -## Competitive Research Summary - -### Phantom Wallet (15M+ MAU) -**Success Factors:** -- 4-step signup (<1 min) -- Social login options -- @username system (no addresses) -- Clean, minimal design -- Transaction previews (Blowfish) - -**Key Lesson:** Hide ALL blockchain complexity - -### Cash App (50M+ users) -**Success Factors:** -- Bold personality (distinctive green) -- Actions faster than explanations -- $Cashtag system -- No onboarding videos needed -- Gen Z appeal - -**Key Lesson:** Personality + simplicity wins - -### Venmo (80M+ users) -**Success Factors:** -- Social feed (payments feel natural) -- Username search -- Payment memos + emojis -- Public/social aspect - -**Key Lesson:** Social features drive engagement - -### Strike -**Success Factors:** -- Users don't know they're using Lightning -- "Send cash, receive cash" -- Simple on/off ramps -- Bitcoin abstraction layer - -**Key Lesson:** Abstract complexity completely - ---- - -## Why Lightning Network Struggles - -| Barrier | User Impact | -|---------|-------------| -| Channel management | "What is a channel?" | -| Inbound liquidity | Can't receive without setup | -| Path finding | "No route found" errors | -| Recovery | Lost funds = panic | -| Terminology | Too technical for normies | - -**Lightning Capacity:** ~5,000 BTC after 7 years -**Problem:** UX complexity, not tech - ---- - -## RuneBolt Differentiation - -### What RuneBolt Should Copy -1. Phantom's username system → Eliminate address anxiety -2. Cash App's personality → Bold, confident design -3. Venmo's social features → Payment memos, contacts -4. Strike's abstraction → Hide channel complexity - -### What RuneBolt Should Avoid -1. Lightning's channel management → Hide it completely -2. Technical terminology → No "channels," "HTLCs," etc. -3. Complexity reveals → Progressive disclosure only -4. Recovery anxiety → Social recovery options - ---- - -## Trust Signals to Implement - -### Immediate (P0) -- Non-custodial badge on all screens -- "Your DOG, your control" messaging -- Transaction security indicators -- Clear fee transparency (ideally: no fees) - -### Short-term (P1) -- Open source link in footer -- Security audit badge (when ready) -- Educational tooltips -- Help system with quick answers - -### Long-term (P2) -- Bug bounty program -- Insurance/FDIC-like messaging -- Community trust score -- Third-party verification - ---- - -## UX Hypothesis for Testing - -### Hypothesis 1: Hiding Channels Increases Adoption -**Test:** Compare onboarding with/without channel mentions -**Metric:** Completion rate, time to first send -**Expected:** Hidden channels = +30% completion - -### Hypothesis 2: Usernames vs Addresses -**Test:** A/B test username-first vs address-first flows -**Metric:** Send success rate, user confidence -**Expected:** Usernames = +50% send completion - -### Hypothesis 3: Friendly Error Messages -**Test:** Technical vs friendly error copy -**Metric:** Retry rate, support tickets -**Expected:** Friendly = +40% retry, -50% tickets - -### Hypothesis 4: Trust Badges Reduce Anxiety -**Test:** Show/hide security badges prominently -**Metric:** Deposit completion, NPS -**Expected:** Badges = +20% deposit rate - ---- - -*Research compiled from Phantom, Cash App, Venmo, Strike, and Lightning Network UX analysis* \ No newline at end of file diff --git a/legacy/taproot-assets-era/backend/.env.example b/legacy/taproot-assets-era/backend/.env.example deleted file mode 100644 index 52a8a26..0000000 --- a/legacy/taproot-assets-era/backend/.env.example +++ /dev/null @@ -1,41 +0,0 @@ -# RuneBolt Backend Environment Configuration -# Copy this file to .env and fill in your values - -# Server -PORT=3001 -NODE_ENV=development - -# PostgreSQL Database -DATABASE_URL=postgresql://runebolt:runebolt@localhost:5432/runebolt -DB_POOL_MAX=50 -DB_POOL_MIN=10 -DB_IDLE_TIMEOUT=30000 -DB_CONNECTION_TIMEOUT=5000 -DB_STATEMENT_TIMEOUT=10000 - -# Redis Cache -REDIS_HOST=localhost -REDIS_PORT=6379 -REDIS_PASSWORD= -REDIS_DB=0 - -# Rate Limiting -RATE_LIMIT_ANON=30 -RATE_LIMIT_AUTH=100 -RATE_LIMIT_GLOBAL=10000 - -# Bitcoin -BITCOIN_RPC_URL=http://localhost:8332 -BITCOIN_RPC_USER= -BITCOIN_RPC_PASS= -BITCOIN_NETWORK=mainnet - -# Rune configuration -RUNE_ID=1:0 -RUNE_NAME=DOG•GO•TO•THE•MOON - -# JWT -JWT_SECRET=your-secret-key-here - -# Logging -LOG_LEVEL=info diff --git a/legacy/taproot-assets-era/backend/.env.production.template b/legacy/taproot-assets-era/backend/.env.production.template deleted file mode 100644 index a916f99..0000000 --- a/legacy/taproot-assets-era/backend/.env.production.template +++ /dev/null @@ -1,75 +0,0 @@ -# ============================================================================= -# RuneBolt Backend — Production Environment Variables -# ============================================================================= -# Copy this file to .env and fill in all values before deploying. -# Lines marked [REQUIRED] must be set. Lines marked [OPTIONAL] have defaults. - -# ==================== Server ==================== - -# [OPTIONAL] Port the server listens on (default: 3141) -PORT=3141 - -# [REQUIRED] Must be "production" for production deployments -NODE_ENV=production - -# ==================== Database ==================== - -# [REQUIRED] PostgreSQL connection string -# Format: postgresql://user:password@host:port/database -DATABASE_URL=postgresql://runebolt:CHANGE_ME@localhost:5432/runebolt - -# [OPTIONAL] Connection pool settings -DB_POOL_MAX=50 -DB_POOL_MIN=10 -DB_IDLE_TIMEOUT=30000 -DB_CONNECTION_TIMEOUT=5000 -DB_STATEMENT_TIMEOUT=10000 - -# ==================== Redis ==================== - -# [OPTIONAL] Redis host and port for caching (default: localhost:6379) -# Server runs in no-cache mode if Redis is unavailable -REDIS_HOST=localhost -REDIS_PORT=6379 - -# ==================== Authentication ==================== - -# [REQUIRED] JWT signing secret — must be 64+ hex characters -# Generate with: openssl rand -hex 32 -# CRITICAL: Never reuse across environments. Rotate periodically. -JWT_SECRET= - -# ==================== CORS ==================== - -# [REQUIRED] Comma-separated list of allowed origins -# Example: https://app.runebolt.io,https://runebolt.io -# CORS is locked down in production — requests from unlisted origins are blocked -CORS_ORIGIN=https://app.runebolt.io - -# ==================== Bitcoin ==================== - -# [OPTIONAL] Bitcoin network: mainnet or testnet (default: mainnet) -BITCOIN_NETWORK=mainnet - -# [OPTIONAL] Mempool API URL for fee estimation and tx broadcasting -# Default: https://mempool.space/api -MEMPOOL_API_URL=https://mempool.space/api - -# [OPTIONAL] Bitcoin RPC URL (if using direct RPC instead of Mempool API) -BITCOIN_RPC_URL= - -# ==================== Rate Limiting ==================== - -# [OPTIONAL] Rate limit window in milliseconds (default: 60000 = 1 minute) -RATE_LIMIT_WINDOW_MS=60000 - -# [OPTIONAL] Max requests per window (default: 100) -RATE_LIMIT_MAX_REQUESTS=100 - -# ==================== Rune Configuration ==================== - -# [OPTIONAL] Rune ID to track (default: 1:0 for DOG) -RUNE_ID=1:0 - -# [OPTIONAL] Rune display name -RUNE_NAME=DOG•GO•TO•THE•MOON diff --git a/legacy/taproot-assets-era/backend/.gitignore b/legacy/taproot-assets-era/backend/.gitignore deleted file mode 100644 index 31a9d6d..0000000 --- a/legacy/taproot-assets-era/backend/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -node_modules/ -dist/ -data/ -.env -*.db -*.db-journal diff --git a/legacy/taproot-assets-era/backend/PERFORMANCE.md b/legacy/taproot-assets-era/backend/PERFORMANCE.md deleted file mode 100644 index ee7c66c..0000000 --- a/legacy/taproot-assets-era/backend/PERFORMANCE.md +++ /dev/null @@ -1,209 +0,0 @@ -# RuneBolt Performance Optimizations - -This document describes the performance optimizations implemented for mass adoption. - -## Overview - -RuneBolt has been optimized to handle millions of users and billions of transactions through: - -1. **PostgreSQL with Connection Pooling** - Replaces SQLite for horizontal scalability -2. **Redis Caching Layer** - Sub-millisecond balance lookups -3. **Worker Thread Pool** - Non-blocking transfer execution -4. **Rate Limiting** - Multi-tier protection (IP, user, global) -5. **Prometheus Monitoring** - Real-time metrics and alerting - -## Architecture - -``` -┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐ -│ WebSocket │────▶│ Express Server │────▶│ Rate Limiter │ -│ Server │ │ (Main Thread) │ │ (Redis) │ -└─────────────────┘ └──────────────────┘ └─────────────────┘ - │ - ▼ -┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐ -│ PostgreSQL │◀────│ Worker Thread │◀────│ Redis Cache │ -│ (Database) │ │ Pool │ │ (Hot Data) │ -└─────────────────┘ └──────────────────┘ └─────────────────┘ - │ - ▼ - ┌──────────────────┐ - │ Prometheus │ - │ Metrics │ - └──────────────────┘ -``` - -## Key Features - -### 1. PostgreSQL Migration - -- **Connection Pooling**: 10-50 connections (configurable) -- **Partitioned Transfers Table**: Monthly partitions for time-series data -- **Optimized Indexes**: No OR conditions, covering indexes -- **Async/Await**: Non-blocking database operations - -**Key Queries Optimized**: -- Transfer history: Uses separate indexed queries for sender/recipient -- Balance lookups: Covered by Redis cache -- Channel state: Partial index on active channels only - -### 2. Redis Caching - -**Cached Data**: -- Channel balances (TTL: 60s) -- Channel states (TTL: 300s) -- User channel lists (TTL: 300s) -- Hot channels (sorted set by activity) - -**Cache Invalidation**: -- Automatic on balance updates -- Manual via `invalidateChannelCache()` -- Distributed locking for concurrent updates - -### 3. Worker Thread Pool - -- **Dynamic Sizing**: 2-4 workers based on CPU cores -- **Batch Processing**: 100 transfers per batch, 50ms flush interval -- **Task Queue**: Max 10,000 queued transfers -- **Graceful Shutdown**: Waits for active tasks to complete - -### 4. Rate Limiting - -| Tier | Limit | Window | -|------|-------|--------| -| Anonymous (IP) | 30 req | 60 sec | -| Authenticated | 100 req | 60 sec | -| Global | 10,000 req | 1 sec | - -Rate limits are stored in Redis for distributed rate limiting across multiple server instances. - -### 5. Monitoring - -**Prometheus Metrics**: -- `http_requests_total` - HTTP request counter -- `http_request_duration_seconds` - Request latency histogram -- `transfers_total` - Transfer rate counter -- `transfer_latency_seconds` - Transfer latency histogram -- `cache_hits_total` / `cache_misses_total` - Cache performance -- `db_pool_connections` - Database pool stats -- `worker_pool_size` - Worker pool stats -- `websocket_active_connections` - WS connection gauge - -**Endpoints**: -- `GET /health` - Health check with service status -- `GET /metrics` - Prometheus metrics - -## Configuration - -Environment variables for performance tuning: - -```bash -# Database Pool -DB_POOL_MAX=50 -DB_POOL_MIN=10 -DB_IDLE_TIMEOUT=30000 -DB_CONNECTION_TIMEOUT=5000 -DB_STATEMENT_TIMEOUT=10000 - -# Redis -REDIS_HOST=localhost -REDIS_PORT=6379 -REDIS_PASSWORD= - -# Rate Limiting -RATE_LIMIT_ANON=30 -RATE_LIMIT_AUTH=100 -RATE_LIMIT_GLOBAL=10000 -``` - -## API Changes - -### Transfer Execution - -The `RuneLedger.transfer()` method is now async and uses worker threads: - -```typescript -const transfer = await ledger.transfer( - fromChannelId, - toChannelId, - amount, - memo, - { useWorker: true } // default: true -); -``` - -### Batch Mode - -Enable batch processing for high-throughput scenarios: - -```typescript -ledger.enableBatchMode(); -// ... many transfers ... -await ledger.disableBatchMode(); -``` - -## Performance Targets - -| Metric | Before | After | Target | -|--------|--------|-------|--------| -| TPS | ~100 | ~2,000 | 10,000+ | -| Latency p99 | ~50ms | ~10ms | <10ms | -| Concurrent Users | ~1,000 | ~50,000 | 500,000+ | -| Cache Hit Rate | 0% | >90% | >95% | - -## Deployment Checklist - -- [ ] PostgreSQL 14+ installed and configured -- [ ] Redis 6+ installed and running -- [ ] Database migrations applied -- [ ] Environment variables configured -- [ ] Prometheus scraping configured -- [ ] Grafana dashboards imported -- [ ] Load testing completed - -## Monitoring Queries - -**Cache Hit Rate**: -``` -rate(cache_hits_total[5m]) / (rate(cache_hits_total[5m]) + rate(cache_misses_total[5m])) -``` - -**Transfer TPS**: -``` -rate(transfers_total{status="success"}[1m]) -``` - -**P99 Latency**: -``` -histogram_quantile(0.99, rate(transfer_latency_seconds_bucket[5m])) -``` - -## Troubleshooting - -**High Database Load**: -- Check `db_pool_connections` metric -- Increase `DB_POOL_MAX` if connections are saturated -- Review slow query logs - -**Cache Misses**: -- Verify Redis connectivity -- Check `cache_misses_total` metric -- Adjust cache TTLs if needed - -**Worker Pool Exhaustion**: -- Monitor `worker_pool_size{state="queued"}` -- Increase worker pool max size -- Enable batch mode for bulk operations - -## Migration from SQLite - -1. Stop the application -2. Export SQLite data: `sqlite3 runebolt.db .dump > backup.sql` -3. Set up PostgreSQL and apply migrations -4. Import data (transform UUIDs as needed) -5. Update environment variables -6. Start with new configuration - -## License - -MIT diff --git a/legacy/taproot-assets-era/backend/SIMULATION_REPORT.md b/legacy/taproot-assets-era/backend/SIMULATION_REPORT.md deleted file mode 100644 index 3f8bd0f..0000000 --- a/legacy/taproot-assets-era/backend/SIMULATION_REPORT.md +++ /dev/null @@ -1,223 +0,0 @@ -# RuneBolt Simulation Test Report - -**Date:** 2026-03-15 -**Version:** 0.2.0 -**Test Framework:** Vitest 4.1.0 -**Database:** PostgreSQL 17 (local) -**Network:** Testnet simulation (no real Bitcoin spent) - ---- - -## Test Results Summary - -| Suite | Tests | Passed | Failed | -|-------|-------|--------|--------| -| simulation.test.ts | 50 | 50 | 0 | -| rune-encoding.test.ts | 45 | 45 | 0 | -| **Total** | **95** | **95** | **0** | - -All 95 tests pass. However, several tests explicitly verify **security findings** — behaviors that pass because the code currently allows them, but which represent risks for mainnet. - ---- - -## Scenarios Tested - -### Scenario 1: DOG Transfer Flow (End-to-End) — 10 tests, ALL PASS -- Real secp256k1 keypair generation (BIP-340 x-only pubkeys) -- Challenge-response authentication with Schnorr signatures -- Channel open (PENDING_OPEN state) -- Funding confirmation simulation (PENDING_OPEN → OPEN) -- Off-chain transfer: 10,000 DOG from Alice to Bob -- Balance verification after transfer -- Fee tier check (free within first 500 txs) -- Cooperative channel close (OPEN → CLOSING) - -### Scenario 2: Security Tests — 7 tests, ALL PASS -- Wrong-key signature rejection (BIP-340 verification works correctly) -- Overflow detection (amount > balance) -- Zero/negative amount rejection (validated in RuneLedger) -- 1% channel reserve enforcement (ChannelReserves module) -- Replay attack prevention (nonce uniqueness via DB) -- One-time-use challenge (deleted after first verification) -- Short signature rejection (must be exactly 64 bytes) - -### Scenario 3: Fee System Tests — 6 tests, ALL PASS -- New user starts with 500 free transactions -- Transaction count tracking and increment -- Free tier exhaustion at exactly 500 -- FeeManager calculates 0.1% off-chain fee for paid tier -- FeeManager calculates 0.5% settlement fee -- Free tier returns 0 fee for new users - -### Scenario 4: Multi-User Concurrent — 4 tests, ALL PASS -- 5 users created simultaneously without conflict -- 10 parallel transfers without deadlock or error -- UUID nonce uniqueness across 100 concurrent operations -- Channel state invariants preserved after concurrent ops - -### Scenario 5: Channel Reserve Enforcement — 3 tests, ALL PASS -- 1% reserve calculation at various capacities -- Spendable balance computation -- Transfer validation against reserve boundary - -### Scenario 6: Channel State Machine — 6 tests, ALL PASS (includes 1 FINDING) -- All valid transitions verified (PENDING_OPEN→OPEN, OPEN→CLOSING, etc.) -- Invalid transitions rejected (CLOSED→OPEN, CLOSING→OPEN) -- assertTransition throws on invalid transition -- DB state transitions work correctly -- Force close path (OPEN→FORCE_CLOSING→CLOSED) -- **FINDING:** DB allows invalid state transitions - -### Scenario 7: Bitmap Escrow — 1 test, PASS -- Escrow table accessible and queryable - -### Scenario 8: Cryptographic Verification — 6 tests, ALL PASS -- Unique keypair generation -- Correct sign + verify round-trip -- Wrong-key rejection -- Tampered message rejection -- 64-byte Schnorr signature format -- Unicode/special character handling - -### Scenario 9: Overflow & Edge Cases — 5 tests, ALL PASS (includes 2 FINDINGS) -- Max safe BigInt reserve calculation -- Minimum reserve edge case -- Balance invariant (local + remote = capacity) preserved correctly -- **FINDING:** DB does not enforce balance invariant -- **FINDING:** DB allows negative balances - -### Scenario 10: Commitment Tracking — 2 tests, ALL PASS -- Commitment create and retrieval (latest by sequence) -- Commitment history with DESC ordering - -### Rune Encoding Tests — 45 tests, ALL PASS (includes 1 FINDING) -- LEB128 encoding/decoding: 0, 1, 127, 128, 255, 300, 840000, 2^32, 2^64 -- Negative value rejection -- Rune ID encode/decode round-trip -- DOG amount formatting and parsing -- Single-edict Runestone build + parse round-trip -- Pointer Runestone build + parse -- Commitment Runestone (2 edicts, delta encoding) -- Multi-transfer Runestone (sorted, delta-encoded) -- Empty transfer list rejection -- Edge cases: non-OP_RETURN, missing OP_13, short buffer -- Protocol conformance: Body=0, Pointer=22, Mint=20 -- **FINDING:** Empty Runestone (OP_RETURN + OP_13, no data) returns null - ---- - -## Security Findings - -### CRITICAL - -**F1: Missing Database Migrations — 8 tables not created by migration files** -- Tables `user_transaction_counts`, `fee_records`, `user_tiers`, `fee_ledger`, `revocation_secrets`, `disputes`, `breach_attempts`, `transaction_status` are referenced in code but have NO migration SQL files. -- The application will crash on first use of fees, disputes, revocations, or transaction status tracking. -- **Risk:** CRITICAL — app will fail in production on any fee/dispute operation. -- **Fix:** Create migration `002_fee_and_security_tables.sql` with all missing tables. - -**F2: Partitioned transfers table has invalid primary key** -- Migration `001_postgres_schema.sql` line 38 creates `transfers` with `PARTITION BY RANGE (created_at)` but uses `id UUID PRIMARY KEY` which does not include the partition column. -- PostgreSQL rejects this: `unique constraint on partitioned table must include all partitioning columns`. -- **Risk:** CRITICAL — transfers table cannot be created from migrations alone. -- **Fix:** Change PK to `PRIMARY KEY (id, created_at)` or remove partitioning. - -### HIGH - -**F3: No DB-level state transition enforcement** -- The database allows any channel state to be set directly (e.g., CLOSED → OPEN). -- State machine enforcement only exists in `ChannelManager` (application layer). -- A bug in any code path that calls `db.updateChannelState()` directly bypasses the state machine. -- **Risk:** HIGH — could allow channels to be "resurrected" from CLOSED state. -- **Fix:** Add PostgreSQL trigger or CHECK constraint that validates state transitions. - -**F4: No DB-level balance invariant enforcement** -- `updateChannelBalances()` can set `local_balance + remote_balance != capacity`. -- It can also set negative balances. -- Application code enforces this, but any code path that directly calls the DB method can break invariants. -- **Risk:** HIGH — could lead to creation/destruction of funds if a bug bypasses application checks. -- **Fix:** Add CHECK constraint: `local_balance >= 0 AND remote_balance >= 0 AND local_balance + remote_balance = capacity`. - -**F5: BigInt precision loss in transfer amounts** -- `FeeManager.calculateFee()` converts BigInt to Number for fee calculation: `BigInt(Math.ceil(Number(transferAmount) * rate))`. -- For amounts > 2^53, `Number(transferAmount)` loses precision. -- `RuneLedger` also casts BigInt to Number for DB operations: `Number(amount)`, `Number(newFromLocal)`. -- **Risk:** HIGH — incorrect fee calculations and silent balance corruption for large DOG amounts. -- **Fix:** Use BigInt-native arithmetic for all balance/fee operations. Replace `Number()` casts with BigInt math. - -### MEDIUM - -**F6: Empty Runestone not recognized by parser** -- `RuneParser.parseRunestone()` rejects scripts shorter than 3 bytes, but a valid empty Runestone is just `OP_RETURN OP_13` (2 bytes). -- Per the Runes protocol specification, this should be a valid no-op Runestone. -- **Risk:** MEDIUM — could cause issues when processing transactions with empty Runestones. -- **Fix:** Change minimum length check from `< 3` to `< 2`. - -**F7: Client signature not cryptographically verified in transfer path** -- `RuneLedger.transfer()` accepts `clientSignature` as a parameter but never verifies it. -- The signature is stored in the DB but not checked against the transfer payload. -- **Risk:** MEDIUM — any party with a valid JWT can forge transfers without proving they hold the private key for each transfer. -- **Fix:** Verify the client signature against the transfer details (fromChannelId, toChannelId, amount, nonce) using the sender's public key. - -**F8: `index.ts` calls `process.exit(1)` on failed mainnet checks** -- This kills the entire process, preventing graceful shutdown. -- In a test environment, this kills the test runner. -- **Risk:** MEDIUM — operational risk, makes testing harder. -- **Fix:** Throw an error instead of calling `process.exit()`. Let the caller decide what to do. - -### LOW - -**F9: No unique constraint on transfer nonce in DB** -- Replay prevention relies on `SELECT id FROM transfers WHERE nonce = $1` but the nonce column has no UNIQUE constraint. -- Under concurrent load, two identical nonces could be inserted simultaneously. -- **Risk:** LOW — UUID v4 collisions are astronomically unlikely, but defense-in-depth says add the constraint. -- **Fix:** `ALTER TABLE transfers ADD CONSTRAINT transfers_nonce_unique UNIQUE (nonce)`. - -**F10: Challenge-response FK requires user to exist first** -- The `challenges` table has `pubkey REFERENCES users(pubkey)`, requiring the user to be created before a challenge can be issued. -- New users can't authenticate until they're in the users table, but users are created during channel opening. -- **Risk:** LOW — chicken-and-egg problem for new user onboarding flow. -- **Fix:** Either remove the FK constraint or create the user during challenge creation. - ---- - -## Component Risk Assessment - -| Component | Risk Level | Notes | -|-----------|-----------|-------| -| Schnorr Auth (BIP-340) | LOW | Real cryptographic verification, working correctly | -| Channel State Machine | HIGH | Application-only enforcement, no DB constraints | -| Balance Management | HIGH | No DB-level invariant checks, BigInt→Number precision loss | -| Fee System | CRITICAL | Missing DB tables, BigInt precision issue for large amounts | -| Rune Encoding | LOW | LEB128 + Runestone encoding is correct and round-trips | -| Replay Prevention | LOW | Nonce-based, working but no UNIQUE constraint | -| Reserve Enforcement | LOW | 1% reserve correctly enforced at application layer | -| Escrow System | MEDIUM | Table exists but no test coverage of actual escrow flows | -| Database Migrations | CRITICAL | 8 missing tables, partitioned transfers table broken | -| Transfer Signatures | MEDIUM | Stored but never verified | - ---- - -## Final Verdict - -### NOT READY for mainnet - -**Blocking issues before mainnet deployment:** - -1. **CRITICAL: Fix database migrations** — 8 missing table definitions will crash the application on first use of fees, disputes, or revocations. The `transfers` table partition key issue prevents the table from being created at all from migrations. - -2. **HIGH: Add DB-level safety constraints** — Channel state transitions, balance invariants (local + remote = capacity, no negatives), and nonce uniqueness should all be enforced at the database level. Application-layer-only enforcement is insufficient for a financial system handling real money. - -3. **HIGH: Fix BigInt precision loss** — Any transfer amount above ~9 quadrillion units (2^53) will silently corrupt balances. While current DOG supply may not hit this, it's a ticking time bomb in a financial system. - -4. **MEDIUM: Implement transfer signature verification** — Client signatures are collected but never verified. Any authenticated user can forge transfers without proving per-transfer authorization. - -**What IS working well:** -- Schnorr authentication is real, verified, and secure -- Rune encoding/decoding is correct and protocol-conformant -- Channel reserve enforcement works properly -- Replay attack prevention via nonces is functional -- The core transfer logic (balance updates, commitments) is sound -- Concurrent operations handle correctly at the DB level - -**Estimated effort to reach mainnet-ready:** Fix the 4 blocking issues above. Items 1-3 are structural fixes (1-2 days). Item 4 requires design decisions about the signature scheme (1 day). diff --git a/legacy/taproot-assets-era/backend/fix-async.sh b/legacy/taproot-assets-era/backend/fix-async.sh deleted file mode 100644 index 35080f4..0000000 --- a/legacy/taproot-assets-era/backend/fix-async.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/bash -# Fix all async/await issues in agent-generated code - -echo "Fixing async issues in RuneBolt backend..." - -# Fix ChannelManager.ts - add await to all db calls -sed -i 's/this.db.createUser(userPubkey);/await this.db.createUser(userPubkey);/g' src/channels/ChannelManager.ts -sed -i 's/this.db.createChannel({/await this.db.createChannel({/g' src/channels/ChannelManager.ts -sed -i 's/const row = this.db.getChannel(channelId);/const row = await this.db.getChannel(channelId);/g' src/channels/ChannelManager.ts -sed -i 's/this.db.updateChannel({/await this.db.updateChannel({/g' src/channels/ChannelManager.ts -sed -i 's/const channels = this.db.getChannelsByPubkey(userPubkey);/const channels = await this.db.getChannelsByPubkey(userPubkey);/g' src/channels/ChannelManager.ts -sed -i 's/this.db.updateChannelState(channelId,/await this.db.updateChannelState(channelId,/g' src/channels/ChannelManager.ts - -# Fix RuneLedger.ts - add await to all db calls -sed -i 's/const fromRow = this.db.getChannel(fromChannelId);/const fromRow = await this.db.getChannel(fromChannelId);/g' src/ledger/RuneLedger.ts -sed -i 's/const toRow = this.db.getChannel(toChannelId);/const toRow = await this.db.getChannel(toChannelId);/g' src/ledger/RuneLedger.ts -sed -i 's/const row = this.db.getChannel(channelId);/const row = await this.db.getChannel(channelId);/g' src/ledger/RuneLedger.ts -sed -i 's/this.db.updateChannelBalances(fromChannelId,/await this.db.updateChannelBalances(fromChannelId,/g' src/ledger/RuneLedger.ts -sed -i 's/this.db.updateChannelBalances(toChannelId,/await this.db.updateChannelBalances(toChannelId,/g' src/ledger/RuneLedger.ts -sed -i 's/this.db.createTransfer({/await this.db.createTransfer({/g' src/ledger/RuneLedger.ts -sed -i 's/this.db.getTransfersByPubkey(pubkey,/const rows = await this.db.getTransfersByPubkey(pubkey,/g' src/ledger/RuneLedger.ts -sed -i 's/const channels = this.db.getChannelsByPubkey(pubkey);/const channels = await this.db.getChannelsByPubkey(pubkey);/g' src/ledger/RuneLedger.ts - -# Fix authRoutes.ts - add await -sed -i 's/db.createUser(result.pubkey);/await db.createUser(result.pubkey);/g' src/api/routes/authRoutes.ts -sed -i 's/const user = await db.getUser(pubkey);/const user = await db.getUser(pubkey);/g' src/api/routes/authRoutes.ts - -echo "Fixes applied. Now building..." -npm run build diff --git a/legacy/taproot-assets-era/backend/migrations/001_postgres_schema.sql b/legacy/taproot-assets-era/backend/migrations/001_postgres_schema.sql deleted file mode 100644 index f5ed9bc..0000000 --- a/legacy/taproot-assets-era/backend/migrations/001_postgres_schema.sql +++ /dev/null @@ -1,141 +0,0 @@ --- PostgreSQL Schema Migration for RuneBolt Performance Optimizations --- Enables partitioning, connection pooling, and optimized indexing - --- Enable UUID extension -CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; - --- Users table -CREATE TABLE IF NOT EXISTS users ( - pubkey TEXT PRIMARY KEY, - username TEXT UNIQUE, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_users_username ON users(username); - --- Channels table with optimized indexes -CREATE TABLE IF NOT EXISTS channels ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - user_pubkey TEXT NOT NULL REFERENCES users(pubkey), - runebolt_pubkey TEXT NOT NULL, - funding_txid TEXT, - funding_vout INTEGER, - capacity BIGINT NOT NULL DEFAULT 0, - local_balance BIGINT NOT NULL DEFAULT 0, - remote_balance BIGINT NOT NULL DEFAULT 0, - state TEXT NOT NULL DEFAULT 'PENDING_OPEN', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_channels_user_pubkey ON channels(user_pubkey); -CREATE INDEX IF NOT EXISTS idx_channels_state ON channels(state); -CREATE INDEX IF NOT EXISTS idx_channels_active ON channels(user_pubkey, state) - WHERE state = 'OPEN'; - --- Transfers table (non-partitioned for simplicity; partition later if needed) -CREATE TABLE IF NOT EXISTS transfers ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - from_channel UUID NOT NULL REFERENCES channels(id), - to_channel UUID NOT NULL REFERENCES channels(id), - amount BIGINT NOT NULL CHECK (amount > 0), - memo VARCHAR(256), - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - --- Optimized indexes (no OR conditions for better performance) -CREATE INDEX IF NOT EXISTS idx_transfers_sender ON transfers(from_channel, created_at DESC) - INCLUDE (id, to_channel, amount, memo); -CREATE INDEX IF NOT EXISTS idx_transfers_recipient ON transfers(to_channel, created_at DESC) - INCLUDE (id, from_channel, amount, memo); -CREATE INDEX IF NOT EXISTS idx_transfers_created ON transfers(created_at DESC); - --- Claim links table -CREATE TABLE IF NOT EXISTS claim_links ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - creator_pubkey TEXT NOT NULL REFERENCES users(pubkey), - amount BIGINT NOT NULL, - memo TEXT, - claimed_by TEXT REFERENCES users(pubkey), - claimed_at TIMESTAMPTZ, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - expires_at TIMESTAMPTZ NOT NULL -); - -CREATE INDEX IF NOT EXISTS idx_claim_links_creator ON claim_links(creator_pubkey); -CREATE INDEX IF NOT EXISTS idx_claim_links_expires ON claim_links(expires_at) - WHERE claimed_by IS NULL; - --- Authentication challenges table -CREATE TABLE IF NOT EXISTS challenges ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - pubkey TEXT NOT NULL REFERENCES users(pubkey), - challenge TEXT NOT NULL, - expires_at TIMESTAMPTZ NOT NULL -); - -CREATE INDEX IF NOT EXISTS idx_challenges_pubkey ON challenges(pubkey); -CREATE INDEX IF NOT EXISTS idx_challenges_expires ON challenges(expires_at); - --- Commitments table (previously in-memory, now persisted) -CREATE TABLE IF NOT EXISTS commitments ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - channel_id UUID NOT NULL REFERENCES channels(id) ON DELETE CASCADE, - sequence INTEGER NOT NULL, - local_balance BIGINT NOT NULL, - remote_balance BIGINT NOT NULL, - commitment_tx TEXT, - signature TEXT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE(channel_id, sequence) -); - -CREATE INDEX IF NOT EXISTS idx_commitments_channel ON commitments(channel_id, sequence DESC); - --- Rate limiting tracking (optional, can use Redis instead) -CREATE TABLE IF NOT EXISTS rate_limit_log ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - key_type TEXT NOT NULL, -- 'ip', 'user', 'global' - key_value TEXT NOT NULL, - request_count INTEGER NOT NULL DEFAULT 1, - window_start TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_rate_limit_lookup ON rate_limit_log(key_type, key_value, window_start); - --- Performance monitoring table -CREATE TABLE IF NOT EXISTS performance_metrics ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - metric_name TEXT NOT NULL, - metric_value DOUBLE PRECISION NOT NULL, - labels JSONB, - recorded_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_metrics_name_time ON performance_metrics(metric_name, recorded_at DESC); - --- Function to update updated_at timestamp -CREATE OR REPLACE FUNCTION update_updated_at_column() -RETURNS TRIGGER AS $$ -BEGIN - NEW.updated_at = NOW(); - RETURN NEW; -END; -$$ LANGUAGE plpgsql; - --- Trigger for channels updated_at -DROP TRIGGER IF EXISTS update_channels_updated_at ON channels; -CREATE TRIGGER update_channels_updated_at - BEFORE UPDATE ON channels - FOR EACH ROW - EXECUTE FUNCTION update_updated_at_column(); - --- Cleanup function for old challenges and rate limit logs -CREATE OR REPLACE FUNCTION cleanup_expired_data() -RETURNS void AS $$ -BEGIN - DELETE FROM challenges WHERE expires_at < NOW() - INTERVAL '1 day'; - DELETE FROM rate_limit_log WHERE window_start < NOW() - INTERVAL '1 hour'; - DELETE FROM performance_metrics WHERE recorded_at < NOW() - INTERVAL '7 days'; -END; -$$ LANGUAGE plpgsql; diff --git a/legacy/taproot-assets-era/backend/migrations/005_multi_asset.sql b/legacy/taproot-assets-era/backend/migrations/005_multi_asset.sql deleted file mode 100644 index 8d045f1..0000000 --- a/legacy/taproot-assets-era/backend/migrations/005_multi_asset.sql +++ /dev/null @@ -1,73 +0,0 @@ --- Migration 005: Multi-asset support --- Adds tables for asset registry, escrows (Bitmap NFT trading), and asset balances (BRC-20 channel tracking). --- --- NOTE: BRC-20 and Bitmap inscriptions use DIFFERENT on-chain mechanisms than Runes. --- Runes use Runestone OP_RETURN; BRC-20 uses inscription JSON; Bitmap uses escrow model. - --- ==================== Assets Table ==================== --- Central registry of supported assets and their configuration. -CREATE TABLE IF NOT EXISTS assets ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - type TEXT NOT NULL CHECK (type IN ('rune', 'btc', 'brc20', 'inscription')), - config JSONB NOT NULL DEFAULT '{}', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_assets_type ON assets(type); - --- Seed initial assets -INSERT INTO assets (id, name, type, config) VALUES - ('dog', 'DOG', 'rune', '{"runeId": "840000:3", "decimals": 5}'), - ('btc', 'Bitcoin', 'btc', '{"decimals": 8}'), - ('ordi', 'ORDI', 'brc20', '{"ticker": "ordi", "decimals": 18}'), - ('bitmap', 'Bitmap', 'inscription', '{"decimals": 0}') -ON CONFLICT (id) DO NOTHING; - --- ==================== Escrows Table ==================== --- Bitmap (NFT inscription) escrow for atomic swaps. --- Seller deposits inscription, buyer deposits payment, hub releases both atomically. -CREATE TABLE IF NOT EXISTS escrows ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - seller_pubkey TEXT NOT NULL, - buyer_pubkey TEXT NOT NULL, - inscription_id TEXT NOT NULL, - price_asset TEXT NOT NULL REFERENCES assets(id), - price_amount NUMERIC NOT NULL CHECK (price_amount > 0), - status TEXT NOT NULL DEFAULT 'created' - CHECK (status IN ('created', 'inscription_deposited', 'payment_deposited', - 'both_deposited', 'executing', 'completed', 'refunded', 'expired')), - timeout_at TIMESTAMPTZ NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_escrows_seller ON escrows(seller_pubkey); -CREATE INDEX IF NOT EXISTS idx_escrows_buyer ON escrows(buyer_pubkey); -CREATE INDEX IF NOT EXISTS idx_escrows_status ON escrows(status) WHERE status NOT IN ('completed', 'refunded', 'expired'); -CREATE INDEX IF NOT EXISTS idx_escrows_timeout ON escrows(timeout_at) WHERE status NOT IN ('completed', 'refunded', 'expired'); - --- ==================== Escrow Deposits Table ==================== --- Tracks individual deposits (inscription or payment) for each escrow. -CREATE TABLE IF NOT EXISTS escrow_deposits ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - escrow_id UUID NOT NULL REFERENCES escrows(id) ON DELETE CASCADE, - side TEXT NOT NULL CHECK (side IN ('seller', 'buyer')), - txid TEXT NOT NULL, - confirmed BOOLEAN NOT NULL DEFAULT false, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_escrow_deposits_escrow ON escrow_deposits(escrow_id); - --- ==================== Asset Balances Table ==================== --- Off-chain asset balances tracked by the hub (used for BRC-20 channel balances). -CREATE TABLE IF NOT EXISTS asset_balances ( - user_pubkey TEXT NOT NULL, - asset_id TEXT NOT NULL REFERENCES assets(id), - balance NUMERIC NOT NULL DEFAULT 0 CHECK (balance >= 0), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (user_pubkey, asset_id) -); - -CREATE INDEX IF NOT EXISTS idx_asset_balances_user ON asset_balances(user_pubkey); -CREATE INDEX IF NOT EXISTS idx_asset_balances_asset ON asset_balances(asset_id); diff --git a/legacy/taproot-assets-era/backend/package-lock.json b/legacy/taproot-assets-era/backend/package-lock.json deleted file mode 100644 index bcd393c..0000000 --- a/legacy/taproot-assets-era/backend/package-lock.json +++ /dev/null @@ -1,3825 +0,0 @@ -{ - "name": "@runebolt/backend", - "version": "0.2.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "@runebolt/backend", - "version": "0.2.0", - "dependencies": { - "@bitcoinerlab/secp256k1": "^1.2.0", - "@noble/hashes": "^2.0.1", - "@noble/secp256k1": "^3.0.0", - "bitcoinjs-lib": "^7.0.1", - "cors": "^2.8.5", - "dotenv": "^16.3.1", - "express": "^4.18.2", - "express-rate-limit": "^7.5.1", - "helmet": "^7.1.0", - "ioredis": "^5.3.2", - "jsonwebtoken": "^9.0.2", - "pg": "^8.20.0", - "prom-client": "^15.1.0", - "uuid": "^9.0.0", - "ws": "^8.16.0", - "zod": "^3.22.4" - }, - "devDependencies": { - "@types/cors": "^2.8.17", - "@types/express": "^4.17.21", - "@types/jsonwebtoken": "^9.0.5", - "@types/node": "^20.10.0", - "@types/pg": "^8.18.0", - "@types/supertest": "^7.2.0", - "@types/uuid": "^9.0.7", - "@types/ws": "^8.5.10", - "supertest": "^7.2.2", - "tsx": "^4.7.0", - "typescript": "^5.3.3", - "vitest": "^4.1.0" - } - }, - "node_modules/@bitcoinerlab/secp256k1": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@bitcoinerlab/secp256k1/-/secp256k1-1.2.0.tgz", - "integrity": "sha512-jeujZSzb3JOZfmJYI0ph1PVpCRV5oaexCgy+RvCXV8XlY+XFB/2n3WOcvBsKLsOw78KYgnQrQWb2HrKE4be88Q==", - "license": "MIT", - "dependencies": { - "@noble/curves": "^1.7.0" - } - }, - "node_modules/@emnapi/core": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.0.tgz", - "integrity": "sha512-0DQ98G9ZQZOxfUcQn1waV2yS8aWdZ6kJMbYCJB3oUBecjWYO1fqJ+a1DRfPF3O5JEkwqwP1A9QEN/9mYm2Yd0w==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.0", - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/runtime": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.0.tgz", - "integrity": "sha512-QN75eB0IH2ywSpRpNddCRfQIhmJYBCJ1x5Lb3IscKAL8bMnVAKnRg8dCoXbHzVLLH7P38N2Z3mtulB7W0J0FKw==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/wasi-threads": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.0.tgz", - "integrity": "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz", - "integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.3.tgz", - "integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.3.tgz", - "integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.3.tgz", - "integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.3.tgz", - "integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.3.tgz", - "integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.3.tgz", - "integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.3.tgz", - "integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.3.tgz", - "integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz", - "integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.3.tgz", - "integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.3.tgz", - "integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.3.tgz", - "integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.3.tgz", - "integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.3.tgz", - "integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.3.tgz", - "integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz", - "integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-arm64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.3.tgz", - "integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.3.tgz", - "integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.3.tgz", - "integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.3.tgz", - "integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openharmony-arm64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.3.tgz", - "integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.3.tgz", - "integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.3.tgz", - "integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.3.tgz", - "integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.3.tgz", - "integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@ioredis/commands": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.5.1.tgz", - "integrity": "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw==", - "license": "MIT" - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", - "dev": true, - "license": "MIT" - }, - "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.1.tgz", - "integrity": "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1", - "@tybys/wasm-util": "^0.10.1" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" - } - }, - "node_modules/@noble/curves": { - "version": "1.9.7", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", - "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.8.0" - }, - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@noble/curves/node_modules/@noble/hashes": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", - "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@noble/hashes": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.1.tgz", - "integrity": "sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==", - "license": "MIT", - "engines": { - "node": ">= 20.19.0" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@noble/secp256k1": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@noble/secp256k1/-/secp256k1-3.0.0.tgz", - "integrity": "sha512-NJBaR352KyIvj3t6sgT/+7xrNyF9Xk9QlLSIqUGVUYlsnDTAUqY8LOmwpcgEx4AMJXRITQ5XEVHD+mMaPfr3mg==", - "license": "MIT", - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@opentelemetry/api": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz", - "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==", - "license": "Apache-2.0", - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/@oxc-project/runtime": { - "version": "0.115.0", - "resolved": "https://registry.npmjs.org/@oxc-project/runtime/-/runtime-0.115.0.tgz", - "integrity": "sha512-Rg8Wlt5dCbXhQnsXPrkOjL1DTSvXLgb2R/KYfnf1/K+R0k6UMLEmbQXPM+kwrWqSmWA2t0B1EtHy2/3zikQpvQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@oxc-project/types": { - "version": "0.115.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.115.0.tgz", - "integrity": "sha512-4n91DKnebUS4yjUHl2g3/b2T+IUdCfmoZGhmwsovZCDaJSs+QkVAM+0AqqTxHSsHfeiMuueT75cZaZcT/m0pSw==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/Boshen" - } - }, - "node_modules/@paralleldrive/cuid2": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@paralleldrive/cuid2/-/cuid2-2.3.1.tgz", - "integrity": "sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@noble/hashes": "^1.1.5" - } - }, - "node_modules/@paralleldrive/cuid2/node_modules/@noble/hashes": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", - "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@rolldown/binding-android-arm64": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.9.tgz", - "integrity": "sha512-lcJL0bN5hpgJfSIz/8PIf02irmyL43P+j1pTCfbD1DbLkmGRuFIA4DD3B3ZOvGqG0XiVvRznbKtN0COQVaKUTg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.9.tgz", - "integrity": "sha512-J7Zk3kLYFsLtuH6U+F4pS2sYVzac0qkjcO5QxHS7OS7yZu2LRs+IXo+uvJ/mvpyUljDJ3LROZPoQfgBIpCMhdQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.9.tgz", - "integrity": "sha512-iwtmmghy8nhfRGeNAIltcNXzD0QMNaaA5U/NyZc1Ia4bxrzFByNMDoppoC+hl7cDiUq5/1CnFthpT9n+UtfFyg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.9.tgz", - "integrity": "sha512-DLFYI78SCiZr5VvdEplsVC2Vx53lnA4/Ga5C65iyldMVaErr86aiqCoNBLl92PXPfDtUYjUh+xFFor40ueNs4Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.9.tgz", - "integrity": "sha512-CsjTmTwd0Hri6iTw/DRMK7kOZ7FwAkrO4h8YWKoX/kcj833e4coqo2wzIFywtch/8Eb5enQ/lwLM7w6JX1W5RQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.9.tgz", - "integrity": "sha512-2x9O2JbSPxpxMDhP9Z74mahAStibTlrBMW0520+epJH5sac7/LwZW5Bmg/E6CXuEF53JJFW509uP+lSedaUNxg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.9.tgz", - "integrity": "sha512-JA1QRW31ogheAIRhIg9tjMfsYbglXXYGNPLdPEYrwFxdbkQCAzvpSCSHCDWNl4hTtrol8WeboCSEpjdZK8qrCg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.9.tgz", - "integrity": "sha512-aOKU9dJheda8Kj8Y3w9gnt9QFOO+qKPAl8SWd7JPHP+Cu0EuDAE5wokQubLzIDQWg2myXq2XhTpOVS07qqvT+w==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.9.tgz", - "integrity": "sha512-OalO94fqj7IWRn3VdXWty75jC5dk4C197AWEuMhIpvVv2lw9fiPhud0+bW2ctCxb3YoBZor71QHbY+9/WToadA==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.9.tgz", - "integrity": "sha512-cVEl1vZtBsBZna3YMjGXNvnYYrOJ7RzuWvZU0ffvJUexWkukMaDuGhUXn0rjnV0ptzGVkvc+vW9Yqy6h8YX4pg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.9.tgz", - "integrity": "sha512-UzYnKCIIc4heAKgI4PZ3dfBGUZefGCJ1TPDuLHoCzgrMYPb5Rv6TLFuYtyM4rWyHM7hymNdsg5ik2C+UD9VDbA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.9.tgz", - "integrity": "sha512-+6zoiF+RRyf5cdlFQP7nm58mq7+/2PFaY2DNQeD4B87N36JzfF/l9mdBkkmTvSYcYPE8tMh/o3cRlsx1ldLfog==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.9.tgz", - "integrity": "sha512-rgFN6sA/dyebil3YTlL2evvi/M+ivhfnyxec7AccTpRPccno/rPoNlqybEZQBkcbZu8Hy+eqNJCqfBR8P7Pg8g==", - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@napi-rs/wasm-runtime": "^1.1.1" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.9.tgz", - "integrity": "sha512-lHVNUG/8nlF1IQk1C0Ci574qKYyty2goMiPlRqkC5R+3LkXDkL5Dhx8ytbxq35m+pkHVIvIxviD+TWLdfeuadA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.9.tgz", - "integrity": "sha512-G0oA4+w1iY5AGi5HcDTxWsoxF509hrFIPB2rduV5aDqS9FtDg1CAfa7V34qImbjfhIcA8C+RekocJZA96EarwQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/pluginutils": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.9.tgz", - "integrity": "sha512-w6oiRWgEBl04QkFZgmW+jnU1EC9b57Oihi2ot3HNWIQRqgHp5PnYDia5iZ5FF7rpa4EQdiqMDXjlqKGXBhsoXw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@standard-schema/spec": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", - "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tybys/wasm-util": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz", - "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@types/body-parser": { - "version": "1.19.6", - "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", - "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/connect": "*", - "@types/node": "*" - } - }, - "node_modules/@types/chai": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", - "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/deep-eql": "*", - "assertion-error": "^2.0.1" - } - }, - "node_modules/@types/connect": { - "version": "3.4.38", - "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", - "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/cookiejar": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@types/cookiejar/-/cookiejar-2.1.5.tgz", - "integrity": "sha512-he+DHOWReW0nghN24E1WUqM0efK4kI9oTqDm6XmK8ZPe2djZ90BSNdGnIyCLzCPw7/pogPlGbzI2wHGGmi4O/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/cors": { - "version": "2.8.19", - "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz", - "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/deep-eql": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", - "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/estree": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", - "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/express": { - "version": "4.17.25", - "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.25.tgz", - "integrity": "sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/body-parser": "*", - "@types/express-serve-static-core": "^4.17.33", - "@types/qs": "*", - "@types/serve-static": "^1" - } - }, - "node_modules/@types/express-serve-static-core": { - "version": "4.19.8", - "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.8.tgz", - "integrity": "sha512-02S5fmqeoKzVZCHPZid4b8JH2eM5HzQLZWN2FohQEy/0eXTq8VXZfSN6Pcr3F6N9R/vNrj7cpgbhjie6m/1tCA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "@types/qs": "*", - "@types/range-parser": "*", - "@types/send": "*" - } - }, - "node_modules/@types/http-errors": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", - "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/jsonwebtoken": { - "version": "9.0.10", - "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz", - "integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/ms": "*", - "@types/node": "*" - } - }, - "node_modules/@types/methods": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz", - "integrity": "sha512-ymXWVrDiCxTBE3+RIrrP533E70eA+9qu7zdWoHuOmGujkYtzf4HQF96b8nwHLqhuf4ykX61IGRIB38CC6/sImQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/mime": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", - "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/ms": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", - "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "20.19.37", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.37.tgz", - "integrity": "sha512-8kzdPJ3FsNsVIurqBs7oodNnCEVbni9yUEkaHbgptDACOPW04jimGagZ51E6+lXUwJjgnBw+hyko/lkFWCldqw==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~6.21.0" - } - }, - "node_modules/@types/pg": { - "version": "8.18.0", - "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.18.0.tgz", - "integrity": "sha512-gT+oueVQkqnj6ajGJXblFR4iavIXWsGAFCk3dP4Kki5+a9R4NMt0JARdk6s8cUKcfUoqP5dAtDSLU8xYUTFV+Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "pg-protocol": "*", - "pg-types": "^2.2.0" - } - }, - "node_modules/@types/qs": { - "version": "6.15.0", - "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.0.tgz", - "integrity": "sha512-JawvT8iBVWpzTrz3EGw9BTQFg3BQNmwERdKE22vlTxawwtbyUSlMppvZYKLZzB5zgACXdXxbD3m1bXaMqP/9ow==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/range-parser": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", - "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/send": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", - "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/serve-static": { - "version": "1.15.10", - "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.10.tgz", - "integrity": "sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/http-errors": "*", - "@types/node": "*", - "@types/send": "<1" - } - }, - "node_modules/@types/serve-static/node_modules/@types/send": { - "version": "0.17.6", - "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.6.tgz", - "integrity": "sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/mime": "^1", - "@types/node": "*" - } - }, - "node_modules/@types/superagent": { - "version": "8.1.9", - "resolved": "https://registry.npmjs.org/@types/superagent/-/superagent-8.1.9.tgz", - "integrity": "sha512-pTVjI73witn+9ILmoJdajHGW2jkSaOzhiFYF1Rd3EQ94kymLqB9PjD9ISg7WaALC7+dCHT0FGe9T2LktLq/3GQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/cookiejar": "^2.1.5", - "@types/methods": "^1.1.4", - "@types/node": "*", - "form-data": "^4.0.0" - } - }, - "node_modules/@types/supertest": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@types/supertest/-/supertest-7.2.0.tgz", - "integrity": "sha512-uh2Lv57xvggst6lCqNdFAmDSvoMG7M/HDtX4iUCquxQ5EGPtaPM5PL5Hmi7LCvOG8db7YaCPNJEeoI8s/WzIQw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/methods": "^1.1.4", - "@types/superagent": "^8.1.0" - } - }, - "node_modules/@types/uuid": { - "version": "9.0.8", - "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.8.tgz", - "integrity": "sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/ws": { - "version": "8.18.1", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", - "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@vitest/expect": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.0.tgz", - "integrity": "sha512-EIxG7k4wlWweuCLG9Y5InKFwpMEOyrMb6ZJ1ihYu02LVj/bzUwn2VMU+13PinsjRW75XnITeFrQBMH5+dLvCDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@standard-schema/spec": "^1.1.0", - "@types/chai": "^5.2.2", - "@vitest/spy": "4.1.0", - "@vitest/utils": "4.1.0", - "chai": "^6.2.2", - "tinyrainbow": "^3.0.3" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/mocker": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.0.tgz", - "integrity": "sha512-evxREh+Hork43+Y4IOhTo+h5lGmVRyjqI739Rz4RlUPqwrkFFDF6EMvOOYjTx4E8Tl6gyCLRL8Mu7Ry12a13Tw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/spy": "4.1.0", - "estree-walker": "^3.0.3", - "magic-string": "^0.30.21" - }, - "funding": { - "url": "https://opencollective.com/vitest" - }, - "peerDependencies": { - "msw": "^2.4.9", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0-0" - }, - "peerDependenciesMeta": { - "msw": { - "optional": true - }, - "vite": { - "optional": true - } - } - }, - "node_modules/@vitest/pretty-format": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.0.tgz", - "integrity": "sha512-3RZLZlh88Ib0J7NQTRATfc/3ZPOnSUn2uDBUoGNn5T36+bALixmzphN26OUD3LRXWkJu4H0s5vvUeqBiw+kS0A==", - "dev": true, - "license": "MIT", - "dependencies": { - "tinyrainbow": "^3.0.3" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/runner": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.0.tgz", - "integrity": "sha512-Duvx2OzQ7d6OjchL+trw+aSrb9idh7pnNfxrklo14p3zmNL4qPCDeIJAK+eBKYjkIwG96Bc6vYuxhqDXQOWpoQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/utils": "4.1.0", - "pathe": "^2.0.3" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/snapshot": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.0.tgz", - "integrity": "sha512-0Vy9euT1kgsnj1CHttwi9i9o+4rRLEaPRSOJ5gyv579GJkNpgJK+B4HSv/rAWixx2wdAFci1X4CEPjiu2bXIMg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/pretty-format": "4.1.0", - "@vitest/utils": "4.1.0", - "magic-string": "^0.30.21", - "pathe": "^2.0.3" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/spy": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.0.tgz", - "integrity": "sha512-pz77k+PgNpyMDv2FV6qmk5ZVau6c3R8HC8v342T2xlFxQKTrSeYw9waIJG8KgV9fFwAtTu4ceRzMivPTH6wSxw==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/utils": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.0.tgz", - "integrity": "sha512-XfPXT6a8TZY3dcGY8EdwsBulFCIw+BeeX0RZn2x/BtiY/75YGh8FeWGG8QISN/WhaqSrE2OrlDgtF8q5uhOTmw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/pretty-format": "4.1.0", - "convert-source-map": "^2.0.0", - "tinyrainbow": "^3.0.3" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/accepts": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", - "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", - "license": "MIT", - "dependencies": { - "mime-types": "~2.1.34", - "negotiator": "0.6.3" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/array-flatten": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", - "license": "MIT" - }, - "node_modules/asap": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", - "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", - "dev": true, - "license": "MIT" - }, - "node_modules/assertion-error": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", - "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - } - }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/base-x": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/base-x/-/base-x-5.0.1.tgz", - "integrity": "sha512-M7uio8Zt++eg3jPj+rHMfCC+IuygQHHCOU+IYsVtik6FWjuYpVt/+MRKcgsAMHh8mMFAwnB+Bs+mTrFiXjMzKg==", - "license": "MIT" - }, - "node_modules/bech32": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/bech32/-/bech32-2.0.0.tgz", - "integrity": "sha512-LcknSilhIGatDAsY1ak2I8VtGaHNhgMSYVxFrGLXv+xLHytaKZKcaUJJUE7qmBr7h33o5YQwP55pMI0xmkpJwg==", - "license": "MIT" - }, - "node_modules/bintrees": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/bintrees/-/bintrees-1.0.2.tgz", - "integrity": "sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==", - "license": "MIT" - }, - "node_modules/bip174": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/bip174/-/bip174-3.0.0.tgz", - "integrity": "sha512-N3vz3rqikLEu0d6yQL8GTrSkpYb35NQKWMR7Hlza0lOj6ZOlvQ3Xr7N9Y+JPebaCVoEUHdBeBSuLxcHr71r+Lw==", - "license": "MIT", - "dependencies": { - "uint8array-tools": "^0.0.9", - "varuint-bitcoin": "^2.0.0" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/bitcoinjs-lib": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/bitcoinjs-lib/-/bitcoinjs-lib-7.0.1.tgz", - "integrity": "sha512-vwEmpL5Tpj0I0RBdNkcDMXePoaYSTeKY6mL6/l5esbnTs+jGdPDuLp4NY1hSh6Zk5wSgePygZ4Wx5JJao30Pww==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "^1.2.0", - "bech32": "^2.0.0", - "bip174": "^3.0.0", - "bs58check": "^4.0.0", - "uint8array-tools": "^0.0.9", - "valibot": "^1.2.0", - "varuint-bitcoin": "^2.0.0" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/bitcoinjs-lib/node_modules/@noble/hashes": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", - "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/body-parser": { - "version": "1.20.4", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", - "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", - "license": "MIT", - "dependencies": { - "bytes": "~3.1.2", - "content-type": "~1.0.5", - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "~1.2.0", - "http-errors": "~2.0.1", - "iconv-lite": "~0.4.24", - "on-finished": "~2.4.1", - "qs": "~6.14.0", - "raw-body": "~2.5.3", - "type-is": "~1.6.18", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/bs58": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/bs58/-/bs58-6.0.0.tgz", - "integrity": "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw==", - "license": "MIT", - "dependencies": { - "base-x": "^5.0.0" - } - }, - "node_modules/bs58check": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/bs58check/-/bs58check-4.0.0.tgz", - "integrity": "sha512-FsGDOnFg9aVI9erdriULkd/JjEWONV/lQE5aYziB5PoBsXRind56lh8doIZIc9X4HoxT5x4bLjMWN1/NB8Zp5g==", - "license": "MIT", - "dependencies": { - "@noble/hashes": "^1.2.0", - "bs58": "^6.0.0" - } - }, - "node_modules/bs58check/node_modules/@noble/hashes": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", - "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/buffer-equal-constant-time": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", - "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", - "license": "BSD-3-Clause" - }, - "node_modules/bytes": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", - "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/call-bound": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", - "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "get-intrinsic": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/chai": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", - "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/cluster-key-slot": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz", - "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==", - "license": "Apache-2.0", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "dev": true, - "license": "MIT", - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/component-emitter": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.1.tgz", - "integrity": "sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/content-disposition": { - "version": "0.5.4", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", - "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", - "license": "MIT", - "dependencies": { - "safe-buffer": "5.2.1" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/content-type": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", - "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", - "dev": true, - "license": "MIT" - }, - "node_modules/cookie": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", - "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie-signature": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", - "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", - "license": "MIT" - }, - "node_modules/cookiejar": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/cookiejar/-/cookiejar-2.1.4.tgz", - "integrity": "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==", - "dev": true, - "license": "MIT" - }, - "node_modules/cors": { - "version": "2.8.6", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", - "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", - "license": "MIT", - "dependencies": { - "object-assign": "^4", - "vary": "^1" - }, - "engines": { - "node": ">= 0.10" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "license": "MIT", - "dependencies": { - "ms": "2.0.0" - } - }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/denque": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", - "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", - "license": "Apache-2.0", - "engines": { - "node": ">=0.10" - } - }, - "node_modules/depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/destroy": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", - "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", - "license": "MIT", - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, - "node_modules/dezalgo": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/dezalgo/-/dezalgo-1.0.4.tgz", - "integrity": "sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==", - "dev": true, - "license": "ISC", - "dependencies": { - "asap": "^2.0.0", - "wrappy": "1" - } - }, - "node_modules/dotenv": { - "version": "16.6.1", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", - "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", - "license": "BSD-2-Clause", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://dotenvx.com" - } - }, - "node_modules/dunder-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", - "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/ecdsa-sig-formatter": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", - "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", - "license": "Apache-2.0", - "dependencies": { - "safe-buffer": "^5.0.1" - } - }, - "node_modules/ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", - "license": "MIT" - }, - "node_modules/encodeurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", - "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/es-define-property": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", - "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-module-lexer": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.0.0.tgz", - "integrity": "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==", - "dev": true, - "license": "MIT" - }, - "node_modules/es-object-atoms": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", - "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-set-tostringtag": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", - "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/esbuild": { - "version": "0.27.3", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz", - "integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.27.3", - "@esbuild/android-arm": "0.27.3", - "@esbuild/android-arm64": "0.27.3", - "@esbuild/android-x64": "0.27.3", - "@esbuild/darwin-arm64": "0.27.3", - "@esbuild/darwin-x64": "0.27.3", - "@esbuild/freebsd-arm64": "0.27.3", - "@esbuild/freebsd-x64": "0.27.3", - "@esbuild/linux-arm": "0.27.3", - "@esbuild/linux-arm64": "0.27.3", - "@esbuild/linux-ia32": "0.27.3", - "@esbuild/linux-loong64": "0.27.3", - "@esbuild/linux-mips64el": "0.27.3", - "@esbuild/linux-ppc64": "0.27.3", - "@esbuild/linux-riscv64": "0.27.3", - "@esbuild/linux-s390x": "0.27.3", - "@esbuild/linux-x64": "0.27.3", - "@esbuild/netbsd-arm64": "0.27.3", - "@esbuild/netbsd-x64": "0.27.3", - "@esbuild/openbsd-arm64": "0.27.3", - "@esbuild/openbsd-x64": "0.27.3", - "@esbuild/openharmony-arm64": "0.27.3", - "@esbuild/sunos-x64": "0.27.3", - "@esbuild/win32-arm64": "0.27.3", - "@esbuild/win32-ia32": "0.27.3", - "@esbuild/win32-x64": "0.27.3" - } - }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", - "license": "MIT" - }, - "node_modules/estree-walker": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", - "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "^1.0.0" - } - }, - "node_modules/etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/expect-type": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", - "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=12.0.0" - } - }, - "node_modules/express": { - "version": "4.22.1", - "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", - "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", - "license": "MIT", - "dependencies": { - "accepts": "~1.3.8", - "array-flatten": "1.1.1", - "body-parser": "~1.20.3", - "content-disposition": "~0.5.4", - "content-type": "~1.0.4", - "cookie": "~0.7.1", - "cookie-signature": "~1.0.6", - "debug": "2.6.9", - "depd": "2.0.0", - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "finalhandler": "~1.3.1", - "fresh": "~0.5.2", - "http-errors": "~2.0.0", - "merge-descriptors": "1.0.3", - "methods": "~1.1.2", - "on-finished": "~2.4.1", - "parseurl": "~1.3.3", - "path-to-regexp": "~0.1.12", - "proxy-addr": "~2.0.7", - "qs": "~6.14.0", - "range-parser": "~1.2.1", - "safe-buffer": "5.2.1", - "send": "~0.19.0", - "serve-static": "~1.16.2", - "setprototypeof": "1.2.0", - "statuses": "~2.0.1", - "type-is": "~1.6.18", - "utils-merge": "1.0.1", - "vary": "~1.1.2" - }, - "engines": { - "node": ">= 0.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/express-rate-limit": { - "version": "7.5.1", - "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.1.tgz", - "integrity": "sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw==", - "license": "MIT", - "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://github.com/sponsors/express-rate-limit" - }, - "peerDependencies": { - "express": ">= 4.11" - } - }, - "node_modules/fast-safe-stringify": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", - "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", - "dev": true, - "license": "MIT" - }, - "node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/finalhandler": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", - "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", - "license": "MIT", - "dependencies": { - "debug": "2.6.9", - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "on-finished": "~2.4.1", - "parseurl": "~1.3.3", - "statuses": "~2.0.2", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/form-data": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", - "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", - "dev": true, - "license": "MIT", - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/formidable": { - "version": "3.5.4", - "resolved": "https://registry.npmjs.org/formidable/-/formidable-3.5.4.tgz", - "integrity": "sha512-YikH+7CUTOtP44ZTnUhR7Ic2UASBPOqmaRkRKxRbywPTe5VxF7RRCck4af9wutiZ/QKM5nME9Bie2fFaPz5Gug==", - "dev": true, - "license": "MIT", - "dependencies": { - "@paralleldrive/cuid2": "^2.2.2", - "dezalgo": "^1.0.4", - "once": "^1.4.0" - }, - "engines": { - "node": ">=14.0.0" - }, - "funding": { - "url": "https://ko-fi.com/tunnckoCore/commissions" - } - }, - "node_modules/forwarded": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", - "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-intrinsic": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", - "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "function-bind": "^1.1.2", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", - "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "license": "MIT", - "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/get-tsconfig": { - "version": "4.13.6", - "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.6.tgz", - "integrity": "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw==", - "dev": true, - "license": "MIT", - "dependencies": { - "resolve-pkg-maps": "^1.0.0" - }, - "funding": { - "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" - } - }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-symbols": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", - "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-tostringtag": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", - "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-symbols": "^1.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/helmet": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/helmet/-/helmet-7.2.0.tgz", - "integrity": "sha512-ZRiwvN089JfMXokizgqEPXsl2Guk094yExfoDXR0cBYWxtBbaSww/w+vT4WEJsBW2iTUi1GgZ6swmoug3Oy4Xw==", - "license": "MIT", - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/http-errors": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", - "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", - "license": "MIT", - "dependencies": { - "depd": "~2.0.0", - "inherits": "~2.0.4", - "setprototypeof": "~1.2.0", - "statuses": "~2.0.2", - "toidentifier": "~1.0.1" - }, - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/iconv-lite": { - "version": "0.4.24", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/ioredis": { - "version": "5.10.0", - "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.10.0.tgz", - "integrity": "sha512-HVBe9OFuqs+Z6n64q09PQvP1/R4Bm+30PAyyD4wIEqssh3v9L21QjCVk4kRLucMBcDokJTcLjsGeVRlq/nH6DA==", - "license": "MIT", - "dependencies": { - "@ioredis/commands": "1.5.1", - "cluster-key-slot": "^1.1.0", - "debug": "^4.3.4", - "denque": "^2.1.0", - "lodash.defaults": "^4.2.0", - "lodash.isarguments": "^3.1.0", - "redis-errors": "^1.2.0", - "redis-parser": "^3.0.0", - "standard-as-callback": "^2.1.0" - }, - "engines": { - "node": ">=12.22.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/ioredis" - } - }, - "node_modules/ioredis/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/ioredis/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/ipaddr.js": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "license": "MIT", - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/jsonwebtoken": { - "version": "9.0.3", - "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", - "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==", - "license": "MIT", - "dependencies": { - "jws": "^4.0.1", - "lodash.includes": "^4.3.0", - "lodash.isboolean": "^3.0.3", - "lodash.isinteger": "^4.0.4", - "lodash.isnumber": "^3.0.3", - "lodash.isplainobject": "^4.0.6", - "lodash.isstring": "^4.0.1", - "lodash.once": "^4.0.0", - "ms": "^2.1.1", - "semver": "^7.5.4" - }, - "engines": { - "node": ">=12", - "npm": ">=6" - } - }, - "node_modules/jsonwebtoken/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/jwa": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", - "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", - "license": "MIT", - "dependencies": { - "buffer-equal-constant-time": "^1.0.1", - "ecdsa-sig-formatter": "1.0.11", - "safe-buffer": "^5.0.1" - } - }, - "node_modules/jws": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", - "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", - "license": "MIT", - "dependencies": { - "jwa": "^2.0.1", - "safe-buffer": "^5.0.1" - } - }, - "node_modules/lightningcss": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", - "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", - "dev": true, - "license": "MPL-2.0", - "dependencies": { - "detect-libc": "^2.0.3" - }, - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - }, - "optionalDependencies": { - "lightningcss-android-arm64": "1.32.0", - "lightningcss-darwin-arm64": "1.32.0", - "lightningcss-darwin-x64": "1.32.0", - "lightningcss-freebsd-x64": "1.32.0", - "lightningcss-linux-arm-gnueabihf": "1.32.0", - "lightningcss-linux-arm64-gnu": "1.32.0", - "lightningcss-linux-arm64-musl": "1.32.0", - "lightningcss-linux-x64-gnu": "1.32.0", - "lightningcss-linux-x64-musl": "1.32.0", - "lightningcss-win32-arm64-msvc": "1.32.0", - "lightningcss-win32-x64-msvc": "1.32.0" - } - }, - "node_modules/lightningcss-android-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", - "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", - "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-darwin-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", - "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-freebsd-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", - "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", - "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", - "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-arm64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", - "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", - "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-linux-x64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", - "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", - "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lightningcss-win32-x64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", - "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MPL-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 12.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/lodash.defaults": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", - "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==", - "license": "MIT" - }, - "node_modules/lodash.includes": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", - "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", - "license": "MIT" - }, - "node_modules/lodash.isarguments": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", - "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==", - "license": "MIT" - }, - "node_modules/lodash.isboolean": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", - "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", - "license": "MIT" - }, - "node_modules/lodash.isinteger": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", - "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", - "license": "MIT" - }, - "node_modules/lodash.isnumber": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", - "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", - "license": "MIT" - }, - "node_modules/lodash.isplainobject": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", - "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", - "license": "MIT" - }, - "node_modules/lodash.isstring": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", - "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", - "license": "MIT" - }, - "node_modules/lodash.once": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", - "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", - "license": "MIT" - }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" - } - }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/media-typer": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/merge-descriptors": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", - "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/methods": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", - "license": "MIT", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", - "license": "MIT" - }, - "node_modules/nanoid": { - "version": "3.3.11", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", - "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/negotiator": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", - "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-inspect": { - "version": "1.13.4", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", - "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/obug": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz", - "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==", - "dev": true, - "funding": [ - "https://github.com/sponsors/sxzz", - "https://opencollective.com/debug" - ], - "license": "MIT" - }, - "node_modules/on-finished": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", - "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", - "license": "MIT", - "dependencies": { - "ee-first": "1.1.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/parseurl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/path-to-regexp": { - "version": "0.1.12", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", - "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", - "license": "MIT" - }, - "node_modules/pathe": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", - "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", - "dev": true, - "license": "MIT" - }, - "node_modules/pg": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz", - "integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==", - "license": "MIT", - "dependencies": { - "pg-connection-string": "^2.12.0", - "pg-pool": "^3.13.0", - "pg-protocol": "^1.13.0", - "pg-types": "2.2.0", - "pgpass": "1.0.5" - }, - "engines": { - "node": ">= 16.0.0" - }, - "optionalDependencies": { - "pg-cloudflare": "^1.3.0" - }, - "peerDependencies": { - "pg-native": ">=3.0.1" - }, - "peerDependenciesMeta": { - "pg-native": { - "optional": true - } - } - }, - "node_modules/pg-cloudflare": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz", - "integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==", - "license": "MIT", - "optional": true - }, - "node_modules/pg-connection-string": { - "version": "2.12.0", - "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.12.0.tgz", - "integrity": "sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==", - "license": "MIT" - }, - "node_modules/pg-int8": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", - "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", - "license": "ISC", - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/pg-pool": { - "version": "3.13.0", - "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.13.0.tgz", - "integrity": "sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==", - "license": "MIT", - "peerDependencies": { - "pg": ">=8.0" - } - }, - "node_modules/pg-protocol": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.13.0.tgz", - "integrity": "sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==", - "license": "MIT" - }, - "node_modules/pg-types": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", - "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", - "license": "MIT", - "dependencies": { - "pg-int8": "1.0.1", - "postgres-array": "~2.0.0", - "postgres-bytea": "~1.0.0", - "postgres-date": "~1.0.4", - "postgres-interval": "^1.1.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/pgpass": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", - "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", - "license": "MIT", - "dependencies": { - "split2": "^4.1.0" - } - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", - "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/postcss": { - "version": "8.5.8", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", - "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.11", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/postgres-array": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", - "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/postgres-bytea": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", - "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postgres-date": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", - "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/postgres-interval": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", - "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", - "license": "MIT", - "dependencies": { - "xtend": "^4.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/prom-client": { - "version": "15.1.3", - "resolved": "https://registry.npmjs.org/prom-client/-/prom-client-15.1.3.tgz", - "integrity": "sha512-6ZiOBfCywsD4k1BN9IX0uZhF+tJkV8q8llP64G5Hajs4JOeVLPCwpPVcpXy3BwYiUGgyJzsJJQeOIv7+hDSq8g==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/api": "^1.4.0", - "tdigest": "^0.1.1" - }, - "engines": { - "node": "^16 || ^18 || >=20" - } - }, - "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", - "license": "MIT", - "dependencies": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/qs": { - "version": "6.14.2", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz", - "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==", - "license": "BSD-3-Clause", - "dependencies": { - "side-channel": "^1.1.0" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/range-parser": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", - "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/raw-body": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", - "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", - "license": "MIT", - "dependencies": { - "bytes": "~3.1.2", - "http-errors": "~2.0.1", - "iconv-lite": "~0.4.24", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/redis-errors": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz", - "integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==", - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/redis-parser": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz", - "integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==", - "license": "MIT", - "dependencies": { - "redis-errors": "^1.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/resolve-pkg-maps": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", - "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" - } - }, - "node_modules/rolldown": { - "version": "1.0.0-rc.9", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.9.tgz", - "integrity": "sha512-9EbgWge7ZH+yqb4d2EnELAntgPTWbfL8ajiTW+SyhJEC4qhBbkCKbqFV4Ge4zmu5ziQuVbWxb/XwLZ+RIO7E8Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@oxc-project/types": "=0.115.0", - "@rolldown/pluginutils": "1.0.0-rc.9" - }, - "bin": { - "rolldown": "bin/cli.mjs" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "optionalDependencies": { - "@rolldown/binding-android-arm64": "1.0.0-rc.9", - "@rolldown/binding-darwin-arm64": "1.0.0-rc.9", - "@rolldown/binding-darwin-x64": "1.0.0-rc.9", - "@rolldown/binding-freebsd-x64": "1.0.0-rc.9", - "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.9", - "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.9", - "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.9", - "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.9", - "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.9", - "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.9", - "@rolldown/binding-linux-x64-musl": "1.0.0-rc.9", - "@rolldown/binding-openharmony-arm64": "1.0.0-rc.9", - "@rolldown/binding-wasm32-wasi": "1.0.0-rc.9", - "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.9", - "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.9" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "license": "MIT" - }, - "node_modules/semver": { - "version": "7.7.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", - "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/send": { - "version": "0.19.2", - "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", - "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", - "license": "MIT", - "dependencies": { - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "fresh": "~0.5.2", - "http-errors": "~2.0.1", - "mime": "1.6.0", - "ms": "2.1.3", - "on-finished": "~2.4.1", - "range-parser": "~1.2.1", - "statuses": "~2.0.2" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/send/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT" - }, - "node_modules/serve-static": { - "version": "1.16.3", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", - "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", - "license": "MIT", - "dependencies": { - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "parseurl": "~1.3.3", - "send": "~0.19.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/setprototypeof": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", - "license": "ISC" - }, - "node_modules/side-channel": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", - "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.3", - "side-channel-list": "^1.0.0", - "side-channel-map": "^1.0.1", - "side-channel-weakmap": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-list": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", - "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-map": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", - "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-weakmap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", - "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3", - "side-channel-map": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/siginfo": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", - "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", - "dev": true, - "license": "ISC" - }, - "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/split2": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", - "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", - "license": "ISC", - "engines": { - "node": ">= 10.x" - } - }, - "node_modules/stackback": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", - "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", - "dev": true, - "license": "MIT" - }, - "node_modules/standard-as-callback": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz", - "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==", - "license": "MIT" - }, - "node_modules/statuses": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", - "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/std-env": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.0.0.tgz", - "integrity": "sha512-zUMPtQ/HBY3/50VbpkupYHbRroTRZJPRLvreamgErJVys0ceuzMkD44J/QjqhHjOzK42GQ3QZIeFG1OYfOtKqQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/superagent": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/superagent/-/superagent-10.3.0.tgz", - "integrity": "sha512-B+4Ik7ROgVKrQsXTV0Jwp2u+PXYLSlqtDAhYnkkD+zn3yg8s/zjA2MeGayPoY/KICrbitwneDHrjSotxKL+0XQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "component-emitter": "^1.3.1", - "cookiejar": "^2.1.4", - "debug": "^4.3.7", - "fast-safe-stringify": "^2.1.1", - "form-data": "^4.0.5", - "formidable": "^3.5.4", - "methods": "^1.1.2", - "mime": "2.6.0", - "qs": "^6.14.1" - }, - "engines": { - "node": ">=14.18.0" - } - }, - "node_modules/superagent/node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/superagent/node_modules/mime": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", - "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", - "dev": true, - "license": "MIT", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/superagent/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "dev": true, - "license": "MIT" - }, - "node_modules/supertest": { - "version": "7.2.2", - "resolved": "https://registry.npmjs.org/supertest/-/supertest-7.2.2.tgz", - "integrity": "sha512-oK8WG9diS3DlhdUkcFn4tkNIiIbBx9lI2ClF8K+b2/m8Eyv47LSawxUzZQSNKUrVb2KsqeTDCcjAAVPYaSLVTA==", - "dev": true, - "license": "MIT", - "dependencies": { - "cookie-signature": "^1.2.2", - "methods": "^1.1.2", - "superagent": "^10.3.0" - }, - "engines": { - "node": ">=14.18.0" - } - }, - "node_modules/supertest/node_modules/cookie-signature": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", - "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.6.0" - } - }, - "node_modules/tdigest": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/tdigest/-/tdigest-0.1.2.tgz", - "integrity": "sha512-+G0LLgjjo9BZX2MfdvPfH+MKLCrxlXSYec5DaPYP1fe6Iyhf0/fSmJ0bFiZ1F8BT6cGXl2LpltQptzjXKWEkKA==", - "license": "MIT", - "dependencies": { - "bintrees": "1.0.2" - } - }, - "node_modules/tinybench": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", - "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", - "dev": true, - "license": "MIT" - }, - "node_modules/tinyexec": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.4.tgz", - "integrity": "sha512-u9r3uZC0bdpGOXtlxUIdwf9pkmvhqJdrVCH9fapQtgy/OeTTMZ1nqH7agtvEfmGui6e1XxjcdrlxvxJvc3sMqw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/tinyglobby": { - "version": "0.2.15", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", - "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "fdir": "^6.5.0", - "picomatch": "^4.0.3" - }, - "engines": { - "node": ">=12.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/SuperchupuDev" - } - }, - "node_modules/tinyrainbow": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", - "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/toidentifier": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "license": "MIT", - "engines": { - "node": ">=0.6" - } - }, - "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "dev": true, - "license": "0BSD", - "optional": true - }, - "node_modules/tsx": { - "version": "4.21.0", - "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz", - "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", - "dev": true, - "license": "MIT", - "dependencies": { - "esbuild": "~0.27.0", - "get-tsconfig": "^4.7.5" - }, - "bin": { - "tsx": "dist/cli.mjs" - }, - "engines": { - "node": ">=18.0.0" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - } - }, - "node_modules/type-is": { - "version": "1.6.18", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", - "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", - "license": "MIT", - "dependencies": { - "media-typer": "0.3.0", - "mime-types": "~2.1.24" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", - "devOptional": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/uint8array-tools": { - "version": "0.0.9", - "resolved": "https://registry.npmjs.org/uint8array-tools/-/uint8array-tools-0.0.9.tgz", - "integrity": "sha512-9vqDWmoSXOoi+K14zNaf6LBV51Q8MayF0/IiQs3GlygIKUYtog603e6virExkjjFosfJUBI4LhbQK1iq8IG11A==", - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", - "license": "MIT", - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/uuid": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", - "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", - "funding": [ - "https://github.com/sponsors/broofa", - "https://github.com/sponsors/ctavan" - ], - "license": "MIT", - "bin": { - "uuid": "dist/bin/uuid" - } - }, - "node_modules/valibot": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/valibot/-/valibot-1.2.0.tgz", - "integrity": "sha512-mm1rxUsmOxzrwnX5arGS+U4T25RdvpPjPN4yR0u9pUBov9+zGVtO84tif1eY4r6zWxVxu3KzIyknJy3rxfRZZg==", - "license": "MIT", - "peerDependencies": { - "typescript": ">=5" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/varuint-bitcoin": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/varuint-bitcoin/-/varuint-bitcoin-2.0.0.tgz", - "integrity": "sha512-6QZbU/rHO2ZQYpWFDALCDSRsXbAs1VOEmXAxtbtjLtKuMJ/FQ8YbhfxlaiKv5nklci0M6lZtlZyxo9Q+qNnyog==", - "license": "MIT", - "dependencies": { - "uint8array-tools": "^0.0.8" - } - }, - "node_modules/varuint-bitcoin/node_modules/uint8array-tools": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/uint8array-tools/-/uint8array-tools-0.0.8.tgz", - "integrity": "sha512-xS6+s8e0Xbx++5/0L+yyexukU7pz//Yg6IHg3BKhXotg1JcYtgxVcUctQ0HxLByiJzpAkNFawz1Nz5Xadzo82g==", - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/vite": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.0.tgz", - "integrity": "sha512-fPGaRNj9Zytaf8LEiBhY7Z6ijnFKdzU/+mL8EFBaKr7Vw1/FWcTBAMW0wLPJAGMPX38ZPVCVgLceWiEqeoqL2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@oxc-project/runtime": "0.115.0", - "lightningcss": "^1.32.0", - "picomatch": "^4.0.3", - "postcss": "^8.5.8", - "rolldown": "1.0.0-rc.9", - "tinyglobby": "^0.2.15" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^20.19.0 || >=22.12.0", - "@vitejs/devtools": "^0.0.0-alpha.31", - "esbuild": "^0.27.0", - "jiti": ">=1.21.0", - "less": "^4.0.0", - "sass": "^1.70.0", - "sass-embedded": "^1.70.0", - "stylus": ">=0.54.8", - "sugarss": "^5.0.0", - "terser": "^5.16.0", - "tsx": "^4.8.1", - "yaml": "^2.4.2" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "@vitejs/devtools": { - "optional": true - }, - "esbuild": { - "optional": true - }, - "jiti": { - "optional": true - }, - "less": { - "optional": true - }, - "sass": { - "optional": true - }, - "sass-embedded": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - }, - "tsx": { - "optional": true - }, - "yaml": { - "optional": true - } - } - }, - "node_modules/vitest": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.0.tgz", - "integrity": "sha512-YbDrMF9jM2Lqc++2530UourxZHmkKLxrs4+mYhEwqWS97WJ7wOYEkcr+QfRgJ3PW9wz3odRijLZjHEaRLTNbqw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/expect": "4.1.0", - "@vitest/mocker": "4.1.0", - "@vitest/pretty-format": "4.1.0", - "@vitest/runner": "4.1.0", - "@vitest/snapshot": "4.1.0", - "@vitest/spy": "4.1.0", - "@vitest/utils": "4.1.0", - "es-module-lexer": "^2.0.0", - "expect-type": "^1.3.0", - "magic-string": "^0.30.21", - "obug": "^2.1.1", - "pathe": "^2.0.3", - "picomatch": "^4.0.3", - "std-env": "^4.0.0-rc.1", - "tinybench": "^2.9.0", - "tinyexec": "^1.0.2", - "tinyglobby": "^0.2.15", - "tinyrainbow": "^3.0.3", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0-0", - "why-is-node-running": "^2.3.0" - }, - "bin": { - "vitest": "vitest.mjs" - }, - "engines": { - "node": "^20.0.0 || ^22.0.0 || >=24.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - }, - "peerDependencies": { - "@edge-runtime/vm": "*", - "@opentelemetry/api": "^1.9.0", - "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "4.1.0", - "@vitest/browser-preview": "4.1.0", - "@vitest/browser-webdriverio": "4.1.0", - "@vitest/ui": "4.1.0", - "happy-dom": "*", - "jsdom": "*", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0-0" - }, - "peerDependenciesMeta": { - "@edge-runtime/vm": { - "optional": true - }, - "@opentelemetry/api": { - "optional": true - }, - "@types/node": { - "optional": true - }, - "@vitest/browser-playwright": { - "optional": true - }, - "@vitest/browser-preview": { - "optional": true - }, - "@vitest/browser-webdriverio": { - "optional": true - }, - "@vitest/ui": { - "optional": true - }, - "happy-dom": { - "optional": true - }, - "jsdom": { - "optional": true - }, - "vite": { - "optional": false - } - } - }, - "node_modules/why-is-node-running": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", - "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", - "dev": true, - "license": "MIT", - "dependencies": { - "siginfo": "^2.0.0", - "stackback": "0.0.2" - }, - "bin": { - "why-is-node-running": "cli.js" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/ws": { - "version": "8.19.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", - "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", - "license": "MIT", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/xtend": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", - "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", - "license": "MIT", - "engines": { - "node": ">=0.4" - } - }, - "node_modules/zod": { - "version": "3.25.76", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", - "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - } - } -} diff --git a/legacy/taproot-assets-era/backend/package.json b/legacy/taproot-assets-era/backend/package.json deleted file mode 100644 index 47cab8b..0000000 --- a/legacy/taproot-assets-era/backend/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "@runebolt/backend", - "version": "0.2.0", - "scripts": { - "dev": "tsx watch src/index.ts", - "build": "tsc", - "start": "node dist/index.js", - "db:migrate": "tsx src/scripts/migrate.ts", - "db:cleanup": "tsx src/scripts/cleanup.ts", - "test": "vitest run", - "test:watch": "vitest" - }, - "dependencies": { - "@bitcoinerlab/secp256k1": "^1.2.0", - "@noble/hashes": "^2.0.1", - "@noble/secp256k1": "^3.0.0", - "bitcoinjs-lib": "^7.0.1", - "cors": "^2.8.5", - "dotenv": "^16.3.1", - "express": "^4.18.2", - "express-rate-limit": "^7.5.1", - "helmet": "^7.1.0", - "ioredis": "^5.3.2", - "jsonwebtoken": "^9.0.2", - "pg": "^8.20.0", - "prom-client": "^15.1.0", - "uuid": "^9.0.0", - "ws": "^8.16.0", - "zod": "^3.22.4" - }, - "devDependencies": { - "@types/cors": "^2.8.17", - "@types/express": "^4.17.21", - "@types/jsonwebtoken": "^9.0.5", - "@types/node": "^20.10.0", - "@types/pg": "^8.18.0", - "@types/supertest": "^7.2.0", - "@types/uuid": "^9.0.7", - "@types/ws": "^8.5.10", - "supertest": "^7.2.2", - "tsx": "^4.7.0", - "typescript": "^5.3.3", - "vitest": "^4.1.0" - } -} diff --git a/legacy/taproot-assets-era/backend/scripts/deploy-production.sh b/legacy/taproot-assets-era/backend/scripts/deploy-production.sh deleted file mode 100755 index b936665..0000000 --- a/legacy/taproot-assets-era/backend/scripts/deploy-production.sh +++ /dev/null @@ -1,131 +0,0 @@ -#!/usr/bin/env bash -# deploy-production.sh — Deploy RuneBolt backend to production server -# -# Usage: ./scripts/deploy-production.sh -# -# Prerequisites: -# - SSH key access to the production server -# - Node.js and pm2 installed on the server -# - PostgreSQL configured and accessible from the server - -set -euo pipefail - -# ==================== Configuration ==================== -SERVER_IP="${SERVER_IP:-your.server.ip}" -SSH_KEY="${SSH_KEY:-$HOME/.ssh/id_rsa}" -DEPLOY_PATH="${DEPLOY_PATH:-/opt/runebolt/backend}" -SSH_USER="${SSH_USER:-deploy}" -PM2_APP_NAME="runebolt-backend" -HEALTH_ENDPOINT="http://localhost:3141/health" -AUTH_ENDPOINT="http://localhost:3141/api/v1/auth/auth/challenge" - -# ==================== Helpers ==================== -log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"; } -die() { log "ERROR: $*"; exit 1; } - -ssh_cmd() { - ssh -i "$SSH_KEY" -o StrictHostKeyChecking=accept-new "${SSH_USER}@${SERVER_IP}" "$@" -} - -# ==================== Pre-flight Checks ==================== -log "Starting RuneBolt production deployment" - -if [ "$SERVER_IP" = "your.server.ip" ]; then - die "Set SERVER_IP before deploying (export SERVER_IP=x.x.x.x)" -fi - -if [ ! -f "$SSH_KEY" ]; then - die "SSH key not found at $SSH_KEY" -fi - -# ==================== Step 1: Build ==================== -log "Building TypeScript..." -npm run build || die "Build failed" -log "Build succeeded" - -# ==================== Step 2: Local Smoke Tests ==================== -log "Running local smoke tests..." -if [ -f scripts/smoke-test.sh ]; then - bash scripts/smoke-test.sh "http://localhost:3141" || log "WARN: Local smoke tests failed (server may not be running locally)" -else - log "WARN: smoke-test.sh not found, skipping local smoke tests" -fi - -# ==================== Step 3: Sync to Server ==================== -log "Syncing dist/ to ${SSH_USER}@${SERVER_IP}:${DEPLOY_PATH}/" -rsync -avz --delete \ - -e "ssh -i $SSH_KEY -o StrictHostKeyChecking=accept-new" \ - dist/ \ - package.json \ - package-lock.json \ - "${SSH_USER}@${SERVER_IP}:${DEPLOY_PATH}/" - -# Also sync migrations if they exist -if [ -d migrations ]; then - rsync -avz \ - -e "ssh -i $SSH_KEY -o StrictHostKeyChecking=accept-new" \ - migrations/ \ - "${SSH_USER}@${SERVER_IP}:${DEPLOY_PATH}/migrations/" -fi - -log "Sync complete" - -# ==================== Step 4: Remote Deploy ==================== -log "Deploying on remote server..." -ssh_cmd bash -s <<'REMOTE_SCRIPT' -set -euo pipefail - -DEPLOY_PATH="${DEPLOY_PATH:-/opt/runebolt/backend}" -PM2_APP_NAME="runebolt-backend" - -cd "$DEPLOY_PATH" - -echo "[remote] Installing production dependencies..." -npm install --omit=dev - -echo "[remote] Running database migrations..." -if [ -d migrations ]; then - node -e " - const Database = require('./dist/db/Database').default; - const db = Database.getInstance(); - db.initialize(); - db.runMigrations().then(() => { - console.log('Migrations complete'); - return db.close(); - }).catch(err => { - console.error('Migration failed:', err); - process.exit(1); - }); - " -fi - -echo "[remote] Restarting application..." -pm2 restart "$PM2_APP_NAME" || pm2 start dist/index.js --name "$PM2_APP_NAME" - -echo "[remote] Waiting for server to start..." -sleep 5 - -echo "[remote] Verifying health endpoint..." -HEALTH=$(curl -sf http://localhost:3141/health) || { echo "Health check failed"; exit 1; } -STATUS=$(echo "$HEALTH" | node -pe "JSON.parse(require('fs').readFileSync('/dev/stdin','utf8')).status" 2>/dev/null || echo "unknown") -if [ "$STATUS" != "ok" ]; then - echo "Health check returned status: $STATUS" - exit 1 -fi -echo "[remote] Health check passed: $STATUS" - -echo "[remote] Verifying auth challenge endpoint..." -AUTH_RESULT=$(curl -sf -X POST http://localhost:3141/api/v1/auth/auth/challenge \ - -H "Content-Type: application/json" \ - -d '{"pubkey":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}') || { echo "Auth challenge check failed"; exit 1; } -echo "[remote] Auth challenge check passed" - -echo "[remote] Deployment verified successfully" -REMOTE_SCRIPT - -log "========================================" -log "Deployment successful!" -log "Server: ${SSH_USER}@${SERVER_IP}" -log "Path: ${DEPLOY_PATH}" -log "Time: $(date '+%Y-%m-%d %H:%M:%S %Z')" -log "========================================" diff --git a/legacy/taproot-assets-era/backend/scripts/run-simulation.sh b/legacy/taproot-assets-era/backend/scripts/run-simulation.sh deleted file mode 100755 index a32f3c5..0000000 --- a/legacy/taproot-assets-era/backend/scripts/run-simulation.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -PROJECT_DIR="$(dirname "$SCRIPT_DIR")" - -cd "$PROJECT_DIR" - -echo "╔══════════════════════════════════════════════════════════╗" -echo "║ RuneBolt E2E Simulation Runner ║" -echo "╚══════════════════════════════════════════════════════════╝" - -# Check dependencies -if ! command -v npx &>/dev/null; then - echo "ERROR: npx not found. Install Node.js first." - exit 1 -fi - -# Set test environment defaults -export NODE_ENV=test -export DATABASE_URL="${DATABASE_URL:-postgresql://runebolt:runebolt@localhost:5432/runebolt_test}" -export JWT_SECRET="${JWT_SECRET:-$(openssl rand -hex 32)}" -export BITCOIN_NETWORK=mainnet - -echo "" -echo "Environment:" -echo " DATABASE_URL: ${DATABASE_URL}" -echo " NODE_ENV: ${NODE_ENV}" -echo " NETWORK: ${BITCOIN_NETWORK}" -echo "" - -# Step 1: Type-check -echo "── Step 1: Type-checking ──────────────────────────────────" -if npx tsc --noEmit 2>&1; then - echo "✅ Type-check passed" -else - echo "⚠️ Type-check had warnings (continuing anyway)" -fi -echo "" - -# Step 2: Run simulation -echo "── Step 2: Running E2E Simulation ─────────────────────────" -echo "" -exec npx tsx src/__tests__/e2e-simulation.ts diff --git a/legacy/taproot-assets-era/backend/scripts/setup-mainnet-env.sh b/legacy/taproot-assets-era/backend/scripts/setup-mainnet-env.sh deleted file mode 100755 index 112f7f2..0000000 --- a/legacy/taproot-assets-era/backend/scripts/setup-mainnet-env.sh +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env bash -# -# setup-mainnet-env.sh — Configure mainnet environment on the RuneBolt server. -# Appends missing env vars, verifies required vars, and restarts PM2. -# -set -euo pipefail - -SERVER="64.23.226.113" -SSH_KEY="$HOME/.ssh/runebolt" -REMOTE_ENV="/root/runebolt/.env" - -echo "=== RuneBolt Mainnet Environment Setup ===" -echo "Server: $SERVER" -echo "" - -ssh -i "$SSH_KEY" "root@$SERVER" bash -s <<'REMOTE_SCRIPT' -set -euo pipefail - -ENV_FILE="/root/runebolt/.env" - -if [ ! -f "$ENV_FILE" ]; then - echo "ERROR: $ENV_FILE not found" - exit 1 -fi - -echo "Current .env found. Checking for missing vars..." - -# Helper: append a var if it's not already in the file -ensure_var() { - local key="$1" - local value="$2" - if ! grep -q "^${key}=" "$ENV_FILE"; then - echo "${key}=${value}" >> "$ENV_FILE" - echo " ADDED: ${key}=${value}" - else - echo " EXISTS: ${key} ($(grep "^${key}=" "$ENV_FILE"))" - fi -} - -ensure_var "BITCOIN_NETWORK" "mainnet" -ensure_var "CORS_ORIGIN" "https://app.runebolt.io" -ensure_var "MEMPOOL_API_URL" "https://mempool.space/api" -ensure_var "NODE_ENV" "production" - -echo "" -echo "--- Verifying required env vars ---" - -REQUIRED_VARS="PORT NODE_ENV DATABASE_URL JWT_SECRET BITCOIN_NETWORK CORS_ORIGIN REDIS_HOST REDIS_PORT" -MISSING=0 - -for var in $REQUIRED_VARS; do - if grep -q "^${var}=" "$ENV_FILE"; then - echo " OK: $var" - else - echo " MISSING: $var" - MISSING=$((MISSING + 1)) - fi -done - -if [ "$MISSING" -gt 0 ]; then - echo "" - echo "WARNING: $MISSING required variable(s) missing from $ENV_FILE" - echo "Fix these before restarting the service." - exit 1 -fi - -echo "" -echo "All required vars present. Restarting PM2..." -cd /root/runebolt -pm2 restart runebolt --update-env || pm2 start dist/index.js --name runebolt -pm2 save - -echo "" -echo "=== Mainnet environment setup complete ===" -REMOTE_SCRIPT - -echo "Done." diff --git a/legacy/taproot-assets-era/backend/scripts/smoke-test.sh b/legacy/taproot-assets-era/backend/scripts/smoke-test.sh deleted file mode 100755 index 719c192..0000000 --- a/legacy/taproot-assets-era/backend/scripts/smoke-test.sh +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/env bash -# smoke-test.sh — Quick validation of RuneBolt backend endpoints -# -# Usage: ./scripts/smoke-test.sh [BASE_URL] -# Default BASE_URL: http://localhost:3141 - -set -uo pipefail - -BASE_URL="${1:-http://localhost:3141}" -PASSED=0 -FAILED=0 - -# Test helper: check HTTP status and optional body match -check() { - local name="$1" - local method="$2" - local url="$3" - local expected_status="$4" - local body_match="${5:-}" - local data="${6:-}" - - local args=(-s -o /tmp/smoke_body -w "%{http_code}" -X "$method") - if [ -n "$data" ]; then - args+=(-H "Content-Type: application/json" -d "$data") - fi - - local status - status=$(curl "${args[@]}" "$url" 2>/dev/null) - - local body - body=$(cat /tmp/smoke_body 2>/dev/null || echo "") - - if [ "$status" != "$expected_status" ]; then - echo "FAIL $name — expected $expected_status, got $status" - FAILED=$((FAILED + 1)) - return - fi - - if [ -n "$body_match" ]; then - if ! echo "$body" | grep -q "$body_match"; then - echo "FAIL $name — response body missing '$body_match'" - FAILED=$((FAILED + 1)) - return - fi - fi - - echo "PASS $name" - PASSED=$((PASSED + 1)) -} - -echo "Running smoke tests against $BASE_URL" -echo "========================================" - -# 1. Health endpoint -check "GET /health → 200 + status ok" \ - GET "$BASE_URL/health" 200 '"status":"ok"' - -# 2. Root endpoint -check "GET / → 200 + version" \ - GET "$BASE_URL/" 200 '"version"' - -# 3. Auth challenge -check "POST /api/v1/auth/auth/challenge → 200 + success" \ - POST "$BASE_URL/api/v1/auth/auth/challenge" 200 '"success":true' \ - '{"pubkey":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}' - -# 4. Fee schedule -check "GET /api/v1/fees/schedule → 200 + success" \ - GET "$BASE_URL/api/v1/fees/schedule" 200 '"success":true' - -# 5. Stats endpoint -check "GET /api/v1/stats → 200 + success" \ - GET "$BASE_URL/api/v1/stats" 200 '"success":true' - -echo "========================================" -echo "Results: $PASSED passed, $FAILED failed" - -rm -f /tmp/smoke_body - -if [ "$FAILED" -gt 0 ]; then - echo "Smoke tests FAILED" - exit 1 -fi - -echo "All smoke tests PASSED" -exit 0 diff --git a/legacy/taproot-assets-era/backend/src/__tests__/e2e-simulation.ts b/legacy/taproot-assets-era/backend/src/__tests__/e2e-simulation.ts deleted file mode 100644 index 540fdbd..0000000 --- a/legacy/taproot-assets-era/backend/src/__tests__/e2e-simulation.ts +++ /dev/null @@ -1,959 +0,0 @@ -/** - * RuneBolt End-to-End Simulation - * - * Tests the ENTIRE flow — wallet connect to channel close — using - * real project modules with real cryptography but simulated Bitcoin - * network responses. - * - * Requires: PostgreSQL + Redis running. - * Run via: npx tsx src/__tests__/e2e-simulation.ts - */ - -import crypto from 'crypto'; -import * as secp256k1 from '@noble/secp256k1'; -import { sha256 } from '@noble/hashes/sha2.js'; -import { hmac } from '@noble/hashes/hmac.js'; -import { v4 as uuidv4 } from 'uuid'; - -// Configure noble hashes before any module that imports secp256k1 -secp256k1.hashes.sha256 = (msg: Uint8Array) => sha256(msg); -secp256k1.hashes.hmacSha256 = (key: Uint8Array, ...msgs: Uint8Array[]) => - hmac(sha256, key, secp256k1.etc.concatBytes(...msgs)); - -// Set environment before importing modules -process.env.NODE_ENV = 'test'; -process.env.JWT_SECRET = crypto.randomBytes(32).toString('hex'); -process.env.DATABASE_URL = - process.env.DATABASE_URL || 'postgresql://runebolt:runebolt@localhost:5432/runebolt_test'; -process.env.BITCOIN_NETWORK = 'mainnet'; - -import Database from '../db/Database'; -import { ChallengeManager } from '../auth/ChallengeManager'; -import { generateToken, verifyToken } from '../auth/AuthMiddleware'; -import { TaprootUtils } from '../bitcoin/TaprootUtils'; -import { ChannelState } from '../channels/ChannelState'; -import { CommitmentManager } from '../channels/CommitmentManager'; -import { PenaltyManager } from '../channels/PenaltyManager'; -import { validateTransferAgainstReserve, calculateReserve } from '../channels/ChannelReserves'; -import { FeeManager } from '../fees/FeeManager'; - -// ── Simulation State ────────────────────────────────────────────────── - -interface SimUser { - name: string; - publicKey: string; - privateKey: string; - jwt: string; - channelId: string; -} - -interface PhaseResult { - phase: number; - name: string; - passed: number; - failed: number; - errors: string[]; -} - -const results: PhaseResult[] = []; -let totalTests = 0; -let totalPassed = 0; - -function startPhase(phase: number, name: string): PhaseResult { - console.log(`\n${'═'.repeat(60)}`); - console.log(` PHASE ${phase}: ${name}`); - console.log('═'.repeat(60)); - return { phase, name, passed: 0, failed: 0, errors: [] }; -} - -function test(result: PhaseResult, name: string, fn: () => boolean | Promise): Promise { - return Promise.resolve(fn()).then( - (ok) => { - totalTests++; - if (ok) { - result.passed++; - totalPassed++; - console.log(` ✅ ${name}`); - } else { - result.failed++; - result.errors.push(name); - console.log(` ❌ ${name}`); - } - }, - (err: unknown) => { - totalTests++; - result.failed++; - const msg = err instanceof Error ? err.message : String(err); - result.errors.push(`${name}: ${msg}`); - console.log(` ❌ ${name} — ${msg}`); - } - ); -} - -function finishPhase(result: PhaseResult): void { - const total = result.passed + result.failed; - const icon = result.failed === 0 ? '✅' : '❌'; - console.log( - `\n${icon} PHASE ${result.phase}: ${result.name} — ${result.failed === 0 ? 'PASSED' : 'FAILED'} (${result.passed}/${total} tests)` - ); - if (result.errors.length > 0) { - for (const e of result.errors) { - console.log(` - ${e}`); - } - } - results.push(result); -} - -// ── Main Simulation ─────────────────────────────────────────────────── - -async function runSimulation(): Promise { - console.log('╔══════════════════════════════════════════════════════════╗'); - console.log('║ RUNEBOLT E2E SIMULATION ║'); - console.log('║ Full flow: wallet → channel → close ║'); - console.log('╚══════════════════════════════════════════════════════════╝'); - - const db = Database.getInstance(); - db.initialize(); - - // Run migrations - try { - await db.runMigrations(); - } catch { - // Migrations might already be applied - } - - // Ensure extra tables exist (may not be in base migration) - await ensureExtraTables(db); - - // Clean up any stale test data - await cleanTestData(db); - - const alice: SimUser = { name: 'Alice', publicKey: '', privateKey: '', jwt: '', channelId: '' }; - const bob: SimUser = { name: 'Bob', publicKey: '', privateKey: '', jwt: '', channelId: '' }; - - // ─── PHASE 1: Setup ───────────────────────────────────────────── - { - const p = startPhase(1, 'Setup — Keys & Infrastructure'); - - await test(p, 'Database health check', async () => { - const health = await db.healthCheck(); - return health.healthy; - }); - - await test(p, 'Generate Alice Schnorr keypair', () => { - const kp = TaprootUtils.generateKeyPair(); - alice.publicKey = kp.publicKey; - alice.privateKey = kp.privateKey; - return kp.publicKey.length === 64 && kp.privateKey.length === 64; - }); - - await test(p, 'Generate Bob Schnorr keypair', () => { - const kp = TaprootUtils.generateKeyPair(); - bob.publicKey = kp.publicKey; - bob.privateKey = kp.privateKey; - return kp.publicKey.length === 64 && kp.privateKey.length === 64; - }); - - await test(p, 'Alice and Bob have different keys', () => { - return alice.publicKey !== bob.publicKey; - }); - - finishPhase(p); - } - - // ─── PHASE 2: Authentication ──────────────────────────────────── - { - const p = startPhase(2, 'Authentication — Challenge/Response'); - const cm = new ChallengeManager(); - - // Create users first (ChallengeManager stores challenges referencing users table) - await db.createUser(alice.publicKey); - await db.createUser(bob.publicKey); - - await test(p, 'Alice requests auth challenge', async () => { - const { challengeId, message } = await cm.createChallenge(alice.publicKey); - return challengeId.length > 0 && message.includes('RuneBolt authentication challenge'); - }); - - await test(p, 'Alice signs and verifies challenge', async () => { - const { challengeId, message } = await cm.createChallenge(alice.publicKey); - const signature = await TaprootUtils.signSchnorr(alice.privateKey, message); - const result = await cm.verifyChallenge(challengeId, signature); - return result.valid && result.pubkey === alice.publicKey; - }); - - await test(p, 'Alice gets JWT after verification', () => { - const token = generateToken(alice.publicKey); - alice.jwt = token; - const decoded = verifyToken(token); - return decoded.pubkey === alice.publicKey; - }); - - await test(p, 'Bob signs and verifies challenge', async () => { - const { challengeId, message } = await cm.createChallenge(bob.publicKey); - const signature = await TaprootUtils.signSchnorr(bob.privateKey, message); - const result = await cm.verifyChallenge(challengeId, signature); - bob.jwt = generateToken(bob.publicKey); - return result.valid && result.pubkey === bob.publicKey; - }); - - await test(p, 'Invalid signature is REJECTED', async () => { - const { challengeId } = await cm.createChallenge(alice.publicKey); - const fakeSig = crypto.randomBytes(64).toString('hex'); - const result = await cm.verifyChallenge(challengeId, fakeSig); - return !result.valid && result.pubkey === null; - }); - - await test(p, 'Wrong key signature is REJECTED', async () => { - const { challengeId, message } = await cm.createChallenge(alice.publicKey); - // Sign with Bob's key but challenge is for Alice - const signature = await TaprootUtils.signSchnorr(bob.privateKey, message); - const result = await cm.verifyChallenge(challengeId, signature); - return !result.valid; - }); - - finishPhase(p); - } - - // ─── PHASE 3: Username Registration ──────────────────────────── - { - const p = startPhase(3, 'Username Registration'); - - await test(p, 'Alice registers @alice', async () => { - await db.updateUsername(alice.publicKey, 'alice'); - const user = await db.getUser(alice.publicKey); - return user?.username === 'alice'; - }); - - await test(p, 'Bob registers @bob', async () => { - await db.updateUsername(bob.publicKey, 'bob'); - const user = await db.getUser(bob.publicKey); - return user?.username === 'bob'; - }); - - await test(p, 'Lookup user by username works', async () => { - const user = await db.getUserByUsername('alice'); - return user?.pubkey === alice.publicKey; - }); - - await test(p, 'Duplicate username fails (DB constraint)', async () => { - // Try to set a third user's name to "alice" - const tmpKey = TaprootUtils.generateKeyPair(); - await db.createUser(tmpKey.publicKey); - try { - await db.updateUsername(tmpKey.publicKey, 'alice'); - // If it didn't throw, check that the original alice still owns it - const user = await db.getUserByUsername('alice'); - return user?.pubkey === alice.publicKey; - } catch { - return true; // constraint violation = expected - } - }); - - await test(p, 'Username validation — alphanumeric, underscores, hyphens only', () => { - // This is validated at the API route level via zod - const validPattern = /^[a-zA-Z0-9_-]+$/; - return ( - validPattern.test('alice') && - validPattern.test('bob_123') && - !validPattern.test('@alice') && - !validPattern.test('al!ce') && - !validPattern.test('a b') - ); - }); - - finishPhase(p); - } - - // ─── PHASE 4: Channel Opening ────────────────────────────────── - { - const p = startPhase(4, 'Channel Opening — Taproot Multisig'); - const CHANNEL_AMOUNT = 1_000_000; - - await test(p, 'TaprootUtils creates valid 2-of-2 multisig', () => { - const multisig = TaprootUtils.createMultisigAddress(alice.publicKey, bob.publicKey); - return multisig.address.startsWith('bc1p') && multisig.internalPubkey.length === 64; - }); - - await test(p, 'Multisig address starts with bc1p (Taproot mainnet)', () => { - const multisig = TaprootUtils.createMultisigAddress(alice.publicKey, bob.publicKey); - return multisig.address.startsWith('bc1p'); - }); - - await test(p, 'Key aggregation is deterministic', () => { - const m1 = TaprootUtils.createMultisigAddress(alice.publicKey, bob.publicKey); - const m2 = TaprootUtils.createMultisigAddress(alice.publicKey, bob.publicKey); - return m1.address === m2.address && m1.internalPubkey === m2.internalPubkey; - }); - - await test(p, 'Key aggregation is order-independent (sorted)', () => { - const m1 = TaprootUtils.createMultisigAddress(alice.publicKey, bob.publicKey); - const m2 = TaprootUtils.createMultisigAddress(bob.publicKey, alice.publicKey); - return m1.address === m2.address; - }); - - // Create Alice's channel directly in DB (simulating the channel open flow) - await test(p, 'Alice opens channel with 1,000,000 DOG', async () => { - const hubKey = TaprootUtils.generateKeyPair(); - alice.channelId = uuidv4(); - await db.createChannel({ - id: alice.channelId, - user_pubkey: alice.publicKey, - runebolt_pubkey: hubKey.publicKey, - funding_txid: null, - funding_vout: null, - capacity: CHANNEL_AMOUNT, - local_balance: CHANNEL_AMOUNT, - remote_balance: 0, - state: ChannelState.PENDING_OPEN, - }); - const ch = await db.getChannel(alice.channelId); - return ch?.state === ChannelState.PENDING_OPEN && ch.capacity === CHANNEL_AMOUNT; - }); - - await test(p, 'Channel state is PENDING_OPEN until confirmed', async () => { - const ch = await db.getChannel(alice.channelId); - return ch?.state === ChannelState.PENDING_OPEN; - }); - - // Simulate funding confirmation - await test(p, 'Simulate funding confirmation → channel OPEN', async () => { - const fakeTxid = crypto.randomBytes(32).toString('hex'); - await db.updateChannel({ - id: alice.channelId, - funding_txid: fakeTxid, - funding_vout: 0, - capacity: CHANNEL_AMOUNT, - local_balance: CHANNEL_AMOUNT, - remote_balance: 0, - state: ChannelState.OPEN, - }); - const ch = await db.getChannel(alice.channelId); - return ch?.state === ChannelState.OPEN && ch.funding_txid === fakeTxid; - }); - - // Create initial commitment for Alice's channel - await CommitmentManager.createCommitment(alice.channelId, BigInt(CHANNEL_AMOUNT), 0n, 0); - - // Create Bob's channel - await test(p, 'Bob opens channel with 1,000,000 DOG', async () => { - const hubKey = TaprootUtils.generateKeyPair(); - bob.channelId = uuidv4(); - await db.createChannel({ - id: bob.channelId, - user_pubkey: bob.publicKey, - runebolt_pubkey: hubKey.publicKey, - funding_txid: crypto.randomBytes(32).toString('hex'), - funding_vout: 0, - capacity: CHANNEL_AMOUNT, - local_balance: 0, - remote_balance: CHANNEL_AMOUNT, - state: ChannelState.OPEN, - }); - await CommitmentManager.createCommitment(bob.channelId, 0n, BigInt(CHANNEL_AMOUNT), 0); - const ch = await db.getChannel(bob.channelId); - return ch?.state === ChannelState.OPEN; - }); - - await test(p, 'Channel below minimum (0) should fail', async () => { - try { - // ChannelManager.openChannel checks amount > 0 - if (0n <= 0n) throw new Error('Channel amount must be positive'); - return false; - } catch { - return true; - } - }); - - finishPhase(p); - } - - // ─── PHASE 5: Transfers ──────────────────────────────────────── - { - const p = startPhase(5, 'Off-Chain Transfers'); - const TRANSFER_AMOUNT = 100_000; - const CHANNEL_AMOUNT = 1_000_000; - - // Execute a transfer directly via DB (simulating RuneLedger flow) - await test(p, 'Alice sends 100,000 DOG to Bob', async () => { - const transferId = uuidv4(); - const nonce = uuidv4(); - - // Update balances atomically - await db.updateChannelBalances(alice.channelId, CHANNEL_AMOUNT - TRANSFER_AMOUNT, TRANSFER_AMOUNT); - await db.updateChannelBalances(bob.channelId, TRANSFER_AMOUNT, CHANNEL_AMOUNT - TRANSFER_AMOUNT); - await db.createTransfer({ - id: transferId, - from_channel: alice.channelId, - to_channel: bob.channelId, - amount: TRANSFER_AMOUNT, - memo: 'First transfer', - nonce, - client_signature: 'sim_sig', - }); - - const aliceCh = await db.getChannel(alice.channelId); - const bobCh = await db.getChannel(bob.channelId); - return ( - aliceCh!.local_balance === CHANNEL_AMOUNT - TRANSFER_AMOUNT && - bobCh!.local_balance === TRANSFER_AMOUNT - ); - }); - - await test(p, 'Alice balance decreased by 100,000', async () => { - const ch = await db.getChannel(alice.channelId); - return ch!.local_balance === 900_000; - }); - - await test(p, 'Bob balance increased by 100,000', async () => { - const ch = await db.getChannel(bob.channelId); - return ch!.local_balance === 100_000; - }); - - await test(p, 'Commitment created with correct sequence', async () => { - // Create commitment for the new state - const aliceCommitment = await CommitmentManager.createCommitment( - alice.channelId, 900_000n, 100_000n, 1 - ); - return aliceCommitment.sequence === 1 && aliceCommitment.localBalance === 900_000n; - }); - - await test(p, 'Revocation secret exchanged for old state', async () => { - const { secret, hash } = PenaltyManager.generateRevocationSecret(); - // Store revocation secret for commitment #0 (now old) - await db.storeRevocationSecret(alice.channelId, 0, secret); - // Verify we can retrieve it - const stored = await db.getRevocationSecret(alice.channelId, 0); - // Verify hash matches - const computedHash = Buffer.from(sha256(Buffer.from(secret, 'hex'))).toString('hex'); - return stored?.secret === secret && computedHash === hash; - }); - - await test(p, 'Transfer exceeding balance fails', async () => { - const aliceCh = await db.getChannel(alice.channelId); - const aliceLocal = BigInt(aliceCh!.local_balance); - const canTransfer = aliceLocal >= BigInt(10_000_000); - return !canTransfer; // 900,000 < 10,000,000 - }); - - await test(p, 'Transfer violating reserve (1%) fails', () => { - // Alice has 900,000 in a 1,000,000 channel - // Reserve = 1% of 1,000,000 = 10,000 - // Max spendable = 900,000 - 10,000 = 890,000 - const reserve = calculateReserve(1_000_000n); - const valid = validateTransferAgainstReserve(900_000n, 1_000_000n, 895_000n); - return reserve === 10_000n && !valid; - }); - - await test(p, 'Transfer just at reserve limit succeeds', () => { - // 900,000 - 890,000 = 10,000 which is exactly the reserve - return validateTransferAgainstReserve(900_000n, 1_000_000n, 890_000n); - }); - - await test(p, 'Dust transfer (< 100 units) is detectable', () => { - // The system could enforce a minimum transfer — we verify the check - const DUST_LIMIT = 100n; - const dustTransfer = 50n; - return dustTransfer < DUST_LIMIT; - }); - - await test(p, 'Negative/zero amount rejected', () => { - // RuneLedger.transfer checks amount <= 0n - const zeroFails = 0n <= 0n; - const negativeFails = -1n <= 0n; - return zeroFails && negativeFails; - }); - - await test(p, 'Replay attack prevented via nonce', async () => { - const nonce = uuidv4(); - // First transfer with this nonce - await db.createTransfer({ - id: uuidv4(), - from_channel: alice.channelId, - to_channel: bob.channelId, - amount: 1000, - memo: null, - nonce, - }); - // Check replay: same nonce should be found - const existing = await db.getTransferByNonce(nonce); - return existing !== undefined; - }); - - finishPhase(p); - } - - // ─── PHASE 6: Fee Tracking ───────────────────────────────────── - { - const p = startPhase(6, 'Fee Tracking — Free Tier & Paid'); - const feeManager = new FeeManager(); - - await test(p, 'First transfer is free (within 500 free tier)', async () => { - const calc = await feeManager.calculateFee(alice.publicKey, 100_000n); - return calc.isFree && calc.feeAmount === 0n; - }); - - await test(p, 'Free transactions remaining starts at 500', async () => { - const remaining = await feeManager.getFreeTransactionsRemaining(alice.publicKey); - return remaining === 500; - }); - - // Simulate 500 transactions by directly incrementing the counter - await test(p, 'After 500 transactions, fees apply', async () => { - // Directly set the transaction count to 500 - await db.query( - `INSERT INTO user_transaction_counts (pubkey, count) VALUES ($1, 500) - ON CONFLICT (pubkey) DO UPDATE SET count = 500`, - [alice.publicKey] - ); - const calc = await feeManager.calculateFee(alice.publicKey, 100_000n); - return !calc.isFree && calc.feeRate === 0.001; - }); - - await test(p, 'Transfer 501 has 0.1% fee applied', async () => { - const calc = await feeManager.calculateFee(alice.publicKey, 1_000_000n); - // 0.1% of 1,000,000 = 1,000 - return calc.feeAmount === 1000n && calc.feeRate === 0.001; - }); - - await test(p, 'Fee recorded in fee_ledger', async () => { - const transferId = uuidv4(); - const calc = await feeManager.calculateFee(alice.publicKey, 100_000n); - await feeManager.recordFee(transferId, alice.publicKey, calc); - - // Verify fee_ledger has the entry - const result = await db.query( - 'SELECT * FROM fee_ledger WHERE transfer_id = $1', - [transferId] - ); - return result.rows.length === 1; - }); - - await test(p, 'Settlement fee is 0.5%', async () => { - const calc = await feeManager.calculateFee(alice.publicKey, 1_000_000n, 'settlement'); - return calc.feeRate === 0.005 && calc.feeAmount === 5000n; - }); - - await test(p, 'User tier info available', async () => { - const info = await feeManager.getUserTierInfo(alice.publicKey); - return info.transactionCount >= 500 && info.freeTransactionsRemaining === 0; - }); - - finishPhase(p); - } - - // ─── PHASE 7: Claim Links ────────────────────────────────────── - { - const p = startPhase(7, 'Claim Links — Create & Redeem'); - const CLAIM_AMOUNT = 50_000; - - let claimId = ''; - - await test(p, 'Alice creates a claim link for 50,000 DOG', async () => { - claimId = uuidv4(); - await db.createClaimLink({ - id: claimId, - creator_pubkey: alice.publicKey, - amount: CLAIM_AMOUNT, - memo: 'Test claim', - expires_at: new Date(Date.now() + 86400000).toISOString(), - }); - const claim = await db.getClaimLink(claimId); - return claim !== undefined && claim.amount === CLAIM_AMOUNT; - }); - - await test(p, 'Bob redeems the claim link', async () => { - // Simulate the redemption: transfer + mark claimed - const aliceCh = await db.getChannel(alice.channelId); - const bobCh = await db.getChannel(bob.channelId); - const newAliceLocal = aliceCh!.local_balance - CLAIM_AMOUNT; - const newAliceRemote = aliceCh!.remote_balance + CLAIM_AMOUNT; - const newBobLocal = bobCh!.local_balance + CLAIM_AMOUNT; - const newBobRemote = bobCh!.remote_balance - CLAIM_AMOUNT; - - await db.updateChannelBalances(alice.channelId, newAliceLocal, newAliceRemote); - await db.updateChannelBalances(bob.channelId, newBobLocal, newBobRemote); - await db.createTransfer({ - id: uuidv4(), - from_channel: alice.channelId, - to_channel: bob.channelId, - amount: CLAIM_AMOUNT, - memo: `Claim: ${claimId}`, - nonce: uuidv4(), - }); - await db.claimLink(claimId, bob.publicKey); - - const claim = await db.getClaimLink(claimId); - const updatedBob = await db.getChannel(bob.channelId); - return claim?.claimed_by === bob.publicKey && updatedBob!.local_balance === newBobLocal; - }); - - await test(p, 'Double-claim fails', async () => { - const claim = await db.getClaimLink(claimId); - return claim?.claimed_by !== null; // Already claimed → should be blocked at API level - }); - - await test(p, 'Expired claim is detectable', async () => { - const expiredId = uuidv4(); - await db.createClaimLink({ - id: expiredId, - creator_pubkey: alice.publicKey, - amount: 1000, - memo: null, - expires_at: new Date(Date.now() - 1000).toISOString(), // Already expired - }); - const claim = await db.getClaimLink(expiredId); - const isExpired = new Date(claim!.expires_at).getTime() < Date.now(); - return isExpired; - }); - - finishPhase(p); - } - - // ─── PHASE 8: Dispute Resolution ────────────────────────────── - { - const p = startPhase(8, 'Dispute Resolution — Breach Detection & Penalty'); - const penaltyManager = new PenaltyManager(); - - // Store multiple revocation secrets (simulating several state updates) - for (let seq = 0; seq < 5; seq++) { - const { secret } = PenaltyManager.generateRevocationSecret(); - await db.storeRevocationSecret(alice.channelId, seq, secret); - await CommitmentManager.createCommitmentWithRevocation( - alice.channelId, - BigInt(900_000 - seq * 10_000), - BigInt(100_000 + seq * 10_000), - seq + 2, // sequences 2-6 (0 and 1 already created) - seq > 0 ? (await db.getRevocationSecret(alice.channelId, seq - 1))?.secret : undefined - ); - } - - await test(p, 'Revocation secrets stored for sequences 0-4', async () => { - const secrets = await db.getRevocationSecrets(alice.channelId); - return secrets.length >= 5; - }); - - await test(p, 'Breach detected: old state (seq 1) broadcast', async () => { - // Simulate broadcasting old commitment #1 - // PenaltyManager.checkForBreach looks at tx locktime - const fakeTx = { - txid: crypto.randomBytes(32).toString('hex'), - version: 2, - locktime: 0x20000001, // Encodes sequence 1 in lower 24 bits - vin: [{ txid: 'fake', vout: 0, prevout: null, scriptsig: '', sequence: 0xffffffff }], - vout: [{ scriptpubkey: '', scriptpubkey_asm: '', scriptpubkey_type: 'witness_v1_taproot', value: 546 }], - size: 250, - weight: 1000, - fee: 500, - status: { confirmed: false }, - }; - const breachSeq = await penaltyManager.checkForBreach(alice.channelId, fakeTx); - return breachSeq === 1; - }); - - await test(p, 'No breach for current state', async () => { - // Current sequence is > 4, no revocation secret for seq 10 - const fakeTx = { - txid: crypto.randomBytes(32).toString('hex'), - version: 2, - locktime: 0x2000000A, // Encodes sequence 10 - vin: [{ txid: 'fake', vout: 0, prevout: null, scriptsig: '', sequence: 0xffffffff }], - vout: [{ scriptpubkey: '', scriptpubkey_asm: '', scriptpubkey_type: 'witness_v1_taproot', value: 546 }], - size: 250, - weight: 1000, - fee: 500, - status: { confirmed: false }, - }; - const breachSeq = await penaltyManager.checkForBreach(alice.channelId, fakeTx); - return breachSeq === null; - }); - - await test(p, 'Penalty transaction constructable for breach', async () => { - const breachTxid = crypto.randomBytes(32).toString('hex'); - const breachTxHex = crypto.randomBytes(100).toString('hex'); - const { penaltyTxHex, penaltyTxid } = await penaltyManager.buildPenaltyTx( - alice.channelId, - breachTxid, - breachTxHex - ); - return penaltyTxHex.length > 0 && penaltyTxid.length > 0; - }); - - await test(p, 'Breach attempt recorded in database', async () => { - const breaches = await db.getBreaches(alice.channelId); - return breaches.length > 0 && breaches[0].status === 'detected'; - }); - - await test(p, 'Commitment revocation marks old state', async () => { - const secrets = await db.getRevocationSecrets(alice.channelId); - const firstSecret = secrets[0]; - await CommitmentManager.revokeCommitment(alice.channelId, 0, firstSecret.secret); - const isRevoked = await CommitmentManager.isCommitmentRevoked(alice.channelId, 0); - return isRevoked; - }); - - finishPhase(p); - } - - // ─── PHASE 9: Cooperative Close ──────────────────────────────── - { - const p = startPhase(9, 'Cooperative Close'); - - await test(p, 'Channel transitions OPEN → CLOSING', async () => { - await db.updateChannelState(alice.channelId, ChannelState.CLOSING); - const ch = await db.getChannel(alice.channelId); - return ch?.state === ChannelState.CLOSING; - }); - - await test(p, 'Closing PSBT has correct balance split', async () => { - const ch = await db.getChannel(alice.channelId); - // Alice should have her remaining balance, Bob gets his share - return ch!.local_balance > 0 && ch!.local_balance + ch!.remote_balance === ch!.capacity; - }); - - await test(p, 'Channel transitions CLOSING → CLOSED', async () => { - await db.updateChannelState(alice.channelId, ChannelState.CLOSED); - const ch = await db.getChannel(alice.channelId); - return ch?.state === ChannelState.CLOSED; - }); - - await test(p, 'Closed channel state is terminal (no further transitions)', () => { - const validNextStates = [ - ChannelState.OPEN, - ChannelState.CLOSING, - ChannelState.FORCE_CLOSING, - ChannelState.PENDING_OPEN, - ]; - // None should be valid from CLOSED - return validNextStates.every((s) => { - try { - const { assertTransition } = require('../channels/ChannelState'); - assertTransition(ChannelState.CLOSED, s); - return false; - } catch { - return true; - } - }); - }); - - await test(p, 'Bob channel still OPEN', async () => { - const ch = await db.getChannel(bob.channelId); - return ch?.state === ChannelState.OPEN; - }); - - finishPhase(p); - } - - // ─── PHASE 10: Stats Verification ────────────────────────────── - { - const p = startPhase(10, 'Stats Verification'); - - await test(p, 'Stats: total_users is accurate', async () => { - const stats = await db.getPublicStats(); - return stats.totalUsers >= 2; // At least Alice and Bob - }); - - await test(p, 'Stats: total_transfers is accurate', async () => { - const stats = await db.getPublicStats(); - return stats.totalTransfers >= 3; // We did at least 3 transfers - }); - - await test(p, 'Stats: total_volume is positive', async () => { - const stats = await db.getPublicStats(); - return parseInt(stats.totalVolume, 10) > 0; - }); - - await test(p, 'Stats: total_channels includes both', async () => { - const stats = await db.getPublicStats(); - return stats.totalChannels >= 2; - }); - - await test(p, 'Stats: open_channels count is correct', async () => { - const stats = await db.getPublicStats(); - // Alice's channel is CLOSED, Bob's is OPEN - return stats.openChannels >= 1; - }); - - await test(p, 'Schnorr signature round-trip verification', async () => { - const message = 'RuneBolt integrity check ' + Date.now(); - const sig = await TaprootUtils.signSchnorr(alice.privateKey, message); - const valid = TaprootUtils.verifySchnorrSignature(alice.publicKey, message, sig); - const invalid = TaprootUtils.verifySchnorrSignature(bob.publicKey, message, sig); - return valid && !invalid; - }); - - await test(p, 'Timelock script generation', () => { - const script = TaprootUtils.createTimelockScript(alice.publicKey, 144); - return script.includes(alice.publicKey) && script.startsWith('b2'); - }); - - finishPhase(p); - } - - // ─── Final Report ────────────────────────────────────────────── - console.log('\n' + '═'.repeat(60)); - console.log(' SIMULATION REPORT'); - console.log('═'.repeat(60)); - - const phasesTotal = results.length; - const phasesPassed = results.filter((r) => r.failed === 0).length; - - for (const r of results) { - const icon = r.failed === 0 ? '✅' : '❌'; - console.log(` ${icon} Phase ${r.phase}: ${r.name} (${r.passed}/${r.passed + r.failed})`); - } - - console.log(`\n📊 SIMULATION COMPLETE: ${phasesPassed}/${phasesTotal} phases passed, ${totalPassed}/${totalTests} tests passed`); - - if (phasesPassed < phasesTotal) { - console.log('\n❌ FAILURES:'); - for (const r of results) { - if (r.failed > 0) { - for (const e of r.errors) { - console.log(` Phase ${r.phase}: ${e}`); - } - } - } - } - - // Cleanup - await cleanTestData(db); - await db.close(); - - process.exit(phasesPassed === phasesTotal ? 0 : 1); -} - -// ── Helpers ─────────────────────────────────────────────────────────── - -async function ensureExtraTables(db: Database): Promise { - // Tables that may not be in the base migration - const extraDDL = ` - -- nonce/signature columns on transfers - DO $$ BEGIN - ALTER TABLE transfers ADD COLUMN IF NOT EXISTS nonce TEXT; - EXCEPTION WHEN others THEN NULL; END $$; - DO $$ BEGIN - ALTER TABLE transfers ADD COLUMN IF NOT EXISTS client_signature TEXT; - EXCEPTION WHEN others THEN NULL; END $$; - DO $$ BEGIN - ALTER TABLE transfers ADD COLUMN IF NOT EXISTS transfer_hash TEXT; - EXCEPTION WHEN others THEN NULL; END $$; - - CREATE UNIQUE INDEX IF NOT EXISTS idx_transfers_nonce ON transfers(nonce) WHERE nonce IS NOT NULL; - - -- Revocation secrets - CREATE TABLE IF NOT EXISTS revocation_secrets ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - channel_id UUID NOT NULL REFERENCES channels(id) ON DELETE CASCADE, - sequence INTEGER NOT NULL, - secret TEXT NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE(channel_id, sequence) - ); - - -- User transaction counts - CREATE TABLE IF NOT EXISTS user_transaction_counts ( - pubkey TEXT PRIMARY KEY REFERENCES users(pubkey), - count INTEGER NOT NULL DEFAULT 0, - free_remaining INTEGER NOT NULL DEFAULT 500, - total_fees_paid BIGINT NOT NULL DEFAULT 0, - last_reset TIMESTAMPTZ NOT NULL DEFAULT NOW() - ); - - -- User tiers - CREATE TABLE IF NOT EXISTS user_tiers ( - pubkey TEXT PRIMARY KEY REFERENCES users(pubkey), - tier TEXT NOT NULL DEFAULT 'free', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - ); - - -- Fee records - CREATE TABLE IF NOT EXISTS fee_records ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - transfer_id UUID NOT NULL, - pubkey TEXT NOT NULL REFERENCES users(pubkey), - amount BIGINT NOT NULL, - fee_type TEXT NOT NULL, - fee_rate DOUBLE PRECISION NOT NULL, - collected_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - ); - - -- Fee ledger - CREATE TABLE IF NOT EXISTS fee_ledger ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - user_pubkey TEXT NOT NULL REFERENCES users(pubkey), - transfer_id UUID NOT NULL, - fee_amount BIGINT NOT NULL DEFAULT 0, - fee_type TEXT NOT NULL DEFAULT 'free', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - ); - - -- Disputes - CREATE TABLE IF NOT EXISTS disputes ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - channel_id UUID NOT NULL REFERENCES channels(id) ON DELETE CASCADE UNIQUE, - initiated_by TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'open', - latest_sequence INTEGER NOT NULL DEFAULT 0, - challenge_deadline TIMESTAMPTZ NOT NULL, - broadcast_txid TEXT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - ); - - -- Breach attempts - CREATE TABLE IF NOT EXISTS breach_attempts ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - channel_id UUID NOT NULL REFERENCES channels(id) ON DELETE CASCADE, - detected_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - breach_txid TEXT NOT NULL, - breach_tx_hex TEXT NOT NULL, - penalty_txid TEXT, - penalty_tx_hex TEXT, - status TEXT NOT NULL DEFAULT 'detected', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - ); - `; - - const client = await db.getClient(); - try { - await client.query(extraDDL); - } finally { - client.release(); - } -} - -async function cleanTestData(db: Database): Promise { - const client = await db.getClient(); - try { - await client.query('BEGIN'); - await client.query('DELETE FROM breach_attempts'); - await client.query('DELETE FROM disputes'); - await client.query('DELETE FROM fee_ledger'); - await client.query('DELETE FROM fee_records'); - await client.query('DELETE FROM revocation_secrets'); - await client.query('DELETE FROM commitments'); - await client.query('DELETE FROM transfers'); - await client.query('DELETE FROM claim_links'); - await client.query('DELETE FROM challenges'); - await client.query('DELETE FROM user_transaction_counts'); - await client.query('DELETE FROM user_tiers'); - await client.query('DELETE FROM channels'); - await client.query('DELETE FROM users'); - await client.query('COMMIT'); - } catch (err) { - await client.query('ROLLBACK'); - console.warn('Cleanup warning:', err instanceof Error ? err.message : err); - } finally { - client.release(); - } -} - -// ── Run ─────────────────────────────────────────────────────────────── - -runSimulation().catch((err) => { - console.error('SIMULATION CRASHED:', err); - process.exit(2); -}); diff --git a/legacy/taproot-assets-era/backend/src/__tests__/integration.test.ts b/legacy/taproot-assets-era/backend/src/__tests__/integration.test.ts deleted file mode 100644 index c38a574..0000000 --- a/legacy/taproot-assets-era/backend/src/__tests__/integration.test.ts +++ /dev/null @@ -1,474 +0,0 @@ -/** - * Integration tests for RuneBolt backend. - * - * Requires a running PostgreSQL instance. - * Set DATABASE_URL env var or use the default test connection string. - */ - -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import request from 'supertest'; -import { v4 as uuidv4 } from 'uuid'; -import crypto from 'crypto'; -import Database from '../db/Database'; - -// Set test environment before importing app -process.env.NODE_ENV = 'test'; -process.env.JWT_SECRET = crypto.randomBytes(32).toString('hex'); -process.env.DATABASE_URL = - process.env.DATABASE_URL || 'postgresql://runebolt:runebolt@localhost:5432/runebolt_test'; - -// Import app after env is configured -import app from '../index'; - -const db = Database.getInstance(); - -// Test pubkeys (valid 64-char hex strings) -const ALICE_PUBKEY = 'a'.repeat(64); -const BOB_PUBKEY = 'b'.repeat(64); - -// Helper to create a channel directly in the DB for testing -async function createTestChannel( - userPubkey: string, - capacity: number, - localBalance: number, - remoteBalance: number, - state = 'OPEN' -): Promise { - const id = uuidv4(); - await db.createChannel({ - id, - user_pubkey: userPubkey, - runebolt_pubkey: crypto.randomBytes(32).toString('hex'), - funding_txid: crypto.randomBytes(32).toString('hex'), - funding_vout: 0, - capacity, - local_balance: localBalance, - remote_balance: remoteBalance, - state, - }); - return id; -} - -// Helper to create a test user -async function createTestUser(pubkey: string, username?: string): Promise { - await db.createUser(pubkey); - if (username) { - await db.updateUsername(pubkey, username); - } -} - -describe('RuneBolt Integration Tests', () => { - beforeAll(async () => { - // Ensure DB is initialized and run migrations - try { - await db.runMigrations(); - } catch { - // Migrations may already be applied - } - }); - - afterAll(async () => { - await db.close(); - }); - - // ==================== Auth Challenge Tests ==================== - - describe('Auth Challenge', () => { - it('should create a challenge with valid pubkey', async () => { - const res = await request(app) - .post('/api/v1/auth/auth/challenge') - .send({ pubkey: ALICE_PUBKEY }) - .expect(200); - - expect(res.body.success).toBe(true); - expect(res.body.data.challengeId).toBeDefined(); - expect(res.body.data.message).toContain('RuneBolt authentication challenge'); - expect(res.body.data.message).toContain(ALICE_PUBKEY); - }); - - it('should reject challenge with invalid pubkey (too short)', async () => { - const res = await request(app) - .post('/api/v1/auth/auth/challenge') - .send({ pubkey: 'abc123' }) - .expect(400); - - expect(res.body.success).toBe(false); - expect(res.body.error).toBeDefined(); - }); - - it('should reject challenge with missing pubkey', async () => { - const res = await request(app) - .post('/api/v1/auth/auth/challenge') - .send({}) - .expect(400); - - expect(res.body.success).toBe(false); - }); - - it('should include nonce and timestamp in challenge message', async () => { - const res = await request(app) - .post('/api/v1/auth/auth/challenge') - .send({ pubkey: ALICE_PUBKEY }) - .expect(200); - - const message = res.body.data.message; - expect(message).toContain('Nonce:'); - expect(message).toContain('Timestamp:'); - expect(message).toContain('Challenge ID:'); - }); - }); - - // ==================== Channel Tests ==================== - - describe('Channel Open', () => { - it('should reject channel open with amount below minimum', async () => { - const res = await request(app) - .post('/api/v1/channels/channel/open') - .send({ pubkey: ALICE_PUBKEY, amount: '100' }) - .expect(400); - - expect(res.body.success).toBe(false); - expect(res.body.error).toContain('at least'); - }); - - it('should reject channel open with amount above maximum', async () => { - const res = await request(app) - .post('/api/v1/channels/channel/open') - .send({ pubkey: ALICE_PUBKEY, amount: '999999999999999' }) - .expect(400); - - expect(res.body.success).toBe(false); - expect(res.body.error).toContain('cannot exceed'); - }); - - it('should reject channel open with non-hex pubkey', async () => { - const res = await request(app) - .post('/api/v1/channels/channel/open') - .send({ pubkey: 'g'.repeat(64), amount: '1000000' }) - .expect(400); - - expect(res.body.success).toBe(false); - }); - - it('should reject channel open with non-numeric amount', async () => { - const res = await request(app) - .post('/api/v1/channels/channel/open') - .send({ pubkey: ALICE_PUBKEY, amount: 'not_a_number' }) - .expect(400); - - expect(res.body.success).toBe(false); - }); - }); - - // ==================== Transfer Tests ==================== - - describe('Transfer Between Channels', () => { - let aliceChannelId: string; - let bobChannelId: string; - - beforeAll(async () => { - await createTestUser(ALICE_PUBKEY); - await createTestUser(BOB_PUBKEY); - // Alice has 1M local, 0 remote; Bob has 0 local, 1M remote (inbound capacity) - aliceChannelId = await createTestChannel(ALICE_PUBKEY, 1_000_000, 1_000_000, 0); - bobChannelId = await createTestChannel(BOB_PUBKEY, 1_000_000, 0, 1_000_000); - }); - - it('should verify sender channel has correct initial balance', async () => { - const channel = await db.getChannel(aliceChannelId); - expect(channel).toBeDefined(); - expect(channel!.local_balance).toBe(1_000_000); - expect(channel!.remote_balance).toBe(0); - expect(channel!.state).toBe('OPEN'); - }); - - it('should verify recipient channel has inbound capacity', async () => { - const channel = await db.getChannel(bobChannelId); - expect(channel).toBeDefined(); - expect(channel!.local_balance).toBe(0); - expect(channel!.remote_balance).toBe(1_000_000); - }); - - it('should execute a valid transfer and update balances', async () => { - const transferAmount = 50_000; - const nonce = uuidv4(); - const transferId = uuidv4(); - - // Execute transfer directly via DB (bypassing worker pool for test determinism) - await db.updateChannelBalances( - aliceChannelId, - 1_000_000 - transferAmount, - 0 + transferAmount - ); - await db.updateChannelBalances( - bobChannelId, - 0 + transferAmount, - 1_000_000 - transferAmount - ); - await db.createTransfer({ - id: transferId, - from_channel: aliceChannelId, - to_channel: bobChannelId, - amount: transferAmount, - memo: 'test transfer', - nonce, - client_signature: 'a'.repeat(128), - }); - - // Verify balances updated - const aliceCh = await db.getChannel(aliceChannelId); - expect(aliceCh!.local_balance).toBe(950_000); - expect(aliceCh!.remote_balance).toBe(50_000); - - const bobCh = await db.getChannel(bobChannelId); - expect(bobCh!.local_balance).toBe(50_000); - expect(bobCh!.remote_balance).toBe(950_000); - }); - - it('should prevent replay by rejecting duplicate nonces', async () => { - const nonce = uuidv4(); - - // Record first transfer with this nonce - await db.createTransfer({ - id: uuidv4(), - from_channel: aliceChannelId, - to_channel: bobChannelId, - amount: 1000, - memo: null, - nonce, - client_signature: 'b'.repeat(128), - }); - - // Verify the nonce is detected - const existing = await db.getTransferByNonce(nonce); - expect(existing).toBeDefined(); - expect(existing!.id).toBeDefined(); - }); - }); - - // ==================== Fee Calculation Tests ==================== - - describe('Fee Calculation', () => { - const FEE_TEST_PUBKEY = 'f'.repeat(64); - - beforeAll(async () => { - await createTestUser(FEE_TEST_PUBKEY); - }); - - it('should return free tier for new users', async () => { - const txCount = await db.getTransactionCount(FEE_TEST_PUBKEY); - const currentCount = txCount?.count ?? 0; - const remaining = Math.max(0, 500 - currentCount); - expect(remaining).toBeGreaterThan(0); - }); - - it('should increment transaction count', async () => { - const before = await db.getTransactionCount(FEE_TEST_PUBKEY); - const beforeCount = before?.count ?? 0; - - const newCount = await db.incrementTransactionCount(FEE_TEST_PUBKEY); - expect(newCount).toBe(beforeCount + 1); - }); - - it('should return correct fee schedule via API', async () => { - const res = await request(app) - .get('/api/v1/fees/schedule') - .expect(200); - - expect(res.body.success).toBe(true); - expect(res.body.data.freeTier).toBeDefined(); - expect(res.body.data.freeTier.freeTransactions).toBe(500); - expect(res.body.data.freeTier.offChainFeeRate).toBe('0%'); - expect(res.body.data.standardTier).toBeDefined(); - expect(res.body.data.standardTier.offChainFeeRate).toBe('0.1%'); - expect(res.body.data.standardTier.settlementFeeRate).toBe('0.5%'); - }); - - it('should calculate paid tier fees correctly', () => { - // Standard tier: off-chain 0.1%, settlement 0.5% - const amount = 1_000_000; - const offChainFee = Math.ceil(amount * 0.001); - const settlementFee = Math.ceil(amount * 0.005); - - expect(offChainFee).toBe(1000); - expect(settlementFee).toBe(5000); - }); - }); - - // ==================== Rate Limiting Tests ==================== - - describe('Rate Limiting', () => { - it('should block auth requests after threshold', async () => { - // Auth rate limit: 5 per 15 minutes - // Send 6 requests rapidly — the 6th should be rate limited - const pubkey = 'c'.repeat(64); - const results: number[] = []; - - for (let i = 0; i < 6; i++) { - const res = await request(app) - .post('/api/v1/auth/auth/challenge') - .send({ pubkey }); - results.push(res.status); - } - - // At least the last request should be rate limited (429) - expect(results).toContain(429); - }); - }); - - // ==================== Username Tests ==================== - - describe('Username Registration and Lookup', () => { - const USERNAME_PUBKEY = 'd'.repeat(64); - const TEST_USERNAME = 'satoshi_test'; - - beforeAll(async () => { - await createTestUser(USERNAME_PUBKEY, TEST_USERNAME); - }); - - it('should register a username for a user', async () => { - const user = await db.getUser(USERNAME_PUBKEY); - expect(user).toBeDefined(); - expect(user!.username).toBe(TEST_USERNAME); - }); - - it('should look up user by username', async () => { - const user = await db.getUserByUsername(TEST_USERNAME); - expect(user).toBeDefined(); - expect(user!.pubkey).toBe(USERNAME_PUBKEY); - }); - - it('should return undefined for non-existent username', async () => { - const user = await db.getUserByUsername('nonexistent_user_xyz'); - expect(user).toBeUndefined(); - }); - - it('should update username', async () => { - const newUsername = 'nakamoto_test'; - await db.updateUsername(USERNAME_PUBKEY, newUsername); - - const user = await db.getUser(USERNAME_PUBKEY); - expect(user!.username).toBe(newUsername); - - // Restore original - await db.updateUsername(USERNAME_PUBKEY, TEST_USERNAME); - }); - }); - - // ==================== Claim Link Tests ==================== - - describe('Claim Link Creation and Redemption', () => { - const CREATOR_PUBKEY = 'e'.repeat(64); - const CLAIMER_PUBKEY = '1'.repeat(64); - let claimId: string; - - beforeAll(async () => { - await createTestUser(CREATOR_PUBKEY); - await createTestUser(CLAIMER_PUBKEY); - }); - - it('should create a claim link in the database', async () => { - claimId = uuidv4(); - const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(); - - await db.createClaimLink({ - id: claimId, - creator_pubkey: CREATOR_PUBKEY, - amount: 100_000, - memo: 'Test claim', - expires_at: expiresAt, - }); - - const claim = await db.getClaimLink(claimId); - expect(claim).toBeDefined(); - expect(claim!.creator_pubkey).toBe(CREATOR_PUBKEY); - expect(claim!.amount).toBe(100_000); - expect(claim!.memo).toBe('Test claim'); - expect(claim!.claimed_by).toBeNull(); - }); - - it('should retrieve claim link details via API', async () => { - const res = await request(app) - .get(`/api/v1/claims/claim/${claimId}`) - .expect(200); - - expect(res.body.success).toBe(true); - expect(res.body.data.claimId).toBe(claimId); - expect(res.body.data.amount).toBe('100000'); - expect(res.body.data.claimed).toBe(false); - expect(res.body.data.expired).toBe(false); - }); - - it('should mark claim link as redeemed in database', async () => { - await db.claimLink(claimId, CLAIMER_PUBKEY); - - const claim = await db.getClaimLink(claimId); - expect(claim!.claimed_by).toBe(CLAIMER_PUBKEY); - expect(claim!.claimed_at).not.toBeNull(); - }); - - it('should return 404 for non-existent claim link', async () => { - const fakeId = uuidv4(); - const res = await request(app) - .get(`/api/v1/claims/claim/${fakeId}`) - .expect(404); - - expect(res.body.success).toBe(false); - }); - }); - - // ==================== Health Endpoint Tests ==================== - - describe('Health Endpoint', () => { - it('should return health status with all checks', async () => { - const res = await request(app) - .get('/health') - .expect(200); - - expect(res.body.status).toBe('ok'); - expect(res.body.service).toBe('runebolt-backend'); - expect(res.body.version).toBeDefined(); - expect(res.body.uptime).toBeGreaterThanOrEqual(0); - expect(res.body.timestamp).toBeDefined(); - expect(res.body.checks).toBeDefined(); - expect(res.body.checks.database).toBeDefined(); - expect(res.body.checks.database.status).toBe('ok'); - expect(res.body.checks.database.latencyMs).toBeGreaterThanOrEqual(0); - expect(res.body.checks.database.pool).toBeDefined(); - expect(res.body.checks.redis).toBeDefined(); - }); - }); - - // ==================== Root Endpoint Tests ==================== - - describe('Root Endpoint', () => { - it('should return service info with version', async () => { - const res = await request(app) - .get('/') - .expect(200); - - expect(res.body.name).toBe('RuneBolt Backend'); - expect(res.body.version).toBeDefined(); - expect(res.body.endpoints).toBeDefined(); - expect(res.body.endpoints.health).toBe('/health'); - }); - }); - - // ==================== Stats Endpoint Tests ==================== - - describe('Stats Endpoint', () => { - it('should return public platform stats', async () => { - const res = await request(app) - .get('/api/v1/stats') - .expect(200); - - expect(res.body.success).toBe(true); - expect(res.body.data).toBeDefined(); - expect(typeof res.body.data.totalUsers).toBe('number'); - expect(typeof res.body.data.totalTransfers).toBe('number'); - expect(res.body.data.totalVolume).toBeDefined(); - expect(typeof res.body.data.totalChannels).toBe('number'); - expect(typeof res.body.data.openChannels).toBe('number'); - }); - }); -}); diff --git a/legacy/taproot-assets-era/backend/src/__tests__/rune-encoding.test.ts b/legacy/taproot-assets-era/backend/src/__tests__/rune-encoding.test.ts deleted file mode 100644 index ed6040f..0000000 --- a/legacy/taproot-assets-era/backend/src/__tests__/rune-encoding.test.ts +++ /dev/null @@ -1,431 +0,0 @@ -/** - * Rune encoding/decoding tests for RuneBolt. - * - * Verifies LEB128 encoding, Runestone building, Runestone parsing, - * and round-trip correctness against the Runes protocol specification. - */ - -import { describe, it, expect } from 'vitest'; -import { encodeLEB128, RuneBuilder } from '../rune/RuneBuilder'; -import { decodeLEB128, RuneParser, RunestoneTag } from '../rune/RuneParser'; -import { - DOG_RUNE_ID, - DOG_RUNE_BLOCK, - DOG_RUNE_TX, - formatDogAmount, - parseDogAmount, -} from '../rune/RuneConstants'; - -// ==================== LEB128 Encoding Tests ==================== - -describe('LEB128 Encoding', () => { - it('should encode 0 as single byte 0x00', () => { - const buf = encodeLEB128(0n); - expect(buf.length).toBe(1); - expect(buf[0]).toBe(0x00); - }); - - it('should encode 1 as single byte 0x01', () => { - const buf = encodeLEB128(1n); - expect(buf.length).toBe(1); - expect(buf[0]).toBe(0x01); - }); - - it('should encode 127 as single byte 0x7f', () => { - const buf = encodeLEB128(127n); - expect(buf.length).toBe(1); - expect(buf[0]).toBe(0x7f); - }); - - it('should encode 128 as two bytes [0x80, 0x01]', () => { - const buf = encodeLEB128(128n); - expect(buf.length).toBe(2); - expect(buf[0]).toBe(0x80); - expect(buf[1]).toBe(0x01); - }); - - it('should encode 255 as two bytes [0xff, 0x01]', () => { - const buf = encodeLEB128(255n); - expect(buf.length).toBe(2); - expect(buf[0]).toBe(0xff); - expect(buf[1]).toBe(0x01); - }); - - it('should encode 300 as two bytes [0xac, 0x02]', () => { - const buf = encodeLEB128(300n); - expect(buf.length).toBe(2); - expect(buf[0]).toBe(0xac); - expect(buf[1]).toBe(0x02); - }); - - it('should encode DOG block 840000 correctly', () => { - // 840000 in LEB128: - // 840000 = 0xCD140 - // Byte 1: 0x40 | 0x80 = 0xC0 - // Byte 2: 0x28 | 0x80 = 0xA8 ... let's just verify round-trip - const buf = encodeLEB128(BigInt(DOG_RUNE_BLOCK)); - expect(buf.length).toBeGreaterThan(1); // 840000 > 127 - expect(buf.length).toBeLessThanOrEqual(3); // 840000 < 2^21 - - // Verify round-trip - const { value, bytesRead } = decodeLEB128(buf, 0); - expect(value).toBe(BigInt(DOG_RUNE_BLOCK)); - expect(bytesRead).toBe(buf.length); - }); - - it('should encode large values (2^32) correctly', () => { - const val = 2n ** 32n; - const buf = encodeLEB128(val); - const { value } = decodeLEB128(buf, 0); - expect(value).toBe(val); - }); - - it('should encode very large values (2^64) correctly', () => { - const val = 2n ** 64n; - const buf = encodeLEB128(val); - const { value } = decodeLEB128(buf, 0); - expect(value).toBe(val); - }); - - it('should reject negative values', () => { - expect(() => encodeLEB128(-1n)).toThrow('negative'); - }); -}); - -// ==================== LEB128 Decoding Tests ==================== - -describe('LEB128 Decoding', () => { - it('should decode 0 from single byte', () => { - const buf = Buffer.from([0x00]); - const { value, bytesRead } = decodeLEB128(buf, 0); - expect(value).toBe(0n); - expect(bytesRead).toBe(1); - }); - - it('should decode 127 from single byte', () => { - const buf = Buffer.from([0x7f]); - const { value, bytesRead } = decodeLEB128(buf, 0); - expect(value).toBe(127n); - expect(bytesRead).toBe(1); - }); - - it('should decode multi-byte values correctly', () => { - const buf = Buffer.from([0x80, 0x01]); - const { value } = decodeLEB128(buf, 0); - expect(value).toBe(128n); - }); - - it('should decode at arbitrary offset', () => { - const buf = Buffer.from([0xff, 0xff, 0x80, 0x01, 0x00]); - const { value, bytesRead } = decodeLEB128(buf, 2); - expect(value).toBe(128n); - expect(bytesRead).toBe(2); - }); - - it('should throw on truncated LEB128', () => { - const buf = Buffer.from([0x80]); // continuation bit set but no next byte - expect(() => decodeLEB128(buf, 0)).toThrow(); - }); - - it('should throw on excessively long encoding (>18 bytes)', () => { - // 19 bytes all with continuation bit set - const bytes = new Array(19).fill(0x80); - bytes.push(0x01); // terminate - const buf = Buffer.from(bytes); - expect(() => decodeLEB128(buf, 0)).toThrow('too long'); - }); - - it('should round-trip all test values', () => { - const testValues = [0n, 1n, 127n, 128n, 255n, 256n, 16383n, 16384n, 840000n, 2n ** 32n, 2n ** 64n - 1n]; - for (const val of testValues) { - const encoded = encodeLEB128(val); - const { value } = decodeLEB128(encoded, 0); - expect(value).toBe(val); - } - }); -}); - -// ==================== Rune ID Parsing Tests ==================== - -describe('Rune ID Encoding/Decoding', () => { - it('should decode DOG rune ID', () => { - const { block, tx } = RuneParser.decodeRuneId(DOG_RUNE_ID); - expect(block).toBe(840000); - expect(tx).toBe(3); - }); - - it('should encode rune ID', () => { - const encoded = RuneParser.encodeRuneId(840000, 3); - expect(encoded).toBe('840000:3'); - }); - - it('should round-trip rune ID', () => { - const { block, tx } = RuneParser.decodeRuneId('123456:789'); - expect(RuneParser.encodeRuneId(block, tx)).toBe('123456:789'); - }); - - it('should reject invalid rune ID format', () => { - expect(() => RuneParser.decodeRuneId('invalid')).toThrow('Invalid rune ID format'); - expect(() => RuneParser.decodeRuneId('abc:def')).toThrow('Invalid rune ID components'); - expect(() => RuneParser.decodeRuneId('1:2:3')).toThrow('Invalid rune ID format'); - }); -}); - -// ==================== DOG Amount Formatting Tests ==================== - -describe('DOG Amount Formatting', () => { - it('should format raw amount to display string', () => { - expect(formatDogAmount(1234500000n)).toBe('12345.00000'); - expect(formatDogAmount(100000n)).toBe('1.00000'); - expect(formatDogAmount(0n)).toBe('0.00000'); - expect(formatDogAmount(1n)).toBe('0.00001'); - expect(formatDogAmount(99999n)).toBe('0.99999'); - }); - - it('should parse display string to raw amount', () => { - expect(parseDogAmount('12345.5')).toBe(1234550000n); - expect(parseDogAmount('1')).toBe(100000n); - expect(parseDogAmount('0.00001')).toBe(1n); - expect(parseDogAmount('0')).toBe(0n); - }); - - it('should round-trip format/parse', () => { - const values = [0n, 1n, 100000n, 1234567890n, 99999999999n]; - for (const val of values) { - expect(parseDogAmount(formatDogAmount(val))).toBe(val); - } - }); - - it('should truncate excess decimal places', () => { - // parseDogAmount truncates to DOG_DECIMALS (5) - expect(parseDogAmount('1.123456789')).toBe(parseDogAmount('1.12345')); - }); -}); - -// ==================== Runestone Building Tests ==================== - -describe('Runestone Building', () => { - it('should build a valid single-edict Runestone', () => { - const output = RuneBuilder.buildRunestoneOutput(DOG_RUNE_ID, 100000n, 1); - expect(output).toBeInstanceOf(Buffer); - - // Must start with OP_RETURN (0x6a) + OP_13 (0x5d) - expect(output[0]).toBe(0x6a); - expect(output[1]).toBe(0x5d); - - // Should be parseable - const parsed = RuneParser.parseRunestone(output); - expect(parsed).not.toBeNull(); - expect(parsed!.edicts.length).toBe(1); - expect(parsed!.edicts[0].runeId.block).toBe(DOG_RUNE_BLOCK); - expect(parsed!.edicts[0].runeId.tx).toBe(DOG_RUNE_TX); - expect(parsed!.edicts[0].amount).toBe(100000n); - expect(parsed!.edicts[0].output).toBe(1); - }); - - it('should build Runestone with pointer', () => { - const output = RuneBuilder.buildRunestoneWithPointer(DOG_RUNE_ID, 50000n, 1, 2); - - const parsed = RuneParser.parseRunestone(output); - expect(parsed).not.toBeNull(); - expect(parsed!.pointer).toBe(2); - expect(parsed!.edicts.length).toBe(1); - expect(parsed!.edicts[0].amount).toBe(50000n); - expect(parsed!.edicts[0].output).toBe(1); - }); - - it('should build commitment Runestone with two edicts (local/remote split)', () => { - const localBalance = 70000n; - const remoteBalance = 30000n; - const output = RuneBuilder.buildCommitmentRunestone('test-channel', localBalance, remoteBalance); - - const parsed = RuneParser.parseRunestone(output); - expect(parsed).not.toBeNull(); - expect(parsed!.edicts.length).toBe(2); - - // First edict: local balance -> output 1 - expect(parsed!.edicts[0].runeId.block).toBe(DOG_RUNE_BLOCK); - expect(parsed!.edicts[0].runeId.tx).toBe(DOG_RUNE_TX); - expect(parsed!.edicts[0].amount).toBe(localBalance); - expect(parsed!.edicts[0].output).toBe(1); - - // Second edict: remote balance -> output 2 (delta-encoded, same rune) - expect(parsed!.edicts[1].runeId.block).toBe(DOG_RUNE_BLOCK); - expect(parsed!.edicts[1].runeId.tx).toBe(DOG_RUNE_TX); - expect(parsed!.edicts[1].amount).toBe(remoteBalance); - expect(parsed!.edicts[1].output).toBe(2); - }); - - it('should build multi-transfer Runestone with sorted edicts', () => { - const transfers = [ - { runeId: '840001:1', amount: 500n, outputIndex: 2 }, - { runeId: '840000:3', amount: 1000n, outputIndex: 1 }, - { runeId: '840000:5', amount: 200n, outputIndex: 3 }, - ]; - - const output = RuneBuilder.buildMultiTransferRunestone(transfers); - const parsed = RuneParser.parseRunestone(output); - expect(parsed).not.toBeNull(); - expect(parsed!.edicts.length).toBe(3); - - // Edicts should be sorted by rune ID (block, then tx) - // 840000:3, 840000:5, 840001:1 - expect(parsed!.edicts[0].runeId.block).toBe(840000); - expect(parsed!.edicts[0].runeId.tx).toBe(3); - expect(parsed!.edicts[0].amount).toBe(1000n); - - expect(parsed!.edicts[1].runeId.block).toBe(840000); - expect(parsed!.edicts[1].runeId.tx).toBe(5); - expect(parsed!.edicts[1].amount).toBe(200n); - - expect(parsed!.edicts[2].runeId.block).toBe(840001); - expect(parsed!.edicts[2].runeId.tx).toBe(1); - expect(parsed!.edicts[2].amount).toBe(500n); - }); - - it('should reject empty transfer list', () => { - expect(() => RuneBuilder.buildMultiTransferRunestone([])).toThrow('no transfers'); - }); -}); - -// ==================== Runestone Round-Trip Tests ==================== - -describe('Runestone Round-Trip', () => { - it('should round-trip single edict', () => { - const amount = 123456789n; - const output = RuneBuilder.buildRunestoneOutput(DOG_RUNE_ID, amount, 0); - const parsed = RuneParser.parseRunestone(output); - - expect(parsed).not.toBeNull(); - expect(parsed!.edicts.length).toBe(1); - expect(parsed!.edicts[0].amount).toBe(amount); - expect(parsed!.edicts[0].runeId.block).toBe(DOG_RUNE_BLOCK); - expect(parsed!.edicts[0].runeId.tx).toBe(DOG_RUNE_TX); - }); - - it('should round-trip commitment with zero balances', () => { - const output = RuneBuilder.buildCommitmentRunestone('ch', 0n, 100000n); - const parsed = RuneParser.parseRunestone(output); - - expect(parsed).not.toBeNull(); - expect(parsed!.edicts[0].amount).toBe(0n); - expect(parsed!.edicts[1].amount).toBe(100000n); - }); - - it('should round-trip large amounts', () => { - const largeAmount = 2n ** 53n - 1n; // MAX_SAFE_INTEGER as bigint - const output = RuneBuilder.buildRunestoneOutput(DOG_RUNE_ID, largeAmount, 1); - const parsed = RuneParser.parseRunestone(output); - - expect(parsed).not.toBeNull(); - expect(parsed!.edicts[0].amount).toBe(largeAmount); - }); - - it('should round-trip with various rune IDs', () => { - const runeIds = ['0:0', '1:0', '840000:3', '999999:999']; - for (const runeId of runeIds) { - const output = RuneBuilder.buildRunestoneOutput(runeId, 1000n, 0); - const parsed = RuneParser.parseRunestone(output); - const { block, tx } = RuneParser.decodeRuneId(runeId); - - expect(parsed).not.toBeNull(); - expect(parsed!.edicts[0].runeId.block).toBe(block); - expect(parsed!.edicts[0].runeId.tx).toBe(tx); - } - }); -}); - -// ==================== Runestone Parser Edge Cases ==================== - -describe('Runestone Parser Edge Cases', () => { - it('should return null for non-OP_RETURN script', () => { - const buf = Buffer.from([0x76, 0xa9, 0x14]); // P2PKH prefix - expect(RuneParser.parseRunestone(buf)).toBeNull(); - }); - - it('should return null for OP_RETURN without OP_13', () => { - const buf = Buffer.from([0x6a, 0x04, 0x01, 0x02, 0x03, 0x04]); // arbitrary OP_RETURN - expect(RuneParser.parseRunestone(buf)).toBeNull(); - }); - - it('should return null for buffer too short', () => { - expect(RuneParser.parseRunestone(Buffer.from([0x6a]))).toBeNull(); - expect(RuneParser.parseRunestone(Buffer.from([]))).toBeNull(); - }); - - it('should return null for empty Runestone (OP_RETURN OP_13 with no data pushes)', () => { - // FINDING: Parser requires minimum 3 bytes (OP_RETURN + OP_13 + at least 1 push byte). - // An empty Runestone (just OP_RETURN OP_13) returns null. - // Per Runes spec, this SHOULD be a valid (no-op) Runestone. - const buf = Buffer.from([0x6a, 0x5d]); - const parsed = RuneParser.parseRunestone(buf); - expect(parsed).toBeNull(); // Actual behavior (spec deviation) - }); - - it('should detect Runestone transactions by hex pattern', () => { - expect(RuneParser.isRunestoneTransaction('00006a5d0100')).toBe(true); - expect(RuneParser.isRunestoneTransaction('00006a040102')).toBe(false); - }); -}); - -// ==================== Known Mainnet Runestone Verification ==================== - -describe('Runestone Protocol Conformance', () => { - it('should encode DOG rune body tag as 0x00 (Body = 0)', () => { - // The Body tag in the Runes protocol is 0 - const bodyTag = encodeLEB128(BigInt(RunestoneTag.Body)); - expect(bodyTag.length).toBe(1); - expect(bodyTag[0]).toBe(0x00); - }); - - it('should encode Pointer tag as 22 (0x16)', () => { - const pointerTag = encodeLEB128(BigInt(RunestoneTag.Pointer)); - expect(pointerTag.length).toBe(1); - expect(pointerTag[0]).toBe(0x16); - }); - - it('should encode Mint tag as 20 (0x14)', () => { - const mintTag = encodeLEB128(BigInt(RunestoneTag.Mint)); - expect(mintTag.length).toBe(1); - expect(mintTag[0]).toBe(0x14); - }); - - it('should produce correct byte layout for DOG transfer', () => { - // A transfer of 1 DOG (100000 raw) to output 1 - const output = RuneBuilder.buildRunestoneOutput(DOG_RUNE_ID, 100000n, 1); - - // Expected structure: - // OP_RETURN (0x6a) + OP_13 (0x5d) + push_length + payload - expect(output[0]).toBe(0x6a); - expect(output[1]).toBe(0x5d); - - // Parse and verify - const parsed = RuneParser.parseRunestone(output); - expect(parsed).not.toBeNull(); - expect(parsed!.edicts[0].runeId.block).toBe(840000); - expect(parsed!.edicts[0].runeId.tx).toBe(3); - expect(parsed!.edicts[0].amount).toBe(100000n); - expect(parsed!.edicts[0].output).toBe(1); - }); - - it('should use delta encoding correctly in multi-edict Runestones', () => { - // Two edicts for the same rune: delta should be 0:0 - const output = RuneBuilder.buildCommitmentRunestone('ch', 50000n, 50000n); - const parsed = RuneParser.parseRunestone(output); - - expect(parsed).not.toBeNull(); - expect(parsed!.edicts.length).toBe(2); - // Both should resolve to the same rune ID after delta decoding - expect(parsed!.edicts[0].runeId.block).toBe(parsed!.edicts[1].runeId.block); - expect(parsed!.edicts[0].runeId.tx).toBe(parsed!.edicts[1].runeId.tx); - }); - - it('should handle data push encoding for payloads ≤75 bytes', () => { - // Small payload: should use direct push (opcode = length) - const output = RuneBuilder.buildRunestoneOutput(DOG_RUNE_ID, 1n, 0); - // After OP_RETURN (0x6a) + OP_13 (0x5d), the next byte is the push length - const pushLen = output[2]; - expect(pushLen).toBeLessThanOrEqual(0x4b); // Direct push max - expect(pushLen).toBe(output.length - 3); // Total - 3 header bytes - }); -}); diff --git a/legacy/taproot-assets-era/backend/src/__tests__/simulation.test.ts b/legacy/taproot-assets-era/backend/src/__tests__/simulation.test.ts deleted file mode 100644 index f7b346f..0000000 --- a/legacy/taproot-assets-era/backend/src/__tests__/simulation.test.ts +++ /dev/null @@ -1,645 +0,0 @@ -/** - * RuneBolt Full End-to-End Simulation Test Suite - * - * Tests the ENTIRE RuneBolt flow without spending real Bitcoin. - * Covers: auth, channels, transfers, fees, security, concurrency, crypto. - * - * Requires a running PostgreSQL instance. - * Set DATABASE_URL env var or uses default test connection string. - * - * NOTE: PostgreSQL returns BIGINT columns as strings, not numbers. - * All balance/capacity assertions use Number() or String() coercion. - */ - -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import { v4 as uuidv4 } from 'uuid'; -import crypto from 'crypto'; -import Database from '../db/Database'; -import { - generateTestKeypair, - signChallenge, - verifySignature, - createTestChannel, - createTestUser, - simulateFundingConfirmation, - generateNonce, - TestKeypair, -} from './test-helpers'; -import { calculateReserve, validateTransferAgainstReserve, getSpendableBalance } from '../channels/ChannelReserves'; -import { ChallengeManager } from '../auth/ChallengeManager'; -import { FeeManager } from '../fees/FeeManager'; -import { ChannelState, canTransition, assertTransition } from '../channels/ChannelState'; - -// Initialize DB directly (not through index.ts which has mainnet checks) -process.env.NODE_ENV = 'test'; -const TEST_DB_URL = process.env.DATABASE_URL || 'postgresql://gravity@localhost:5432/runebolt_test'; -const db = Database.getInstance(); -db.initialize(TEST_DB_URL); - -// ==================== Scenario 1: DOG Transfer Flow ==================== - -describe('Scenario 1: DOG Transfer Flow (End-to-End)', () => { - let alice: TestKeypair; - let bob: TestKeypair; - let aliceChallengeId: string; - let aliceChallengeMessage: string; - let aliceChannelId: string; - let bobChannelId: string; - - beforeAll(async () => { - try { - await db.runMigrations(); - } catch { - // Migrations may already be applied - } - - alice = generateTestKeypair(); - bob = generateTestKeypair(); - - // Create users first (FK constraint on challenges table) - await createTestUser(db, alice.publicKey); - await createTestUser(db, bob.publicKey); - }); - - it('Step 1: Alice and Bob generate valid secp256k1 keypairs', () => { - expect(alice.privateKey).toHaveLength(64); - expect(alice.publicKey).toHaveLength(64); - expect(bob.privateKey).toHaveLength(64); - expect(bob.publicKey).toHaveLength(64); - expect(alice.publicKey).not.toBe(bob.publicKey); - expect(/^[0-9a-f]{64}$/.test(alice.publicKey)).toBe(true); - expect(/^[0-9a-f]{64}$/.test(bob.publicKey)).toBe(true); - }); - - it('Step 2: Alice requests auth challenge', async () => { - const challengeManager = new ChallengeManager(); - const result = await challengeManager.createChallenge(alice.publicKey); - - expect(result.challengeId).toBeDefined(); - expect(result.message).toContain('RuneBolt authentication challenge'); - expect(result.message).toContain(alice.publicKey); - expect(result.message).toContain('Nonce:'); - expect(result.message).toContain('Timestamp:'); - - aliceChallengeId = result.challengeId; - aliceChallengeMessage = result.message; - }); - - it('Step 3: Alice signs challenge with real Schnorr signature → verified', async () => { - const signature = await signChallenge(alice.privateKey, aliceChallengeMessage); - expect(signature).toHaveLength(128); - - const localValid = await verifySignature(alice.publicKey, aliceChallengeMessage, signature); - expect(localValid).toBe(true); - - const challengeManager = new ChallengeManager(); - const result = await challengeManager.verifyChallenge(aliceChallengeId, signature); - expect(result.valid).toBe(true); - expect(result.pubkey).toBe(alice.publicKey); - }); - - it('Step 4: Alice opens a DOG channel with 100,000 DOG (PENDING_OPEN)', async () => { - aliceChannelId = await createTestChannel( - db, alice.publicKey, 10_000_000_000, 10_000_000_000, 0, 'PENDING_OPEN' - ); - - const channel = await db.getChannel(aliceChannelId); - expect(channel).toBeDefined(); - expect(channel!.user_pubkey).toBe(alice.publicKey); - expect(Number(channel!.capacity)).toBe(10_000_000_000); - expect(channel!.state).toBe('PENDING_OPEN'); - }); - - it('Step 5: Simulate funding tx confirmation → channel activates (OPEN)', async () => { - await simulateFundingConfirmation(db, aliceChannelId); - - const channel = await db.getChannel(aliceChannelId); - expect(channel!.state).toBe('OPEN'); - expect(Number(channel!.local_balance)).toBe(10_000_000_000); - expect(Number(channel!.remote_balance)).toBe(0); - expect(channel!.funding_txid).toBeDefined(); - }); - - it('Step 6: Create Bob channel with inbound capacity', async () => { - bobChannelId = await createTestChannel( - db, bob.publicKey, 10_000_000_000, 0, 10_000_000_000, 'OPEN' - ); - - const channel = await db.getChannel(bobChannelId); - expect(channel!.state).toBe('OPEN'); - expect(Number(channel!.remote_balance)).toBe(10_000_000_000); - }); - - it('Step 7: Alice sends 10,000 DOG (1,000,000,000 raw) to Bob', async () => { - const transferAmount = 1_000_000_000; - - await db.updateChannelBalances(aliceChannelId, 10_000_000_000 - transferAmount, 0 + transferAmount); - await db.updateChannelBalances(bobChannelId, 0 + transferAmount, 10_000_000_000 - transferAmount); - await db.createTransfer({ - id: uuidv4(), - from_channel: aliceChannelId, - to_channel: bobChannelId, - amount: transferAmount, - memo: 'DOG transfer test', - nonce: generateNonce(), - client_signature: 'a'.repeat(128), - }); - }); - - it('Step 8: Alice balance = 90,000 DOG, Bob balance = 10,000 DOG', async () => { - const aliceCh = await db.getChannel(aliceChannelId); - expect(Number(aliceCh!.local_balance)).toBe(9_000_000_000); - expect(Number(aliceCh!.remote_balance)).toBe(1_000_000_000); - - const bobCh = await db.getChannel(bobChannelId); - expect(Number(bobCh!.local_balance)).toBe(1_000_000_000); - expect(Number(bobCh!.remote_balance)).toBe(9_000_000_000); - }); - - it('Step 9: Fee should be free (within first 500 txs)', async () => { - const txCount = await db.getTransactionCount(alice.publicKey); - const currentCount = txCount?.count ?? 0; - expect(currentCount).toBeLessThan(500); - }); - - it('Step 10: Alice closes channel cooperatively → CLOSING', async () => { - await db.updateChannelState(aliceChannelId, 'CLOSING'); - const channel = await db.getChannel(aliceChannelId); - expect(channel!.state).toBe('CLOSING'); - expect(Number(channel!.local_balance)).toBe(9_000_000_000); - expect(Number(channel!.remote_balance)).toBe(1_000_000_000); - }); -}); - -// ==================== Scenario 2: Security Tests ==================== - -describe('Scenario 2: Security Tests', () => { - let attacker: TestKeypair; - let victim: TestKeypair; - let attackerChannelId: string; - let victimChannelId: string; - - beforeAll(async () => { - attacker = generateTestKeypair(); - victim = generateTestKeypair(); - - await createTestUser(db, attacker.publicKey); - await createTestUser(db, victim.publicKey); - - attackerChannelId = await createTestChannel(db, attacker.publicKey, 100_000, 100_000, 0, 'OPEN'); - victimChannelId = await createTestChannel(db, victim.publicKey, 100_000, 0, 100_000, 'OPEN'); - }); - - it('should reject auth with wrong private key (invalid signature)', async () => { - const challengeManager = new ChallengeManager(); - const { challengeId, message } = await challengeManager.createChallenge(attacker.publicKey); - - const wrongSig = await signChallenge(victim.privateKey, message); - const result = await challengeManager.verifyChallenge(challengeId, wrongSig); - expect(result.valid).toBe(false); - expect(result.pubkey).toBeNull(); - }); - - it('should reject sending more than balance (overflow check)', async () => { - const channel = await db.getChannel(attackerChannelId); - const localBalance = BigInt(channel!.local_balance); - const overAmount = localBalance + 1n; - expect(localBalance < overAmount).toBe(true); - }); - - it('should reject zero and negative transfer amounts', () => { - expect(0n <= 0n).toBe(true); - expect(-1n <= 0n).toBe(true); - }); - - it('should enforce 1% reserve — cannot drain channel below reserve', () => { - const capacity = 100_000n; - const localBalance = 100_000n; - const reserve = calculateReserve(capacity); - - expect(reserve).toBe(1000n); - expect(validateTransferAgainstReserve(localBalance, capacity, localBalance - reserve)).toBe(true); - expect(validateTransferAgainstReserve(localBalance, capacity, localBalance - reserve + 1n)).toBe(false); - expect(validateTransferAgainstReserve(localBalance, capacity, localBalance)).toBe(false); - }); - - it('should prevent replay attacks via nonce uniqueness', async () => { - const nonce = generateNonce(); - - await db.createTransfer({ - id: uuidv4(), - from_channel: attackerChannelId, - to_channel: victimChannelId, - amount: 1000, - memo: null, - nonce, - client_signature: 'a'.repeat(128), - }); - - const existing = await db.getTransferByNonce(nonce); - expect(existing).toBeDefined(); - expect(existing!.id).toBeDefined(); - }); - - it('should reject replaying an old auth challenge (one-time use)', async () => { - const challengeManager = new ChallengeManager(); - const { challengeId, message } = await challengeManager.createChallenge(attacker.publicKey); - const signature = await signChallenge(attacker.privateKey, message); - - const first = await challengeManager.verifyChallenge(challengeId, signature); - expect(first.valid).toBe(true); - - const second = await challengeManager.verifyChallenge(challengeId, signature); - expect(second.valid).toBe(false); - }); - - it('should reject signature with wrong length', async () => { - const challengeManager = new ChallengeManager(); - const { challengeId } = await challengeManager.createChallenge(attacker.publicKey); - - const shortSig = 'a'.repeat(64); - const result = await challengeManager.verifyChallenge(challengeId, shortSig); - expect(result.valid).toBe(false); - }); -}); - -// ==================== Scenario 3: Fee System Tests ==================== - -describe('Scenario 3: Fee System Tests', () => { - const FEE_USER_PUBKEY = crypto.randomBytes(32).toString('hex'); - - beforeAll(async () => { - await createTestUser(db, FEE_USER_PUBKEY); - }); - - it('should start with 500 free transactions', async () => { - const txCount = await db.getTransactionCount(FEE_USER_PUBKEY); - const currentCount = txCount?.count ?? 0; - expect(Math.max(0, 500 - currentCount)).toBe(500); - }); - - it('should track transaction count increments', async () => { - for (let i = 0; i < 5; i++) { - await db.incrementTransactionCount(FEE_USER_PUBKEY); - } - - const txCount = await db.getTransactionCount(FEE_USER_PUBKEY); - expect(txCount!.count).toBe(5); - expect(Math.max(0, 500 - txCount!.count)).toBe(495); - }); - - it('should exhaust free tier at exactly 500 transactions', async () => { - const current = (await db.getTransactionCount(FEE_USER_PUBKEY))?.count ?? 0; - for (let i = current; i < 500; i++) { - await db.incrementTransactionCount(FEE_USER_PUBKEY); - } - - const txCount = await db.getTransactionCount(FEE_USER_PUBKEY); - expect(txCount!.count).toBe(500); - expect(Math.max(0, 500 - txCount!.count)).toBe(0); - }); - - it('should calculate FeeManager fees correctly for paid tier', async () => { - const feeManager = new FeeManager(); - const fee = await feeManager.calculateFee(FEE_USER_PUBKEY, 1_000_000n, 'off_chain'); - expect(fee.isFree).toBe(false); - expect(fee.feeRate).toBe(0.001); - expect(fee.feeAmount).toBe(1000n); - }); - - it('should calculate settlement fee at 0.5%', async () => { - const feeManager = new FeeManager(); - const fee = await feeManager.calculateFee(FEE_USER_PUBKEY, 1_000_000n, 'settlement'); - expect(fee.isFree).toBe(false); - expect(fee.feeRate).toBe(0.005); - expect(fee.feeAmount).toBe(5000n); - }); - - it('should calculate free tier for new user', async () => { - const newUser = crypto.randomBytes(32).toString('hex'); - await createTestUser(db, newUser); - const feeManager = new FeeManager(); - const fee = await feeManager.calculateFee(newUser, 1_000_000n, 'off_chain'); - expect(fee.isFree).toBe(true); - expect(fee.feeAmount).toBe(0n); - expect(fee.freeTransactionsRemaining).toBe(499); - }); -}); - -// ==================== Scenario 4: Multi-User Concurrent ==================== - -describe('Scenario 4: Multi-User Concurrent Operations', () => { - const NUM_USERS = 5; - const users: Array<{ pubkey: string; channelId: string }> = []; - - beforeAll(async () => { - for (let i = 0; i < NUM_USERS; i++) { - const kp = generateTestKeypair(); - await createTestUser(db, kp.publicKey); - const channelId = await createTestChannel( - db, kp.publicKey, 1_000_000, 500_000, 500_000, 'OPEN' - ); - users.push({ pubkey: kp.publicKey, channelId }); - } - }); - - it('should handle 5 simultaneous channel creations without error', () => { - expect(users.length).toBe(NUM_USERS); - for (const user of users) { - expect(user.channelId).toBeDefined(); - expect(user.pubkey).toHaveLength(64); - } - }); - - it('should handle 10 parallel transfers correctly', async () => { - const transferPromises: Promise[] = []; - - for (let i = 0; i < 10; i++) { - const fromIdx = i % NUM_USERS; - const toIdx = (i + 1) % NUM_USERS; - - transferPromises.push( - db.createTransfer({ - id: uuidv4(), - from_channel: users[fromIdx].channelId, - to_channel: users[toIdx].channelId, - amount: 1000, - memo: `concurrent transfer ${i}`, - nonce: generateNonce(), - client_signature: 'a'.repeat(128), - }) - ); - } - - await expect(Promise.all(transferPromises)).resolves.not.toThrow(); - }); - - it('should maintain unique nonces across concurrent transfers', () => { - const nonces = new Set(); - for (let i = 0; i < 100; i++) { - const nonce = generateNonce(); - expect(nonces.has(nonce)).toBe(false); - nonces.add(nonce); - } - expect(nonces.size).toBe(100); - }); - - it('should verify all channel states remain valid after concurrent ops', async () => { - for (const user of users) { - const channel = await db.getChannel(user.channelId); - expect(channel).toBeDefined(); - expect(channel!.state).toBe('OPEN'); - expect(Number(channel!.capacity)).toBe(1_000_000); - // BIGINT comes back as string, so coerce for arithmetic - expect(Number(channel!.local_balance) + Number(channel!.remote_balance)).toBe(Number(channel!.capacity)); - } - }); -}); - -// ==================== Scenario 5: Channel Reserve Tests ==================== - -describe('Scenario 5: Channel Reserve Enforcement', () => { - it('should calculate 1% reserve correctly', () => { - expect(calculateReserve(100_000n)).toBe(1000n); - expect(calculateReserve(1_000_000n)).toBe(10_000n); - expect(calculateReserve(10_000n)).toBe(100n); - expect(calculateReserve(100n)).toBe(1n); - expect(calculateReserve(1n)).toBe(1n); - expect(calculateReserve(0n)).toBe(1n); - }); - - it('should correctly compute spendable balance', () => { - expect(getSpendableBalance(100_000n, 100_000n)).toBe(99_000n); - expect(getSpendableBalance(1000n, 100_000n)).toBe(0n); - expect(getSpendableBalance(500n, 100_000n)).toBe(0n); - }); - - it('should validate transfer against reserve', () => { - const capacity = 1_000_000n; - const balance = 500_000n; - expect(validateTransferAgainstReserve(balance, capacity, 490_000n)).toBe(true); - expect(validateTransferAgainstReserve(balance, capacity, 490_001n)).toBe(false); - }); -}); - -// ==================== Scenario 6: Channel State Machine ==================== - -describe('Scenario 6: Channel State Machine', () => { - it('should validate all allowed transitions', () => { - expect(canTransition(ChannelState.PENDING_OPEN, ChannelState.OPEN)).toBe(true); - expect(canTransition(ChannelState.PENDING_OPEN, ChannelState.CLOSED)).toBe(true); - expect(canTransition(ChannelState.OPEN, ChannelState.CLOSING)).toBe(true); - expect(canTransition(ChannelState.OPEN, ChannelState.FORCE_CLOSING)).toBe(true); - expect(canTransition(ChannelState.CLOSING, ChannelState.CLOSED)).toBe(true); - expect(canTransition(ChannelState.FORCE_CLOSING, ChannelState.CLOSED)).toBe(true); - }); - - it('should reject invalid transitions', () => { - expect(canTransition(ChannelState.PENDING_OPEN, ChannelState.CLOSING)).toBe(false); - expect(canTransition(ChannelState.CLOSED, ChannelState.OPEN)).toBe(false); - expect(canTransition(ChannelState.CLOSING, ChannelState.OPEN)).toBe(false); - expect(canTransition(ChannelState.FORCE_CLOSING, ChannelState.OPEN)).toBe(false); - }); - - it('should throw on invalid transition via assertTransition', () => { - expect(() => assertTransition(ChannelState.CLOSED, ChannelState.OPEN)).toThrow('Invalid channel state transition'); - }); - - it('should follow valid state transitions in DB', async () => { - const kp = generateTestKeypair(); - await createTestUser(db, kp.publicKey); - - const chId = await createTestChannel(db, kp.publicKey, 100_000, 100_000, 0, 'PENDING_OPEN'); - await db.updateChannelState(chId, 'OPEN'); - let ch = await db.getChannel(chId); - expect(ch!.state).toBe('OPEN'); - - await db.updateChannelState(chId, 'CLOSING'); - ch = await db.getChannel(chId); - expect(ch!.state).toBe('CLOSING'); - - await db.updateChannelState(chId, 'CLOSED'); - ch = await db.getChannel(chId); - expect(ch!.state).toBe('CLOSED'); - }); - - it('should support force close path in DB', async () => { - const kp = generateTestKeypair(); - await createTestUser(db, kp.publicKey); - - const chId = await createTestChannel(db, kp.publicKey, 100_000, 100_000, 0, 'OPEN'); - - await db.updateChannelState(chId, 'FORCE_CLOSING'); - let ch = await db.getChannel(chId); - expect(ch!.state).toBe('FORCE_CLOSING'); - - await db.updateChannelState(chId, 'CLOSED'); - ch = await db.getChannel(chId); - expect(ch!.state).toBe('CLOSED'); - }); - - it('FINDING: DB allows invalid state transitions (no DB-level enforcement)', async () => { - const kp = generateTestKeypair(); - await createTestUser(db, kp.publicKey); - - const chId = await createTestChannel(db, kp.publicKey, 100_000, 100_000, 0, 'CLOSED'); - // DB allows CLOSED -> OPEN (which is invalid per state machine) - await db.updateChannelState(chId, 'OPEN'); - const ch = await db.getChannel(chId); - expect(ch!.state).toBe('OPEN'); - }); -}); - -// ==================== Scenario 7: Bitmap Escrow ==================== - -describe('Scenario 7: Bitmap Escrow Flow', () => { - it('should have escrow table accessible', async () => { - const kp = generateTestKeypair(); - const escrows = await db.getEscrowsByPubkey(kp.publicKey); - expect(Array.isArray(escrows)).toBe(true); - expect(escrows.length).toBe(0); - }); -}); - -// ==================== Scenario 8: Cryptographic Verification ==================== - -describe('Scenario 8: Cryptographic Verification', () => { - it('should generate unique keypairs every time', () => { - const kp1 = generateTestKeypair(); - const kp2 = generateTestKeypair(); - expect(kp1.publicKey).not.toBe(kp2.publicKey); - expect(kp1.privateKey).not.toBe(kp2.privateKey); - }); - - it('should sign and verify correctly with matching keys', async () => { - const kp = generateTestKeypair(); - const sig = await signChallenge(kp.privateKey, 'test message for signing'); - const valid = await verifySignature(kp.publicKey, 'test message for signing', sig); - expect(valid).toBe(true); - }); - - it('should reject signature from wrong key', async () => { - const kp1 = generateTestKeypair(); - const kp2 = generateTestKeypair(); - const sig = await signChallenge(kp1.privateKey, 'test message'); - const valid = await verifySignature(kp2.publicKey, 'test message', sig); - expect(valid).toBe(false); - }); - - it('should reject tampered message', async () => { - const kp = generateTestKeypair(); - const sig = await signChallenge(kp.privateKey, 'original message'); - const valid = await verifySignature(kp.publicKey, 'tampered message', sig); - expect(valid).toBe(false); - }); - - it('should produce 64-byte Schnorr signatures', async () => { - const kp = generateTestKeypair(); - const sig = await signChallenge(kp.privateKey, 'test'); - expect(sig).toHaveLength(128); - }); - - it('should handle special characters in message', async () => { - const kp = generateTestKeypair(); - const message = 'RuneBolt auth\nNonce: abc123\nTimestamp: 1234567890\n🔒'; - const sig = await signChallenge(kp.privateKey, message); - const valid = await verifySignature(kp.publicKey, message, sig); - expect(valid).toBe(true); - }); -}); - -// ==================== Scenario 9: Overflow & Edge Cases ==================== - -describe('Scenario 9: Overflow and Edge Cases', () => { - it('should handle max safe BigInt amounts in reserve calculation', () => { - const maxSafe = BigInt(Number.MAX_SAFE_INTEGER); - const reserve = calculateReserve(maxSafe); - expect(reserve).toBeGreaterThan(0n); - expect(typeof reserve).toBe('bigint'); - }); - - it('should handle minimum reserve (capacity = 1)', () => { - expect(calculateReserve(1n)).toBe(1n); - }); - - it('should preserve balance invariant: local + remote = capacity', async () => { - const kp = generateTestKeypair(); - await createTestUser(db, kp.publicKey); - - const capacity = 1_000_000; - const channelId = await createTestChannel(db, kp.publicKey, capacity, capacity, 0, 'OPEN'); - - const updates = [[900_000, 100_000], [500_000, 500_000], [100_000, 900_000], [0, 1_000_000]]; - - for (const [local, remote] of updates) { - await db.updateChannelBalances(channelId, local, remote); - const ch = await db.getChannel(channelId); - expect(Number(ch!.local_balance) + Number(ch!.remote_balance)).toBe(capacity); - } - }); - - it('FINDING: DB does NOT enforce balance invariant (local + remote = capacity)', async () => { - const kp = generateTestKeypair(); - await createTestUser(db, kp.publicKey); - - const channelId = await createTestChannel(db, kp.publicKey, 100_000, 100_000, 0, 'OPEN'); - await db.updateChannelBalances(channelId, 200_000, 200_000); - const ch = await db.getChannel(channelId); - expect(Number(ch!.local_balance) + Number(ch!.remote_balance)).toBe(400_000); // Exceeds capacity! - expect(Number(ch!.capacity)).toBe(100_000); - }); - - it('FINDING: DB allows negative balances', async () => { - const kp = generateTestKeypair(); - await createTestUser(db, kp.publicKey); - - const channelId = await createTestChannel(db, kp.publicKey, 100_000, 100_000, 0, 'OPEN'); - await db.updateChannelBalances(channelId, -50_000, 150_000); - const ch = await db.getChannel(channelId); - expect(Number(ch!.local_balance)).toBe(-50_000); - }); -}); - -// ==================== Scenario 10: Commitment Tracking ==================== - -describe('Scenario 10: Commitment Tracking', () => { - it('should create and retrieve commitments', async () => { - const kp = generateTestKeypair(); - await createTestUser(db, kp.publicKey); - const channelId = await createTestChannel(db, kp.publicKey, 100_000, 100_000, 0, 'OPEN'); - - await db.createCommitment({ channel_id: channelId, sequence: 0, local_balance: 100_000, remote_balance: 0 }); - await db.createCommitment({ channel_id: channelId, sequence: 1, local_balance: 90_000, remote_balance: 10_000 }); - - const latest = await db.getLatestCommitment(channelId); - expect(latest).toBeDefined(); - expect(latest!.sequence).toBe(1); - expect(Number(latest!.local_balance)).toBe(90_000); - expect(Number(latest!.remote_balance)).toBe(10_000); - }); - - it('should track commitment history', async () => { - const kp = generateTestKeypair(); - await createTestUser(db, kp.publicKey); - const channelId = await createTestChannel(db, kp.publicKey, 100_000, 100_000, 0, 'OPEN'); - - for (let i = 0; i < 5; i++) { - await db.createCommitment({ - channel_id: channelId, - sequence: i, - local_balance: 100_000 - i * 10_000, - remote_balance: i * 10_000, - }); - } - - const history = await db.getCommitmentsByChannel(channelId, 10); - expect(history.length).toBe(5); - expect(history[0].sequence).toBe(4); - expect(history[4].sequence).toBe(0); - }); -}); - -// Clean up at the very end -afterAll(async () => { - await db.close(); -}); diff --git a/legacy/taproot-assets-era/backend/src/__tests__/test-helpers.ts b/legacy/taproot-assets-era/backend/src/__tests__/test-helpers.ts deleted file mode 100644 index 507eb69..0000000 --- a/legacy/taproot-assets-era/backend/src/__tests__/test-helpers.ts +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Test helpers for RuneBolt simulation tests. - * - * Provides real cryptographic operations using @noble/secp256k1 v3 - * for generating keypairs and Schnorr signatures identical to - * those used in production. - */ - -import * as secp256k1 from '@noble/secp256k1'; -import { sha256 } from '@noble/hashes/sha2.js'; -import { hmac } from '@noble/hashes/hmac.js'; -import { bytesToHex, randomBytes } from '@noble/hashes/utils.js'; -import crypto from 'crypto'; -import { v4 as uuidv4 } from 'uuid'; -import Database from '../db/Database'; - -// Configure @noble/secp256k1 v3 with hash functions (must match production) -secp256k1.hashes.sha256 = (msg: Uint8Array) => sha256(msg); -secp256k1.hashes.hmacSha256 = (key: Uint8Array, ...msgs: Uint8Array[]) => - hmac(sha256, key, secp256k1.etc.concatBytes(...msgs)); - -export interface TestKeypair { - privateKey: string; // 64-char hex (32 bytes) - publicKey: string; // 64-char hex (32-byte x-only Schnorr pubkey) -} - -/** - * Generate a real secp256k1 keypair suitable for Schnorr signing. - * Returns x-only public key (32 bytes) as used by BIP-340. - */ -export function generateTestKeypair(): TestKeypair { - const privBytes = randomBytes(32); - const privateKey = bytesToHex(privBytes); - // getPublicKey with second arg true returns compressed (33 bytes), - // but for Schnorr/BIP-340 we need the x-only (32 bytes) form. - const pubFull = secp256k1.getPublicKey(privBytes, true); - // x-only: drop the prefix byte - const publicKey = bytesToHex(pubFull.slice(1)); - return { privateKey, publicKey }; -} - -/** - * Sign a challenge message with a private key using BIP-340 Schnorr. - * This mirrors the exact signing flow a real client would use. - */ -export async function signChallenge( - privateKey: string, - message: string -): Promise { - const messageHash = sha256(new TextEncoder().encode(message)); - const privBytes = new Uint8Array(Buffer.from(privateKey, 'hex')); - const sig = await secp256k1.schnorr.sign(messageHash, privBytes); - return bytesToHex(sig); -} - -/** - * Verify a Schnorr signature (mirrors ChallengeManager.verifyChallenge). - */ -export async function verifySignature( - publicKey: string, - message: string, - signature: string -): Promise { - const messageHash = sha256(new TextEncoder().encode(message)); - const sigBytes = new Uint8Array(Buffer.from(signature, 'hex')); - const pubBytes = new Uint8Array(Buffer.from(publicKey, 'hex')); - return secp256k1.schnorr.verify(sigBytes, messageHash, pubBytes); -} - -/** - * Create a test channel directly in the database. - */ -export async function createTestChannel( - db: Database, - userPubkey: string, - capacity: number, - localBalance: number, - remoteBalance: number, - state = 'OPEN' -): Promise { - const id = uuidv4(); - await db.createChannel({ - id, - user_pubkey: userPubkey, - runebolt_pubkey: crypto.randomBytes(32).toString('hex'), - funding_txid: crypto.randomBytes(32).toString('hex'), - funding_vout: 0, - capacity, - local_balance: localBalance, - remote_balance: remoteBalance, - state, - }); - return id; -} - -/** - * Create a test user in the database. - */ -export async function createTestUser( - db: Database, - pubkey: string, - username?: string -): Promise { - await db.createUser(pubkey); - if (username) { - await db.updateUsername(pubkey, username); - } -} - -/** - * Simulate funding confirmation by transitioning channel to OPEN state. - */ -export async function simulateFundingConfirmation( - db: Database, - channelId: string -): Promise { - const channel = await db.getChannel(channelId); - if (!channel) throw new Error(`Channel ${channelId} not found`); - if (channel.state !== 'PENDING_OPEN') { - throw new Error(`Channel ${channelId} is not in PENDING_OPEN state (is ${channel.state})`); - } - - await db.updateChannel({ - id: channelId, - funding_txid: crypto.randomBytes(32).toString('hex'), - funding_vout: 0, - capacity: channel.capacity, - local_balance: channel.local_balance, - remote_balance: channel.remote_balance, - state: 'OPEN', - }); -} - -/** - * Generate a unique nonce for a transfer (UUID v4). - */ -export function generateNonce(): string { - return uuidv4(); -} diff --git a/legacy/taproot-assets-era/backend/src/api/auth.ts b/legacy/taproot-assets-era/backend/src/api/auth.ts deleted file mode 100644 index d6495ae..0000000 --- a/legacy/taproot-assets-era/backend/src/api/auth.ts +++ /dev/null @@ -1,385 +0,0 @@ -/** - * Enhanced authentication with social login support - * Supports: Google OAuth, Apple Sign In, Email Magic Links - * Falls back to wallet-based authentication - */ - -import { Router, Request, Response } from 'express'; -import { z } from 'zod'; -import crypto from 'crypto'; -import { ChallengeManager } from '../auth/ChallengeManager'; -import { generateToken, requireAuth } from '../auth/AuthMiddleware'; -import Database from '../db/Database'; -import { generateUsername } from '../usernames/usernameUtils'; - -const router = Router(); -const challengeManager = new ChallengeManager(); -const db = Database.getInstance(); - -// In-memory store for magic links (production: use Redis) -const magicLinkStore = new Map(); - -/** - * POST /auth/social/initiate - * Start social login flow (Google, Apple, Email) - */ -const socialInitiateSchema = z.object({ - provider: z.enum(['google', 'apple', 'email']), - email: z.string().email().optional(), - redirectUri: z.string().optional(), -}); - -router.post('/auth/social/initiate', async (req: Request, res: Response) => { - try { - const parsed = socialInitiateSchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map((e) => e.message).join('; '), - userFriendly: { - title: 'Invalid request', - message: 'Please check your information and try again.', - action: 'Try again', - }, - }); - return; - } - - const { provider, email, redirectUri } = parsed.data; - - // Generate a deterministic pubkey from social provider - const pubkey = generateSocialPubkey(provider, email || ''); - - if (provider === 'email' && email) { - // Generate magic link - const magicLinkId = crypto.randomUUID(); - const expiresAt = new Date(Date.now() + 30 * 60 * 1000); // 30 minutes - - magicLinkStore.set(magicLinkId, { email, expiresAt, pubkey }); - - // In production: Send actual email here - console.log(`[Magic Link] ${email}: ${magicLinkId}`); - - res.json({ - success: true, - data: { - message: 'Magic link sent to your email', - magicLinkId: process.env.NODE_ENV !== 'production' ? magicLinkId : undefined, - }, - }); - return; - } - - // For Google/Apple, return OAuth URL - const authUrl = getOAuthUrl(provider, redirectUri); - - res.json({ - success: true, - data: { - authUrl, - provider, - state: crypto.randomUUID(), - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[authEnhanced] POST /auth/social/initiate error:', message); - res.status(500).json({ - success: false, - error: message, - userFriendly: { - title: "Couldn't start login", - message: 'Something went wrong on our end. Please try again.', - action: 'Try again in a moment', - }, - }); - } -}); - -/** - * POST /auth/social/verify - * Verify social login callback and return JWT - */ -const socialVerifySchema = z.object({ - provider: z.enum(['google', 'apple', 'email']), - code: z.string().optional(), - magicLinkId: z.string().uuid().optional(), - idToken: z.string().optional(), -}); - -router.post('/auth/social/verify', async (req: Request, res: Response) => { - try { - const parsed = socialVerifySchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map((e) => e.message).join('; '), - }); - return; - } - - const { provider, code, magicLinkId, idToken } = parsed.data; - let pubkey: string; - let email: string | undefined; - let isNewUser = false; - - if (provider === 'email' && magicLinkId) { - const magicLink = magicLinkStore.get(magicLinkId); - if (!magicLink || magicLink.expiresAt < new Date()) { - res.status(401).json({ - success: false, - error: 'Magic link expired or invalid', - userFriendly: { - title: 'Link expired', - message: 'This magic link has expired. Please request a new one.', - action: 'Request new link', - }, - }); - return; - } - - pubkey = magicLink.pubkey; - email = magicLink.email; - magicLinkStore.delete(magicLinkId); - } else if (provider === 'google' && code) { - pubkey = generateSocialPubkey('google', code); - isNewUser = !(await db.getUser(pubkey)); - } else if (provider === 'apple' && idToken) { - pubkey = generateSocialPubkey('apple', idToken); - isNewUser = !(await db.getUser(pubkey)); - } else { - res.status(400).json({ - success: false, - error: 'Invalid verification parameters', - }); - return; - } - - // Ensure user exists - await db.createUser(pubkey); - - // Auto-generate username for new users - if (isNewUser) { - const suggestedUsername = generateUsername(email?.split('@')[0] || 'user'); - if (!(await db.getUserByUsername(suggestedUsername))) { - await db.updateUsername(pubkey, suggestedUsername); - } - } - - const user = await db.getUser(pubkey); - const token = generateToken(pubkey); - - res.json({ - success: true, - data: { - token, - pubkey, - username: user?.username, - isNewUser, - onboardingComplete: !!user?.username && !isNewUser, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[authEnhanced] POST /auth/social/verify error:', message); - res.status(500).json({ - success: false, - error: message, - userFriendly: { - title: "Couldn't sign you in", - message: 'Something went wrong. Please try again.', - action: 'Try again', - }, - }); - } -}); - -/** - * POST /auth/wallet/challenge - * Generate challenge for wallet-based auth (existing flow) - */ -const challengeSchema = z.object({ - pubkey: z.string().min(64).max(66), -}); - -router.post('/auth/wallet/challenge', async (req: Request, res: Response) => { - try { - const parsed = challengeSchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map((e) => e.message).join('; '), - userFriendly: { - title: 'Invalid wallet address', - message: 'The wallet address format is not recognized.', - action: 'Check your wallet connection', - }, - }); - return; - } - - const { pubkey } = parsed.data; - const { challengeId, message } = await challengeManager.createChallenge(pubkey); - - res.json({ - success: true, - data: { - challengeId, - message, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[authEnhanced] POST /auth/wallet/challenge error:', message); - res.status(500).json({ - success: false, - error: message, - userFriendly: { - title: "Couldn't generate challenge", - message: 'Please try connecting your wallet again.', - action: 'Try again', - }, - }); - } -}); - -/** - * POST /auth/wallet/verify - * Verify wallet signature and return JWT - */ -const walletVerifySchema = z.object({ - challengeId: z.string().uuid(), - signature: z.string().min(1), -}); - -router.post('/auth/wallet/verify', async (req: Request, res: Response) => { - try { - const parsed = walletVerifySchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map((e) => e.message).join('; '), - }); - return; - } - - const { challengeId, signature } = parsed.data; - const result = await challengeManager.verifyChallenge(challengeId, signature); - - if (!result.valid || !result.pubkey) { - res.status(401).json({ - success: false, - error: 'Challenge verification failed', - userFriendly: { - title: 'Signature failed', - message: "We couldn't verify your wallet signature. The challenge may have expired.", - action: 'Try connecting again', - }, - }); - return; - } - - const isNewUser = !(await db.getUser(result.pubkey)); - await db.createUser(result.pubkey); - - // Auto-generate username for new users - if (isNewUser) { - const suggestedUsername = generateUsername('user'); - if (!(await db.getUserByUsername(suggestedUsername))) { - await db.updateUsername(result.pubkey, suggestedUsername); - } - } - - const user = await db.getUser(result.pubkey); - const token = generateToken(result.pubkey); - - res.json({ - success: true, - data: { - token, - pubkey: result.pubkey, - username: user?.username, - isNewUser, - onboardingComplete: !!user?.username && !isNewUser, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[authEnhanced] POST /auth/wallet/verify error:', message); - res.status(500).json({ - success: false, - error: message, - userFriendly: { - title: "Couldn't sign you in", - message: 'Something went wrong verifying your wallet.', - action: 'Try again', - }, - }); - } -}); - -/** - * GET /auth/me - * Get current user info - */ -router.get('/auth/me', requireAuth, async (req: Request, res: Response) => { - try { - const pubkey = req.auth!.pubkey; - const user = await db.getUser(pubkey); - - if (!user) { - res.status(404).json({ - success: false, - error: 'User not found', - userFriendly: { - title: 'Account not found', - message: "We couldn't find your account. Please sign in again.", - action: 'Sign in', - }, - }); - return; - } - - res.json({ - success: true, - data: { - pubkey: user.pubkey, - username: user.username, - profileUrl: user.username ? `https://runebolt.io/${user.username}` : undefined, - createdAt: user.created_at, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[authEnhanced] GET /auth/me error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -// Helper functions -function generateSocialPubkey(provider: string, identifier: string): string { - const hash = crypto.createHash('sha256') - .update(`${provider}:${identifier}:${process.env.SOCIAL_AUTH_SECRET || 'dev-secret'}`) - .digest('hex'); - return hash.slice(0, 64); -} - -function getOAuthUrl(provider: string, redirectUri?: string): string { - const state = crypto.randomUUID(); - - if (provider === 'google') { - const clientId = process.env.GOOGLE_CLIENT_ID || 'dev-client-id'; - const redirect = encodeURIComponent(redirectUri || `${process.env.FRONTEND_URL}/auth/callback/google`); - return `https://accounts.google.com/o/oauth2/v2/auth?client_id=${clientId}&redirect_uri=${redirect}&response_type=code&scope=openid%20email%20profile&state=${state}`; - } - - if (provider === 'apple') { - const clientId = process.env.APPLE_CLIENT_ID || 'dev-client-id'; - const redirect = encodeURIComponent(redirectUri || `${process.env.FRONTEND_URL}/auth/callback/apple`); - return `https://appleid.apple.com/auth/authorize?client_id=${clientId}&redirect_uri=${redirect}&response_type=code%20id_token&scope=name%20email&state=${state}`; - } - - return ''; -} - -export default router; diff --git a/legacy/taproot-assets-era/backend/src/api/routes/assetRoutes.ts b/legacy/taproot-assets-era/backend/src/api/routes/assetRoutes.ts deleted file mode 100644 index 663c314..0000000 --- a/legacy/taproot-assets-era/backend/src/api/routes/assetRoutes.ts +++ /dev/null @@ -1,294 +0,0 @@ -/** - * Multi-asset API routes for RuneBolt. - * - * Provides endpoints for: - * - Asset registry (list/query supported assets) - * - Asset balances per user - * - Bitmap escrow operations (create, deposit, execute, status) - */ - -import { Router, Request, Response } from 'express'; -import { z } from 'zod'; -import AssetRegistry, { assetToJson } from '../../assets/AssetRegistry'; -import BRC20Manager from '../../assets/BRC20Manager'; -import BitmapEscrow from '../../assets/BitmapEscrow'; -import Database from '../../db/Database'; -import { requireAuth } from '../../auth/AuthMiddleware'; - -const router = Router(); -const registry = AssetRegistry.getInstance(); -const brc20Manager = new BRC20Manager(); -const escrow = new BitmapEscrow(); - -// ==================== Asset Registry Routes ==================== - -/** - * GET /assets - * List all supported assets. - */ -router.get('/assets', (_req: Request, res: Response) => { - const assets = registry.getAll().map(assetToJson); - res.json({ success: true, data: assets }); -}); - -/** - * GET /assets/:id - * Get a single asset by ID. - */ -router.get('/assets/:id', (req: Request, res: Response) => { - const asset = registry.get(req.params.id); - if (!asset) { - res.status(404).json({ success: false, error: 'Asset not found' }); - return; - } - res.json({ success: true, data: assetToJson(asset) }); -}); - -/** - * GET /assets/:id/balance/:pubkey - * Get balance for a specific asset and user. - */ -router.get('/assets/:id/balance/:pubkey', async (req: Request, res: Response) => { - try { - const { id, pubkey } = req.params; - - const asset = registry.get(id); - if (!asset) { - res.status(404).json({ success: false, error: 'Asset not found' }); - return; - } - - const balance = await brc20Manager.getChannelBalance(pubkey, id); - - res.json({ - success: true, - data: { - asset: id, - pubkey, - balance, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[assetRoutes] GET /assets/:id/balance/:pubkey error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -// ==================== Escrow Routes ==================== - -const pubkeySchema = z - .string() - .length(66, 'Compressed public key must be exactly 66 hex characters') - .regex(/^(02|03)[0-9a-fA-F]{64}$/, 'Must be a valid compressed pubkey'); - -/** - * POST /escrow/create - * Create a new Bitmap escrow. - */ -const createEscrowSchema = z.object({ - sellerPubkey: pubkeySchema, - buyerPubkey: pubkeySchema, - inscriptionId: z.string().min(1, 'Inscription ID is required'), - priceAsset: z.string().min(1, 'Price asset is required'), - priceAmount: z.string().regex(/^\d+$/, 'Price must be a numeric string'), - timeoutMs: z.number().int().positive().optional(), -}); - -router.post('/escrow/create', requireAuth, async (req: Request, res: Response) => { - try { - const parsed = createEscrowSchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map(e => e.message).join('; '), - }); - return; - } - - const { sellerPubkey, buyerPubkey, inscriptionId, priceAsset, priceAmount, timeoutMs } = parsed.data; - - // Verify the authenticated user is the seller or buyer - if (req.auth!.pubkey !== sellerPubkey && req.auth!.pubkey !== buyerPubkey) { - res.status(403).json({ - success: false, - error: 'Authenticated user must be the seller or buyer', - }); - return; - } - - // Verify price asset exists - if (!registry.has(priceAsset)) { - res.status(400).json({ - success: false, - error: `Unknown price asset: ${priceAsset}`, - }); - return; - } - - const escrowId = await escrow.createEscrow( - sellerPubkey, buyerPubkey, inscriptionId, priceAsset, priceAmount, timeoutMs - ); - - res.status(201).json({ - success: true, - data: { escrowId }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[assetRoutes] POST /escrow/create error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -/** - * POST /escrow/:id/deposit - * Record a deposit (inscription or payment) for an escrow. - */ -const depositSchema = z.object({ - side: z.enum(['seller', 'buyer']), - txid: z.string().length(64, 'Transaction ID must be 64 hex characters').regex(/^[0-9a-fA-F]{64}$/), -}); - -router.post('/escrow/:id/deposit', requireAuth, async (req: Request, res: Response) => { - try { - const parsed = depositSchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map(e => e.message).join('; '), - }); - return; - } - - const { side, txid } = parsed.data; - const escrowId = req.params.id; - - let result; - if (side === 'seller') { - result = await escrow.depositInscription(escrowId, txid); - } else { - result = await escrow.depositPayment(escrowId, txid); - } - - res.json({ - success: true, - data: { escrowId, status: result.status }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - const status = message.includes('not found') ? 404 : 500; - console.error('[assetRoutes] POST /escrow/:id/deposit error:', message); - res.status(status).json({ success: false, error: message }); - } -}); - -/** - * POST /escrow/:id/execute - * Execute the atomic swap for a fully-deposited escrow. - */ -router.post('/escrow/:id/execute', requireAuth, async (req: Request, res: Response) => { - try { - const escrowId = req.params.id; - const result = await escrow.executeSwap(escrowId); - - res.json({ - success: true, - data: { escrowId, status: result.status }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - const status = message.includes('not found') ? 404 : 500; - console.error('[assetRoutes] POST /escrow/:id/execute error:', message); - res.status(status).json({ success: false, error: message }); - } -}); - -/** - * POST /escrow/:id/cancel - * Cancel/refund an escrow (seller cancels, or anyone after timeout). - */ -router.post('/escrow/:id/cancel', requireAuth, async (req: Request, res: Response) => { - try { - const escrowId = req.params.id; - const result = await escrow.refundEscrow(escrowId); - - res.json({ - success: true, - data: { escrowId, status: result.status }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - const status = message.includes('not found') ? 404 : 500; - console.error('[assetRoutes] POST /escrow/:id/cancel error:', message); - res.status(status).json({ success: false, error: message }); - } -}); - -/** - * GET /escrow/active - * List all active (non-terminal) escrows. - * NOTE: Must be registered BEFORE /escrow/:id to avoid "active" matching as :id. - */ -router.get('/escrow/active', async (_req: Request, res: Response) => { - try { - const db = Database.getInstance(); - const result = await db.query<{ - id: string; - seller_pubkey: string; - buyer_pubkey: string; - inscription_id: string; - price_asset: string; - price_amount: string; - status: string; - timeout_at: string; - created_at: string; - }>( - `SELECT * FROM escrows - WHERE status NOT IN ('completed', 'refunded', 'expired') - ORDER BY created_at DESC` - ); - - res.json({ - success: true, - data: result.rows.map(r => ({ - id: r.id, - sellerPubkey: r.seller_pubkey, - buyerPubkey: r.buyer_pubkey, - inscriptionId: r.inscription_id, - priceAsset: r.price_asset, - priceAmount: r.price_amount, - status: r.status, - timeoutAt: r.timeout_at, - createdAt: r.created_at, - })), - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[assetRoutes] GET /escrow/active error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -/** - * GET /escrow/:id - * Get escrow status and deposit details. - */ -router.get('/escrow/:id', async (req: Request, res: Response) => { - try { - const escrowId = req.params.id; - const result = await escrow.getEscrowStatus(escrowId); - - res.json({ - success: true, - data: result, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - const status = message.includes('not found') ? 404 : 500; - console.error('[assetRoutes] GET /escrow/:id error:', message); - res.status(status).json({ success: false, error: message }); - } -}); - -export default router; diff --git a/legacy/taproot-assets-era/backend/src/api/routes/authRoutes.ts b/legacy/taproot-assets-era/backend/src/api/routes/authRoutes.ts deleted file mode 100644 index ca9ae8c..0000000 --- a/legacy/taproot-assets-era/backend/src/api/routes/authRoutes.ts +++ /dev/null @@ -1,137 +0,0 @@ -/** - * Authentication API routes using challenge-response with Bitcoin signing. - */ - -import { Router, Request, Response } from 'express'; -import { z } from 'zod'; -import { ChallengeManager } from '../../auth/ChallengeManager'; -import { generateToken, requireAuth } from '../../auth/AuthMiddleware'; -import Database from '../../db/Database'; - -const router = Router(); -const challengeManager = new ChallengeManager(); -const db = Database.getInstance(); - -/** - * POST /auth/challenge - * Generate a challenge for the given pubkey to sign. - */ -const challengeSchema = z.object({ - pubkey: z - .string() - .min(64, 'Public key must be at least 64 characters') - .max(66, 'Public key must be at most 66 characters'), -}); - -router.post('/auth/challenge', async (req: Request, res: Response) => { - try { - const parsed = challengeSchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map((e) => e.message).join('; '), - }); - return; - } - - const { pubkey } = parsed.data; - const { challengeId, message } = await challengeManager.createChallenge(pubkey); - - res.json({ - success: true, - data: { - challengeId, - message, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[authRoutes] POST /auth/challenge error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -/** - * POST /auth/verify - * Verify a signed challenge and return a JWT. - */ -const verifySchema = z.object({ - challengeId: z.string().uuid('Invalid challengeId format'), - signature: z.string().min(1, 'Signature is required'), -}); - -router.post('/auth/verify', async (req: Request, res: Response) => { - try { - const parsed = verifySchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map((e) => e.message).join('; '), - }); - return; - } - - const { challengeId, signature } = parsed.data; - const result = await challengeManager.verifyChallenge(challengeId, signature); - - if (!result.valid || !result.pubkey) { - res.status(401).json({ - success: false, - error: 'Challenge verification failed. The challenge may have expired or the signature is invalid.', - }); - return; - } - - // Ensure user exists in the database - db.createUser(result.pubkey); - - // Generate JWT - const token = generateToken(result.pubkey); - - res.json({ - success: true, - data: { - token, - pubkey: result.pubkey, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[authRoutes] POST /auth/verify error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -/** - * GET /auth/me - * Get the current authenticated user's info. - */ -router.get('/auth/me', requireAuth, async (req: Request, res: Response) => { - try { - const pubkey = req.auth!.pubkey; - const user = await db.getUser(pubkey); - - if (!user) { - res.status(404).json({ - success: false, - error: 'User not found', - }); - return; - } - - res.json({ - success: true, - data: { - pubkey: user.pubkey, - username: user.username, - createdAt: user.created_at, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[authRoutes] GET /auth/me error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -export default router; diff --git a/legacy/taproot-assets-era/backend/src/api/routes/channelRoutes.ts b/legacy/taproot-assets-era/backend/src/api/routes/channelRoutes.ts deleted file mode 100644 index 8bb34af..0000000 --- a/legacy/taproot-assets-era/backend/src/api/routes/channelRoutes.ts +++ /dev/null @@ -1,253 +0,0 @@ -/** - * Channel management API routes. - * - * SECURITY: Includes amount bounds checking to prevent overflow and abuse. - */ - -import { Router, Request, Response } from 'express'; -import { z } from 'zod'; -import { ChannelManager } from '../../channels/ChannelManager'; -import { channelToJson } from '../../channels/ChannelState'; -import { RuneLedger } from '../../ledger/RuneLedger'; -import { requireAuth } from '../../auth/AuthMiddleware'; -import { getWebSocketManager } from '../../ws/WebSocketServer'; -import { calculateReserve, getSpendableBalance } from '../../channels/ChannelReserves'; -import { SupportedAsset, DOG_RUNE_ID } from '../../rune/RuneConstants'; - -const router = Router(); -const channelManager = new ChannelManager(); -const ledger = new RuneLedger(); - -/** Channel amount bounds */ -const MIN_CHANNEL_AMOUNT = 10_000n; -const MAX_CHANNEL_AMOUNT = 100_000_000_000n; - -/** - * POST /channel/open - * Open a new payment channel. - * - * SECURITY: Validates amount against MIN/MAX channel capacity. - */ -/** Map supported asset types to their rune IDs */ -const ASSET_RUNE_MAP: Record = { - [SupportedAsset.DOG]: DOG_RUNE_ID, -}; - -const openChannelSchema = z.object({ - pubkey: z - .string() - .length(66, 'Compressed public key must be exactly 66 hex characters') - .regex(/^(02|03)[0-9a-fA-F]{64}$/, 'Public key must be a valid compressed pubkey (66-char hex starting with 02 or 03)'), - amount: z - .string() - .regex(/^\d+$/, 'Amount must be a numeric string representing raw units'), - assetType: z - .nativeEnum(SupportedAsset) - .default(SupportedAsset.DOG), -}); - -router.post('/channel/open', async (req: Request, res: Response) => { - try { - const parsed = openChannelSchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map((e) => e.message).join('; '), - }); - return; - } - - const { pubkey, amount, assetType } = parsed.data; - const amountBigInt = BigInt(amount); - - // Resolve runeId from asset type (BTC channels don't use Runestones) - const runeId = ASSET_RUNE_MAP[assetType]; - if (assetType !== SupportedAsset.BTC && !runeId) { - res.status(400).json({ - success: false, - error: `Unsupported asset type for rune channels: ${assetType}`, - }); - return; - } - - // SECURITY: Enforce channel capacity bounds - if (amountBigInt < MIN_CHANNEL_AMOUNT) { - res.status(400).json({ - success: false, - error: `Channel capacity must be at least ${MIN_CHANNEL_AMOUNT} raw units (got ${amount})`, - }); - return; - } - - if (amountBigInt > MAX_CHANNEL_AMOUNT) { - res.status(400).json({ - success: false, - error: `Channel capacity cannot exceed ${MAX_CHANNEL_AMOUNT} raw units`, - }); - return; - } - - const reserve = calculateReserve(amountBigInt); - - const result = await channelManager.openChannel(pubkey, amountBigInt, runeId); - - res.status(201).json({ - success: true, - data: { - channelId: result.channelId, - psbt: result.psbt, - channelAddress: result.channelAddress, - assetType, - reserve: reserve.toString(), - spendable: getSpendableBalance(amountBigInt, amountBigInt).toString(), - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[channelRoutes] POST /channel/open error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -/** - * POST /channel/activate - * Activate a pending channel after user signs the funding PSBT. - */ -const activateChannelSchema = z.object({ - channelId: z.string().uuid('Invalid channelId format'), - signedPsbt: z.string().min(1, 'signedPsbt is required'), -}); - -router.post('/channel/activate', async (req: Request, res: Response) => { - try { - const parsed = activateChannelSchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map((e) => e.message).join('; '), - }); - return; - } - - const { channelId, signedPsbt } = parsed.data; - const channel = await channelManager.activateChannel(channelId, signedPsbt); - - // Notify via WebSocket - const wsManager = getWebSocketManager(); - if (wsManager) { - wsManager.broadcastChannelStateChange(channelId, channel.state, { - capacity: channel.capacity.toString(), - fundingTxid: channel.fundingTxid, - }); - wsManager.broadcastToUser(channel.userPubkey, 'channel:activated', { - channelId, - state: channel.state, - capacity: channel.capacity.toString(), - }); - } - - res.json({ - success: true, - data: channelToJson(channel), - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - const status = message.includes('not found') ? 404 : 500; - console.error('[channelRoutes] POST /channel/activate error:', message); - res.status(status).json({ success: false, error: message }); - } -}); - -/** - * POST /channel/close - * Initiate a cooperative channel close. Requires authentication. - */ -const closeChannelSchema = z.object({ - channelId: z.string().uuid('Invalid channelId format'), -}); - -router.post('/channel/close', requireAuth, async (req: Request, res: Response) => { - try { - const parsed = closeChannelSchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map((e) => e.message).join('; '), - }); - return; - } - - const { channelId } = parsed.data; - - // Verify the user owns this channel - const channel = await channelManager.getChannel(channelId); - if (channel.userPubkey !== req.auth!.pubkey) { - res.status(403).json({ - success: false, - error: 'You do not own this channel', - }); - return; - } - - const result = await channelManager.closeChannel(channelId); - - // Notify via WebSocket - const wsManager = getWebSocketManager(); - if (wsManager) { - wsManager.broadcastChannelStateChange(channelId, 'CLOSING'); - wsManager.broadcastToUser(req.auth!.pubkey, 'channel:closing', { - channelId, - state: 'CLOSING', - }); - } - - res.json({ - success: true, - data: { psbt: result.psbt }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - const status = message.includes('not found') - ? 404 - : message.includes('Invalid channel state') - ? 409 - : 500; - console.error('[channelRoutes] POST /channel/close error:', message); - res.status(status).json({ success: false, error: message }); - } -}); - -/** - * GET /channel/:channelId - * Get channel state and balance. - */ -router.get('/channel/:channelId', async (req: Request, res: Response) => { - try { - const { channelId } = req.params; - const channel = await channelManager.getChannel(channelId); - const balance = await ledger.getBalance(channelId); - - const reserve = calculateReserve(balance.capacity); - const spendable = getSpendableBalance(balance.local, balance.capacity); - - res.json({ - success: true, - data: { - ...channelToJson(channel), - balance: { - local: balance.local.toString(), - remote: balance.remote.toString(), - capacity: balance.capacity.toString(), - reserve: reserve.toString(), - spendable: spendable.toString(), - }, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - const status = message.includes('not found') ? 404 : 500; - res.status(status).json({ success: false, error: message }); - } -}); - -export default router; diff --git a/legacy/taproot-assets-era/backend/src/api/routes/claimRoutes.ts b/legacy/taproot-assets-era/backend/src/api/routes/claimRoutes.ts deleted file mode 100644 index d576bbc..0000000 --- a/legacy/taproot-assets-era/backend/src/api/routes/claimRoutes.ts +++ /dev/null @@ -1,260 +0,0 @@ -/** - * Claim link API routes — shareable links for sending runes. - */ - -import crypto from 'crypto'; -import { Router, Request, Response } from 'express'; -import { z } from 'zod'; -import { v4 as uuidv4 } from 'uuid'; -import Database from '../../db/Database'; -import { RuneLedger } from '../../ledger/RuneLedger'; -import { requireAuth } from '../../auth/AuthMiddleware'; -import { getWebSocketManager } from '../../ws/WebSocketServer'; - -const router = Router(); -const db = Database.getInstance(); -const ledger = new RuneLedger(); - -/** Default claim link expiry: 24 hours */ -const CLAIM_LINK_EXPIRY_MS = 24 * 60 * 60 * 1000; - -/** - * POST /claim/create - * Create a shareable claim link. Requires authentication. - */ -const createClaimSchema = z.object({ - amount: z.string().regex(/^\d+$/, 'Amount must be a numeric string'), - memo: z.string().max(256, 'Memo must be 256 characters or less').optional(), - expiresInMs: z - .number() - .int() - .positive() - .max(7 * 24 * 60 * 60 * 1000, 'Max expiry is 7 days') - .optional(), -}); - -router.post('/claim/create', requireAuth, async (req: Request, res: Response) => { - try { - const parsed = createClaimSchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map((e) => e.message).join('; '), - }); - return; - } - - const { amount, memo, expiresInMs } = parsed.data; - const creatorPubkey = req.auth!.pubkey; - - // Verify creator has sufficient balance in at least one channel - const creatorChannel = await ledger.findOpenChannelForPubkey(creatorPubkey); - if (!creatorChannel) { - res.status(422).json({ - success: false, - error: 'No open channel found. Open a channel first.', - }); - return; - } - - const balance = await ledger.getBalance(creatorChannel); - if (balance.local < BigInt(amount)) { - res.status(422).json({ - success: false, - error: `Insufficient balance: have ${balance.local}, need ${amount}`, - }); - return; - } - - const claimId = uuidv4(); - const expiresAt = new Date( - Date.now() + (expiresInMs || CLAIM_LINK_EXPIRY_MS) - ).toISOString(); - - await db.createClaimLink({ - id: claimId, - creator_pubkey: creatorPubkey, - amount: Number(amount), - memo: memo || null, - expires_at: expiresAt, - }); - - const baseUrl = `${req.protocol}://${req.get('host')}`; - const claimUrl = `${baseUrl}/api/v1/claim/${claimId}`; - - res.status(201).json({ - success: true, - data: { - claimId, - url: claimUrl, - amount, - memo: memo || null, - expiresAt, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[claimRoutes] POST /claim/create error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -/** - * GET /claim/:claimId - * Get claim link details. - */ -router.get('/claim/:claimId', async (req: Request, res: Response) => { - try { - const { claimId } = req.params; - const claim = await db.getClaimLink(claimId); - - if (!claim) { - res.status(404).json({ - success: false, - error: 'Claim link not found', - }); - return; - } - - // Check if expired - const isExpired = new Date(claim.expires_at).getTime() < Date.now(); - - res.json({ - success: true, - data: { - claimId: claim.id, - creatorPubkey: claim.creator_pubkey, - amount: claim.amount.toString(), - memo: claim.memo, - claimed: !!claim.claimed_by, - claimedBy: claim.claimed_by, - claimedAt: claim.claimed_at, - createdAt: claim.created_at, - expiresAt: claim.expires_at, - expired: isExpired, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[claimRoutes] GET /claim/:claimId error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -/** - * POST /claim/:claimId/redeem - * Redeem a claim link. Requires authentication. - */ -router.post('/claim/:claimId/redeem', requireAuth, async (req: Request, res: Response) => { - try { - const { claimId } = req.params; - const claimerPubkey = req.auth!.pubkey; - - const claim = await db.getClaimLink(claimId); - if (!claim) { - res.status(404).json({ - success: false, - error: 'Claim link not found', - }); - return; - } - - // Check if already claimed - if (claim.claimed_by) { - res.status(409).json({ - success: false, - error: 'Claim link has already been redeemed', - }); - return; - } - - // Check if expired - if (new Date(claim.expires_at).getTime() < Date.now()) { - res.status(410).json({ - success: false, - error: 'Claim link has expired', - }); - return; - } - - // Cannot claim your own link - if (claim.creator_pubkey === claimerPubkey) { - res.status(400).json({ - success: false, - error: 'Cannot redeem your own claim link', - }); - return; - } - - // Find channels for both parties - const fromChannel = await ledger.findOpenChannelForPubkey(claim.creator_pubkey); - if (!fromChannel) { - res.status(422).json({ - success: false, - error: 'Creator has no open channel', - }); - return; - } - - const toChannel = await ledger.findOpenChannelForPubkey(claimerPubkey); - if (!toChannel) { - res.status(422).json({ - success: false, - error: 'You need an open channel to redeem this claim', - }); - return; - } - - // Execute the transfer - const claimNonce = crypto.randomUUID(); - const claimSignature = crypto.createHmac('sha256', process.env.JWT_SECRET || 'fallback') - .update(`${fromChannel}:${toChannel}:${claim.amount}:${claimNonce}`) - .digest('hex'); - - const transfer = await ledger.transfer( - fromChannel, - toChannel, - BigInt(claim.amount), - claim.memo || `Claim: ${claimId}`, - claimNonce, - claimSignature, - claim.creator_pubkey - ); - - // Mark as claimed - await db.claimLink(claimId, claimerPubkey); - - // Broadcast via WebSocket - const wsManager = getWebSocketManager(); - if (wsManager) { - wsManager.broadcastToUser(claim.creator_pubkey, 'claim:redeemed', { - claimId, - claimedBy: claimerPubkey, - amount: claim.amount.toString(), - }); - - wsManager.broadcastToUser(claimerPubkey, 'claim:received', { - claimId, - amount: claim.amount.toString(), - from: claim.creator_pubkey, - }); - } - - res.json({ - success: true, - data: { - claimId, - transferId: transfer.id, - amount: claim.amount.toString(), - memo: claim.memo, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - const status = message.includes('Insufficient') ? 422 : 500; - console.error('[claimRoutes] POST /claim/:claimId/redeem error:', message); - res.status(status).json({ success: false, error: message }); - } -}); - -export default router; diff --git a/legacy/taproot-assets-era/backend/src/api/routes/feeRoutes.ts b/legacy/taproot-assets-era/backend/src/api/routes/feeRoutes.ts deleted file mode 100644 index 69e9f38..0000000 --- a/legacy/taproot-assets-era/backend/src/api/routes/feeRoutes.ts +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Fee API routes — fee status and schedule endpoints. - */ - -import { Router, Request, Response } from 'express'; -import Database from '../../db/Database'; -import { FeeManager } from '../../fees/FeeManager'; - -const router = Router(); -const db = Database.getInstance(); -const feeManager = new FeeManager(); - -/** - * GET /status/:pubkey - * Returns free transactions remaining, total fees paid, and tier info. - */ -router.get('/status/:pubkey', async (req: Request, res: Response) => { - try { - const { pubkey } = req.params; - - const user = await db.getUser(pubkey); - if (!user) { - res.status(404).json({ - success: false, - error: 'User not found', - userMessage: 'No user found with this public key.', - }); - return; - } - - const tierInfo = await feeManager.getUserTierInfo(pubkey); - - // Get total fees paid from fee_records - const feesResult = await db.queryOne<{ total: string }>( - 'SELECT COALESCE(SUM(amount), 0) as total FROM fee_records WHERE pubkey = $1', - [pubkey] - ); - const totalFeesPaid = feesResult?.total || '0'; - - res.json({ - success: true, - data: { - pubkey, - tier: tierInfo.tier, - transactionCount: tierInfo.transactionCount, - freeTransactionsRemaining: tierInfo.freeTransactionsRemaining, - totalFeesPaid, - currentRates: tierInfo.feeRates, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[feeRoutes] GET /status/:pubkey error:', message); - res.status(500).json({ - success: false, - error: message, - userMessage: 'Failed to retrieve fee status. Please try again.', - }); - } -}); - -/** - * GET /schedule - * Returns the fee schedule for all tiers. - */ -router.get('/schedule', (_req: Request, res: Response) => { - res.json({ - success: true, - data: { - freeTier: { - freeTransactions: 500, - offChainFeeRate: '0%', - settlementFeeRate: '0%', - description: 'First 500 transactions are completely free', - }, - standardTier: { - offChainFeeRate: '0.1%', - settlementFeeRate: '0.5%', - description: 'After 500 free transactions, standard micro-fees apply', - }, - }, - }); -}); - -export default router; diff --git a/legacy/taproot-assets-era/backend/src/api/routes/statsRoutes.ts b/legacy/taproot-assets-era/backend/src/api/routes/statsRoutes.ts deleted file mode 100644 index 5ac46bc..0000000 --- a/legacy/taproot-assets-era/backend/src/api/routes/statsRoutes.ts +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Public stats and user tier API routes. - */ - -import { Router, Request, Response } from 'express'; -import Database from '../../db/Database'; -import { FeeManager } from '../../fees/FeeManager'; - -const router = Router(); -const db = Database.getInstance(); -const feeManager = new FeeManager(); - -/** - * GET /stats - * Public stats endpoint: total users, transfers, volume, channels. - */ -router.get('/stats', async (_req: Request, res: Response) => { - try { - const stats = await db.getPublicStats(); - - res.json({ - success: true, - data: { - totalUsers: stats.totalUsers, - totalTransfers: stats.totalTransfers, - totalVolume: stats.totalVolume, - totalChannels: stats.totalChannels, - openChannels: stats.openChannels, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[statsRoutes] GET /stats error:', message); - res.status(500).json({ - success: false, - error: message, - userMessage: 'Failed to retrieve platform statistics. Please try again.', - }); - } -}); - -/** - * GET /user/:pubkey/tier - * Get user tier info and remaining free transactions. - */ -router.get('/user/:pubkey/tier', async (req: Request, res: Response) => { - try { - const { pubkey } = req.params; - - const user = await db.getUser(pubkey); - if (!user) { - res.status(404).json({ - success: false, - error: 'User not found', - userMessage: 'No user found with this public key.', - }); - return; - } - - const tierInfo = await feeManager.getUserTierInfo(pubkey); - - res.json({ - success: true, - data: tierInfo, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[statsRoutes] GET /user/:pubkey/tier error:', message); - res.status(500).json({ - success: false, - error: message, - userMessage: 'Failed to retrieve tier information. Please try again.', - }); - } -}); - -export default router; diff --git a/legacy/taproot-assets-era/backend/src/api/routes/transferRoutes.ts b/legacy/taproot-assets-era/backend/src/api/routes/transferRoutes.ts deleted file mode 100644 index a4899fb..0000000 --- a/legacy/taproot-assets-era/backend/src/api/routes/transferRoutes.ts +++ /dev/null @@ -1,292 +0,0 @@ -/** - * Transfer API routes for sending runes between channels. - * - * SECURITY: Validates transfer amounts, enforces nonce uniqueness, - * and prevents negative/zero transfers. - */ - -import { Router, Request, Response } from 'express'; -import { z } from 'zod'; -import { RuneLedger } from '../../ledger/RuneLedger'; -import { transferToJson } from '../../ledger/Transfer'; -import { requireAuth } from '../../auth/AuthMiddleware'; -import { ChannelManager } from '../../channels/ChannelManager'; -import { getWebSocketManager } from '../../ws/WebSocketServer'; -import { FeeManager } from '../../fees/FeeManager'; -import { getSpendableBalance } from '../../channels/ChannelReserves'; - -const router = Router(); -const ledger = new RuneLedger(); -const channelManager = new ChannelManager(); -const feeManager = new FeeManager(); - -/** Transfer amount bounds */ -const MIN_TRANSFER_AMOUNT = 1n; -/** Dust limit: reject transfers below this threshold */ -const DUST_LIMIT = 100n; -/** Maximum safe amount for BigInt (mirrors Number.MAX_SAFE_INTEGER) */ -const MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER); - -/** - * Map error messages to user-friendly messages and HTTP status codes. - */ -function mapTransferError(message: string): { status: number; userMessage: string } { - if (message.includes('not found')) { - return { status: 404, userMessage: 'The specified channel could not be found. Please check the channel ID and try again.' }; - } - if (message.includes('Insufficient balance')) { - return { status: 422, userMessage: 'Insufficient balance to complete this transfer. Please check your channel balance.' }; - } - if (message.includes('Insufficient inbound')) { - return { status: 422, userMessage: 'The recipient channel does not have enough inbound capacity for this transfer.' }; - } - if (message.includes('not OPEN')) { - return { status: 409, userMessage: 'This channel is not in an active state. Only open channels can send or receive transfers.' }; - } - if (message.includes('replay') || message.includes('nonce')) { - return { status: 409, userMessage: 'This transfer has already been processed. Each transfer requires a unique nonce.' }; - } - if (message.includes('signature')) { - return { status: 401, userMessage: 'Invalid transfer signature. Please sign the transfer with your private key.' }; - } - return { status: 500, userMessage: 'An unexpected error occurred while processing your transfer. Please try again.' }; -} - -/** - * POST /transfer - * Execute a transfer between channels. Requires authentication. - * - * SECURITY: Requires nonce (replay protection) and signature (authorization). - * Validates amount is positive and within bounds. - * Calculates and applies fees based on user tier. - */ -const transferSchema = z - .object({ - fromChannelId: z.string().uuid('Invalid fromChannelId format'), - toChannelId: z.string().uuid('Invalid toChannelId format').optional(), - recipientPubkey: z - .string() - .min(64, 'Public key must be at least 64 characters') - .max(66, 'Public key must be at most 66 characters') - .regex(/^[0-9a-fA-F]+$/, 'Public key must be hex-encoded') - .optional(), - amount: z - .string() - .regex(/^\d+$/, 'Amount must be a numeric string') - .refine((val) => { - const n = BigInt(val); - return n >= MIN_TRANSFER_AMOUNT; - }, 'Amount must be at least 1') - .refine((val) => { - const n = BigInt(val); - return n >= DUST_LIMIT; - }, `Transfer amount below dust limit (minimum ${DUST_LIMIT} units)`) - .refine((val) => { - const n = BigInt(val); - return n <= MAX_SAFE_BIGINT; - }, 'Amount exceeds maximum safe value'), - memo: z.string().max(256, 'Memo must be 256 characters or less').optional(), - nonce: z.string().uuid('Nonce must be a valid UUID'), - signature: z.string().min(128, 'Signature must be at least 128 characters'), - }) - .refine((data) => data.toChannelId || data.recipientPubkey, { - message: 'Either toChannelId or recipientPubkey must be provided', - }); - -router.post('/transfer', requireAuth, async (req: Request, res: Response) => { - try { - const parsed = transferSchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map((e) => e.message).join('; '), - userMessage: 'Invalid transfer request. Please check your input and try again.', - }); - return; - } - - const { fromChannelId, toChannelId, recipientPubkey, amount, memo, nonce, signature } = parsed.data; - const senderPubkey = req.auth!.pubkey; - - // Verify the sender owns the source channel - const fromChannel = await channelManager.getChannel(fromChannelId); - if (fromChannel.userPubkey !== senderPubkey) { - res.status(403).json({ - success: false, - error: 'You do not own the source channel', - userMessage: 'You can only send transfers from your own channels.', - }); - return; - } - - // Resolve recipient channel - let resolvedToChannelId = toChannelId; - - if (!resolvedToChannelId && recipientPubkey) { - resolvedToChannelId = await ledger.findOpenChannelForPubkey(recipientPubkey) || undefined; - if (!resolvedToChannelId) { - res.status(404).json({ - success: false, - error: `No open channel found for recipient ${recipientPubkey.slice(0, 16)}...`, - userMessage: 'The recipient does not have an open channel to receive transfers.', - }); - return; - } - } - - if (!resolvedToChannelId) { - res.status(400).json({ - success: false, - error: 'Could not resolve recipient channel', - userMessage: 'Please provide either a recipient channel ID or public key.', - }); - return; - } - - // Calculate fee - const transferAmount = BigInt(amount); - - // Verify transfer amount does not exceed channel capacity - if (transferAmount > fromChannel.capacity) { - res.status(422).json({ - success: false, - error: 'Transfer amount exceeds channel capacity', - userMessage: `Transfer amount (${amount}) exceeds channel capacity (${fromChannel.capacity.toString()}).`, - }); - return; - } - - const feeCalc = await feeManager.calculateFee(senderPubkey, transferAmount, 'off_chain'); - - // Verify sender has enough spendable balance (balance minus reserve) for amount + fee - const totalRequired = transferAmount + feeCalc.feeAmount; - const spendable = getSpendableBalance(fromChannel.localBalance, fromChannel.capacity); - if (spendable < totalRequired) { - res.status(422).json({ - success: false, - error: 'Insufficient spendable balance (reserve protected)', - userMessage: `Insufficient spendable balance. Spendable: ${spendable.toString()}, Transfer: ${amount}, Fee: ${feeCalc.feeAmount.toString()}, Total required: ${totalRequired.toString()}`, - }); - return; - } - - // Execute transfer with replay protection (nonce) and signature verification - const transfer = await ledger.transfer( - fromChannelId, - resolvedToChannelId, - transferAmount, - memo, - nonce, - signature, - senderPubkey - ); - - // Record fee and increment transaction count - await feeManager.recordFee(transfer.id, senderPubkey, feeCalc); - - // Broadcast updates via WebSocket - const wsManager = getWebSocketManager(); - if (wsManager) { - const transferData = transferToJson(transfer); - - // Notify sender channel subscribers - wsManager.broadcastToChannel(fromChannelId, 'transfer:sent', transferData); - - // Notify recipient channel subscribers - wsManager.broadcastToChannel(resolvedToChannelId, 'transfer:received', transferData); - - // Notify recipient user - const toChannel = await channelManager.getChannel(resolvedToChannelId); - wsManager.broadcastToUser(toChannel.userPubkey, 'transfer:incoming', transferData); - - // Send balance updates to both sender and recipient - const senderBalance = await ledger.getBalance(fromChannelId); - const recipientBalance = await ledger.getBalance(resolvedToChannelId); - - wsManager.broadcastToUser(senderPubkey, 'balance:updated', { - channelId: fromChannelId, - local: senderBalance.local.toString(), - remote: senderBalance.remote.toString(), - capacity: senderBalance.capacity.toString(), - }); - - wsManager.broadcastToUser(toChannel.userPubkey, 'balance:updated', { - channelId: resolvedToChannelId, - local: recipientBalance.local.toString(), - remote: recipientBalance.remote.toString(), - capacity: recipientBalance.capacity.toString(), - }); - } - - res.status(201).json({ - success: true, - data: { - ...transferToJson(transfer), - fee: { - amount: feeCalc.feeAmount.toString(), - rate: feeCalc.feeRate, - type: feeCalc.feeType, - wasFree: feeCalc.isFree, - }, - freeTransactionsRemaining: feeCalc.freeTransactionsRemaining, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - const { status, userMessage } = mapTransferError(message); - console.error('[transferRoutes] POST /transfer error:', message); - res.status(status).json({ success: false, error: message, userMessage }); - } -}); - -/** - * GET /history/:pubkey - * Get paginated transfer history for a pubkey. - */ -const historyQuerySchema = z.object({ - limit: z - .string() - .optional() - .transform((v) => Math.min(Math.max(parseInt(v || '50', 10), 1), 200)), - offset: z - .string() - .optional() - .transform((v) => Math.max(parseInt(v || '0', 10), 0)), -}); - -router.get('/history/:pubkey', async (req: Request, res: Response) => { - try { - const { pubkey } = req.params; - - const queryParsed = historyQuerySchema.safeParse(req.query); - if (!queryParsed.success) { - res.status(400).json({ - success: false, - error: 'Invalid query parameters', - userMessage: 'Please provide valid limit and offset values.', - }); - return; - } - - const { limit, offset } = queryParsed.data; - const transfers = await ledger.getTransferHistory(pubkey, limit, offset); - - res.json({ - success: true, - data: { - transfers: transfers.map(transferToJson), - pagination: { limit, offset, count: transfers.length }, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[transferRoutes] GET /history error:', message); - res.status(500).json({ - success: false, - error: message, - userMessage: 'Failed to retrieve transfer history. Please try again.', - }); - } -}); - -export default router; diff --git a/legacy/taproot-assets-era/backend/src/api/routes/userRoutes.ts b/legacy/taproot-assets-era/backend/src/api/routes/userRoutes.ts deleted file mode 100644 index 31fca95..0000000 --- a/legacy/taproot-assets-era/backend/src/api/routes/userRoutes.ts +++ /dev/null @@ -1,145 +0,0 @@ -/** - * User management API routes. - */ - -import { Router, Request, Response } from 'express'; -import { z } from 'zod'; -import Database from '../../db/Database'; -import { ChannelManager } from '../../channels/ChannelManager'; -import { channelToJson } from '../../channels/ChannelState'; -import { requireAuth } from '../../auth/AuthMiddleware'; -import { FeeManager } from '../../fees/FeeManager'; - -const router = Router(); -const db = Database.getInstance(); -const channelManager = new ChannelManager(); -const feeManager = new FeeManager(); - -/** - * GET /user/:pubkey - * Get user info, their channels, and aggregate balance. - */ -router.get('/user/:pubkey', async (req: Request, res: Response) => { - try { - const { pubkey } = req.params; - - const user = await db.getUser(pubkey); - if (!user) { - res.status(404).json({ - success: false, - error: 'User not found', - }); - return; - } - - const channels = await channelManager.getChannelsByPubkey(pubkey); - - // Aggregate balance across all open channels - let totalLocal = 0n; - let totalRemote = 0n; - let totalCapacity = 0n; - - for (const channel of channels) { - if (channel.state === 'OPEN') { - totalLocal += channel.localBalance; - totalRemote += channel.remoteBalance; - totalCapacity += channel.capacity; - } - } - - const freeRemaining = await feeManager.getFreeTransactionsRemaining(pubkey); - - res.json({ - success: true, - data: { - pubkey: user.pubkey, - username: user.username, - createdAt: user.created_at, - channels: channels.map(channelToJson), - aggregateBalance: { - local: totalLocal.toString(), - remote: totalRemote.toString(), - capacity: totalCapacity.toString(), - }, - channelCount: channels.length, - openChannelCount: channels.filter((c) => c.state === 'OPEN').length, - freeTransactionsRemaining: freeRemaining, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[userRoutes] GET /user/:pubkey error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -/** - * POST /user/register - * Register a username for the authenticated user's pubkey. - */ -const registerSchema = z.object({ - username: z - .string() - .min(3, 'Username must be at least 3 characters') - .max(32, 'Username must be at most 32 characters') - .regex( - /^[a-zA-Z0-9_-]+$/, - 'Username can only contain letters, numbers, underscores, and hyphens' - ), -}); - -router.post('/user/register', requireAuth, async (req: Request, res: Response) => { - try { - const parsed = registerSchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map((e) => e.message).join('; '), - }); - return; - } - - const { username } = parsed.data; - const pubkey = req.auth!.pubkey; - - // Check if username is already taken - const existing = await db.getUserByUsername(username); - if (existing && existing.pubkey !== pubkey) { - res.status(409).json({ - success: false, - error: 'Username is already taken', - }); - return; - } - - // Ensure user exists - await db.createUser(pubkey); - - // Update username - await db.updateUsername(pubkey, username); - - const user = await db.getUser(pubkey); - - res.json({ - success: true, - data: { - pubkey: user!.pubkey, - username: user!.username, - createdAt: user!.created_at, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - if (message.includes('UNIQUE constraint')) { - res.status(409).json({ - success: false, - error: 'Username is already taken', - }); - return; - } - console.error('[userRoutes] POST /user/register error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -export default router; diff --git a/legacy/taproot-assets-era/backend/src/api/routes/wellKnownRoutes.ts b/legacy/taproot-assets-era/backend/src/api/routes/wellKnownRoutes.ts deleted file mode 100644 index cff4de2..0000000 --- a/legacy/taproot-assets-era/backend/src/api/routes/wellKnownRoutes.ts +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Well-known routes for protocol-level discovery. - * Similar to Lightning Address (.well-known/lnurlp), this allows - * resolving a RuneBolt username to channel information. - */ - -import { Router, Request, Response } from 'express'; -import Database from '../../db/Database'; -import { ChannelManager } from '../../channels/ChannelManager'; -import { channelToJson } from '../../channels/ChannelState'; - -const router = Router(); -const db = Database.getInstance(); -const channelManager = new ChannelManager(); - -/** - * GET /.well-known/rune-address/:username - * Resolve a username to pubkey and channel info. - */ -router.get('/.well-known/rune-address/:username', async (req: Request, res: Response) => { - try { - const { username } = req.params; - - const user = await db.getUserByUsername(username); - if (!user) { - res.status(404).json({ - success: false, - error: `Username "${username}" not found`, - }); - return; - } - - const channels = await channelManager.getChannelsByPubkey(user.pubkey); - const openChannels = channels.filter((c) => c.state === 'OPEN'); - - let totalInboundCapacity = 0n; - for (const channel of openChannels) { - totalInboundCapacity += channel.remoteBalance; - } - - res.json({ - success: true, - data: { - username: user.username, - pubkey: user.pubkey, - status: openChannels.length > 0 ? 'online' : 'offline', - channels: openChannels.map(channelToJson), - inboundCapacity: totalInboundCapacity.toString(), - canReceive: openChannels.length > 0 && totalInboundCapacity > 0n, - metadata: { - protocol: 'runebolt', - version: '0.1.0', - rune: 'DOG\u2022GO\u2022TO\u2022THE\u2022MOON', - runeId: '1:0', - }, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[wellKnownRoutes] Error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -export default router; diff --git a/legacy/taproot-assets-era/backend/src/assets/AssetRegistry.ts b/legacy/taproot-assets-era/backend/src/assets/AssetRegistry.ts deleted file mode 100644 index 7d8f909..0000000 --- a/legacy/taproot-assets-era/backend/src/assets/AssetRegistry.ts +++ /dev/null @@ -1,145 +0,0 @@ -/** - * AssetRegistry — Central registry of supported assets in RuneBolt. - * - * RuneBolt supports FOUR asset types, each with a DIFFERENT on-chain mechanism: - * - RUNE: Uses Runestone OP_RETURN protocol (e.g. DOG) - * - BTC: Native Bitcoin sats - * - BRC20: Uses inscription-based transfers (JSON envelope), NOT Runestones - * - INSCRIPTION: NFTs like Bitmap — non-fungible, uses escrow model - */ - -export enum AssetType { - RUNE = 'rune', - BTC = 'btc', - BRC20 = 'brc20', - INSCRIPTION = 'inscription', -} - -export interface Asset { - id: string; - name: string; - type: AssetType; - decimals: number; - /** Only set for Rune assets (e.g. '840000:3') */ - runeId?: string; - /** Only set for BRC-20 tokens (e.g. 'ordi') */ - ticker?: string; - minTransfer: bigint; - maxTransfer: bigint; -} - -/** JSON-safe representation for API responses */ -export interface AssetJson { - id: string; - name: string; - type: AssetType; - decimals: number; - runeId?: string; - ticker?: string; - minTransfer: string; - maxTransfer: string; -} - -export function assetToJson(asset: Asset): AssetJson { - return { - id: asset.id, - name: asset.name, - type: asset.type, - decimals: asset.decimals, - ...(asset.runeId ? { runeId: asset.runeId } : {}), - ...(asset.ticker ? { ticker: asset.ticker } : {}), - minTransfer: asset.minTransfer.toString(), - maxTransfer: asset.maxTransfer.toString(), - }; -} - -/** - * AssetRegistry — singleton registry for all supported assets. - * - * Pre-loaded with the four launch assets: DOG, BTC, ORDI, BITMAP. - */ -class AssetRegistry { - private static instance: AssetRegistry; - private assets: Map = new Map(); - - private constructor() { - this.registerDefaults(); - } - - static getInstance(): AssetRegistry { - if (!AssetRegistry.instance) { - AssetRegistry.instance = new AssetRegistry(); - } - return AssetRegistry.instance; - } - - private registerDefaults(): void { - // DOG — Rune token, uses Runestone OP_RETURN - this.register({ - id: 'dog', - name: 'DOG', - type: AssetType.RUNE, - decimals: 5, - runeId: '840000:3', - minTransfer: 1n, - maxTransfer: 100_000_000_000_000n, // 1 billion DOG at 5 decimals - }); - - // BTC — Native sats - this.register({ - id: 'btc', - name: 'Bitcoin', - type: AssetType.BTC, - decimals: 8, - minTransfer: 546n, // dust limit - maxTransfer: 21_000_000_00_000_000n, // 21M BTC in sats - }); - - // ORDI — BRC-20 token, uses inscription-based transfer (NOT Runestones) - this.register({ - id: 'ordi', - name: 'ORDI', - type: AssetType.BRC20, - decimals: 18, - ticker: 'ordi', - minTransfer: 1n, - maxTransfer: 21_000_000_000_000_000_000_000_000n, // 21M at 18 decimals - }); - - // BITMAP — Inscription NFT, uses escrow model (non-fungible, cannot be split) - this.register({ - id: 'bitmap', - name: 'Bitmap', - type: AssetType.INSCRIPTION, - decimals: 0, - minTransfer: 1n, - maxTransfer: 1n, // NFTs are always 1 - }); - } - - register(asset: Asset): void { - this.assets.set(asset.id, asset); - } - - get(id: string): Asset | undefined { - return this.assets.get(id); - } - - getAll(): Asset[] { - return Array.from(this.assets.values()); - } - - getByType(type: AssetType): Asset[] { - return this.getAll().filter(a => a.type === type); - } - - getByTicker(ticker: string): Asset | undefined { - return this.getAll().find(a => a.ticker === ticker); - } - - has(id: string): boolean { - return this.assets.has(id); - } -} - -export default AssetRegistry; diff --git a/legacy/taproot-assets-era/backend/src/assets/BRC20Manager.ts b/legacy/taproot-assets-era/backend/src/assets/BRC20Manager.ts deleted file mode 100644 index 5c58928..0000000 --- a/legacy/taproot-assets-era/backend/src/assets/BRC20Manager.ts +++ /dev/null @@ -1,237 +0,0 @@ -/** - * BRC20Manager — Handles BRC-20 token operations for RuneBolt. - * - * IMPORTANT: BRC-20 tokens use a DIFFERENT on-chain mechanism than Runes. - * - Runes use Runestone OP_RETURN protocol - * - BRC-20 tokens transfer via inscriptions containing JSON payloads: - * { "p": "brc-20", "op": "transfer", "tick": "ordi", "amt": "1000" } - * - * For RuneBolt payment channels: - * 1. User sends BRC-20 inscription to hub multisig address - * 2. Hub tracks balances off-chain within the channel - * 3. Settlement: hub inscribes a transfer back to the user's address - */ - -import Database from '../db/Database'; - -/** BRC-20 transfer inscription content */ -export interface BRC20TransferContent { - p: 'brc-20'; - op: 'transfer'; - tick: string; - amt: string; -} - -/** BRC-20 inscription metadata returned from indexer APIs */ -export interface BRC20Inscription { - inscriptionId: string; - ticker: string; - amount: string; - owner: string; - confirmed: boolean; -} - -/** Balance info for a BRC-20 token */ -export interface BRC20Balance { - ticker: string; - available: string; - transferable: string; - total: string; -} - -class BRC20Manager { - private db: Database; - private readonly unisatBaseUrl: string; - - constructor() { - this.db = Database.getInstance(); - this.unisatBaseUrl = process.env.UNISAT_API_URL || 'https://open-api.unisat.io/v1'; - } - - /** - * Build the JSON content for a BRC-20 transfer inscription. - * - * This is the payload that gets inscribed on-chain to move BRC-20 tokens. - * NOT an OP_RETURN — it's an ordinals inscription with JSON content. - */ - buildTransferInscription(ticker: string, amount: string): BRC20TransferContent { - if (!ticker || ticker.length < 1 || ticker.length > 5) { - throw new Error('BRC-20 ticker must be 1-5 characters'); - } - - if (!amount || !/^\d+$/.test(amount)) { - throw new Error('BRC-20 amount must be a positive integer string'); - } - - if (BigInt(amount) <= 0n) { - throw new Error('BRC-20 transfer amount must be greater than zero'); - } - - return { - p: 'brc-20', - op: 'transfer', - tick: ticker.toLowerCase(), - amt: amount, - }; - } - - /** - * Serialize a BRC-20 transfer inscription to the JSON string that gets inscribed. - */ - serializeInscription(content: BRC20TransferContent): string { - return JSON.stringify(content); - } - - /** - * Verify a BRC-20 balance for an address via the Unisat API. - * - * In production, this calls the Unisat indexer. In dev/test, returns mock data - * if UNISAT_API_KEY is not set. - */ - async verifyBRC20Balance(address: string, ticker: string): Promise { - const apiKey = process.env.UNISAT_API_KEY; - - if (!apiKey) { - // Dev/test fallback: return zero balances - console.warn('[BRC20Manager] No UNISAT_API_KEY set — returning zero balances'); - return { - ticker, - available: '0', - transferable: '0', - total: '0', - }; - } - - const url = `${this.unisatBaseUrl}/indexer/address/${address}/brc20/${ticker}/info`; - - const response = await fetch(url, { - headers: { - 'Authorization': `Bearer ${apiKey}`, - 'Content-Type': 'application/json', - }, - }); - - if (!response.ok) { - throw new Error(`Unisat API error: ${response.status} ${response.statusText}`); - } - - const data = await response.json() as { - code: number; - data: { - availableBalance: string; - transferableBalance: string; - overallBalance: string; - }; - }; - - if (data.code !== 0) { - throw new Error(`Unisat API returned error code: ${data.code}`); - } - - return { - ticker, - available: data.data.availableBalance, - transferable: data.data.transferableBalance, - total: data.data.overallBalance, - }; - } - - /** - * Get BRC-20 inscriptions held by an address via the Unisat API. - */ - async getInscriptionsByAddress(address: string): Promise { - const apiKey = process.env.UNISAT_API_KEY; - - if (!apiKey) { - console.warn('[BRC20Manager] No UNISAT_API_KEY set — returning empty inscriptions'); - return []; - } - - const url = `${this.unisatBaseUrl}/indexer/address/${address}/inscription-data?cursor=0&size=100`; - - const response = await fetch(url, { - headers: { - 'Authorization': `Bearer ${apiKey}`, - 'Content-Type': 'application/json', - }, - }); - - if (!response.ok) { - throw new Error(`Unisat API error: ${response.status} ${response.statusText}`); - } - - const data = await response.json() as { - code: number; - data: { - inscription: Array<{ - inscriptionId: string; - contentType: string; - contentBody: string; - address: string; - utxo: { satoshi: number; confirmations: number }; - }>; - }; - }; - - if (data.code !== 0) { - throw new Error(`Unisat API returned error code: ${data.code}`); - } - - const brc20Inscriptions: BRC20Inscription[] = []; - - for (const insc of data.data.inscription) { - if (!insc.contentType?.includes('json')) continue; - - try { - const content = JSON.parse(insc.contentBody) as Record; - if (content.p === 'brc-20' && content.op === 'transfer') { - brc20Inscriptions.push({ - inscriptionId: insc.inscriptionId, - ticker: String(content.tick), - amount: String(content.amt), - owner: insc.address, - confirmed: insc.utxo.confirmations > 0, - }); - } - } catch { - // Not valid JSON — skip - } - } - - return brc20Inscriptions; - } - - /** - * Record a BRC-20 channel deposit in the database. - * Called when a user sends a BRC-20 inscription to the hub multisig. - */ - async recordDeposit( - userPubkey: string, - assetId: string, - amount: string, - inscriptionId: string, - ): Promise { - await this.db.query( - `INSERT INTO asset_balances (user_pubkey, asset_id, balance, updated_at) - VALUES ($1, $2, $3, NOW()) - ON CONFLICT (user_pubkey, asset_id) - DO UPDATE SET balance = asset_balances.balance + $3::numeric, updated_at = NOW()`, - [userPubkey, assetId, amount] - ); - - console.log(`[BRC20Manager] Recorded deposit: ${amount} ${assetId} from ${userPubkey} (inscription: ${inscriptionId})`); - } - - /** - * Get a user's off-chain BRC-20 balance tracked by the hub. - */ - async getChannelBalance(userPubkey: string, assetId: string): Promise { - const row = await this.db.queryOne<{ balance: string }>( - 'SELECT balance FROM asset_balances WHERE user_pubkey = $1 AND asset_id = $2', - [userPubkey, assetId] - ); - return row?.balance ?? '0'; - } -} - -export default BRC20Manager; diff --git a/legacy/taproot-assets-era/backend/src/assets/BitmapEscrow.ts b/legacy/taproot-assets-era/backend/src/assets/BitmapEscrow.ts deleted file mode 100644 index 1b91277..0000000 --- a/legacy/taproot-assets-era/backend/src/assets/BitmapEscrow.ts +++ /dev/null @@ -1,357 +0,0 @@ -/** - * BitmapEscrow — Escrow model for Bitmap (NFT inscription) trading on RuneBolt. - * - * IMPORTANT: Bitmaps are single, non-fungible inscriptions — they CANNOT be split. - * This is a DIFFERENT model than Rune/BRC-20 payment channels. - * - * Transfer model — Atomic swap via escrow: - * 1. Seller deposits Bitmap inscription to escrow multisig address - * 2. Buyer deposits payment (BTC/DOG) to escrow - * 3. Hub verifies both sides arrived - * 4. Hub releases both atomically (inscription to buyer, payment to seller) - * 5. If either side doesn't fulfill within timeout, refund - */ - -import { v4 as uuidv4 } from 'uuid'; -import Database from '../db/Database'; - -export enum EscrowStatus { - CREATED = 'created', - INSCRIPTION_DEPOSITED = 'inscription_deposited', - PAYMENT_DEPOSITED = 'payment_deposited', - BOTH_DEPOSITED = 'both_deposited', - EXECUTING = 'executing', - COMPLETED = 'completed', - REFUNDED = 'refunded', - EXPIRED = 'expired', -} - -export interface Escrow { - id: string; - sellerPubkey: string; - buyerPubkey: string; - inscriptionId: string; - priceAsset: string; - priceAmount: string; - status: EscrowStatus; - timeoutAt: string; - createdAt: string; -} - -export interface EscrowDeposit { - escrowId: string; - side: 'seller' | 'buyer'; - txid: string; - confirmed: boolean; - createdAt: string; -} - -/** Default escrow timeout: 24 hours */ -const DEFAULT_TIMEOUT_MS = 24 * 60 * 60 * 1000; - -class BitmapEscrow { - private db: Database; - - constructor() { - this.db = Database.getInstance(); - } - - /** - * Create a new escrow for a Bitmap inscription trade. - * - * @param sellerPubkey - Pubkey of the inscription owner - * @param buyerPubkey - Pubkey of the buyer - * @param inscriptionId - The ordinals inscription ID being sold - * @param priceAsset - Asset used for payment (e.g. 'btc', 'dog') - * @param priceAmount - Price in the smallest unit of priceAsset - * @param timeoutMs - Optional timeout in ms (default 24h) - */ - async createEscrow( - sellerPubkey: string, - buyerPubkey: string, - inscriptionId: string, - priceAsset: string, - priceAmount: string, - timeoutMs: number = DEFAULT_TIMEOUT_MS, - ): Promise { - if (sellerPubkey === buyerPubkey) { - throw new Error('Seller and buyer cannot be the same pubkey'); - } - - if (!inscriptionId) { - throw new Error('Inscription ID is required'); - } - - if (!priceAmount || BigInt(priceAmount) <= 0n) { - throw new Error('Price must be greater than zero'); - } - - const id = uuidv4(); - const timeoutAt = new Date(Date.now() + timeoutMs).toISOString(); - - await this.db.query( - `INSERT INTO escrows (id, seller_pubkey, buyer_pubkey, inscription_id, price_asset, price_amount, status, timeout_at) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, - [id, sellerPubkey, buyerPubkey, inscriptionId, priceAsset, priceAmount, EscrowStatus.CREATED, timeoutAt] - ); - - console.log(`[BitmapEscrow] Created escrow ${id}: ${inscriptionId} for ${priceAmount} ${priceAsset}`); - return id; - } - - /** - * Record that the seller has deposited the inscription to the escrow multisig. - */ - async depositInscription(escrowId: string, txid: string): Promise { - return await this.db.transaction(async (client) => { - const escrow = await this.getEscrowWithClient(client, escrowId); - - if (escrow.status !== EscrowStatus.CREATED && escrow.status !== EscrowStatus.PAYMENT_DEPOSITED) { - throw new Error(`Cannot deposit inscription in escrow state: ${escrow.status}`); - } - - // Record the deposit - await client.query( - `INSERT INTO escrow_deposits (escrow_id, side, txid, confirmed) - VALUES ($1, 'seller', $2, false)`, - [escrowId, txid] - ); - - // Update escrow status - const newStatus = escrow.status === EscrowStatus.PAYMENT_DEPOSITED - ? EscrowStatus.BOTH_DEPOSITED - : EscrowStatus.INSCRIPTION_DEPOSITED; - - await client.query( - 'UPDATE escrows SET status = $1 WHERE id = $2', - [newStatus, escrowId] - ); - - return { ...escrow, status: newStatus }; - }); - } - - /** - * Record that the buyer has deposited payment to the escrow. - */ - async depositPayment(escrowId: string, txid: string): Promise { - return await this.db.transaction(async (client) => { - const escrow = await this.getEscrowWithClient(client, escrowId); - - if (escrow.status !== EscrowStatus.CREATED && escrow.status !== EscrowStatus.INSCRIPTION_DEPOSITED) { - throw new Error(`Cannot deposit payment in escrow state: ${escrow.status}`); - } - - // Record the deposit - await client.query( - `INSERT INTO escrow_deposits (escrow_id, side, txid, confirmed) - VALUES ($1, 'buyer', $2, false)`, - [escrowId, txid] - ); - - // Update escrow status - const newStatus = escrow.status === EscrowStatus.INSCRIPTION_DEPOSITED - ? EscrowStatus.BOTH_DEPOSITED - : EscrowStatus.PAYMENT_DEPOSITED; - - await client.query( - 'UPDATE escrows SET status = $1 WHERE id = $2', - [newStatus, escrowId] - ); - - return { ...escrow, status: newStatus }; - }); - } - - /** - * Execute the atomic swap — release inscription to buyer, payment to seller. - * - * Only callable when both sides have deposited (status = BOTH_DEPOSITED). - * In production this would broadcast the release transactions on-chain. - */ - async executeSwap(escrowId: string): Promise { - return await this.db.transaction(async (client) => { - const escrow = await this.getEscrowWithClient(client, escrowId); - - if (escrow.status !== EscrowStatus.BOTH_DEPOSITED) { - throw new Error(`Cannot execute swap: escrow is in state ${escrow.status}, expected ${EscrowStatus.BOTH_DEPOSITED}`); - } - - // Mark as executing - await client.query( - 'UPDATE escrows SET status = $1 WHERE id = $2', - [EscrowStatus.EXECUTING, escrowId] - ); - - // TODO: In production, broadcast release transactions: - // 1. Transfer inscription from multisig to buyer address - // 2. Transfer payment from multisig to seller address - // For now, mark both deposits as confirmed and complete the escrow. - - await client.query( - 'UPDATE escrow_deposits SET confirmed = true WHERE escrow_id = $1', - [escrowId] - ); - - await client.query( - 'UPDATE escrows SET status = $1 WHERE id = $2', - [EscrowStatus.COMPLETED, escrowId] - ); - - console.log(`[BitmapEscrow] Swap executed for escrow ${escrowId}`); - return { ...escrow, status: EscrowStatus.COMPLETED }; - }); - } - - /** - * Refund an escrow that has timed out or where one side didn't fulfill. - * - * Returns deposits to their original owners. - */ - async refundEscrow(escrowId: string): Promise { - return await this.db.transaction(async (client) => { - const escrow = await this.getEscrowWithClient(client, escrowId); - - const refundableStates: string[] = [ - EscrowStatus.CREATED, - EscrowStatus.INSCRIPTION_DEPOSITED, - EscrowStatus.PAYMENT_DEPOSITED, - EscrowStatus.BOTH_DEPOSITED, - ]; - - if (!refundableStates.includes(escrow.status)) { - throw new Error(`Cannot refund escrow in state: ${escrow.status}`); - } - - // Check if timeout has passed (anyone can trigger refund after timeout) - const now = new Date(); - const timeout = new Date(escrow.timeoutAt); - if (now < timeout && escrow.status !== EscrowStatus.CREATED) { - throw new Error('Escrow has not timed out yet — both parties must wait for timeout or complete the swap'); - } - - // TODO: In production, broadcast refund transactions on-chain - - await client.query( - 'UPDATE escrows SET status = $1 WHERE id = $2', - [EscrowStatus.REFUNDED, escrowId] - ); - - console.log(`[BitmapEscrow] Refunded escrow ${escrowId}`); - return { ...escrow, status: EscrowStatus.REFUNDED }; - }); - } - - /** - * Get escrow status and details. - */ - async getEscrowStatus(escrowId: string): Promise<{ escrow: Escrow; deposits: EscrowDeposit[] }> { - const escrowRow = await this.db.queryOne<{ - id: string; - seller_pubkey: string; - buyer_pubkey: string; - inscription_id: string; - price_asset: string; - price_amount: string; - status: EscrowStatus; - timeout_at: string; - created_at: string; - }>('SELECT * FROM escrows WHERE id = $1', [escrowId]); - - if (!escrowRow) { - throw new Error(`Escrow not found: ${escrowId}`); - } - - const depositRows = await this.db.query<{ - escrow_id: string; - side: 'seller' | 'buyer'; - txid: string; - confirmed: boolean; - created_at: string; - }>('SELECT * FROM escrow_deposits WHERE escrow_id = $1 ORDER BY created_at ASC', [escrowId]); - - const escrow: Escrow = { - id: escrowRow.id, - sellerPubkey: escrowRow.seller_pubkey, - buyerPubkey: escrowRow.buyer_pubkey, - inscriptionId: escrowRow.inscription_id, - priceAsset: escrowRow.price_asset, - priceAmount: escrowRow.price_amount, - status: escrowRow.status, - timeoutAt: escrowRow.timeout_at, - createdAt: escrowRow.created_at, - }; - - const deposits: EscrowDeposit[] = depositRows.rows.map(d => ({ - escrowId: d.escrow_id, - side: d.side, - txid: d.txid, - confirmed: d.confirmed, - createdAt: d.created_at, - })); - - return { escrow, deposits }; - } - - /** - * Get all escrows for a pubkey (as seller or buyer). - */ - async getEscrowsByPubkey(pubkey: string): Promise { - const result = await this.db.query<{ - id: string; - seller_pubkey: string; - buyer_pubkey: string; - inscription_id: string; - price_asset: string; - price_amount: string; - status: EscrowStatus; - timeout_at: string; - created_at: string; - }>( - 'SELECT * FROM escrows WHERE seller_pubkey = $1 OR buyer_pubkey = $1 ORDER BY created_at DESC', - [pubkey] - ); - - return result.rows.map(r => ({ - id: r.id, - sellerPubkey: r.seller_pubkey, - buyerPubkey: r.buyer_pubkey, - inscriptionId: r.inscription_id, - priceAsset: r.price_asset, - priceAmount: r.price_amount, - status: r.status, - timeoutAt: r.timeout_at, - createdAt: r.created_at, - })); - } - - // Internal helper: fetch escrow within an existing transaction - private async getEscrowWithClient( - client: import('pg').PoolClient, - escrowId: string, - ): Promise { - const result = await client.query( - 'SELECT * FROM escrows WHERE id = $1 FOR UPDATE', - [escrowId] - ); - - const row = result.rows[0]; - if (!row) { - throw new Error(`Escrow not found: ${escrowId}`); - } - - return { - id: row.id, - sellerPubkey: row.seller_pubkey, - buyerPubkey: row.buyer_pubkey, - inscriptionId: row.inscription_id, - priceAsset: row.price_asset, - priceAmount: row.price_amount, - status: row.status as EscrowStatus, - timeoutAt: row.timeout_at, - createdAt: row.created_at, - }; - } -} - -export default BitmapEscrow; diff --git a/legacy/taproot-assets-era/backend/src/auth/AuthMiddleware.ts b/legacy/taproot-assets-era/backend/src/auth/AuthMiddleware.ts deleted file mode 100644 index 187bf04..0000000 --- a/legacy/taproot-assets-era/backend/src/auth/AuthMiddleware.ts +++ /dev/null @@ -1,153 +0,0 @@ -/** - * JWT-based authentication middleware for Express routes. - */ - -import { Request, Response, NextFunction } from 'express'; -import jwt from 'jsonwebtoken'; -import crypto from 'crypto'; - -// SECURITY: Generate strong JWT secret if not provided -// In production, JWT_SECRET MUST be set via environment variable -function getJwtSecret(): string { - const envSecret = process.env.JWT_SECRET; - - if (envSecret && envSecret.length >= 32 && envSecret !== 'change_me_in_production') { - return envSecret; - } - - if (process.env.NODE_ENV === 'production') { - throw new Error( - 'CRITICAL: JWT_SECRET must be set to a strong secret (min 32 chars) in production. ' + - 'Run: export JWT_SECRET=$(openssl rand -hex 32)' - ); - } - - // Development: generate a temporary secret with warning - const devSecret = crypto.randomBytes(32).toString('hex'); - console.warn('[AuthMiddleware] WARNING: Using temporary JWT secret. Set JWT_SECRET in .env for persistence.'); - return devSecret; -} - -const JWT_SECRET = getJwtSecret(); -const JWT_EXPIRY = '24h'; -const JWT_ALGORITHM = 'HS256'; - -export interface AuthPayload { - pubkey: string; - iat?: number; - exp?: number; -} - -/** - * Extend Express Request to include authenticated user info. - */ -declare global { - namespace Express { - interface Request { - auth?: AuthPayload; - } - } -} - -/** - * Generate a JWT token for an authenticated user. - */ -export function generateToken(pubkey: string): string { - const payload: AuthPayload = { pubkey }; - return jwt.sign(payload, JWT_SECRET, { - expiresIn: JWT_EXPIRY, - algorithm: JWT_ALGORITHM as jwt.Algorithm, - }); -} - -/** - * Verify and decode a JWT token with strict validation. - */ -export function verifyToken(token: string): AuthPayload { - try { - const decoded = jwt.verify(token, JWT_SECRET, { - algorithms: [JWT_ALGORITHM as jwt.Algorithm], - maxAge: JWT_EXPIRY, - }) as AuthPayload; - - // Validate payload structure - if (!decoded.pubkey || typeof decoded.pubkey !== 'string') { - throw new Error('Invalid token payload: missing pubkey'); - } - - // Validate pubkey format (64-66 hex characters) - if (!/^[0-9a-fA-F]{64,66}$/.test(decoded.pubkey)) { - throw new Error('Invalid token payload: malformed pubkey'); - } - - return decoded; - } catch (err) { - if (err instanceof jwt.JsonWebTokenError) { - throw new Error('Invalid token'); - } - if (err instanceof jwt.TokenExpiredError) { - throw new Error('Token expired'); - } - throw new Error('Authentication failed'); - } -} - -/** - * Required authentication middleware. - * Rejects requests without a valid JWT. - */ -export function requireAuth(req: Request, res: Response, next: NextFunction): void { - const authHeader = req.headers.authorization; - - if (!authHeader) { - res.status(401).json({ - success: false, - error: 'Authorization header is required', - }); - return; - } - - const parts = authHeader.split(' '); - if (parts.length !== 2 || parts[0] !== 'Bearer') { - res.status(401).json({ - success: false, - error: 'Authorization header must be: Bearer ', - }); - return; - } - - const token = parts[1]; - - try { - const payload = verifyToken(token); - req.auth = payload; - next(); - } catch { - res.status(401).json({ - success: false, - error: 'Invalid or expired authentication token', - }); - } -} - -/** - * Optional authentication middleware. - * Attaches auth info if a valid JWT is present, but doesn't reject otherwise. - */ -export function optionalAuth(req: Request, _res: Response, next: NextFunction): void { - const authHeader = req.headers.authorization; - - if (authHeader) { - const parts = authHeader.split(' '); - if (parts.length === 2 && parts[0] === 'Bearer') { - try { - const payload = verifyToken(parts[1]); - req.auth = payload; - } catch { - // Ignore invalid tokens for optional auth - } - } - } - - next(); -} diff --git a/legacy/taproot-assets-era/backend/src/auth/ChallengeManager.ts b/legacy/taproot-assets-era/backend/src/auth/ChallengeManager.ts deleted file mode 100644 index 9b4083d..0000000 --- a/legacy/taproot-assets-era/backend/src/auth/ChallengeManager.ts +++ /dev/null @@ -1,114 +0,0 @@ -/** - * Challenge-response authentication using Bitcoin message signing. - * - * Flow: - * 1. Client requests a challenge for their pubkey - * 2. Server generates a random challenge string and stores it - * 3. Client signs the challenge with their Bitcoin private key - * 4. Server verifies the signature and issues a JWT - */ - -import crypto from 'crypto'; -import { v4 as uuidv4 } from 'uuid'; -import * as secp256k1 from '@noble/secp256k1'; -import { sha256 } from '@noble/hashes/sha2.js'; -import { hmac } from '@noble/hashes/hmac.js'; -import Database from '../db/Database'; - -// Configure @noble/secp256k1 v3 with hash functions (idempotent) -secp256k1.hashes.sha256 = (msg: Uint8Array) => sha256(msg); -secp256k1.hashes.hmacSha256 = (key: Uint8Array, ...msgs: Uint8Array[]) => - hmac(sha256, key, secp256k1.etc.concatBytes(...msgs)); - -/** Challenge validity duration in milliseconds (5 minutes) */ -const CHALLENGE_EXPIRY_MS = 5 * 60 * 1000; - -export class ChallengeManager { - private db: Database; - - constructor() { - this.db = Database.getInstance(); - } - - /** - * Create a new authentication challenge for a given pubkey. - */ - async createChallenge(pubkey: string): Promise<{ challengeId: string; message: string }> { - const challengeId = uuidv4(); - const nonce = crypto.randomBytes(32).toString('hex'); - const timestamp = Date.now(); - - // Create a human-readable challenge message that the user will sign - const message = - `RuneBolt authentication challenge\n` + - `Pubkey: ${pubkey}\n` + - `Nonce: ${nonce}\n` + - `Timestamp: ${timestamp}\n` + - `Challenge ID: ${challengeId}`; - - const expiresAt = new Date(timestamp + CHALLENGE_EXPIRY_MS).toISOString(); - - // Store challenge in database - await this.db.createChallenge({ - id: challengeId, - pubkey, - challenge: message, - expires_at: expiresAt, - }); - - console.log(`[ChallengeManager] Challenge created for ${pubkey.slice(0, 16)}...: ${challengeId}`); - - return { challengeId, message }; - } - - /** - * Verify a signed challenge using BIP-322 Schnorr signature verification. - * - * SECURITY: This implements real cryptographic signature verification. - * Never accepts signatures in any mode without proper verification. - */ - async verifyChallenge(challengeId: string, signature: string): Promise<{ valid: boolean; pubkey: string | null }> { - // Fetch the challenge from the database - const challenge = await this.db.getChallenge(challengeId); - if (!challenge) { - console.log(`[ChallengeManager] Challenge ${challengeId} not found`); - return { valid: false, pubkey: null }; - } - - // Check expiry - const expiresAt = new Date(challenge.expires_at).getTime(); - if (Date.now() > expiresAt) { - console.log(`[ChallengeManager] Challenge ${challengeId} expired`); - await this.db.deleteChallenge(challengeId); - return { valid: false, pubkey: null }; - } - - // CRITICAL: Actually verify the signature - try { - const messageHash = sha256(new TextEncoder().encode(challenge.challenge)); - const sigBytes = new Uint8Array(Buffer.from(signature, 'hex')); - const pubkeyBytes = new Uint8Array(Buffer.from(challenge.pubkey, 'hex')); - - if (sigBytes.length !== 64) { - console.log(`[ChallengeManager] Invalid signature length: ${sigBytes.length}`); - return { valid: false, pubkey: null }; - } - - const isValid = await secp256k1.schnorr.verify(sigBytes, messageHash, pubkeyBytes); - - if (!isValid) { - console.log(`[ChallengeManager] Signature verification failed for ${challenge.pubkey.slice(0, 16)}...`); - return { valid: false, pubkey: null }; - } - - // Clean up the used challenge (one-time use) - await this.db.deleteChallenge(challengeId); - - console.log(`[ChallengeManager] Challenge ${challengeId} verified successfully for ${challenge.pubkey.slice(0, 16)}...`); - return { valid: true, pubkey: challenge.pubkey }; - } catch (err) { - console.error('[ChallengeManager] Signature verification error:', err); - return { valid: false, pubkey: null }; - } - } -} diff --git a/legacy/taproot-assets-era/backend/src/bitcoin/BitcoinClient.ts b/legacy/taproot-assets-era/backend/src/bitcoin/BitcoinClient.ts deleted file mode 100644 index adf0a4e..0000000 --- a/legacy/taproot-assets-era/backend/src/bitcoin/BitcoinClient.ts +++ /dev/null @@ -1,313 +0,0 @@ -/** - * High-level Bitcoin client that orchestrates Taproot operations - * and mempool interactions for channel funding and closing. - * - * Uses bitcoinjs-lib for real PSBT construction and mempool.space - * for broadcasting and fee estimation. - */ - -import * as bitcoin from 'bitcoinjs-lib'; -import * as ecc from '@bitcoinerlab/secp256k1'; -import { TaprootUtils } from './TaprootUtils'; -import { MempoolClient, UTXO, FeeEstimates, Transaction } from './MempoolClient'; -import { Channel } from '../channels/ChannelState'; -import { RuneBuilder } from '../rune/RuneBuilder'; -import { DOG_RUNE_ID } from '../rune/RuneConstants'; - -bitcoin.initEccLib(ecc); - -/** Default confirmation polling interval (30 seconds) */ -const POLL_INTERVAL_MS = 30_000; -/** Default max polling attempts (100 × 30s ≈ 50 minutes) */ -const MAX_POLL_ATTEMPTS = 100; - -/** - * Get the Bitcoin network from BITCOIN_NETWORK env var. - */ -function getNetwork(): bitcoin.Network { - const networkName = process.env.BITCOIN_NETWORK || 'mainnet'; - switch (networkName) { - case 'testnet': - return bitcoin.networks.testnet; - case 'regtest': - return bitcoin.networks.regtest; - default: - return bitcoin.networks.bitcoin; - } -} - -export class BitcoinClient { - private mempool: MempoolClient; - - constructor(mempoolClient?: MempoolClient) { - this.mempool = mempoolClient || new MempoolClient(); - } - - /** - * Create a funding PSBT for opening a channel. - * The PSBT spends user UTXOs to a 2-of-2 Taproot multisig address. - * - * Returns a real BIP-174 PSBT (base64) and the channel multisig address. - */ - createFundingPsbt( - userPubkey: string, - amount: bigint, - utxos: UTXO[], - runeId: string = DOG_RUNE_ID - ): { psbt: string; channelAddress: string } { - console.log( - `[BitcoinClient] Creating funding PSBT: user=${userPubkey.slice(0, 16)}..., amount=${amount}` - ); - - const network = getNetwork(); - - // Generate hub key for this channel - const hubKey = TaprootUtils.generateKeyPair(); - - // Create 2-of-2 multisig address - const multisig = TaprootUtils.createMultisigAddress(userPubkey, hubKey.publicKey); - - // Select UTXOs to cover amount + estimated fees - // For rune transfers, the BTC output is dust (546 sats) — runes are tracked by Runestone - const dustAmount = 546; - const estimatedVbytes = 150 + utxos.length * 68; // ~68 vB per Taproot input - const estimatedFee = estimatedVbytes * 10; // default 10 sat/vB, caller should use getFeeEstimate - const requiredSats = dustAmount + estimatedFee; - - let totalInput = 0; - const selectedUtxos: UTXO[] = []; - for (const utxo of utxos) { - selectedUtxos.push(utxo); - totalInput += utxo.value; - if (totalInput >= requiredSats) break; - } - - if (totalInput < requiredSats) { - throw new Error( - `Insufficient UTXOs: have ${totalInput} sats, need ${requiredSats} sats` - ); - } - - // Build real PSBT using bitcoinjs-lib - const psbt = new bitcoin.Psbt({ network }); - - // Add inputs - for (const utxo of selectedUtxos) { - psbt.addInput({ - hash: utxo.txid, - index: utxo.vout, - witnessUtxo: { - script: Buffer.from(multisig.script, 'hex'), // placeholder — caller provides real scriptPubkey - value: BigInt(utxo.value), - }, - }); - } - - // Output 1: Dust output to channel multisig (this holds the runes) - psbt.addOutput({ - address: multisig.address, - value: BigInt(dustAmount), - }); - - // Output 2: OP_RETURN Runestone for rune transfer - // destinationIndex=0 directs the runes to the multisig output (output 0) - const runestoneScript = RuneBuilder.buildRunestoneOutput(runeId, amount, 0); - psbt.addOutput({ - script: runestoneScript, - value: 0n, - }); - - // Output 3: Change back to user (if any) - const changeValue = totalInput - dustAmount - estimatedFee; - if (changeValue > 546) { - // Create a P2TR change output for the user - const userPubkeyBuf = Buffer.from(userPubkey, 'hex'); - const p2trChange = bitcoin.payments.p2tr({ - internalPubkey: userPubkeyBuf, - network, - }); - if (p2trChange.address) { - psbt.addOutput({ - address: p2trChange.address, - value: BigInt(changeValue), - }); - } - } - - const psbtBase64 = psbt.toBase64(); - - console.log(`[BitcoinClient] Funding PSBT created for address ${multisig.address.slice(0, 20)}...`); - - return { - psbt: psbtBase64, - channelAddress: multisig.address, - }; - } - - /** - * Finalize a signed PSBT and broadcast the resulting transaction - * via the mempool.space API. - * - * Expects a fully-signed PSBT (base64). Finalizes all inputs, - * extracts the raw transaction hex, and broadcasts it. - * - * Returns the txid from the network. - */ - async signAndBroadcastFundingTx( - psbtBase64: string, - _userSignature: string - ): Promise { - console.log('[BitcoinClient] Finalizing and broadcasting funding transaction'); - - const network = getNetwork(); - const psbt = bitcoin.Psbt.fromBase64(psbtBase64, { network }); - - // Finalize all inputs (assumes all required signatures are present) - psbt.finalizeAllInputs(); - - // Extract the raw transaction hex - const txHex = psbt.extractTransaction().toHex(); - - console.log(`[BitcoinClient] Broadcasting tx (${txHex.length / 2} bytes)`); - - // Broadcast via mempool.space - const txid = await this.mempool.broadcastTx(txHex); - - console.log(`[BitcoinClient] Funding tx broadcast: ${txid}`); - return txid; - } - - /** - * Create a closing PSBT that distributes the channel funds - * according to the final balance state. - * - * Returns a real BIP-174 PSBT (base64). - */ - createClosingPsbt( - channel: Channel, - userBalance: bigint, - hubBalance: bigint - ): string { - console.log( - `[BitcoinClient] Creating closing PSBT for channel ${channel.id}: ` + - `user=${userBalance}, hub=${hubBalance}` - ); - - if (!channel.fundingTxid || channel.fundingVout === null) { - throw new Error('Channel has no funding transaction'); - } - - const network = getNetwork(); - const psbt = new bitcoin.Psbt({ network }); - - // Input: spend the funding output - const multisig = TaprootUtils.createMultisigAddress( - channel.userPubkey, - channel.runeboltPubkey - ); - psbt.addInput({ - hash: channel.fundingTxid, - index: channel.fundingVout, - witnessUtxo: { - script: Buffer.from(multisig.script, 'hex'), - value: 546n, // dust amount held by the funding output - }, - }); - - // Output 0: OP_RETURN Runestone encoding the balance distribution - // Uses commitment Runestone with two edicts: user (output 1) and hub (output 2) - const runestoneScript = RuneBuilder.buildCommitmentRunestone( - channel.id, - userBalance, - hubBalance - ); - psbt.addOutput({ - script: runestoneScript, - value: 0n, - }); - - // Output 2: User's share (if any) - if (userBalance > 0n) { - const userP2tr = bitcoin.payments.p2tr({ - internalPubkey: Buffer.from(channel.userPubkey, 'hex'), - network, - }); - if (userP2tr.address) { - psbt.addOutput({ - address: userP2tr.address, - value: 546n, - }); - } - } - - // Output 3: Hub's share (if any) - if (hubBalance > 0n) { - const hubP2tr = bitcoin.payments.p2tr({ - internalPubkey: Buffer.from(channel.runeboltPubkey, 'hex'), - network, - }); - if (hubP2tr.address) { - psbt.addOutput({ - address: hubP2tr.address, - value: 546n, - }); - } - } - - const psbtBase64 = psbt.toBase64(); - console.log(`[BitcoinClient] Closing PSBT built (${psbtBase64.length} chars base64)`); - return psbtBase64; - } - - /** - * Get current fee estimates from mempool.space (sat/vB). - */ - async getFeeEstimate(): Promise { - return this.mempool.getFeeEstimates(); - } - - /** - * Get a transaction by txid from mempool.space. - */ - async getTransaction(txid: string): Promise { - return this.mempool.getTx(txid); - } - - /** - * Poll mempool.space until a transaction is confirmed. - * Throws if max attempts are exhausted. - */ - async waitForConfirmation( - txid: string, - intervalMs: number = POLL_INTERVAL_MS, - maxAttempts: number = MAX_POLL_ATTEMPTS - ): Promise { - console.log(`[BitcoinClient] Waiting for confirmation of ${txid}`); - - for (let attempt = 1; attempt <= maxAttempts; attempt++) { - const tx = await this.mempool.getTx(txid); - if (tx.status.confirmed) { - console.log( - `[BitcoinClient] Transaction ${txid} confirmed at block ${tx.status.block_height}` - ); - return tx; - } - - console.log( - `[BitcoinClient] Attempt ${attempt}/${maxAttempts}: ${txid} unconfirmed, waiting ${intervalMs}ms` - ); - await new Promise((resolve) => setTimeout(resolve, intervalMs)); - } - - throw new Error( - `Transaction ${txid} not confirmed after ${maxAttempts} attempts` - ); - } - - /** - * Get the mempool client for direct API access. - */ - getMempoolClient(): MempoolClient { - return this.mempool; - } -} diff --git a/legacy/taproot-assets-era/backend/src/bitcoin/MempoolClient.ts b/legacy/taproot-assets-era/backend/src/bitcoin/MempoolClient.ts deleted file mode 100644 index ed5d291..0000000 --- a/legacy/taproot-assets-era/backend/src/bitcoin/MempoolClient.ts +++ /dev/null @@ -1,208 +0,0 @@ -/** - * Client for the mempool.space REST API. - * Provides access to UTXOs, transactions, fee estimates, and broadcasting. - * - * Supports mainnet, testnet, and signet via BITCOIN_NETWORK env var. - */ - -export interface UTXO { - txid: string; - vout: number; - status: { - confirmed: boolean; - block_height?: number; - block_hash?: string; - block_time?: number; - }; - value: number; -} - -export interface Transaction { - txid: string; - version: number; - locktime: number; - vin: TxInput[]; - vout: TxOutput[]; - size: number; - weight: number; - fee: number; - status: { - confirmed: boolean; - block_height?: number; - block_hash?: string; - block_time?: number; - }; -} - -export interface TxInput { - txid: string; - vout: number; - prevout: TxOutput | null; - scriptsig: string; - sequence: number; - witness?: string[]; -} - -export interface TxOutput { - scriptpubkey: string; - scriptpubkey_asm: string; - scriptpubkey_type: string; - scriptpubkey_address?: string; - value: number; -} - -export interface FeeEstimates { - fastestFee: number; - halfHourFee: number; - hourFee: number; - economyFee: number; - minimumFee: number; -} - -/** - * Resolve the mempool.space base URL from environment. - * MEMPOOL_API takes precedence; otherwise inferred from BITCOIN_NETWORK. - */ -function resolveBaseUrl(): string { - if (process.env.MEMPOOL_API) { - return process.env.MEMPOOL_API; - } - - const network = process.env.BITCOIN_NETWORK || 'mainnet'; - switch (network) { - case 'testnet': - return 'https://mempool.space/testnet/api'; - case 'signet': - return 'https://mempool.space/signet/api'; - default: - return 'https://mempool.space/api'; - } -} - -export class MempoolClient { - private baseUrl: string; - - constructor(baseUrl?: string) { - this.baseUrl = baseUrl || resolveBaseUrl(); - } - - /** - * Fetch UTXOs for a given Bitcoin address. - */ - async getUtxos(address: string): Promise { - const url = `${this.baseUrl}/address/${address}/utxo`; - console.log(`[MempoolClient] Fetching UTXOs for ${address}`); - - const response = await fetch(url); - if (!response.ok) { - throw new Error(`Failed to fetch UTXOs: ${response.status} ${response.statusText}`); - } - - return (await response.json()) as UTXO[]; - } - - /** - * Fetch a transaction by its txid. - */ - async getTx(txid: string): Promise { - const url = `${this.baseUrl}/tx/${txid}`; - console.log(`[MempoolClient] Fetching tx ${txid}`); - - const response = await fetch(url); - if (!response.ok) { - throw new Error(`Failed to fetch transaction: ${response.status} ${response.statusText}`); - } - - return (await response.json()) as Transaction; - } - - /** - * Fetch raw transaction hex by txid. - */ - async getTxHex(txid: string): Promise { - const url = `${this.baseUrl}/tx/${txid}/hex`; - const response = await fetch(url); - if (!response.ok) { - throw new Error(`Failed to fetch tx hex: ${response.status} ${response.statusText}`); - } - - return await response.text(); - } - - /** - * Broadcast a signed transaction to the network. - * Returns the txid on success. - */ - async broadcastTx(txHex: string): Promise { - const url = `${this.baseUrl}/tx`; - console.log(`[MempoolClient] Broadcasting transaction (${txHex.length / 2} bytes)`); - - const response = await fetch(url, { - method: 'POST', - headers: { 'Content-Type': 'text/plain' }, - body: txHex, - }); - - if (!response.ok) { - const errorText = await response.text(); - throw new Error(`Failed to broadcast transaction: ${response.status} — ${errorText}`); - } - - const txid = await response.text(); - console.log(`[MempoolClient] Transaction broadcast successful: ${txid}`); - return txid; - } - - /** - * Get the current block height. - */ - async getBlockHeight(): Promise { - const url = `${this.baseUrl}/blocks/tip/height`; - const response = await fetch(url); - if (!response.ok) { - throw new Error(`Failed to fetch block height: ${response.status} ${response.statusText}`); - } - - const height = await response.text(); - return parseInt(height, 10); - } - - /** - * Get current fee estimates (in sat/vB). - */ - async getFeeEstimates(): Promise { - const url = `${this.baseUrl}/v1/fees/recommended`; - const response = await fetch(url); - if (!response.ok) { - throw new Error(`Failed to fetch fee estimates: ${response.status} ${response.statusText}`); - } - - return (await response.json()) as FeeEstimates; - } - - /** - * Check if a transaction is confirmed. - */ - async isConfirmed(txid: string): Promise { - try { - const tx = await this.getTx(txid); - return tx.status.confirmed; - } catch { - return false; - } - } - - /** - * Get the address for UTXOs (alias for getUtxos for backward compat). - */ - async getAddressUtxos(address: string): Promise { - return this.getUtxos(address); - } - - /** - * Get transaction details (alias for getTx). - */ - async getTransaction(txid: string): Promise { - return this.getTx(txid); - } -} diff --git a/legacy/taproot-assets-era/backend/src/bitcoin/TaprootUtils.ts b/legacy/taproot-assets-era/backend/src/bitcoin/TaprootUtils.ts deleted file mode 100644 index 9f46e9b..0000000 --- a/legacy/taproot-assets-era/backend/src/bitcoin/TaprootUtils.ts +++ /dev/null @@ -1,196 +0,0 @@ -/** - * Taproot utilities for generating keys and creating multisig addresses. - * - * Uses @noble/secp256k1 for real BIP-340 Schnorr signature operations - * and bitcoinjs-lib for real P2TR address construction. - */ - -import * as secp256k1 from '@noble/secp256k1'; -import { sha256 } from '@noble/hashes/sha2.js'; -import { hmac } from '@noble/hashes/hmac.js'; -import * as bitcoin from 'bitcoinjs-lib'; -import * as ecc from '@bitcoinerlab/secp256k1'; - -// Configure @noble/secp256k1 v3 with hash functions -secp256k1.hashes.sha256 = (msg: Uint8Array) => sha256(msg); -secp256k1.hashes.hmacSha256 = (key: Uint8Array, ...msgs: Uint8Array[]) => - hmac(sha256, key, secp256k1.etc.concatBytes(...msgs)); - -bitcoin.initEccLib(ecc); - -export interface KeyPair { - publicKey: string; - privateKey: string; -} - -export interface MultisigAddress { - address: string; - script: string; - internalPubkey: string; -} - -/** - * Get the Bitcoin network from BITCOIN_NETWORK env var. - */ -function getNetwork(): bitcoin.Network { - const networkName = process.env.BITCOIN_NETWORK || 'mainnet'; - switch (networkName) { - case 'testnet': - return bitcoin.networks.testnet; - case 'regtest': - return bitcoin.networks.regtest; - default: - return bitcoin.networks.bitcoin; - } -} - -export class TaprootUtils { - /** - * Generate a new Schnorr key pair using secp256k1. - */ - static generateKeyPair(): KeyPair { - const privateKeyBytes = secp256k1.utils.randomSecretKey(); - const publicKeyBytes = secp256k1.schnorr.getPublicKey(privateKeyBytes); - - const privateKey = Buffer.from(privateKeyBytes).toString('hex'); - const publicKey = Buffer.from(publicKeyBytes).toString('hex'); - - console.log(`[TaprootUtils] Generated key pair (pubkey: ${publicKey.slice(0, 16)}...)`); - - return { publicKey, privateKey }; - } - - /** - * Create a 2-of-2 Taproot multisig address from two x-only public keys. - * - * Uses real key aggregation (sorted point addition) to produce a combined - * internal pubkey, then constructs a real P2TR address via bitcoinjs-lib. - */ - static createMultisigAddress(pubkey1: string, pubkey2: string): MultisigAddress { - console.log( - `[TaprootUtils] Creating 2-of-2 multisig: ${pubkey1.slice(0, 8)}... + ${pubkey2.slice(0, 8)}...` - ); - - // Aggregate the two x-only public keys via EC point addition - const aggregatedXOnly = this.aggregatePublicKeys([pubkey1, pubkey2]); - const internalPubkey = Buffer.from(aggregatedXOnly, 'hex'); - - // Build a real P2TR (Pay-to-Taproot) output using bitcoinjs-lib - const network = getNetwork(); - const p2tr = bitcoin.payments.p2tr({ - internalPubkey, - network, - }); - - if (!p2tr.address || !p2tr.output) { - throw new Error('Failed to create P2TR payment'); - } - - const address = p2tr.address; - const script = Buffer.from(p2tr.output).toString('hex'); - - console.log(`[TaprootUtils] Created multisig address: ${address.slice(0, 20)}...`); - - return { address, script, internalPubkey: aggregatedXOnly }; - } - - /** - * Aggregate multiple x-only public keys using EC point addition. - * - * Converts x-only (32-byte) pubkeys to compressed (33-byte with 0x02 prefix), - * performs EC point addition, then returns the x-only result. - */ - static aggregatePublicKeys(pubkeys: string[]): string { - if (pubkeys.length === 0) { - throw new Error('Cannot aggregate empty pubkey list'); - } - - if (pubkeys.length === 1) { - return pubkeys[0]; - } - - console.log(`[TaprootUtils] Aggregating ${pubkeys.length} public keys`); - - // Sort pubkeys lexicographically for deterministic aggregation - const sorted = [...pubkeys].sort(); - - // Convert x-only pubkeys to compressed format (prepend 0x02) - // and perform sequential point addition - let accumulated = Buffer.concat([Buffer.from([0x02]), Buffer.from(sorted[0], 'hex')]); - - for (let i = 1; i < sorted.length; i++) { - const nextCompressed = Buffer.concat([Buffer.from([0x02]), Buffer.from(sorted[i], 'hex')]); - const sum = ecc.pointAdd(accumulated, nextCompressed); - if (!sum) { - throw new Error('Point addition failed — keys may be inverses'); - } - accumulated = Buffer.from(sum); - } - - // Extract x-only (drop the prefix byte) from the compressed result - const xOnly = accumulated.subarray(1); - return Buffer.from(xOnly).toString('hex'); - } - - /** - * Verify a BIP-340 Schnorr signature against a public key and message. - * - * SECURITY: Uses real cryptographic verification via @noble/secp256k1. - */ - static verifySchnorrSignature( - publicKey: string, - message: string, - signature: string - ): boolean { - console.log( - `[TaprootUtils] Verifying Schnorr signature from ${publicKey.slice(0, 16)}...` - ); - - try { - const pubkeyBytes = Buffer.from(publicKey, 'hex'); - const sigBytes = Buffer.from(signature, 'hex'); - - if (pubkeyBytes.length !== 32) { - console.error(`[TaprootUtils] Invalid pubkey length: ${pubkeyBytes.length}, expected 32`); - return false; - } - - if (sigBytes.length !== 64) { - console.error(`[TaprootUtils] Invalid signature length: ${sigBytes.length}, expected 64`); - return false; - } - - const messageHash = sha256(new TextEncoder().encode(message)); - return secp256k1.schnorr.verify(sigBytes, messageHash, pubkeyBytes); - } catch (err) { - console.error('[TaprootUtils] Signature verification error:', err); - return false; - } - } - - /** - * Sign a message with BIP-340 Schnorr. - */ - static async signSchnorr(privateKey: string, message: string): Promise { - const privkeyBytes = Buffer.from(privateKey, 'hex'); - const messageHash = sha256(new TextEncoder().encode(message)); - const signature = await secp256k1.schnorr.sign(messageHash, privkeyBytes); - return Buffer.from(signature).toString('hex'); - } - - /** - * Create a timelocked script path for force-close scenarios. - * After N blocks, the hub can unilaterally close the channel. - * - * Script: OP_CHECKSEQUENCEVERIFY OP_DROP OP_CHECKSIG - */ - static createTimelockScript(pubkey: string, lockBlocks: number): string { - console.log( - `[TaprootUtils] Creating timelock script: ${lockBlocks} blocks for ${pubkey.slice(0, 16)}...` - ); - - const lockBlocksHex = lockBlocks.toString(16).padStart(4, '0'); - // OP_CSV (0xb2) OP_DROP (0x75) <32-byte-pubkey> OP_CHECKSIG (0xac) - return `b2${lockBlocksHex}75${pubkey}ac`; - } -} diff --git a/legacy/taproot-assets-era/backend/src/cache/RedisCache.ts b/legacy/taproot-assets-era/backend/src/cache/RedisCache.ts deleted file mode 100644 index 0e240eb..0000000 --- a/legacy/taproot-assets-era/backend/src/cache/RedisCache.ts +++ /dev/null @@ -1,482 +0,0 @@ -import Redis from 'ioredis'; -import { EventEmitter } from 'events'; - -interface CacheConfig { - host: string; - port: number; - password?: string; - db?: number; - maxRetriesPerRequest?: number; - enableReadyCheck?: boolean; - retryStrategy?: (times: number) => number | null; -} - - - -/** - * RedisCache - High-performance caching layer for RuneBolt - * - * Caches: - * - User balances (channel states) - * - Hot transfers (recent high-volume channels) - * - Rate limit counters - * - Session data - */ -export class RedisCache extends EventEmitter { - private client: Redis; - private isConnected: boolean = false; - private defaultTTL: number = 300; // 5 minutes default - - // Cache key prefixes - private static readonly PREFIXES = { - CHANNEL_BALANCE: 'ch:bal:', - CHANNEL_STATE: 'ch:state:', - USER_CHANNELS: 'usr:ch:', - TRANSFER_BATCH: 'xfer:batch:', - RATE_LIMIT: 'ratelimit:', - HOT_CHANNEL: 'hot:ch:', - LOCK: 'lock:', - } as const; - - constructor(config?: Partial) { - super(); - - const redisConfig: CacheConfig = { - host: process.env.REDIS_HOST || 'localhost', - port: parseInt(process.env.REDIS_PORT || '6379', 10), - password: process.env.REDIS_PASSWORD, - db: parseInt(process.env.REDIS_DB || '0', 10), - maxRetriesPerRequest: 3, - enableReadyCheck: true, - retryStrategy: (times: number) => { - const delay = Math.min(times * 50, 2000); - return delay; - }, - ...config, - }; - - try { - this.client = new Redis({ - ...redisConfig, - lazyConnect: true, - maxRetriesPerRequest: 1, - retryStrategy: (times: number) => { - if (times > 3) { - console.log('[RedisCache] Max retries reached, running without cache'); - return null; // Stop retrying - } - return Math.min(times * 200, 2000); - }, - }); - this.setupEventHandlers(); - // Try to connect but don't block startup - this.client.connect().catch(() => { - console.log('[RedisCache] Redis not available — running in no-cache mode'); - this.isConnected = false; - }); - } catch { - console.log('[RedisCache] Redis initialization failed — running in no-cache mode'); - this.client = null as any; - this.isConnected = false; - } - } - - private setupEventHandlers(): void { - if (!this.client) return; - - this.client.on('connect', () => { - this.isConnected = true; - console.log('[RedisCache] Connected to Redis'); - this.emit('connect'); - }); - - this.client.on('error', (err) => { - this.isConnected = false; - // Don't spam logs - just note once - if (err.message.includes('ECONNREFUSED')) { - // Expected when Redis is not installed - } else { - console.error('[RedisCache] Redis error:', err.message); - } - }); - - this.client.on('close', () => { - this.isConnected = false; - }); - } - - /** - * Get the underlying Redis client for advanced operations - */ - getClient(): Redis { - return this.client; - } - - /** - * Check if Redis is connected - */ - connected(): boolean { - return this.isConnected; - } - - /** - * Generic get method with JSON parsing - */ - async get(key: string): Promise { - if (!this.isConnected || !this.client) return null; - try { - const value = await this.client.get(key); - if (!value) return null; - return JSON.parse(value) as T; - } catch (err) { - return null; - } - } - - /** - * Generic set method with JSON serialization - */ - async set(key: string, value: T, ttlSeconds?: number): Promise { - if (!this.isConnected || !this.client) return; - try { - const serialized = JSON.stringify(value); - const ttl = ttlSeconds ?? this.defaultTTL; - await this.client.setex(key, ttl, serialized); - } catch (err) { - console.error('[RedisCache] Set error:', err); - } - } - - /** - * Delete a key - */ - async del(key: string): Promise { - if (!this.isConnected || !this.client) return; - try { - await this.client.del(key); - } catch (err) { - // silent - } - } - - /** - * Delete keys by pattern - */ - async delPattern(pattern: string): Promise { - if (!this.isConnected || !this.client) return; - try { - const keys = await this.client.keys(pattern); - if (keys.length > 0) { - await this.client.del(...keys); - } - } catch (err) { - // silent - } - } - - /** - * Get channel balance from cache - */ - async getChannelBalance(channelId: string): Promise<{ local: bigint; remote: bigint; capacity: bigint } | null> { - const cached = await this.get<{ local: string; remote: string; capacity: string }>( - RedisCache.PREFIXES.CHANNEL_BALANCE + channelId - ); - if (!cached) return null; - return { - local: BigInt(cached.local), - remote: BigInt(cached.remote), - capacity: BigInt(cached.capacity), - }; - } - - /** - * Set channel balance in cache - */ - async setChannelBalance( - channelId: string, - balance: { local: bigint; remote: bigint; capacity: bigint }, - ttlSeconds: number = 60 - ): Promise { - await this.set( - RedisCache.PREFIXES.CHANNEL_BALANCE + channelId, - { - local: balance.local.toString(), - remote: balance.remote.toString(), - capacity: balance.capacity.toString(), - }, - ttlSeconds - ); - } - - /** - * Invalidate channel balance cache - */ - async invalidateChannelBalance(channelId: string): Promise { - await this.del(RedisCache.PREFIXES.CHANNEL_BALANCE + channelId); - } - - /** - * Get channel state from cache - */ - async getChannelState(channelId: string): Promise { - return this.get(RedisCache.PREFIXES.CHANNEL_STATE + channelId); - } - - /** - * Set channel state in cache - */ - async setChannelState(channelId: string, state: string, ttlSeconds: number = 300): Promise { - await this.set(RedisCache.PREFIXES.CHANNEL_STATE + channelId, state, ttlSeconds); - } - - /** - * Get user channels from cache - */ - async getUserChannels(pubkey: string): Promise { - return this.get(RedisCache.PREFIXES.USER_CHANNELS + pubkey); - } - - /** - * Set user channels in cache - */ - async setUserChannels(pubkey: string, channelIds: string[], ttlSeconds: number = 300): Promise { - await this.set(RedisCache.PREFIXES.USER_CHANNELS + pubkey, channelIds, ttlSeconds); - } - - /** - * Invalidate user channels cache - */ - async invalidateUserChannels(pubkey: string): Promise { - await this.del(RedisCache.PREFIXES.USER_CHANNELS + pubkey); - } - - /** - * Increment rate limit counter - */ - async incrementRateLimit(key: string, windowSeconds: number): Promise { - if (!this.isConnected || !this.client) return 0; - try { - const multi = this.client.multi(); - const fullKey = RedisCache.PREFIXES.RATE_LIMIT + key; - multi.incr(fullKey); - multi.expire(fullKey, windowSeconds); - const results = await multi.exec(); - return (results?.[0]?.[1] as number) || 0; - } catch (err) { - console.error('[RedisCache] Rate limit increment error:', err); - return 0; - } - } - - /** - * Get current rate limit count - */ - async getRateLimitCount(key: string): Promise { - if (!this.isConnected || !this.client) return 0; - try { - const count = await this.client.get(RedisCache.PREFIXES.RATE_LIMIT + key); - return parseInt(count || '0', 10); - } catch (err) { - console.error('[RedisCache] Rate limit get error:', err); - return 0; - } - } - - /** - * Mark a channel as "hot" (high transfer volume) - */ - async markHotChannel(channelId: string, score: number = 1): Promise { - if (!this.isConnected || !this.client) return; - try { - await this.client.zincrby(RedisCache.PREFIXES.HOT_CHANNEL, score, channelId); - // Expire the sorted set entries after 1 hour - await this.client.expire(RedisCache.PREFIXES.HOT_CHANNEL, 3600); - } catch (err) { - console.error('[RedisCache] Mark hot channel error:', err); - } - } - - /** - * Get hot channels (top N by activity) - */ - async getHotChannels(limit: number = 100): Promise { - if (!this.isConnected || !this.client) return []; - try { - return await this.client.zrevrange(RedisCache.PREFIXES.HOT_CHANNEL, 0, limit - 1); - } catch (err) { - console.error('[RedisCache] Get hot channels error:', err); - return []; - } - } - - /** - * Acquire distributed lock - */ - async acquireLock(lockKey: string, ttlSeconds: number = 10): Promise { - if (!this.isConnected || !this.client) return null; - try { - const token = `${Date.now()}-${Math.random()}`; - const fullKey = RedisCache.PREFIXES.LOCK + lockKey; - const result = await this.client.set(fullKey, token, 'EX', ttlSeconds, 'NX'); - return result === 'OK' ? token : null; - } catch (err) { - console.error('[RedisCache] Acquire lock error:', err); - return null; - } - } - - /** - * Release distributed lock - */ - async releaseLock(lockKey: string, token: string): Promise { - if (!this.isConnected || !this.client) return false; - try { - const fullKey = RedisCache.PREFIXES.LOCK + lockKey; - const currentToken = await this.client.get(fullKey); - if (currentToken === token) { - await this.client.del(fullKey); - return true; - } - return false; - } catch (err) { - console.error('[RedisCache] Release lock error:', err); - return false; - } - } - - /** - * Execute operation with distributed lock - */ - async withLock(lockKey: string, operation: () => Promise, ttlSeconds: number = 10): Promise { - const token = await this.acquireLock(lockKey, ttlSeconds); - if (!token) return null; - - try { - const result = await operation(); - return result; - } finally { - await this.releaseLock(lockKey, token); - } - } - - /** - * Add transfer to batch for processing - */ - async addToBatch(batchId: string, transferData: unknown): Promise { - if (!this.isConnected || !this.client) return 0; - try { - const key = RedisCache.PREFIXES.TRANSFER_BATCH + batchId; - const result = await this.client.lpush(key, JSON.stringify(transferData)); - return result; - } catch (err) { - console.error('[RedisCache] Add to batch error:', err); - return 0; - } - } - - /** - * Get and clear batch - */ - async getAndClearBatch(batchId: string): Promise { - if (!this.isConnected || !this.client) return []; - try { - const key = RedisCache.PREFIXES.TRANSFER_BATCH + batchId; - const multi = this.client.multi(); - multi.lrange(key, 0, -1); - multi.del(key); - const results = await multi.exec(); - - if (!results || !results[0]) return []; - const items = results[0][1] as string[]; - return items.map(item => JSON.parse(item)); - } catch (err) { - console.error('[RedisCache] Get batch error:', err); - return []; - } - } - - /** - * Publish message to Redis pub/sub (for WebSocket scaling) - */ - async publish(channel: string, message: unknown): Promise { - if (!this.isConnected || !this.client) return; - try { - await this.client.publish(channel, JSON.stringify(message)); - } catch (err) { - console.error('[RedisCache] Publish error:', err); - } - } - - /** - * Subscribe to Redis pub/sub channel - */ - subscribe(channel: string, callback: (message: unknown) => void): void { - if (!this.isConnected || !this.client) return; - const subscriber = this.client.duplicate(); - subscriber.subscribe(channel); - subscriber.on('message', (_chan: string, message: string) => { - try { - callback(JSON.parse(message)); - } catch (err) { - console.error('[RedisCache] Message parse error:', err); - } - }); - } - - /** - * Get cache statistics - */ - async getStats(): Promise<{ connected: boolean; keys: number; hitRate?: number }> { - try { - const keyspace = await this.client.info('keyspace'); - - // Parse key count from keyspace info - const keyMatch = keyspace.match(/keys=(\d+)/); - const keys = keyMatch ? parseInt(keyMatch[1], 10) : 0; - - return { - connected: this.isConnected, - keys, - }; - } catch (err) { - return { connected: false, keys: 0 }; - } - } - - /** - * Ping Redis to check connectivity - */ - async ping(): Promise { - try { - const result = await this.client.ping(); - return result === 'PONG'; - } catch { - return false; - } - } - - /** - * Close Redis connection - */ - async close(): Promise { - if (!this.client) return; - await this.client.quit(); - this.isConnected = false; - } -} - -// Singleton instance -let cacheInstance: RedisCache | null = null; - -export function getCache(): RedisCache { - if (!cacheInstance) { - cacheInstance = new RedisCache(); - } - return cacheInstance; -} - -export function resetCache(): void { - cacheInstance = null; -} - -export default RedisCache; diff --git a/legacy/taproot-assets-era/backend/src/channels/ChannelManager.ts b/legacy/taproot-assets-era/backend/src/channels/ChannelManager.ts deleted file mode 100644 index c82ea45..0000000 --- a/legacy/taproot-assets-era/backend/src/channels/ChannelManager.ts +++ /dev/null @@ -1,193 +0,0 @@ -/** - * Main orchestrator for channel lifecycle operations. - * Coordinates between Database, BitcoinClient, and CommitmentManager. - */ - -import { v4 as uuidv4 } from 'uuid'; -import Database from '../db/Database'; -import { BitcoinClient } from '../bitcoin/BitcoinClient'; -import { TaprootUtils } from '../bitcoin/TaprootUtils'; -import { - Channel, - ChannelState, - assertTransition, - channelFromRow, -} from './ChannelState'; -import { CommitmentManager } from './CommitmentManager'; -import { DOG_RUNE_ID } from '../rune/RuneConstants'; - -export class ChannelManager { - private db: Database; - private bitcoin: BitcoinClient; - - constructor() { - this.db = Database.getInstance(); - this.bitcoin = new BitcoinClient(); - } - - /** - * Open a new payment channel. - * - * @param runeId - The rune ID for the asset being locked in the channel. - * Defaults to DOG•GO•TO•THE•MOON. - */ - async openChannel( - userPubkey: string, - amount: bigint, - runeId: string = DOG_RUNE_ID - ): Promise<{ channelId: string; psbt: string; channelAddress: string }> { - console.log( - `[ChannelManager] Opening channel: user=${userPubkey.slice(0, 16)}..., amount=${amount}, rune=${runeId}` - ); - - if (amount <= 0n) { - throw new Error('Channel amount must be positive'); - } - - const hubKey = TaprootUtils.generateKeyPair(); - const multisig = TaprootUtils.createMultisigAddress(userPubkey, hubKey.publicKey); - const { psbt } = this.bitcoin.createFundingPsbt(userPubkey, amount, [], runeId); - const channelId = uuidv4(); - - await this.db.createUser(userPubkey); - - await this.db.createChannel({ - id: channelId, - user_pubkey: userPubkey, - runebolt_pubkey: hubKey.publicKey, - funding_txid: null, - funding_vout: null, - capacity: Number(amount), - local_balance: Number(amount), - remote_balance: 0, - state: ChannelState.PENDING_OPEN, - }); - - await CommitmentManager.createCommitment(channelId, amount, 0n, 0); - - console.log(`[ChannelManager] Channel ${channelId} created in PENDING_OPEN state`); - - return { - channelId, - psbt, - channelAddress: multisig.address, - }; - } - - /** - * Activate a channel after the user signs the funding PSBT. - */ - async activateChannel(channelId: string, signedPsbt: string): Promise { - const row = await this.db.getChannel(channelId); - if (!row) { - throw new Error(`Channel ${channelId} not found`); - } - - const channel = channelFromRow(row); - assertTransition(channel.state, ChannelState.OPEN); - - const txid = await this.bitcoin.signAndBroadcastFundingTx(signedPsbt, 'hub_signature'); - - // Verify the funding tx was accepted into the mempool - const tx = await this.bitcoin.getTransaction(txid); - if (!tx) { - throw new Error(`Funding transaction ${txid} not found in mempool after broadcast`); - } - - await this.db.updateChannel({ - id: channelId, - funding_txid: txid, - funding_vout: 0, - capacity: Number(channel.capacity), - local_balance: Number(channel.localBalance), - remote_balance: Number(channel.remoteBalance), - state: ChannelState.OPEN, - }); - - console.log(`[ChannelManager] Channel ${channelId} activated, funding txid: ${txid}`); - - const updatedRow = await this.db.getChannel(channelId); - if (!updatedRow) { - throw new Error(`Channel ${channelId} disappeared after activation`); - } - - return channelFromRow(updatedRow); - } - - /** - * Initiate a cooperative channel close. - */ - async closeChannel(channelId: string): Promise<{ psbt: string }> { - const row = await this.db.getChannel(channelId); - if (!row) { - throw new Error(`Channel ${channelId} not found`); - } - - const channel = channelFromRow(row); - assertTransition(channel.state, ChannelState.CLOSING); - - const psbt = this.bitcoin.createClosingPsbt( - channel, - channel.localBalance, - channel.remoteBalance - ); - - await this.db.updateChannelState(channelId, ChannelState.CLOSING); - CommitmentManager.clearCommitments(channelId); - - console.log(`[ChannelManager] Channel ${channelId} closing initiated`); - - return { psbt }; - } - - /** - * Force close a channel unilaterally. - */ - async forceCloseChannel(channelId: string): Promise { - const row = await this.db.getChannel(channelId); - if (!row) { - throw new Error(`Channel ${channelId} not found`); - } - - const channel = channelFromRow(row); - assertTransition(channel.state, ChannelState.FORCE_CLOSING); - - const commitment = await CommitmentManager.getLatestCommitment(channelId); - if (!commitment) { - throw new Error(`No commitment found for channel ${channelId}`); - } - - const closingPsbt = this.bitcoin.createClosingPsbt( - channel, - commitment.localBalance, - commitment.remoteBalance - ); - - const txid = await this.bitcoin.signAndBroadcastFundingTx(closingPsbt, 'force_close_sig'); - - await this.db.updateChannelState(channelId, ChannelState.FORCE_CLOSING); - CommitmentManager.clearCommitments(channelId); - - console.log(`[ChannelManager] Channel ${channelId} force-closed, txid: ${txid}`); - return txid; - } - - /** - * Get a channel by ID. - */ - async getChannel(channelId: string): Promise { - const row = await this.db.getChannel(channelId); - if (!row) { - throw new Error(`Channel ${channelId} not found`); - } - return channelFromRow(row); - } - - /** - * Get all channels for a given pubkey. - */ - async getChannelsByPubkey(pubkey: string): Promise { - const rows = await this.db.getChannelsByPubkey(pubkey); - return rows.map(channelFromRow); - } -} diff --git a/legacy/taproot-assets-era/backend/src/channels/ChannelReserves.ts b/legacy/taproot-assets-era/backend/src/channels/ChannelReserves.ts deleted file mode 100644 index e497e31..0000000 --- a/legacy/taproot-assets-era/backend/src/channels/ChannelReserves.ts +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Channel reserve calculations and validation. - * - * Reserves ensure that each channel always retains a minimum balance, - * preventing dust channels and providing a security margin for - * dispute resolution. - * - * RESERVE POLICY: 1% of channel capacity is unspendable. - */ - -/** Reserve percentage as basis points (100 = 1%) */ -const RESERVE_BASIS_POINTS = 100n; -const BASIS_POINTS_DENOMINATOR = 10_000n; - -/** - * Calculate the reserve amount for a given channel capacity. - * Reserve = 1% of capacity (rounded up to prevent zero reserves). - */ -export function calculateReserve(capacity: bigint): bigint { - const reserve = (capacity * RESERVE_BASIS_POINTS + BASIS_POINTS_DENOMINATOR - 1n) / BASIS_POINTS_DENOMINATOR; - // Minimum reserve of 1 unit to prevent zero-reserve edge case - return reserve < 1n ? 1n : reserve; -} - -/** - * Validate that a transfer does not violate the channel reserve. - * Returns true if the transfer is allowed, false otherwise. - */ -export function validateTransferAgainstReserve( - localBalance: bigint, - capacity: bigint, - transferAmount: bigint -): boolean { - const reserve = calculateReserve(capacity); - return (localBalance - transferAmount) >= reserve; -} - -/** - * Get the spendable balance for a channel (capacity minus reserve). - * This is the maximum amount a user can transfer out. - */ -export function getSpendableBalance(localBalance: bigint, capacity: bigint): bigint { - const reserve = calculateReserve(capacity); - if (localBalance <= reserve) return 0n; - return localBalance - reserve; -} diff --git a/legacy/taproot-assets-era/backend/src/channels/ChannelState.ts b/legacy/taproot-assets-era/backend/src/channels/ChannelState.ts deleted file mode 100644 index e26f9f6..0000000 --- a/legacy/taproot-assets-era/backend/src/channels/ChannelState.ts +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Channel state machine and type definitions. - */ - -export enum ChannelState { - PENDING_OPEN = 'PENDING_OPEN', - OPEN = 'OPEN', - CLOSING = 'CLOSING', - CLOSED = 'CLOSED', - FORCE_CLOSING = 'FORCE_CLOSING', -} - -/** - * Valid state transitions for the channel lifecycle. - * - * PENDING_OPEN -> OPEN (funding tx confirmed) - * PENDING_OPEN -> CLOSED (funding failed or cancelled) - * OPEN -> CLOSING (cooperative close initiated) - * OPEN -> FORCE_CLOSING (unilateral close) - * CLOSING -> CLOSED (closing tx confirmed) - * FORCE_CLOSING -> CLOSED (timelock expired and sweep confirmed) - */ -const VALID_TRANSITIONS: Record = { - [ChannelState.PENDING_OPEN]: [ChannelState.OPEN, ChannelState.CLOSED], - [ChannelState.OPEN]: [ChannelState.CLOSING, ChannelState.FORCE_CLOSING], - [ChannelState.CLOSING]: [ChannelState.CLOSED], - [ChannelState.CLOSED]: [], - [ChannelState.FORCE_CLOSING]: [ChannelState.CLOSED], -}; - -/** - * Check whether a state transition is valid. - */ -export function canTransition(from: ChannelState, to: ChannelState): boolean { - return VALID_TRANSITIONS[from]?.includes(to) ?? false; -} - -/** - * Validate and perform a state transition, throwing if invalid. - */ -export function assertTransition(from: ChannelState, to: ChannelState): void { - if (!canTransition(from, to)) { - throw new Error( - `Invalid channel state transition: ${from} -> ${to}. ` + - `Allowed transitions from ${from}: [${VALID_TRANSITIONS[from].join(', ')}]` - ); - } -} - -/** - * Channel data structure. - */ -export interface Channel { - id: string; - userPubkey: string; - runeboltPubkey: string; - fundingTxid: string | null; - fundingVout: number | null; - capacity: bigint; - localBalance: bigint; - remoteBalance: bigint; - state: ChannelState; - createdAt: string; - updatedAt: string; -} - -/** - * Convert a database row to a Channel object. - */ -export function channelFromRow(row: { - id: string; - user_pubkey: string; - runebolt_pubkey: string; - funding_txid: string | null; - funding_vout: number | null; - capacity: number; - local_balance: number; - remote_balance: number; - state: string; - created_at: string; - updated_at: string; -}): Channel { - return { - id: row.id, - userPubkey: row.user_pubkey, - runeboltPubkey: row.runebolt_pubkey, - fundingTxid: row.funding_txid, - fundingVout: row.funding_vout, - capacity: BigInt(row.capacity), - localBalance: BigInt(row.local_balance), - remoteBalance: BigInt(row.remote_balance), - state: row.state as ChannelState, - createdAt: row.created_at, - updatedAt: row.updated_at, - }; -} - -/** - * Serialize a Channel for JSON responses (bigints -> strings). - */ -export function channelToJson(channel: Channel): Record { - return { - id: channel.id, - userPubkey: channel.userPubkey, - runeboltPubkey: channel.runeboltPubkey, - fundingTxid: channel.fundingTxid, - fundingVout: channel.fundingVout, - capacity: channel.capacity.toString(), - localBalance: channel.localBalance.toString(), - remoteBalance: channel.remoteBalance.toString(), - state: channel.state, - createdAt: channel.createdAt, - updatedAt: channel.updatedAt, - }; -} diff --git a/legacy/taproot-assets-era/backend/src/channels/CommitmentManager.ts b/legacy/taproot-assets-era/backend/src/channels/CommitmentManager.ts deleted file mode 100644 index 0bb56fe..0000000 --- a/legacy/taproot-assets-era/backend/src/channels/CommitmentManager.ts +++ /dev/null @@ -1,290 +0,0 @@ -/** - * Manages off-chain commitment states for payment channels. - * - * Each commitment represents an agreed-upon balance distribution - * that could be broadcast on-chain if needed. - * - * SECURITY: All commitments are persisted to the database. - * Revocation secrets enforce old-state punishment. - */ - -import crypto from 'crypto'; -import { sha256 } from '@noble/hashes/sha2.js'; -import * as secp256k1 from '@noble/secp256k1'; -import Database from '../db/Database'; -import { PenaltyManager } from './PenaltyManager'; - -export interface CommitmentState { - id: string; - channelId: string; - sequence: number; - localBalance: bigint; - remoteBalance: bigint; - localSignature: string | null; - remoteSignature: string | null; - hash: string; - revocationHash: string | null; - isRevoked: boolean; - createdAt: string; -} - -export class CommitmentManager { - private static db = Database.getInstance(); - - /** - * Create a new commitment state for a channel. - * Each commitment has a monotonically increasing sequence number. - * - * SECURITY: Persisted to database immediately. - * Accepts an optional revocation secret whose hash is stored for future enforcement. - */ - static async createCommitment( - channelId: string, - localBalance: bigint, - remoteBalance: bigint, - sequence: number, - revocationSecret?: string - ): Promise { - console.log( - `[CommitmentManager] Creating commitment #${sequence} for channel ${channelId}: ` + - `local=${localBalance}, remote=${remoteBalance}` - ); - - // Validate that balances are non-negative - if (localBalance < 0n || remoteBalance < 0n) { - throw new Error('Commitment balances cannot be negative'); - } - - // Compute commitment hash - const preimage = `${channelId}:${sequence}:${localBalance}:${remoteBalance}:${Date.now()}`; - const hash = crypto.createHash('sha256').update(preimage).digest('hex'); - - // Compute revocation hash if secret provided - const revocationHash = revocationSecret - ? Buffer.from(sha256(Buffer.from(revocationSecret, 'hex'))).toString('hex') - : null; - - const commitment: CommitmentState = { - id: crypto.randomUUID(), - channelId, - sequence, - localBalance, - remoteBalance, - localSignature: null, - remoteSignature: null, - hash, - revocationHash, - isRevoked: false, - createdAt: new Date().toISOString(), - }; - - // PERSIST to database - await this.db.createCommitment({ - channel_id: channelId, - sequence, - local_balance: Number(localBalance), - remote_balance: Number(remoteBalance), - }); - - console.log(`[CommitmentManager] Persisted commitment ${commitment.id} to database`); - return commitment; - } - - /** - * Verify a commitment signature using BIP-340 Schnorr verification. - * - * SECURITY: Uses real cryptographic verification. - * Requires the signer's public key and the commitment hash as the signed message. - */ - static verifyCommitment( - commitment: CommitmentState, - signature: string, - signerPubkey: string - ): boolean { - console.log( - `[CommitmentManager] Verifying commitment #${commitment.sequence} ` + - `for channel ${commitment.channelId}` - ); - - if (!signature || signature.length === 0) { - console.log('[CommitmentManager] Empty signature, verification failed'); - return false; - } - - try { - const sigBytes = Buffer.from(signature, 'hex'); - const pubkeyBytes = Buffer.from(signerPubkey, 'hex'); - - if (sigBytes.length !== 64) { - console.log(`[CommitmentManager] Invalid signature length: ${sigBytes.length}`); - return false; - } - - if (pubkeyBytes.length !== 32) { - console.log(`[CommitmentManager] Invalid pubkey length: ${pubkeyBytes.length}`); - return false; - } - - // Verify signature against commitment hash - const messageHash = sha256(new TextEncoder().encode(commitment.hash)); - const isValid = secp256k1.schnorr.verify(sigBytes, messageHash, pubkeyBytes); - - if (!isValid) { - console.log('[CommitmentManager] Schnorr signature verification failed'); - } - return isValid; - } catch (err) { - console.error('[CommitmentManager] Signature verification error:', err); - return false; - } - } - - /** - * Revoke an old commitment by revealing its revocation secret. - * - * SECURITY: Once revoked, broadcasting this old state is punishable. - * The counterparty can use the revocation secret to claim all funds. - */ - static async revokeCommitment( - channelId: string, - sequence: number, - revocationSecret: string - ): Promise { - const commitments = await this.db.getCommitmentsByChannel(channelId, 1000); - const target = commitments.find(c => c.sequence === sequence); - - if (!target) { - throw new Error(`Commitment #${sequence} not found for channel ${channelId}`); - } - - // Verify the secret matches the stored hash - const computedHash = Buffer.from(sha256(Buffer.from(revocationSecret, 'hex'))).toString('hex'); - - // We store revocation_hash in the DB if the schema supports it; - // for now, validate against the commitment data - console.log(`[CommitmentManager] Revoking commitment #${sequence} for channel ${channelId}`); - - // Mark as revoked in the database - await this.db.query( - `UPDATE commitments SET signature = 'REVOKED:' || $1 WHERE channel_id = $2 AND sequence = $3`, - [computedHash, channelId, sequence] - ); - - console.log(`[CommitmentManager] Commitment #${sequence} revoked successfully`); - } - - /** - * Check if a commitment has been revoked. - */ - static async isCommitmentRevoked(channelId: string, sequence: number): Promise { - const row = await this.db.queryOne<{ signature: string | null }>( - 'SELECT signature FROM commitments WHERE channel_id = $1 AND sequence = $2', - [channelId, sequence] - ); - return row?.signature?.startsWith('REVOKED:') ?? false; - } - - /** - * Get the latest commitment state for a channel from the database. - * - * SECURITY: Always fetches from persistent storage. - */ - static async getLatestCommitment(channelId: string): Promise { - const row = await this.db.getLatestCommitment(channelId); - if (!row) { - return null; - } - return this.rowToCommitment(row); - } - - /** - * Clear all commitments for a channel (used when channel closes). - * - * Note: We don't actually delete for audit purposes, just mark as closed. - */ - static clearCommitments(channelId: string): void { - console.log(`[CommitmentManager] Clearing commitments for channel ${channelId}`); - // Commitments are kept in database for audit/dispute resolution - } - - /** - * Create a new commitment with automatic revocation of the previous one. - * Generates a revocation secret for the NEW commitment and stores the - * revocation secret for the PREVIOUS commitment (revoking it). - */ - static async createCommitmentWithRevocation( - channelId: string, - localBalance: bigint, - remoteBalance: bigint, - sequence: number, - previousRevocationSecret?: string - ): Promise<{ commitment: CommitmentState; revocationHash: string }> { - // Generate revocation secret for this new commitment - const { secret, hash } = PenaltyManager.generateRevocationSecret(); - - // Store revocation secret for the previous commitment (revoking it) - if (previousRevocationSecret && sequence > 0) { - await this.db.storeRevocationSecret( - channelId, - sequence - 1, - previousRevocationSecret - ); - console.log( - `[CommitmentManager] Stored revocation secret for previous commitment #${sequence - 1}` - ); - } - - // Create the new commitment with the revocation secret - const commitment = await this.createCommitment( - channelId, - localBalance, - remoteBalance, - sequence, - secret - ); - - return { commitment, revocationHash: hash }; - } - - /** - * Get all stored revocation secrets for a channel. - * Used by the PenaltyManager to detect and punish breaches. - */ - static async getRevocationSecrets( - channelId: string - ): Promise> { - const rows = await this.db.getRevocationSecrets(channelId); - return rows.map((r) => ({ sequence: r.sequence, secret: r.secret })); - } - - /** - * Convert a database row to a CommitmentState. - */ - private static rowToCommitment(row: { - id: string; - channel_id: string; - sequence: number; - local_balance: number; - remote_balance: number; - commitment_tx: string | null; - signature: string | null; - created_at: string; - }): CommitmentState { - const isRevoked = row.signature?.startsWith('REVOKED:') ?? false; - return { - id: row.id, - channelId: row.channel_id, - sequence: row.sequence, - localBalance: BigInt(row.local_balance), - remoteBalance: BigInt(row.remote_balance), - localSignature: null, - remoteSignature: isRevoked ? null : row.signature, - hash: '', - revocationHash: null, - isRevoked, - createdAt: row.created_at, - }; - } -} - -export default CommitmentManager; diff --git a/legacy/taproot-assets-era/backend/src/channels/DisputeManager.ts b/legacy/taproot-assets-era/backend/src/channels/DisputeManager.ts deleted file mode 100644 index a509417..0000000 --- a/legacy/taproot-assets-era/backend/src/channels/DisputeManager.ts +++ /dev/null @@ -1,225 +0,0 @@ -/** - * DisputeManager — Handles dispute resolution for unilateral channel closes. - * - * When a party force-closes a channel, a challenge period (144 blocks / ~24 hours) - * begins. During this window the counterparty can submit a newer state or - * prove a breach. After the challenge period expires, the close is finalized. - */ - -import Database from '../db/Database'; -import { MempoolClient } from '../bitcoin/MempoolClient'; -import { CommitmentManager } from './CommitmentManager'; -import { ChannelState } from './ChannelState'; - -/** 144 blocks ≈ 24 hours on Bitcoin mainnet */ -const CHALLENGE_PERIOD_BLOCKS = 144; - -export type DisputeStatus = 'open' | 'challenged' | 'resolved' | 'penalized'; - -export interface Dispute { - id: string; - channelId: string; - initiatedBy: string; - status: DisputeStatus; - latestSequence: number; - challengeDeadline: string; - broadcastTxid: string | null; - createdAt: string; - updatedAt: string; -} - -export class DisputeManager { - private db: Database; - private mempool: MempoolClient; - - constructor(mempoolClient?: MempoolClient) { - this.db = Database.getInstance(); - this.mempool = mempoolClient || new MempoolClient(); - } - - /** - * Initiate a dispute when a unilateral close is detected or requested. - * Calculates the challenge deadline based on the current block height. - */ - async handleDisputeOpen( - channelId: string, - initiatedBy: string, - broadcastTxid?: string - ): Promise { - console.log( - `[DisputeManager] Opening dispute for channel ${channelId} by ${initiatedBy.slice(0, 16)}...` - ); - - // Get latest commitment to record the sequence - const latestCommitment = await CommitmentManager.getLatestCommitment(channelId); - if (!latestCommitment) { - throw new Error(`No commitments found for channel ${channelId}`); - } - - // Calculate challenge deadline - const currentHeight = await this.mempool.getBlockHeight(); - const deadlineHeight = currentHeight + CHALLENGE_PERIOD_BLOCKS; - // Approximate: 10 minutes per block - const deadlineTime = new Date( - Date.now() + CHALLENGE_PERIOD_BLOCKS * 10 * 60 * 1000 - ); - - const row = await this.db.createDispute({ - channel_id: channelId, - initiated_by: initiatedBy, - latest_sequence: latestCommitment.sequence, - challenge_deadline: deadlineTime.toISOString(), - broadcast_txid: broadcastTxid || null, - }); - - // Update channel state to force-closing - await this.db.updateChannelState(channelId, ChannelState.FORCE_CLOSING); - - console.log( - `[DisputeManager] Dispute opened for channel ${channelId}. ` + - `Challenge deadline: block ${deadlineHeight} (~${deadlineTime.toISOString()})` - ); - - return this.rowToDispute(row); - } - - /** - * Submit the latest state during a dispute's challenge period. - * If our latest commitment has a higher sequence than the disputed one, - * we can override the close with a more recent state. - */ - async submitLatestState( - channelId: string, - submitterPubkey: string - ): Promise<{ updated: boolean; sequence: number }> { - console.log( - `[DisputeManager] Submitting latest state for dispute on channel ${channelId}` - ); - - const dispute = await this.db.getDispute(channelId); - if (!dispute) { - throw new Error(`No active dispute for channel ${channelId}`); - } - - if (dispute.status !== 'open') { - throw new Error( - `Dispute for channel ${channelId} is already ${dispute.status}` - ); - } - - // Check if challenge period has expired - if (new Date(dispute.challenge_deadline) < new Date()) { - throw new Error( - `Challenge period for channel ${channelId} has expired` - ); - } - - const latestCommitment = await CommitmentManager.getLatestCommitment(channelId); - if (!latestCommitment) { - throw new Error(`No commitments found for channel ${channelId}`); - } - - if (latestCommitment.sequence <= dispute.latest_sequence) { - console.log( - `[DisputeManager] No newer state available (latest: ${latestCommitment.sequence}, ` + - `disputed: ${dispute.latest_sequence})` - ); - return { updated: false, sequence: latestCommitment.sequence }; - } - - // We have a newer state — update the dispute - await this.db.query( - `UPDATE disputes - SET latest_sequence = $1, status = 'challenged', updated_at = NOW() - WHERE channel_id = $2`, - [latestCommitment.sequence, channelId] - ); - - console.log( - `[DisputeManager] Dispute challenged with newer state #${latestCommitment.sequence} ` + - `by ${submitterPubkey.slice(0, 16)}...` - ); - - return { updated: true, sequence: latestCommitment.sequence }; - } - - /** - * Resolve a dispute after the challenge period has expired. - * Finalizes the channel close with the latest submitted state. - */ - async resolveDispute(channelId: string): Promise { - console.log(`[DisputeManager] Resolving dispute for channel ${channelId}`); - - const dispute = await this.db.getDispute(channelId); - if (!dispute) { - throw new Error(`No active dispute for channel ${channelId}`); - } - - if (dispute.status === 'resolved' || dispute.status === 'penalized') { - throw new Error( - `Dispute for channel ${channelId} is already ${dispute.status}` - ); - } - - // Verify challenge period has expired - if (new Date(dispute.challenge_deadline) > new Date()) { - const remaining = new Date(dispute.challenge_deadline).getTime() - Date.now(); - const blocksRemaining = Math.ceil(remaining / (10 * 60 * 1000)); - throw new Error( - `Challenge period has not expired. ~${blocksRemaining} blocks remaining` - ); - } - - // Finalize: mark dispute as resolved and close the channel - const resolvedRow = await this.db.resolveDispute(channelId); - await this.db.updateChannelState(channelId, ChannelState.CLOSED); - - console.log( - `[DisputeManager] Dispute resolved for channel ${channelId} at sequence #${dispute.latest_sequence}` - ); - - return this.rowToDispute(resolvedRow); - } - - /** - * Get the current dispute status for a channel. - */ - async getDispute(channelId: string): Promise { - const row = await this.db.getDispute(channelId); - if (!row) return null; - return this.rowToDispute(row); - } - - /** - * Check if a dispute's challenge period has expired. - */ - async isChallengeExpired(channelId: string): Promise { - const dispute = await this.db.getDispute(channelId); - if (!dispute) return false; - return new Date(dispute.challenge_deadline) < new Date(); - } - - private rowToDispute(row: { - id: string; - channel_id: string; - initiated_by: string; - status: string; - latest_sequence: number; - challenge_deadline: string; - broadcast_txid: string | null; - created_at: string; - updated_at: string; - }): Dispute { - return { - id: row.id, - channelId: row.channel_id, - initiatedBy: row.initiated_by, - status: row.status as DisputeStatus, - latestSequence: row.latest_sequence, - challengeDeadline: row.challenge_deadline, - broadcastTxid: row.broadcast_txid, - createdAt: row.created_at, - updatedAt: row.updated_at, - }; - } -} diff --git a/legacy/taproot-assets-era/backend/src/channels/PenaltyManager.ts b/legacy/taproot-assets-era/backend/src/channels/PenaltyManager.ts deleted file mode 100644 index 17107e6..0000000 --- a/legacy/taproot-assets-era/backend/src/channels/PenaltyManager.ts +++ /dev/null @@ -1,235 +0,0 @@ -/** - * PenaltyManager — Revocation enforcement for payment channels. - * - * When a user broadcasts an OLD (revoked) commitment transaction, - * the counterparty can use the revealed revocation secret to claim ALL funds. - * This is the core punishment mechanism that makes channels secure. - */ - -import crypto from 'crypto'; -import { sha256 } from '@noble/hashes/sha2.js'; -import Database from '../db/Database'; -import { MempoolClient, Transaction } from '../bitcoin/MempoolClient'; - -export interface RevocationSecret { - channelId: string; - sequence: number; - secret: string; - createdAt: string; -} - -export interface BreachAttempt { - id: string; - channelId: string; - detectedAt: string; - breachTxid: string; - breachTxHex: string; - penaltyTxid: string | null; - penaltyTxHex: string | null; - status: 'detected' | 'penalty_broadcast' | 'penalty_confirmed' | 'failed'; -} - -export class PenaltyManager { - private db: Database; - private mempool: MempoolClient; - - constructor(mempoolClient?: MempoolClient) { - this.db = Database.getInstance(); - this.mempool = mempoolClient || new MempoolClient(); - } - - /** - * Generate a new revocation secret for a commitment. - * Returns both the secret and its hash (the hash is shared with the counterparty). - */ - static generateRevocationSecret(): { secret: string; hash: string } { - const secret = crypto.randomBytes(32).toString('hex'); - const hash = Buffer.from(sha256(Buffer.from(secret, 'hex'))).toString('hex'); - return { secret, hash }; - } - - /** - * Store a revocation secret revealed by the counterparty. - * Called when a new commitment is created and the old one is revoked. - */ - async storeRevocationSecret( - channelId: string, - sequence: number, - secret: string - ): Promise { - console.log( - `[PenaltyManager] Storing revocation secret for channel ${channelId} seq #${sequence}` - ); - - await this.db.storeRevocationSecret(channelId, sequence, secret); - } - - /** - * Check if a broadcast transaction is an old (revoked) commitment. - * Compares the broadcast tx against stored revocation secrets. - * - * Returns the breached sequence number, or null if the tx is legitimate. - */ - async checkForBreach( - channelId: string, - broadcastedTx: Transaction - ): Promise { - console.log( - `[PenaltyManager] Checking for breach on channel ${channelId}, tx ${broadcastedTx.txid}` - ); - - const secrets = await this.db.getRevocationSecrets(channelId); - if (secrets.length === 0) { - return null; - } - - // Extract the sequence number from the broadcast transaction. - // In a real implementation, the commitment tx encodes the sequence - // in the locktime or nSequence field per BOLT spec conventions. - const txSequence = this.extractSequenceFromTx(broadcastedTx); - if (txSequence === null) { - return null; - } - - // If we have a revocation secret for this sequence, it's a breach - const match = secrets.find((s) => s.sequence === txSequence); - if (match) { - console.log( - `[PenaltyManager] BREACH DETECTED on channel ${channelId}! ` + - `Old commitment #${txSequence} was broadcast` - ); - return txSequence; - } - - return null; - } - - /** - * Build a penalty transaction that claims ALL channel funds. - * Uses the revocation secret to spend from the breacher's output. - */ - async buildPenaltyTx( - channelId: string, - breachTxid: string, - breachTxHex: string - ): Promise<{ penaltyTxHex: string; penaltyTxid: string }> { - console.log( - `[PenaltyManager] Building penalty tx for breach on channel ${channelId}` - ); - - const channel = await this.db.getChannel(channelId); - if (!channel) { - throw new Error(`Channel ${channelId} not found`); - } - - const secrets = await this.db.getRevocationSecrets(channelId); - if (secrets.length === 0) { - throw new Error(`No revocation secrets found for channel ${channelId}`); - } - - // In production, this would: - // 1. Parse the breach transaction to find outputs - // 2. Use the revocation secret to create a spending script - // 3. Build a transaction spending ALL outputs to our address - // 4. Sign with the revocation key path - // - // The penalty tx sends everything to the honest party's address. - const penaltyData = { - version: 2, - inputs: [ - { - txid: breachTxid, - vout: 0, - witness: ['revocation_signature', secrets[0].secret], - sequence: 0xffffffff, - }, - { - txid: breachTxid, - vout: 1, - witness: ['revocation_signature', secrets[0].secret], - sequence: 0xffffffff, - }, - ], - outputs: [ - { - address: `bc1p_penalty_${channel.runebolt_pubkey.slice(0, 8)}`, - value: 546, - }, - { script: 'OP_RETURN runestone_penalty_sweep', value: 0 }, - ], - locktime: 0, - }; - - const penaltyTxHex = Buffer.from(JSON.stringify(penaltyData)).toString('hex'); - const penaltyTxid = Buffer.from( - sha256(Buffer.from(penaltyTxHex, 'hex')) - ).toString('hex'); - - // Record the breach attempt - await this.db.recordBreach({ - channel_id: channelId, - breach_txid: breachTxid, - breach_tx_hex: breachTxHex, - penalty_txid: penaltyTxid, - penalty_tx_hex: penaltyTxHex, - status: 'detected', - }); - - console.log( - `[PenaltyManager] Penalty tx built: ${penaltyTxid.slice(0, 16)}...` - ); - - return { penaltyTxHex, penaltyTxid }; - } - - /** - * Broadcast a penalty transaction to claim funds from a breach. - */ - async broadcastPenaltyTx( - channelId: string, - penaltyTxHex: string - ): Promise { - console.log( - `[PenaltyManager] Broadcasting penalty tx for channel ${channelId}` - ); - - const txid = await this.mempool.broadcastTx(penaltyTxHex); - - // Update breach record status - const breaches = await this.db.getBreaches(channelId); - const latest = breaches[0]; - if (latest) { - await this.db.query( - `UPDATE breach_attempts SET status = 'penalty_broadcast', penalty_txid = $1, updated_at = NOW() - WHERE id = $2`, - [txid, latest.id] - ); - } - - console.log(`[PenaltyManager] Penalty tx broadcast: ${txid}`); - return txid; - } - - /** - * Extract commitment sequence number from a transaction. - * In LN-style channels, the sequence is encoded in the locktime - * or nSequence fields of the commitment transaction. - */ - private extractSequenceFromTx(tx: Transaction): number | null { - // Convention: commitment sequence is encoded in the lower 24 bits of locktime - // Upper 8 bits = 0x20 marker to distinguish from block height/timestamp - if ((tx.locktime & 0xff000000) === 0x20000000) { - return tx.locktime & 0x00ffffff; - } - - // Fallback: check nSequence of first input - if (tx.vin.length > 0) { - const seq = tx.vin[0].sequence; - if (seq !== 0xffffffff && seq !== 0xfffffffe) { - return seq & 0x00ffffff; - } - } - - return null; - } -} diff --git a/legacy/taproot-assets-era/backend/src/config/mainnet-checks.ts b/legacy/taproot-assets-era/backend/src/config/mainnet-checks.ts deleted file mode 100644 index 5163515..0000000 --- a/legacy/taproot-assets-era/backend/src/config/mainnet-checks.ts +++ /dev/null @@ -1,162 +0,0 @@ -/** - * Mainnet startup validation checks. - * Runs on boot to verify the server is correctly configured for production. - */ - -import { getCache } from '../cache/RedisCache'; - -interface CheckResult { - name: string; - passed: boolean; - critical: boolean; - message: string; -} - -const VERSION = '0.2.0'; - -/** - * Run all mainnet startup checks. - * Returns false if any CRITICAL check failed (server should not start). - */ -export async function runMainnetChecks(): Promise { - const network = process.env.BITCOIN_NETWORK || 'not set'; - const isProduction = process.env.NODE_ENV === 'production'; - - const results: CheckResult[] = []; - - // 1. BITCOIN_NETWORK check - if (!process.env.BITCOIN_NETWORK) { - results.push({ - name: 'BITCOIN_NETWORK', - passed: false, - critical: false, - message: 'BITCOIN_NETWORK is not set (defaults to mainnet)', - }); - } else if (process.env.BITCOIN_NETWORK !== 'mainnet' && isProduction) { - results.push({ - name: 'BITCOIN_NETWORK', - passed: false, - critical: true, - message: `BITCOIN_NETWORK is "${process.env.BITCOIN_NETWORK}" in production — expected "mainnet"`, - }); - } else { - results.push({ - name: 'BITCOIN_NETWORK', - passed: true, - critical: false, - message: `Network: ${process.env.BITCOIN_NETWORK}`, - }); - } - - // 2. JWT_SECRET length check - const jwtSecret = process.env.JWT_SECRET || ''; - if (jwtSecret.length < 32) { - results.push({ - name: 'JWT_SECRET', - passed: false, - critical: true, - message: `JWT_SECRET is ${jwtSecret.length} bytes — must be at least 32`, - }); - } else { - results.push({ - name: 'JWT_SECRET', - passed: true, - critical: false, - message: `JWT_SECRET: ${jwtSecret.length} bytes`, - }); - } - - // 3. DATABASE_URL — not using default password - const dbUrl = process.env.DATABASE_URL || ''; - if (!dbUrl) { - results.push({ - name: 'DATABASE_URL', - passed: false, - critical: true, - message: 'DATABASE_URL is not set', - }); - } else if (isProduction && (dbUrl.includes(':runebolt@') || dbUrl.includes(':CHANGE_ME@') || dbUrl.includes(':password@'))) { - results.push({ - name: 'DATABASE_URL', - passed: false, - critical: true, - message: 'DATABASE_URL appears to use a default password in production', - }); - } else { - results.push({ - name: 'DATABASE_URL', - passed: true, - critical: false, - message: 'DATABASE_URL: configured', - }); - } - - // 4. CORS_ORIGIN — not wildcard in production - const corsOrigin = process.env.CORS_ORIGIN || ''; - if (isProduction && (!corsOrigin || corsOrigin === '*')) { - results.push({ - name: 'CORS_ORIGIN', - passed: false, - critical: true, - message: 'CORS_ORIGIN must not be wildcard (*) or empty in production', - }); - } else { - results.push({ - name: 'CORS_ORIGIN', - passed: true, - critical: false, - message: `CORS_ORIGIN: ${corsOrigin || '(dev mode, permissive)'}`, - }); - } - - // 5. Redis reachability - try { - const cache = getCache(); - const redisOk = cache.connected(); - results.push({ - name: 'REDIS', - passed: redisOk, - critical: false, - message: redisOk ? 'Redis: connected' : 'Redis: not connected (caching disabled)', - }); - } catch { - results.push({ - name: 'REDIS', - passed: false, - critical: false, - message: 'Redis: connection check failed', - }); - } - - // Print startup banner - const passed = results.filter((r) => r.passed).length; - const total = results.length; - const criticalFailures = results.filter((r) => !r.passed && r.critical); - - console.log(''); - console.log('='.repeat(60)); - console.log(` RuneBolt v${VERSION} — Startup Checks`); - console.log(` Network: ${network}`); - console.log(` Environment: ${process.env.NODE_ENV || 'development'}`); - console.log('='.repeat(60)); - - for (const r of results) { - const icon = r.passed ? 'PASS' : r.critical ? 'FAIL' : 'WARN'; - console.log(` [${icon}] ${r.message}`); - } - - console.log('-'.repeat(60)); - console.log(` Checks: ${passed}/${total} passed`); - - if (criticalFailures.length > 0) { - console.log(` CRITICAL: ${criticalFailures.length} check(s) failed — server will NOT start`); - console.log('='.repeat(60)); - console.log(''); - return false; - } - - console.log(` Status: ready`); - console.log('='.repeat(60)); - console.log(''); - return true; -} diff --git a/legacy/taproot-assets-era/backend/src/config/security.ts b/legacy/taproot-assets-era/backend/src/config/security.ts deleted file mode 100644 index 7ba2cda..0000000 --- a/legacy/taproot-assets-era/backend/src/config/security.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Security Configuration for RuneBolt - */ - -export function validateSecurityConfig(): void { - const jwtSecret = process.env.JWT_SECRET; - if (!jwtSecret || jwtSecret.length < 32) { - throw new Error('JWT_SECRET must be set and at least 32 characters'); - } - if (jwtSecret === 'change_me_in_production') { - throw new Error('JWT_SECRET cannot use default placeholder'); - } -} - -export const rateLimits = { - auth: { windowMs: 15 * 60 * 1000, max: 5 }, - transfer: { windowMs: 60 * 1000, max: 30 }, - general: { windowMs: 60 * 1000, max: 100 }, -}; - -export const channelLimits = { - minCapacity: BigInt(100000), - maxCapacity: BigInt(100000000000000), -}; diff --git a/legacy/taproot-assets-era/backend/src/db/Database.ts b/legacy/taproot-assets-era/backend/src/db/Database.ts deleted file mode 100644 index f08ea95..0000000 --- a/legacy/taproot-assets-era/backend/src/db/Database.ts +++ /dev/null @@ -1,947 +0,0 @@ -import { Pool, PoolClient, QueryResult, QueryResultRow } from 'pg'; -import path from 'path'; -import fs from 'fs'; - -export interface ChannelRow { - id: string; - user_pubkey: string; - runebolt_pubkey: string; - funding_txid: string | null; - funding_vout: number | null; - capacity: number; - local_balance: number; - remote_balance: number; - state: string; - created_at: string; - updated_at: string; -} - -export interface TransferRow { - id: string; - from_channel: string; - to_channel: string; - amount: number; - memo: string | null; - nonce: string | null; - client_signature: string | null; - transfer_hash: string | null; - created_at: string; -} - -export interface UserRow { - pubkey: string; - username: string | null; - created_at: string; -} - -export interface ClaimLinkRow { - id: string; - creator_pubkey: string; - amount: number; - memo: string | null; - claimed_by: string | null; - claimed_at: string | null; - created_at: string; - expires_at: string; -} - -export interface ChallengeRow { - id: string; - pubkey: string; - challenge: string; - expires_at: string; -} - -export interface FeeRecordRow { - id: string; - transfer_id: string; - pubkey: string; - amount: number; - fee_type: string; - fee_rate: number; - collected_at: string; -} - -export interface UserTransactionCountRow { - pubkey: string; - count: number; - last_reset: string; -} - -export interface UserTierRow { - pubkey: string; - tier: string; - created_at: string; - updated_at: string; -} - -export interface CommitmentRow { - id: string; - channel_id: string; - sequence: number; - local_balance: number; - remote_balance: number; - commitment_tx: string | null; - signature: string | null; - created_at: string; -} - -export interface RevocationSecretRow { - id: string; - channel_id: string; - sequence: number; - secret: string; - created_at: string; -} - -export interface DisputeRow { - id: string; - channel_id: string; - initiated_by: string; - status: string; - latest_sequence: number; - challenge_deadline: string; - broadcast_txid: string | null; - created_at: string; - updated_at: string; -} - -export interface BreachAttemptRow { - id: string; - channel_id: string; - detected_at: string; - breach_txid: string; - breach_tx_hex: string; - penalty_txid: string | null; - penalty_tx_hex: string | null; - status: string; - created_at: string; - updated_at: string; -} - -interface PoolMetrics { - totalCount: number; - idleCount: number; - waitingCount: number; -} - -/** - * Database - PostgreSQL connection pool manager for RuneBolt - * - * Features: - * - Connection pooling with configurable min/max connections - * - Automatic prepared statements - * - Transaction support - * - Health checks and metrics - */ -class Database { - private static instance: Database; - private pool!: Pool; - private isInitialized: boolean = false; - - private constructor() {} - - static getInstance(): Database { - if (!Database.instance) { - Database.instance = new Database(); - } - return Database.instance; - } - - /** - * Initialize the database connection pool - */ - initialize(connectionString?: string): void { - if (this.isInitialized) { - return; - } - - const connString = connectionString || process.env.DATABASE_URL; - if (!connString) { - throw new Error('DATABASE_URL environment variable is required'); - } - - this.pool = new Pool({ - connectionString: connString, - max: parseInt(process.env.DB_POOL_MAX || '50', 10), - min: parseInt(process.env.DB_POOL_MIN || '10', 10), - idleTimeoutMillis: parseInt(process.env.DB_IDLE_TIMEOUT || '30000', 10), - connectionTimeoutMillis: parseInt(process.env.DB_CONNECTION_TIMEOUT || '5000', 10), - statement_timeout: parseInt(process.env.DB_STATEMENT_TIMEOUT || '10000', 10), - }); - - // Handle pool errors - this.pool.on('error', (err) => { - console.error('[Database] Unexpected pool error:', err); - }); - - this.isInitialized = true; - console.log('[Database] PostgreSQL pool initialized'); - } - - /** - * Run migrations from SQL file - */ - async runMigrations(migrationsPath?: string): Promise { - const client = await this.pool.connect(); - try { - const migrationsDir = migrationsPath || path.join(__dirname, '../../migrations'); - const migrationFiles = fs.existsSync(migrationsDir) - ? fs.readdirSync(migrationsDir).filter(f => f.endsWith('.sql')).sort() - : []; - - for (const file of migrationFiles) { - const filePath = path.join(migrationsDir, file); - const schema = fs.readFileSync(filePath, 'utf-8'); - await client.query(schema); - console.log(`[Database] Migration applied: ${file}`); - } - - console.log('[Database] All migrations completed'); - } finally { - client.release(); - } - } - - /** - * Get a client from the pool - */ - async getClient(): Promise { - return this.pool.connect(); - } - - /** - * Execute a query - */ - async query(sql: string, params?: unknown[]): Promise> { - return this.pool.query(sql, params); - } - - /** - * Execute a single-row query - */ - async queryOne(sql: string, params?: unknown[]): Promise { - const result = await this.pool.query(sql, params); - return result.rows[0]; - } - - /** - * Execute a transaction - */ - async transaction(fn: (client: PoolClient) => Promise): Promise { - const client = await this.pool.connect(); - try { - await client.query('BEGIN'); - const result = await fn(client); - await client.query('COMMIT'); - return result; - } catch (err) { - await client.query('ROLLBACK'); - throw err; - } finally { - client.release(); - } - } - - // ==================== Channel Methods ==================== - - async getChannel(id: string): Promise { - const result = await this.queryOne( - 'SELECT * FROM channels WHERE id = $1', - [id] - ); - return result; - } - - async getChannelsByPubkey(pubkey: string): Promise { - const result = await this.query( - 'SELECT * FROM channels WHERE user_pubkey = $1 ORDER BY created_at DESC', - [pubkey] - ); - return result.rows; - } - - async createChannel(channel: { - id: string; - user_pubkey: string; - runebolt_pubkey: string; - funding_txid: string | null; - funding_vout: number | null; - capacity: number | string; - local_balance: number | string; - remote_balance: number | string; - state: string; - }): Promise { - await this.query( - `INSERT INTO channels (id, user_pubkey, runebolt_pubkey, funding_txid, funding_vout, capacity, local_balance, remote_balance, state) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, - [channel.id, channel.user_pubkey, channel.runebolt_pubkey, channel.funding_txid, - channel.funding_vout, channel.capacity, channel.local_balance, channel.remote_balance, channel.state] - ); - } - - async updateChannel(channel: { - id: string; - funding_txid: string | null; - funding_vout: number | null; - capacity: number | string; - local_balance: number | string; - remote_balance: number | string; - state: string; - }): Promise { - await this.query( - `UPDATE channels - SET funding_txid = $1, funding_vout = $2, capacity = $3, local_balance = $4, - remote_balance = $5, state = $6, updated_at = NOW() - WHERE id = $7`, - [channel.funding_txid, channel.funding_vout, channel.capacity, channel.local_balance, - channel.remote_balance, channel.state, channel.id] - ); - } - - async updateChannelState(id: string, state: string): Promise { - await this.query( - 'UPDATE channels SET state = $1, updated_at = NOW() WHERE id = $2', - [state, id] - ); - } - - async updateChannelBalances(id: string, localBalance: number | string, remoteBalance: number | string): Promise { - await this.query( - 'UPDATE channels SET local_balance = $1, remote_balance = $2, updated_at = NOW() WHERE id = $3', - [localBalance, remoteBalance, id] - ); - } - - // ==================== Transfer Methods ==================== - - async createTransfer(transfer: { - id: string; - from_channel: string; - to_channel: string; - amount: number | string; - memo: string | null; - nonce?: string | null; - client_signature?: string | null; - transfer_hash?: string | null; - }): Promise { - await this.query( - `INSERT INTO transfers (id, from_channel, to_channel, amount, memo, nonce, client_signature, transfer_hash) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, - [transfer.id, transfer.from_channel, transfer.to_channel, transfer.amount, transfer.memo, - transfer.nonce || null, transfer.client_signature || null, transfer.transfer_hash || null] - ); - } - - async getTransferByNonce(nonce: string): Promise<{ id: string } | undefined> { - return this.queryOne<{ id: string }>( - 'SELECT id FROM transfers WHERE nonce = $1', - [nonce] - ); - } - - async getTransfersByChannel(channelId: string, limit: number = 50, offset: number = 0): Promise { - const result = await this.query( - `SELECT * FROM transfers - WHERE from_channel = $1 OR to_channel = $1 - ORDER BY created_at DESC LIMIT $2 OFFSET $3`, - [channelId, limit, offset] - ); - return result.rows; - } - - async getTransfersBySender(channelIds: string[], limit: number = 50): Promise { - const result = await this.query( - `SELECT * FROM transfers - WHERE from_channel = ANY($1) - ORDER BY created_at DESC LIMIT $2`, - [channelIds, limit] - ); - return result.rows; - } - - async getTransfersByRecipient(channelIds: string[], limit: number = 50): Promise { - const result = await this.query( - `SELECT * FROM transfers - WHERE to_channel = ANY($1) - ORDER BY created_at DESC LIMIT $2`, - [channelIds, limit] - ); - return result.rows; - } - - async getTransfersByPubkey(pubkey: string, limit: number = 50, offset: number = 0): Promise { - const channelsResult = await this.query<{ id: string }>( - 'SELECT id FROM channels WHERE user_pubkey = $1', - [pubkey] - ); - const channelIds = channelsResult.rows.map(r => r.id); - - if (channelIds.length === 0) return []; - - const [sent, received] = await Promise.all([ - this.getTransfersBySender(channelIds, limit), - this.getTransfersByRecipient(channelIds, limit), - ]); - - const all = [...sent, ...received]; - all.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()); - - return all.slice(offset, offset + limit); - } - - // ==================== User Methods ==================== - - async getUser(pubkey: string): Promise { - return this.queryOne('SELECT * FROM users WHERE pubkey = $1', [pubkey]); - } - - async getUserByUsername(username: string): Promise { - return this.queryOne('SELECT * FROM users WHERE username = $1', [username]); - } - - async createUser(pubkey: string): Promise { - await this.query( - 'INSERT INTO users (pubkey) VALUES ($1) ON CONFLICT (pubkey) DO NOTHING', - [pubkey] - ); - } - - async updateUsername(pubkey: string, username: string): Promise { - await this.query('UPDATE users SET username = $1 WHERE pubkey = $2', [username, pubkey]); - } - - // ==================== Claim Link Methods ==================== - - async createClaimLink(link: { - id: string; - creator_pubkey: string; - amount: number; - memo: string | null; - expires_at: string; - }): Promise { - await this.query( - `INSERT INTO claim_links (id, creator_pubkey, amount, memo, expires_at) - VALUES ($1, $2, $3, $4, $5)`, - [link.id, link.creator_pubkey, link.amount, link.memo, link.expires_at] - ); - } - - async getClaimLink(id: string): Promise { - return this.queryOne('SELECT * FROM claim_links WHERE id = $1', [id]); - } - - async claimLink(id: string, claimedBy: string): Promise { - await this.query( - 'UPDATE claim_links SET claimed_by = $1, claimed_at = NOW() WHERE id = $2', - [claimedBy, id] - ); - } - - // ==================== Challenge Methods ==================== - - async createChallenge(challenge: { - id: string; - pubkey: string; - challenge: string; - expires_at: string; - }): Promise { - await this.transaction(async (client) => { - await client.query('DELETE FROM challenges WHERE expires_at < NOW()'); - await client.query( - 'INSERT INTO challenges (id, pubkey, challenge, expires_at) VALUES ($1, $2, $3, $4)', - [challenge.id, challenge.pubkey, challenge.challenge, challenge.expires_at] - ); - }); - } - - async getChallenge(id: string): Promise { - return this.queryOne('SELECT * FROM challenges WHERE id = $1', [id]); - } - - async deleteChallenge(id: string): Promise { - await this.query('DELETE FROM challenges WHERE id = $1', [id]); - } - - // ==================== Commitment Methods ==================== - - async createCommitment(commitment: { - channel_id: string; - sequence: number; - local_balance: number; - remote_balance: number; - commitment_tx?: string; - signature?: string; - }): Promise { - await this.query( - `INSERT INTO commitments (channel_id, sequence, local_balance, remote_balance, commitment_tx, signature) - VALUES ($1, $2, $3, $4, $5, $6)`, - [commitment.channel_id, commitment.sequence, commitment.local_balance, - commitment.remote_balance, commitment.commitment_tx || null, commitment.signature || null] - ); - } - - async getLatestCommitment(channelId: string): Promise { - return this.queryOne( - 'SELECT * FROM commitments WHERE channel_id = $1 ORDER BY sequence DESC LIMIT 1', - [channelId] - ); - } - - async getCommitmentsByChannel(channelId: string, limit: number = 10): Promise { - const result = await this.query( - 'SELECT * FROM commitments WHERE channel_id = $1 ORDER BY sequence DESC LIMIT $2', - [channelId, limit] - ); - return result.rows; - } - - // ==================== Health & Metrics ==================== - - async healthCheck(): Promise<{ healthy: boolean; latency: number; error?: string }> { - const start = Date.now(); - try { - await this.pool.query('SELECT 1'); - return { healthy: true, latency: Date.now() - start }; - } catch (err) { - return { - healthy: false, - latency: Date.now() - start, - error: err instanceof Error ? err.message : 'Unknown error' - }; - } - } - - getPoolMetrics(): PoolMetrics { - return { - totalCount: this.pool.totalCount, - idleCount: this.pool.idleCount, - waitingCount: this.pool.waitingCount, - }; - } - - async createNextPartition(): Promise { - try { - await this.query('SELECT create_transfer_partition()'); - console.log('[Database] Created next month partition'); - } catch (err) { - console.error('[Database] Failed to create partition:', err); - } - } - - async cleanupExpiredData(): Promise { - try { - await this.query('SELECT cleanup_expired_data()'); - console.log('[Database] Cleaned up expired data'); - } catch (err) { - console.error('[Database] Failed to cleanup:', err); - } - } - - // ==================== Transaction Status Methods ==================== - - async createTransactionStatus(tx: { - id: string; - type: string; - from_pubkey?: string; - to_pubkey?: string; - amount?: number; - metadata?: Record; - }): Promise { - await this.query( - `INSERT INTO transaction_status (id, type, status, from_pubkey, to_pubkey, amount, metadata, created_at, updated_at) - VALUES ($1, $2, 'pending', $3, $4, $5, $6, NOW(), NOW())`, - [tx.id, tx.type, tx.from_pubkey || null, tx.to_pubkey || null, tx.amount || null, - tx.metadata ? JSON.stringify(tx.metadata) : null] - ); - } - - async updateTransactionStatus( - id: string, - status: string, - metadata?: Record - ): Promise { - const completedAt = status === 'confirmed' || status === 'failed' ? 'NOW()' : null; - await this.query( - `UPDATE transaction_status - SET status = $1, updated_at = NOW(), - completed_at = ${completedAt}, - metadata = COALESCE($2, metadata) - WHERE id = $3`, - [status, metadata ? JSON.stringify(metadata) : null, id] - ); - } - - async getTransactionStatus(id: string): Promise<{ - id: string; - type: string; - status: string; - from_pubkey: string | null; - to_pubkey: string | null; - amount: number | null; - metadata: Record | null; - created_at: string; - updated_at: string; - completed_at: string | null; - } | undefined> { - const row = await this.queryOne<{ - id: string; - type: string; - status: string; - from_pubkey: string | null; - to_pubkey: string | null; - amount: number | null; - metadata: string | null; - created_at: string; - updated_at: string; - completed_at: string | null; - }>('SELECT * FROM transaction_status WHERE id = $1', [id]); - - if (!row) return undefined; - - return { - ...row, - metadata: row.metadata ? JSON.parse(row.metadata) : null, - }; - } - - async getTransactionsByPubkey( - pubkey: string, - limit: number = 20 - ): Promise> { - const result = await this.query<{ - id: string; - type: string; - status: string; - from_pubkey: string | null; - to_pubkey: string | null; - amount: number | null; - created_at: string; - updated_at: string; - }>( - `SELECT id, type, status, from_pubkey, to_pubkey, amount, created_at, updated_at - FROM transaction_status - WHERE from_pubkey = $1 OR to_pubkey = $1 - ORDER BY updated_at DESC LIMIT $2`, - [pubkey, limit] - ); - return result.rows; - } - - // ==================== Transaction Count Methods ==================== - - async getTransactionCount(pubkey: string): Promise { - return this.queryOne( - 'SELECT * FROM user_transaction_counts WHERE pubkey = $1', - [pubkey] - ); - } - - async incrementTransactionCount(pubkey: string): Promise { - const result = await this.queryOne<{ count: number }>( - `INSERT INTO user_transaction_counts (pubkey, count) - VALUES ($1, 1) - ON CONFLICT (pubkey) DO UPDATE SET count = user_transaction_counts.count + 1 - RETURNING count`, - [pubkey] - ); - return result?.count ?? 1; - } - - // ==================== Fee Record Methods ==================== - - async createFeeRecord(fee: { - transfer_id: string; - pubkey: string; - amount: number | string; - fee_type: string; - fee_rate: number; - }): Promise { - await this.query( - `INSERT INTO fee_records (transfer_id, pubkey, amount, fee_type, fee_rate) - VALUES ($1, $2, $3, $4, $5)`, - [fee.transfer_id, fee.pubkey, fee.amount, fee.fee_type, fee.fee_rate] - ); - } - - async getFeesByPubkey(pubkey: string, limit: number = 50): Promise { - const result = await this.query( - 'SELECT * FROM fee_records WHERE pubkey = $1 ORDER BY collected_at DESC LIMIT $2', - [pubkey, limit] - ); - return result.rows; - } - - // ==================== User Tier Methods ==================== - - async getUserTier(pubkey: string): Promise { - return this.queryOne( - 'SELECT * FROM user_tiers WHERE pubkey = $1', - [pubkey] - ); - } - - async ensureUserTier(pubkey: string): Promise { - const result = await this.queryOne( - `INSERT INTO user_tiers (pubkey, tier) - VALUES ($1, 'free') - ON CONFLICT (pubkey) DO UPDATE SET pubkey = user_tiers.pubkey - RETURNING *`, - [pubkey] - ); - return result!; - } - - async updateUserTier(pubkey: string, tier: string): Promise { - await this.query( - `INSERT INTO user_tiers (pubkey, tier) - VALUES ($1, $2) - ON CONFLICT (pubkey) DO UPDATE SET tier = $2`, - [pubkey, tier] - ); - } - - // ==================== Revocation Secret Methods ==================== - - async storeRevocationSecret( - channelId: string, - sequence: number, - secret: string - ): Promise { - await this.query( - `INSERT INTO revocation_secrets (channel_id, sequence, secret) - VALUES ($1, $2, $3) - ON CONFLICT (channel_id, sequence) DO UPDATE SET secret = $3`, - [channelId, sequence, secret] - ); - } - - async getRevocationSecrets(channelId: string): Promise { - const result = await this.query( - 'SELECT * FROM revocation_secrets WHERE channel_id = $1 ORDER BY sequence ASC', - [channelId] - ); - return result.rows; - } - - async getRevocationSecret( - channelId: string, - sequence: number - ): Promise { - return this.queryOne( - 'SELECT * FROM revocation_secrets WHERE channel_id = $1 AND sequence = $2', - [channelId, sequence] - ); - } - - // ==================== Dispute Methods ==================== - - async createDispute(dispute: { - channel_id: string; - initiated_by: string; - latest_sequence: number; - challenge_deadline: string; - broadcast_txid: string | null; - }): Promise { - const result = await this.queryOne( - `INSERT INTO disputes (channel_id, initiated_by, latest_sequence, challenge_deadline, broadcast_txid) - VALUES ($1, $2, $3, $4, $5) - ON CONFLICT (channel_id) DO UPDATE - SET initiated_by = $2, status = 'open', latest_sequence = $3, - challenge_deadline = $4, broadcast_txid = $5, updated_at = NOW() - RETURNING *`, - [dispute.channel_id, dispute.initiated_by, dispute.latest_sequence, - dispute.challenge_deadline, dispute.broadcast_txid] - ); - return result!; - } - - async getDispute(channelId: string): Promise { - return this.queryOne( - 'SELECT * FROM disputes WHERE channel_id = $1', - [channelId] - ); - } - - async resolveDispute(channelId: string): Promise { - const result = await this.queryOne( - `UPDATE disputes SET status = 'resolved', updated_at = NOW() - WHERE channel_id = $1 RETURNING *`, - [channelId] - ); - if (!result) { - throw new Error(`No dispute found for channel ${channelId}`); - } - return result; - } - - // ==================== Breach Attempt Methods ==================== - - async recordBreach(breach: { - channel_id: string; - breach_txid: string; - breach_tx_hex: string; - penalty_txid: string | null; - penalty_tx_hex: string | null; - status: string; - }): Promise { - const result = await this.queryOne( - `INSERT INTO breach_attempts (channel_id, breach_txid, breach_tx_hex, penalty_txid, penalty_tx_hex, status) - VALUES ($1, $2, $3, $4, $5, $6) - RETURNING *`, - [breach.channel_id, breach.breach_txid, breach.breach_tx_hex, - breach.penalty_txid, breach.penalty_tx_hex, breach.status] - ); - return result!; - } - - async getBreaches(channelId: string): Promise { - const result = await this.query( - 'SELECT * FROM breach_attempts WHERE channel_id = $1 ORDER BY detected_at DESC', - [channelId] - ); - return result.rows; - } - - // ==================== Stats Methods ==================== - - async getPublicStats(): Promise<{ - totalUsers: number; - totalTransfers: number; - totalVolume: string; - totalChannels: number; - openChannels: number; - }> { - const [users, transfers, volume, channels, openChannels] = await Promise.all([ - this.queryOne<{ count: string }>('SELECT COUNT(*) as count FROM users'), - this.queryOne<{ count: string }>('SELECT COUNT(*) as count FROM transfers'), - this.queryOne<{ total: string }>('SELECT COALESCE(SUM(amount), 0) as total FROM transfers'), - this.queryOne<{ count: string }>('SELECT COUNT(*) as count FROM channels'), - this.queryOne<{ count: string }>("SELECT COUNT(*) as count FROM channels WHERE state = 'OPEN'"), - ]); - - return { - totalUsers: parseInt(users?.count || '0', 10), - totalTransfers: parseInt(transfers?.count || '0', 10), - totalVolume: volume?.total || '0', - totalChannels: parseInt(channels?.count || '0', 10), - openChannels: parseInt(openChannels?.count || '0', 10), - }; - } - - // ==================== Asset Methods ==================== - - async getAsset(id: string): Promise<{ id: string; name: string; type: string; config: Record; created_at: string } | undefined> { - const row = await this.queryOne<{ id: string; name: string; type: string; config: string; created_at: string }>( - 'SELECT * FROM assets WHERE id = $1', - [id] - ); - if (!row) return undefined; - return { ...row, config: typeof row.config === 'string' ? JSON.parse(row.config) : row.config }; - } - - async getAllAssets(): Promise; created_at: string }>> { - const result = await this.query<{ id: string; name: string; type: string; config: string; created_at: string }>( - 'SELECT * FROM assets ORDER BY id' - ); - return result.rows.map(row => ({ - ...row, - config: typeof row.config === 'string' ? JSON.parse(row.config) : row.config, - })); - } - - async upsertAsset(asset: { id: string; name: string; type: string; config: Record }): Promise { - await this.query( - `INSERT INTO assets (id, name, type, config) - VALUES ($1, $2, $3, $4) - ON CONFLICT (id) DO UPDATE SET name = $2, type = $3, config = $4`, - [asset.id, asset.name, asset.type, JSON.stringify(asset.config)] - ); - } - - // ==================== Escrow Methods ==================== - - async getEscrow(id: string): Promise<{ - id: string; seller_pubkey: string; buyer_pubkey: string; inscription_id: string; - price_asset: string; price_amount: string; status: string; timeout_at: string; created_at: string; - } | undefined> { - return this.queryOne( - 'SELECT * FROM escrows WHERE id = $1', - [id] - ); - } - - async getEscrowsByPubkey(pubkey: string): Promise> { - const result = await this.query( - 'SELECT * FROM escrows WHERE seller_pubkey = $1 OR buyer_pubkey = $1 ORDER BY created_at DESC', - [pubkey] - ); - return result.rows as Array<{ - id: string; seller_pubkey: string; buyer_pubkey: string; inscription_id: string; - price_asset: string; price_amount: string; status: string; timeout_at: string; created_at: string; - }>; - } - - async getExpiredEscrows(): Promise> { - const result = await this.query<{ id: string; status: string }>( - `SELECT id, status FROM escrows - WHERE timeout_at < NOW() AND status NOT IN ('completed', 'refunded', 'expired')` - ); - return result.rows; - } - - async expireEscrow(id: string): Promise { - await this.query( - "UPDATE escrows SET status = 'expired' WHERE id = $1", - [id] - ); - } - - // ==================== Asset Balance Methods ==================== - - async getAssetBalance(userPubkey: string, assetId: string): Promise { - const row = await this.queryOne<{ balance: string }>( - 'SELECT balance FROM asset_balances WHERE user_pubkey = $1 AND asset_id = $2', - [userPubkey, assetId] - ); - return row?.balance ?? '0'; - } - - async getAssetBalancesByPubkey(userPubkey: string): Promise> { - const result = await this.query<{ asset_id: string; balance: string; updated_at: string }>( - 'SELECT asset_id, balance, updated_at FROM asset_balances WHERE user_pubkey = $1', - [userPubkey] - ); - return result.rows; - } - - async updateAssetBalance(userPubkey: string, assetId: string, amount: string): Promise { - await this.query( - `INSERT INTO asset_balances (user_pubkey, asset_id, balance, updated_at) - VALUES ($1, $2, $3, NOW()) - ON CONFLICT (user_pubkey, asset_id) - DO UPDATE SET balance = asset_balances.balance + $3::numeric, updated_at = NOW()`, - [userPubkey, assetId, amount] - ); - } - - async close(): Promise { - await this.pool.end(); - this.isInitialized = false; - console.log('[Database] Pool closed'); - } -} - -export default Database; \ No newline at end of file diff --git a/legacy/taproot-assets-era/backend/src/db/migrations/001_security_fixes.sql b/legacy/taproot-assets-era/backend/src/db/migrations/001_security_fixes.sql deleted file mode 100644 index fc7ede1..0000000 --- a/legacy/taproot-assets-era/backend/src/db/migrations/001_security_fixes.sql +++ /dev/null @@ -1,66 +0,0 @@ --- Migration: Security Fixes for RuneBolt v0.2.0 --- Date: 2026-03-14 --- Description: Adds replay protection, persistent commitments, and audit logging - --- ============================================================ --- C2: Replay Protection - Add nonce and signature columns --- ============================================================ - --- Add nonce column for replay protection -ALTER TABLE transfers ADD COLUMN nonce TEXT UNIQUE; - --- Add client signature column for authorization -ALTER TABLE transfers ADD COLUMN client_signature TEXT; - --- Add transfer hash column for verification -ALTER TABLE transfers ADD COLUMN transfer_hash TEXT; - --- Create index for fast nonce lookups -CREATE INDEX IF NOT EXISTS idx_transfers_nonce ON transfers(nonce); - --- ============================================================ --- C3: Persistent Commitments --- ============================================================ - --- Create commitments table -CREATE TABLE IF NOT EXISTS commitments ( - id TEXT PRIMARY KEY, - channel_id TEXT NOT NULL, - sequence INTEGER NOT NULL, - local_balance TEXT NOT NULL, -- Stored as TEXT for BigInt - remote_balance TEXT NOT NULL, - hash TEXT NOT NULL, - local_signature TEXT, - remote_signature TEXT, - revocation_secret TEXT, -- For penalty transactions - revocation_hash TEXT, -- Hash of revocation secret - is_revoked INTEGER DEFAULT 0, -- Boolean flag - created_at TEXT NOT NULL DEFAULT (datetime('now')), - FOREIGN KEY (channel_id) REFERENCES channels(id), - UNIQUE(channel_id, sequence) -); - --- Create indexes for commitment queries -CREATE INDEX IF NOT EXISTS idx_commitments_channel ON commitments(channel_id); -CREATE INDEX IF NOT EXISTS idx_commitments_channel_sequence ON commitments(channel_id, sequence); - --- ============================================================ --- Idempotency Table for API Requests --- ============================================================ - --- Create idempotent_requests table -CREATE TABLE IF NOT EXISTS idempotent_requests ( - key TEXT PRIMARY KEY, - response TEXT NOT NULL, - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); - --- Create index for cleanup -CREATE INDEX IF NOT EXISTS idx_idempotent_requests_created ON idempotent_requests(created_at); - --- ============================================================ --- Migration Complete --- ============================================================ - --- Verify migration -SELECT 'Migration complete: Security fixes applied' as status; diff --git a/legacy/taproot-assets-era/backend/src/db/migrations/002_username_social_auth.sql b/legacy/taproot-assets-era/backend/src/db/migrations/002_username_social_auth.sql deleted file mode 100644 index cf2f8d2..0000000 --- a/legacy/taproot-assets-era/backend/src/db/migrations/002_username_social_auth.sql +++ /dev/null @@ -1,49 +0,0 @@ --- Username registry table with additional constraints -CREATE TABLE IF NOT EXISTS username_registry ( - username TEXT PRIMARY KEY, - pubkey TEXT NOT NULL UNIQUE, - display_name TEXT, - avatar_url TEXT, - created_at TEXT NOT NULL DEFAULT (datetime('now')), - updated_at TEXT NOT NULL DEFAULT (datetime('now')), - FOREIGN KEY (pubkey) REFERENCES users(pubkey) ON DELETE CASCADE -); - --- Index for fast lookups -CREATE INDEX IF NOT EXISTS idx_username_registry_pubkey ON username_registry(pubkey); - --- Social auth providers table -CREATE TABLE IF NOT EXISTS social_auth ( - id TEXT PRIMARY KEY, - provider TEXT NOT NULL, -- 'google', 'apple', 'email' - provider_user_id TEXT NOT NULL, - email TEXT, - username TEXT, - pubkey TEXT NOT NULL, - created_at TEXT NOT NULL DEFAULT (datetime('now')), - UNIQUE(provider, provider_user_id) -); - -CREATE INDEX IF NOT EXISTS idx_social_auth_pubkey ON social_auth(pubkey); -CREATE INDEX IF NOT EXISTS idx_social_auth_provider ON social_auth(provider, provider_user_id); - --- Claim links enhanced table (already exists, but document here) --- Supports both registered and unregistered recipients - --- Transaction status tracking for WebSocket updates -CREATE TABLE IF NOT EXISTS transaction_status ( - id TEXT PRIMARY KEY, - type TEXT NOT NULL, -- 'transfer', 'claim', 'deposit', 'withdrawal' - status TEXT NOT NULL DEFAULT 'pending', -- 'pending', 'confirming', 'confirmed', 'failed' - from_pubkey TEXT, - to_pubkey TEXT, - amount INTEGER, - metadata TEXT, -- JSON blob for additional data - created_at TEXT NOT NULL DEFAULT (datetime('now')), - updated_at TEXT NOT NULL DEFAULT (datetime('now')), - completed_at TEXT -); - -CREATE INDEX IF NOT EXISTS idx_transaction_status_from ON transaction_status(from_pubkey); -CREATE INDEX IF NOT EXISTS idx_transaction_status_to ON transaction_status(to_pubkey); -CREATE INDEX IF NOT EXISTS idx_transaction_status_status ON transaction_status(status); diff --git a/legacy/taproot-assets-era/backend/src/db/migrations/003_fee_tracking.sql b/legacy/taproot-assets-era/backend/src/db/migrations/003_fee_tracking.sql deleted file mode 100644 index e932a1a..0000000 --- a/legacy/taproot-assets-era/backend/src/db/migrations/003_fee_tracking.sql +++ /dev/null @@ -1,31 +0,0 @@ --- RuneBolt Migration 003: Enhanced fee tracking --- Adds free_remaining and total_fees_paid columns to user_transaction_counts, --- and creates fee_ledger table for detailed fee audit trail. - --- ============================================================ --- Enhance user_transaction_counts with free_remaining and total_fees_paid --- ============================================================ -ALTER TABLE user_transaction_counts - ADD COLUMN IF NOT EXISTS free_remaining INTEGER NOT NULL DEFAULT 500, - ADD COLUMN IF NOT EXISTS total_fees_paid BIGINT NOT NULL DEFAULT 0; - --- Backfill free_remaining from existing count data -UPDATE user_transaction_counts -SET free_remaining = GREATEST(0, 500 - count) -WHERE free_remaining = 500 AND count > 0; - --- ============================================================ --- Fee ledger — detailed per-transfer fee audit trail --- ============================================================ -CREATE TABLE IF NOT EXISTS fee_ledger ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - user_pubkey TEXT NOT NULL, - transfer_id UUID NOT NULL, - fee_amount BIGINT NOT NULL, - fee_type TEXT NOT NULL CHECK (fee_type IN ('free', 'off_chain', 'settlement')), - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_fee_ledger_user ON fee_ledger(user_pubkey); -CREATE INDEX IF NOT EXISTS idx_fee_ledger_transfer ON fee_ledger(transfer_id); -CREATE INDEX IF NOT EXISTS idx_fee_ledger_created ON fee_ledger(created_at); diff --git a/legacy/taproot-assets-era/backend/src/db/migrations/004_security_tables.sql b/legacy/taproot-assets-era/backend/src/db/migrations/004_security_tables.sql deleted file mode 100644 index f8af044..0000000 --- a/legacy/taproot-assets-era/backend/src/db/migrations/004_security_tables.sql +++ /dev/null @@ -1,51 +0,0 @@ --- Migration 004: Security tables for penalty, dispute, and breach detection --- Required for mainnet safety: revocation enforcement, dispute resolution, watchtower - --- Revocation secrets: stored when counterparty reveals secret for old commitment -CREATE TABLE IF NOT EXISTS revocation_secrets ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - channel_id UUID NOT NULL REFERENCES channels(id), - sequence INTEGER NOT NULL, - secret TEXT NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE(channel_id, sequence) -); - -CREATE INDEX IF NOT EXISTS idx_revocation_secrets_channel - ON revocation_secrets(channel_id); - --- Disputes: tracks unilateral close disputes and challenge windows -CREATE TABLE IF NOT EXISTS disputes ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - channel_id UUID NOT NULL REFERENCES channels(id), - initiated_by TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'open', - latest_sequence INTEGER NOT NULL, - challenge_deadline TIMESTAMPTZ NOT NULL, - broadcast_txid TEXT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE(channel_id) -); - -CREATE INDEX IF NOT EXISTS idx_disputes_status - ON disputes(status); - --- Breach attempts: records detected old-state broadcasts and penalty responses -CREATE TABLE IF NOT EXISTS breach_attempts ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - channel_id UUID NOT NULL REFERENCES channels(id), - detected_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - breach_txid TEXT NOT NULL, - breach_tx_hex TEXT NOT NULL, - penalty_txid TEXT, - penalty_tx_hex TEXT, - status TEXT NOT NULL DEFAULT 'detected', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_breach_attempts_channel - ON breach_attempts(channel_id); -CREATE INDEX IF NOT EXISTS idx_breach_attempts_status - ON breach_attempts(status); diff --git a/legacy/taproot-assets-era/backend/src/db/migrations/005_multi_asset.sql b/legacy/taproot-assets-era/backend/src/db/migrations/005_multi_asset.sql deleted file mode 100644 index 8d045f1..0000000 --- a/legacy/taproot-assets-era/backend/src/db/migrations/005_multi_asset.sql +++ /dev/null @@ -1,73 +0,0 @@ --- Migration 005: Multi-asset support --- Adds tables for asset registry, escrows (Bitmap NFT trading), and asset balances (BRC-20 channel tracking). --- --- NOTE: BRC-20 and Bitmap inscriptions use DIFFERENT on-chain mechanisms than Runes. --- Runes use Runestone OP_RETURN; BRC-20 uses inscription JSON; Bitmap uses escrow model. - --- ==================== Assets Table ==================== --- Central registry of supported assets and their configuration. -CREATE TABLE IF NOT EXISTS assets ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - type TEXT NOT NULL CHECK (type IN ('rune', 'btc', 'brc20', 'inscription')), - config JSONB NOT NULL DEFAULT '{}', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_assets_type ON assets(type); - --- Seed initial assets -INSERT INTO assets (id, name, type, config) VALUES - ('dog', 'DOG', 'rune', '{"runeId": "840000:3", "decimals": 5}'), - ('btc', 'Bitcoin', 'btc', '{"decimals": 8}'), - ('ordi', 'ORDI', 'brc20', '{"ticker": "ordi", "decimals": 18}'), - ('bitmap', 'Bitmap', 'inscription', '{"decimals": 0}') -ON CONFLICT (id) DO NOTHING; - --- ==================== Escrows Table ==================== --- Bitmap (NFT inscription) escrow for atomic swaps. --- Seller deposits inscription, buyer deposits payment, hub releases both atomically. -CREATE TABLE IF NOT EXISTS escrows ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - seller_pubkey TEXT NOT NULL, - buyer_pubkey TEXT NOT NULL, - inscription_id TEXT NOT NULL, - price_asset TEXT NOT NULL REFERENCES assets(id), - price_amount NUMERIC NOT NULL CHECK (price_amount > 0), - status TEXT NOT NULL DEFAULT 'created' - CHECK (status IN ('created', 'inscription_deposited', 'payment_deposited', - 'both_deposited', 'executing', 'completed', 'refunded', 'expired')), - timeout_at TIMESTAMPTZ NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_escrows_seller ON escrows(seller_pubkey); -CREATE INDEX IF NOT EXISTS idx_escrows_buyer ON escrows(buyer_pubkey); -CREATE INDEX IF NOT EXISTS idx_escrows_status ON escrows(status) WHERE status NOT IN ('completed', 'refunded', 'expired'); -CREATE INDEX IF NOT EXISTS idx_escrows_timeout ON escrows(timeout_at) WHERE status NOT IN ('completed', 'refunded', 'expired'); - --- ==================== Escrow Deposits Table ==================== --- Tracks individual deposits (inscription or payment) for each escrow. -CREATE TABLE IF NOT EXISTS escrow_deposits ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - escrow_id UUID NOT NULL REFERENCES escrows(id) ON DELETE CASCADE, - side TEXT NOT NULL CHECK (side IN ('seller', 'buyer')), - txid TEXT NOT NULL, - confirmed BOOLEAN NOT NULL DEFAULT false, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_escrow_deposits_escrow ON escrow_deposits(escrow_id); - --- ==================== Asset Balances Table ==================== --- Off-chain asset balances tracked by the hub (used for BRC-20 channel balances). -CREATE TABLE IF NOT EXISTS asset_balances ( - user_pubkey TEXT NOT NULL, - asset_id TEXT NOT NULL REFERENCES assets(id), - balance NUMERIC NOT NULL DEFAULT 0 CHECK (balance >= 0), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (user_pubkey, asset_id) -); - -CREATE INDEX IF NOT EXISTS idx_asset_balances_user ON asset_balances(user_pubkey); -CREATE INDEX IF NOT EXISTS idx_asset_balances_asset ON asset_balances(asset_id); diff --git a/legacy/taproot-assets-era/backend/src/db/migrations/006_missing_tables.sql b/legacy/taproot-assets-era/backend/src/db/migrations/006_missing_tables.sql deleted file mode 100644 index 29ecf6b..0000000 --- a/legacy/taproot-assets-era/backend/src/db/migrations/006_missing_tables.sql +++ /dev/null @@ -1,141 +0,0 @@ --- Migration 006: Create all missing tables required for mainnet --- Ensures tables exist that other migrations/code depend on - --- ============================================================ --- user_transaction_counts: tracks per-user transaction counts and free tier --- ============================================================ -CREATE TABLE IF NOT EXISTS user_transaction_counts ( - pubkey TEXT PRIMARY KEY, - count INTEGER NOT NULL DEFAULT 0, - free_remaining INTEGER NOT NULL DEFAULT 500, - total_fees_paid BIGINT NOT NULL DEFAULT 0, - last_reset TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - --- ============================================================ --- fee_records: individual fee collection records --- ============================================================ -CREATE TABLE IF NOT EXISTS fee_records ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - transfer_id UUID, - pubkey TEXT NOT NULL, - amount BIGINT NOT NULL, - fee_type TEXT NOT NULL, - fee_rate DOUBLE PRECISION NOT NULL DEFAULT 0, - collected_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_fee_records_pubkey ON fee_records(pubkey); -CREATE INDEX IF NOT EXISTS idx_fee_records_transfer ON fee_records(transfer_id); - --- ============================================================ --- fee_ledger: detailed per-transfer fee audit trail --- ============================================================ -CREATE TABLE IF NOT EXISTS fee_ledger ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - user_pubkey TEXT NOT NULL, - transfer_id UUID, - fee_amount BIGINT NOT NULL, - fee_type TEXT NOT NULL DEFAULT 'off_chain', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_fee_ledger_user ON fee_ledger(user_pubkey); -CREATE INDEX IF NOT EXISTS idx_fee_ledger_transfer ON fee_ledger(transfer_id); - --- ============================================================ --- user_tiers: tracks user pricing tier --- ============================================================ -CREATE TABLE IF NOT EXISTS user_tiers ( - pubkey TEXT PRIMARY KEY, - tier TEXT NOT NULL DEFAULT 'free', - upgraded_at TIMESTAMPTZ, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - --- ============================================================ --- transaction_status: WebSocket-driven transaction tracking --- ============================================================ -CREATE TABLE IF NOT EXISTS transaction_status ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - type TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - from_pubkey TEXT, - to_pubkey TEXT, - amount BIGINT, - metadata JSONB, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - completed_at TIMESTAMPTZ -); - -CREATE INDEX IF NOT EXISTS idx_transaction_status_from ON transaction_status(from_pubkey); -CREATE INDEX IF NOT EXISTS idx_transaction_status_to ON transaction_status(to_pubkey); -CREATE INDEX IF NOT EXISTS idx_transaction_status_status ON transaction_status(status); - --- ============================================================ --- Security tables (re-create with IF NOT EXISTS for safety) --- ============================================================ -CREATE TABLE IF NOT EXISTS revocation_secrets ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - channel_id UUID NOT NULL, - sequence INTEGER NOT NULL, - secret TEXT NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE(channel_id, sequence) -); - -CREATE INDEX IF NOT EXISTS idx_revocation_secrets_channel ON revocation_secrets(channel_id); - -CREATE TABLE IF NOT EXISTS disputes ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - channel_id UUID NOT NULL, - initiated_by TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'open', - latest_sequence INTEGER NOT NULL, - challenge_deadline TIMESTAMPTZ NOT NULL, - broadcast_txid TEXT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE(channel_id) -); - -CREATE INDEX IF NOT EXISTS idx_disputes_status ON disputes(status); - -CREATE TABLE IF NOT EXISTS breach_attempts ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - channel_id UUID NOT NULL, - detected_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - breach_txid TEXT NOT NULL, - breach_tx_hex TEXT, - penalty_txid TEXT, - penalty_tx_hex TEXT, - status TEXT NOT NULL DEFAULT 'detected', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_breach_attempts_channel ON breach_attempts(channel_id); -CREATE INDEX IF NOT EXISTS idx_breach_attempts_status ON breach_attempts(status); - --- ============================================================ --- DB constraints --- ============================================================ - --- Ensure channel balances never go negative -DO $$ -BEGIN - IF NOT EXISTS ( - SELECT 1 FROM pg_constraint WHERE conname = 'channels_balance_positive' - ) THEN - ALTER TABLE channels ADD CONSTRAINT channels_balance_positive - CHECK (local_balance >= 0 AND remote_balance >= 0); - END IF; -END $$; - --- Ensure transfer nonces are unique (may already exist from migration 001_security_fixes) --- The nonce column already has UNIQUE constraint from ALTER TABLE, skip if exists - --- Remove FK constraint on challenges.pubkey so new users can auth before existing in users table -ALTER TABLE challenges DROP CONSTRAINT IF EXISTS challenges_pubkey_fkey; diff --git a/legacy/taproot-assets-era/backend/src/db/schema.sql b/legacy/taproot-assets-era/backend/src/db/schema.sql deleted file mode 100644 index f7a7316..0000000 --- a/legacy/taproot-assets-era/backend/src/db/schema.sql +++ /dev/null @@ -1,113 +0,0 @@ -CREATE TABLE IF NOT EXISTS channels ( - id TEXT PRIMARY KEY, - user_pubkey TEXT NOT NULL, - runebolt_pubkey TEXT NOT NULL, - funding_txid TEXT, - funding_vout INTEGER, - capacity BIGINT NOT NULL DEFAULT 0, - local_balance BIGINT NOT NULL DEFAULT 0, - remote_balance BIGINT NOT NULL DEFAULT 0, - state TEXT NOT NULL DEFAULT 'PENDING_OPEN', - created_at TEXT NOT NULL DEFAULT (datetime('now')), - updated_at TEXT NOT NULL DEFAULT (datetime('now')) -); - -CREATE INDEX IF NOT EXISTS idx_channels_user_pubkey ON channels(user_pubkey); -CREATE INDEX IF NOT EXISTS idx_channels_state ON channels(state); - -CREATE TABLE IF NOT EXISTS transfers ( - id TEXT PRIMARY KEY, - from_channel TEXT NOT NULL, - to_channel TEXT NOT NULL, - amount BIGINT NOT NULL, - memo TEXT, - nonce TEXT UNIQUE, -- REPLAY PROTECTION: prevents double-spends - client_signature TEXT, -- Client signature for the transfer - transfer_hash TEXT, -- Hash of transfer details for verification - created_at TEXT NOT NULL DEFAULT (datetime('now')), - FOREIGN KEY (from_channel) REFERENCES channels(id), - FOREIGN KEY (to_channel) REFERENCES channels(id) -); - -CREATE INDEX IF NOT EXISTS idx_transfers_from ON transfers(from_channel); -CREATE INDEX IF NOT EXISTS idx_transfers_to ON transfers(to_channel); -CREATE INDEX IF NOT EXISTS idx_transfers_nonce ON transfers(nonce); -- Fast nonce lookups for replay protection - -CREATE TABLE IF NOT EXISTS users ( - pubkey TEXT PRIMARY KEY, - username TEXT UNIQUE, - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); - -CREATE INDEX IF NOT EXISTS idx_users_username ON users(username); - -CREATE TABLE IF NOT EXISTS claim_links ( - id TEXT PRIMARY KEY, - creator_pubkey TEXT NOT NULL, - amount BIGINT NOT NULL, - memo TEXT, - claimed_by TEXT, - claimed_at TEXT, - created_at TEXT NOT NULL DEFAULT (datetime('now')), - expires_at TEXT NOT NULL -); - -CREATE INDEX IF NOT EXISTS idx_claim_links_creator ON claim_links(creator_pubkey); - -CREATE TABLE IF NOT EXISTS challenges ( - id TEXT PRIMARY KEY, - pubkey TEXT NOT NULL, - challenge TEXT NOT NULL, - expires_at TEXT NOT NULL -); - -CREATE INDEX IF NOT EXISTS idx_challenges_pubkey ON challenges(pubkey); - --- Commitments table for persistent storage of channel commitment states -CREATE TABLE IF NOT EXISTS commitments ( - id TEXT PRIMARY KEY, - channel_id TEXT NOT NULL, - sequence INTEGER NOT NULL, - local_balance TEXT NOT NULL, -- Stored as TEXT for BigInt - remote_balance TEXT NOT NULL, - hash TEXT NOT NULL, - local_signature TEXT, - remote_signature TEXT, - revocation_secret TEXT, -- For penalty transactions - revocation_hash TEXT, -- Hash of revocation secret - is_revoked INTEGER DEFAULT 0, -- Boolean flag - created_at TEXT NOT NULL DEFAULT (datetime('now')), - FOREIGN KEY (channel_id) REFERENCES channels(id), - UNIQUE(channel_id, sequence) -); - -CREATE INDEX IF NOT EXISTS idx_commitments_channel ON commitments(channel_id); -CREATE INDEX IF NOT EXISTS idx_commitments_channel_sequence ON commitments(channel_id, sequence); - --- Idempotency table for API requests to prevent duplicate operations -CREATE TABLE IF NOT EXISTS idempotent_requests ( - key TEXT PRIMARY KEY, - response TEXT NOT NULL, - created_at TEXT NOT NULL DEFAULT (datetime('now')) -); - -CREATE INDEX IF NOT EXISTS idx_idempotent_requests_created ON idempotent_requests(created_at); - --- Transaction status tracking for real-time WebSocket updates -CREATE TABLE IF NOT EXISTS transaction_status ( - id TEXT PRIMARY KEY, - type TEXT NOT NULL, -- 'transfer', 'claim', 'deposit', 'withdrawal' - status TEXT NOT NULL DEFAULT 'pending', -- 'pending', 'confirming', 'confirmed', 'failed' - from_pubkey TEXT, - to_pubkey TEXT, - amount BIGINT, - metadata TEXT, -- JSON blob for additional data - created_at TEXT NOT NULL DEFAULT (datetime('now')), - updated_at TEXT NOT NULL DEFAULT (datetime('now')), - completed_at TEXT -); - -CREATE INDEX IF NOT EXISTS idx_transaction_status_from ON transaction_status(from_pubkey); -CREATE INDEX IF NOT EXISTS idx_transaction_status_to ON transaction_status(to_pubkey); -CREATE INDEX IF NOT EXISTS idx_transaction_status_status ON transaction_status(status); -CREATE INDEX IF NOT EXISTS idx_transaction_status_updated ON transaction_status(updated_at); diff --git a/legacy/taproot-assets-era/backend/src/fees/FeeManager.ts b/legacy/taproot-assets-era/backend/src/fees/FeeManager.ts deleted file mode 100644 index 882c50d..0000000 --- a/legacy/taproot-assets-era/backend/src/fees/FeeManager.ts +++ /dev/null @@ -1,161 +0,0 @@ -/** - * FeeManager — calculates and records fees for RuneBolt transfers. - * - * Free tier: first 500 transactions per user are free. - * After free tier: - * - Off-chain transfer fee: 0.1% - * - Settlement (on-chain) fee: 0.5% - */ - -import Database from '../db/Database'; - -const FREE_TIER_LIMIT = 500; -const OFF_CHAIN_FEE_RATE = 0.001; // 0.1% -const SETTLEMENT_FEE_RATE = 0.005; // 0.5% - -export type FeeType = 'off_chain' | 'settlement'; - -export interface FeeCalculation { - feeAmount: bigint; - feeRate: number; - feeType: FeeType; - isFree: boolean; - freeTransactionsRemaining: number; -} - -export interface FeeRecord { - transferId: string; - pubkey: string; - amount: bigint; - feeType: FeeType; - feeRate: number; -} - -export class FeeManager { - private db: Database; - - constructor() { - this.db = Database.getInstance(); - } - - /** - * Calculate the fee for a transfer based on user tier and transaction count. - */ - async calculateFee( - pubkey: string, - transferAmount: bigint, - feeType: FeeType = 'off_chain' - ): Promise { - const txCount = await this.db.getTransactionCount(pubkey); - const currentCount = txCount?.count ?? 0; - const remaining = Math.max(0, FREE_TIER_LIMIT - currentCount); - - if (remaining > 0) { - return { - feeAmount: 0n, - feeRate: 0, - feeType, - isFree: true, - freeTransactionsRemaining: remaining - 1, // will decrement after this tx - }; - } - - const rate = feeType === 'settlement' ? SETTLEMENT_FEE_RATE : OFF_CHAIN_FEE_RATE; - // Pure BigInt arithmetic: multiply by scaled rate, then divide to avoid Number precision loss - const scaledRate = BigInt(Math.round(rate * 1_000_000)); - const feeAmount = (transferAmount * scaledRate + 999_999n) / 1_000_000n; // ceil division - - return { - feeAmount, - feeRate: rate, - feeType, - isFree: false, - freeTransactionsRemaining: 0, - }; - } - - /** - * Record a fee and increment the user's transaction count. - * Call this after a successful transfer. - */ - async recordFee( - transferId: string, - pubkey: string, - feeCalc: FeeCalculation - ): Promise { - // Always increment transaction count - await this.db.incrementTransactionCount(pubkey); - - // Record in fee_ledger (tracks all transactions including free ones) - await this.db.query( - `INSERT INTO fee_ledger (user_pubkey, transfer_id, fee_amount, fee_type) - VALUES ($1, $2, $3, $4)`, - [pubkey, transferId, feeCalc.feeAmount.toString(), feeCalc.isFree ? 'free' : feeCalc.feeType] - ); - - // Update free_remaining and total_fees_paid in user_transaction_counts - await this.db.query( - `UPDATE user_transaction_counts - SET free_remaining = GREATEST(0, 500 - count), - total_fees_paid = total_fees_paid + $1 - WHERE pubkey = $2`, - [feeCalc.feeAmount.toString(), pubkey] - ); - - // Only record a fee_records entry if there was a non-zero fee - if (feeCalc.feeAmount > 0n) { - await this.db.createFeeRecord({ - transfer_id: transferId, - pubkey, - amount: feeCalc.feeAmount.toString(), - fee_type: feeCalc.feeType, - fee_rate: feeCalc.feeRate, - }); - } - - // Auto-upgrade tier when free transactions are exhausted - if (feeCalc.freeTransactionsRemaining === 0 && feeCalc.isFree) { - await this.db.updateUserTier(pubkey, 'standard'); - } - } - - /** - * Get the number of free transactions remaining for a user. - */ - async getFreeTransactionsRemaining(pubkey: string): Promise { - const txCount = await this.db.getTransactionCount(pubkey); - const currentCount = txCount?.count ?? 0; - return Math.max(0, FREE_TIER_LIMIT - currentCount); - } - - /** - * Get user tier info for API responses. - */ - async getUserTierInfo(pubkey: string): Promise<{ - tier: string; - transactionCount: number; - freeTransactionsRemaining: number; - feeRates: { offChain: string; settlement: string }; - }> { - const [tierRow, txCount] = await Promise.all([ - this.db.getUserTier(pubkey), - this.db.getTransactionCount(pubkey), - ]); - - const currentCount = txCount?.count ?? 0; - const remaining = Math.max(0, FREE_TIER_LIMIT - currentCount); - const tier = tierRow?.tier ?? 'free'; - - return { - tier, - transactionCount: currentCount, - freeTransactionsRemaining: remaining, - feeRates: { - offChain: remaining > 0 ? '0%' : `${OFF_CHAIN_FEE_RATE * 100}%`, - settlement: remaining > 0 ? '0%' : `${SETTLEMENT_FEE_RATE * 100}%`, - }, - }; - } -} - -export default FeeManager; diff --git a/legacy/taproot-assets-era/backend/src/index.ts b/legacy/taproot-assets-era/backend/src/index.ts deleted file mode 100644 index 9b74341..0000000 --- a/legacy/taproot-assets-era/backend/src/index.ts +++ /dev/null @@ -1,191 +0,0 @@ -/** - * RuneBolt Backend — Hub-based Rune payment channel server - * PRODUCTION VERSION - Optimized & Secure - */ - -import dotenv from 'dotenv'; -dotenv.config(); - -import express from 'express'; -import cors from 'cors'; -import helmet from 'helmet'; -import http from 'http'; -import rateLimit from 'express-rate-limit'; - -// Database -import Database from './db/Database'; - -// Security config -import { rateLimits } from './config/security'; - -// Mainnet startup checks -import { runMainnetChecks } from './config/mainnet-checks'; - -// API routes -import channelRoutes from './api/routes/channelRoutes'; -import transferRoutes from './api/routes/transferRoutes'; -import userRoutes from './api/routes/userRoutes'; -import claimRoutes from './api/routes/claimRoutes'; -import authRoutes from './api/routes/authRoutes'; -import wellKnownRoutes from './api/routes/wellKnownRoutes'; -import feeRoutes from './api/routes/feeRoutes'; -import statsRoutes from './api/routes/statsRoutes'; -import assetRoutes from './api/routes/assetRoutes'; - -// Cache -import { getCache } from './cache/RedisCache'; - -const PORT = parseInt(process.env.PORT || '3141', 10); -const isProduction = process.env.NODE_ENV === 'production'; -const startTime = Date.now(); - -// Initialize database -const db = Database.getInstance(); -db.initialize(); - -// Initialize Express app -const app = express(); -const server = http.createServer(app); - -// Security middleware -app.use(helmet({ - contentSecurityPolicy: false, - crossOriginEmbedderPolicy: false, -})); - -// CORS — locked down in production, permissive in development -const corsOrigin = process.env.CORS_ORIGIN; -app.use(cors({ - origin: isProduction - ? corsOrigin - ? corsOrigin.split(',').map(o => o.trim()) - : false - : corsOrigin || '*', - credentials: true, - methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], - allowedHeaders: ['Content-Type', 'Authorization'], -})); - -app.use(express.json({ limit: '1mb' })); - -// Rate limiting -const authLimiter = rateLimit({ - windowMs: rateLimits.auth.windowMs, - max: rateLimits.auth.max, - message: { success: false, error: 'Too many authentication attempts, try again later' }, - standardHeaders: true, - legacyHeaders: false, -}); - -const transferLimiter = rateLimit({ - windowMs: rateLimits.transfer.windowMs, - max: rateLimits.transfer.max, - message: { success: false, error: 'Transfer rate limit exceeded, try again later' }, - standardHeaders: true, - legacyHeaders: false, -}); - -const generalLimiter = rateLimit({ - windowMs: rateLimits.general.windowMs, - max: rateLimits.general.max, - message: { success: false, error: 'API rate limit exceeded, try again later' }, - standardHeaders: true, - legacyHeaders: false, -}); - -// Apply general rate limit to all API routes -app.use('/api/', generalLimiter); - -// Request logging -app.use((_req, _res, next) => { - console.log(`[${new Date().toISOString()}] ${_req.method} ${_req.path}`); - next(); -}); - -// Health check endpoint with detailed checks (not rate limited) -app.get('/health', async (_req, res) => { - const dbHealth = await db.healthCheck(); - const cache = getCache(); - const redisConnected = cache.connected(); - - const status = dbHealth.healthy ? 'ok' : 'degraded'; - - res.status(dbHealth.healthy ? 200 : 503).json({ - status, - service: 'runebolt-backend', - version: '0.2.0', - uptime: Math.floor((Date.now() - startTime) / 1000), - timestamp: new Date().toISOString(), - checks: { - database: { - status: dbHealth.healthy ? 'ok' : 'error', - latencyMs: dbHealth.latency, - pool: db.getPoolMetrics(), - ...(dbHealth.error ? { error: dbHealth.error } : {}), - }, - redis: { - status: redisConnected ? 'ok' : 'unavailable', - }, - }, - }); -}); - -// API routes with specific rate limiters -app.use('/api/v1/auth', authLimiter, authRoutes); -app.use('/api/v1/transfers', transferLimiter, transferRoutes); -app.use('/api/v1/channels', channelRoutes); -app.use('/api/v1/users', userRoutes); -app.use('/api/v1/claims', claimRoutes); -app.use('/api/v1/fees', feeRoutes); -app.use('/api/v1', statsRoutes); -app.use('/api/v1', assetRoutes); -app.use('/.well-known', wellKnownRoutes); - -// Root endpoint -app.get('/', (_req, res) => { - res.json({ - name: 'RuneBolt Backend', - version: '0.2.0', - description: 'Hub-based Rune payment channel server', - endpoints: { - health: '/health', - channels: '/api/v1/channels', - transfers: '/api/v1/transfers', - users: '/api/v1/users', - claims: '/api/v1/claims', - auth: '/api/v1/auth', - fees: '/api/v1/fees', - stats: '/api/v1/stats', - assets: '/api/v1/assets', - escrow: '/api/v1/escrow', - }, - }); -}); - -// Error handling — sanitize messages in production -app.use((err: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => { - console.error('Error:', err); - res.status(500).json({ - error: 'Internal server error', - message: isProduction ? undefined : err.message, - }); -}); - -// Run mainnet checks, then start server -(async () => { - const checksOk = await runMainnetChecks(); - if (!checksOk) { - console.error('[RuneBolt] CRITICAL checks failed — refusing to start'); - process.exit(1); - } - - server.listen(PORT, '0.0.0.0', () => { - console.log(`[RuneBolt] Server running on port ${PORT}`); - console.log(`[RuneBolt] Environment: ${isProduction ? 'production' : 'development'}`); - console.log(`[RuneBolt] CORS origin: ${isProduction ? (corsOrigin || 'LOCKED DOWN') : 'permissive'}`); - console.log(`[RuneBolt] Rate limiting: enabled`); - console.log(`[RuneBolt] Health check: http://localhost:${PORT}/health`); - }); -})(); - -export default app; diff --git a/legacy/taproot-assets-era/backend/src/ledger/RuneLedger.ts b/legacy/taproot-assets-era/backend/src/ledger/RuneLedger.ts deleted file mode 100644 index 43f22f8..0000000 --- a/legacy/taproot-assets-era/backend/src/ledger/RuneLedger.ts +++ /dev/null @@ -1,452 +0,0 @@ -/** - * RuneLedger — the off-chain ledger for Rune transfers between channels. - * - * OPTIMIZED VERSION for mass adoption: - * - Redis caching for sub-millisecond balance lookups - * - Worker thread pool for non-blocking transfer execution - * - Batch processing for high-throughput scenarios - * - Cache invalidation on state changes - * - * SECURITY FEATURES: - * - Nonce-based replay attack prevention - * - Client-side signature verification - * - Double-spend prevention via database transaction - */ - -import { v4 as uuidv4 } from 'uuid'; -import * as secp256k1 from '@noble/secp256k1'; -import { sha256 } from '@noble/hashes/sha2.js'; -import Database from '../db/Database'; -import { ChannelState, channelFromRow } from '../channels/ChannelState'; -import { CommitmentManager } from '../channels/CommitmentManager'; -import { Transfer } from './Transfer'; -import { getCache, RedisCache } from '../cache/RedisCache'; -import { getTransferWorkerPool, TransferWorkerPool } from '../workers/TransferWorker'; -import { validateTransferAgainstReserve } from '../channels/ChannelReserves'; - -/** Maximum safe BigInt amount — mirrors Number.MAX_SAFE_INTEGER */ -const MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER); - -interface TransferOptions { - skipCache?: boolean; - useWorker?: boolean; -} - -export class RuneLedger { - private db: Database; - private cache: RedisCache; - private workerPool: TransferWorkerPool; - private batchMode: boolean = false; - private batchQueue: Array<{ - fromChannelId: string; - toChannelId: string; - amount: bigint; - memo?: string; - resolve: (transfer: Transfer) => void; - reject: (error: Error) => void; - }> = []; - private batchTimer: NodeJS.Timeout | null = null; - private readonly BATCH_SIZE = 100; - private readonly BATCH_FLUSH_MS = 50; - - constructor() { - this.db = Database.getInstance(); - this.cache = getCache(); - this.workerPool = getTransferWorkerPool(); - } - - /** - * Enable batch mode for high-throughput processing. - */ - enableBatchMode(): void { - this.batchMode = true; - this.startBatchTimer(); - console.log('[RuneLedger] Batch mode enabled'); - } - - /** - * Disable batch mode and flush remaining transfers. - */ - async disableBatchMode(): Promise { - this.batchMode = false; - if (this.batchTimer) { - clearInterval(this.batchTimer); - this.batchTimer = null; - } - await this.flushBatch(); - console.log('[RuneLedger] Batch mode disabled'); - } - - private startBatchTimer(): void { - this.batchTimer = setInterval(() => { - if (this.batchQueue.length > 0) { - this.flushBatch(); - } - }, this.BATCH_FLUSH_MS); - } - - private async flushBatch(): Promise { - if (this.batchQueue.length === 0) return; - - const batch = this.batchQueue.splice(0, this.BATCH_SIZE); - console.log(`[RuneLedger] Flushing batch of ${batch.length} transfers`); - - await this.db.transaction(async () => { - for (const item of batch) { - try { - const transfer = await this.executeTransferInternal( - item.fromChannelId, - item.toChannelId, - item.amount, - item.memo - ); - item.resolve(transfer); - } catch (err) { - item.reject(err instanceof Error ? err : new Error(String(err))); - } - } - }); - } - - /** - * Execute a transfer between two channels. - */ - async transfer( - fromChannelId: string, - toChannelId: string, - amount: bigint, - memo: string | undefined, - nonce: string, - clientSignature: string, - _senderPubkey: string, - options: TransferOptions = {} - ): Promise { - if (amount <= 0n) { - throw new Error('Transfer amount must be positive'); - } - - // SECURITY: Overflow protection - if (amount > MAX_SAFE_BIGINT) { - throw new Error('Transfer amount exceeds maximum safe value'); - } - - if (fromChannelId === toChannelId) { - throw new Error('Cannot transfer to the same channel'); - } - - // SECURITY: Enforce nonce uniqueness to prevent replay attacks - if (nonce) { - const existingTransfer = await this.db.getTransferByNonce(nonce); - if (existingTransfer) { - throw new Error('Transfer nonce already used (replay attack prevented)'); - } - } - - // SECURITY: Verify client signature over transfer parameters - if (clientSignature && _senderPubkey) { - const message = `${fromChannelId}${toChannelId}${amount.toString()}${nonce}`; - const messageHash = sha256(new TextEncoder().encode(message)); - try { - const sigBytes = Uint8Array.from(Buffer.from(clientSignature, 'hex')); - const pubkeyBytes = Uint8Array.from(Buffer.from(_senderPubkey, 'hex')); - const valid = secp256k1.schnorr.verify(sigBytes, messageHash, pubkeyBytes); - if (!valid) { - throw new Error('Invalid transfer signature'); - } - } catch (err) { - if (err instanceof Error && err.message === 'Invalid transfer signature') { - throw err; - } - throw new Error('Transfer signature verification failed: ' + (err instanceof Error ? err.message : String(err))); - } - } - - if (this.batchMode) { - return new Promise((resolve, reject) => { - this.batchQueue.push({ fromChannelId, toChannelId, amount, memo, resolve, reject }); - if (this.batchQueue.length >= this.BATCH_SIZE) { - this.flushBatch(); - } - }); - } - - let fromBalance = options.skipCache ? null : await this.cache.getChannelBalance(fromChannelId); - let toBalance = options.skipCache ? null : await this.cache.getChannelBalance(toChannelId); - - if (!fromBalance) { - const fromRow = await this.db.getChannel(fromChannelId); - if (!fromRow) throw new Error(`Sender channel ${fromChannelId} not found`); - const channel = channelFromRow(fromRow); - fromBalance = { local: channel.localBalance, remote: channel.remoteBalance, capacity: channel.capacity }; - await this.cache.setChannelBalance(fromChannelId, fromBalance); - } - - if (!toBalance) { - const toRow = await this.db.getChannel(toChannelId); - if (!toRow) throw new Error(`Recipient channel ${toChannelId} not found`); - const channel = channelFromRow(toRow); - toBalance = { local: channel.localBalance, remote: channel.remoteBalance, capacity: channel.capacity }; - await this.cache.setChannelBalance(toChannelId, toBalance); - } - - if (fromBalance.local < amount) { - throw new Error(`Insufficient balance in channel ${fromChannelId}`); - } - - // SECURITY: Check reserve — sender must retain 1% of capacity after transfer - if (!validateTransferAgainstReserve(fromBalance.local, fromBalance.capacity, amount)) { - throw new Error(`Transfer would violate channel reserve in ${fromChannelId}`); - } - - if (toBalance.remote < amount) { - throw new Error(`Insufficient inbound capacity in channel ${toChannelId}`); - } - - let transfer: Transfer; - if (options.useWorker !== false) { - transfer = await this.executeTransferWithWorker(fromChannelId, toChannelId, fromBalance, toBalance, amount, memo, { nonce, clientSignature }); - } else { - transfer = await this.executeTransferSync(fromChannelId, toChannelId, amount, memo, { nonce, clientSignature }); - } - - // Structured audit log for every transfer - console.log(JSON.stringify({ - audit: 'transfer', - id: transfer.id, - from: fromChannelId, - to: toChannelId, - amount: amount.toString(), - nonce, - timestamp: transfer.createdAt, - })); - - return transfer; - } - - private async executeTransferWithWorker( - fromChannelId: string, - toChannelId: string, - fromBalance: { local: bigint; remote: bigint; capacity: bigint }, - toBalance: { local: bigint; remote: bigint; capacity: bigint }, - amount: bigint, - memo: string | undefined, - security: { nonce: string; clientSignature: string } - ): Promise { - const transferId = uuidv4(); - - const workerResult = await this.workerPool.executeTransfer({ - id: transferId, - fromChannel: fromChannelId, - toChannel: toChannelId, - fromBalance: { local: fromBalance.local.toString(), remote: fromBalance.remote.toString() }, - toBalance: { local: toBalance.local.toString(), remote: toBalance.remote.toString() }, - amount: amount.toString(), - memo, - }); - - if (!workerResult.success) { - throw new Error(workerResult.error || 'Transfer failed in worker'); - } - - const transfer = await this.db.transaction(async () => { - await this.db.updateChannelBalances(fromChannelId, workerResult.newFromBalance!.local, workerResult.newFromBalance!.remote); - await this.db.updateChannelBalances(toChannelId, workerResult.newToBalance!.local, workerResult.newToBalance!.remote); - await this.db.createTransfer({ id: transferId, from_channel: fromChannelId, to_channel: toChannelId, amount: amount.toString(), memo: memo || null, nonce: security.nonce, client_signature: security.clientSignature }); - - const fromCommitment = await CommitmentManager.getLatestCommitment(fromChannelId); - const toCommitment = await CommitmentManager.getLatestCommitment(toChannelId); - - await CommitmentManager.createCommitment(fromChannelId, BigInt(workerResult.newFromBalance!.local), BigInt(workerResult.newFromBalance!.remote), (fromCommitment?.sequence ?? 0) + 1); - await CommitmentManager.createCommitment(toChannelId, BigInt(workerResult.newToBalance!.local), BigInt(workerResult.newToBalance!.remote), (toCommitment?.sequence ?? 0) + 1); - - return { - id: transferId, - fromChannel: fromChannelId, - toChannel: toChannelId, - amount, - memo: memo || null, - nonce: security.nonce, - clientSignature: security.clientSignature, - transferHash: '', - createdAt: workerResult.timestamp, - } satisfies Transfer; - }); - - await this.cache.setChannelBalance(fromChannelId, { local: BigInt(workerResult.newFromBalance!.local), remote: BigInt(workerResult.newFromBalance!.remote), capacity: fromBalance.capacity }); - await this.cache.setChannelBalance(toChannelId, { local: BigInt(workerResult.newToBalance!.local), remote: BigInt(workerResult.newToBalance!.remote), capacity: toBalance.capacity }); - await this.cache.markHotChannel(fromChannelId); - await this.cache.markHotChannel(toChannelId); - - return transfer; - } - - private async executeTransferSync(fromChannelId: string, toChannelId: string, amount: bigint, memo: string | undefined, security: { nonce: string; clientSignature: string }): Promise { - return this.db.transaction(async () => { - const fromRow = await this.db.getChannel(fromChannelId); - if (!fromRow) throw new Error(`Sender channel ${fromChannelId} not found`); - const fromChannel = channelFromRow(fromRow); - if (fromChannel.state !== ChannelState.OPEN) throw new Error(`Sender channel ${fromChannelId} is not OPEN`); - - const toRow = await this.db.getChannel(toChannelId); - if (!toRow) throw new Error(`Recipient channel ${toChannelId} not found`); - const toChannel = channelFromRow(toRow); - if (toChannel.state !== ChannelState.OPEN) throw new Error(`Recipient channel ${toChannelId} is not OPEN`); - - if (fromChannel.localBalance < amount) throw new Error(`Insufficient balance in channel ${fromChannelId}`); - if (toChannel.remoteBalance < amount) throw new Error(`Insufficient inbound capacity in channel ${toChannelId}`); - - const newFromLocal = fromChannel.localBalance - amount; - const newFromRemote = fromChannel.remoteBalance + amount; - const newToLocal = toChannel.localBalance + amount; - const newToRemote = toChannel.remoteBalance - amount; - - await this.db.updateChannelBalances(fromChannelId, newFromLocal.toString(), newFromRemote.toString()); - await this.db.updateChannelBalances(toChannelId, newToLocal.toString(), newToRemote.toString()); - - const transferId = uuidv4(); - await this.db.createTransfer({ id: transferId, from_channel: fromChannelId, to_channel: toChannelId, amount: amount.toString(), memo: memo || null, nonce: security.nonce, client_signature: security.clientSignature }); - - const fromCommitment = await CommitmentManager.getLatestCommitment(fromChannelId); - const toCommitment = await CommitmentManager.getLatestCommitment(toChannelId); - - await CommitmentManager.createCommitment(fromChannelId, newFromLocal, newFromRemote, (fromCommitment?.sequence ?? 0) + 1); - await CommitmentManager.createCommitment(toChannelId, newToLocal, newToRemote, (toCommitment?.sequence ?? 0) + 1); - - await this.cache.setChannelBalance(fromChannelId, { local: newFromLocal, remote: newFromRemote, capacity: fromChannel.capacity }); - await this.cache.setChannelBalance(toChannelId, { local: newToLocal, remote: newToRemote, capacity: toChannel.capacity }); - - return { - id: transferId, - fromChannel: fromChannelId, - toChannel: toChannelId, - amount, - memo: memo || null, - nonce: security.nonce, - clientSignature: security.clientSignature, - transferHash: '', - createdAt: new Date().toISOString(), - } satisfies Transfer; - }); - } - - private async executeTransferInternal(fromChannelId: string, toChannelId: string, amount: bigint, memo?: string): Promise { - const fromRow = await this.db.getChannel(fromChannelId); - if (!fromRow) throw new Error(`Sender channel ${fromChannelId} not found`); - const fromChannel = channelFromRow(fromRow); - if (fromChannel.state !== ChannelState.OPEN) throw new Error(`Sender channel ${fromChannelId} is not OPEN`); - - const toRow = await this.db.getChannel(toChannelId); - if (!toRow) throw new Error(`Recipient channel ${toChannelId} not found`); - const toChannel = channelFromRow(toRow); - if (toChannel.state !== ChannelState.OPEN) throw new Error(`Recipient channel ${toChannelId} is not OPEN`); - - if (fromChannel.localBalance < amount) throw new Error(`Insufficient balance in channel ${fromChannelId}`); - if (toChannel.remoteBalance < amount) throw new Error(`Insufficient inbound capacity in channel ${toChannelId}`); - - const newFromLocal = fromChannel.localBalance - amount; - const newFromRemote = fromChannel.remoteBalance + amount; - const newToLocal = toChannel.localBalance + amount; - const newToRemote = toChannel.remoteBalance - amount; - - await this.db.updateChannelBalances(fromChannelId, newFromLocal.toString(), newFromRemote.toString()); - await this.db.updateChannelBalances(toChannelId, newToLocal.toString(), newToRemote.toString()); - - const transferId = uuidv4(); - await this.db.createTransfer({ id: transferId, from_channel: fromChannelId, to_channel: toChannelId, amount: amount.toString(), memo: memo || null }); - - await this.cache.setChannelBalance(fromChannelId, { local: newFromLocal, remote: newFromRemote, capacity: fromChannel.capacity }); - await this.cache.setChannelBalance(toChannelId, { local: newToLocal, remote: newToRemote, capacity: toChannel.capacity }); - - return { - id: transferId, - fromChannel: fromChannelId, - toChannel: toChannelId, - amount, - memo: memo || null, - nonce: '', - clientSignature: '', - transferHash: '', - createdAt: new Date().toISOString(), - }; - } - - /** - * Get the current balance of a channel (cached). - */ - async getBalance(channelId: string): Promise<{ local: bigint; remote: bigint; capacity: bigint }> { - const cached = await this.cache.getChannelBalance(channelId); - if (cached) return cached; - - const row = await this.db.getChannel(channelId); - if (!row) throw new Error(`Channel ${channelId} not found`); - - const channel = channelFromRow(row); - const balance = { local: channel.localBalance, remote: channel.remoteBalance, capacity: channel.capacity }; - await this.cache.setChannelBalance(channelId, balance); - return balance; - } - - /** - * Get transfer history for a user. - */ - async getTransferHistory(pubkey: string, limit: number = 50, offset: number = 0): Promise { - const rows = await this.db.getTransfersByPubkey(pubkey, limit, offset); - return rows.map((row) => ({ - id: row.id, - fromChannel: row.from_channel, - toChannel: row.to_channel, - amount: BigInt(row.amount), - memo: row.memo, - nonce: '', - clientSignature: '', - transferHash: '', - createdAt: row.created_at, - })); - } - - /** - * Find an open channel for a given pubkey. - */ - async findOpenChannelForPubkey(pubkey: string): Promise { - const cached = await this.cache.getUserChannels(pubkey); - if (cached) { - for (const channelId of cached) { - const state = await this.cache.getChannelState(channelId); - if (state === ChannelState.OPEN) return channelId; - } - } - - const channels = await this.db.getChannelsByPubkey(pubkey); - const channelIds = channels.map(ch => ch.id); - await this.cache.setUserChannels(pubkey, channelIds); - - for (const ch of channels) { - await this.cache.setChannelState(ch.id, ch.state); - if (ch.state === ChannelState.OPEN) return ch.id; - } - return null; - } - - /** - * Invalidate cache for a channel. - */ - async invalidateChannelCache(channelId: string): Promise { - await this.cache.invalidateChannelBalance(channelId); - } - - /** - * Get hot channels (high activity). - */ - async getHotChannels(limit: number = 100): Promise { - return this.cache.getHotChannels(limit); - } - - /** - * Get ledger statistics. - */ - getStats(): { batchQueueSize: number; workerPoolStats: ReturnType } { - return { batchQueueSize: this.batchQueue.length, workerPoolStats: this.workerPool.getStats() }; - } -} - -export default RuneLedger; diff --git a/legacy/taproot-assets-era/backend/src/ledger/Transfer.ts b/legacy/taproot-assets-era/backend/src/ledger/Transfer.ts deleted file mode 100644 index df3055d..0000000 --- a/legacy/taproot-assets-era/backend/src/ledger/Transfer.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Transfer type definitions and validation schemas. - */ - -import { z } from 'zod'; - -export interface Transfer { - id: string; - fromChannel: string; - toChannel: string; - amount: bigint; - memo: string | null; - nonce: string; // REQUIRED - prevents replay - clientSignature: string; // REQUIRED - client signs transfer - transferHash: string; // Hash of transfer details - createdAt: string; -} - -export interface TransferRequest { - fromChannelId: string; - toChannelId?: string; - recipientPubkey?: string; - amount: bigint; - memo?: string; - nonce: string; // REQUIRED - prevents replay - signature: string; // REQUIRED - client signature -} - -/** - * Zod schema for transfer request body validation. - */ -export const TransferRequestSchema = z - .object({ - fromChannelId: z.string().uuid('Invalid fromChannelId format'), - toChannelId: z.string().uuid('Invalid toChannelId format').optional(), - recipientPubkey: z - .string() - .min(64, 'Public key must be at least 64 characters') - .max(66, 'Public key must be at most 66 characters') - .optional(), - amount: z.string().regex(/^\d+$/, 'Amount must be a numeric string'), - memo: z.string().max(256, 'Memo must be 256 characters or less').optional(), - nonce: z.string().uuid(), // REQUIRED - prevents replay attacks - signature: z.string().min(128, 'Signature must be at least 128 characters'), // REQUIRED - client signature - }) - .refine((data) => data.toChannelId || data.recipientPubkey, { - message: 'Either toChannelId or recipientPubkey must be provided', - }); - -/** - * Serialize a Transfer for JSON responses (bigints -> strings). - */ -export function transferToJson(transfer: Transfer): Record { - return { - id: transfer.id, - fromChannel: transfer.fromChannel, - toChannel: transfer.toChannel, - amount: transfer.amount.toString(), - memo: transfer.memo, - nonce: transfer.nonce, - transferHash: transfer.transferHash, - createdAt: transfer.createdAt, - }; -} diff --git a/legacy/taproot-assets-era/backend/src/monitoring/metrics.ts b/legacy/taproot-assets-era/backend/src/monitoring/metrics.ts deleted file mode 100644 index 7e7ee0b..0000000 --- a/legacy/taproot-assets-era/backend/src/monitoring/metrics.ts +++ /dev/null @@ -1,201 +0,0 @@ -/** - * Prometheus metrics setup for RuneBolt monitoring. - * - * Metrics exposed: - * - http_requests_total: Counter of HTTP requests - * - http_request_duration_seconds: Histogram of request durations - * - active_connections: Gauge of active WebSocket connections - * - transfer_rate: Counter of transfers per second - * - cache_hit_rate: Gauge of cache hit percentage - * - db_pool_size: Gauge of database connection pool stats - */ - -import promClient from 'prom-client'; -import { Request, Response, NextFunction } from 'express'; - -// Create a Registry -const register = new promClient.Registry(); - -// Add default metrics (memory, CPU, event loop lag, etc.) -promClient.collectDefaultMetrics({ register }); - -// HTTP request counter -const httpRequestsTotal = new promClient.Counter({ - name: 'http_requests_total', - help: 'Total number of HTTP requests', - labelNames: ['method', 'route', 'status_code'], - registers: [register], -}); - -// HTTP request duration histogram -const httpRequestDuration = new promClient.Histogram({ - name: 'http_request_duration_seconds', - help: 'Duration of HTTP requests in seconds', - labelNames: ['method', 'route', 'status_code'], - buckets: [0.001, 0.005, 0.015, 0.05, 0.1, 0.5, 1, 5], - registers: [register], -}); - -// Active WebSocket connections -const activeConnections = new promClient.Gauge({ - name: 'websocket_active_connections', - help: 'Number of active WebSocket connections', - registers: [register], -}); - -// Transfer rate counter -const transferRate = new promClient.Counter({ - name: 'transfers_total', - help: 'Total number of transfers executed', - labelNames: ['status'], - registers: [register], -}); - -// Transfer latency histogram -const transferLatency = new promClient.Histogram({ - name: 'transfer_latency_seconds', - help: 'Transfer execution latency in seconds', - buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1], - registers: [register], -}); - -// Cache hit rate -const cacheHits = new promClient.Counter({ - name: 'cache_hits_total', - help: 'Total number of cache hits', - labelNames: ['cache_type'], - registers: [register], -}); - -const cacheMisses = new promClient.Counter({ - name: 'cache_misses_total', - help: 'Total number of cache misses', - labelNames: ['cache_type'], - registers: [register], -}); - -// Database pool metrics -const dbPoolSize = new promClient.Gauge({ - name: 'db_pool_connections', - help: 'Database connection pool size', - labelNames: ['state'], - registers: [register], -}); - -// Worker pool metrics -const workerPoolSize = new promClient.Gauge({ - name: 'worker_pool_size', - help: 'Worker thread pool size', - labelNames: ['state'], - registers: [register], -}); - -// Rate limit hits -const rateLimitHits = new promClient.Counter({ - name: 'rate_limit_hits_total', - help: 'Total number of rate limit hits', - labelNames: ['tier'], - registers: [register], -}); - -// Batch queue size -const batchQueueSize = new promClient.Gauge({ - name: 'transfer_batch_queue_size', - help: 'Current size of the transfer batch queue', - registers: [register], -}); - -// Middleware to track HTTP metrics -function metricsMiddleware(req: Request, res: Response, next: NextFunction): void { - const start = Date.now(); - - res.on('finish', () => { - const duration = (Date.now() - start) / 1000; - const route = req.route ? req.route.path : req.path; - - httpRequestsTotal.inc({ - method: req.method, - route: route, - status_code: res.statusCode, - }); - - httpRequestDuration.observe( - { - method: req.method, - route: route, - status_code: res.statusCode, - }, - duration - ); - }); - - next(); -} - -// Helper to record cache hit/miss -function recordCacheHit(cacheType: string): void { - cacheHits.inc({ cache_type: cacheType }); -} - -function recordCacheMiss(cacheType: string): void { - cacheMisses.inc({ cache_type: cacheType }); -} - -// Helper to record transfer -function recordTransfer(status: 'success' | 'failed', latencySeconds: number): void { - transferRate.inc({ status }); - transferLatency.observe(latencySeconds); -} - -// Helper to update DB pool metrics -function updateDbPoolMetrics(total: number, idle: number, waiting: number): void { - dbPoolSize.set({ state: 'total' }, total); - dbPoolSize.set({ state: 'idle' }, idle); - dbPoolSize.set({ state: 'waiting' }, waiting); -} - -// Helper to update worker pool metrics -function updateWorkerPoolMetrics(total: number, active: number, queued: number): void { - workerPoolSize.set({ state: 'total' }, total); - workerPoolSize.set({ state: 'active' }, active); - workerPoolSize.set({ state: 'queued' }, queued); -} - -// Helper to update WebSocket connections -function updateActiveConnections(count: number): void { - activeConnections.set(count); -} - -// Helper to record rate limit hit -function recordRateLimitHit(tier: string): void { - rateLimitHits.inc({ tier }); -} - -// Helper to update batch queue size -function updateBatchQueueSize(size: number): void { - batchQueueSize.set(size); -} - -export { - register, - metricsMiddleware, - httpRequestsTotal, - httpRequestDuration, - activeConnections, - transferRate, - transferLatency, - cacheHits, - cacheMisses, - dbPoolSize, - workerPoolSize, - rateLimitHits, - batchQueueSize, - recordCacheHit, - recordCacheMiss, - recordTransfer, - updateDbPoolMetrics, - updateWorkerPoolMetrics, - updateActiveConnections, - recordRateLimitHit, - updateBatchQueueSize, -}; diff --git a/legacy/taproot-assets-era/backend/src/rune/RuneBuilder.ts b/legacy/taproot-assets-era/backend/src/rune/RuneBuilder.ts deleted file mode 100644 index 4de4195..0000000 --- a/legacy/taproot-assets-era/backend/src/rune/RuneBuilder.ts +++ /dev/null @@ -1,223 +0,0 @@ -/** - * Builder for Runestone OP_RETURN outputs. - * - * Creates valid OP_RETURN scripts encoding Rune protocol operations - * into Bitcoin transactions using LEB128 varint encoding and - * delta-encoded edict sequences per the Runes protocol specification. - * - * Wire format: - * OP_RETURN (0x6a) | OP_13 (0x5d) | - * - * Payload structure: - * [tag-value pairs...] [Body tag (0)] [edicts as delta-encoded quadruples...] - */ - -import { DOG_RUNE_ID } from './RuneConstants'; -import { RuneParser, RunestoneTag } from './RuneParser'; - -/** - * Encode an unsigned integer as LEB128 (Little Endian Base 128). - * Used throughout the Runes protocol for compact integer encoding. - */ -export function encodeLEB128(value: bigint): Buffer { - if (value < 0n) { - throw new Error('LEB128 encoding does not support negative values'); - } - const bytes: number[] = []; - do { - let byte = Number(value & 0x7fn); - value >>= 7n; - if (value !== 0n) byte |= 0x80; - bytes.push(byte); - } while (value !== 0n); - return Buffer.from(bytes); -} - -/** - * Wrap a raw Runestone payload in a valid OP_RETURN script. - * The payload is split into data pushes as required by Bitcoin script rules. - * - * Returns a complete scriptPubKey: OP_RETURN OP_13 - */ -function wrapInOpReturn(payload: Buffer): Buffer { - const parts: Buffer[] = [ - Buffer.from([0x6a]), // OP_RETURN - Buffer.from([0x5d]), // OP_13 (Runestone protocol tag) - ]; - - // Push the payload using minimal push encoding - // Bitcoin script allows pushes up to 520 bytes per push - const MAX_PUSH = 520; - let offset = 0; - - while (offset < payload.length) { - const remaining = payload.length - offset; - const chunkLen = Math.min(remaining, MAX_PUSH); - const chunk = payload.subarray(offset, offset + chunkLen); - - if (chunkLen <= 0x4b) { - // Direct push: length byte IS the opcode - parts.push(Buffer.from([chunkLen])); - } else if (chunkLen <= 0xff) { - // OP_PUSHDATA1 - parts.push(Buffer.from([0x4c, chunkLen])); - } else { - // OP_PUSHDATA2 - parts.push(Buffer.from([0x4d, chunkLen & 0xff, (chunkLen >> 8) & 0xff])); - } - parts.push(chunk); - offset += chunkLen; - } - - return Buffer.concat(parts); -} - -export class RuneBuilder { - /** - * Build an OP_RETURN output containing a Runestone that transfers - * a specified amount of a rune to a given output index. - * - * The edict directs `amount` of `runeId` to transaction output `destinationIndex`. - */ - static buildRunestoneOutput( - runeId: string, - amount: bigint, - destinationIndex: number - ): Buffer { - const { block, tx } = RuneParser.decodeRuneId(runeId); - - // Build payload: Body tag followed by a single edict - // Edict format: [block, tx, amount, output] — all LEB128 encoded - // First edict uses absolute values (no prior edict to delta from) - const payload = Buffer.concat([ - encodeLEB128(BigInt(RunestoneTag.Body)), // Body tag = 0 - encodeLEB128(BigInt(block)), // block (absolute, first edict) - encodeLEB128(BigInt(tx)), // tx (absolute, first edict) - encodeLEB128(amount), // amount - encodeLEB128(BigInt(destinationIndex)), // output index - ]); - - return wrapInOpReturn(payload); - } - - /** - * Build a Runestone with a Pointer field and a single edict. - * The Pointer directs any unallocated runes to the specified output. - */ - static buildRunestoneWithPointer( - runeId: string, - amount: bigint, - destinationIndex: number, - pointerIndex: number - ): Buffer { - const { block, tx } = RuneParser.decodeRuneId(runeId); - - const payload = Buffer.concat([ - // Pointer tag-value pair - encodeLEB128(BigInt(RunestoneTag.Pointer)), - encodeLEB128(BigInt(pointerIndex)), - // Body tag then edict - encodeLEB128(BigInt(RunestoneTag.Body)), - encodeLEB128(BigInt(block)), - encodeLEB128(BigInt(tx)), - encodeLEB128(amount), - encodeLEB128(BigInt(destinationIndex)), - ]); - - return wrapInOpReturn(payload); - } - - /** - * Build a Runestone for a channel commitment/closing transaction. - * Encodes two edicts splitting rune amounts between user and hub outputs. - * - * Output layout: - * Output 0: OP_RETURN (Runestone) — value 0 - * Output 1: User's rune balance — dust (546 sats) - * Output 2: Hub's rune balance — dust (546 sats) - * - * The edicts use delta encoding: the second edict's rune ID is - * encoded as the delta from the first (0:0 for the same rune). - */ - static buildCommitmentRunestone( - _channelId: string, - localBalance: bigint, - remoteBalance: bigint - ): Buffer { - const { block, tx } = RuneParser.decodeRuneId(DOG_RUNE_ID); - - const edictParts: Buffer[] = []; - - // Edict 1: localBalance -> output 1 (user) - // First edict: absolute rune ID - edictParts.push(encodeLEB128(BigInt(block))); // block (absolute) - edictParts.push(encodeLEB128(BigInt(tx))); // tx (absolute) - edictParts.push(encodeLEB128(localBalance)); // amount - edictParts.push(encodeLEB128(1n)); // output index 1 - - // Edict 2: remoteBalance -> output 2 (hub) - // Delta from previous edict: same rune, so delta = 0:0 - edictParts.push(encodeLEB128(0n)); // block delta = 0 - edictParts.push(encodeLEB128(0n)); // tx delta = 0 - edictParts.push(encodeLEB128(remoteBalance)); // amount - edictParts.push(encodeLEB128(2n)); // output index 2 - - const payload = Buffer.concat([ - encodeLEB128(BigInt(RunestoneTag.Body)), // Body tag - ...edictParts, - ]); - - return wrapInOpReturn(payload); - } - - /** - * Build a Runestone for batched multi-transfer operations. - * Each transfer specifies a rune ID, amount, and destination output index. - * - * Edicts are sorted by rune ID (block, then tx) for canonical encoding, - * then delta-encoded. - */ - static buildMultiTransferRunestone( - transfers: Array<{ - runeId: string; - amount: bigint; - outputIndex: number; - }> - ): Buffer { - if (transfers.length === 0) { - throw new Error('Cannot build Runestone with no transfers'); - } - - // Parse and sort by rune ID for canonical ordering - const parsed = transfers.map((t) => ({ - ...RuneParser.decodeRuneId(t.runeId), - amount: t.amount, - outputIndex: t.outputIndex, - })); - parsed.sort((a, b) => a.block - b.block || a.tx - b.tx); - - const edictParts: Buffer[] = []; - let prevBlock = 0; - let prevTx = 0; - - for (const edict of parsed) { - const blockDelta = edict.block - prevBlock; - const txDelta = blockDelta !== 0 ? edict.tx : edict.tx - prevTx; - - edictParts.push(encodeLEB128(BigInt(blockDelta))); - edictParts.push(encodeLEB128(BigInt(txDelta))); - edictParts.push(encodeLEB128(edict.amount)); - edictParts.push(encodeLEB128(BigInt(edict.outputIndex))); - - prevBlock = edict.block; - prevTx = edict.tx; - } - - const payload = Buffer.concat([ - encodeLEB128(BigInt(RunestoneTag.Body)), - ...edictParts, - ]); - - return wrapInOpReturn(payload); - } -} diff --git a/legacy/taproot-assets-era/backend/src/rune/RuneConstants.ts b/legacy/taproot-assets-era/backend/src/rune/RuneConstants.ts deleted file mode 100644 index feaf624..0000000 --- a/legacy/taproot-assets-era/backend/src/rune/RuneConstants.ts +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Constants and utilities for Rune assets on Bitcoin. - */ - -/** - * Supported asset types for RuneBolt channels. - * - * - DOG: DOG•GO•TO•THE•MOON rune, transferred via Runestones - * - BTC: Native Bitcoin (no Runestone needed) - * - * Note: BRC-20 tokens and Bitmap use inscription-based transfers (not Runestones) - * and require a fundamentally different transfer mechanism. They are NOT supported - * via the Runestone path. - */ -export enum SupportedAsset { - DOG = 'DOG', - BTC = 'BTC', -} - -/** The Rune ID for DOG•GO•TO•THE•MOON (etched in block 840000, tx 3) */ -export const DOG_RUNE_ID = '840000:3'; - -/** DOG rune block component */ -export const DOG_RUNE_BLOCK = 840000; - -/** DOG rune tx component */ -export const DOG_RUNE_TX = 3; - -/** Human-readable name with bullet separators */ -export const DOG_RUNE_NAME = 'DOG\u2022GO\u2022TO\u2022THE\u2022MOON'; - -/** Number of decimal places for DOG amounts */ -export const DOG_DECIMALS = 5; - -/** The multiplier for converting display amounts to raw amounts */ -const DOG_MULTIPLIER = BigInt(10 ** DOG_DECIMALS); // 100000 - -/** - * Convert a raw (on-chain) DOG amount to a human-readable display string. - * e.g., 1234500000n -> "12345.00000" - */ -export function formatDogAmount(raw: bigint): string { - const whole = raw / DOG_MULTIPLIER; - const frac = raw % DOG_MULTIPLIER; - const fracStr = frac.toString().padStart(DOG_DECIMALS, '0'); - return `${whole}.${fracStr}`; -} - -/** - * Parse a human-readable DOG amount string to a raw bigint. - * e.g., "12345.5" -> 1234550000n - */ -export function parseDogAmount(display: string): bigint { - const parts = display.split('.'); - const whole = BigInt(parts[0] || '0'); - - let fracStr = parts[1] || '0'; - if (fracStr.length > DOG_DECIMALS) { - fracStr = fracStr.slice(0, DOG_DECIMALS); - } else { - fracStr = fracStr.padEnd(DOG_DECIMALS, '0'); - } - - return whole * DOG_MULTIPLIER + BigInt(fracStr); -} - -/** Minimum channel capacity in raw DOG units (1 DOG) */ -export const MIN_CHANNEL_CAPACITY = DOG_MULTIPLIER; - -/** Maximum channel capacity in raw DOG units (1 billion DOG) */ -export const MAX_CHANNEL_CAPACITY = BigInt(1_000_000_000) * DOG_MULTIPLIER; diff --git a/legacy/taproot-assets-era/backend/src/rune/RuneParser.ts b/legacy/taproot-assets-era/backend/src/rune/RuneParser.ts deleted file mode 100644 index d063563..0000000 --- a/legacy/taproot-assets-era/backend/src/rune/RuneParser.ts +++ /dev/null @@ -1,341 +0,0 @@ -/** - * Parser for Runestone data embedded in Bitcoin transaction outputs. - * - * Runestones are OP_RETURN outputs that encode Rune protocol operations - * (etching, minting, transferring) using LEB128 varint encoding with - * tag-value pairs and delta-encoded edict sequences. - */ - -/** Runestone protocol tags */ -export const enum RunestoneTag { - Body = 0, - Flags = 2, - Rune = 4, - Premine = 6, - Cap = 8, - Amount = 10, - HeightStart = 12, - HeightEnd = 14, - OffsetStart = 16, - OffsetEnd = 18, - Mint = 20, - Pointer = 22, - Cenotaph = 126, -} - -export interface RunestoneData { - edicts: RuneEdict[]; - etching: RuneEtching | null; - mint: RuneMint | null; - pointer: number | null; -} - -export interface RuneEdict { - runeId: { block: number; tx: number }; - amount: bigint; - output: number; -} - -export interface RuneEtching { - rune: string | null; - divisibility: number; - spacers: number; - symbol: string | null; - premine: bigint; -} - -export interface RuneMint { - runeId: { block: number; tx: number }; - amount: bigint; -} - -/** - * Decode a LEB128-encoded unsigned integer from a buffer. - * Returns the decoded bigint value and the number of bytes consumed. - */ -export function decodeLEB128( - buffer: Buffer, - offset: number -): { value: bigint; bytesRead: number } { - let value = 0n; - let shift = 0n; - let bytesRead = 0; - - while (offset + bytesRead < buffer.length) { - const byte = buffer[offset + bytesRead]; - bytesRead++; - - value |= BigInt(byte & 0x7f) << shift; - shift += 7n; - - if ((byte & 0x80) === 0) { - return { value, bytesRead }; - } - - // Guard against excessively long encodings (max 18 bytes for u128) - if (bytesRead > 18) { - throw new Error('LEB128 encoding too long'); - } - } - - throw new Error('Unexpected end of buffer while decoding LEB128'); -} - -export class RuneParser { - /** - * Parse a Runestone from a scriptPubKey buffer. - * Expects a script starting with OP_RETURN (0x6a) + OP_13 (0x5d). - */ - static parseRunestone(scriptPubKey: Buffer): RunestoneData | null { - // Minimum: OP_RETURN + OP_13 + at least 1 data push - if (scriptPubKey.length < 3) { - return null; - } - - // Validate OP_RETURN + OP_13 prefix - if (scriptPubKey[0] !== 0x6a) { - return null; - } - - // Find OP_13 (0x5d) — it may follow OP_RETURN directly or after pushdata - let payloadStart = -1; - let pos = 1; - - if (scriptPubKey[pos] === 0x5d) { - // OP_RETURN OP_13 — standard Runestone prefix - pos++; - payloadStart = pos; - } else { - return null; - } - - // Extract payload: parse script data pushes after OP_13 - const payload = this.extractPayload(scriptPubKey, payloadStart); - if (payload.length === 0) { - return { edicts: [], etching: null, mint: null, pointer: null }; - } - - // Parse tag-value pairs and edicts from the payload - return this.decodePayload(payload); - } - - /** - * Extract the concatenated payload from script data pushes. - */ - private static extractPayload(script: Buffer, start: number): Buffer { - const chunks: Buffer[] = []; - let pos = start; - - while (pos < script.length) { - const opcode = script[pos]; - pos++; - - if (opcode >= 0x01 && opcode <= 0x4b) { - // Direct push: opcode is the length - const len = opcode; - if (pos + len > script.length) break; - chunks.push(script.subarray(pos, pos + len)); - pos += len; - } else if (opcode === 0x4c) { - // OP_PUSHDATA1 - if (pos >= script.length) break; - const len = script[pos]; - pos++; - if (pos + len > script.length) break; - chunks.push(script.subarray(pos, pos + len)); - pos += len; - } else if (opcode === 0x4d) { - // OP_PUSHDATA2 - if (pos + 2 > script.length) break; - const len = script[pos] | (script[pos + 1] << 8); - pos += 2; - if (pos + len > script.length) break; - chunks.push(script.subarray(pos, pos + len)); - pos += len; - } else if (opcode === 0x4e) { - // OP_PUSHDATA4 - if (pos + 4 > script.length) break; - const len = - script[pos] | - (script[pos + 1] << 8) | - (script[pos + 2] << 16) | - (script[pos + 3] << 24); - pos += 4; - if (pos + len > script.length) break; - chunks.push(script.subarray(pos, pos + len)); - pos += len; - } else { - // Non-push opcode — stop parsing - break; - } - } - - return Buffer.concat(chunks); - } - - /** - * Decode the Runestone payload into structured data. - */ - private static decodePayload(payload: Buffer): RunestoneData { - const edicts: RuneEdict[] = []; - let pointer: number | null = null; - let mintBlock: bigint | null = null; - let mintTx: bigint | null = null; - - let offset = 0; - let inBody = false; - - while (offset < payload.length) { - const tagResult = decodeLEB128(payload, offset); - offset += tagResult.bytesRead; - const tag = Number(tagResult.value); - - if (tag === RunestoneTag.Body) { - inBody = true; - // After the Body tag, remaining data is edicts as quadruples - break; - } - - // Read the value for this tag - if (offset >= payload.length) break; - const valResult = decodeLEB128(payload, offset); - offset += valResult.bytesRead; - - switch (tag) { - case RunestoneTag.Pointer: - pointer = Number(valResult.value); - break; - case RunestoneTag.Mint: - // Mint tag appears twice: first for block, second for tx - if (mintBlock === null) { - mintBlock = valResult.value; - } else { - mintTx = valResult.value; - } - break; - // Other tags (Flags, Rune, etc.) are not needed for transfer parsing - default: - break; - } - } - - // Parse edicts (after Body tag) - if (inBody) { - let prevBlock = 0; - let prevTx = 0; - - while (offset + 3 <= payload.length) { - // Each edict is 4 LEB128 values: block_delta, tx_delta, amount, output - const blockDelta = decodeLEB128(payload, offset); - offset += blockDelta.bytesRead; - if (offset >= payload.length) break; - - const txDelta = decodeLEB128(payload, offset); - offset += txDelta.bytesRead; - if (offset >= payload.length) break; - - const amount = decodeLEB128(payload, offset); - offset += amount.bytesRead; - if (offset >= payload.length) break; - - const output = decodeLEB128(payload, offset); - offset += output.bytesRead; - - // Delta decoding: if block delta is non-zero, tx resets to delta value - const blockDeltaNum = Number(blockDelta.value); - const txDeltaNum = Number(txDelta.value); - - let block: number; - let tx: number; - if (blockDeltaNum !== 0) { - block = prevBlock + blockDeltaNum; - tx = txDeltaNum; - } else { - block = prevBlock; - tx = prevTx + txDeltaNum; - } - - edicts.push({ - runeId: { block, tx }, - amount: amount.value, - output: Number(output.value), - }); - - prevBlock = block; - prevTx = tx; - } - } - - const mint: RuneMint | null = - mintBlock !== null && mintTx !== null - ? { - runeId: { block: Number(mintBlock), tx: Number(mintTx) }, - amount: 0n, // Mint amount comes from the rune's terms, not the runestone - } - : null; - - return { - edicts, - etching: null, // Etching parsing not needed for channel operations - mint, - pointer, - }; - } - - /** - * Parse a Runestone from a raw transaction hex. - * Scans all outputs for an OP_RETURN with the Runestone OP_13 tag. - */ - static parseRunestoneFromTxHex(txHex: string): RunestoneData | null { - const txBuf = Buffer.from(txHex, 'hex'); - - // Scan for OP_RETURN (0x6a) followed by OP_13 (0x5d) - for (let i = 0; i < txBuf.length - 2; i++) { - if (txBuf[i] === 0x6a && txBuf[i + 1] === 0x5d) { - // Found potential Runestone output script - // Try to find the script boundaries — for simplicity, parse from this point - const scriptBuf = txBuf.subarray(i); - const result = this.parseRunestone(scriptBuf); - if (result && (result.edicts.length > 0 || result.mint || result.pointer !== null)) { - return result; - } - } - } - - return null; - } - - /** - * Decode a rune ID string (e.g., "840000:3") into block and tx components. - */ - static decodeRuneId(encoded: string): { block: number; tx: number } { - const parts = encoded.split(':'); - if (parts.length !== 2) { - throw new Error(`Invalid rune ID format: ${encoded}. Expected "block:tx"`); - } - - const block = parseInt(parts[0], 10); - const tx = parseInt(parts[1], 10); - - if (isNaN(block) || isNaN(tx)) { - throw new Error(`Invalid rune ID components: ${encoded}`); - } - - return { block, tx }; - } - - /** - * Encode block and tx into a rune ID string. - */ - static encodeRuneId(block: number, tx: number): string { - return `${block}:${tx}`; - } - - /** - * Validate that a hex string represents a plausible Runestone transaction. - */ - static isRunestoneTransaction(txHex: string): boolean { - // Runestone protocol tag bytes (OP_RETURN OP_13) - return txHex.includes('6a5d'); - } -} diff --git a/legacy/taproot-assets-era/backend/src/usernames/index.ts b/legacy/taproot-assets-era/backend/src/usernames/index.ts deleted file mode 100644 index 60a7d6a..0000000 --- a/legacy/taproot-assets-era/backend/src/usernames/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { default as usernameRoutes } from './usernameRoutes'; -export * from './usernameUtils'; diff --git a/legacy/taproot-assets-era/backend/src/usernames/usernameRoutes.ts b/legacy/taproot-assets-era/backend/src/usernames/usernameRoutes.ts deleted file mode 100644 index 1e6b44a..0000000 --- a/legacy/taproot-assets-era/backend/src/usernames/usernameRoutes.ts +++ /dev/null @@ -1,206 +0,0 @@ -import { Router, Request, Response } from 'express'; -import { z } from 'zod'; -import Database from '../db/Database'; -import { requireAuth } from '../auth/AuthMiddleware'; -import { generateUsername, isValidUsername } from './usernameUtils'; - -const router = Router(); -const db = Database.getInstance(); - -/** - * Username validation and availability check - * GET /usernames/check/:username - */ -router.get('/usernames/check/:username', async (req: Request, res: Response) => { - try { - const username = req.params.username.toLowerCase().replace(/^@/, ''); - - if (!isValidUsername(username)) { - res.json({ - success: true, - data: { - available: false, - reason: 'Username must be 3-20 characters, letters, numbers, and underscores only', - }, - }); - return; - } - - const existing = await db.getUserByUsername(username); - - res.json({ - success: true, - data: { - available: !existing, - username: username, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[usernameRoutes] GET /usernames/check error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -/** - * Get username for a pubkey - * GET /usernames/resolve/:pubkey - */ -router.get('/usernames/resolve/:pubkey', async (req: Request, res: Response) => { - try { - const { pubkey } = req.params; - const user = await db.getUser(pubkey); - - if (!user) { - res.status(404).json({ - success: false, - error: 'User not found', - }); - return; - } - - res.json({ - success: true, - data: { - pubkey: user.pubkey, - username: user.username, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[usernameRoutes] GET /usernames/resolve error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -/** - * Resolve username to pubkey - * GET /usernames/:username - */ -router.get('/usernames/:username', async (req: Request, res: Response) => { - try { - const username = req.params.username.toLowerCase().replace(/^@/, ''); - const user = await db.getUserByUsername(username); - - if (!user) { - res.status(404).json({ - success: false, - error: 'Username not found', - userFriendly: { - title: "We couldn't find @" + username, - message: 'Check the spelling or ask them to join RuneBolt.', - action: 'You can send them a claim link instead!', - }, - }); - return; - } - - res.json({ - success: true, - data: { - username: user.username, - pubkey: user.pubkey, - profileUrl: `https://runebolt.io/${user.username}`, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[usernameRoutes] GET /usernames/:username error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -/** - * Register or update username (authenticated) - * POST /usernames/register - */ -const registerSchema = z.object({ - username: z.string() - .min(3, 'Username must be at least 3 characters') - .max(20, 'Username must be at most 20 characters') - .regex(/^[a-zA-Z0-9_]+$/, 'Username can only contain letters, numbers, and underscores'), -}); - -router.post('/usernames/register', requireAuth, async (req: Request, res: Response) => { - try { - const parsed = registerSchema.safeParse(req.body); - if (!parsed.success) { - res.status(400).json({ - success: false, - error: parsed.error.errors.map((e) => e.message).join('; '), - userFriendly: { - title: 'Invalid username', - message: 'Usernames must be 3-20 characters and can only contain letters, numbers, and underscores.', - action: 'Try a different username', - }, - }); - return; - } - - const { username: rawUsername } = parsed.data; - const username = rawUsername.toLowerCase(); - const pubkey = req.auth!.pubkey; - - const existing = await db.getUserByUsername(username); - if (existing && existing.pubkey !== pubkey) { - res.status(409).json({ - success: false, - error: 'Username already taken', - userFriendly: { - title: `@${username} is taken`, - message: 'Someone else is already using this username.', - action: 'Try a different variation', - }, - }); - return; - } - - await db.updateUsername(pubkey, username); - - res.json({ - success: true, - data: { - username, - pubkey, - profileUrl: `https://runebolt.io/${username}`, - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[usernameRoutes] POST /usernames/register error:', message); - res.status(500).json({ - success: false, - error: message, - userFriendly: { - title: 'Something went wrong', - message: "We couldn't save your username. Please try again.", - action: 'Try again in a moment', - }, - }); - } -}); - -/** - * Auto-generate a username suggestion - * GET /usernames/suggest/:prefix? - */ -router.get('/usernames/suggest/:prefix?', async (req: Request, res: Response) => { - try { - const prefix = req.params.prefix || 'user'; - const suggestion = generateUsername(prefix); - - res.json({ - success: true, - data: { - suggestion, - available: !(await db.getUserByUsername(suggestion)), - }, - }); - } catch (err) { - const message = err instanceof Error ? err.message : 'Unknown error'; - console.error('[usernameRoutes] GET /usernames/suggest error:', message); - res.status(500).json({ success: false, error: message }); - } -}); - -export default router; diff --git a/legacy/taproot-assets-era/backend/src/usernames/usernameUtils.ts b/legacy/taproot-assets-era/backend/src/usernames/usernameUtils.ts deleted file mode 100644 index 79979fd..0000000 --- a/legacy/taproot-assets-era/backend/src/usernames/usernameUtils.ts +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Username utilities for validation, generation, and resolution - */ - -// Valid username regex: 3-20 chars, alphanumeric + underscore -const USERNAME_REGEX = /^[a-zA-Z0-9_]{3,20}$/; - -// Reserved usernames that cannot be registered -const RESERVED_USERNAMES = new Set([ - 'admin', 'administrator', 'root', 'system', 'support', 'help', - 'runebolt', 'official', 'team', 'staff', 'mod', 'moderator', - 'api', 'www', 'app', 'mail', 'email', 'support', 'contact', - 'billing', 'security', 'legal', 'terms', 'privacy', 'about', - 'login', 'signup', 'register', 'auth', 'oauth', 'callback', - 'pay', 'payment', 'claim', 'wallet', 'bitcoin', 'dog', - 'null', 'undefined', 'nan', 'test', 'testing', 'demo', -]); - -/** - * Validate if a username is valid format - */ -export function isValidUsername(username: string): boolean { - if (!username) return false; - const normalized = username.toLowerCase().replace(/^@/, ''); - - if (!USERNAME_REGEX.test(normalized)) return false; - if (RESERVED_USERNAMES.has(normalized)) return false; - if (normalized.startsWith('_') || normalized.endsWith('_')) return false; - if (normalized.includes('__')) return false; - - return true; -} - -/** - * Normalize username (lowercase, remove @ prefix) - */ -export function normalizeUsername(username: string): string { - return username.toLowerCase().replace(/^@/, ''); -} - -/** - * Generate a username suggestion based on a prefix - */ -export function generateUsername(prefix: string = 'user'): string { - const cleanPrefix = prefix.toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 10); - const randomSuffix = Math.random().toString(36).substring(2, 6); - return `${cleanPrefix}_${randomSuffix}`; -} - -/** - * Generate multiple username suggestions - */ -export function generateUsernameSuggestions(prefix: string = 'user', count: number = 3): string[] { - const suggestions: string[] = []; - const base = prefix.toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 10); - - // Try base + random suffixes - while (suggestions.length < count) { - const suffix = Math.random().toString(36).substring(2, 6); - const suggestion = `${base}_${suffix}`; - if (!suggestions.includes(suggestion)) { - suggestions.push(suggestion); - } - } - - return suggestions; -} - -/** - * Format username with @ prefix for display - */ -export function formatUsername(username: string | null | undefined): string { - if (!username) return ''; - const normalized = normalizeUsername(username); - return `@${normalized}`; -} - -/** - * Create profile URL from username - */ -export function getProfileUrl(username: string): string { - const normalized = normalizeUsername(username); - return `https://runebolt.io/${normalized}`; -} - -/** - * Parse a recipient string to determine type and extract identifier - * Returns: { type: 'username' | 'pubkey' | 'address', value: string } - */ -export function parseRecipient(input: string): { - type: 'username' | 'pubkey' | 'address' | 'unknown'; - value: string; -} { - const trimmed = input.trim(); - - // Check for username (starts with @ or contains @runebolt) - if (trimmed.startsWith('@')) { - return { type: 'username', value: normalizeUsername(trimmed) }; - } - - if (trimmed.includes('@runebolt.io')) { - const username = trimmed.split('@')[0]; - return { type: 'username', value: normalizeUsername(username) }; - } - - // Check for Bitcoin address - if (trimmed.startsWith('bc1') || trimmed.startsWith('1') || trimmed.startsWith('3')) { - return { type: 'address', value: trimmed }; - } - - // Check for pubkey (64-66 hex chars) - if (/^[0-9a-fA-F]{64,66}$/.test(trimmed)) { - return { type: 'pubkey', value: trimmed }; - } - - // Might be a bare username without @ - if (isValidUsername(trimmed)) { - return { type: 'username', value: normalizeUsername(trimmed) }; - } - - return { type: 'unknown', value: trimmed }; -} diff --git a/legacy/taproot-assets-era/backend/src/watchtower/Watchtower.ts b/legacy/taproot-assets-era/backend/src/watchtower/Watchtower.ts deleted file mode 100644 index 914eb58..0000000 --- a/legacy/taproot-assets-era/backend/src/watchtower/Watchtower.ts +++ /dev/null @@ -1,261 +0,0 @@ -/** - * Watchtower — Background service that monitors Bitcoin mempool for breach attempts. - * - * Watches funding transaction outputs for spends. If a revoked commitment - * is broadcast, the watchtower automatically constructs and broadcasts - * a penalty transaction to claim all channel funds. - * - * Polls mempool.space every 30 seconds for watched funding tx spends. - */ - -import { MempoolClient, Transaction } from '../bitcoin/MempoolClient'; -import { PenaltyManager } from '../channels/PenaltyManager'; - -const POLL_INTERVAL_MS = 30_000; // 30 seconds - -export interface WatchedChannel { - channelId: string; - fundingTxid: string; - fundingVout: number; - latestSequence: number; -} - -type BreachCallback = ( - channelId: string, - breachTxid: string, - penaltyTxid: string -) => void; - -export class Watchtower { - private mempool: MempoolClient; - private penaltyManager: PenaltyManager; - private watchedChannels: Map = new Map(); - private pollTimer: ReturnType | null = null; - private breachCallbacks: BreachCallback[] = []; - private isRunning: boolean = false; - - constructor(mempoolClient?: MempoolClient) { - this.mempool = mempoolClient || new MempoolClient(); - this.penaltyManager = new PenaltyManager(this.mempool); - } - - /** - * Register a channel for monitoring. - * The watchtower will watch for spends of the funding output. - */ - async startWatching( - channelId: string, - fundingTxid: string, - fundingVout: number, - latestSequence: number - ): Promise { - console.log( - `[Watchtower] Start watching channel ${channelId}, ` + - `funding: ${fundingTxid.slice(0, 16)}...:${fundingVout}` - ); - - this.watchedChannels.set(channelId, { - channelId, - fundingTxid, - fundingVout, - latestSequence, - }); - - // Auto-start polling if not already running - if (!this.isRunning && this.watchedChannels.size > 0) { - this.start(); - } - } - - /** - * Update the latest known sequence for a watched channel. - * Called after each successful state update. - */ - updateLatestSequence(channelId: string, sequence: number): void { - const watched = this.watchedChannels.get(channelId); - if (watched) { - watched.latestSequence = sequence; - } - } - - /** - * Unregister a channel from monitoring. - * Called on cooperative close when there is no breach risk. - */ - stopWatching(channelId: string): void { - console.log(`[Watchtower] Stop watching channel ${channelId}`); - this.watchedChannels.delete(channelId); - - // Stop polling if no channels to watch - if (this.watchedChannels.size === 0) { - this.stop(); - } - } - - /** - * Register a callback for breach detection events. - */ - onBreachDetected(callback: BreachCallback): void { - this.breachCallbacks.push(callback); - } - - /** - * Start the background polling loop. - */ - start(): void { - if (this.isRunning) { - console.log('[Watchtower] Already running'); - return; - } - - console.log( - `[Watchtower] Starting — monitoring ${this.watchedChannels.size} channels` - ); - this.isRunning = true; - - // Initial poll - void this.pollForBreaches(); - - // Recurring poll - this.pollTimer = setInterval(() => { - void this.pollForBreaches(); - }, POLL_INTERVAL_MS); - } - - /** - * Stop the background polling loop. - */ - stop(): void { - if (!this.isRunning) return; - - console.log('[Watchtower] Stopping'); - this.isRunning = false; - - if (this.pollTimer) { - clearInterval(this.pollTimer); - this.pollTimer = null; - } - } - - /** - * Get the number of channels currently being watched. - */ - getWatchedCount(): number { - return this.watchedChannels.size; - } - - /** - * Check if the watchtower is actively running. - */ - getIsRunning(): boolean { - return this.isRunning; - } - - /** - * Poll mempool for spends of watched funding outputs. - * If a spend is detected, check if it's a breach (old state). - */ - private async pollForBreaches(): Promise { - if (this.watchedChannels.size === 0) return; - - console.log( - `[Watchtower] Polling ${this.watchedChannels.size} channels for breaches` - ); - - for (const [channelId, watched] of this.watchedChannels) { - try { - await this.checkChannel(channelId, watched); - } catch (err) { - console.error( - `[Watchtower] Error checking channel ${channelId}:`, - err - ); - } - } - } - - /** - * Check a single channel for breach attempts. - */ - private async checkChannel( - channelId: string, - watched: WatchedChannel - ): Promise { - let spendingTx: Transaction; - try { - // Check if the funding output has been spent - spendingTx = await this.mempool.getTx(watched.fundingTxid); - } catch { - // Transaction not found or API error — skip this round - return; - } - - // If the funding tx is still unspent, nothing to do - if (!spendingTx.status.confirmed) { - return; - } - - // Check if there's a spending transaction for this output - // by looking for transactions that reference our funding txid as an input - const breachedSequence = await this.penaltyManager.checkForBreach( - channelId, - spendingTx - ); - - if (breachedSequence !== null) { - console.log( - `[Watchtower] BREACH on channel ${channelId}! ` + - `Old state #${breachedSequence} broadcast` - ); - await this.handleBreach(channelId, spendingTx); - } - } - - /** - * Handle a detected breach: build and broadcast penalty transaction. - */ - private async handleBreach( - channelId: string, - breachTx: Transaction - ): Promise { - try { - // Get the raw hex for the breach tx - const breachTxHex = await this.mempool.getTxHex(breachTx.txid); - - // Build penalty transaction - const { penaltyTxHex } = - await this.penaltyManager.buildPenaltyTx( - channelId, - breachTx.txid, - breachTxHex - ); - - // Broadcast penalty transaction - const broadcastTxid = await this.penaltyManager.broadcastPenaltyTx( - channelId, - penaltyTxHex - ); - - // Notify callbacks - for (const callback of this.breachCallbacks) { - try { - callback(channelId, breachTx.txid, broadcastTxid); - } catch (err) { - console.error('[Watchtower] Breach callback error:', err); - } - } - - // Stop watching this channel — it's been penalized - this.stopWatching(channelId); - - console.log( - `[Watchtower] Penalty tx broadcast for channel ${channelId}: ${broadcastTxid}` - ); - } catch (err) { - console.error( - `[Watchtower] Failed to handle breach on channel ${channelId}:`, - err - ); - } - } -} diff --git a/legacy/taproot-assets-era/backend/src/workers/TransferWorker.ts b/legacy/taproot-assets-era/backend/src/workers/TransferWorker.ts deleted file mode 100644 index 082dbc3..0000000 --- a/legacy/taproot-assets-era/backend/src/workers/TransferWorker.ts +++ /dev/null @@ -1,463 +0,0 @@ -import { Worker, isMainThread, parentPort } from 'worker_threads'; -import { EventEmitter } from 'events'; -import os from 'os'; - -interface TransferRequest { - id: string; - fromChannel: string; - toChannel: string; - fromBalance: { local: string; remote: string }; - toBalance: { local: string; remote: string }; - amount: string; - memo?: string; -} - -interface TransferResult { - id: string; - success: boolean; - error?: string; - newFromBalance?: { local: string; remote: string }; - newToBalance?: { local: string; remote: string }; - timestamp: string; -} - -interface WorkerPoolConfig { - minWorkers?: number; - maxWorkers?: number; - taskTimeout?: number; - maxQueueSize?: number; -} - -interface QueuedTask { - id: number; - type: string; - data: unknown; - resolve: (value: unknown) => void; - reject: (reason: Error) => void; - timestamp: number; -} - -/** - * TransferWorkerPool - Manages worker threads for off-main-thread transfer processing - * - * Features: - * - Dynamic worker pool sizing based on CPU cores - * - Task queue with backpressure - * - Batch processing for high throughput - * - Automatic worker restart on failure - */ -export class TransferWorkerPool extends EventEmitter { - private workers: Worker[] = []; - private queue: QueuedTask[] = []; - private activeTasks: Map = new Map(); - private taskIdCounter: number = 0; - - private minWorkers: number; - private maxWorkers: number; - private taskTimeout: number; - private maxQueueSize: number; - - private isShuttingDown: boolean = false; - private batchTimer: NodeJS.Timeout | null = null; - private currentBatch: QueuedTask[] = []; - private batchSize: number = 50; - private batchFlushInterval: number = 50; // ms - - constructor(config: WorkerPoolConfig = {}) { - super(); - - this.minWorkers = config.minWorkers || Math.max(2, Math.floor(os.cpus().length / 2)); - this.maxWorkers = config.maxWorkers || Math.max(4, os.cpus().length); - this.taskTimeout = config.taskTimeout || 30000; // 30 seconds - this.maxQueueSize = config.maxQueueSize || 10000; - - this.initializeWorkers(); - this.startBatchTimer(); - } - - /** - * Initialize the minimum number of workers - */ - private initializeWorkers(): void { - for (let i = 0; i < this.minWorkers; i++) { - this.addWorker(); - } - console.log(`[TransferWorkerPool] Initialized with ${this.minWorkers} workers`); - } - - /** - * Add a new worker to the pool - */ - private addWorker(): Worker | null { - if (this.workers.length >= this.maxWorkers) return null; - - try { - const worker = new Worker(__filename); - - worker.on('message', (result: { taskId: number; data: unknown }) => { - this.handleWorkerMessage(worker, result); - }); - - worker.on('error', (err) => { - console.error('[TransferWorkerPool] Worker error:', err); - this.removeWorker(worker); - this.addWorker(); // Replace failed worker - }); - - worker.on('exit', (code) => { - if (code !== 0) { - console.error(`[TransferWorkerPool] Worker exited with code ${code}`); - this.removeWorker(worker); - if (!this.isShuttingDown) { - this.addWorker(); // Replace crashed worker - } - } - }); - - this.workers.push(worker); - return worker; - } catch (err) { - console.error('[TransferWorkerPool] Failed to create worker:', err); - return null; - } - } - - /** - * Remove a worker from the pool - */ - private removeWorker(worker: Worker): void { - const index = this.workers.indexOf(worker); - if (index !== -1) { - this.workers.splice(index, 1); - } - - // Reassign any active tasks from this worker - for (const [taskId, task] of this.activeTasks) { - if (this.activeTasks.has(taskId)) { - this.activeTasks.delete(taskId); - this.queue.unshift(task); // Put back at front of queue - } - } - - worker.terminate().catch(() => {}); - } - - /** - * Handle message from worker - */ - private handleWorkerMessage(_worker: Worker, result: { taskId: number; data: unknown }): void { - const task = this.activeTasks.get(result.taskId); - if (task) { - this.activeTasks.delete(result.taskId); - const transferResult = result.data as TransferResult; - - if (transferResult.success) { - task.resolve(transferResult); - } else { - task.reject(new Error(transferResult.error || 'Unknown error')); - } - - this.processQueue(); - } - } - - /** - * Get available worker (one with no active task) - */ - private getAvailableWorker(): Worker | null { - // Simple round-robin: find worker with no active task - const activeWorkerIds = new Set(this.activeTasks.keys()); - for (let i = 0; i < this.workers.length; i++) { - if (!activeWorkerIds.has(i)) { - return this.workers[i]; - } - } - return null; - } - - /** - * Start batch processing timer - */ - private startBatchTimer(): void { - this.batchTimer = setInterval(() => { - this.flushBatch(); - }, this.batchFlushInterval); - } - - /** - * Add task to current batch - */ - private addToBatch(task: QueuedTask): void { - this.currentBatch.push(task); - - if (this.currentBatch.length >= this.batchSize) { - this.flushBatch(); - } - } - - /** - * Flush current batch to workers - */ - private flushBatch(): void { - if (this.currentBatch.length === 0) return; - - const batch = this.currentBatch.splice(0, this.batchSize); - - // Distribute batch across available workers - for (const task of batch) { - const worker = this.getAvailableWorker() || this.addWorker(); - - if (worker) { - this.activeTasks.set(task.id as unknown as number, task); - worker.postMessage({ taskId: task.id, type: task.type, data: task.data }); - - // Set timeout for task - setTimeout(() => { - if (this.activeTasks.has(task.id as unknown as number)) { - this.activeTasks.delete(task.id as unknown as number); - task.reject(new Error('Task timeout')); - } - }, this.taskTimeout); - } else { - // No workers available, put back in queue - task.reject(new Error('No workers available')); - } - } - } - - /** - * Process queued tasks - */ - private processQueue(): void { - if (this.queue.length === 0) return; - - while (this.queue.length > 0 && this.workers.length > this.activeTasks.size) { - const task = this.queue.shift(); - if (task) { - this.addToBatch(task); - } - } - } - - /** - * Execute a transfer in a worker thread - */ - async executeTransfer(request: TransferRequest): Promise { - return this.execute('transfer', request) as Promise; - } - - /** - * Execute a generic task in a worker thread - */ - private execute(type: string, data: unknown): Promise { - if (this.isShuttingDown) { - return Promise.reject(new Error('Worker pool is shutting down')); - } - - if (this.queue.length >= this.maxQueueSize) { - return Promise.reject(new Error('Queue is full')); - } - - return new Promise((resolve, reject) => { - const task: QueuedTask = { - id: ++this.taskIdCounter, - type, - data, - resolve, - reject, - timestamp: Date.now(), - }; - - // Check if we can execute immediately - const worker = this.getAvailableWorker(); - if (worker && this.currentBatch.length === 0) { - this.activeTasks.set(task.id, task); - worker.postMessage({ taskId: task.id, type, data }); - - // Set timeout - setTimeout(() => { - if (this.activeTasks.has(task.id)) { - this.activeTasks.delete(task.id); - reject(new Error('Task timeout')); - } - }, this.taskTimeout); - } else { - // Queue for batch processing - this.queue.push(task); - this.processQueue(); - } - }); - } - - /** - * Get pool statistics - */ - getStats(): { - workers: number; - activeTasks: number; - queuedTasks: number; - batchSize: number; - } { - return { - workers: this.workers.length, - activeTasks: this.activeTasks.size, - queuedTasks: this.queue.length, - batchSize: this.currentBatch.length, - }; - } - - /** - * Graceful shutdown - */ - async shutdown(timeoutMs: number = 30000): Promise { - this.isShuttingDown = true; - - if (this.batchTimer) { - clearInterval(this.batchTimer); - this.batchTimer = null; - } - - // Flush remaining batch - this.flushBatch(); - - // Wait for active tasks with timeout - const startTime = Date.now(); - while (this.activeTasks.size > 0 && Date.now() - startTime < timeoutMs) { - await new Promise(resolve => setTimeout(resolve, 100)); - } - - // Terminate all workers - await Promise.all(this.workers.map(w => w.terminate())); - this.workers = []; - - // Reject any remaining queued tasks - for (const task of this.queue) { - task.reject(new Error('Worker pool shutdown')); - } - this.queue = []; - - console.log('[TransferWorkerPool] Shutdown complete'); - } -} - -/** - * Worker thread execution logic - * This runs inside the worker thread, not the main thread - */ -function workerThreadLogic(): void { - if (!parentPort) return; - - parentPort.on('message', async (message: { taskId: number; type: string; data: unknown }) => { - const { taskId, type, data } = message; - - try { - let result: unknown; - - switch (type) { - case 'transfer': - result = await processTransfer(data as TransferRequest); - break; - default: - throw new Error(`Unknown task type: ${type}`); - } - - parentPort!.postMessage({ taskId, data: result }); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Unknown error'; - parentPort!.postMessage({ - taskId, - data: { - success: false, - error: errorMessage, - }, - }); - } - }); -} - -/** - * Process a transfer (runs in worker thread) - * This performs the actual balance calculations - */ -async function processTransfer(request: TransferRequest): Promise { - try { - const amount = BigInt(request.amount); - const fromLocal = BigInt(request.fromBalance.local); - const fromRemote = BigInt(request.fromBalance.remote); - const toLocal = BigInt(request.toBalance.local); - const toRemote = BigInt(request.toBalance.remote); - - // Validate balances - if (fromLocal < amount) { - return { - id: request.id, - success: false, - error: 'Insufficient balance', - timestamp: new Date().toISOString(), - }; - } - - if (toRemote < amount) { - return { - id: request.id, - success: false, - error: 'Insufficient recipient capacity', - timestamp: new Date().toISOString(), - }; - } - - // Calculate new balances - const newFromLocal = (fromLocal - amount).toString(); - const newFromRemote = (fromRemote + amount).toString(); - const newToLocal = (toLocal + amount).toString(); - const newToRemote = (toRemote - amount).toString(); - - // Simulate some processing time for cryptographic operations - // In production, this would include signature verification, etc. - await new Promise(resolve => setTimeout(resolve, 1)); - - return { - id: request.id, - success: true, - newFromBalance: { - local: newFromLocal, - remote: newFromRemote, - }, - newToBalance: { - local: newToLocal, - remote: newToRemote, - }, - timestamp: new Date().toISOString(), - }; - } catch (err) { - const errorMessage = err instanceof Error ? err.message : 'Unknown error'; - return { - id: request.id, - success: false, - error: errorMessage, - timestamp: new Date().toISOString(), - }; - } -} - -// If this file is being run as a worker thread, start the worker logic -if (!isMainThread) { - workerThreadLogic(); -} - -// Singleton instance for main thread -let poolInstance: TransferWorkerPool | null = null; - -export function getTransferWorkerPool(config?: WorkerPoolConfig): TransferWorkerPool { - if (!poolInstance) { - poolInstance = new TransferWorkerPool(config); - } - return poolInstance; -} - -export function resetTransferWorkerPool(): void { - poolInstance = null; -} - -export default TransferWorkerPool; -export type { TransferRequest, TransferResult }; diff --git a/legacy/taproot-assets-era/backend/src/ws/TransactionStatusHandler.ts b/legacy/taproot-assets-era/backend/src/ws/TransactionStatusHandler.ts deleted file mode 100644 index b985126..0000000 --- a/legacy/taproot-assets-era/backend/src/ws/TransactionStatusHandler.ts +++ /dev/null @@ -1,225 +0,0 @@ -/** - * WebSocket handlers for real-time transaction status updates - * Enables push notifications for pending, confirming, and confirmed transactions - */ - -import { WebSocket } from 'ws'; -import Database from '../db/Database'; - -interface TransactionUpdate { - id: string; - type: 'transfer' | 'claim' | 'deposit' | 'withdrawal'; - status: 'pending' | 'confirming' | 'confirmed' | 'failed'; - amount?: number; - recipient?: string; - sender?: string; - timestamp: number; - progress?: number; - estimatedTime?: string; - error?: string; -} - -interface ClientSubscription { - pubkey: string; - ws: WebSocket; - subscriptions: Set; -} - -// In-memory client registry (use Redis pub/sub for multi-instance in production) -const clients = new Map(); - -/** - * Subscribe a WebSocket client to transaction updates for a pubkey - */ -export function subscribeToTransactions( - clientId: string, - pubkey: string, - ws: WebSocket -): void { - const existing = clients.get(clientId); - if (existing) { - existing.pubkey = pubkey; - existing.subscriptions.add(pubkey); - } else { - clients.set(clientId, { - pubkey, - ws, - subscriptions: new Set([pubkey]), - }); - } - console.log(`[WS] Client ${clientId} subscribed to pubkey ${pubkey}`); -} - -/** - * Unsubscribe a client from all updates - */ -export function unsubscribeClient(clientId: string): void { - clients.delete(clientId); - console.log(`[WS] Client ${clientId} unsubscribed`); -} - -/** - * Broadcast a transaction update to all subscribed clients - */ -export function broadcastTransactionUpdate( - pubkey: string, - update: TransactionUpdate -): void { - const message = JSON.stringify({ - type: 'transaction_update', - data: update, - }); - - let sentCount = 0; - for (const [_clientId, client] of clients) { - if (client.subscriptions.has(pubkey) || client.pubkey === pubkey) { - if (client.ws.readyState === WebSocket.OPEN) { - client.ws.send(message); - sentCount++; - } - } - } - - console.log(`[WS] Broadcast transaction ${update.id} to ${sentCount} clients`); -} - -/** - * Send a transaction status update to a specific client - */ -export function sendTransactionStatus( - clientId: string, - update: TransactionUpdate -): boolean { - const client = clients.get(clientId); - if (!client || client.ws.readyState !== WebSocket.OPEN) { - return false; - } - - client.ws.send(JSON.stringify({ - type: 'transaction_update', - data: update, - })); - return true; -} - -/** - * Create a new transaction and broadcast its initial pending status - */ -export async function createAndBroadcastTransaction( - tx: { - id: string; - type: TransactionUpdate['type']; - from_pubkey?: string; - to_pubkey?: string; - amount?: number; - metadata?: Record; - } -): Promise { - const db = Database.getInstance(); - - // Save to database - await db.createTransactionStatus(tx); - - // Broadcast to involved parties - const update: TransactionUpdate = { - id: tx.id, - type: tx.type, - status: 'pending', - amount: tx.amount, - sender: tx.from_pubkey, - recipient: tx.to_pubkey, - timestamp: Date.now(), - progress: 0, - estimatedTime: tx.type === 'transfer' ? '< 1 second' : '~10 minutes', - }; - - if (tx.from_pubkey) { - broadcastTransactionUpdate(tx.from_pubkey, update); - } - if (tx.to_pubkey && tx.to_pubkey !== tx.from_pubkey) { - broadcastTransactionUpdate(tx.to_pubkey, { ...update, status: 'pending' }); - } -} - -/** - * Update transaction status and broadcast to subscribers - */ -export async function updateAndBroadcastTransaction( - txId: string, - status: TransactionUpdate['status'], - metadata?: Record -): Promise { - const db = Database.getInstance(); - - // Update in database - await db.updateTransactionStatus(txId, status, metadata); - - // Get transaction details - const tx = await db.getTransactionStatus(txId); - if (!tx) return; - - // Build update message - const update: TransactionUpdate = { - id: txId, - type: tx.type as TransactionUpdate['type'], - status, - amount: tx.amount || undefined, - sender: tx.from_pubkey || undefined, - recipient: tx.to_pubkey || undefined, - timestamp: Date.now(), - progress: status === 'pending' ? 25 : status === 'confirming' ? 75 : 100, - estimatedTime: status === 'confirmed' ? 'Complete' : status === 'failed' ? 'Failed' : undefined, - error: metadata?.error as string | undefined, - }; - - // Broadcast to involved parties - if (tx.from_pubkey) { - broadcastTransactionUpdate(tx.from_pubkey, update); - } - if (tx.to_pubkey && tx.to_pubkey !== tx.from_pubkey) { - broadcastTransactionUpdate(tx.to_pubkey, update); - } -} - -/** - * Get active transaction count for metrics - */ -export function getActiveSubscriptionCount(): number { - return clients.size; -} - -/** - * Handle WebSocket message for transaction subscription - */ -export function handleTransactionMessage( - clientId: string, - message: unknown, - ws: WebSocket -): void { - const msg = message as { type: string; pubkey?: string; action?: string }; - - if (msg.type === 'subscribe_transactions' && msg.pubkey) { - subscribeToTransactions(clientId, msg.pubkey, ws); - - // Send acknowledgment - ws.send(JSON.stringify({ - type: 'subscribed', - pubkey: msg.pubkey, - })); - } - - if (msg.type === 'unsubscribe_transactions') { - unsubscribeClient(clientId); - } -} - -export default { - subscribeToTransactions, - unsubscribeClient, - broadcastTransactionUpdate, - sendTransactionStatus, - createAndBroadcastTransaction, - updateAndBroadcastTransaction, - getActiveSubscriptionCount, - handleTransactionMessage, -}; diff --git a/legacy/taproot-assets-era/backend/src/ws/WebSocketServer.ts b/legacy/taproot-assets-era/backend/src/ws/WebSocketServer.ts deleted file mode 100644 index b60edfb..0000000 --- a/legacy/taproot-assets-era/backend/src/ws/WebSocketServer.ts +++ /dev/null @@ -1,440 +0,0 @@ -/** - * WebSocket server for real-time channel updates and transfer notifications. - * - * SECURITY HARDENING: - * - JWT authentication required on connection upgrade - * - Message size limit (64KB) - * - Rate limiting (100 messages/minute per connection) - * - Heartbeat ping/pong (30s interval, 90s timeout kills dead connections) - * - JSON structure validation before processing - */ - -import { Server as HttpServer } from 'http'; -import { WebSocketServer as WsServer, WebSocket } from 'ws'; -import { verifyToken, AuthPayload } from '../auth/AuthMiddleware'; - -/** Maximum message size in bytes (64KB) */ -const MAX_MESSAGE_SIZE = 64 * 1024; -/** Maximum messages per rate limit window */ -const RATE_LIMIT_MAX = 100; -/** Rate limit window in milliseconds (60 seconds) */ -const RATE_LIMIT_WINDOW_MS = 60_000; -/** Heartbeat ping interval (30 seconds) */ -const HEARTBEAT_INTERVAL_MS = 30_000; -/** Connection considered dead after this many ms without pong (90 seconds) */ -const HEARTBEAT_TIMEOUT_MS = 90_000; - -interface AuthenticatedClient { - ws: WebSocket; - pubkey: string; - subscribedChannels: Set; - /** Timestamps of recent messages for rate limiting */ - messageTimestamps: number[]; - /** Last time we received a pong from this client */ - lastPong: number; - /** Whether we are waiting for a pong response */ - awaitingPong: boolean; -} - -export class WebSocketManager { - private wss: WsServer; - private clients: Map = new Map(); - // Map from channel ID to set of connected client IDs - private channelSubscriptions: Map> = new Map(); - // Map from pubkey to set of client IDs (a user may have multiple connections) - private pubkeyClients: Map> = new Map(); - private clientIdCounter = 0; - private heartbeatTimer: NodeJS.Timeout | null = null; - - constructor(server: HttpServer) { - this.wss = new WsServer({ - server, - path: '/ws', - maxPayload: MAX_MESSAGE_SIZE, - }); - - this.wss.on('connection', (ws, req) => { - this.handleConnection(ws, req.url || ''); - }); - - // Start heartbeat check - this.heartbeatTimer = setInterval(() => this.checkHeartbeats(), HEARTBEAT_INTERVAL_MS); - - console.log('[WebSocket] Server initialized on /ws'); - } - - /** - * Check all connections for heartbeat health. - * Sends ping to alive connections, terminates dead ones. - */ - private checkHeartbeats(): void { - const now = Date.now(); - - for (const [clientId, client] of this.clients) { - if (client.ws.readyState !== WebSocket.OPEN) { - this.handleDisconnect(clientId); - continue; - } - - // If we sent a ping and haven't gotten a pong within the timeout, kill it - if (client.awaitingPong && (now - client.lastPong) > HEARTBEAT_TIMEOUT_MS) { - console.log(`[WebSocket] Heartbeat timeout for ${clientId}, terminating`); - client.ws.terminate(); - this.handleDisconnect(clientId); - continue; - } - - // Send ping - client.awaitingPong = true; - client.ws.ping(); - } - } - - private handleConnection(ws: WebSocket, url: string): void { - const clientId = `client_${++this.clientIdCounter}`; - - // Extract token from query string - const urlParams = new URL(url, 'http://localhost'); - const token = urlParams.searchParams.get('token'); - - // SECURITY: Require authentication — reject connections without valid JWT - if (!token) { - ws.send( - JSON.stringify({ - event: 'error', - data: { message: 'Authentication required: provide ?token=' }, - }) - ); - ws.close(4001, 'Authentication required'); - return; - } - - let auth: AuthPayload; - try { - auth = verifyToken(token); - console.log(`[WebSocket] Authenticated: ${auth.pubkey.slice(0, 16)}...`); - } catch { - console.log(`[WebSocket] Invalid token for ${clientId}`); - ws.send( - JSON.stringify({ - event: 'error', - data: { message: 'Invalid authentication token' }, - }) - ); - ws.close(4001, 'Authentication failed'); - return; - } - - const now = Date.now(); - const client: AuthenticatedClient = { - ws, - pubkey: auth.pubkey, - subscribedChannels: new Set(), - messageTimestamps: [], - lastPong: now, - awaitingPong: false, - }; - - this.clients.set(clientId, client); - - // Track pubkey -> clients mapping - if (!this.pubkeyClients.has(auth.pubkey)) { - this.pubkeyClients.set(auth.pubkey, new Set()); - } - this.pubkeyClients.get(auth.pubkey)!.add(clientId); - - // Send welcome message - ws.send( - JSON.stringify({ - event: 'connected', - data: { - clientId, - authenticated: true, - pubkey: auth.pubkey.slice(0, 16), - }, - }) - ); - - // Handle pong responses for heartbeat - ws.on('pong', () => { - client.lastPong = Date.now(); - client.awaitingPong = false; - }); - - // Handle incoming messages - ws.on('message', (data) => { - const raw = data.toString(); - - // SECURITY: Message size check (defense in depth — maxPayload handles binary) - if (raw.length > MAX_MESSAGE_SIZE) { - ws.send( - JSON.stringify({ - event: 'error', - data: { message: 'Message exceeds maximum size of 64KB' }, - }) - ); - return; - } - - // SECURITY: Rate limiting - if (!this.checkRateLimit(client)) { - ws.send( - JSON.stringify({ - event: 'error', - data: { message: `Rate limit exceeded: max ${RATE_LIMIT_MAX} messages per minute` }, - }) - ); - return; - } - - this.handleMessage(clientId, raw); - }); - - // Handle disconnection - ws.on('close', () => { - this.handleDisconnect(clientId); - }); - - ws.on('error', (err) => { - console.log(`[WebSocket] Error for ${clientId}:`, err.message); - this.handleDisconnect(clientId); - }); - - console.log(`[WebSocket] New connection: ${clientId}`); - } - - /** - * Check and enforce rate limiting for a client. - * Returns true if message is allowed, false if rate limited. - */ - private checkRateLimit(client: AuthenticatedClient): boolean { - const now = Date.now(); - const windowStart = now - RATE_LIMIT_WINDOW_MS; - - // Remove timestamps outside the window - client.messageTimestamps = client.messageTimestamps.filter(ts => ts > windowStart); - - if (client.messageTimestamps.length >= RATE_LIMIT_MAX) { - return false; - } - - client.messageTimestamps.push(now); - return true; - } - - private handleMessage(clientId: string, raw: string): void { - const client = this.clients.get(clientId); - if (!client) return; - - // SECURITY: Validate JSON structure before processing - let message: { event?: unknown; data?: unknown }; - try { - message = JSON.parse(raw) as { event?: unknown; data?: unknown }; - } catch { - client.ws.send( - JSON.stringify({ - event: 'error', - data: { message: 'Invalid JSON message' }, - }) - ); - return; - } - - // Validate message has required structure - if (!message || typeof message !== 'object' || typeof message.event !== 'string') { - client.ws.send( - JSON.stringify({ - event: 'error', - data: { message: 'Message must have a string "event" field' }, - }) - ); - return; - } - - switch (message.event) { - case 'subscribe': { - const data = message.data as { channelId?: string } | undefined; - const channelId = data?.channelId; - if (!channelId || typeof channelId !== 'string') { - client.ws.send( - JSON.stringify({ - event: 'error', - data: { message: 'channelId is required for subscribe' }, - }) - ); - return; - } - - // Subscribe to channel updates - client.subscribedChannels.add(channelId); - if (!this.channelSubscriptions.has(channelId)) { - this.channelSubscriptions.set(channelId, new Set()); - } - this.channelSubscriptions.get(channelId)!.add(clientId); - - client.ws.send( - JSON.stringify({ - event: 'subscribed', - data: { channelId }, - }) - ); - - console.log(`[WebSocket] ${clientId} subscribed to channel ${channelId}`); - break; - } - - case 'unsubscribe': { - const data = message.data as { channelId?: string } | undefined; - const channelId = data?.channelId; - if (channelId && typeof channelId === 'string') { - client.subscribedChannels.delete(channelId); - this.channelSubscriptions.get(channelId)?.delete(clientId); - } - - client.ws.send( - JSON.stringify({ - event: 'unsubscribed', - data: { channelId }, - }) - ); - break; - } - - case 'ping': { - client.ws.send(JSON.stringify({ event: 'pong', data: {} })); - break; - } - - default: { - client.ws.send( - JSON.stringify({ - event: 'error', - data: { message: `Unknown event: ${message.event}` }, - }) - ); - } - } - } - - private handleDisconnect(clientId: string): void { - const client = this.clients.get(clientId); - if (!client) return; - - // Remove from channel subscriptions - for (const channelId of client.subscribedChannels) { - this.channelSubscriptions.get(channelId)?.delete(clientId); - if (this.channelSubscriptions.get(channelId)?.size === 0) { - this.channelSubscriptions.delete(channelId); - } - } - - // Remove from pubkey tracking - if (client.pubkey) { - this.pubkeyClients.get(client.pubkey)?.delete(clientId); - if (this.pubkeyClients.get(client.pubkey)?.size === 0) { - this.pubkeyClients.delete(client.pubkey); - } - } - - this.clients.delete(clientId); - console.log(`[WebSocket] ${clientId} disconnected`); - } - - /** - * Broadcast an event to all clients subscribed to a specific channel. - */ - broadcastToChannel(channelId: string, event: string, data: unknown): void { - const subscribers = this.channelSubscriptions.get(channelId); - if (!subscribers || subscribers.size === 0) return; - - const message = JSON.stringify({ event, data }); - - for (const clientId of subscribers) { - const client = this.clients.get(clientId); - if (client && client.ws.readyState === WebSocket.OPEN) { - client.ws.send(message); - } - } - - console.log(`[WebSocket] Broadcast "${event}" to ${subscribers.size} subscribers of channel ${channelId}`); - } - - /** - * Broadcast an event to all connections for a specific pubkey. - */ - broadcastToUser(pubkey: string, event: string, data: unknown): void { - const clientIds = this.pubkeyClients.get(pubkey); - if (!clientIds || clientIds.size === 0) return; - - const message = JSON.stringify({ event, data }); - - for (const clientId of clientIds) { - const client = this.clients.get(clientId); - if (client && client.ws.readyState === WebSocket.OPEN) { - client.ws.send(message); - } - } - - console.log(`[WebSocket] Broadcast "${event}" to ${clientIds.size} connections for pubkey ${pubkey.slice(0, 16)}...`); - } - - /** - * Broadcast a channel state change to all subscribers of that channel. - */ - broadcastChannelStateChange(channelId: string, newState: string, details?: Record): void { - this.broadcastToChannel(channelId, 'channel:state_changed', { - channelId, - state: newState, - ...details, - }); - } - - /** - * Broadcast balance update to a specific user for a specific channel. - */ - broadcastBalanceUpdate(pubkey: string, channelId: string, balance: { - local: string; - remote: string; - capacity: string; - }): void { - this.broadcastToUser(pubkey, 'balance:updated', { - channelId, - ...balance, - }); - } - - /** - * Get the number of connected clients. - */ - getConnectionCount(): number { - return this.clients.size; - } - - /** - * Graceful shutdown: stop heartbeat and close all connections. - */ - shutdown(): void { - if (this.heartbeatTimer) { - clearInterval(this.heartbeatTimer); - this.heartbeatTimer = null; - } - for (const [, client] of this.clients) { - client.ws.close(1001, 'Server shutting down'); - } - this.clients.clear(); - this.channelSubscriptions.clear(); - this.pubkeyClients.clear(); - } -} - -// Singleton instance, initialized when the HTTP server starts -let wsManager: WebSocketManager | null = null; - -export function initializeWebSocket(server: HttpServer): WebSocketManager { - wsManager = new WebSocketManager(server); - return wsManager; -} - -export function getWebSocketManager(): WebSocketManager | null { - return wsManager; -} diff --git a/legacy/taproot-assets-era/backend/tsconfig.json b/legacy/taproot-assets-era/backend/tsconfig.json deleted file mode 100644 index 4a347ca..0000000 --- a/legacy/taproot-assets-era/backend/tsconfig.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "module": "commonjs", - "lib": ["ES2022"], - "outDir": "./dist", - "rootDir": "./src", - "strict": true, - "esModuleInterop": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "resolveJsonModule": true, - "declaration": true, - "declarationMap": true, - "sourceMap": true, - "noEmit": false, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noImplicitReturns": true, - "noFallthroughCasesInSwitch": true, - "moduleResolution": "node", - "typeRoots": ["./node_modules/@types"] - }, - "include": ["src/**/*"], - "exclude": ["node_modules", "dist"] -} diff --git a/legacy/taproot-assets-era/docker-compose.prod.yml b/legacy/taproot-assets-era/docker-compose.prod.yml deleted file mode 100644 index bd6f9a9..0000000 --- a/legacy/taproot-assets-era/docker-compose.prod.yml +++ /dev/null @@ -1,479 +0,0 @@ -# RuneBolt Production Docker Compose -# Version: 1.0.0 -# Usage: docker compose -f docker-compose.prod.yml up -d - -version: '3.8' - -services: - # ============================================ - # FRONTEND (Next.js) - # ============================================ - frontend: - image: ghcr.io/bitmap-asset/runebolt-frontend:${VERSION:-latest} - container_name: runebolt-frontend - restart: unless-stopped - ports: - - "3000:3000" - environment: - - NODE_ENV=production - - NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL:-https://api.runebolt.io} - - NEXT_PUBLIC_WS_URL=${NEXT_PUBLIC_WS_URL:-wss://ws.runebolt.io} - - PORT=3000 - healthcheck: - test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:3000/health"] - interval: 30s - timeout: 10s - retries: 3 - start_period: 40s - deploy: - resources: - limits: - cpus: '0.5' - memory: 512M - reservations: - cpus: '0.25' - memory: 256M - networks: - - frontend - - monitoring - logging: - driver: "json-file" - options: - max-size: "100m" - max-file: "5" - - # ============================================ - # BACKEND API - # ============================================ - backend-api: - build: - context: ./backend - dockerfile: ../Dockerfile - target: production - image: runebolt-backend:local - container_name: runebolt-backend-api - restart: unless-stopped - ports: - - "3001:3001" - environment: - - NODE_ENV=production - - PORT=3001 - - DATABASE_PATH=/data/runebolt.db - - VAULT_ADDR=http://vault:8200 - - REDIS_URL=redis://redis:6379 - - POSTGRES_URL=postgresql://postgres:5432/runebolt - - POSTGRES_USER=${POSTGRES_USER:-runebolt} - - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - - JWT_SECRET=${JWT_SECRET} - - NETWORK=${NETWORK:-mainnet} - - MEMPOOL_API=${MEMPOOL_API:-https://mempool.space/api} - - RUNEBOLT_XPUB=${RUNEBOLT_XPUB} - - RUNEBOLT_PRIVKEY=${RUNEBOLT_PRIVKEY} - - VAULT_TOKEN=${VAULT_TOKEN} - volumes: - - backend-data:/data - - ./logs/backend:/app/logs - healthcheck: - test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:3001/health"] - interval: 30s - timeout: 10s - retries: 3 - start_period: 40s - deploy: - resources: - limits: - cpus: '1.0' - memory: 1G - reservations: - cpus: '0.5' - memory: 512M - networks: - - backend - - frontend - - database - - cache - - monitoring - depends_on: - postgres: - condition: service_healthy - redis: - condition: service_healthy - logging: - driver: "json-file" - options: - max-size: "100m" - max-file: "5" - - # ============================================ - # BACKEND WORKERS - # ============================================ - backend-worker: - build: - context: ./backend - dockerfile: ../Dockerfile - target: worker - image: runebolt-backend:local - container_name: runebolt-backend-worker - restart: unless-stopped - environment: - - NODE_ENV=production - - VAULT_ADDR=http://vault:8200 - - REDIS_URL=redis://redis:6379 - - POSTGRES_URL=postgresql://postgres:5432/runebolt - - POSTGRES_USER=${POSTGRES_USER:-runebolt} - - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - - JWT_SECRET=${JWT_SECRET} - - VAULT_TOKEN=${VAULT_TOKEN} - - NETWORK=${NETWORK:-mainnet} - - MEMPOOL_API=${MEMPOOL_API:-https://mempool.space/api} - - RUNEBOLT_XPUB=${RUNEBOLT_XPUB} - - RUNEBOLT_PRIVKEY=${RUNEBOLT_PRIVKEY} - volumes: - - backend-data:/data - - ./logs/worker:/app/logs - deploy: - replicas: 2 - resources: - limits: - cpus: '0.5' - memory: 512M - reservations: - cpus: '0.25' - memory: 256M - networks: - - backend - - database - - cache - depends_on: - postgres: - condition: service_healthy - redis: - condition: service_healthy - logging: - driver: "json-file" - options: - max-size: "100m" - max-file: "5" - - # ============================================ - # LOAD BALANCER (HAProxy) - # ============================================ - haproxy: - image: haproxy:2.8-alpine - container_name: runebolt-haproxy - restart: unless-stopped - ports: - - "80:80" - - "443:443" - - "8404:8404" - volumes: - - ./infrastructure/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro - - ./infrastructure/ssl/certs:/etc/ssl/certs:ro - - ./infrastructure/ssl/private:/etc/ssl/private:ro - networks: - - frontend - - backend - depends_on: - - frontend - - backend-api - logging: - driver: "json-file" - options: - max-size: "50m" - max-file: "3" - - # ============================================ - # POSTGRESQL - # ============================================ - postgres: - image: postgres:15-alpine - container_name: runebolt-postgres - restart: unless-stopped - ports: - - "5432:5432" - environment: - - POSTGRES_DB=runebolt - - POSTGRES_USER=${POSTGRES_USER:-runebolt} - - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - - PGDATA=/var/lib/postgresql/data/pgdata - volumes: - - postgres-data:/var/lib/postgresql/data - - postgres-wal:/var/lib/postgresql/wal - - ./backups/postgres:/backups - - ./infrastructure/postgres/init-scripts:/docker-entrypoint-initdb.d:ro - healthcheck: - test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-runebolt} -d runebolt"] - interval: 10s - timeout: 5s - retries: 5 - start_period: 30s - deploy: - resources: - limits: - cpus: '2.0' - memory: 4G - reservations: - cpus: '1.0' - memory: 2G - networks: - - database - logging: - driver: "json-file" - options: - max-size: "100m" - max-file: "5" - - # ============================================ - # PGBOUNCER (Connection Pooling) - # ============================================ - pgbouncer: - image: pgbouncer/pgbouncer:1.20 - container_name: runebolt-pgbouncer - restart: unless-stopped - ports: - - "6432:6432" - environment: - - DATABASES_HOST=postgres - - DATABASES_PORT=5432 - - DATABASES_DATABASE=runebolt - - DATABASES_USER=${POSTGRES_USER:-runebolt} - - DATABASES_PASSWORD=${POSTGRES_PASSWORD} - - POOL_MODE=transaction - - MAX_CLIENT_CONN=1000 - - DEFAULT_POOL_SIZE=25 - - RESERVE_POOL_SIZE=5 - - MAX_DB_CONNECTIONS=100 - - SERVER_IDLE_TIMEOUT=600 - - SERVER_LIFETIME=3600 - volumes: - - ./infrastructure/pgbouncer/pgbouncer.ini:/etc/pgbouncer/pgbouncer.ini:ro - networks: - - database - depends_on: - postgres: - condition: service_healthy - logging: - driver: "json-file" - options: - max-size: "50m" - max-file: "3" - - # ============================================ - # REDIS - # ============================================ - redis: - image: redis:7-alpine - container_name: runebolt-redis - restart: unless-stopped - ports: - - "6379:6379" - command: > - redis-server - --appendonly yes - --appendfsync everysec - --maxmemory 2gb - --maxmemory-policy allkeys-lru - --save 900 1 - --save 300 10 - --save 60 10000 - --dir /data - volumes: - - redis-data:/data - - ./backups/redis:/backups - healthcheck: - test: ["CMD", "redis-cli", "ping"] - interval: 10s - timeout: 5s - retries: 3 - start_period: 10s - deploy: - resources: - limits: - cpus: '1.0' - memory: 2G - reservations: - cpus: '0.5' - memory: 1G - networks: - - cache - logging: - driver: "json-file" - options: - max-size: "100m" - max-file: "5" - - # ============================================ - # HASHICORP VAULT - # ============================================ - vault: - image: hashicorp/vault:1.15 - container_name: runebolt-vault - restart: unless-stopped - ports: - - "8200:8200" - cap_add: - - IPC_LOCK - environment: - - VAULT_ADDR=http://0.0.0.0:8200 - - VAULT_API_ADDR=http://0.0.0.0:8200 - - VAULT_LOCAL_CONFIG=${VAULT_LOCAL_CONFIG} - - VAULT_DEV_ROOT_TOKEN_ID=${VAULT_DEV_ROOT_TOKEN_ID} - volumes: - - vault-data:/vault/file - - ./infrastructure/vault/config:/vault/config:ro - - ./infrastructure/vault/policies:/vault/policies:ro - command: server -config=/vault/config/vault.hcl - networks: - - backend - logging: - driver: "json-file" - options: - max-size: "50m" - max-file: "3" - - # ============================================ - # PROMETHEUS - # ============================================ - prometheus: - image: prom/prometheus:v2.48 - container_name: runebolt-prometheus - restart: unless-stopped - ports: - - "9090:9090" - command: - - '--config.file=/etc/prometheus/prometheus.yml' - - '--storage.tsdb.path=/prometheus' - - '--storage.tsdb.retention.time=30d' - - '--storage.tsdb.retention.size=50GB' - - '--web.console.libraries=/usr/share/prometheus/console_libraries' - - '--web.console.templates=/usr/share/prometheus/consoles' - - '--web.enable-lifecycle' - - '--web.enable-admin-api' - volumes: - - ./monitoring/prometheus.yml:/etc/prometheus/prometheus.yml:ro - - ./monitoring/alerts:/etc/prometheus/alerts:ro - - prometheus-data:/prometheus - networks: - - monitoring - logging: - driver: "json-file" - options: - max-size: "50m" - max-file: "3" - - # ============================================ - # GRAFANA - # ============================================ - grafana: - image: grafana/grafana:10.2 - container_name: runebolt-grafana - restart: unless-stopped - ports: - - "3003:3000" - environment: - - GF_SECURITY_ADMIN_USER=${GRAFANA_ADMIN_USER:-admin} - - GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_ADMIN_PASSWORD} - - GF_USERS_ALLOW_SIGN_UP=false - - GF_SERVER_ROOT_URL=${GRAFANA_ROOT_URL:-https://grafana.runebolt.io} - - GF_SMTP_ENABLED=${GF_SMTP_ENABLED:-false} - - GF_SMTP_HOST=${GF_SMTP_HOST} - - GF_SMTP_USER=${GF_SMTP_USER} - - GF_SMTP_PASSWORD=${GF_SMTP_PASSWORD} - - GF_SMTP_FROM_ADDRESS=${GF_SMTP_FROM_ADDRESS} - - GF_ALERTING_ENABLED=true - - GF_UNIFIED_ALERTING_ENABLED=true - volumes: - - grafana-data:/var/lib/grafana - - ./monitoring/grafana/dashboards:/etc/grafana/provisioning/dashboards:ro - - ./monitoring/grafana/datasources:/etc/grafana/provisioning/datasources:ro - - ./monitoring/grafana/notifiers:/etc/grafana/provisioning/notifiers:ro - networks: - - monitoring - logging: - driver: "json-file" - options: - max-size: "50m" - max-file: "3" - - # ============================================ - # LOKI (Log Aggregation) - # ============================================ - loki: - image: grafana/loki:2.9 - container_name: runebolt-loki - restart: unless-stopped - ports: - - "3100:3100" - volumes: - - ./monitoring/loki/loki.yml:/etc/loki/local-config.yaml:ro - - loki-data:/loki - command: -config.file=/etc/loki/local-config.yaml - networks: - - monitoring - logging: - driver: "json-file" - options: - max-size: "50m" - max-file: "3" - - # ============================================ - # PROMTAIL (Log Shipper) - # ============================================ - promtail: - image: grafana/promtail:2.9 - container_name: runebolt-promtail - restart: unless-stopped - volumes: - - ./monitoring/promtail/promtail.yml:/etc/promtail/config.yml:ro - - ./logs:/var/log/runebolt:ro - - /var/lib/docker/containers:/var/lib/docker/containers:ro - - /var/run/docker.sock:/var/run/docker.sock:ro - command: -config.file=/etc/promtail/config.yml - networks: - - monitoring - depends_on: - - loki - logging: - driver: "json-file" - options: - max-size: "50m" - max-file: "3" - -# ============================================ -# NETWORKS -# ============================================ -networks: - frontend: - driver: bridge - backend: - driver: bridge - internal: false - database: - driver: bridge - internal: false - cache: - driver: bridge - internal: false - monitoring: - driver: bridge - -# ============================================ -# VOLUMES -# ============================================ -volumes: - backend-data: - driver: local - postgres-data: - driver: local - postgres-wal: - driver: local - redis-data: - driver: local - vault-data: - driver: local - prometheus-data: - driver: local - grafana-data: - driver: local - loki-data: - driver: local diff --git a/legacy/taproot-assets-era/docker-compose.yml b/legacy/taproot-assets-era/docker-compose.yml deleted file mode 100644 index 327d611..0000000 --- a/legacy/taproot-assets-era/docker-compose.yml +++ /dev/null @@ -1,338 +0,0 @@ -# RuneBolt Production Docker Compose Configuration -# Version: 1.0.0 -# Usage: docker stack deploy -c docker-compose.yml runebolt - -version: '3.8' - -services: - # FRONTEND (Next.js) - frontend: - image: ghcr.io/bitmap-asset/runebolt-frontend:${VERSION:-latest} - deploy: - replicas: 3 - update_config: - parallelism: 1 - delay: 10s - order: start-first - failure_action: rollback - restart_policy: - condition: any - delay: 5s - max_attempts: 3 - resources: - limits: - cpus: '0.5' - memory: 512M - reservations: - cpus: '0.25' - memory: 256M - placement: - constraints: - - node.role == worker - environment: - - NODE_ENV=production - - NEXT_PUBLIC_API_URL=https://api.runebolt.io - - NEXT_PUBLIC_WS_URL=wss://ws.runebolt.io - - PORT=3000 - healthcheck: - test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:3000/health"] - interval: 30s - timeout: 10s - retries: 3 - networks: - - frontend - - monitoring - - # BACKEND API - backend-api: - image: ghcr.io/bitmap-asset/runebolt-backend:${VERSION:-latest} - deploy: - replicas: 3 - update_config: - parallelism: 1 - delay: 15s - order: start-first - failure_action: rollback - restart_policy: - condition: any - delay: 5s - max_attempts: 3 - resources: - limits: - cpus: '1.0' - memory: 1G - reservations: - cpus: '0.5' - memory: 512M - placement: - constraints: - - node.role == worker - environment: - - NODE_ENV=production - - PORT=3001 - - DATABASE_PATH=/data/runebolt.db - - VAULT_ADDR=http://vault:8200 - - REDIS_URL=redis://redis:6379 - - POSTGRES_URL=postgresql://pgbouncer:6432/runebolt - secrets: - - vault_token - - jwt_secret - volumes: - - backend-data:/data - healthcheck: - test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:3001/health"] - interval: 30s - timeout: 10s - retries: 3 - networks: - - backend - - frontend - - database - - cache - - monitoring - - # BACKEND WORKERS - backend-worker: - image: ghcr.io/bitmap-asset/runebolt-backend:${VERSION:-latest} - command: ["node", "dist/worker.js"] - deploy: - replicas: 2 - restart_policy: - condition: any - resources: - limits: - cpus: '0.5' - memory: 512M - environment: - - NODE_ENV=production - - VAULT_ADDR=http://vault:8200 - - REDIS_URL=redis://redis:6379 - - POSTGRES_URL=postgresql://pgbouncer:6432/runebolt - secrets: - - vault_token - volumes: - - backend-data:/data - networks: - - backend - - database - - cache - - # LOAD BALANCER (HAProxy) - haproxy: - image: haproxy:2.8-alpine - deploy: - replicas: 2 - placement: - constraints: - - node.role == manager - ports: - - "80:80" - - "443:443" - configs: - - source: haproxy_config - target: /usr/local/etc/haproxy/haproxy.cfg - secrets: - - ssl_certificate - - ssl_private_key - networks: - - frontend - - backend - - # POSTGRESQL PRIMARY - postgres-primary: - image: postgres:15-alpine - deploy: - replicas: 1 - placement: - constraints: - - node.labels.database == primary - environment: - - POSTGRES_DB=runebolt - - POSTGRES_USER=runebolt - - POSTGRES_PASSWORD_FILE=/run/secrets/postgres_password - - PGDATA=/var/lib/postgresql/data/pgdata - secrets: - - postgres_password - volumes: - - postgres-data:/var/lib/postgresql/data - - postgres-wal:/var/lib/postgresql/wal - networks: - - database - - # POSTGRESQL REPLICA - postgres-replica: - image: postgres:15-alpine - deploy: - replicas: 2 - placement: - constraints: - - node.labels.database == replica - environment: - - POSTGRES_DB=runebolt - - POSTGRES_USER=runebolt - - POSTGRES_PASSWORD_FILE=/run/secrets/postgres_password - - REPLICATION_MODE=slave - secrets: - - postgres_password - volumes: - - postgres-replica-data:/var/lib/postgresql/data - networks: - - database - - # PGBOUNCER - pgbouncer: - image: pgbouncer/pgbouncer:1.20 - deploy: - replicas: 2 - environment: - - DATABASES_HOST=postgres-primary - - DATABASES_PORT=5432 - - DATABASES_DATABASE=runebolt - - POOL_MODE=transaction - - MAX_CLIENT_CONN=1000 - secrets: - - postgres_password - networks: - - database - - # REDIS - redis: - image: redis:7-alpine - deploy: - replicas: 3 - placement: - max_replicas_per_node: 1 - command: redis-server --appendonly yes --maxmemory 2gb --maxmemory-policy allkeys-lru - volumes: - - redis-data:/data - networks: - - cache - - # VAULT - vault: - image: hashicorp/vault:1.15 - deploy: - replicas: 1 - placement: - constraints: - - node.labels.vault == true - cap_add: - - IPC_LOCK - environment: - - VAULT_ADDR=http://0.0.0.0:8200 - configs: - - source: vault_config - target: /vault/config/vault.hcl - volumes: - - vault-data:/vault/file - networks: - - backend - - # PROMETHEUS - prometheus: - image: prom/prometheus:v2.48 - deploy: - replicas: 1 - placement: - constraints: - - node.role == manager - command: - - '--config.file=/etc/prometheus/prometheus.yml' - - '--storage.tsdb.retention.time=30d' - configs: - - source: prometheus_config - target: /etc/prometheus/prometheus.yml - volumes: - - prometheus-data:/prometheus - networks: - - monitoring - - # GRAFANA - grafana: - image: grafana/grafana:10.2 - deploy: - replicas: 1 - placement: - constraints: - - node.role == manager - environment: - - GF_SECURITY_ADMIN_PASSWORD__FILE=/run/secrets/grafana_admin_password - secrets: - - grafana_admin_password - volumes: - - grafana-data:/var/lib/grafana - networks: - - monitoring - - # LOKI - loki: - image: grafana/loki:2.9 - deploy: - replicas: 1 - placement: - constraints: - - node.role == manager - volumes: - - loki-data:/loki - networks: - - monitoring - -networks: - frontend: - driver: overlay - attachable: true - backend: - driver: overlay - internal: true - attachable: true - database: - driver: overlay - internal: true - cache: - driver: overlay - internal: true - monitoring: - driver: overlay - attachable: true - -volumes: - backend-data: - driver: rexray/ebs - postgres-data: - driver: rexray/ebs - postgres-wal: - driver: rexray/ebs - postgres-replica-data: - driver: rexray/ebs - redis-data: - driver: local - vault-data: - driver: rexray/ebs - prometheus-data: - driver: local - grafana-data: - driver: local - loki-data: - driver: local - -secrets: - vault_token: - external: true - jwt_secret: - external: true - postgres_password: - external: true - grafana_admin_password: - external: true - ssl_certificate: - external: true - ssl_private_key: - external: true - -configs: - haproxy_config: - external: true - vault_config: - external: true - prometheus_config: - external: true diff --git a/legacy/taproot-assets-era/frontend/.gitignore b/legacy/taproot-assets-era/frontend/.gitignore deleted file mode 100644 index 7bb0d3e..0000000 --- a/legacy/taproot-assets-era/frontend/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -.next -node_modules -out -*.tsbuildinfo -next-env.d.ts diff --git a/legacy/taproot-assets-era/frontend/app/app/channels/page.tsx b/legacy/taproot-assets-era/frontend/app/app/channels/page.tsx deleted file mode 100644 index 20e0dc6..0000000 --- a/legacy/taproot-assets-era/frontend/app/app/channels/page.tsx +++ /dev/null @@ -1,407 +0,0 @@ -'use client'; - -import { useState, useEffect } from 'react'; -import { motion, AnimatePresence } from 'framer-motion'; -import { ArrowLeft, Plus, X, Check, Loader2 } from 'lucide-react'; -import Link from 'next/link'; -import ChannelCard from '@/components/ChannelCard'; -import GlassCard from '@/components/GlassCard'; -import { useUnisat } from '@/hooks/useUnisat'; -import { useApi } from '@/hooks/useApi'; -import { api } from '@/lib/api'; -import { demoChannels, demoUser } from '@/lib/demo-data'; -import { Channel, ChannelState } from '@/lib/types'; -import { formatDogAmount } from '@/lib/format'; -import clsx from 'clsx'; - -type OpenStep = 'amount' | 'review' | 'signing' | 'waiting' | 'success'; - -export default function ChannelsPage() { - const { connected, publicKey, signMessage } = useUnisat(); - const { - getChannels, - openChannel: apiOpenChannel, - closeChannel: apiCloseChannel, - authenticate, - } = useApi(); - - const [channels, setChannels] = useState(demoChannels); - const [showOpen, setShowOpen] = useState(false); - const [openStep, setOpenStep] = useState('amount'); - const [lockAmount, setLockAmount] = useState(''); - const [closingChannelId, setClosingChannelId] = useState(null); - const [balance, setBalance] = useState(demoUser.balance); - - // Load channels - useEffect(() => { - if (!connected || !publicKey) return; - const load = async () => { - if (!api.isAuthenticated()) { - const result = await authenticate(publicKey, signMessage); - if (!result) return; - } - const ch = await getChannels(); - if (ch) { - setChannels(ch); - const total = ch.reduce((sum, c) => sum + c.localBalance, 0); - setBalance(total); - } - }; - load(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [connected, publicKey]); - - const openChannels = channels.filter((c) => c.state === ChannelState.OPEN); - const otherChannels = channels.filter((c) => c.state !== ChannelState.OPEN); - - const handleOpenChannel = () => { - setShowOpen(true); - setOpenStep('amount'); - setLockAmount(''); - }; - - const handleReview = () => { - if (parseFloat(lockAmount) > 0) setOpenStep('review'); - }; - - const handleSign = async () => { - setOpenStep('signing'); - - if (!api.isAuthenticated()) { - // Demo mode - setTimeout(() => setOpenStep('waiting'), 1500); - setTimeout(() => setOpenStep('success'), 3500); - return; - } - - const result = await apiOpenChannel(parseFloat(lockAmount)); - if (result) { - setOpenStep('success'); - // Refresh channel list - const ch = await getChannels(); - if (ch) { - setChannels(ch); - const total = ch.reduce((sum, c) => sum + c.localBalance, 0); - setBalance(total); - } - } else { - setOpenStep('amount'); - } - }; - - const handleCloseModal = () => { - setShowOpen(false); - setOpenStep('amount'); - setLockAmount(''); - }; - - const handleCloseChannel = async (channelId: string) => { - setClosingChannelId(channelId); - - if (!api.isAuthenticated()) { - // Demo mode - setTimeout(() => { - setChannels((prev) => - prev.map((c) => - c.id === channelId ? { ...c, state: ChannelState.CLOSING } : c - ) - ); - setClosingChannelId(null); - }, 1500); - return; - } - - const result = await apiCloseChannel(channelId); - if (result) { - const ch = await getChannels(); - if (ch) setChannels(ch); - } - setClosingChannelId(null); - }; - - return ( -
- {/* Header */} -
-
- - - -
-

Payment Channels

- - {channels.length} - -
-
- - - Open Channel - -
- - {/* Channel List */} -
- {openChannels.length > 0 && ( -
-

- Open ({openChannels.length}) -

-
- {openChannels.map((channel, i) => ( -
- - {closingChannelId === channel.id && ( -
-
- - Closing channel... -
-
- )} -
- ))} -
-
- )} - - {otherChannels.length > 0 && ( -
-

- Other ({otherChannels.length}) -

-
- {otherChannels.map((channel, i) => ( - - ))} -
-
- )} -
- - {/* Open Channel Modal */} - - {showOpen && ( - - e.stopPropagation()} - className="w-full max-w-md overflow-hidden rounded-2xl border border-dark-700 bg-dark-800 shadow-2xl" - > -
-

Open New Channel

- -
- -
- - {openStep === 'amount' && ( - -
- -
- setLockAmount(e.target.value)} - placeholder="0.00000" - className="w-full rounded-xl border border-dark-700 bg-dark-900/60 px-4 py-3 pr-20 font-mono text-lg text-white placeholder-gray-500 outline-none focus:border-bitcoin/50" - /> -
- - DOG -
-
-

- Available: {formatDogAmount(balance)} DOG -

-
- - 0 - ? 'bg-gradient-to-r from-bitcoin to-orange-600 text-white shadow-lg shadow-bitcoin/20' - : 'bg-dark-700 text-gray-500 cursor-not-allowed' - )} - > - Continue - -
- )} - - {openStep === 'review' && ( - -
-

Locking

-

- {formatDogAmount(parseFloat(lockAmount))} -

-

DOG

-
- -
-
- Channel with - RuneBolt Hub -
-
- Type - 2-of-2 Taproot Multisig -
-
- On-chain fee - ~1,500 sats -
-
- -
- - - Sign with Unisat - -
-
- )} - - {openStep === 'signing' && ( - - -

- Opening channel... -

-

- Sending request to RuneBolt Hub -

-
- )} - - {openStep === 'waiting' && ( - - -

- Waiting for confirmation... -

-

- Broadcasting funding transaction -

-
- )} - - {openStep === 'success' && ( - - - - -

Channel Opened!

-

- {formatDogAmount(parseFloat(lockAmount))} DOG locked in channel -

- - Done - -
- )} -
-
-
-
- )} -
-
- ); -} diff --git a/legacy/taproot-assets-era/frontend/app/app/history/page.tsx b/legacy/taproot-assets-era/frontend/app/app/history/page.tsx deleted file mode 100644 index 844f575..0000000 --- a/legacy/taproot-assets-era/frontend/app/app/history/page.tsx +++ /dev/null @@ -1,218 +0,0 @@ -'use client'; - -import { useState, useMemo } from 'react'; -import { motion } from 'framer-motion'; -import { ArrowLeft, ArrowUpRight, ArrowDownLeft, Download, ChevronDown } from 'lucide-react'; -import Link from 'next/link'; -import GlassCard from '@/components/GlassCard'; -import { demoTransfers } from '@/lib/demo-data'; -import { Transfer } from '@/lib/types'; -import { formatDogAmount, formatAddress, formatTimeAgo } from '@/lib/format'; -import clsx from 'clsx'; - -type FilterTab = 'all' | 'sent' | 'received' | 'onchain'; - -export default function HistoryPage() { - const [activeTab, setActiveTab] = useState('all'); - const [visibleCount, setVisibleCount] = useState(5); - - const tabs: { key: FilterTab; label: string }[] = [ - { key: 'all', label: 'All' }, - { key: 'sent', label: 'Sent' }, - { key: 'received', label: 'Received' }, - { key: 'onchain', label: 'On-Chain' }, - ]; - - const filteredTransfers = useMemo(() => { - switch (activeTab) { - case 'sent': - return demoTransfers.filter((t) => t.direction === 'sent'); - case 'received': - return demoTransfers.filter((t) => t.direction === 'received'); - case 'onchain': - return []; - default: - return demoTransfers; - } - }, [activeTab]); - - const visibleTransfers = filteredTransfers.slice(0, visibleCount); - const hasMore = visibleCount < filteredTransfers.length; - - const exportCsv = () => { - const headers = ['Date', 'Direction', 'Amount (DOG)', 'Counterparty', 'Status']; - const rows = filteredTransfers.map((t) => [ - t.timestamp.toISOString(), - t.direction, - t.amount.toFixed(5), - t.counterpartyName || t.counterparty, - t.status, - ]); - - const csv = [headers, ...rows].map((row) => row.join(',')).join('\n'); - const blob = new Blob([csv], { type: 'text/csv' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `runebolt-history-${new Date().toISOString().split('T')[0]}.csv`; - a.click(); - URL.revokeObjectURL(url); - }; - - return ( -
- {/* Header */} -
-
- - - -

Transaction History

-
- - - Export CSV - -
- - {/* Filter Tabs */} -
- {tabs.map((tab) => ( - - ))} -
- - {/* Transfer List */} -
- {visibleTransfers.length === 0 ? ( - -

No transactions found

-

- {activeTab === 'onchain' - ? 'On-chain transactions will appear here' - : 'Try a different filter'} -

-
- ) : ( - visibleTransfers.map((transfer, i) => ( - - )) - )} -
- - {/* Load More */} - {hasMore && ( -
- setVisibleCount((prev) => prev + 5)} - className="flex mx-auto items-center gap-2 rounded-xl border border-dark-700 bg-dark-800 px-6 py-2.5 text-sm font-medium text-gray-300 transition-colors hover:border-dark-600 hover:text-white" - > - Load More - - -
- )} -
- ); -} - -function TransferRow({ transfer, index }: { transfer: Transfer; index: number }) { - return ( - - -
- {transfer.direction === 'received' ? ( - - ) : ( - - )} -
- -
-

- {transfer.direction === 'received' ? 'Received' : 'Sent'} -

-

- {transfer.counterpartyName - ? `${transfer.counterpartyName}@runebolt.io` - : formatAddress(transfer.counterparty)} -

-
- -
-

- {transfer.timestamp.toLocaleDateString('en-US', { - month: 'short', - day: 'numeric', - year: 'numeric', - })} -

-

- {transfer.timestamp.toLocaleTimeString('en-US', { - hour: '2-digit', - minute: '2-digit', - })} -

-
- -
-

- {transfer.direction === 'received' ? '+' : '-'} - {formatDogAmount(transfer.amount)} -

-

- {formatTimeAgo(transfer.timestamp)} -

- -
-
-
- ); -} diff --git a/legacy/taproot-assets-era/frontend/app/app/layout.tsx b/legacy/taproot-assets-era/frontend/app/app/layout.tsx deleted file mode 100644 index fb3f3fa..0000000 --- a/legacy/taproot-assets-era/frontend/app/app/layout.tsx +++ /dev/null @@ -1,12 +0,0 @@ -'use client'; - -import AppHeader from '@/components/AppHeader'; - -export default function AppLayout({ children }: { children: React.ReactNode }) { - return ( -
- -
{children}
-
- ); -} diff --git a/legacy/taproot-assets-era/frontend/app/app/page.tsx b/legacy/taproot-assets-era/frontend/app/app/page.tsx deleted file mode 100644 index 48f2969..0000000 --- a/legacy/taproot-assets-era/frontend/app/app/page.tsx +++ /dev/null @@ -1,267 +0,0 @@ -'use client'; - -import { useState, useEffect } from 'react'; -import { motion } from 'framer-motion'; -import { Wifi, WifiOff } from 'lucide-react'; -import Link from 'next/link'; -import BalanceCard from '@/components/BalanceCard'; -import TransferList from '@/components/TransferList'; -import ChannelCard from '@/components/ChannelCard'; -import SendModal from '@/components/SendModal'; -import GlassCard from '@/components/GlassCard'; -import ShibaInu from '@/components/ShibaInu'; -import { useUnisat } from '@/hooks/useUnisat'; -import { useApi } from '@/hooks/useApi'; -import { api } from '@/lib/api'; -import { Channel, Transfer, FeeStatus } from '@/lib/types'; -import { demoUser, demoTransfers, demoChannels } from '@/lib/demo-data'; - -const quickActions = [ - { - label: 'Send DOG', - sublabel: 'Yeet some DOG', - href: '/runebolt/app/send', - emoji: '🚀', - }, - { - label: 'Receive', - sublabel: 'Gimme DOG', - href: '/runebolt/app/receive', - emoji: '🎁', - }, - { - label: 'Open Channel', - sublabel: 'More power', - href: '/runebolt/app/channels', - emoji: '⚡', - }, - { - label: 'Close Channel', - sublabel: 'Cash out', - href: '/runebolt/app/channels', - emoji: '💰', - }, -]; - -export default function DashboardPage() { - const [sendModalOpen, setSendModalOpen] = useState(false); - const { connected, publicKey, signMessage } = useUnisat(); - const { authenticate, getChannels, getTransfers, getFeeStatus, sendTransfer } = useApi(); - - const [channels, setChannels] = useState(demoChannels); - const [transfers, setTransfers] = useState(demoTransfers); - const [feeStatus, setFeeStatus] = useState(null); - const [balance, setBalance] = useState(demoUser.balance); - const [username, setUsername] = useState(demoUser.username || 'anon'); - const [isLive, setIsLive] = useState(false); - - // Authenticate when wallet connects - useEffect(() => { - if (!connected || !publicKey) return; - if (api.isAuthenticated()) { - loadData(); - return; - } - (async () => { - const result = await authenticate(publicKey, signMessage); - if (result) { - if (result.user.username) setUsername(result.user.username); - loadData(); - } - })(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [connected, publicKey]); - - const loadData = async () => { - const [ch, tx, fee] = await Promise.all([ - getChannels(), - getTransfers(10), - publicKey ? getFeeStatus(publicKey) : null, - ]); - if (ch) { setChannels(ch); setIsLive(true); } - if (tx) { setTransfers(tx.transfers); setIsLive(true); } - if (fee) setFeeStatus(fee); - - // Compute balance from channel local balances - if (ch && ch.length > 0) { - const total = ch.reduce((sum, c) => sum + c.localBalance, 0); - setBalance(total); - } - }; - - const handleSend = async (recipient: string, amount: number) => { - const result = await sendTransfer(recipient, amount); - if (result) { - loadData(); - } - }; - - const openCount = channels.filter((c) => c.state === 'OPEN').length; - - return ( -
- {/* Welcome + Balance */} -
-
- - Gm, @{username}! 👋 - - - Let's get that DOG moving 🐕 - -
- - - -
- - - - {/* Connection Health */} - - -
-
- {isLive ? : } -
-
-

- {isLive ? 'Connection: Strong 💪' : 'Demo Mode 🎮'} -

-

- {isLive - ? `${openCount} channel${openCount !== 1 ? 's' : ''} active • Ready to send` - : 'Connect wallet for live data'} -

-
-
-
- {feeStatus && ( - - {feeStatus.freeRemaining} free txs left - - )} -
- - {isLive ? 'Online' : 'Offline'} - -
- - - - {/* Quick Actions */} -
- {quickActions.map((action, i) => { - const isFirstAction = i === 0; - return ( - - {isFirstAction ? ( - setSendModalOpen(true)} - className="flex flex-col items-center gap-2 p-5" - > - - {action.emoji} - - {action.label} - {action.sublabel} - - ) : ( - - - - {action.emoji} - - {action.label} - {action.sublabel} - - - )} - - ); - })} -
- - {/* Two-column layout */} -
- {/* Recent Transfers */} - - -
-

Recent Activity 📋

- - View All - -
- -
-
- - {/* Active Channels */} - -
-

Payment Channels ⚡

- - Manage - -
-
- {channels.map((channel, i) => ( - - ))} -
-
-
- - setSendModalOpen(false)} - onSend={handleSend} - maxBalance={balance} - /> -
- ); -} diff --git a/legacy/taproot-assets-era/frontend/app/app/receive/page.tsx b/legacy/taproot-assets-era/frontend/app/app/receive/page.tsx deleted file mode 100644 index f823015..0000000 --- a/legacy/taproot-assets-era/frontend/app/app/receive/page.tsx +++ /dev/null @@ -1,234 +0,0 @@ -'use client'; - -import { useState, useEffect } from 'react'; -import { motion } from 'framer-motion'; -import { ArrowLeft, Copy, Check, Link2, Share2 } from 'lucide-react'; -import Link from 'next/link'; -import { QRCodeSVG } from 'qrcode.react'; -import GlassCard from '@/components/GlassCard'; -import { useUnisat } from '@/hooks/useUnisat'; -import { useApi } from '@/hooks/useApi'; -import { api } from '@/lib/api'; -import { Transfer } from '@/lib/types'; -import { demoUser, demoTransfers } from '@/lib/demo-data'; -import { formatDogAmount, formatTimeAgo } from '@/lib/format'; - -export default function ReceivePage() { - const [copiedAddress, setCopiedAddress] = useState(false); - const [copiedLink, setCopiedLink] = useState(false); - const [claimAmount, setClaimAmount] = useState(''); - const [generatedLink, setGeneratedLink] = useState(''); - - const { connected, address } = useUnisat(); - const { getTransfers, createClaimLink } = useApi(); - const [recentReceived, setRecentReceived] = useState( - demoTransfers.filter((t) => t.direction === 'received').slice(0, 3) - ); - - const runeboltAddress = connected && address - ? `${address.slice(0, 8)}@runebolt.io` - : demoUser.runeboltAddress; - - useEffect(() => { - if (!connected || !api.isAuthenticated()) return; - (async () => { - const result = await getTransfers(10); - if (result) { - setRecentReceived( - result.transfers.filter((t) => t.direction === 'received').slice(0, 3) - ); - } - })(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [connected]); - - const copyAddress = async () => { - await navigator.clipboard.writeText(runeboltAddress); - setCopiedAddress(true); - setTimeout(() => setCopiedAddress(false), 2000); - }; - - const copyLink = async () => { - if (!generatedLink) return; - await navigator.clipboard.writeText(generatedLink); - setCopiedLink(true); - setTimeout(() => setCopiedLink(false), 2000); - }; - - const handleShare = async () => { - if (navigator.share) { - try { - await navigator.share({ - title: 'My RuneBolt Address', - text: `Send me DOG at ${runeboltAddress}`, - }); - } catch { - // user cancelled - } - } else { - copyAddress(); - } - }; - - const generateClaimLink = async () => { - const amount = parseFloat(claimAmount); - if (amount <= 0) return; - - if (!api.isAuthenticated()) { - // Demo mode - setGeneratedLink(`https://runebolt.io/claim/demo_${Math.random().toString(36).slice(2, 10)}`); - return; - } - - const result = await createClaimLink(amount); - if (result) { - setGeneratedLink(`https://runebolt.io/claim/${result.id}`); - } - }; - - return ( -
- {/* Header */} -
- - - -

Receive DOG

-
- -
- {/* Your RuneBolt Address */} - -

Your RuneBolt Address

- -
-
- -
-
- - - {runeboltAddress} - {copiedAddress ? ( - - ) : ( - - )} - - -
- -
- -

- Share this address to receive DOG instantly -

-
- - {/* Create Claim Link */} - -
- -

Create Claim Link

-
- -
-
- { - setClaimAmount(e.target.value); - setGeneratedLink(''); - }} - placeholder="Amount in DOG" - className="w-full rounded-xl border border-dark-700 bg-dark-900/60 px-4 py-3 font-mono text-sm text-white placeholder-gray-500 outline-none transition-colors focus:border-bitcoin/50" - /> -
- - Generate - -
- - {generatedLink && ( - -

- Claim link for {formatDogAmount(parseFloat(claimAmount))} DOG -

- - - {generatedLink} - - {copiedLink ? ( - - ) : ( - - )} - -
- )} -
- - {/* Pending Incoming */} - -

Recent Received

-
- {recentReceived.map((transfer) => ( -
-
-

- {transfer.counterpartyName || 'Unknown'} -

-

- {formatTimeAgo(transfer.timestamp)} -

-
-

- +{formatDogAmount(transfer.amount)} -

-
- ))} -
-
-
-
- ); -} diff --git a/legacy/taproot-assets-era/frontend/app/app/send/page.tsx b/legacy/taproot-assets-era/frontend/app/app/send/page.tsx deleted file mode 100644 index 54806e8..0000000 --- a/legacy/taproot-assets-era/frontend/app/app/send/page.tsx +++ /dev/null @@ -1,402 +0,0 @@ -'use client'; - -import { useState, useEffect } from 'react'; -import { motion, AnimatePresence } from 'framer-motion'; -import { ArrowLeft, ArrowRight, AlertCircle } from 'lucide-react'; -import Link from 'next/link'; -import AddressInput from '@/components/AddressInput'; -import GlassCard from '@/components/GlassCard'; -import ShibaInu from '@/components/ShibaInu'; -import Confetti from '@/components/Confetti'; -import { formatDogAmount, formatUsd } from '@/lib/format'; -import { DEMO_USD_RATE } from '@/lib/constants'; -import { useUnisat } from '@/hooks/useUnisat'; -import { useApi } from '@/hooks/useApi'; -import { api } from '@/lib/api'; -import { FeeStatus } from '@/lib/types'; -import { demoUser } from '@/lib/demo-data'; -import clsx from 'clsx'; - -type Step = 'input' | 'review' | 'sending' | 'success' | 'error'; - -export default function SendPage() { - const [step, setStep] = useState('input'); - const [recipient, setRecipient] = useState(''); - const [recipientType, setRecipientType] = useState<'runebolt' | 'bitcoin' | null>(null); - const [amount, setAmount] = useState(''); - const [showUsd, setShowUsd] = useState(false); - const [showConfetti, setShowConfetti] = useState(false); - const [errorMsg, setErrorMsg] = useState(''); - - const { connected, publicKey } = useUnisat(); - const { sendTransfer, getFeeStatus } = useApi(); - const [feeStatus, setFeeStatus] = useState(null); - const [balance, setBalance] = useState(demoUser.balance); - - // Load fee status and balance - useEffect(() => { - if (!connected || !publicKey || !api.isAuthenticated()) return; - (async () => { - const fee = await getFeeStatus(publicKey); - if (fee) setFeeStatus(fee); - })(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [connected, publicKey]); - - const numAmount = parseFloat(amount) || 0; - const usdAmount = numAmount * DEMO_USD_RATE; - const isValid = recipientType !== null && numAmount > 0 && numAmount <= balance; - - // Fee calculation - const isFree = feeStatus ? feeStatus.isFree : true; - const feeRate = feeStatus ? feeStatus.feeRate : 0; - const fee = isFree ? 0 : numAmount * feeRate; - - const handleReview = () => { - if (isValid) setStep('review'); - }; - - const handleSend = async () => { - setStep('sending'); - - if (!api.isAuthenticated()) { - // Demo mode - simulate - setTimeout(() => { - setStep('success'); - setShowConfetti(true); - setTimeout(() => setShowConfetti(false), 4000); - }, 1500); - return; - } - - const result = await sendTransfer(recipient, numAmount); - if (result) { - setStep('success'); - setShowConfetti(true); - setTimeout(() => setShowConfetti(false), 4000); - } else { - setErrorMsg('Transfer failed. Please try again.'); - setStep('error'); - } - }; - - const handleReset = () => { - setStep('input'); - setRecipient(''); - setAmount(''); - setRecipientType(null); - setErrorMsg(''); - }; - - return ( -
- - - {/* Header */} -
- - - -

Send DOG 🐕

-
- - - {/* Step 1: Input */} - {step === 'input' && ( - - {/* Recipient */} - - - - - - {/* Amount */} - -
- - -
- -
- setAmount(e.target.value)} - placeholder="0.00000" - className="w-full bg-transparent font-mono text-4xl font-bold text-white placeholder-dark-600 outline-none" - /> -
-

- {showUsd ? `${formatDogAmount(numAmount)} DOG` : formatUsd(usdAmount)} -

- -
-
- - {numAmount > balance && ( -

- - Your DOG wallet is on a diet 🐕💨 -

- )} -
- - {/* Fee estimate */} - -
-
- Network Fee - - {recipientType === 'runebolt' - ? isFree - ? '0 DOG (free! 🎉)' - : `${formatDogAmount(fee)} DOG (${(feeRate * 100).toFixed(1)}%)` - : '~500 sats'} - -
- {feeStatus && recipientType === 'runebolt' && ( -
- Free txs remaining - {feeStatus.freeRemaining} -
- )} -
- Speed - - {recipientType === 'runebolt' ? 'Instant ⚡' : '~10 min 🐢'} - -
-
- You Send - - {formatDogAmount(numAmount)} DOG - -
-
-
- - - Review Transfer 🐕 - - -
- )} - - {/* Step 2: Review */} - {step === 'review' && ( - - -
- - 🐕 - -

You're about to yeet

-

- {formatDogAmount(numAmount)} -

-

DOG

-

{formatUsd(usdAmount)}

-
-
-
- To - {recipient} -
-
- Speed - - {recipientType === 'runebolt' ? 'Off-Chain (Instant ⚡)' : 'On-Chain 🐢'} - -
-
- Fee - - {isFree ? 'FREE 🎉' : `${formatDogAmount(fee)} DOG`} - -
-
-
- Total - {formatDogAmount(numAmount + fee)} DOG -
-
-
-
- -

- No takebacks! Make sure everything looks right 👀 -

- -
- - - Send it! 🚀 - -
-
- )} - - {/* Step 3: Sending */} - {step === 'sending' && ( - - - 🐕 - -

Sending DOG...

-

Your DOG is on its way! Much speed. Very instant. 🚀

-
- )} - - {/* Step 4: Success */} - {step === 'success' && ( - - - - - -

DOG Delivered! 🎉

-

- Much speed. Very instant. Wow. -

-

- {formatDogAmount(numAmount)} DOG sent to {recipient} -

- - {/* Share on X button */} - - Flex this on X 📱 - - -
- - Send More DOG 🐕 - - - - Back to Dashboard - - -
-
- )} - - {/* Step 5: Error */} - {step === 'error' && ( - -
- -
-

Transfer Failed

-

{errorMsg}

- - Try Again 🐕 - -
- )} -
-
- ); -} diff --git a/legacy/taproot-assets-era/frontend/app/claim/[id]/ClaimPageClient.tsx b/legacy/taproot-assets-era/frontend/app/claim/[id]/ClaimPageClient.tsx deleted file mode 100644 index 6674948..0000000 --- a/legacy/taproot-assets-era/frontend/app/claim/[id]/ClaimPageClient.tsx +++ /dev/null @@ -1,266 +0,0 @@ -'use client'; - -import { useState, useEffect } from 'react'; -import { motion } from 'framer-motion'; -import { Wallet, Check, Clock, ArrowRight } from 'lucide-react'; -import Link from 'next/link'; -import GlassCard from '@/components/GlassCard'; -import ShibaInu from '@/components/ShibaInu'; -import Confetti from '@/components/Confetti'; -import { demoClaimLink } from '@/lib/demo-data'; -import { formatDogAmount } from '@/lib/format'; - -type ClaimState = 'not-connected' | 'no-channel' | 'ready' | 'claiming' | 'success'; - -export default function ClaimPageClient() { - const [state, setState] = useState('not-connected'); - const [timeLeft, setTimeLeft] = useState(''); - const [showConfetti, setShowConfetti] = useState(false); - - const claim = demoClaimLink; - - useEffect(() => { - if (!claim.expiresAt) return; - - const updateTimer = () => { - const now = new Date(); - const diff = claim.expiresAt!.getTime() - now.getTime(); - if (diff <= 0) { - setTimeLeft('Expired'); - return; - } - const hours = Math.floor(diff / (1000 * 60 * 60)); - const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); - setTimeLeft(`${hours}h ${minutes}m`); - }; - - updateTimer(); - const interval = setInterval(updateTimer, 60000); - return () => clearInterval(interval); - }, [claim.expiresAt]); - - const handleConnect = () => setState('no-channel'); - const handleOpenChannel = () => setState('ready'); - const handleClaim = () => { - setState('claiming'); - setTimeout(() => { - setState('success'); - setShowConfetti(true); - setTimeout(() => setShowConfetti(false), 4000); - }, 2000); - }; - - return ( -
- - -
- {/* Header */} -
- - - - - - {state === 'success' ? 'DOG Claimed! 🎉' : 'Someone sent you DOG! 🐕'} - - - {state === 'success' - ? 'Much wow. Very generous. Such crypto.' - : 'Quick, claim it before the DOG runs away! 🏃‍♂️'} - -
- - {/* Claim Card - Gift Card Aesthetic */} - {state !== 'success' && ( - - - {/* Gift card header */} -
- {/* Decorative dots */} -
-
-
-
-
-
- GIFT -
- - {/* Amount */} - -
- {formatDogAmount(claim.amount)} -
-
- DOG•GO•TO•THE•MOON 🌙 -
-
-
- - {/* Card details */} -
-
- From - - @{claim.senderName || 'anonymous'} 🤝 - -
-
- Message - {claim.message} -
-
- Expires in - - {timeLeft === 'Expired' ? 'DOG ran away! 🐕💨' : `${timeLeft} ⏰`} - -
-
- - {/* Urgency bar */} - {timeLeft !== 'Expired' && ( -
-
- -
-
- )} - - - )} - - {/* Action Buttons */} - {state === 'not-connected' && ( - - - Unleash Your Wallet 🔓 - - )} - - {state === 'no-channel' && ( - - ⚡ Open Channel & Claim - - )} - - {state === 'ready' && ( - - - Claim {formatDogAmount(claim.amount)} DOG 🐕 - - )} - - {state === 'claiming' && ( -
- - - - Fetching your DOG... good boy! 🐾 -
- )} - - {state === 'success' && ( - - - - - -

- {formatDogAmount(claim.amount)} DOG is yours! 🎉 -

-

- DOG delivered! Much speed. Very instant. 🚀 -

-
- - - Go to Dashboard - - - - - Flex this on X 📱 - -
- )} -
-
- ); -} diff --git a/legacy/taproot-assets-era/frontend/app/claim/[id]/page.tsx b/legacy/taproot-assets-era/frontend/app/claim/[id]/page.tsx deleted file mode 100644 index 9c93dd2..0000000 --- a/legacy/taproot-assets-era/frontend/app/claim/[id]/page.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import ClaimPageClient from './ClaimPageClient'; - -// Generate static params for export -export function generateStaticParams() { - return [ - { id: 'demo' }, - { id: 'sample' }, - ]; -} - -export default function ClaimPage() { - return ; -} diff --git a/legacy/taproot-assets-era/frontend/app/globals.css b/legacy/taproot-assets-era/frontend/app/globals.css deleted file mode 100644 index 90e5377..0000000 --- a/legacy/taproot-assets-era/frontend/app/globals.css +++ /dev/null @@ -1,113 +0,0 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; - -@layer base { - html { - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; - } - - body { - @apply bg-dark-900 text-white antialiased; - } - - /* Custom scrollbar */ - ::-webkit-scrollbar { - width: 6px; - height: 6px; - } - - ::-webkit-scrollbar-track { - @apply bg-transparent; - } - - ::-webkit-scrollbar-thumb { - @apply rounded-full bg-dark-600; - } - - ::-webkit-scrollbar-thumb:hover { - @apply bg-dark-700; - } - - /* Firefox scrollbar */ - * { - scrollbar-width: thin; - scrollbar-color: #2a2a3e transparent; - } -} - -@layer utilities { - .glass-card { - @apply rounded-2xl border border-dark-700 bg-dark-800/80 backdrop-blur-xl shadow-lg shadow-black/20; - } - - .gradient-text { - @apply bg-gradient-to-r from-bitcoin to-cyan bg-clip-text text-transparent; - } - - .gradient-text-orange { - @apply bg-gradient-to-r from-bitcoin to-orange-400 bg-clip-text text-transparent; - } - - .glass-card-glow { - @apply rounded-2xl border border-dark-700 bg-dark-800/80 backdrop-blur-xl shadow-lg shadow-black/20; - box-shadow: - 0 0 0 1px rgba(247, 147, 26, 0.05), - 0 4px 24px rgba(0, 0, 0, 0.3), - inset 0 1px 0 rgba(255, 255, 255, 0.03); - } - - .fun-button { - @apply relative overflow-hidden rounded-2xl bg-gradient-to-r from-bitcoin via-orange-500 to-bitcoin - px-8 py-4 text-base font-bold text-white shadow-xl shadow-bitcoin/25 - transition-all duration-300; - background-size: 200% 100%; - } - - .fun-button:hover { - background-position: 100% 0; - box-shadow: 0 0 30px rgba(247, 147, 26, 0.4), 0 10px 40px rgba(247, 147, 26, 0.2); - transform: translateY(-2px); - } - - .fun-button:active { - transform: translateY(0); - } -} - -@keyframes pulse-glow { - 0%, 100% { - box-shadow: 0 0 20px rgba(247, 147, 26, 0.2); - } - 50% { - box-shadow: 0 0 40px rgba(247, 147, 26, 0.4); - } -} - -.animate-pulse-glow { - animation: pulse-glow 2s ease-in-out infinite; -} - -/* Shiba paw trail effect */ -@keyframes paw-trail { - 0% { opacity: 0; transform: scale(0); } - 30% { opacity: 0.6; transform: scale(1); } - 100% { opacity: 0; transform: scale(0.8); } -} - -/* Number input - hide spinners */ -input[type='number']::-webkit-outer-spin-button, -input[type='number']::-webkit-inner-spin-button { - -webkit-appearance: none; - margin: 0; -} - -input[type='number'] { - -moz-appearance: textfield; -} - -/* Selection color */ -::selection { - background: rgba(247, 147, 26, 0.3); - color: white; -} diff --git a/legacy/taproot-assets-era/frontend/app/layout.tsx b/legacy/taproot-assets-era/frontend/app/layout.tsx deleted file mode 100644 index edb150b..0000000 --- a/legacy/taproot-assets-era/frontend/app/layout.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import type { Metadata } from 'next'; -import './globals.css'; - -export const metadata: Metadata = { - title: 'RuneBolt — Instant DOG Transfers', - description: - 'Lock your DOG•GO•TO•THE•MOON in payment channels. Transfer instantly. Settle on Bitcoin.', - icons: { - icon: '/favicon.ico', - }, -}; - -export default function RootLayout({ children }: { children: React.ReactNode }) { - return ( - - {children} - - ); -} diff --git a/legacy/taproot-assets-era/frontend/app/page.tsx b/legacy/taproot-assets-era/frontend/app/page.tsx deleted file mode 100644 index b5116e0..0000000 --- a/legacy/taproot-assets-era/frontend/app/page.tsx +++ /dev/null @@ -1,400 +0,0 @@ -'use client'; - -import { useState } from 'react'; -import { motion } from 'framer-motion'; -import { - Zap, - Shield, - ArrowRight, - Wallet, - Send, - Users, - Gift, - Github, - Twitter, - Clock, - Sparkles, - ChevronDown, -} from 'lucide-react'; -import Link from 'next/link'; -import Navbar from '@/components/Navbar'; -import GlassCard from '@/components/GlassCard'; -import StatCard from '@/components/StatCard'; -import OnboardingFlow from '@/components/OnboardingFlow'; -import ShibaInu from '@/components/ShibaInu'; - -const features = [ - { - icon: Zap, - title: 'Instant. Like, Actually Instant.', - description: 'Send DOG in milliseconds. Blink and you\'ll miss it. No cap.', - emoji: '⚡', - }, - { - icon: Shield, - title: 'Your Keys, Your Treats', - description: 'Non-custodial means nobody touches your DOG. Not even us. Pinky promise.', - emoji: '🔒', - }, - { - icon: Zap, - title: 'Bitcoin Native. No Bridges.', - description: 'Built on Bitcoin L1. No wrapped tokens, no bridges to nowhere, no cap.', - emoji: '₿', - }, - { - icon: Users, - title: '@Username = Your Address', - description: 'Send DOG to @satoshi like it\'s Venmo. Long addresses are so 2023.', - emoji: '🏷️', - }, - { - icon: Gift, - title: 'Gift Links Go Brrr', - description: 'Send DOG to anyone with a link. Even your grandma who thinks Bitcoin is a video game.', - emoji: '🎁', - }, - { - icon: Clock, - title: 'Zero Brain Cells Required', - description: 'We handle channels, routing, and complexity. You just vibe and send.', - emoji: '🧠', - }, -]; - -const howItWorks = [ - { - step: '1', - title: 'Unleash Your Wallet', - description: 'Connect your Unisat wallet. It takes 3 seconds. We counted.', - emoji: '🔓', - shibaReaction: 'Such wallet. Very connect.', - }, - { - step: '2', - title: 'Type @username + Amount', - description: 'No copy-pasting 64-character addresses. Just type who gets the DOG.', - emoji: '📝', - shibaReaction: 'Much simple. Wow.', - }, - { - step: '3', - title: 'Hit Send. Done.', - description: 'DOG arrives instantly. No waiting 10 minutes for a block. Go touch grass.', - emoji: '🚀', - shibaReaction: 'Very speed. So instant.', - }, -]; - -export default function LandingPage() { - const [showOnboarding, setShowOnboarding] = useState(false); - - return ( -
- - - {/* HERO SECTION */} -
- {/* Background effects */} -
-
-
-
-
- - {/* Floating paw prints in background */} -
- {[...Array(6)].map((_, i) => ( - - 🐾 - - ))} -
- -
- - {/* Free badge */} - - - First 500 transactions FREE — zero fees, zero stress 🎉 - - - {/* Shiba hero */} - - - - -

- Send DOG -
- like a text message - - ⚡ - -

- -

- The fastest way to send DOG•GO•TO•THE•MOON. - No channel management. No 64-character addresses. - Just @username and vibes. -

- -
- setShowOnboarding(true)} - className="fun-button flex items-center gap-2 text-lg" - > - 🐕 - Let's Gooo - - - - - - - Unleash Your Wallet 🔓 - - -
- - {/* Scroll indicator */} - - - -
-
-
- - {/* STATS BAR */} -
-
-
- - - - -
-
-
- - {/* HOW IT WORKS */} -
-
- -

- Three Steps. That's It. -

-

- If you can send a text, you can send DOG. It's that simple. -

-
- -
- {howItWorks.map((item, i) => ( - - - {/* Step number glow */} -
- - {/* Emoji */} - - {item.emoji} - - - {/* Step badge */} -
- {item.step} -
- -

{item.title}

-

{item.description}

- - {/* Shiba reaction */} -
- 🐕 {item.shibaReaction} -
- - - ))} -
-
-
- - {/* FEATURES */} -
-
- -

- Why RuneBolt? 🐕⚡ -

-

- Because sending DOG should be fun, not a PhD thesis. -

-
- -
- {features.map((feature, i) => ( - - - - {feature.emoji} - -

{feature.title}

-

- {feature.description} -

-
-
- ))} -
-
-
- - {/* CTA SECTION */} -
-
- - -

- Ready to send DOG at -
- the speed of light? -

-

- Join thousands of DOG holders who are already sending - instant transfers. First 500 txs are free. No excuses. -

-
- setShowOnboarding(true)} - className="fun-button flex items-center gap-2 text-lg" - > - 🚀 Start Sending Now - - -
-

- No signup required. Just connect wallet and go brrrr. -

-
-
-
- - {/* FOOTER */} -
-
-
-
-
- -
- RuneBolt - 🐕 -
- -

- Built for the DOG army. Much love. Very community. 🐕 -

-
-
-
- - setShowOnboarding(false)} - onComplete={(data) => { - console.log('Onboarding complete:', data); - setShowOnboarding(false); - }} - /> -
- ); -} diff --git a/legacy/taproot-assets-era/frontend/components/AddressInput.tsx b/legacy/taproot-assets-era/frontend/components/AddressInput.tsx deleted file mode 100644 index a7f1e57..0000000 --- a/legacy/taproot-assets-era/frontend/components/AddressInput.tsx +++ /dev/null @@ -1,102 +0,0 @@ -'use client'; - -import { useState, useEffect } from 'react'; -import { motion, AnimatePresence } from 'framer-motion'; -import { AtSign, Bitcoin, AlertCircle } from 'lucide-react'; -import clsx from 'clsx'; - -interface AddressInputProps { - value: string; - onChange: (value: string) => void; - onResolve?: (type: 'runebolt' | 'bitcoin' | null) => void; - className?: string; -} - -type AddressType = 'runebolt' | 'bitcoin' | 'invalid' | null; - -export default function AddressInput({ value, onChange, onResolve, className }: AddressInputProps) { - const [addressType, setAddressType] = useState(null); - - useEffect(() => { - const timer = setTimeout(() => { - if (!value) { - setAddressType(null); - onResolve?.(null); - return; - } - - if (value.includes('@')) { - setAddressType('runebolt'); - onResolve?.('runebolt'); - } else if (value.startsWith('bc1') || value.startsWith('tb1')) { - setAddressType('bitcoin'); - onResolve?.('bitcoin'); - } else if (value.length > 5) { - setAddressType('invalid'); - onResolve?.(null); - } else { - setAddressType(null); - onResolve?.(null); - } - }, 300); - - return () => clearTimeout(timer); - }, [value, onResolve]); - - return ( -
- onChange(e.target.value)} - placeholder="username@runebolt.io or bc1q..." - className={clsx( - 'w-full rounded-xl border bg-dark-800 px-4 py-3 pr-32 font-mono text-sm text-white', - 'placeholder-gray-500 outline-none transition-colors', - addressType === 'invalid' - ? 'border-red-500/50 focus:border-red-500' - : 'border-dark-700 focus:border-bitcoin/50' - )} - /> - - {addressType && addressType !== 'invalid' && ( - - {addressType === 'runebolt' ? ( - <> - - RuneBolt User - - ) : ( - <> - - Bitcoin Address - - )} - - )} - {addressType === 'invalid' && ( - - - Invalid - - )} - -
- ); -} diff --git a/legacy/taproot-assets-era/frontend/components/AppHeader.tsx b/legacy/taproot-assets-era/frontend/components/AppHeader.tsx deleted file mode 100644 index 7dc6c62..0000000 --- a/legacy/taproot-assets-era/frontend/components/AppHeader.tsx +++ /dev/null @@ -1,89 +0,0 @@ -'use client'; - -import Link from 'next/link'; -import { usePathname } from 'next/navigation'; -import { Zap } from 'lucide-react'; -import WalletConnect from './WalletConnect'; -import clsx from 'clsx'; - -const navItems = [ - { href: '/app', label: 'Dashboard', emoji: '🏠' }, - { href: '/app/send', label: 'Send', emoji: '🚀' }, - { href: '/app/receive', label: 'Receive', emoji: '🎁' }, - { href: '/app/channels', label: 'Channels', emoji: '⚡' }, - { href: '/app/history', label: 'History', emoji: '📜' }, -]; - -export default function AppHeader() { - const pathname = usePathname(); - - return ( -
-
- {/* Logo */} - -
- -
- - RuneBolt - - 🐕 - - - {/* Desktop nav */} - - - {/* Right side */} -
-
-
- Testnet -
- -
-
- - {/* Mobile nav */} -
- {navItems.map((item) => { - const isActive = pathname === item.href; - return ( - - {item.emoji} - {item.label} - - ); - })} -
-
- ); -} diff --git a/legacy/taproot-assets-era/frontend/components/BalanceCard.tsx b/legacy/taproot-assets-era/frontend/components/BalanceCard.tsx deleted file mode 100644 index f35ea40..0000000 --- a/legacy/taproot-assets-era/frontend/components/BalanceCard.tsx +++ /dev/null @@ -1,98 +0,0 @@ -'use client'; - -import { useEffect, useState, useMemo } from 'react'; -import { motion } from 'framer-motion'; -import { formatDogAmount, formatUsd } from '@/lib/format'; -import { DEMO_USD_RATE } from '@/lib/constants'; - -interface BalanceCardProps { - balance: number; - usdRate?: number; -} - -const funComparisons = [ - { threshold: 100000, text: 'Enough to buy a virtual dog park! 🏞️' }, - { threshold: 50000, text: 'That\'s 50,000 virtual treats! 🦴' }, - { threshold: 10000, text: 'You\'re a certified good boi 🏆' }, - { threshold: 1000, text: 'Stack those DOG, king 👑' }, - { threshold: 0, text: 'Every DOG journey starts small 🐾' }, -]; - -export default function BalanceCard({ balance, usdRate = DEMO_USD_RATE }: BalanceCardProps) { - const [displayBalance, setDisplayBalance] = useState(0); - - useEffect(() => { - const duration = 1200; - const steps = 40; - const increment = balance / steps; - let current = 0; - let step = 0; - - const timer = setInterval(() => { - step++; - current = Math.min(balance, increment * step); - setDisplayBalance(current); - if (step >= steps) { - clearInterval(timer); - setDisplayBalance(balance); - } - }, duration / steps); - - return () => clearInterval(timer); - }, [balance]); - - const usdValue = displayBalance * usdRate; - const comparison = useMemo( - () => funComparisons.find((c) => balance >= c.threshold) || funComparisons[funComparisons.length - 1], - [balance] - ); - - return ( - - {/* Gradient border effect */} -
-
-
- - {/* Background glow */} -
-
- - {/* Floating emoji */} - - 🐕 - - -
-

Your DOG Stash 💰

-
- - {formatDogAmount(displayBalance)} - - DOG -
-

- {formatUsd(usdValue)} USD -

- {/* Fun comparison */} - - {comparison.text} - -
- - ); -} diff --git a/legacy/taproot-assets-era/frontend/components/ChannelCard.tsx b/legacy/taproot-assets-era/frontend/components/ChannelCard.tsx deleted file mode 100644 index ebb2777..0000000 --- a/legacy/taproot-assets-era/frontend/components/ChannelCard.tsx +++ /dev/null @@ -1,77 +0,0 @@ -'use client'; - -import { motion } from 'framer-motion'; -import { X } from 'lucide-react'; -import { Channel, ChannelState } from '@/lib/types'; -import { formatDogAmount, formatChannelId } from '@/lib/format'; -import StatusBadge from './StatusBadge'; -import GlassCard from './GlassCard'; - -interface ChannelCardProps { - channel: Channel; - onClose?: (channelId: string) => void; - index?: number; -} - -export default function ChannelCard({ channel, onClose, index = 0 }: ChannelCardProps) { - const localPercent = channel.capacity > 0 ? (channel.localBalance / channel.capacity) * 100 : 0; - - return ( - - -
-
-
-

- {formatChannelId(channel.id)} -

- -
-

- Capacity: {formatDogAmount(channel.capacity)} DOG -

-
- {channel.state === ChannelState.OPEN && onClose && ( - onClose(channel.id)} - className="rounded-lg p-1.5 text-gray-500 transition-colors hover:bg-dark-700 hover:text-red-400" - title="Close Channel" - > - - - )} -
- - {/* Capacity bar */} -
-
- Local - Remote -
-
- -
-
- - {formatDogAmount(channel.localBalance)} - - - {formatDogAmount(channel.remoteBalance)} - -
-
-
-
- ); -} diff --git a/legacy/taproot-assets-era/frontend/components/ClaimLink.tsx b/legacy/taproot-assets-era/frontend/components/ClaimLink.tsx deleted file mode 100644 index 3cca2c2..0000000 --- a/legacy/taproot-assets-era/frontend/components/ClaimLink.tsx +++ /dev/null @@ -1,365 +0,0 @@ -'use client'; - -import { useState } from 'react'; -import { motion, AnimatePresence } from 'framer-motion'; -import { - X, - Link as LinkIcon, - QrCode, - Copy, - Check, - Share2, - Gift, - ArrowRight, - Download -} from 'lucide-react'; -import { QRCodeSVG } from 'qrcode.react'; -import GlassCard from './GlassCard'; -import clsx from 'clsx'; - -interface ClaimLinkProps { - isOpen: boolean; - onClose: () => void; - maxBalance?: number; - userPubkey?: string; - apiBaseUrl?: string; -} - -type Step = 'create' | 'generated' | 'share'; - -interface GeneratedLink { - id: string; - url: string; - amount: number; - memo: string; - expiresAt: Date; -} - -export default function ClaimLink({ - isOpen, - onClose, - maxBalance = 125000, - userPubkey, - apiBaseUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001' -}: ClaimLinkProps) { - const [step, setStep] = useState('create'); - const [amount, setAmount] = useState(''); - const [memo, setMemo] = useState(''); - const [generatedLink, setGeneratedLink] = useState(null); - const [copied, setCopied] = useState(false); - const [showQR, setShowQR] = useState(false); - - const numAmount = parseFloat(amount) || 0; - const isValid = numAmount > 0 && numAmount <= maxBalance; - - const handleCreate = async () => { - if (!isValid || !userPubkey) return; - - try { - // In production: Call API to create claim link - // const response = await fetch(`${apiBaseUrl}/api/v1/claims`, { - // method: 'POST', - // headers: { 'Content-Type': 'application/json' }, - // body: JSON.stringify({ amount: numAmount, memo }), - // }); - // const data = await response.json(); - - // Mock for now - const linkId = Math.random().toString(36).substring(2, 10); - const claimUrl = `https://runebolt.io/claim/${linkId}`; - - setGeneratedLink({ - id: linkId, - url: claimUrl, - amount: numAmount, - memo: memo || 'Gift from RuneBolt!', - expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days - }); - - setStep('generated'); - } catch (err) { - console.error('Failed to create claim link:', err); - } - }; - - const handleCopy = async () => { - if (!generatedLink) return; - await navigator.clipboard.writeText(generatedLink.url); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - }; - - const handleShare = async () => { - if (!generatedLink) return; - - if (navigator.share) { - try { - await navigator.share({ - title: 'You\'ve received DOG! 🐕', - text: `${generatedLink.memo}\n\nClick to claim ${numAmount.toLocaleString()} DOG:`, - url: generatedLink.url, - }); - } catch (err) { - // User cancelled or share failed - handleCopy(); - } - } else { - handleCopy(); - } - }; - - const handleClose = () => { - setStep('create'); - setAmount(''); - setMemo(''); - setGeneratedLink(null); - setCopied(false); - setShowQR(false); - onClose(); - }; - - const formatExpiry = (date: Date) => { - const days = Math.ceil((date.getTime() - Date.now()) / (1000 * 60 * 60 * 24)); - return `Expires in ${days} days`; - }; - - return ( - - {isOpen && ( - - e.stopPropagation()} - className="w-full max-w-md overflow-hidden rounded-2xl border border-dark-700 bg-dark-800 shadow-2xl" - > - {/* Header */} -
-
-
- -
-

- {step === 'create' && 'Create Gift Link'} - {step === 'generated' && 'Link Ready!'} -

-
- -
- - {/* Content */} -
- - {step === 'create' && ( - -

- Create a shareable link to send DOG to anyone — they don't even need a RuneBolt account yet! -

- -
- -
- setAmount(e.target.value)} - placeholder="0.00000" - className="w-full rounded-xl border border-dark-700 bg-dark-800 px-4 py-3 pr-24 font-mono text-lg text-white placeholder-gray-500 outline-none transition-colors focus:border-bitcoin/50" - /> -
- DOG -
-
- {numAmount > maxBalance && ( -

- You only have {maxBalance.toLocaleString()} DOG -

- )} -
- -
- - setMemo(e.target.value)} - placeholder="e.g., Thanks for the pizza! 🍕" - maxLength={50} - className="w-full rounded-xl border border-dark-700 bg-dark-800 px-4 py-3 text-sm text-white placeholder-gray-500 outline-none transition-colors focus:border-bitcoin/50" - /> -

- {memo.length}/50 characters -

-
- -
-
-
- 💡 -
-
-

How it works

-
    -
  • • They click the link to claim their DOG
  • -
  • • No account needed to receive
  • -
  • • Link expires in 7 days if unclaimed
  • -
  • • Unclaimed DOG returns to you
  • -
-
-
-
- - - Create Link - - -
- )} - - {step === 'generated' && generatedLink && ( - -
- - - -

- {generatedLink.amount.toLocaleString()} DOG Ready! -

-

{generatedLink.memo}

-
- - {/* Link Display */} -
-
- - - -
-
- - {/* QR Code Toggle */} - - {showQR && ( - -
- -
-
- )} -
- - {/* Action Buttons */} -
- setShowQR(!showQR)} - className="flex items-center justify-center gap-2 rounded-xl border border-dark-700 bg-dark-800 py-3 text-sm font-medium text-gray-300 transition-colors hover:bg-dark-700 hover:text-white" - > - - {showQR ? 'Hide QR' : 'Show QR'} - - - - - Share Link - -
- - {/* Download QR */} - {showQR && ( - - )} - -
-

{formatExpiry(generatedLink.expiresAt)}

-
-
- )} -
-
-
-
- )} -
- ); -} diff --git a/legacy/taproot-assets-era/frontend/components/Confetti.tsx b/legacy/taproot-assets-era/frontend/components/Confetti.tsx deleted file mode 100644 index e423203..0000000 --- a/legacy/taproot-assets-era/frontend/components/Confetti.tsx +++ /dev/null @@ -1,98 +0,0 @@ -'use client'; - -import { useEffect, useState } from 'react'; -import { motion, AnimatePresence } from 'framer-motion'; - -interface ConfettiProps { - active: boolean; - duration?: number; -} - -const COLORS = ['#F7931A', '#00CFFF', '#FFD700', '#FF6B8A', '#7C3AED', '#10B981', '#F59E0B', '#EF4444']; -const EMOJIS = ['🐕', '⚡', '🚀', '🎉', '✨', '🔥', '💎', '🌙']; - -interface Particle { - id: number; - x: number; - emoji: boolean; - content: string; - color: string; - delay: number; - duration: number; - rotation: number; - size: number; -} - -export default function Confetti({ active, duration = 3000 }: ConfettiProps) { - const [particles, setParticles] = useState([]); - - useEffect(() => { - if (!active) { - setParticles([]); - return; - } - - const newParticles: Particle[] = Array.from({ length: 50 }, (_, i) => ({ - id: i, - x: Math.random() * 100, - emoji: Math.random() > 0.6, - content: Math.random() > 0.6 ? EMOJIS[Math.floor(Math.random() * EMOJIS.length)] : '', - color: COLORS[Math.floor(Math.random() * COLORS.length)], - delay: Math.random() * 0.8, - duration: 2 + Math.random() * 2, - rotation: Math.random() * 720 - 360, - size: Math.random() * 8 + 4, - })); - - setParticles(newParticles); - - const timeout = setTimeout(() => setParticles([]), duration); - return () => clearTimeout(timeout); - }, [active, duration]); - - return ( - - {particles.length > 0 && ( -
- {particles.map((p) => ( - - {p.emoji ? ( - {p.content} - ) : ( -
0.5 ? 1 : 2.5), - backgroundColor: p.color, - borderRadius: Math.random() > 0.5 ? '50%' : '2px', - }} - /> - )} - - ))} -
- )} - - ); -} diff --git a/legacy/taproot-assets-era/frontend/components/ErrorMessage.tsx b/legacy/taproot-assets-era/frontend/components/ErrorMessage.tsx deleted file mode 100644 index 390bd8a..0000000 --- a/legacy/taproot-assets-era/frontend/components/ErrorMessage.tsx +++ /dev/null @@ -1,426 +0,0 @@ -'use client'; - -import React from 'react'; -import { motion } from 'framer-motion'; -import { - Wallet, - XCircle, - Lock, - Search, - Coins, - Rocket, - AlertTriangle, - Wifi, - RefreshCw, - ArrowRight, - HelpCircle, - ExternalLink, - Mail -} from 'lucide-react'; -import clsx from 'clsx'; - -// Error types with user-friendly messaging -export type ErrorType = - | 'wallet_not_connected' - | 'connection_rejected' - | 'wallet_locked' - | 'network_mismatch' - | 'insufficient_funds' - | 'no_active_account' - | 'transfer_failed' - | 'recipient_not_found' - | 'amount_too_small' - | 'funding_pending' - | 'mempool_congestion' - | 'service_unavailable' - | 'unknown'; - -interface UserFriendlyError { - type: ErrorType; - icon: React.ElementType; - title: string; - message: string; - action: string; - actionLabel: string; - secondaryAction?: string; - secondaryActionLabel?: string; - showHelpLink?: boolean; -} - -const errorMessages: Record = { - wallet_not_connected: { - type: 'wallet_not_connected', - icon: Wallet, - title: 'Unleash your wallet! 🔓', - message: 'Your DOG needs a home. Connect your wallet to get started.', - action: 'connect', - actionLabel: 'Unleash Wallet 🐕', - secondaryAction: 'social', - secondaryActionLabel: 'Or create an account with email →', - }, - connection_rejected: { - type: 'connection_rejected', - icon: XCircle, - title: 'The DOG was denied entry 🚪', - message: "You declined the connection. No worries, the DOG will wait patiently!", - action: 'retry', - actionLabel: 'Let the DOG in 🐾', - secondaryAction: 'social', - secondaryActionLabel: 'Or create an account with email', - }, - wallet_locked: { - type: 'wallet_locked', - icon: Lock, - title: 'Wallet is napping 😴', - message: 'Your wallet is locked. Wake it up and try again!', - action: 'open_wallet', - actionLabel: 'Wake Up Wallet', - showHelpLink: true, - }, - network_mismatch: { - type: 'network_mismatch', - icon: Wifi, - title: 'Wrong neighborhood! 🏘️', - message: 'Your wallet wandered to the wrong network. Guide it back to Bitcoin Mainnet.', - action: 'open_settings', - actionLabel: 'Fix Network', - showHelpLink: true, - }, - insufficient_funds: { - type: 'insufficient_funds', - icon: Coins, - title: 'Your DOG wallet is on a diet 🐕💨', - message: 'Not enough DOG for this treat. Add more or reduce the amount.', - action: 'add_funds', - actionLabel: 'Feed the Wallet 🦴', - secondaryAction: 'reduce', - secondaryActionLabel: 'Or reduce the amount', - }, - no_active_account: { - type: 'no_active_account', - icon: Rocket, - title: 'Your DOG needs fuel! 🚀', - message: 'Add at least 1,000 DOG to start sending instant payments. To the moon!', - action: 'add_funds', - actionLabel: 'Add DOG Now 🐕', - secondaryAction: 'learn', - secondaryActionLabel: 'Why do I need to add DOG? →', - }, - transfer_failed: { - type: 'transfer_failed', - icon: AlertTriangle, - title: 'Oops! The DOG tripped 🐕‍🦺', - message: "Don't worry — your DOG is safe! Sometimes even good boys stumble. Try again in a sec.", - action: 'retry', - actionLabel: 'Try Again 🔄', - secondaryAction: 'support', - secondaryActionLabel: 'Still stuck? Get help →', - }, - recipient_not_found: { - type: 'recipient_not_found', - icon: Search, - title: "Can't sniff them out 🐕🔍", - message: 'Check the spelling or send them a claim link instead!', - action: 'search_again', - actionLabel: 'Sniff Again', - secondaryAction: 'claim_link', - secondaryActionLabel: 'Send a claim link instead →', - }, - amount_too_small: { - type: 'amount_too_small', - icon: Coins, - title: 'That\'s a crumb, not a treat! 🍪', - message: 'Minimum send is 100 DOG. Be more generous with your DOG!', - action: 'update', - actionLabel: 'Update Amount', - secondaryAction: 'learn', - secondaryActionLabel: 'Why is there a minimum? →', - }, - funding_pending: { - type: 'funding_pending', - icon: RefreshCw, - title: 'Your DOG is on its way! 🏃‍♂️', - message: "Bitcoin is fetching your deposit. Good boy! ~10 minutes.", - action: 'view_mempool', - actionLabel: 'Watch it Run 👀', - secondaryAction: 'notify', - secondaryActionLabel: 'Notify me when ready', - }, - mempool_congestion: { - type: 'mempool_congestion', - icon: AlertTriangle, - title: 'Traffic jam on the blockchain! 🚗', - message: 'Bitcoin is packed like a dog park on Saturday. Your tx may take a bit longer.', - action: 'speed_up', - actionLabel: 'Speed Up (Higher Fee) 💨', - secondaryAction: 'wait', - secondaryActionLabel: "I'll wait patiently like a good boy", - }, - service_unavailable: { - type: 'service_unavailable', - icon: Wifi, - title: "We're chasing our tail 🌀", - message: "Something went wrong on our end. Your DOG is safe! Try again in a minute.", - action: 'retry', - actionLabel: 'Try Again 🔄', - secondaryAction: 'status', - secondaryActionLabel: 'Status page: status.runebolt.io', - }, - unknown: { - type: 'unknown', - icon: AlertTriangle, - title: 'Ruh roh! Something broke 🐕', - message: 'An unexpected error occurred. Your DOG is safe though!', - action: 'retry', - actionLabel: 'Try Again 🔄', - secondaryAction: 'support', - secondaryActionLabel: 'Contact support', - }, -}; - -interface ErrorMessageProps { - error?: ErrorType | string; - technicalError?: string; - context?: 'modal' | 'inline' | 'page' | 'toast'; - onAction?: (action: string) => void; - onClose?: () => void; - className?: string; -} - -export function ErrorMessage({ - error = 'unknown', - technicalError, - context = 'inline', - onAction, - onClose, - className, -}: ErrorMessageProps) { - // Determine error type - const errorType: ErrorType = typeof error === 'string' && error in errorMessages - ? (error as ErrorType) - : 'unknown'; - - const errorConfig = errorMessages[errorType]; - const Icon = errorConfig.icon; - - const handleAction = (action: string) => { - onAction?.(action); - }; - - // Compact toast version - if (context === 'toast') { - return ( - - -
-

{errorConfig.title}

-

{errorConfig.message}

-
- -
- ); - } - - // Inline compact version - if (context === 'inline') { - return ( - -
-
- -
-
-

{errorConfig.title}

-

{errorConfig.message}

-
- - {errorConfig.secondaryAction && ( - - )} -
-
-
- {technicalError && ( -
-

{technicalError}

-
- )} -
- ); - } - - // Full modal/page version - return ( - - {/* Background gradient */} -
- -
- - - - -

{errorConfig.title}

-

{errorConfig.message}

- - {/* Primary Action */} - handleAction(errorConfig.action)} - className="mx-auto mt-6 flex w-full max-w-xs items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-bitcoin to-orange-600 py-3 text-sm font-semibold text-white shadow-lg shadow-bitcoin/20" - > - {errorConfig.actionLabel} - - - - {/* Secondary Action */} - {errorConfig.secondaryAction && ( - - )} - - {/* Help Link */} - {errorConfig.showHelpLink && ( - - - Need help? Contact support - - )} - - {/* Technical Error (for debugging) */} - {technicalError && ( -
-

{technicalError}

-
- )} -
- - ); -} - -// Error boundary wrapper for catching React errors -interface ErrorBoundaryProps { - children: React.ReactNode; - fallback?: React.ReactNode; -} - -interface ErrorBoundaryState { - hasError: boolean; - error: Error | null; -} - -export class ErrorBoundary extends React.Component { - constructor(props: ErrorBoundaryProps) { - super(props); - this.state = { hasError: false, error: null }; - } - - static getDerivedStateFromError(error: Error): ErrorBoundaryState { - return { hasError: true, error }; - } - - componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { - console.error('ErrorBoundary caught error:', error, errorInfo); - } - - render() { - if (this.state.hasError) { - if (this.props.fallback) { - return this.props.fallback; - } - return ( -
- { - if (action === 'retry') { - window.location.reload(); - } - }} - /> -
- ); - } - - return this.props.children; - } -} - -// Helper to map technical errors to user-friendly types -export function mapErrorToType(error: string | Error): ErrorType { - const message = typeof error === 'string' ? error.toLowerCase() : error.message.toLowerCase(); - - if (message.includes('wallet') && message.includes('detected')) return 'wallet_not_connected'; - if (message.includes('rejected') || message.includes('declined')) return 'connection_rejected'; - if (message.includes('locked') || message.includes('unauthorized')) return 'wallet_locked'; - if (message.includes('network') || message.includes('mainnet')) return 'network_mismatch'; - if (message.includes('insufficient') || message.includes('balance')) return 'insufficient_funds'; - if (message.includes('channel') || message.includes('no active')) return 'no_active_account'; - if (message.includes('recipient') || message.includes('not found')) return 'recipient_not_found'; - if (message.includes('dust') || message.includes('too small')) return 'amount_too_small'; - if (message.includes('funding') && message.includes('pending')) return 'funding_pending'; - if (message.includes('fee') || message.includes('congestion')) return 'mempool_congestion'; - if (message.includes('500') || message.includes('unavailable')) return 'service_unavailable'; - if (message.includes('transfer') && message.includes('fail')) return 'transfer_failed'; - - return 'unknown'; -} - -// Default export with all exports -export default ErrorMessage; diff --git a/legacy/taproot-assets-era/frontend/components/GlassCard.tsx b/legacy/taproot-assets-era/frontend/components/GlassCard.tsx deleted file mode 100644 index 3c54ce8..0000000 --- a/legacy/taproot-assets-era/frontend/components/GlassCard.tsx +++ /dev/null @@ -1,30 +0,0 @@ -'use client'; - -import { motion } from 'framer-motion'; -import clsx from 'clsx'; - -interface GlassCardProps { - children: React.ReactNode; - className?: string; - hover?: boolean; - onClick?: () => void; -} - -export default function GlassCard({ children, className, hover = false, onClick }: GlassCardProps) { - return ( - - {children} - - ); -} diff --git a/legacy/taproot-assets-era/frontend/components/LoadingSpinner.tsx b/legacy/taproot-assets-era/frontend/components/LoadingSpinner.tsx deleted file mode 100644 index e8d32a6..0000000 --- a/legacy/taproot-assets-era/frontend/components/LoadingSpinner.tsx +++ /dev/null @@ -1,47 +0,0 @@ -'use client'; - -import { motion } from 'framer-motion'; -import clsx from 'clsx'; - -interface LoadingSpinnerProps { - size?: 'sm' | 'md' | 'lg'; - className?: string; - message?: string; -} - -const sizeMap = { - sm: { container: 'w-6 h-6', text: 'text-xs' }, - md: { container: 'w-10 h-10', text: 'text-sm' }, - lg: { container: 'w-16 h-16', text: 'text-base' }, -}; - -const funMessages = [ - 'Fetching... good boy! 🐾', - 'Sniffing the blockchain... 🐕', - 'Wagging intensifies... 🐕‍🦺', - 'Much load. Very patience. 🌀', - 'Almost there, hooman! 🐶', -]; - -export default function LoadingSpinner({ size = 'md', className, message }: LoadingSpinnerProps) { - const s = sizeMap[size]; - const displayMessage = message || funMessages[Math.floor(Math.random() * funMessages.length)]; - - return ( -
- -
-
- 🐕 - -

{displayMessage}

-
- ); -} diff --git a/legacy/taproot-assets-era/frontend/components/Navbar.tsx b/legacy/taproot-assets-era/frontend/components/Navbar.tsx deleted file mode 100644 index f0ae400..0000000 --- a/legacy/taproot-assets-era/frontend/components/Navbar.tsx +++ /dev/null @@ -1,118 +0,0 @@ -'use client'; - -import { useState } from 'react'; -import { motion, AnimatePresence } from 'framer-motion'; -import { Zap, Menu, X } from 'lucide-react'; -import Link from 'next/link'; - -export default function Navbar() { - const [mobileOpen, setMobileOpen] = useState(false); - - return ( - - ); -} diff --git a/legacy/taproot-assets-era/frontend/components/OnboardingFlow.tsx b/legacy/taproot-assets-era/frontend/components/OnboardingFlow.tsx deleted file mode 100644 index c1c84cd..0000000 --- a/legacy/taproot-assets-era/frontend/components/OnboardingFlow.tsx +++ /dev/null @@ -1,361 +0,0 @@ -'use client'; - -import { useState } from 'react'; -import { motion, AnimatePresence } from 'framer-motion'; -import { - ArrowRight, - Mail, - Wallet, - User, - Check, - Loader2, - Zap, - Sparkles -} from 'lucide-react'; -import clsx from 'clsx'; - -// Social login providers -const providers = [ - { - id: 'google', - name: 'Google', - icon: 'G', - color: 'bg-white text-gray-800 hover:bg-gray-50', - }, - { - id: 'apple', - name: 'Apple', - icon: 'A', - color: 'bg-white text-gray-800 hover:bg-gray-50', - }, - { - id: 'email', - name: 'Email', - icon: , - color: 'bg-cyan/10 text-cyan border border-cyan/20 hover:bg-cyan/20', - }, -]; - -type AuthStep = 'method' | 'username' | 'complete'; -type AuthMethod = 'social' | 'wallet' | null; - -interface OnboardingFlowProps { - isOpen: boolean; - onClose: () => void; - onComplete?: (data: { method: string; username?: string; pubkey?: string }) => void; -} - -export default function OnboardingFlow({ - isOpen, - onClose, - onComplete, -}: OnboardingFlowProps) { - const [step, setStep] = useState('method'); - const [selectedProvider, setSelectedProvider] = useState(null); - const [username, setUsername] = useState(''); - const [isLoading, setIsLoading] = useState(false); - const [error, setError] = useState(''); - - const handleProviderSelect = async (providerId: string) => { - setIsLoading(true); - setSelectedProvider(providerId); - - try { - // Simulate API call - await new Promise((resolve) => setTimeout(resolve, 800)); - setStep('username'); - } catch (err) { - setError('Failed to connect. Please try again.'); - } finally { - setIsLoading(false); - } - }; - - const handleWalletConnect = async () => { - setIsLoading(true); - - try { - if (typeof window !== 'undefined' && !(window as any).unisat) { - window.open('https://unisat.io', '_blank'); - setError('Please install Unisat wallet and refresh.'); - setIsLoading(false); - return; - } - - const accounts = await (window as any).unisat.requestAccounts(); - if (accounts && accounts.length > 0) { - setStep('username'); - } - } catch (err) { - setError('Connection declined. Try again or use email.'); - } finally { - setIsLoading(false); - } - }; - - const handleUsernameSubmit = async (e: React.FormEvent) => { - e.preventDefault(); - if (!isValidUsername(username)) { - setError('3-20 characters, letters/numbers/underscores only'); - return; - } - - setIsLoading(true); - - try { - await new Promise((resolve) => setTimeout(resolve, 600)); - setStep('complete'); - - setTimeout(() => { - onComplete?.({ method: selectedProvider || 'wallet', username }); - handleClose(); - }, 1500); - } catch (err) { - setError('Username taken. Try another.'); - } finally { - setIsLoading(false); - } - }; - - const handleClose = () => { - setStep('method'); - setSelectedProvider(null); - setUsername(''); - setError(''); - onClose(); - }; - - const isValidUsername = (name: string) => { - return /^[a-zA-Z0-9_]{3,20}$/.test(name); - }; - - if (!isOpen) return null; - - return ( - - - e.stopPropagation()} - className="relative w-full max-w-md overflow-hidden rounded-2xl border border-dark-700 bg-dark-800 shadow-2xl" - > - {/* Progress Bar */} -
- -
- - - {/* Step 1: Choose Method */} - {step === 'method' && ( - -
- - - -

Welcome to RuneBolt

-

- Send DOG instantly on Bitcoin. No channel management required. -

-
- -
-

- Continue with -

- - {providers.map((provider) => ( - handleProviderSelect(provider.id)} - disabled={isLoading} - className={clsx( - 'flex w-full items-center justify-center gap-3 rounded-xl px-4 py-3 font-medium transition-all', - provider.color - )} - > - {provider.icon} - {isLoading && selectedProvider === provider.id ? ( - - ) : ( - `Continue with ${provider.name}` - )} - - ))} -
- -
-
- or -
-
- - - - {isLoading ? : 'Connect Bitcoin Wallet'} - - - {error && ( -

{error}

- )} - -

- By continuing, you agree to our Terms and Privacy Policy -

- - )} - - {/* Step 2: Username */} - {step === 'username' && ( - - - -
-
- -
-

Choose your username

-

- This is how people will find you on RuneBolt. -

-
- -
-
- @ - { - setUsername(e.target.value.toLowerCase()); - setError(''); - }} - placeholder="username" - maxLength={20} - className="w-full rounded-xl border border-dark-700 bg-dark-900 py-3 pl-8 pr-4 font-mono text-white placeholder-gray-500 outline-none transition-colors focus:border-emerald-500/50" - /> -
- - {username && isValidUsername(username) && ( - - ✓ Available! Your profile will be: runebolt.io/{username} - - )} - - {error && ( -

{error}

- )} - - - {isLoading ? ( - - ) : ( - <> - Claim Username - - - )} - -
- -

- You can change this later in settings -

-
- )} - - {/* Step 3: Complete */} - {step === 'complete' && ( - - - - - -

You're all set!

-

- Welcome to RuneBolt, @{username}! -

- -
- - Redirecting to your wallet... -
-
- )} - - - - - ); -} diff --git a/legacy/taproot-assets-era/frontend/components/SendModal.tsx b/legacy/taproot-assets-era/frontend/components/SendModal.tsx deleted file mode 100644 index d4cb108..0000000 --- a/legacy/taproot-assets-era/frontend/components/SendModal.tsx +++ /dev/null @@ -1,277 +0,0 @@ -'use client'; - -import { useState } from 'react'; -import { motion, AnimatePresence } from 'framer-motion'; -import { X, ArrowRight, Check, AlertCircle } from 'lucide-react'; -import AddressInput from './AddressInput'; -import { formatDogAmount, formatUsd } from '@/lib/format'; -import { DEMO_USD_RATE } from '@/lib/constants'; -import clsx from 'clsx'; - -interface SendModalProps { - isOpen: boolean; - onClose: () => void; - onSend?: (recipient: string, amount: number) => void; - maxBalance?: number; -} - -type Step = 'input' | 'review' | 'success' | 'error'; - -export default function SendModal({ isOpen, onClose, onSend, maxBalance = 125000 }: SendModalProps) { - const [step, setStep] = useState('input'); - const [recipient, setRecipient] = useState(''); - const [recipientType, setRecipientType] = useState<'runebolt' | 'bitcoin' | null>(null); - const [amount, setAmount] = useState(''); - - const numAmount = parseFloat(amount) || 0; - const isValid = recipientType !== null && numAmount > 0 && numAmount <= maxBalance; - - const handleReview = () => { - if (isValid) setStep('review'); - }; - - const handleConfirm = () => { - onSend?.(recipient, numAmount); - setStep('success'); - }; - - const handleClose = () => { - setStep('input'); - setRecipient(''); - setAmount(''); - setRecipientType(null); - onClose(); - }; - - const handleMax = () => { - setAmount(maxBalance.toString()); - }; - - return ( - - {isOpen && ( - - e.stopPropagation()} - className="w-full max-w-md overflow-hidden rounded-2xl border border-dark-700 bg-dark-800 shadow-2xl" - > - {/* Header */} -
-

- {step === 'input' && 'Send DOG'} - {step === 'review' && 'Review Transfer'} - {step === 'success' && 'Transfer Complete'} - {step === 'error' && 'Transfer Failed'} -

- -
- - {/* Content */} -
- - {step === 'input' && ( - -
- - -
- -
- -
- setAmount(e.target.value)} - placeholder="0.00000" - className="w-full rounded-xl border border-dark-700 bg-dark-800 px-4 py-3 pr-24 font-mono text-lg text-white placeholder-gray-500 outline-none transition-colors focus:border-bitcoin/50" - /> -
- - DOG -
-
- {numAmount > 0 && ( -

- {formatUsd(numAmount * DEMO_USD_RATE)} USD -

- )} -
- -
-
- Network Fee - 0 DOG (off-chain) -
-
- Estimated Time - < 1 second -
-
- - - Review Transfer - - -
- )} - - {step === 'review' && ( - -
-

Sending

-

- {formatDogAmount(numAmount)} -

-

DOG

-
- -
-
- To - {recipient} -
-
- Type - - {recipientType === 'runebolt' ? 'Off-Chain' : 'On-Chain'} - -
-
- Fee - 0 DOG -
-
- -
- - - Confirm & Send - -
-
- )} - - {step === 'success' && ( - - - - -

Transfer Sent!

-

- {formatDogAmount(numAmount)} DOG sent to {recipient} -

- - Done - -
- )} - - {step === 'error' && ( - -
- -
-

Transfer Failed

-

- Something went wrong. Please try again. -

- setStep('input')} - className="mt-6 w-full rounded-xl bg-gradient-to-r from-bitcoin to-orange-600 py-3 text-sm font-semibold text-white" - > - Try Again - -
- )} -
-
-
-
- )} -
- ); -} diff --git a/legacy/taproot-assets-era/frontend/components/ShibaInu.tsx b/legacy/taproot-assets-era/frontend/components/ShibaInu.tsx deleted file mode 100644 index 3b9623f..0000000 --- a/legacy/taproot-assets-era/frontend/components/ShibaInu.tsx +++ /dev/null @@ -1,137 +0,0 @@ -'use client'; - -import { motion } from 'framer-motion'; -import clsx from 'clsx'; - -interface ShibaInuProps { - size?: 'sm' | 'md' | 'lg' | 'xl' | 'hero'; - mood?: 'happy' | 'excited' | 'cool' | 'wink' | 'love'; - animate?: boolean; - className?: string; -} - -const sizeMap = { - sm: 'w-8 h-8 text-[8px]', - md: 'w-16 h-16 text-base', - lg: 'w-24 h-24 text-lg', - xl: 'w-32 h-32 text-xl', - hero: 'w-48 h-48 text-3xl', -}; - -const moodEmoji = { - happy: '(^ o ^)', - excited: '(>w<)', - cool: '( -_-)', - wink: '(^ _ ~)', - love: '(^ u ^)', -}; - -export default function ShibaInu({ size = 'md', mood = 'happy', animate = true, className }: ShibaInuProps) { - return ( - - - {/* Body circle */} - - - - {/* Face lighter area */} - - - {/* Left ear */} - - - - {/* Right ear */} - - - - {/* Eyes */} - {mood === 'wink' ? ( - <> - - - - - ) : mood === 'excited' ? ( - <> - - - - ) : mood === 'love' ? ( - <> - - - - ) : mood === 'cool' ? ( - <> - - - - - ) : ( - <> - - - - - - )} - - {/* Nose */} - - - - {/* Mouth */} - {mood === 'excited' || mood === 'happy' ? ( - - ) : ( - - )} - - {/* Blush */} - - - - {/* Tongue (excited/happy) */} - {(mood === 'excited' || mood === 'happy') && ( - - )} - - - {/* Sparkles around the shiba */} - {animate && (mood === 'excited' || mood === 'love') && ( - <> - - ✨ - - - ✨ - - - ⚡ - - - )} - - ); -} diff --git a/legacy/taproot-assets-era/frontend/components/StatCard.tsx b/legacy/taproot-assets-era/frontend/components/StatCard.tsx deleted file mode 100644 index 73e428d..0000000 --- a/legacy/taproot-assets-era/frontend/components/StatCard.tsx +++ /dev/null @@ -1,27 +0,0 @@ -'use client'; - -import { motion } from 'framer-motion'; -import GlassCard from './GlassCard'; - -interface StatCardProps { - label: string; - value: string; -} - -export default function StatCard({ label, value }: StatCardProps) { - return ( - - -

- {value} -

-

{label}

-
-
- ); -} diff --git a/legacy/taproot-assets-era/frontend/components/StatusBadge.tsx b/legacy/taproot-assets-era/frontend/components/StatusBadge.tsx deleted file mode 100644 index 630a2fa..0000000 --- a/legacy/taproot-assets-era/frontend/components/StatusBadge.tsx +++ /dev/null @@ -1,79 +0,0 @@ -'use client'; - -import clsx from 'clsx'; -import { ChannelState } from '@/lib/types'; - -interface StatusBadgeProps { - status: ChannelState | string; - className?: string; -} - -const statusConfig: Record = { - [ChannelState.OPEN]: { - label: 'Open', - color: 'bg-emerald-500/20 text-emerald-400 border-emerald-500/30', - pulse: true, - }, - [ChannelState.PENDING_OPEN]: { - label: 'Pending', - color: 'bg-amber-500/20 text-amber-400 border-amber-500/30', - pulse: true, - }, - [ChannelState.CLOSING]: { - label: 'Closing', - color: 'bg-orange-500/20 text-orange-400 border-orange-500/30', - pulse: true, - }, - [ChannelState.CLOSED]: { - label: 'Closed', - color: 'bg-gray-500/20 text-gray-400 border-gray-500/30', - pulse: false, - }, - [ChannelState.FORCE_CLOSING]: { - label: 'Force Closing', - color: 'bg-red-500/20 text-red-400 border-red-500/30', - pulse: true, - }, -}; - -export default function StatusBadge({ status, className }: StatusBadgeProps) { - const config = statusConfig[status] || { - label: status, - color: 'bg-gray-500/20 text-gray-400 border-gray-500/30', - pulse: false, - }; - - return ( - - {config.pulse && ( - - - - - )} - {config.label} - - ); -} diff --git a/legacy/taproot-assets-era/frontend/components/TransactionStatus.tsx b/legacy/taproot-assets-era/frontend/components/TransactionStatus.tsx deleted file mode 100644 index cdc239f..0000000 --- a/legacy/taproot-assets-era/frontend/components/TransactionStatus.tsx +++ /dev/null @@ -1,298 +0,0 @@ -'use client'; - -import { useEffect, useState } from 'react'; -import { motion, AnimatePresence } from 'framer-motion'; -import { - Loader2, - CheckCircle2, - XCircle, - Clock, - ArrowRight, - Zap -} from 'lucide-react'; -import clsx from 'clsx'; - -export type TransactionStatus = 'pending' | 'confirming' | 'confirmed' | 'failed'; -export type TransactionType = 'send' | 'receive' | 'claim' | 'deposit' | 'withdrawal'; - -export interface TransactionState { - id: string; - type: TransactionType; - status: TransactionStatus; - amount: number; - recipient?: string; - sender?: string; - timestamp: number; - estimatedConfirmationTime?: number; - error?: string; -} - -interface TransactionStatusIndicatorProps { - transaction: TransactionState; - onClose?: () => void; - showDetails?: boolean; - className?: string; -} - -const statusConfig = { - pending: { - icon: Loader2, - color: 'text-yellow-400', - bgColor: 'bg-yellow-400/10', - borderColor: 'border-yellow-400/20', - title: 'Sending...', - description: 'Your transaction is being processed', - showProgress: true, - }, - confirming: { - icon: Clock, - color: 'text-cyan', - bgColor: 'bg-cyan/10', - borderColor: 'border-cyan/20', - title: 'Confirming...', - description: 'Waiting for Bitcoin confirmation', - showProgress: true, - }, - confirmed: { - icon: CheckCircle2, - color: 'text-emerald-400', - bgColor: 'bg-emerald-400/10', - borderColor: 'border-emerald-400/20', - title: 'Complete!', - description: 'Transaction confirmed successfully', - showProgress: false, - }, - failed: { - icon: XCircle, - color: 'text-red-400', - bgColor: 'bg-red-400/10', - borderColor: 'border-red-400/20', - title: 'Failed', - description: 'Something went wrong', - showProgress: false, - }, -}; - -export function TransactionStatusIndicator({ - transaction, - onClose, - showDetails = true, - className, -}: TransactionStatusIndicatorProps) { - const [progress, setProgress] = useState(0); - const [elapsedTime, setElapsedTime] = useState(0); - - const config = statusConfig[transaction.status]; - const StatusIcon = config.icon; - - // Animate progress bar - useEffect(() => { - if (!config.showProgress) return; - - const interval = setInterval(() => { - setElapsedTime((prev) => prev + 1); - setProgress((prev) => { - if (prev >= 95) return 95; - return prev + Math.random() * 3; - }); - }, 1000); - - return () => clearInterval(interval); - }, [config.showProgress]); - - // Auto-close on confirmed after delay - useEffect(() => { - if (transaction.status === 'confirmed' && onClose) { - const timer = setTimeout(onClose, 5000); - return () => clearTimeout(timer); - } - }, [transaction.status, onClose]); - - const formatTime = (seconds: number) => { - if (seconds < 60) return `${seconds}s`; - const mins = Math.floor(seconds / 60); - const secs = seconds % 60; - return `${mins}m ${secs}s`; - }; - - const getTimeEstimate = () => { - if (transaction.status === 'pending') { - return '< 1 second'; - } - if (transaction.status === 'confirming') { - const remaining = Math.max(0, (transaction.estimatedConfirmationTime || 600) - elapsedTime); - return `~${Math.ceil(remaining / 60)} minutes`; - } - return ''; - }; - - return ( - - {/* Animated background for pending/confirming */} - {config.showProgress && ( - - )} - -
- {/* Status Icon */} -
- -
- - {/* Content */} -
-
-

- {config.title} -

- {transaction.status === 'pending' && ( - - - Instant - - )} -
- - {showDetails && ( - <> -

- {config.description} -

- - {/* Transaction Details */} -
- {transaction.type === 'send' && transaction.recipient && ( -

Sending to {transaction.recipient}

- )} - {transaction.type === 'receive' && transaction.sender && ( -

From {transaction.sender}

- )} -
- - {/* Progress Info */} - {config.showProgress && ( -
-
- Progress - {Math.round(progress)}% -
-
- -
-

- Estimated time: {getTimeEstimate()} -

-
- )} - - {/* Amount */} - {transaction.amount > 0 && ( -
- - {transaction.amount.toLocaleString()} - - DOG -
- )} - - {/* Error Message */} - {transaction.status === 'failed' && transaction.error && ( -

- {transaction.error} -

- )} - - )} -
-
-
- ); -} - -// Toast notification component for transaction updates -interface TransactionToastProps { - transactions: TransactionState[]; - onDismiss: (id: string) => void; -} - -export function TransactionToastContainer({ transactions, onDismiss }: TransactionToastProps) { - return ( -
- - {transactions.map((tx) => ( - - onDismiss(tx.id)} - /> - - ))} - -
- ); -} - -// Hook for managing transaction states with WebSocket updates -export function useTransactionStatus() { - const [transactions, setTransactions] = useState([]); - - const addTransaction = (tx: Omit) => { - setTransactions((prev) => [ - { ...tx, timestamp: Date.now() }, - ...prev, - ]); - }; - - const updateTransaction = (id: string, updates: Partial) => { - setTransactions((prev) => - prev.map((tx) => (tx.id === id ? { ...tx, ...updates } : tx)) - ); - }; - - const removeTransaction = (id: string) => { - setTransactions((prev) => prev.filter((tx) => tx.id !== id)); - }; - - const dismissTransaction = (id: string) => { - removeTransaction(id); - }; - - return { - transactions, - addTransaction, - updateTransaction, - removeTransaction, - dismissTransaction, - }; -} - -export default TransactionStatusIndicator; diff --git a/legacy/taproot-assets-era/frontend/components/TransferList.tsx b/legacy/taproot-assets-era/frontend/components/TransferList.tsx deleted file mode 100644 index 335d096..0000000 --- a/legacy/taproot-assets-era/frontend/components/TransferList.tsx +++ /dev/null @@ -1,115 +0,0 @@ -'use client'; - -import { motion } from 'framer-motion'; -import { Inbox } from 'lucide-react'; -import { Transfer } from '@/lib/types'; -import { formatDogAmount, formatAddress, formatTimeAgo } from '@/lib/format'; -import Link from 'next/link'; -import clsx from 'clsx'; - -interface TransferListProps { - transfers: Transfer[]; - showAllLink?: string; - maxItems?: number; -} - -const statusEmoji = { - sent: '🚀', - received: '🎁', - pending: '⏳', -}; - -export default function TransferList({ transfers, showAllLink, maxItems }: TransferListProps) { - const items = maxItems ? transfers.slice(0, maxItems) : transfers; - - if (items.length === 0) { - return ( -
- - 🐕 - -

No transfers yet

-

- Send some DOG to get the party started! 🎉 -

-
- ); - } - - return ( -
-
- {items.map((transfer, index) => { - const emoji = transfer.status === 'pending' - ? statusEmoji.pending - : statusEmoji[transfer.direction as keyof typeof statusEmoji] || '⚡'; - - return ( - - {/* Emoji status */} - - {emoji} - - -
-

- {transfer.direction === 'received' ? 'Received' : 'Sent'} - {transfer.counterpartyName && ( - - {transfer.direction === 'received' ? ' from ' : ' to '} - @{transfer.counterpartyName} - - )} -

-

- {transfer.counterpartyName - ? `${transfer.counterpartyName}@runebolt.io` - : formatAddress(transfer.counterparty)} -

-
- -
-

- {transfer.direction === 'received' ? '+' : '-'} - {formatDogAmount(transfer.amount)} -

-

- {formatTimeAgo(transfer.timestamp)} -

-
-
- ); - })} -
- - {showAllLink && ( -
- - View All Transfers 📜 - -
- )} -
- ); -} diff --git a/legacy/taproot-assets-era/frontend/components/WalletConnect.tsx b/legacy/taproot-assets-era/frontend/components/WalletConnect.tsx deleted file mode 100644 index f1f36c6..0000000 --- a/legacy/taproot-assets-era/frontend/components/WalletConnect.tsx +++ /dev/null @@ -1,120 +0,0 @@ -'use client'; - -import { useState, useRef, useEffect } from 'react'; -import { motion, AnimatePresence } from 'framer-motion'; -import { Wallet, Copy, LogOut, Check, ExternalLink } from 'lucide-react'; -import { useUnisat } from '@/hooks/useUnisat'; -import { formatAddress } from '@/lib/format'; -import clsx from 'clsx'; - -interface WalletConnectProps { - className?: string; - compact?: boolean; -} - -export default function WalletConnect({ className, compact = false }: WalletConnectProps) { - const { connected, address, loading, installed, connect, disconnect } = useUnisat(); - const [menuOpen, setMenuOpen] = useState(false); - const [copied, setCopied] = useState(false); - const menuRef = useRef(null); - - useEffect(() => { - function handleClickOutside(event: MouseEvent) { - if (menuRef.current && !menuRef.current.contains(event.target as Node)) { - setMenuOpen(false); - } - } - document.addEventListener('mousedown', handleClickOutside); - return () => document.removeEventListener('mousedown', handleClickOutside); - }, []); - - const copyAddress = async () => { - if (!address) return; - await navigator.clipboard.writeText(address); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - }; - - if (!connected) { - return ( - - - {loading ? 'Connecting...' : installed === false ? 'Install Unisat' : 'Connect Wallet'} - - ); - } - - return ( -
- setMenuOpen(!menuOpen)} - className={clsx( - 'flex items-center gap-2 rounded-xl border border-dark-700 bg-dark-800 px-4 py-2.5', - 'text-sm text-white transition-colors hover:border-dark-600' - )} - > -
- {formatAddress(address || '', compact ? 4 : 6)} - - - - {menuOpen && ( - -
-

Connected

-

{formatAddress(address || '', 8)}

-
-
- - - - View on Explorer - - -
-
- )} -
-
- ); -} diff --git a/legacy/taproot-assets-era/frontend/components/index.ts b/legacy/taproot-assets-era/frontend/components/index.ts deleted file mode 100644 index 936cf48..0000000 --- a/legacy/taproot-assets-era/frontend/components/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -// New UX Components for RuneBolt Mass Adoption -export { default as OnboardingFlow } from './OnboardingFlow'; -export { default as ClaimLink } from './ClaimLink'; -export { default as ErrorMessage, mapErrorToType } from './ErrorMessage'; -export { - default as TransactionStatusIndicator, - TransactionToastContainer, - useTransactionStatus, - type TransactionStatus, - type TransactionType, - type TransactionState, -} from './TransactionStatus'; diff --git a/legacy/taproot-assets-era/frontend/hooks/useApi.ts b/legacy/taproot-assets-era/frontend/hooks/useApi.ts deleted file mode 100644 index 4271de6..0000000 --- a/legacy/taproot-assets-era/frontend/hooks/useApi.ts +++ /dev/null @@ -1,108 +0,0 @@ -'use client'; - -import { useState, useCallback } from 'react'; -import { api } from '@/lib/api'; -import { Channel, Transfer, ClaimLink, FeeStatus, Stats } from '@/lib/types'; - -export function useApi() { - const [loading, setLoading] = useState(false); - const [error, setError] = useState(null); - - const withLoading = useCallback(async (fn: () => Promise): Promise => { - setLoading(true); - setError(null); - try { - const result = await fn(); - return result; - } catch (err) { - const message = err instanceof Error ? err.message : 'An error occurred'; - setError(message); - return null; - } finally { - setLoading(false); - } - }, []); - - const authenticate = useCallback( - async (pubkey: string, signFn: (msg: string) => Promise) => { - return withLoading(async () => { - const { challengeId, message } = await api.challenge(pubkey); - const signature = await signFn(message); - if (!signature) throw new Error('User rejected signature'); - return api.verify(challengeId, signature); - }); - }, - [withLoading] - ); - - const getChannels = useCallback( - () => withLoading(() => api.getChannels()) as Promise, - [withLoading] - ); - - const openChannel = useCallback( - (amount: number) => - withLoading(() => api.openChannel(amount)) as Promise, - [withLoading] - ); - - const closeChannel = useCallback( - (channelId: string) => withLoading(() => api.closeChannel(channelId)), - [withLoading] - ); - - const sendTransfer = useCallback( - (to: string, amount: number, memo?: string) => - withLoading(() => api.transfer(to, amount, memo)) as Promise, - [withLoading] - ); - - const getTransfers = useCallback( - (limit?: number) => withLoading(() => api.getTransfers(limit)), - [withLoading] - ); - - const getFeeStatus = useCallback( - (pubkey: string) => - withLoading(() => api.getFeeStatus(pubkey)) as Promise, - [withLoading] - ); - - const getStats = useCallback( - () => withLoading(() => api.getStats()) as Promise, - [withLoading] - ); - - const createClaimLink = useCallback( - (amount: number) => - withLoading(() => api.createClaimLink(amount)) as Promise, - [withLoading] - ); - - const claimLink = useCallback( - (claimId: string) => withLoading(() => api.claimLink(claimId)), - [withLoading] - ); - - const getClaimLink = useCallback( - (claimId: string) => - withLoading(() => api.getClaimLink(claimId)) as Promise, - [withLoading] - ); - - return { - loading, - error, - authenticate, - getChannels, - openChannel, - closeChannel, - sendTransfer, - getTransfers, - getFeeStatus, - getStats, - createClaimLink, - claimLink, - getClaimLink, - }; -} diff --git a/legacy/taproot-assets-era/frontend/hooks/useUnisat.ts b/legacy/taproot-assets-era/frontend/hooks/useUnisat.ts deleted file mode 100644 index 3c02aaa..0000000 --- a/legacy/taproot-assets-era/frontend/hooks/useUnisat.ts +++ /dev/null @@ -1,149 +0,0 @@ -'use client'; - -import { useState, useEffect, useCallback } from 'react'; -import { WalletState } from '@/lib/types'; - -declare global { - interface Window { - unisat?: { - requestAccounts: () => Promise; - getAccounts: () => Promise; - getPublicKey: () => Promise; - getBalance: () => Promise<{ confirmed: number; unconfirmed: number; total: number }>; - signMessage: (msg: string) => Promise; - signPsbt: (psbtHex: string) => Promise; - on: (event: string, handler: (...args: unknown[]) => void) => void; - removeListener: (event: string, handler: (...args: unknown[]) => void) => void; - }; - } -} - -const STORAGE_KEY = 'runebolt_wallet_connected'; - -export function useUnisat() { - const [wallet, setWallet] = useState({ - connected: false, - address: null, - publicKey: null, - balance: 0, - loading: false, - }); - const [installed, setInstalled] = useState(null); - - useEffect(() => { - const checkInstalled = () => { - setInstalled(typeof window !== 'undefined' && !!window.unisat); - }; - - checkInstalled(); - - const timer = setTimeout(checkInstalled, 500); - return () => clearTimeout(timer); - }, []); - - useEffect(() => { - if (installed && localStorage.getItem(STORAGE_KEY) === 'true') { - reconnect(); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [installed]); - - const reconnect = async () => { - if (!window.unisat) return; - try { - const accounts = await window.unisat.getAccounts(); - if (accounts.length > 0) { - const pubKey = await window.unisat.getPublicKey(); - setWallet({ - connected: true, - address: accounts[0], - publicKey: pubKey, - balance: 0, - loading: false, - }); - } - } catch { - localStorage.removeItem(STORAGE_KEY); - } - }; - - const connect = useCallback(async () => { - if (!window.unisat) { - window.open('https://unisat.io', '_blank'); - return; - } - - setWallet((prev) => ({ ...prev, loading: true })); - - try { - const accounts = await window.unisat.requestAccounts(); - const pubKey = await window.unisat.getPublicKey(); - - setWallet({ - connected: true, - address: accounts[0], - publicKey: pubKey, - balance: 0, - loading: false, - }); - - localStorage.setItem(STORAGE_KEY, 'true'); - } catch { - setWallet((prev) => ({ ...prev, loading: false })); - } - }, []); - - const disconnect = useCallback(() => { - setWallet({ - connected: false, - address: null, - publicKey: null, - balance: 0, - loading: false, - }); - localStorage.removeItem(STORAGE_KEY); - }, []); - - const signMessage = useCallback( - async (msg: string): Promise => { - if (!window.unisat || !wallet.connected) return null; - try { - return await window.unisat.signMessage(msg); - } catch { - return null; - } - }, - [wallet.connected] - ); - - const signPsbt = useCallback( - async (psbtHex: string): Promise => { - if (!window.unisat || !wallet.connected) return null; - try { - return await window.unisat.signPsbt(psbtHex); - } catch { - return null; - } - }, - [wallet.connected] - ); - - const getPublicKey = useCallback(async (): Promise => { - if (!window.unisat) return null; - try { - return await window.unisat.getPublicKey(); - } catch { - return null; - } - }, []); - - return { - ...wallet, - installed, - connect, - disconnect, - signMessage, - signPsbt, - getPublicKey, - }; -} diff --git a/legacy/taproot-assets-era/frontend/hooks/useWebSocket.ts b/legacy/taproot-assets-era/frontend/hooks/useWebSocket.ts deleted file mode 100644 index b5aefd0..0000000 --- a/legacy/taproot-assets-era/frontend/hooks/useWebSocket.ts +++ /dev/null @@ -1,107 +0,0 @@ -'use client'; - -import { useEffect, useRef, useCallback, useState } from 'react'; -import { WS_URL } from '@/lib/constants'; -import { Transfer } from '@/lib/types'; - -interface WebSocketHookOptions { - url?: string; - onTransfer?: (transfer: Transfer) => void; - onChannelUpdate?: (channelId: string, state: string) => void; - autoReconnect?: boolean; - reconnectInterval?: number; -} - -export function useWebSocket(options: WebSocketHookOptions = {}) { - const { - url = WS_URL, - onTransfer, - onChannelUpdate, - autoReconnect = true, - reconnectInterval = 3000, - } = options; - - const wsRef = useRef(null); - const reconnectTimerRef = useRef(null); - const [connected, setConnected] = useState(false); - - const cleanup = useCallback(() => { - if (reconnectTimerRef.current) { - clearTimeout(reconnectTimerRef.current); - reconnectTimerRef.current = null; - } - if (wsRef.current) { - wsRef.current.close(); - wsRef.current = null; - } - }, []); - - const connectWs = useCallback(() => { - cleanup(); - - try { - const ws = new WebSocket(url); - wsRef.current = ws; - - ws.onopen = () => { - setConnected(true); - }; - - ws.onmessage = (event) => { - try { - const data = JSON.parse(event.data); - - if (data.type === 'transfer' && onTransfer) { - onTransfer(data.payload as Transfer); - } - - if (data.type === 'channel_update' && onChannelUpdate) { - onChannelUpdate(data.payload.channelId, data.payload.state); - } - } catch { - // Invalid JSON, ignore - } - }; - - ws.onclose = () => { - setConnected(false); - if (autoReconnect) { - reconnectTimerRef.current = setTimeout(connectWs, reconnectInterval); - } - }; - - ws.onerror = () => { - ws.close(); - }; - } catch { - if (autoReconnect) { - reconnectTimerRef.current = setTimeout(connectWs, reconnectInterval); - } - } - }, [url, onTransfer, onChannelUpdate, autoReconnect, reconnectInterval, cleanup]); - - const subscribe = useCallback( - (channelId: string) => { - if (wsRef.current?.readyState === WebSocket.OPEN) { - wsRef.current.send(JSON.stringify({ type: 'subscribe', channelId })); - } - }, - [] - ); - - const disconnect = useCallback(() => { - cleanup(); - setConnected(false); - }, [cleanup]); - - useEffect(() => { - return cleanup; - }, [cleanup]); - - return { - connected, - connect: connectWs, - disconnect, - subscribe, - }; -} diff --git a/legacy/taproot-assets-era/frontend/lib/api.ts b/legacy/taproot-assets-era/frontend/lib/api.ts deleted file mode 100644 index 36aef88..0000000 --- a/legacy/taproot-assets-era/frontend/lib/api.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { API_URL } from './constants'; -import { Channel, Transfer, ClaimLink, FeeStatus, Stats } from './types'; - -const AUTH_TOKEN_KEY = 'runebolt_jwt'; - -class RuneBoltAPI { - private baseUrl: string; - - constructor(baseUrl: string = API_URL) { - this.baseUrl = baseUrl; - } - - private getToken(): string | null { - if (typeof window === 'undefined') return null; - return localStorage.getItem(AUTH_TOKEN_KEY); - } - - setToken(token: string) { - localStorage.setItem(AUTH_TOKEN_KEY, token); - } - - clearToken() { - localStorage.removeItem(AUTH_TOKEN_KEY); - } - - isAuthenticated(): boolean { - return !!this.getToken(); - } - - private async request(path: string, options: RequestInit = {}): Promise { - const headers: Record = { - 'Content-Type': 'application/json', - ...(options.headers as Record), - }; - - const token = this.getToken(); - if (token) { - headers['Authorization'] = `Bearer ${token}`; - } - - const response = await fetch(`${this.baseUrl}${path}`, { - ...options, - headers, - }); - - if (response.status === 401) { - this.clearToken(); - if (typeof window !== 'undefined') { - window.location.href = '/runebolt/app'; - } - throw new Error('Session expired'); - } - - if (!response.ok) { - const error = await response.json().catch(() => ({ message: 'Request failed' })); - throw new Error(error.message || `HTTP ${response.status}`); - } - - return response.json(); - } - - // Auth flow - async challenge(pubkey: string) { - return this.request<{ challengeId: string; message: string }>( - '/auth/auth/challenge', - { - method: 'POST', - body: JSON.stringify({ pubkey }), - } - ); - } - - async verify(challengeId: string, signature: string) { - const result = await this.request<{ token: string; user: { address: string; username?: string } }>( - '/auth/auth/wallet/verify', - { - method: 'POST', - body: JSON.stringify({ challengeId, signature }), - } - ); - this.setToken(result.token); - return result; - } - - // Channels - async getChannels() { - return this.request('/channels'); - } - - async openChannel(amount: number) { - return this.request('/channels/open', { - method: 'POST', - body: JSON.stringify({ amount }), - }); - } - - async closeChannel(channelId: string) { - return this.request<{ txid: string }>(`/channels/${channelId}/close`, { - method: 'POST', - }); - } - - // Transfers - async transfer(to: string, amount: number, memo?: string) { - return this.request('/transfers', { - method: 'POST', - body: JSON.stringify({ to, amount, memo }), - }); - } - - async getTransfers(limit: number = 20) { - return this.request<{ transfers: Transfer[]; total: number }>( - `/transfers/history?limit=${limit}` - ); - } - - // Fees - async getFeeStatus(pubkey: string) { - return this.request(`/fees/status/${pubkey}`); - } - - // Stats - async getStats() { - return this.request('/stats'); - } - - // Claims (kept for compatibility) - async createClaimLink(amount: number) { - return this.request('/claim/create', { - method: 'POST', - body: JSON.stringify({ amount }), - }); - } - - async claimLink(claimId: string) { - return this.request<{ transfer: Transfer }>(`/claim/${claimId}`, { - method: 'POST', - }); - } - - async getClaimLink(claimId: string) { - return this.request(`/claim/${claimId}`); - } -} - -export const api = new RuneBoltAPI(); -export default RuneBoltAPI; diff --git a/legacy/taproot-assets-era/frontend/lib/constants.ts b/legacy/taproot-assets-era/frontend/lib/constants.ts deleted file mode 100644 index a5f0a80..0000000 --- a/legacy/taproot-assets-era/frontend/lib/constants.ts +++ /dev/null @@ -1,11 +0,0 @@ -export const DOG_RUNE_ID = '3891316:293'; -export const DOG_RUNE_NAME = 'DOG\u2022GO\u2022TO\u2022THE\u2022MOON'; -export const DOG_TICKER = 'DOG'; -export const DOG_DECIMALS = 5; - -export const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3141'; -export const WS_URL = process.env.NEXT_PUBLIC_WS_URL || 'ws://localhost:3141'; - -export const NETWORK = process.env.NEXT_PUBLIC_NETWORK || 'testnet'; - -export const DEMO_USD_RATE = 0.0034; diff --git a/legacy/taproot-assets-era/frontend/lib/demo-data.ts b/legacy/taproot-assets-era/frontend/lib/demo-data.ts deleted file mode 100644 index d82a9bf..0000000 --- a/legacy/taproot-assets-era/frontend/lib/demo-data.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { Channel, ChannelState, Transfer, User, ClaimLink } from './types'; - -export const demoUser: User = { - address: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh', - publicKey: '02a1633cafcc01ebfb6d78e39f687a1f0995c62fc95f51ead10a02ee0be551b5dc', - username: 'satoshi', - runeboltAddress: 'satoshi@runebolt.io', - balance: 125000.12345, - usdBalance: 425.00, -}; - -export const demoChannels: Channel[] = [ - { - id: 'ch_a1b2c3d4e5f6g7h8', - counterparty: 'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq', - localBalance: 50000.00000, - remoteBalance: 30000.00000, - capacity: 80000.00000, - state: ChannelState.OPEN, - createdAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), - updatedAt: new Date(Date.now() - 2 * 60 * 60 * 1000), - }, - { - id: 'ch_x9y8z7w6v5u4t3s2', - counterparty: 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4', - localBalance: 75000.12345, - remoteBalance: 25000.00000, - capacity: 100000.12345, - state: ChannelState.OPEN, - createdAt: new Date(Date.now() - 14 * 24 * 60 * 60 * 1000), - updatedAt: new Date(Date.now() - 30 * 60 * 1000), - }, - { - id: 'ch_m1n2o3p4q5r6s7t8', - counterparty: 'bc1qc7slrfxkknhcq86cc3eag7tycdrmrlhp9v6l5s', - localBalance: 0, - remoteBalance: 0, - capacity: 45000.00000, - state: ChannelState.CLOSING, - createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), - updatedAt: new Date(Date.now() - 1 * 60 * 60 * 1000), - }, -]; - -const now = Date.now(); - -export const demoTransfers: Transfer[] = [ - { - id: 'tx_001', - direction: 'received', - amount: 5000.00000, - counterparty: 'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq', - counterpartyName: 'alice', - channelId: 'ch_a1b2c3d4e5f6g7h8', - timestamp: new Date(now - 5 * 60 * 1000), - status: 'completed', - }, - { - id: 'tx_002', - direction: 'sent', - amount: 12500.50000, - counterparty: 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4', - counterpartyName: 'bob', - channelId: 'ch_x9y8z7w6v5u4t3s2', - timestamp: new Date(now - 15 * 60 * 1000), - status: 'completed', - }, - { - id: 'tx_003', - direction: 'received', - amount: 750.00000, - counterparty: 'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq', - channelId: 'ch_a1b2c3d4e5f6g7h8', - timestamp: new Date(now - 2 * 60 * 60 * 1000), - status: 'completed', - }, - { - id: 'tx_004', - direction: 'sent', - amount: 25000.00000, - counterparty: 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4', - counterpartyName: 'charlie', - channelId: 'ch_x9y8z7w6v5u4t3s2', - timestamp: new Date(now - 5 * 60 * 60 * 1000), - status: 'completed', - }, - { - id: 'tx_005', - direction: 'received', - amount: 100.00000, - counterparty: 'bc1qc7slrfxkknhcq86cc3eag7tycdrmrlhp9v6l5s', - channelId: 'ch_m1n2o3p4q5r6s7t8', - timestamp: new Date(now - 12 * 60 * 60 * 1000), - status: 'completed', - }, - { - id: 'tx_006', - direction: 'sent', - amount: 3200.00000, - counterparty: 'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq', - counterpartyName: 'alice', - channelId: 'ch_a1b2c3d4e5f6g7h8', - timestamp: new Date(now - 24 * 60 * 60 * 1000), - status: 'completed', - }, - { - id: 'tx_007', - direction: 'received', - amount: 8800.12345, - counterparty: 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4', - channelId: 'ch_x9y8z7w6v5u4t3s2', - timestamp: new Date(now - 36 * 60 * 60 * 1000), - status: 'completed', - }, - { - id: 'tx_008', - direction: 'sent', - amount: 500.00000, - counterparty: 'bc1qc7slrfxkknhcq86cc3eag7tycdrmrlhp9v6l5s', - channelId: 'ch_m1n2o3p4q5r6s7t8', - timestamp: new Date(now - 2 * 24 * 60 * 60 * 1000), - status: 'completed', - }, - { - id: 'tx_009', - direction: 'received', - amount: 15000.00000, - counterparty: 'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq', - counterpartyName: 'alice', - channelId: 'ch_a1b2c3d4e5f6g7h8', - timestamp: new Date(now - 3 * 24 * 60 * 60 * 1000), - status: 'completed', - }, - { - id: 'tx_010', - direction: 'sent', - amount: 42000.00000, - counterparty: 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4', - counterpartyName: 'bob', - channelId: 'ch_x9y8z7w6v5u4t3s2', - timestamp: new Date(now - 5 * 24 * 60 * 60 * 1000), - status: 'completed', - }, -]; - -export const demoClaimLink: ClaimLink & { runeName: string; message: string } = { - id: 'claim_abc123', - amount: 10000.00000, - runeName: 'DOG•GO•TO•THE•MOON', - sender: 'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq', - senderName: 'alice', - message: 'Enjoy your DOG! 🐕', - expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), - claimed: false, -}; diff --git a/legacy/taproot-assets-era/frontend/lib/format.ts b/legacy/taproot-assets-era/frontend/lib/format.ts deleted file mode 100644 index 2bdec84..0000000 --- a/legacy/taproot-assets-era/frontend/lib/format.ts +++ /dev/null @@ -1,34 +0,0 @@ -export function formatDogAmount(amount: number): string { - return amount.toLocaleString('en-US', { - minimumFractionDigits: 5, - maximumFractionDigits: 5, - }); -} - -export function formatAddress(addr: string, chars: number = 6): string { - if (addr.length <= chars * 2 + 3) return addr; - return `${addr.slice(0, chars)}...${addr.slice(-chars)}`; -} - -export function formatTimeAgo(date: Date): string { - const now = new Date(); - const seconds = Math.floor((now.getTime() - date.getTime()) / 1000); - - if (seconds < 60) return 'just now'; - if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`; - if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`; - if (seconds < 604800) return `${Math.floor(seconds / 86400)}d ago`; - return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }); -} - -export function formatUsd(amount: number): string { - return `$${amount.toLocaleString('en-US', { - minimumFractionDigits: 2, - maximumFractionDigits: 2, - })}`; -} - -export function formatChannelId(id: string): string { - if (id.length <= 12) return id; - return `${id.slice(0, 8)}...${id.slice(-4)}`; -} diff --git a/legacy/taproot-assets-era/frontend/lib/types.ts b/legacy/taproot-assets-era/frontend/lib/types.ts deleted file mode 100644 index a5e17bd..0000000 --- a/legacy/taproot-assets-era/frontend/lib/types.ts +++ /dev/null @@ -1,70 +0,0 @@ -export enum ChannelState { - PENDING_OPEN = 'PENDING_OPEN', - OPEN = 'OPEN', - CLOSING = 'CLOSING', - CLOSED = 'CLOSED', - FORCE_CLOSING = 'FORCE_CLOSING', -} - -export interface Channel { - id: string; - counterparty: string; - localBalance: number; - remoteBalance: number; - capacity: number; - state: ChannelState; - createdAt: Date; - updatedAt: Date; -} - -export interface Transfer { - id: string; - direction: 'sent' | 'received'; - amount: number; - counterparty: string; - counterpartyName?: string; - channelId: string; - timestamp: Date; - status: 'completed' | 'pending' | 'failed'; -} - -export interface User { - address: string; - publicKey: string; - username?: string; - runeboltAddress: string; - balance: number; - usdBalance: number; -} - -export interface ClaimLink { - id: string; - amount: number; - sender: string; - senderName?: string; - expiresAt?: Date; - claimed: boolean; -} - -export interface WalletState { - connected: boolean; - address: string | null; - publicKey: string | null; - balance: number; - loading: boolean; -} - -export interface FeeStatus { - pubkey: string; - totalTransfers: number; - freeRemaining: number; - feeRate: number; - isFree: boolean; -} - -export interface Stats { - totalUsers: number; - totalTransfers: number; - totalVolume: number; - avgSpeed: number; -} diff --git a/legacy/taproot-assets-era/frontend/lib/wallet.ts b/legacy/taproot-assets-era/frontend/lib/wallet.ts deleted file mode 100644 index 47af3c9..0000000 --- a/legacy/taproot-assets-era/frontend/lib/wallet.ts +++ /dev/null @@ -1,54 +0,0 @@ -declare global { - interface Window { - unisat?: { - requestAccounts: () => Promise; - getAccounts: () => Promise; - getPublicKey: () => Promise; - getBalance: () => Promise<{ confirmed: number; unconfirmed: number; total: number }>; - signMessage: (msg: string) => Promise; - signPsbt: (psbtHex: string) => Promise; - on: (event: string, handler: (...args: unknown[]) => void) => void; - removeListener: (event: string, handler: (...args: unknown[]) => void) => void; - }; - } -} - -export function detectWallet(): boolean { - return typeof window !== 'undefined' && !!window.unisat; -} - -export async function connectWallet(): Promise<{ address: string; publicKey: string } | null> { - if (!window.unisat) { - window.open('https://unisat.io', '_blank'); - return null; - } - const accounts = await window.unisat.requestAccounts(); - const publicKey = await window.unisat.getPublicKey(); - return { address: accounts[0], publicKey }; -} - -export async function signMessage(message: string): Promise { - if (!window.unisat) return null; - try { - return await window.unisat.signMessage(message); - } catch { - return null; - } -} - -export async function getAddress(): Promise { - if (!window.unisat) return null; - try { - const accounts = await window.unisat.getAccounts(); - return accounts[0] || null; - } catch { - return null; - } -} - -export function onAccountChanged(callback: (accounts: string[]) => void): () => void { - if (!window.unisat) return () => {}; - const handler = (...args: unknown[]) => callback(args[0] as string[]); - window.unisat.on('accountsChanged', handler); - return () => window.unisat?.removeListener('accountsChanged', handler); -} diff --git a/legacy/taproot-assets-era/frontend/next.config.js b/legacy/taproot-assets-era/frontend/next.config.js deleted file mode 100644 index 0bc7c62..0000000 --- a/legacy/taproot-assets-era/frontend/next.config.js +++ /dev/null @@ -1,17 +0,0 @@ -/** @type {import('next').NextConfig} */ -const nextConfig = { - reactStrictMode: true, - output: 'export', - distDir: 'dist', - assetPrefix: '/runebolt', - basePath: '/runebolt', - images: { - unoptimized: true, - }, - env: { - NEXT_PUBLIC_API_URL: 'https://runebolt.blockgenomics.io/api/v1', - NEXT_PUBLIC_WS_URL: 'wss://runebolt.blockgenomics.io/ws', - }, -}; - -module.exports = nextConfig; diff --git a/legacy/taproot-assets-era/frontend/package-lock.json b/legacy/taproot-assets-era/frontend/package-lock.json deleted file mode 100644 index 8012f89..0000000 --- a/legacy/taproot-assets-era/frontend/package-lock.json +++ /dev/null @@ -1,1682 +0,0 @@ -{ - "name": "@runebolt/frontend", - "version": "0.1.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "@runebolt/frontend", - "version": "0.1.0", - "dependencies": { - "clsx": "^2.1.0", - "framer-motion": "^10.18.0", - "lucide-react": "^0.303.0", - "next": "14.1.0", - "qrcode.react": "^3.2.0", - "react": "^18.2.0", - "react-dom": "^18.2.0" - }, - "devDependencies": { - "@types/node": "^20.10.0", - "@types/react": "^18.2.45", - "@types/react-dom": "^18.2.18", - "autoprefixer": "^10.4.16", - "postcss": "^8.4.32", - "tailwindcss": "^3.4.0", - "typescript": "^5.3.3" - } - }, - "node_modules/@alloc/quick-lru": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", - "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@emotion/is-prop-valid": { - "version": "0.8.8", - "resolved": "https://registry.npmjs.org/@emotion/is-prop-valid/-/is-prop-valid-0.8.8.tgz", - "integrity": "sha512-u5WtneEAr5IDG2Wv65yhunPSMLIpuKsbuOktRojfrEiEvRyC85LgPMZI63cr7NUqT8ZIGdSVg8ZKGxIug4lXcA==", - "license": "MIT", - "optional": true, - "dependencies": { - "@emotion/memoize": "0.7.4" - } - }, - "node_modules/@emotion/memoize": { - "version": "0.7.4", - "resolved": "https://registry.npmjs.org/@emotion/memoize/-/memoize-0.7.4.tgz", - "integrity": "sha512-Ja/Vfqe3HpuzRsG1oBtWTHk2PGZ7GR+2Vz5iYGelAw8dx32K0y7PjVuxK6z1nMpZOqAFsRUPCkK1YjJ56qJlgw==", - "license": "MIT", - "optional": true - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.13", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", - "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.0", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.31", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", - "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } - }, - "node_modules/@next/env": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/@next/env/-/env-14.1.0.tgz", - "integrity": "sha512-Py8zIo+02ht82brwwhTg36iogzFqGLPXlRGKQw5s+qP/kMNc4MAyDeEwBKDijk6zTIbegEgu8Qy7C1LboslQAw==", - "license": "MIT" - }, - "node_modules/@next/swc-darwin-arm64": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-14.1.0.tgz", - "integrity": "sha512-nUDn7TOGcIeyQni6lZHfzNoo9S0euXnu0jhsbMOmMJUBfgsnESdjN97kM7cBqQxZa8L/bM9om/S5/1dzCrW6wQ==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-darwin-x64": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-14.1.0.tgz", - "integrity": "sha512-1jgudN5haWxiAl3O1ljUS2GfupPmcftu2RYJqZiMJmmbBT5M1XDffjUtRUzP4W3cBHsrvkfOFdQ71hAreNQP6g==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-linux-arm64-gnu": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-14.1.0.tgz", - "integrity": "sha512-RHo7Tcj+jllXUbK7xk2NyIDod3YcCPDZxj1WLIYxd709BQ7WuRYl3OWUNG+WUfqeQBds6kvZYlc42NJJTNi4tQ==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-linux-arm64-musl": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-14.1.0.tgz", - "integrity": "sha512-v6kP8sHYxjO8RwHmWMJSq7VZP2nYCkRVQ0qolh2l6xroe9QjbgV8siTbduED4u0hlk0+tjS6/Tuy4n5XCp+l6g==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-linux-x64-gnu": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-14.1.0.tgz", - "integrity": "sha512-zJ2pnoFYB1F4vmEVlb/eSe+VH679zT1VdXlZKX+pE66grOgjmKJHKacf82g/sWE4MQ4Rk2FMBCRnX+l6/TVYzQ==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-linux-x64-musl": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-14.1.0.tgz", - "integrity": "sha512-rbaIYFt2X9YZBSbH/CwGAjbBG2/MrACCVu2X0+kSykHzHnYH5FjHxwXLkcoJ10cX0aWCEynpu+rP76x0914atg==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-win32-arm64-msvc": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-14.1.0.tgz", - "integrity": "sha512-o1N5TsYc8f/HpGt39OUQpQ9AKIGApd3QLueu7hXk//2xq5Z9OxmV6sQfNp8C7qYmiOlHYODOGqNNa0e9jvchGQ==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-win32-ia32-msvc": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.1.0.tgz", - "integrity": "sha512-XXIuB1DBRCFwNO6EEzCTMHT5pauwaSj4SWs7CYnME57eaReAKBXCnkUE80p/pAZcewm7hs+vGvNqDPacEXHVkw==", - "cpu": [ - "ia32" - ], - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@next/swc-win32-x64-msvc": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-14.1.0.tgz", - "integrity": "sha512-9WEbVRRAqJ3YFVqEZIxUqkiO8l1nool1LmNxygr5HWF8AcSYsEpneUDhmjUVJEzO2A04+oPtZdombzzPPkTtgg==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@swc/helpers": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.2.tgz", - "integrity": "sha512-E4KcWTpoLHqwPHLxidpOqQbcrZVgi0rsmmZXUle1jXmJfuIf/UWpczUJ7MZZ5tlxytgJXyp0w4PGkkeLiuIdZw==", - "license": "Apache-2.0", - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@types/node": { - "version": "20.19.37", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.37.tgz", - "integrity": "sha512-8kzdPJ3FsNsVIurqBs7oodNnCEVbni9yUEkaHbgptDACOPW04jimGagZ51E6+lXUwJjgnBw+hyko/lkFWCldqw==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~6.21.0" - } - }, - "node_modules/@types/prop-types": { - "version": "15.7.15", - "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", - "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/react": { - "version": "18.3.28", - "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz", - "integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/prop-types": "*", - "csstype": "^3.2.2" - } - }, - "node_modules/@types/react-dom": { - "version": "18.3.7", - "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz", - "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "@types/react": "^18.0.0" - } - }, - "node_modules/any-promise": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", - "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", - "dev": true, - "license": "MIT" - }, - "node_modules/anymatch": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "dev": true, - "license": "ISC", - "dependencies": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/arg": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", - "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", - "dev": true, - "license": "MIT" - }, - "node_modules/autoprefixer": { - "version": "10.4.27", - "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.27.tgz", - "integrity": "sha512-NP9APE+tO+LuJGn7/9+cohklunJsXWiaWEfV3si4Gi/XHDwVNgkwr1J3RQYFIvPy76GmJ9/bW8vyoU1LcxwKHA==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/autoprefixer" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "browserslist": "^4.28.1", - "caniuse-lite": "^1.0.30001774", - "fraction.js": "^5.3.4", - "picocolors": "^1.1.1", - "postcss-value-parser": "^4.2.0" - }, - "bin": { - "autoprefixer": "bin/autoprefixer" - }, - "engines": { - "node": "^10 || ^12 || >=14" - }, - "peerDependencies": { - "postcss": "^8.1.0" - } - }, - "node_modules/baseline-browser-mapping": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.0.tgz", - "integrity": "sha512-lIyg0szRfYbiy67j9KN8IyeD7q7hcmqnJ1ddWmNt19ItGpNN64mnllmxUNFIOdOm6by97jlL6wfpTTJrmnjWAA==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "baseline-browser-mapping": "dist/cli.cjs" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/binary-extensions": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", - "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/braces": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", - "dev": true, - "license": "MIT", - "dependencies": { - "fill-range": "^7.1.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/browserslist": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz", - "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "baseline-browser-mapping": "^2.9.0", - "caniuse-lite": "^1.0.30001759", - "electron-to-chromium": "^1.5.263", - "node-releases": "^2.0.27", - "update-browserslist-db": "^1.2.0" - }, - "bin": { - "browserslist": "cli.js" - }, - "engines": { - "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - } - }, - "node_modules/busboy": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", - "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", - "dependencies": { - "streamsearch": "^1.1.0" - }, - "engines": { - "node": ">=10.16.0" - } - }, - "node_modules/camelcase-css": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz", - "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/caniuse-lite": { - "version": "1.0.30001777", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001777.tgz", - "integrity": "sha512-tmN+fJxroPndC74efCdp12j+0rk0RHwV5Jwa1zWaFVyw2ZxAuPeG8ZgWC3Wz7uSjT3qMRQ5XHZ4COgQmsCMJAQ==", - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/caniuse-lite" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "CC-BY-4.0" - }, - "node_modules/chokidar": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", - "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", - "dev": true, - "license": "MIT", - "dependencies": { - "anymatch": "~3.1.2", - "braces": "~3.0.2", - "glob-parent": "~5.1.2", - "is-binary-path": "~2.1.0", - "is-glob": "~4.0.1", - "normalize-path": "~3.0.0", - "readdirp": "~3.6.0" - }, - "engines": { - "node": ">= 8.10.0" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - }, - "optionalDependencies": { - "fsevents": "~2.3.2" - } - }, - "node_modules/chokidar/node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/client-only": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz", - "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==", - "license": "MIT" - }, - "node_modules/clsx": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", - "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/commander": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", - "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/cssesc": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", - "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", - "dev": true, - "license": "MIT", - "bin": { - "cssesc": "bin/cssesc" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/csstype": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", - "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/didyoumean": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", - "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", - "dev": true, - "license": "Apache-2.0" - }, - "node_modules/dlv": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", - "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", - "dev": true, - "license": "MIT" - }, - "node_modules/electron-to-chromium": { - "version": "1.5.307", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.307.tgz", - "integrity": "sha512-5z3uFKBWjiNR44nFcYdkcXjKMbg5KXNdciu7mhTPo9tB7NbqSNP2sSnGR+fqknZSCwKkBN+oxiiajWs4dT6ORg==", - "dev": true, - "license": "ISC" - }, - "node_modules/escalade": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/fast-glob": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", - "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.8" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/fast-glob/node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/fastq": { - "version": "1.20.1", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", - "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", - "dev": true, - "license": "ISC", - "dependencies": { - "reusify": "^1.0.4" - } - }, - "node_modules/fill-range": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", - "dev": true, - "license": "MIT", - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/fraction.js": { - "version": "5.3.4", - "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz", - "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": "*" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/rawify" - } - }, - "node_modules/framer-motion": { - "version": "10.18.0", - "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-10.18.0.tgz", - "integrity": "sha512-oGlDh1Q1XqYPksuTD/usb0I70hq95OUzmL9+6Zd+Hs4XV0oaISBa/UUMSjYiq6m8EUF32132mOJ8xVZS+I0S6w==", - "license": "MIT", - "dependencies": { - "tslib": "^2.4.0" - }, - "optionalDependencies": { - "@emotion/is-prop-valid": "^0.8.2" - }, - "peerDependencies": { - "react": "^18.0.0", - "react-dom": "^18.0.0" - }, - "peerDependenciesMeta": { - "react": { - "optional": true - }, - "react-dom": { - "optional": true - } - } - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/glob-parent": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "license": "ISC" - }, - "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/is-binary-path": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", - "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", - "dev": true, - "license": "MIT", - "dependencies": { - "binary-extensions": "^2.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/is-core-module": { - "version": "2.16.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", - "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", - "dev": true, - "license": "MIT", - "dependencies": { - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/jiti": { - "version": "1.21.7", - "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz", - "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==", - "dev": true, - "license": "MIT", - "bin": { - "jiti": "bin/jiti.js" - } - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "license": "MIT" - }, - "node_modules/lilconfig": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", - "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/antonk52" - } - }, - "node_modules/lines-and-columns": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true, - "license": "MIT" - }, - "node_modules/loose-envify": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", - "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", - "license": "MIT", - "dependencies": { - "js-tokens": "^3.0.0 || ^4.0.0" - }, - "bin": { - "loose-envify": "cli.js" - } - }, - "node_modules/lucide-react": { - "version": "0.303.0", - "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.303.0.tgz", - "integrity": "sha512-B0B9T3dLEFBYPCUlnUS1mvAhW1craSbF9HO+JfBjAtpFUJ7gMIqmEwNSclikY3RiN2OnCkj/V1ReAQpaHae8Bg==", - "license": "ISC", - "peerDependencies": { - "react": "^16.5.1 || ^17.0.0 || ^18.0.0" - } - }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/mz": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", - "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "any-promise": "^1.0.0", - "object-assign": "^4.0.1", - "thenify-all": "^1.0.0" - } - }, - "node_modules/nanoid": { - "version": "3.3.11", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", - "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/next": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/next/-/next-14.1.0.tgz", - "integrity": "sha512-wlzrsbfeSU48YQBjZhDzOwhWhGsy+uQycR8bHAOt1LY1bn3zZEcDyHQOEoN3aWzQ8LHCAJ1nqrWCc9XF2+O45Q==", - "deprecated": "This version has a security vulnerability. Please upgrade to a patched version. See https://nextjs.org/blog/security-update-2025-12-11 for more details.", - "license": "MIT", - "dependencies": { - "@next/env": "14.1.0", - "@swc/helpers": "0.5.2", - "busboy": "1.6.0", - "caniuse-lite": "^1.0.30001579", - "graceful-fs": "^4.2.11", - "postcss": "8.4.31", - "styled-jsx": "5.1.1" - }, - "bin": { - "next": "dist/bin/next" - }, - "engines": { - "node": ">=18.17.0" - }, - "optionalDependencies": { - "@next/swc-darwin-arm64": "14.1.0", - "@next/swc-darwin-x64": "14.1.0", - "@next/swc-linux-arm64-gnu": "14.1.0", - "@next/swc-linux-arm64-musl": "14.1.0", - "@next/swc-linux-x64-gnu": "14.1.0", - "@next/swc-linux-x64-musl": "14.1.0", - "@next/swc-win32-arm64-msvc": "14.1.0", - "@next/swc-win32-ia32-msvc": "14.1.0", - "@next/swc-win32-x64-msvc": "14.1.0" - }, - "peerDependencies": { - "@opentelemetry/api": "^1.1.0", - "react": "^18.2.0", - "react-dom": "^18.2.0", - "sass": "^1.3.0" - }, - "peerDependenciesMeta": { - "@opentelemetry/api": { - "optional": true - }, - "sass": { - "optional": true - } - } - }, - "node_modules/next/node_modules/postcss": { - "version": "8.4.31", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz", - "integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==", - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.6", - "picocolors": "^1.0.0", - "source-map-js": "^1.0.2" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/node-releases": { - "version": "2.0.36", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.36.tgz", - "integrity": "sha512-TdC8FSgHz8Mwtw9g5L4gR/Sh9XhSP/0DEkQxfEFXOpiul5IiHgHan2VhYYb6agDSfp4KuvltmGApc8HMgUrIkA==", - "dev": true, - "license": "MIT" - }, - "node_modules/normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/object-hash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", - "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true, - "license": "MIT" - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/pify": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", - "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/pirates": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", - "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/postcss": { - "version": "8.5.8", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", - "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.11", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/postcss-import": { - "version": "15.1.0", - "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz", - "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==", - "dev": true, - "license": "MIT", - "dependencies": { - "postcss-value-parser": "^4.0.0", - "read-cache": "^1.0.0", - "resolve": "^1.1.7" - }, - "engines": { - "node": ">=14.0.0" - }, - "peerDependencies": { - "postcss": "^8.0.0" - } - }, - "node_modules/postcss-js": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.1.0.tgz", - "integrity": "sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "camelcase-css": "^2.0.1" - }, - "engines": { - "node": "^12 || ^14 || >= 16" - }, - "peerDependencies": { - "postcss": "^8.4.21" - } - }, - "node_modules/postcss-load-config": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz", - "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "lilconfig": "^3.1.1" - }, - "engines": { - "node": ">= 18" - }, - "peerDependencies": { - "jiti": ">=1.21.0", - "postcss": ">=8.0.9", - "tsx": "^4.8.1", - "yaml": "^2.4.2" - }, - "peerDependenciesMeta": { - "jiti": { - "optional": true - }, - "postcss": { - "optional": true - }, - "tsx": { - "optional": true - }, - "yaml": { - "optional": true - } - } - }, - "node_modules/postcss-nested": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz", - "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "postcss-selector-parser": "^6.1.1" - }, - "engines": { - "node": ">=12.0" - }, - "peerDependencies": { - "postcss": "^8.2.14" - } - }, - "node_modules/postcss-selector-parser": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", - "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==", - "dev": true, - "license": "MIT", - "dependencies": { - "cssesc": "^3.0.0", - "util-deprecate": "^1.0.2" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/postcss-value-parser": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", - "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/qrcode.react": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-3.2.0.tgz", - "integrity": "sha512-YietHHltOHA4+l5na1srdaMx4sVSOjV9tamHs+mwiLWAMr6QVACRUw1Neax5CptFILcNoITctJY0Ipyn5enQ8g==", - "license": "ISC", - "peerDependencies": { - "react": "^16.8.0 || ^17.0.0 || ^18.0.0" - } - }, - "node_modules/queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/react": { - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", - "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", - "license": "MIT", - "dependencies": { - "loose-envify": "^1.1.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/react-dom": { - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", - "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", - "license": "MIT", - "dependencies": { - "loose-envify": "^1.1.0", - "scheduler": "^0.23.2" - }, - "peerDependencies": { - "react": "^18.3.1" - } - }, - "node_modules/read-cache": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", - "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==", - "dev": true, - "license": "MIT", - "dependencies": { - "pify": "^2.3.0" - } - }, - "node_modules/readdirp": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", - "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", - "dev": true, - "license": "MIT", - "dependencies": { - "picomatch": "^2.2.1" - }, - "engines": { - "node": ">=8.10.0" - } - }, - "node_modules/resolve": { - "version": "1.22.11", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", - "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-core-module": "^2.16.1", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/reusify": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", - "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", - "dev": true, - "license": "MIT", - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" - } - }, - "node_modules/run-parallel": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "queue-microtask": "^1.2.2" - } - }, - "node_modules/scheduler": { - "version": "0.23.2", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", - "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", - "license": "MIT", - "dependencies": { - "loose-envify": "^1.1.0" - } - }, - "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/streamsearch": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", - "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/styled-jsx": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.1.tgz", - "integrity": "sha512-pW7uC1l4mBZ8ugbiZrcIsiIvVx1UmTfw7UkC3Um2tmfUq9Bhk8IiyEIPl6F8agHgjzku6j0xQEZbfA5uSgSaCw==", - "license": "MIT", - "dependencies": { - "client-only": "0.0.1" - }, - "engines": { - "node": ">= 12.0.0" - }, - "peerDependencies": { - "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0" - }, - "peerDependenciesMeta": { - "@babel/core": { - "optional": true - }, - "babel-plugin-macros": { - "optional": true - } - } - }, - "node_modules/sucrase": { - "version": "3.35.1", - "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", - "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.2", - "commander": "^4.0.0", - "lines-and-columns": "^1.1.6", - "mz": "^2.7.0", - "pirates": "^4.0.1", - "tinyglobby": "^0.2.11", - "ts-interface-checker": "^0.1.9" - }, - "bin": { - "sucrase": "bin/sucrase", - "sucrase-node": "bin/sucrase-node" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/tailwindcss": { - "version": "3.4.19", - "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.19.tgz", - "integrity": "sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@alloc/quick-lru": "^5.2.0", - "arg": "^5.0.2", - "chokidar": "^3.6.0", - "didyoumean": "^1.2.2", - "dlv": "^1.1.3", - "fast-glob": "^3.3.2", - "glob-parent": "^6.0.2", - "is-glob": "^4.0.3", - "jiti": "^1.21.7", - "lilconfig": "^3.1.3", - "micromatch": "^4.0.8", - "normalize-path": "^3.0.0", - "object-hash": "^3.0.0", - "picocolors": "^1.1.1", - "postcss": "^8.4.47", - "postcss-import": "^15.1.0", - "postcss-js": "^4.0.1", - "postcss-load-config": "^4.0.2 || ^5.0 || ^6.0", - "postcss-nested": "^6.2.0", - "postcss-selector-parser": "^6.1.2", - "resolve": "^1.22.8", - "sucrase": "^3.35.0" - }, - "bin": { - "tailwind": "lib/cli.js", - "tailwindcss": "lib/cli.js" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/thenify": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", - "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "any-promise": "^1.0.0" - } - }, - "node_modules/thenify-all": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", - "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", - "dev": true, - "license": "MIT", - "dependencies": { - "thenify": ">= 3.1.0 < 4" - }, - "engines": { - "node": ">=0.8" - } - }, - "node_modules/tinyglobby": { - "version": "0.2.15", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", - "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "fdir": "^6.5.0", - "picomatch": "^4.0.3" - }, - "engines": { - "node": ">=12.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/SuperchupuDev" - } - }, - "node_modules/tinyglobby/node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/tinyglobby/node_modules/picomatch": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", - "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/ts-interface-checker": { - "version": "0.1.13", - "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", - "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", - "dev": true, - "license": "Apache-2.0" - }, - "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "license": "0BSD" - }, - "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/update-browserslist-db": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", - "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "escalade": "^3.2.0", - "picocolors": "^1.1.1" - }, - "bin": { - "update-browserslist-db": "cli.js" - }, - "peerDependencies": { - "browserslist": ">= 4.21.0" - } - }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "dev": true, - "license": "MIT" - } - } -} diff --git a/legacy/taproot-assets-era/frontend/package.json b/legacy/taproot-assets-era/frontend/package.json deleted file mode 100644 index e04c7d6..0000000 --- a/legacy/taproot-assets-era/frontend/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "@runebolt/frontend", - "version": "0.1.0", - "private": true, - "scripts": { - "dev": "next dev --port 3000", - "build": "next build", - "start": "next start" - }, - "dependencies": { - "clsx": "^2.1.0", - "framer-motion": "^10.18.0", - "lucide-react": "^0.303.0", - "next": "14.1.0", - "qrcode.react": "^3.2.0", - "react": "^18.2.0", - "react-dom": "^18.2.0" - }, - "devDependencies": { - "@types/node": "^20.10.0", - "@types/react": "^18.2.45", - "@types/react-dom": "^18.2.18", - "autoprefixer": "^10.4.16", - "postcss": "^8.4.32", - "tailwindcss": "^3.4.0", - "typescript": "^5.3.3" - } -} diff --git a/legacy/taproot-assets-era/frontend/postcss.config.js b/legacy/taproot-assets-era/frontend/postcss.config.js deleted file mode 100644 index 12a703d..0000000 --- a/legacy/taproot-assets-era/frontend/postcss.config.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = { - plugins: { - tailwindcss: {}, - autoprefixer: {}, - }, -}; diff --git a/legacy/taproot-assets-era/frontend/tailwind.config.ts b/legacy/taproot-assets-era/frontend/tailwind.config.ts deleted file mode 100644 index 70b8441..0000000 --- a/legacy/taproot-assets-era/frontend/tailwind.config.ts +++ /dev/null @@ -1,75 +0,0 @@ -import type { Config } from 'tailwindcss'; - -const config: Config = { - content: [ - './app/**/*.{js,ts,jsx,tsx,mdx}', - './components/**/*.{js,ts,jsx,tsx,mdx}', - ], - theme: { - extend: { - colors: { - bitcoin: '#F7931A', - cyan: '#00CFFF', - dark: { - 900: '#0a0a0a', - 800: '#111111', - 700: '#1a1a2e', - 600: '#2a2a3e', - }, - }, - fontFamily: { - mono: ['ui-monospace', 'SFMono-Regular', 'Menlo', 'Monaco', 'monospace'], - sans: ['-apple-system', 'BlinkMacSystemFont', 'Segoe UI', 'Roboto', 'sans-serif'], - }, - animation: { - 'pulse-glow': 'pulse-glow 2s ease-in-out infinite', - 'float': 'float 3s ease-in-out infinite', - 'wiggle': 'wiggle 0.5s ease-in-out infinite', - 'bounce-slow': 'bounce-slow 2s ease-in-out infinite', - 'spin-slow': 'spin 3s linear infinite', - 'tail-wag': 'tail-wag 0.3s ease-in-out infinite', - 'happy-dance': 'happy-dance 0.6s ease-in-out infinite', - 'slide-up': 'slide-up 0.5s ease-out', - 'glow-pulse': 'glow-pulse 2s ease-in-out infinite', - }, - keyframes: { - 'pulse-glow': { - '0%, 100%': { boxShadow: '0 0 20px rgba(247, 147, 26, 0.3)' }, - '50%': { boxShadow: '0 0 40px rgba(247, 147, 26, 0.6)' }, - }, - 'float': { - '0%, 100%': { transform: 'translateY(0px)' }, - '50%': { transform: 'translateY(-10px)' }, - }, - 'wiggle': { - '0%, 100%': { transform: 'rotate(-3deg)' }, - '50%': { transform: 'rotate(3deg)' }, - }, - 'bounce-slow': { - '0%, 100%': { transform: 'translateY(0)' }, - '50%': { transform: 'translateY(-8px)' }, - }, - 'tail-wag': { - '0%, 100%': { transform: 'rotate(-10deg)' }, - '50%': { transform: 'rotate(10deg)' }, - }, - 'happy-dance': { - '0%, 100%': { transform: 'translateY(0) rotate(0deg)' }, - '25%': { transform: 'translateY(-8px) rotate(-5deg)' }, - '75%': { transform: 'translateY(-8px) rotate(5deg)' }, - }, - 'slide-up': { - '0%': { transform: 'translateY(20px)', opacity: '0' }, - '100%': { transform: 'translateY(0)', opacity: '1' }, - }, - 'glow-pulse': { - '0%, 100%': { boxShadow: '0 0 20px rgba(0, 207, 255, 0.2), 0 0 40px rgba(247, 147, 26, 0.1)' }, - '50%': { boxShadow: '0 0 30px rgba(0, 207, 255, 0.4), 0 0 60px rgba(247, 147, 26, 0.2)' }, - }, - }, - }, - }, - plugins: [], -}; - -export default config; diff --git a/legacy/taproot-assets-era/frontend/tsconfig.json b/legacy/taproot-assets-era/frontend/tsconfig.json deleted file mode 100644 index c714696..0000000 --- a/legacy/taproot-assets-era/frontend/tsconfig.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "compilerOptions": { - "target": "es5", - "lib": ["dom", "dom.iterable", "esnext"], - "allowJs": true, - "skipLibCheck": true, - "strict": true, - "noEmit": true, - "esModuleInterop": true, - "module": "esnext", - "moduleResolution": "bundler", - "resolveJsonModule": true, - "isolatedModules": true, - "jsx": "preserve", - "incremental": true, - "plugins": [ - { - "name": "next" - } - ], - "paths": { - "@/*": ["./*"] - } - }, - "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], - "exclude": ["node_modules"] -} diff --git a/legacy/taproot-assets-era/infrastructure/README.md b/legacy/taproot-assets-era/infrastructure/README.md deleted file mode 100644 index 52feeac..0000000 --- a/legacy/taproot-assets-era/infrastructure/README.md +++ /dev/null @@ -1,72 +0,0 @@ -# RuneBolt Infrastructure - -Production-grade infrastructure for RuneBolt Bitcoin L2 payment hub. - -## Quick Start - -### Prerequisites -- Docker & Docker Swarm -- Terraform >= 1.5 -- doctl (DigitalOcean CLI) -- kubectl (optional, for K8s migration path) - -### Deploy Infrastructure - -```bash -cd terraform -terraform init -terraform plan -var="do_token=$DO_TOKEN" -terraform apply -``` - -### Deploy Application - -```bash -# Initialize Swarm (on manager) -docker swarm init - -# Deploy stack -docker stack deploy -c ../docker-compose.yml runebolt -``` - -## Directory Structure - -``` -infrastructure/ -├── terraform/ # IaC for DigitalOcean -├── scripts/ # Automation scripts -│ └── backup.sh # Backup automation -├── runbooks/ # Operational procedures -│ ├── 01-service-restart.md -│ ├── 02-database-restore.md -│ ├── 03-scale-infrastructure.md -│ ├── 04-vault-unseal.md -│ └── 05-incident-response.md -└── configs/ # Service configurations - └── haproxy.cfg -``` - -## Monitoring - -- Grafana: https://grafana.runebolt.io -- Prometheus: http://localhost:9090 -- AlertManager: http://localhost:9093 - -## Backups - -Automated backups run every 6 hours. To restore: - -```bash -./scripts/backup.sh restore 20240314_120000 -``` - -## Security - -- All secrets stored in Vault -- mTLS between services -- Network segmentation via VPC -- WAF + DDoS protection (CloudFlare) - -## Support - -For issues, refer to the runbooks or page the on-call engineer. diff --git a/legacy/taproot-assets-era/infrastructure/configs/haproxy.cfg b/legacy/taproot-assets-era/infrastructure/configs/haproxy.cfg deleted file mode 100644 index 909a447..0000000 --- a/legacy/taproot-assets-era/infrastructure/configs/haproxy.cfg +++ /dev/null @@ -1,78 +0,0 @@ -global - maxconn 4096 - log /dev/log local0 - log /dev/log local1 notice - chroot /var/lib/haproxy - stats socket /run/haproxy/admin.sock mode 660 level admin - stats timeout 30s - user haproxy - group haproxy - daemon - -defaults - mode http - log global - option httplog - option dontlognull - option log-health-checks - timeout connect 5000 - timeout client 50000 - timeout server 50000 - errorfile 400 /etc/haproxy/errors/400.http - errorfile 503 /etc/haproxy/errors/503.http - -# Stats page -listen stats - bind *:8404 - stats enable - stats uri /stats - stats refresh 10s - stats admin if TRUE - -# Frontend (Next.js) -frontend frontend_http - bind *:80 - redirect scheme https if !{ ssl_fc } - -frontend frontend_https - bind *:443 ssl crt /run/secrets/ssl_certificate alpn h2,http/1.1 - default_backend frontend_nodes - - # Security headers - http-response set-header X-Frame-Options DENY - http-response set-header X-Content-Type-Options nosniff - http-response set-header X-XSS-Protection "1; mode=block" - http-response set-header Strict-Transport-Security "max-age=31536000; includeSubDomains" - -backend frontend_nodes - balance roundrobin - option httpchk GET /health - server frontend1 frontend:3000 check inter 5s fall 3 rise 2 - server frontend2 frontend:3000 check inter 5s fall 3 rise 2 - server frontend3 frontend:3000 check inter 5s fall 3 rise 2 - -# Backend API -frontend api_https - bind *:443 ssl crt /run/secrets/ssl_certificate alpn h2,http/1.1 - acl is_api path_beg /api - use_backend api_nodes if is_api - -backend api_nodes - balance roundrobin - option httpchk GET /health - server backend1 backend-api:3001 check inter 5s fall 3 rise 2 - server backend2 backend-api:3001 check inter 5s fall 3 rise 2 - server backend3 backend-api:3001 check inter 5s fall 3 rise 2 - -# WebSocket -frontend ws_https - bind *:443 ssl crt /run/secrets/ssl_certificate alpn h2,http/1.1 - acl is_ws path_beg /ws - use_backend ws_nodes if is_ws - -backend ws_nodes - balance source - option httpchk GET /health - server ws1 backend-api:3001 check inter 5s fall 3 rise 2 - server ws2 backend-api:3001 check inter 5s fall 3 rise 2 - server ws3 backend-api:3001 check inter 5s fall 3 rise 2 diff --git a/legacy/taproot-assets-era/infrastructure/haproxy/haproxy.cfg b/legacy/taproot-assets-era/infrastructure/haproxy/haproxy.cfg deleted file mode 100644 index a74bc37..0000000 --- a/legacy/taproot-assets-era/infrastructure/haproxy/haproxy.cfg +++ /dev/null @@ -1,138 +0,0 @@ -# HAProxy Configuration for RuneBolt -# Load balancing and SSL termination - -global - log stdout local0 - log stdout local1 notice - chroot /var/lib/haproxy - stats socket /run/haproxy/admin.sock mode 660 level admin - stats timeout 30s - user haproxy - group haproxy - daemon - - # Default SSL material locations - ca-base /etc/ssl/certs - crt-base /etc/ssl/private - - # SSL configuration - ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384 - ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256 - ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets - -defaults - mode http - log global - option httplog - option dontlognull - option log-health-checks - option forwardfor except 127.0.0.0/8 - option redispatch - retries 3 - timeout http-request 10s - timeout queue 1m - timeout connect 10s - timeout client 1m - timeout server 1m - timeout http-keep-alive 10s - timeout check 10s - maxconn 3000 - errorfile 400 /usr/local/etc/haproxy/errors/400.http - errorfile 403 /usr/local/etc/haproxy/errors/403.http - errorfile 408 /usr/local/etc/haproxy/errors/408.http - errorfile 500 /usr/local/etc/haproxy/errors/500.http - errorfile 502 /usr/local/etc/haproxy/errors/502.http - errorfile 503 /usr/local/etc/haproxy/errors/503.http - errorfile 504 /usr/local/etc/haproxy/errors/504.http - -# Statistics page -listen stats - bind *:8404 - stats enable - stats uri /stats - stats refresh 10s - stats admin if TRUE - -# Frontend: HTTP to HTTPS redirect -frontend http - bind *:80 - mode http - - # ACME challenge for Let's Encrypt - acl url_acme_http01 path_beg /.well-known/acme-challenge/ - use_backend acme_challenge if url_acme_http01 - - # Redirect to HTTPS - redirect scheme https code 301 if !url_acme_http01 - -# Frontend: HTTPS -frontend https - bind *:443 ssl crt /etc/ssl/certs/runebolt.pem alpn h2,http/1.1 - - # Security headers - http-response set-header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" - http-response set-header X-Frame-Options "SAMEORIGIN" - http-response set-header X-Content-Type-Options "nosniff" - http-response set-header X-XSS-Protection "1; mode=block" - http-response set-header Referrer-Policy "strict-origin-when-cross-origin" - - # Rate limiting (100 requests per 10 seconds per IP) - stick-table type ip size 100k expire 30s store http_req_rate(10s) - http-request track-sc0 src - http-request deny deny_status 429 if { sc_http_req_rate(0) gt 100 } - - # ACLs - acl is_api path_beg /api - acl is_websocket hdr(Upgrade) -i websocket - acl is_grafana path_beg /grafana - acl is_prometheus path_beg /prometheus - - # Backends - use_backend websocket_backend if is_websocket - use_backend api_backend if is_api - use_backend grafana_backend if is_grafana - use_backend prometheus_backend if is_prometheus - default_backend frontend_backend - -# Backend: Frontend (Next.js) -backend frontend_backend - balance roundrobin - option httpchk GET /health - http-check expect status 200 - server frontend1 frontend:3000 check inter 5s fall 3 rise 2 - # Add more servers for scaling: - # server frontend2 frontend2:3000 check inter 5s fall 3 rise 2 - -# Backend: API -backend api_backend - balance roundrobin - option httpchk GET /health - http-check expect status 200 - server api1 backend-api:3001 check inter 5s fall 3 rise 2 - # server api2 backend-api-2:3001 check inter 5s fall 3 rise 2 - -# Backend: WebSocket -backend websocket_backend - balance source - option httpchk GET /health - http-check expect status 200 - server ws1 backend-api:3001 check inter 5s fall 3 rise 2 - -# Backend: Grafana -backend grafana_backend - balance roundrobin - option httpchk GET /api/health - http-check expect status 200 - server grafana1 grafana:3000 check inter 5s fall 3 rise 2 - -# Backend: Prometheus (restricted access recommended) -backend prometheus_backend - balance roundrobin - option httpchk GET /-/healthy - http-check expect status 200 - server prometheus1 prometheus:9090 check inter 5s fall 3 rise 2 - # Add IP whitelist ACL in production - -# Backend: ACME Challenge -backend acme_challenge - server acme 127.0.0.1:63443 diff --git a/legacy/taproot-assets-era/infrastructure/k8s/backend-deployment.yaml b/legacy/taproot-assets-era/infrastructure/k8s/backend-deployment.yaml deleted file mode 100644 index 3797d77..0000000 --- a/legacy/taproot-assets-era/infrastructure/k8s/backend-deployment.yaml +++ /dev/null @@ -1,70 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: runebolt-backend - namespace: runebolt - labels: - app: runebolt-backend -spec: - replicas: 3 - strategy: - type: RollingUpdate - rollingUpdate: - maxSurge: 1 - maxUnavailable: 0 - selector: - matchLabels: - app: runebolt-backend - template: - metadata: - labels: - app: runebolt-backend - spec: - containers: - - name: backend - image: ghcr.io/bitmap-asset/runebolt-backend:latest - ports: - - containerPort: 3001 - name: http - env: - - name: NODE_ENV - value: "production" - - name: PORT - value: "3001" - resources: - requests: - memory: "512Mi" - cpu: "500m" - limits: - memory: "1Gi" - cpu: "1000m" - livenessProbe: - httpGet: - path: /health - port: 3001 - initialDelaySeconds: 30 - periodSeconds: 10 - readinessProbe: - httpGet: - path: /health - port: 3001 - initialDelaySeconds: 5 - periodSeconds: 5 - securityContext: - allowPrivilegeEscalation: false - readOnlyRootFilesystem: true - runAsNonRoot: true - runAsUser: 1000 ---- -apiVersion: v1 -kind: Service -metadata: - name: runebolt-backend - namespace: runebolt -spec: - selector: - app: runebolt-backend - ports: - - port: 3001 - targetPort: 3001 - type: ClusterIP diff --git a/legacy/taproot-assets-era/infrastructure/k8s/ingress.yaml b/legacy/taproot-assets-era/infrastructure/k8s/ingress.yaml deleted file mode 100644 index a8762db..0000000 --- a/legacy/taproot-assets-era/infrastructure/k8s/ingress.yaml +++ /dev/null @@ -1,36 +0,0 @@ -apiVersion: networking.k8s.io/v1 -kind: Ingress -metadata: - name: runebolt-ingress - namespace: runebolt - annotations: - cert-manager.io/cluster-issuer: "letsencrypt-prod" - nginx.ingress.kubernetes.io/ssl-redirect: "true" - nginx.ingress.kubernetes.io/rate-limit: "100" -spec: - tls: - - hosts: - - runebolt.io - - api.runebolt.io - secretName: runebolt-tls - rules: - - host: runebolt.io - http: - paths: - - path: / - pathType: Prefix - backend: - service: - name: runebolt-frontend - port: - number: 3000 - - host: api.runebolt.io - http: - paths: - - path: / - pathType: Prefix - backend: - service: - name: runebolt-backend - port: - number: 3001 diff --git a/legacy/taproot-assets-era/infrastructure/k8s/namespace.yaml b/legacy/taproot-assets-era/infrastructure/k8s/namespace.yaml deleted file mode 100644 index a252950..0000000 --- a/legacy/taproot-assets-era/infrastructure/k8s/namespace.yaml +++ /dev/null @@ -1,20 +0,0 @@ -apiVersion: v1 -kind: Namespace -metadata: - name: runebolt - labels: - name: runebolt - environment: production ---- -apiVersion: v1 -kind: ResourceQuota -metadata: - name: runebolt-quota - namespace: runebolt -spec: - hard: - requests.cpu: "10" - requests.memory: 20Gi - limits.cpu: "20" - limits.memory: 40Gi - pods: "20" diff --git a/legacy/taproot-assets-era/infrastructure/pgbouncer/pgbouncer.ini b/legacy/taproot-assets-era/infrastructure/pgbouncer/pgbouncer.ini deleted file mode 100644 index dc56969..0000000 --- a/legacy/taproot-assets-era/infrastructure/pgbouncer/pgbouncer.ini +++ /dev/null @@ -1,44 +0,0 @@ -# PgBouncer Configuration -# Connection pooling for PostgreSQL - -[databases] -runebolt = host=postgres port=5432 dbname=runebolt - -[pgbouncer] -listen_port = 6432 -listen_addr = 0.0.0.0 -auth_type = md5 -auth_file = /etc/pgbouncer/userlist.txt - -# Pool settings -pool_mode = transaction -max_client_conn = 1000 -default_pool_size = 25 -min_pool_size = 5 -reserve_pool_size = 5 -reserve_pool_timeout = 3 - -# Connection limits -max_db_connections = 100 -max_user_connections = 100 - -# Timeouts -server_idle_timeout = 600 -server_lifetime = 3600 -server_connect_timeout = 15 -server_login_retry = 15 -query_timeout = 0 -query_wait_timeout = 120 -client_idle_timeout = 0 -client_login_timeout = 60 -idle_transaction_timeout = 0 - -# Logging -log_connections = 1 -log_disconnections = 1 -log_pooler_errors = 1 -stats_period = 60 - -# Admin console -admin_users = runebolt -stats_users = runebolt diff --git a/legacy/taproot-assets-era/infrastructure/runbooks/01-service-restart.md b/legacy/taproot-assets-era/infrastructure/runbooks/01-service-restart.md deleted file mode 100644 index 7d5ef34..0000000 --- a/legacy/taproot-assets-era/infrastructure/runbooks/01-service-restart.md +++ /dev/null @@ -1,48 +0,0 @@ -# Runbook: Service Restart - -## Overview -Quickly restart services without affecting user transactions. - -## Prerequisites -- Docker Swarm access -- Vault unsealed - -## Rolling Restart (Zero Downtime) - -```bash -# Restart backend API (rolling) -docker service update --force runebolt_backend-api - -# Restart frontend (rolling) -docker service update --force runebolt_frontend - -# Restart workers -docker service update --force runebolt_backend-worker -``` - -## Restart Specific Container - -```bash -# Get container ID -docker ps | grep backend-api - -# Restart specific container -docker restart -``` - -## Verify Health - -```bash -# Check service health -curl http://localhost:3001/health -docker service ps runebolt_backend-api - -# Check logs -docker service logs runebolt_backend-api --tail 100 -``` - -## Rollback if Issues - -```bash -docker service rollback runebolt_backend-api -``` diff --git a/legacy/taproot-assets-era/infrastructure/runbooks/02-database-restore.md b/legacy/taproot-assets-era/infrastructure/runbooks/02-database-restore.md deleted file mode 100644 index df5d9cd..0000000 --- a/legacy/taproot-assets-era/infrastructure/runbooks/02-database-restore.md +++ /dev/null @@ -1,46 +0,0 @@ -# Runbook: Database Restore - -## Overview -Restore PostgreSQL from backup. - -## Prerequisites -- Access to S3 backup bucket -- PostgreSQL primary stopped - -## Full Restore - -```bash -# 1. Stop application writes -docker service scale runebolt_backend-api=0 - -# 2. Stop PostgreSQL -docker stop runebolt_postgres-primary - -# 3. Clear old data -rm -rf /var/lib/postgresql/data/* - -# 4. Download backup -aws s3 cp s3://runebolt-backups/postgresql/runebolt_YYYYMMDD.sql.gz /tmp/ - -# 5. Restore -gunzip < /tmp/runebolt_YYYYMMDD.sql.gz | psql -U runebolt runebolt - -# 6. Start PostgreSQL -docker start runebolt_postgres-primary - -# 7. Verify -curl http://localhost:3001/health - -# 8. Scale back up -docker service scale runebolt_backend-api=3 -``` - -## Point-in-Time Recovery - -```bash -# Restore to specific time (using WAL) -pg_basebackup -D /var/lib/postgresql/data -X fetch - -# Replay WAL to specific point -pg_waldump /var/lib/postgresql/wal/* | head -100 -``` diff --git a/legacy/taproot-assets-era/infrastructure/runbooks/03-scale-infrastructure.md b/legacy/taproot-assets-era/infrastructure/runbooks/03-scale-infrastructure.md deleted file mode 100644 index 4df690f..0000000 --- a/legacy/taproot-assets-era/infrastructure/runbooks/03-scale-infrastructure.md +++ /dev/null @@ -1,27 +0,0 @@ -# Runbook: Scale Infrastructure - -## Scale Application - -```bash -# Scale API horizontally -docker service scale runebolt_backend-api=5 - -# Scale workers -docker service scale runebolt_backend-worker=4 - -# Scale frontend -docker service scale runebolt_frontend=4 -``` - -## Add New Node - -```bash -# On manager -docker swarm join-token worker - -# On new node -docker swarm join --token :2377 - -# Label node -docker node update --label-add role=worker -``` diff --git a/legacy/taproot-assets-era/infrastructure/runbooks/04-vault-unseal.md b/legacy/taproot-assets-era/infrastructure/runbooks/04-vault-unseal.md deleted file mode 100644 index a5e31c1..0000000 --- a/legacy/taproot-assets-era/infrastructure/runbooks/04-vault-unseal.md +++ /dev/null @@ -1,29 +0,0 @@ -# Runbook: Vault Unseal - -## Prerequisites -- 3 unseal keys from secure storage - -## Unseal Process - -```bash -# Check status -docker exec runebolt_vault vault status - -# Unseal (run 3 times with different keys) -docker exec runebolt_vault vault operator unseal -docker exec runebolt_vault vault operator unseal -docker exec runebolt_vault vault operator unseal - -# Verify -vault status -``` - -## If Auto-Unseal Fails - -```bash -# Check logs -docker logs runebolt_vault - -# Check Consul backend -docker exec consul consul members -``` diff --git a/legacy/taproot-assets-era/infrastructure/runbooks/05-incident-response.md b/legacy/taproot-assets-era/infrastructure/runbooks/05-incident-response.md deleted file mode 100644 index 4857740..0000000 --- a/legacy/taproot-assets-era/infrastructure/runbooks/05-incident-response.md +++ /dev/null @@ -1,36 +0,0 @@ -# Runbook: Incident Response - -## Severity Levels - -- **P1 (Critical)**: Complete outage, data loss, security breach -- **P2 (High)**: Major feature degraded -- **P3 (Medium)**: Minor issues -- **P4 (Low)**: Cosmetic issues - -## P1 Response - -1. **Assess (0-5 min)** - - Acknowledge page - - Check status page - - Verify scope - -2. **Communicate (5-10 min)** - - Internal: #incidents channel - - External: Status page update - - Users: Twitter if widespread - -3. **Mitigate (10-30 min)** - - Apply known fixes - - Scale resources - - Enable circuit breakers - - Fallback to DR if needed - -4. **Resolve** - - Root cause analysis - - Post-mortem within 24h - -## Emergency Contacts - -- Primary: +1-XXX-XXX-XXXX -- Secondary: +1-XXX-XXX-XXXX -- Escalation: +1-XXX-XXX-XXXX diff --git a/legacy/taproot-assets-era/infrastructure/scripts/backup.sh b/legacy/taproot-assets-era/infrastructure/scripts/backup.sh deleted file mode 100755 index 1fedd34..0000000 --- a/legacy/taproot-assets-era/infrastructure/scripts/backup.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/bash -# RuneBolt Backup Automation Script -set -euo pipefail - -BACKUP_DIR="/backups/runebolt" -S3_BUCKET="s3://runebolt-backups" -DATE=$(date +%Y%m%d_%H%M%S) - -backup_postgres() { - echo "Backing up PostgreSQL..." - pg_dump -h postgres-primary -U runebolt runebolt | gzip > "$BACKUP_DIR/postgres_$DATE.sql.gz" - aws s3 cp "$BACKUP_DIR/postgres_$DATE.sql.gz" "$S3_BUCKET/postgresql/" -} - -backup_vault() { - echo "Backing up Vault..." - vault operator raft snapshot save "$BACKUP_DIR/vault_$DATE.snap" - aws s3 cp "$BACKUP_DIR/vault_$DATE.snap" "$S3_BUCKET/vault/" -} - -backup_redis() { - echo "Backing up Redis..." - redis-cli BGSAVE - cp /data/redis/dump.rdb "$BACKUP_DIR/redis_$DATE.rdb" - aws s3 cp "$BACKUP_DIR/redis_$DATE.rdb" "$S3_BUCKET/redis/" -} - -main() { - mkdir -p "$BACKUP_DIR" - backup_postgres - backup_vault - backup_redis - echo "Backup complete!" -} - -main "$@" diff --git a/legacy/taproot-assets-era/infrastructure/scripts/deploy.sh b/legacy/taproot-assets-era/infrastructure/scripts/deploy.sh deleted file mode 100755 index 271451d..0000000 --- a/legacy/taproot-assets-era/infrastructure/scripts/deploy.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash -# Deploy script for RuneBolt -set -e - -ENV=${1:-staging} -VERSION=${2:-latest} - -echo "Deploying RuneBolt to $ENV (version: $VERSION)" - -# Update stack -docker stack deploy -c docker-compose.yml runebolt - -# Verify -echo "Verifying deployment..." -sleep 30 -curl -f http://localhost:3001/health || exit 1 - -echo "Deployment complete!" diff --git a/legacy/taproot-assets-era/infrastructure/terraform/main.tf b/legacy/taproot-assets-era/infrastructure/terraform/main.tf deleted file mode 100644 index 906c1c7..0000000 --- a/legacy/taproot-assets-era/infrastructure/terraform/main.tf +++ /dev/null @@ -1,281 +0,0 @@ -# RuneBolt DigitalOcean Infrastructure -# Terraform configuration for production deployment - -terraform { - required_version = ">= 1.5.0" - - backend "s3" { - bucket = "runebolt-terraform-state" - key = "production/terraform.tfstate" - region = "us-east-1" - endpoint = "https://nyc3.digitaloceanspaces.com" - skip_credentials_validation = true - skip_metadata_api_check = true - } - - required_providers { - digitalocean = { - source = "digitalocean/digitalocean" - version = "~> 2.0" - } - } -} - -provider "digitalocean" { - token = var.do_token -} - -# ═══════════════════════════════════════════════════════════════════════════════ -# PROJECT -# ═══════════════════════════════════════════════════════════════════════════════ -resource "digitalocean_project" "runebolt" { - name = "runebolt-production" - description = "RuneBolt Bitcoin L2 Payment Hub" - purpose = "Service or API" - environment = "Production" - resources = [ - digitalocean_droplet.manager.urn, - digitalocean_droplet.worker.urn, - digitalocean_droplet.database.urn, - digitalocean_database_cluster.main.urn, - ] -} - -# ═══════════════════════════════════════════════════════════════════════════════ -# VPC -# ═══════════════════════════════════════════════════════════════════════════════ -resource "digitalocean_vpc" "main" { - name = "runebolt-vpc-nyc1" - region = "nyc1" - ip_range = "10.10.0.0/16" -} - -# ═══════════════════════════════════════════════════════════════════════════════ -# FIREWALL -# ═══════════════════════════════════════════════════════════════════════════════ -resource "digitalocean_firewall" "public" { - name = "runebolt-public" - - droplet_ids = [for droplet in digitalocean_droplet.manager : droplet.id] - - inbound_rule { - protocol = "tcp" - port_range = "22" - source_addresses = var.admin_ips - } - - inbound_rule { - protocol = "tcp" - port_range = "80" - source_addresses = ["0.0.0.0/0", "::/0"] - } - - inbound_rule { - protocol = "tcp" - port_range = "443" - source_addresses = ["0.0.0.0/0", "::/0"] - } - - outbound_rule { - protocol = "tcp" - port_range = "1-65535" - destination_addresses = ["0.0.0.0/0", "::/0"] - } - - outbound_rule { - protocol = "udp" - port_range = "53" - destination_addresses = ["0.0.0.0/0", "::/0"] - } -} - -resource "digitalocean_firewall" "private" { - name = "runebolt-private" - - droplet_ids = concat( - [for droplet in digitalocean_droplet.worker : droplet.id], - [for droplet in digitalocean_droplet.database : droplet.id] - ) - - inbound_rule { - protocol = "tcp" - port_range = "22" - source_addresses = ["10.10.0.0/16"] - } - - inbound_rule { - protocol = "tcp" - port_range = "1-65535" - source_addresses = ["10.10.0.0/16"] - } - - outbound_rule { - protocol = "tcp" - port_range = "1-65535" - destination_addresses = ["0.0.0.0/0", "::/0"] - } -} - -# ═══════════════════════════════════════════════════════════════════════════════ -# MANAGER NODES (Docker Swarm Managers) -# ═══════════════════════════════════════════════════════════════════════════════ -resource "digitalocean_droplet" "manager" { - count = 3 - name = "runebolt-manager-${count.index + 1}" - region = "nyc1" - size = "s-2vcpu-4gb" - image = "ubuntu-22-04-x64" - - vpc_uuid = digitalocean_vpc.main.id - - ssh_keys = [digitalocean_ssh_key.deploy.id] - - tags = ["manager", "runebolt"] - - user_data = <<-EOF - #!/bin/bash - apt-get update - apt-get install -y docker.io docker-compose-plugin - - # Initialize Docker Swarm (only on first manager) - if [ "${count.index}" = "0" ]; then - docker swarm init --advertise-addr $(hostname -I | awk '{print $1}') - fi - - # Install monitoring agent - curl -sSL https://repos.insights.digitalocean.com/install.sh | sudo bash - EOF -} - -# ═══════════════════════════════════════════════════════════════════════════════ -# WORKER NODES (Application containers) -# ═══════════════════════════════════════════════════════════════════════════════ -resource "digitalocean_droplet" "worker" { - count = 3 - name = "runebolt-worker-${count.index + 1}" - region = "nyc1" - size = "s-4vcpu-8gb" - image = "ubuntu-22-04-x64" - - vpc_uuid = digitalocean_vpc.main.id - - ssh_keys = [digitalocean_ssh_key.deploy.id] - - tags = ["worker", "runebolt"] - - user_data = <<-EOF - #!/bin/bash - apt-get update - apt-get install -y docker.io docker-compose-plugin - - # Install monitoring agent - curl -sSL https://repos.insights.digitalocean.com/install.sh | sudo bash - EOF -} - -# ═══════════════════════════════════════════════════════════════════════════════ -# DATABASE NODES (PostgreSQL + Vault) -# ═══════════════════════════════════════════════════════════════════════════════ -resource "digitalocean_droplet" "database" { - count = 3 - name = "runebolt-db-${count.index + 1}" - region = "nyc1" - size = "s-4vcpu-8gb" - image = "ubuntu-22-04-x64" - - vpc_uuid = digitalocean_vpc.main.id - - ssh_keys = [digitalocean_ssh_key.deploy.id] - - tags = ["database", "runebolt"] - - user_data = <<-EOF - #!/bin/bash - apt-get update - apt-get install -y docker.io - - # Setup for high I/O - echo 'vm.swappiness=10' >> /etc/sysctl.conf - echo 'vm.dirty_ratio=40' >> /etc/sysctl.conf - echo 'vm.dirty_background_ratio=10' >> /etc/sysctl.conf - sysctl -p - - # Install monitoring agent - curl -sSL https://repos.insights.digitalocean.com/install.sh | sudo bash - EOF -} - -# ═══════════════════════════════════════════════════════════════════════════════ -# MANAGED DATABASE (PostgreSQL) -# ═══════════════════════════════════════════════════════════════════════════════ -resource "digitalocean_database_cluster" "main" { - name = "runebolt-postgres" - engine = "pg" - version = "15" - size = "db-s-2vcpu-4gb" - region = "nyc1" - node_count = 2 - - private_network_uuid = digitalocean_vpc.main.id -} - -resource "digitalocean_database_db" "runebolt" { - cluster_id = digitalocean_database_cluster.main.id - name = "runebolt" -} - -resource "digitalocean_database_user" "app" { - cluster_id = digitalocean_database_cluster.main.id - name = "runebolt_app" -} - -# ═══════════════════════════════════════════════════════════════════════════════ -# SPACES (S3-compatible object storage) -# ═══════════════════════════════════════════════════════════════════════════════ -resource "digitalocean_spaces_bucket" "backups" { - name = "runebolt-backups" - region = "nyc3" - acl = "private" -} - -resource "digitalocean_spaces_bucket" "terraform_state" { - name = "runebolt-terraform-state" - region = "nyc3" - acl = "private" -} - -# ═══════════════════════════════════════════════════════════════════════════════ -# LOAD BALANCER -# ═══════════════════════════════════════════════════════════════════════════════ -resource "digitalocean_loadbalancer" "public" { - name = "runebolt-lb" - region = "nyc1" - - forwarding_rule { - entry_port = 80 - entry_protocol = "http" - - target_port = 80 - target_protocol = "http" - } - - forwarding_rule { - entry_port = 443 - entry_protocol = "https" - - target_port = 443 - target_protocol = "https" - - certificate_id = digitalocean_certificate.main.id - } - - healthcheck { - port = 80 - protocol = "http" - path = "/health" - } - - droplet_ids = digitalocean_droplet.manager[*].id -} - -resource \ No newline at end of file diff --git a/legacy/taproot-assets-era/infrastructure/terraform/outputs.tf b/legacy/taproot-assets-era/infrastructure/terraform/outputs.tf deleted file mode 100644 index 797a7bb..0000000 --- a/legacy/taproot-assets-era/infrastructure/terraform/outputs.tf +++ /dev/null @@ -1,15 +0,0 @@ -output "manager_ips" { - description = "Manager node public IPs" - value = digitalocean_droplet.manager[*].ipv4_address -} - -output "database_endpoint" { - description = "PostgreSQL endpoint" - value = digitalocean_database_cluster.main.host - sensitive = true -} - -output "vpc_id" { - description = "VPC ID" - value = digitalocean_vpc.main.id -} diff --git a/legacy/taproot-assets-era/infrastructure/terraform/variables.tf b/legacy/taproot-assets-era/infrastructure/terraform/variables.tf deleted file mode 100644 index b5f3295..0000000 --- a/legacy/taproot-assets-era/infrastructure/terraform/variables.tf +++ /dev/null @@ -1,23 +0,0 @@ -variable "do_token" { - description = "DigitalOcean API token" - type = string - sensitive = true -} - -variable "admin_ips" { - description = "Allowed admin IPs for SSH access" - type = list(string) - default = [] -} - -variable "region" { - description = "DigitalOcean region" - type = string - default = "nyc1" -} - -variable "environment" { - description = "Environment name" - type = string - default = "production" -} diff --git a/legacy/taproot-assets-era/infrastructure/vault/config/vault.hcl b/legacy/taproot-assets-era/infrastructure/vault/config/vault.hcl deleted file mode 100644 index 29360fb..0000000 --- a/legacy/taproot-assets-era/infrastructure/vault/config/vault.hcl +++ /dev/null @@ -1,26 +0,0 @@ -# Vault Configuration for RuneBolt -# Development mode - change for production! - -storage "file" { - path = "/vault/file" -} - -listener "tcp" { - address = "0.0.0.0:8200" - tls_disable = 1 # Enable TLS in production! -} - -api_addr = "http://0.0.0.0:8200" -cluster_addr = "http://0.0.0.0:8201" - -ui = true - -# Enable telemetry for Prometheus -telemetry { - prometheus_retention_time = "30s" - disable_hostname = false -} - -# Default lease settings -default_lease_ttl = "768h" # 32 days -max_lease_ttl = "768h" diff --git a/legacy/taproot-assets-era/migrations/001_postgres_schema.sql b/legacy/taproot-assets-era/migrations/001_postgres_schema.sql deleted file mode 100644 index d1afc03..0000000 --- a/legacy/taproot-assets-era/migrations/001_postgres_schema.sql +++ /dev/null @@ -1,297 +0,0 @@ --- RuneBolt PostgreSQL Migration Schema --- Migration: 001_initial_postgres_schema.sql --- Purpose: Production-ready schema optimized for high throughput - --- Enable required extensions -CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; -CREATE EXTENSION IF NOT EXISTS "pg_stat_statements"; - --- ============================================================================= --- CHANNELS TABLE --- ============================================================================= -CREATE TABLE channels ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - user_pubkey BYTEA NOT NULL CHECK (octet_length(user_pubkey) IN (33, 65)), - runebolt_pubkey BYTEA NOT NULL CHECK (octet_length(runebolt_pubkey) IN (33, 65)), - funding_txid BYTEA CHECK (octet_length(funding_txid) = 32), - funding_vout SMALLINT, - capacity BIGINT NOT NULL DEFAULT 0 CHECK (capacity >= 0), - local_balance BIGINT NOT NULL DEFAULT 0 CHECK (local_balance >= 0), - remote_balance BIGINT NOT NULL DEFAULT 0 CHECK (remote_balance >= 0), - state VARCHAR(20) NOT NULL DEFAULT 'PENDING_OPEN', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - - -- Constraints - CONSTRAINT valid_balance CHECK (local_balance + remote_balance = capacity), - CONSTRAINT valid_state CHECK (state IN ('PENDING_OPEN', 'OPEN', 'CLOSING', 'CLOSED', 'FORCE_CLOSING')) -); - --- Optimized indexes for channels -CREATE INDEX CONCURRENTLY idx_channels_user_pubkey ON channels(user_pubkey); -CREATE INDEX CONCURRENTLY idx_channels_state ON channels(state) WHERE state IN ('OPEN', 'PENDING_OPEN'); -CREATE INDEX CONCURRENTLY idx_channels_created_at ON channels(created_at); - --- Partial index for active channels (hot data only) -CREATE INDEX CONCURRENTLY idx_channels_active ON channels(user_pubkey, state) - WHERE state = 'OPEN'; - --- Composite index for common lookups -CREATE INDEX CONCURRENTLY idx_channels_user_state ON channels(user_pubkey, state, created_at DESC); - --- ============================================================================= --- TRANSFERS TABLE (PARTITIONED) --- ============================================================================= -CREATE TABLE transfers ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - from_channel UUID NOT NULL REFERENCES channels(id) ON DELETE RESTRICT, - to_channel UUID NOT NULL REFERENCES channels(id) ON DELETE RESTRICT, - amount BIGINT NOT NULL CHECK (amount > 0), - memo VARCHAR(256), - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -) PARTITION BY RANGE (created_at); - --- Create monthly partitions (adjust as needed) -CREATE TABLE transfers_2026_03 PARTITION OF transfers - FOR VALUES FROM ('2026-03-01') TO ('2026-04-01'); -CREATE TABLE transfers_2026_04 PARTITION OF transfers - FOR VALUES FROM ('2026-04-01') TO ('2026-05-01'); -CREATE TABLE transfers_2026_05 PARTITION OF transfers - FOR VALUES FROM ('2026-05-01') TO ('2026-06-01'); -CREATE TABLE transfers_2026_06 PARTITION OF transfers - FOR VALUES FROM ('2026-06-01') TO ('2026-07-01'); - --- Optimized indexes for transfers -CREATE INDEX CONCURRENTLY idx_transfers_from_created ON transfers(from_channel, created_at DESC); -CREATE INDEX CONCURRENTLY idx_transfers_to_created ON transfers(to_channel, created_at DESC); - --- Covering indexes for common queries -CREATE INDEX CONCURRENTLY idx_transfers_sender ON transfers(from_channel, created_at DESC) - INCLUDE (id, to_channel, amount, memo); -CREATE INDEX CONCURRENTLY idx_transfers_recipient ON transfers(to_channel, created_at DESC) - INCLUDE (id, from_channel, amount, memo); - --- ============================================================================= --- USERS TABLE --- ============================================================================= -CREATE TABLE users ( - pubkey BYTEA PRIMARY KEY CHECK (octet_length(pubkey) IN (33, 65)), - username VARCHAR(32) UNIQUE CHECK (username ~ '^[a-z0-9_]+$'), - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX CONCURRENTLY idx_users_username ON users(username); - --- ============================================================================= --- CLAIM LINKS TABLE --- ============================================================================= -CREATE TABLE claim_links ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - creator_pubkey BYTEA NOT NULL REFERENCES users(pubkey), - amount BIGINT NOT NULL CHECK (amount > 0), - memo VARCHAR(256), - claimed_by BYTEA REFERENCES users(pubkey), - claimed_at TIMESTAMPTZ, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - expires_at TIMESTAMPTZ NOT NULL -); - -CREATE INDEX CONCURRENTLY idx_claim_links_creator ON claim_links(creator_pubkey); -CREATE INDEX CONCURRENTLY idx_claim_links_expires ON claim_links(expires_at) - WHERE claimed_by IS NULL; - --- ============================================================================= --- CHALLENGES TABLE (for auth) --- ============================================================================= -CREATE TABLE challenges ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), - pubkey BYTEA NOT NULL, - challenge_hash BYTEA NOT NULL, -- Store hash only - expires_at TIMESTAMPTZ NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX CONCURRENTLY idx_challenges_pubkey ON challenges(pubkey); -CREATE INDEX CONCURRENTLY idx_challenges_expires ON challenges(expires_at); - --- ============================================================================= --- HELPER FUNCTIONS --- ============================================================================= - --- Auto-update updated_at column -CREATE OR REPLACE FUNCTION update_updated_at_column() -RETURNS TRIGGER AS $$ -BEGIN - NEW.updated_at = NOW(); - RETURN NEW; -END; -$$ LANGUAGE plpgsql; - -CREATE TRIGGER channels_updated_at - BEFORE UPDATE ON channels - FOR EACH ROW - EXECUTE FUNCTION update_updated_at_column(); - --- Cleanup expired challenges function -CREATE OR REPLACE FUNCTION cleanup_expired_challenges() -RETURNS INTEGER AS $$ -DECLARE - deleted_count INTEGER; -BEGIN - DELETE FROM challenges WHERE expires_at < NOW(); - GET DIAGNOSTICS deleted_count = ROW_COUNT; - RETURN deleted_count; -END; -$$ LANGUAGE plpgsql; - --- Get user transfer history (optimized - no OR conditions) -CREATE OR REPLACE FUNCTION get_user_transfers( - p_pubkey BYTEA, - p_limit INTEGER DEFAULT 50, - p_offset INTEGER DEFAULT 0 -) -RETURNS TABLE ( - id UUID, - from_channel UUID, - to_channel UUID, - amount BIGINT, - memo VARCHAR(256), - created_at TIMESTAMPTZ, - direction VARCHAR(10) -) AS $$ -BEGIN - -- Get user's channel IDs first - RETURN QUERY - WITH user_channels AS ( - SELECT id FROM channels WHERE user_pubkey = p_pubkey - ) - SELECT - t.id, - t.from_channel, - t.to_channel, - t.amount, - t.memo, - t.created_at, - CASE - WHEN t.from_channel IN (SELECT id FROM user_channels) THEN 'sent' - ELSE 'received' - END as direction - FROM transfers t - WHERE t.from_channel IN (SELECT id FROM user_channels) - OR t.to_channel IN (SELECT id FROM user_channels) - ORDER BY t.created_at DESC - LIMIT p_limit - OFFSET p_offset; -END; -$$ LANGUAGE plpgsql; - --- Atomic transfer execution -CREATE OR REPLACE FUNCTION execute_transfer( - p_from_channel UUID, - p_to_channel UUID, - p_amount BIGINT, - p_memo VARCHAR(256) DEFAULT NULL -) -RETURNS UUID AS $$ -DECLARE - v_transfer_id UUID; - v_from_local BIGINT; - v_from_remote BIGINT; - v_to_local BIGINT; - v_to_remote BIGINT; -BEGIN - -- Lock both channels for update (prevents race conditions) - SELECT local_balance, remote_balance - INTO v_from_local, v_from_remote - FROM channels - WHERE id = p_from_channel - AND state = 'OPEN' - FOR UPDATE; - - IF NOT FOUND THEN - RAISE EXCEPTION 'Sender channel not found or not open'; - END IF; - - IF v_from_local < p_amount THEN - RAISE EXCEPTION 'Insufficient balance'; - END IF; - - SELECT local_balance, remote_balance - INTO v_to_local, v_to_remote - FROM channels - WHERE id = p_to_channel - AND state = 'OPEN' - FOR UPDATE; - - IF NOT FOUND THEN - RAISE EXCEPTION 'Recipient channel not found or not open'; - END IF; - - IF v_to_remote < p_amount THEN - RAISE EXCEPTION 'Insufficient inbound capacity'; - END IF; - - -- Update balances - UPDATE channels - SET local_balance = v_from_local - p_amount, - remote_balance = v_from_remote + p_amount - WHERE id = p_from_channel; - - UPDATE channels - SET local_balance = v_to_local + p_amount, - remote_balance = v_to_remote - p_amount - WHERE id = p_to_channel; - - -- Create transfer record - v_transfer_id := uuid_generate_v4(); - INSERT INTO transfers (id, from_channel, to_channel, amount, memo) - VALUES (v_transfer_id, p_from_channel, p_to_channel, p_amount, p_memo); - - RETURN v_transfer_id; -END; -$$ LANGUAGE plpgsql; - --- ============================================================================= --- MAINTENANCE PROCEDURES --- ============================================================================= - --- Create new partition for next month (run monthly) -CREATE OR REPLACE FUNCTION create_next_transfer_partition() -RETURNS TEXT AS $$ -DECLARE - v_next_month TEXT; - v_start_date TEXT; - v_end_date TEXT; - v_partition_name TEXT; -BEGIN - v_next_month := TO_CHAR(NOW() + INTERVAL '1 month', 'YYYY_MM'); - v_start_date := TO_CHAR(NOW() + INTERVAL '1 month', 'YYYY-MM-01'); - v_end_date := TO_CHAR(NOW() + INTERVAL '2 months', 'YYYY-MM-01'); - v_partition_name := 'transfers_' || v_next_month; - - EXECUTE format( - 'CREATE TABLE IF NOT EXISTS %I PARTITION OF transfers FOR VALUES FROM (%L) TO (%L)', - v_partition_name, v_start_date, v_end_date - ); - - RETURN v_partition_name; -END; -$$ LANGUAGE plpgsql; - --- Archive old partitions (run quarterly) -CREATE OR REPLACE FUNCTION archive_old_partitions(p_months_old INTEGER DEFAULT 6) -RETURNS TABLE (archived_partition TEXT) AS $$ -DECLARE - v_partition RECORD; -BEGIN - FOR v_partition IN - SELECT tablename - FROM pg_tables - WHERE tablename LIKE 'transfers_20%' - AND tablename < 'transfers_' || TO_CHAR(NOW() - (p_months_old || ' months')::INTERVAL, 'YYYY_MM') - LOOP - -- Detach and archive logic here - RETURN QUERY SELECT v_partition.tablename::TEXT; - END LOOP; -END; -$$ LANGUAGE plpgsql; \ No newline at end of file diff --git a/legacy/taproot-assets-era/migrations/002_fees_and_tiers.sql b/legacy/taproot-assets-era/migrations/002_fees_and_tiers.sql deleted file mode 100644 index 077a1d0..0000000 --- a/legacy/taproot-assets-era/migrations/002_fees_and_tiers.sql +++ /dev/null @@ -1,55 +0,0 @@ --- RuneBolt Migration 002: Fee system and user tiers --- Adds free tier tracking, fee records, and user tier management - --- ============================================================ --- User transaction counts (tracks free tier usage) --- ============================================================ -CREATE TABLE IF NOT EXISTS user_transaction_counts ( - pubkey TEXT PRIMARY KEY REFERENCES users(pubkey), - count INTEGER NOT NULL DEFAULT 0, - last_reset TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_user_tx_counts_last_reset ON user_transaction_counts(last_reset); - --- ============================================================ --- Fee records (accounting trail for all fees collected) --- ============================================================ -CREATE TABLE IF NOT EXISTS fee_records ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - transfer_id UUID NOT NULL, - pubkey TEXT NOT NULL REFERENCES users(pubkey), - amount BIGINT NOT NULL, - fee_type TEXT NOT NULL CHECK (fee_type IN ('off_chain', 'settlement')), - fee_rate NUMERIC(10, 6) NOT NULL, - collected_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_fee_records_transfer ON fee_records(transfer_id); -CREATE INDEX IF NOT EXISTS idx_fee_records_pubkey ON fee_records(pubkey); -CREATE INDEX IF NOT EXISTS idx_fee_records_collected ON fee_records(collected_at); - --- ============================================================ --- User tiers --- ============================================================ -CREATE TABLE IF NOT EXISTS user_tiers ( - pubkey TEXT PRIMARY KEY REFERENCES users(pubkey), - tier TEXT NOT NULL DEFAULT 'free' CHECK (tier IN ('free', 'standard')), - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - --- Trigger for updated_at on user_tiers -CREATE OR REPLACE FUNCTION update_user_tiers_updated_at() -RETURNS TRIGGER AS $$ -BEGIN - NEW.updated_at = NOW(); - RETURN NEW; -END; -$$ LANGUAGE plpgsql; - -DROP TRIGGER IF EXISTS trigger_user_tiers_updated_at ON user_tiers; -CREATE TRIGGER trigger_user_tiers_updated_at - BEFORE UPDATE ON user_tiers - FOR EACH ROW - EXECUTE FUNCTION update_user_tiers_updated_at(); diff --git a/legacy/taproot-assets-era/migrations/005_multi_asset.sql b/legacy/taproot-assets-era/migrations/005_multi_asset.sql deleted file mode 100644 index 8d045f1..0000000 --- a/legacy/taproot-assets-era/migrations/005_multi_asset.sql +++ /dev/null @@ -1,73 +0,0 @@ --- Migration 005: Multi-asset support --- Adds tables for asset registry, escrows (Bitmap NFT trading), and asset balances (BRC-20 channel tracking). --- --- NOTE: BRC-20 and Bitmap inscriptions use DIFFERENT on-chain mechanisms than Runes. --- Runes use Runestone OP_RETURN; BRC-20 uses inscription JSON; Bitmap uses escrow model. - --- ==================== Assets Table ==================== --- Central registry of supported assets and their configuration. -CREATE TABLE IF NOT EXISTS assets ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - type TEXT NOT NULL CHECK (type IN ('rune', 'btc', 'brc20', 'inscription')), - config JSONB NOT NULL DEFAULT '{}', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_assets_type ON assets(type); - --- Seed initial assets -INSERT INTO assets (id, name, type, config) VALUES - ('dog', 'DOG', 'rune', '{"runeId": "840000:3", "decimals": 5}'), - ('btc', 'Bitcoin', 'btc', '{"decimals": 8}'), - ('ordi', 'ORDI', 'brc20', '{"ticker": "ordi", "decimals": 18}'), - ('bitmap', 'Bitmap', 'inscription', '{"decimals": 0}') -ON CONFLICT (id) DO NOTHING; - --- ==================== Escrows Table ==================== --- Bitmap (NFT inscription) escrow for atomic swaps. --- Seller deposits inscription, buyer deposits payment, hub releases both atomically. -CREATE TABLE IF NOT EXISTS escrows ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - seller_pubkey TEXT NOT NULL, - buyer_pubkey TEXT NOT NULL, - inscription_id TEXT NOT NULL, - price_asset TEXT NOT NULL REFERENCES assets(id), - price_amount NUMERIC NOT NULL CHECK (price_amount > 0), - status TEXT NOT NULL DEFAULT 'created' - CHECK (status IN ('created', 'inscription_deposited', 'payment_deposited', - 'both_deposited', 'executing', 'completed', 'refunded', 'expired')), - timeout_at TIMESTAMPTZ NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_escrows_seller ON escrows(seller_pubkey); -CREATE INDEX IF NOT EXISTS idx_escrows_buyer ON escrows(buyer_pubkey); -CREATE INDEX IF NOT EXISTS idx_escrows_status ON escrows(status) WHERE status NOT IN ('completed', 'refunded', 'expired'); -CREATE INDEX IF NOT EXISTS idx_escrows_timeout ON escrows(timeout_at) WHERE status NOT IN ('completed', 'refunded', 'expired'); - --- ==================== Escrow Deposits Table ==================== --- Tracks individual deposits (inscription or payment) for each escrow. -CREATE TABLE IF NOT EXISTS escrow_deposits ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - escrow_id UUID NOT NULL REFERENCES escrows(id) ON DELETE CASCADE, - side TEXT NOT NULL CHECK (side IN ('seller', 'buyer')), - txid TEXT NOT NULL, - confirmed BOOLEAN NOT NULL DEFAULT false, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE INDEX IF NOT EXISTS idx_escrow_deposits_escrow ON escrow_deposits(escrow_id); - --- ==================== Asset Balances Table ==================== --- Off-chain asset balances tracked by the hub (used for BRC-20 channel balances). -CREATE TABLE IF NOT EXISTS asset_balances ( - user_pubkey TEXT NOT NULL, - asset_id TEXT NOT NULL REFERENCES assets(id), - balance NUMERIC NOT NULL DEFAULT 0 CHECK (balance >= 0), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (user_pubkey, asset_id) -); - -CREATE INDEX IF NOT EXISTS idx_asset_balances_user ON asset_balances(user_pubkey); -CREATE INDEX IF NOT EXISTS idx_asset_balances_asset ON asset_balances(asset_id); diff --git a/legacy/taproot-assets-era/monitoring/alerts/alerts.yml b/legacy/taproot-assets-era/monitoring/alerts/alerts.yml deleted file mode 100644 index 49de10f..0000000 --- a/legacy/taproot-assets-era/monitoring/alerts/alerts.yml +++ /dev/null @@ -1,309 +0,0 @@ -# RuneBolt Prometheus Alert Rules -# Critical, Warning, and Info level alerts -# Version: 1.0.0 - -groups: - # ============================================ - # Critical Alerts (P1 - Page Immediately) - # ============================================ - - name: critical - interval: 15s - rules: - # API Down - - alert: RuneBoltAPIDown - expr: up{job="runebolt-backend-api"} == 0 - for: 1m - labels: - severity: critical - priority: P1 - service: backend-api - annotations: - summary: "RuneBolt API is down" - description: "RuneBolt API has been down for more than 1 minute" - runbook_url: "https://wiki.runebolt.io/runbooks/api-down" - action: "Check service status: docker compose ps backend-api" - - # Database Connection Failure - - alert: PostgreSQLDown - expr: up{job="postgres-exporter"} == 0 - for: 1m - labels: - severity: critical - priority: P1 - service: postgres - annotations: - summary: "PostgreSQL is down" - description: "PostgreSQL database is not responding" - action: "Check database status: docker compose ps postgres" - - # High Error Rate - - alert: HighErrorRate - expr: | - ( - sum(rate(http_requests_total{status=~"5.."}[5m])) - / - sum(rate(http_requests_total[5m])) - ) > 0.01 - for: 2m - labels: - severity: critical - priority: P1 - service: backend-api - annotations: - summary: "High error rate detected" - description: "Error rate is above 1% for 2 minutes" - value: "{{ $value | humanizePercentage }}" - - # Vault Sealed - - alert: VaultSealed - expr: vault_core_sealed == 1 - for: 0s - labels: - severity: critical - priority: P1 - service: vault - annotations: - summary: "Vault is sealed" - description: "HashiCorp Vault is sealed and requires unsealing" - action: "Run: ./scripts/vault-unseal.sh" - - # Redis Down - - alert: RedisDown - expr: up{job="redis-exporter"} == 0 - for: 1m - labels: - severity: critical - priority: P1 - service: redis - annotations: - summary: "Redis is down" - description: "Redis cache server is not responding" - - # ============================================ - # High Priority Alerts (P2 - Slack Notification) - # ============================================ - - name: high - interval: 30s - rules: - # High Latency - - alert: HighLatency - expr: | - histogram_quantile(0.99, - sum(rate(http_request_duration_seconds_bucket[5m])) by (le) - ) > 0.5 - for: 5m - labels: - severity: high - priority: P2 - service: backend-api - annotations: - summary: "High API latency detected" - description: "99th percentile latency is above 500ms" - value: "{{ $value | humanizeDuration }}" - - # CPU Usage - - alert: HighCPUUsage - expr: | - 100 - (avg by(instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80 - for: 5m - labels: - severity: high - priority: P2 - service: infrastructure - annotations: - summary: "High CPU usage" - description: "CPU usage is above 80% for 5 minutes" - value: "{{ $value | humanize }}%" - - # Memory Usage - - alert: HighMemoryUsage - expr: | - ( - node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes - ) / node_memory_MemTotal_bytes * 100 > 85 - for: 5m - labels: - severity: high - priority: P2 - service: infrastructure - annotations: - summary: "High memory usage" - description: "Memory usage is above 85% for 5 minutes" - value: "{{ $value | humanize }}%" - - # Disk Usage - - alert: HighDiskUsage - expr: | - ( - node_filesystem_avail_bytes{mountpoint="/"} / - node_filesystem_size_bytes{mountpoint="/"} - ) < 0.2 - for: 5m - labels: - severity: high - priority: P2 - service: infrastructure - annotations: - summary: "High disk usage" - description: "Disk usage is above 80% (less than 20% free)" - value: "{{ $value | humanizePercentage }} free" - - # Database Connections - - alert: PostgreSQLHighConnections - expr: | - pg_stat_activity_count / pg_settings_max_connections * 100 > 80 - for: 5m - labels: - severity: high - priority: P2 - service: postgres - annotations: - summary: "PostgreSQL high connection count" - description: "PostgreSQL connection count is above 80% of max" - value: "{{ $value | humanize }}%" - - # Redis Memory - - alert: RedisHighMemory - expr: | - redis_memory_used_bytes / redis_memory_max_bytes * 100 > 90 - for: 5m - labels: - severity: high - priority: P2 - service: redis - annotations: - summary: "Redis high memory usage" - description: "Redis memory usage is above 90%" - value: "{{ $value | humanize }}%" - - # ============================================ - # Medium Priority Alerts (P3 - Email) - # ============================================ - - name: medium - interval: 1m - rules: - # Slow Requests - - alert: SlowRequests - expr: | - histogram_quantile(0.95, - sum(rate(http_request_duration_seconds_bucket[5m])) by (le) - ) > 0.2 - for: 10m - labels: - severity: warning - priority: P3 - service: backend-api - annotations: - summary: "Slow requests detected" - description: "95th percentile latency is above 200ms" - value: "{{ $value | humanizeDuration }}" - - # Container Restart - - alert: ContainerRestart - expr: | - increase(container_last_seen[15m]) > 0 - for: 0s - labels: - severity: warning - priority: P3 - service: infrastructure - annotations: - summary: "Container restart detected" - description: "A container has restarted" - - # SSL Certificate Expiry - - alert: SSLCertificateExpiring - expr: | - probe_ssl_earliest_cert_expiry - time() < 86400 * 7 - for: 1h - labels: - severity: warning - priority: P3 - service: tls - annotations: - summary: "SSL certificate expiring soon" - description: "SSL certificate expires in less than 7 days" - value: "{{ $value | humanizeDuration }} until expiry" - - # Backup Failure - - alert: BackupFailure - expr: | - time() - max(backup_last_success_time) > 86400 - for: 1h - labels: - severity: warning - priority: P3 - service: backup - annotations: - summary: "Backup may have failed" - description: "No successful backup in the last 24 hours" - - # Rate Limiting Triggered - - alert: RateLimitTriggered - expr: | - increase(rate_limit_hits_total[5m]) > 100 - for: 5m - labels: - severity: warning - priority: P3 - service: backend-api - annotations: - summary: "Rate limiting triggered frequently" - description: "Rate limit is being hit frequently - possible attack or misconfiguration" - - # ============================================ - # Business Metrics Alerts - # ============================================ - - name: business - interval: 1m - rules: - # Channel Failure Rate - - alert: ChannelOpenFailureRate - expr: | - ( - sum(rate(channel_open_failed_total[10m])) - / - sum(rate(channel_open_total[10m])) - ) > 0.1 - for: 5m - labels: - severity: high - priority: P2 - service: business - annotations: - summary: "High channel open failure rate" - description: "More than 10% of channel open attempts are failing" - - # Transfer Failure Rate - - alert: TransferFailureRate - expr: | - ( - sum(rate(transfer_failed_total[10m])) - / - sum(rate(transfer_total[10m])) - ) > 0.05 - for: 5m - labels: - severity: critical - priority: P1 - service: business - annotations: - summary: "High transfer failure rate" - description: "More than 5% of transfers are failing" - - # Unusual Activity - - alert: UnusualTransferVolume - expr: | - ( - sum(rate(transfer_volume_sats[1h])) - > - 2 * avg_over_time(sum(rate(transfer_volume_sats[1h]))[24h:1h]) - ) - for: 15m - labels: - severity: warning - priority: P3 - service: business - annotations: - summary: "Unusual transfer volume detected" - description: "Transfer volume is 2x higher than 24h average" diff --git a/legacy/taproot-assets-era/monitoring/dashboard-specs.json b/legacy/taproot-assets-era/monitoring/dashboard-specs.json deleted file mode 100644 index 12d1d9c..0000000 --- a/legacy/taproot-assets-era/monitoring/dashboard-specs.json +++ /dev/null @@ -1,109 +0,0 @@ -{ - "dashboard": { - "title": "RuneBolt Performance Dashboard", - "refresh": "5s", - "panels": [ - { - "id": 1, - "title": "Transfer Throughput (TPS)", - "type": "graph", - "targets": [ - { - "expr": "rate(transfers_total[1m])", - "legendFormat": "Transfers/sec" - } - ], - "alert": { - "name": "Low TPS", - "condition": "transfer_rate < 100", - "for": "5m" - } - }, - { - "id": 2, - "title": "Latency Percentiles", - "type": "graph", - "targets": [ - { "expr": "histogram_quantile(0.50, transfer_duration_seconds)", "legendFormat": "p50" }, - { "expr": "histogram_quantile(0.95, transfer_duration_seconds)", "legendFormat": "p95" }, - { "expr": "histogram_quantile(0.99, transfer_duration_seconds)", "legendFormat": "p99" } - ] - }, - { - "id": 3, - "title": "Database Pool Status", - "type": "stat", - "targets": [ - { "expr": "db_pool_total", "legendFormat": "Total" }, - { "expr": "db_pool_idle", "legendFormat": "Idle" }, - { "expr": "db_pool_waiting", "legendFormat": "Waiting" } - ] - }, - { - "id": 4, - "title": "Cache Hit Rate", - "type": "gauge", - "targets": [ - { "expr": "redis_keyspace_hits / (redis_keyspace_hits + redis_keyspace_misses)" } - ] - }, - { - "id": 5, - "title": "WebSocket Connections", - "type": "graph", - "targets": [ - { "expr": "websocket_connections", "legendFormat": "Active" } - ], - "alert": { - "name": "High Connection Count", - "condition": "websocket_connections > 10000", - "for": "1m" - } - }, - { - "id": 6, - "title": "Error Rate by Endpoint", - "type": "graph", - "targets": [ - { "expr": "rate(http_requests_total{status=~\"5..\"}[5m])", "legendFormat": "{{endpoint}}" } - ] - }, - { - "id": 7, - "title": "Active Channels by State", - "type": "pie", - "targets": [ - { "expr": "channels_total", "legendFormat": "{{state}}" } - ] - }, - { - "id": 8, - "title": "Rate Limit Hits", - "type": "graph", - "targets": [ - { "expr": "rate(rate_limit_hits_total[1m])", "legendFormat": "Rate Limited" } - ] - } - ], - "alerts": [ - { - "name": "HighLatency", - "expr": "histogram_quantile(0.99, transfer_duration_seconds) > 0.05", - "for": "5m", - "severity": "warning" - }, - { - "name": "DatabasePoolExhausted", - "expr": "db_pool_waiting > 10", - "for": "1m", - "severity": "critical" - }, - { - "name": "CacheHitRateLow", - "expr": "redis_keyspace_hits / (redis_keyspace_hits + redis_keyspace_misses) < 0.8", - "for": "5m", - "severity": "warning" - } - ] - } -} diff --git a/legacy/taproot-assets-era/monitoring/grafana/dashboards/dashboards.yml b/legacy/taproot-assets-era/monitoring/grafana/dashboards/dashboards.yml deleted file mode 100644 index 645866e..0000000 --- a/legacy/taproot-assets-era/monitoring/grafana/dashboards/dashboards.yml +++ /dev/null @@ -1,12 +0,0 @@ -apiVersion: 1 - -providers: - - name: 'RuneBolt Dashboards' - orgId: 1 - folder: 'RuneBolt' - type: file - disableDeletion: false - updateIntervalSeconds: 30 - allowUiUpdates: true - options: - path: /etc/grafana/provisioning/dashboards diff --git a/legacy/taproot-assets-era/monitoring/grafana/dashboards/overview.json b/legacy/taproot-assets-era/monitoring/grafana/dashboards/overview.json deleted file mode 100644 index 17fb26b..0000000 --- a/legacy/taproot-assets-era/monitoring/grafana/dashboards/overview.json +++ /dev/null @@ -1,327 +0,0 @@ -{ - "annotations": { - "list": [ - { - "builtIn": 1, - "datasource": "-- Grafana --", - "enable": true, - "hide": true, - "iconColor": "rgba(0, 211, 255, 1)", - "name": "Annotations & Alerts", - "type": "dashboard" - } - ] - }, - "description": "RuneBolt System Overview - Key metrics for all services", - "editable": true, - "gnetId": null, - "graphTooltip": 0, - "id": null, - "links": [], - "panels": [ - { - "collapsed": false, - "datasource": "Prometheus", - "gridPos": { - "h": 1, - "w": 24, - "x": 0, - "y": 0 - }, - "id": 20, - "panels": [], - "title": "System Overview", - "type": "row" - }, - { - "datasource": "Prometheus", - "fieldConfig": { - "defaults": { - "color": { - "mode": "thresholds" - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 0 - }, - { - "color": "green", - "value": 1 - } - ] - }, - "unit": "short" - }, - "overrides": [] - }, - "gridPos": { - "h": 4, - "w": 4, - "x": 0, - "y": 1 - }, - "id": 2, - "options": { - "colorMode": "background", - "graphMode": "area", - "justifyMode": "auto", - "orientation": "auto", - "reduceOptions": { - "calcs": ["lastNotNull"], - "fields": "", - "values": false - }, - "textMode": "auto" - }, - "pluginVersion": "10.2.0", - "targets": [ - { - "expr": "up{job=\"runebolt-backend-api\"}", - "refId": "A" - } - ], - "title": "API Status", - "type": "stat" - }, - { - "datasource": "Prometheus", - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic" - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - } - ] - }, - "unit": "reqps" - }, - "overrides": [] - }, - "gridPos": { - "h": 4, - "w": 5, - "x": 4, - "y": 1 - }, - "id": 4, - "options": { - "colorMode": "value", - "graphMode": "area", - "justifyMode": "auto", - "orientation": "auto", - "reduceOptions": { - "calcs": ["mean"], - "fields": "", - "values": false - }, - "textMode": "auto" - }, - "pluginVersion": "10.2.0", - "targets": [ - { - "expr": "sum(rate(http_requests_total[5m]))", - "refId": "A" - } - ], - "title": "Request Rate", - "type": "stat" - }, - { - "datasource": "Prometheus", - "fieldConfig": { - "defaults": { - "color": { - "mode": "thresholds" - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "yellow", - "value": 100 - }, - { - "color": "red", - "value": 200 - } - ] - }, - "unit": "ms" - }, - "overrides": [] - }, - "gridPos": { - "h": 4, - "w": 5, - "x": 9, - "y": 1 - }, - "id": 6, - "options": { - "colorMode": "value", - "graphMode": "area", - "justifyMode": "auto", - "orientation": "auto", - "reduceOptions": { - "calcs": ["lastNotNull"], - "fields": "", - "values": false - }, - "textMode": "auto" - }, - "pluginVersion": "10.2.0", - "targets": [ - { - "expr": "histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le)) * 1000", - "refId": "A" - } - ], - "title": "P99 Latency", - "type": "stat" - }, - { - "datasource": "Prometheus", - "fieldConfig": { - "defaults": { - "color": { - "mode": "thresholds" - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "yellow", - "value": 0.001 - }, - { - "color": "red", - "value": 0.01 - } - ] - }, - "unit": "percentunit" - }, - "overrides": [] - }, - "gridPos": { - "h": 4, - "w": 5, - "x": 14, - "y": 1 - }, - "id": 8, - "options": { - "colorMode": "background", - "graphMode": "area", - "justifyMode": "auto", - "orientation": "auto", - "reduceOptions": { - "calcs": ["mean"], - "fields": "", - "values": false - }, - "textMode": "auto" - }, - "pluginVersion": "10.2.0", - "targets": [ - { - "expr": "sum(rate(http_requests_total{status=~\"5..\"}[5m])) / sum(rate(http_requests_total[5m]))", - "refId": "A" - } - ], - "title": "Error Rate", - "type": "stat" - }, - { - "datasource": "Prometheus", - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic" - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - } - ] - }, - "unit": "short" - }, - "overrides": [] - }, - "gridPos": { - "h": 4, - "w": 5, - "x": 19, - "y": 1 - }, - "id": 10, - "options": { - "colorMode": "value", - "graphMode": "area", - "justifyMode": "auto", - "orientation": "auto", - "reduceOptions": { - "calcs": ["lastNotNull"], - "fields": "", - "values": false - }, - "textMode": "auto" - }, - "pluginVersion": "10.2.0", - "targets": [ - { - "expr": "active_channels_total", - "refId": "A" - } - ], - "title": "Active Channels", - "type": "stat" - } - ], - "refresh": "30s", - "schemaVersion": 36, - "style": "dark", - "tags": ["runebolt", "overview"], - "templating": { - "list": [] - }, - "time": { - "from": "now-1h", - "to": "now" - }, - "timepicker": {}, - "timezone": "browser", - "title": "RuneBolt System Overview", - "uid": "runebolt-overview", - "version": 1 -} \ No newline at end of file diff --git a/legacy/taproot-assets-era/monitoring/grafana/datasources/datasources.yml b/legacy/taproot-assets-era/monitoring/grafana/datasources/datasources.yml deleted file mode 100644 index 6767ef8..0000000 --- a/legacy/taproot-assets-era/monitoring/grafana/datasources/datasources.yml +++ /dev/null @@ -1,51 +0,0 @@ -apiVersion: 1 - -datasources: - - name: Prometheus - type: prometheus - access: proxy - url: http://prometheus:9090 - isDefault: true - editable: true - jsonData: - timeInterval: 15s - httpMethod: POST - manageAlerts: true - alertmanagerUid: alertmanager - - - name: Loki - type: loki - access: proxy - url: http://loki:3100 - editable: true - jsonData: - maxLines: 1000 - derivedFields: - - name: TraceID - matcherRegex: '"trace_id":"([^"]+)"' - url: '$${__value.raw}' - - - name: Jaeger - type: jaeger - access: proxy - url: http://jaeger:16686 - editable: true - jsonData: - tracesToLogs: - datasourceUid: loki - tags: ['service'] - mappedTags: [{ key: 'service', value: 'service' }] - mapTagNamesEnabled: false - spanStartTimeShift: 1h - spanEndTimeShift: 1h - filterByTraceID: false - filterBySpanID: false - - - name: Alertmanager - type: alertmanager - uid: alertmanager - access: proxy - url: http://alertmanager:9093 - editable: true - jsonData: - implementation: prometheus diff --git a/legacy/taproot-assets-era/monitoring/loki/loki.yml b/legacy/taproot-assets-era/monitoring/loki/loki.yml deleted file mode 100644 index edbdf10..0000000 --- a/legacy/taproot-assets-era/monitoring/loki/loki.yml +++ /dev/null @@ -1,61 +0,0 @@ -# Loki Configuration -# Log aggregation for RuneBolt - -auth_enabled: false - -server: - http_listen_port: 3100 - grpc_listen_port: 9096 - -common: - path_prefix: /loki - storage: - filesystem: - chunks_directory: /loki/chunks - rules_directory: /loki/rules - replication_factor: 1 - ring: - instance_addr: 127.0.0.1 - kvstore: - store: inmemory - -query_range: - results_cache: - cache: - embedded_cache: - enabled: true - max_size_mb: 100 - -schema_config: - configs: - - from: 2024-01-01 - store: boltdb-shipper - object_store: filesystem - schema: v11 - index: - prefix: index_ - period: 24h - -ruler: - alertmanager_url: http://alertmanager:9093 - -# Retention configuration -compactor: - working_directory: /loki/compactor - shared_store: filesystem - compaction_interval: 10m - retention_enabled: true - retention_delete_delay: 2h - retention_delete_worker_count: 150 - -table_manager: - retention_deletes_enabled: true - retention_period: 720h # 30 days - -limits_config: - reject_old_samples: true - reject_old_samples_max_age: 168h - ingestion_rate_mb: 16 - ingestion_burst_size_mb: 32 - per_stream_rate_limit: 3MB - per_stream_rate_limit_burst: 10MB diff --git a/legacy/taproot-assets-era/monitoring/prometheus.yml b/legacy/taproot-assets-era/monitoring/prometheus.yml deleted file mode 100644 index 05bbd3e..0000000 --- a/legacy/taproot-assets-era/monitoring/prometheus.yml +++ /dev/null @@ -1,223 +0,0 @@ -# RuneBolt Prometheus Configuration -# Version: 1.0.0 -# Monitors: Application metrics, infrastructure, business metrics - -global: - scrape_interval: 15s - evaluation_interval: 15s - external_labels: - cluster: 'runebolt-production' - replica: '{{.ExternalURL}}' - -# Alertmanager configuration -alerting: - alertmanagers: - - static_configs: - - targets: - - alertmanager:9093 - -# Load alerting rules -rule_files: - - '/etc/prometheus/alerts/*.yml' - -# Scrape configurations -scrape_configs: - # ============================================ - # Prometheus Self-Monitoring - # ============================================ - - job_name: 'prometheus' - static_configs: - - targets: ['localhost:9090'] - scrape_interval: 30s - metrics_path: /metrics - - # ============================================ - # RuneBolt Backend API - # ============================================ - - job_name: 'runebolt-backend-api' - static_configs: - - targets: ['backend-api:3001'] - labels: - service: 'backend-api' - tier: 'application' - scrape_interval: 15s - scrape_timeout: 10s - metrics_path: /metrics - scheme: http - - # ============================================ - # RuneBolt Backend Worker - # ============================================ - - job_name: 'runebolt-backend-worker' - static_configs: - - targets: ['backend-worker:3001'] - labels: - service: 'backend-worker' - tier: 'application' - scrape_interval: 30s - scrape_timeout: 10s - metrics_path: /metrics - scheme: http - - # ============================================ - # RuneBolt Frontend - # ============================================ - - job_name: 'runebolt-frontend' - static_configs: - - targets: ['frontend:3000'] - labels: - service: 'frontend' - tier: 'application' - scrape_interval: 30s - scrape_timeout: 10s - metrics_path: /metrics - scheme: http - - # ============================================ - # Node Exporter (System Metrics) - # ============================================ - - job_name: 'node-exporter' - static_configs: - - targets: ['node-exporter:9100'] - labels: - service: 'node-exporter' - tier: 'infrastructure' - scrape_interval: 15s - metrics_path: /metrics - - # ============================================ - # cAdvisor (Container Metrics) - # ============================================ - - job_name: 'cadvisor' - static_configs: - - targets: ['cadvisor:8080'] - labels: - service: 'cadvisor' - tier: 'infrastructure' - scrape_interval: 15s - metrics_path: /metrics - - # ============================================ - # PostgreSQL Exporter - # ============================================ - - job_name: 'postgres-exporter' - static_configs: - - targets: ['postgres-exporter:9187'] - labels: - service: 'postgres' - tier: 'database' - scrape_interval: 30s - metrics_path: /metrics - - # ============================================ - # Redis Exporter - # ============================================ - - job_name: 'redis-exporter' - static_configs: - - targets: ['redis-exporter:9121'] - labels: - service: 'redis' - tier: 'cache' - scrape_interval: 30s - metrics_path: /metrics - - # ============================================ - # HAProxy Exporter - # ============================================ - - job_name: 'haproxy-exporter' - static_configs: - - targets: ['haproxy:8404'] - labels: - service: 'haproxy' - tier: 'loadbalancer' - scrape_interval: 15s - metrics_path: /metrics - - # ============================================ - # Vault Metrics - # ============================================ - - job_name: 'vault' - static_configs: - - targets: ['vault:8200'] - labels: - service: 'vault' - tier: 'secrets' - scrape_interval: 30s - metrics_path: /v1/sys/metrics - params: - format: ['prometheus'] - scheme: http - # bearer_token_file: /etc/prometheus/vault-token (if ACL enabled) - - # ============================================ - # Docker Daemon Metrics - # ============================================ - - job_name: 'docker' - static_configs: - - targets: ['localhost:9323'] - labels: - service: 'docker' - tier: 'infrastructure' - scrape_interval: 30s - metrics_path: /metrics - - # ============================================ - # Blackbox Exporter (Probes) - # ============================================ - - job_name: 'blackbox-http' - metrics_path: /probe - params: - module: [http_2xx] - static_configs: - - targets: - - https://runebolt.io/health - - https://api.runebolt.io/health - - https://ws.runebolt.io/health - relabel_configs: - - source_labels: [__address__] - target_label: __param_target - - source_labels: [__param_target] - target_label: instance - - target_label: __address__ - replacement: blackbox-exporter:9115 - - - job_name: 'blackbox-tcp' - metrics_path: /probe - params: - module: [tcp_connect] - static_configs: - - targets: - - postgres:5432 - - redis:6379 - - vault:8200 - relabel_configs: - - source_labels: [__address__] - target_label: __param_target - - source_labels: [__param_target] - target_label: instance - - target_label: __address__ - replacement: blackbox-exporter:9115 - - # ============================================ - # Custom Business Metrics (Pushgateway) - # ============================================ - - job_name: 'pushgateway' - honor_labels: true - static_configs: - - targets: ['pushgateway:9091'] - labels: - service: 'pushgateway' - tier: 'metrics' - scrape_interval: 30s - - # ============================================ - # Loki Metrics - # ============================================ - - job_name: 'loki' - static_configs: - - targets: ['loki:3100'] - labels: - service: 'loki' - tier: 'logging' - scrape_interval: 30s - metrics_path: /metrics diff --git a/legacy/taproot-assets-era/monitoring/promtail/promtail.yml b/legacy/taproot-assets-era/monitoring/promtail/promtail.yml deleted file mode 100644 index d1398a5..0000000 --- a/legacy/taproot-assets-era/monitoring/promtail/promtail.yml +++ /dev/null @@ -1,67 +0,0 @@ -server: - http_listen_port: 9080 - grpc_listen_port: 0 - -positions: - filename: /tmp/positions.yaml - -clients: - - url: http://loki:3100/loki/api/v1/push - batchwait: 1s - batchsize: 102400 - -scrape_configs: - # Docker container logs - - job_name: docker - static_configs: - - targets: - - localhost - labels: - job: docker - __path__: /var/lib/docker/containers/*/*log - pipeline_stages: - - json: - expressions: - output: log - stream: stream - attrs: - - json: - source: attrs - expressions: - tag: - - regex: - source: tag - expression: (?P(?:[^|])*[^|]) - - timestamp: - format: RFC3339Nano - source: time - - labels: - stream: - container_name: - - output: - source: output - - # RuneBolt application logs - - job_name: runebolt - static_configs: - - targets: - - localhost - labels: - job: runebolt - __path__: /var/log/runebolt/**/*.log - pipeline_stages: - - json: - expressions: - timestamp: - level: - message: - service: - trace_id: - - labels: - level: - service: - - timestamp: - source: timestamp - format: RFC3339 - - output: - source: message diff --git a/legacy/taproot-assets-era/scripts/backup.sh b/legacy/taproot-assets-era/scripts/backup.sh deleted file mode 100755 index 8270f71..0000000 --- a/legacy/taproot-assets-era/scripts/backup.sh +++ /dev/null @@ -1,335 +0,0 @@ -#!/bin/bash -# RuneBolt Backup Automation Script -# Version: 1.0.0 -# Handles: PostgreSQL, Redis, SQLite, Vault backups to S3 - -set -euo pipefail - -# ============================================ -# Configuration -# ============================================ -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" - -BACKUP_DIR="${BACKUP_DIR:-$PROJECT_ROOT/backups}" -BACKUP_RETENTION_DAYS="${BACKUP_RETENTION_DAYS:-30}" -TIMESTAMP=$(date +%Y%m%d_%H%M%S) -DATE=$(date +%Y-%m-%d) - -S3_BUCKET="${S3_BUCKET:-runebolt-backups}" -S3_REGION="${S3_REGION:-us-east-1}" -S3_ENDPOINT="${S3_ENDPOINT:-}" - -POSTGRES_HOST="${POSTGRES_HOST:-localhost}" -POSTGRES_PORT="${POSTGRES_PORT:-5432}" -POSTGRES_DB="${POSTGRES_DB:-runebolt}" -POSTGRES_USER="${POSTGRES_USER:-runebolt}" -POSTGRES_PASSWORD="${POSTGRES_PASSWORD:-}" - -REDIS_HOST="${REDIS_HOST:-localhost}" -REDIS_PORT="${REDIS_PORT:-6379}" -REDIS_PASSWORD="${REDIS_PASSWORD:-}" - -SLACK_WEBHOOK_URL="${SLACK_WEBHOOK_URL:-}" - -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' - -log_info() { echo -e "${BLUE}[INFO]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"; } -log_success() { echo -e "${GREEN}[SUCCESS]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"; } -log_warn() { echo -e "${YELLOW}[WARN]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"; } -log_error() { echo -e "${RED}[ERROR]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"; } - -usage() { - cat << EOF -RuneBolt Backup Script - -Usage: $0 [OPTIONS] - -Commands: - full Run full backup (all components) - postgres Backup PostgreSQL database - redis Backup Redis - sqlite Backup SQLite databases - vault Backup Vault - cleanup Clean up old backups - -Options: - -h, --help Show this help - -d, --dry-run Show what would be done without executing - -q, --quiet Suppress output (for cron) - -EOF -} - -COMMAND="" -DRY_RUN=false -QUIET=false - -while [[ $# -gt 0 ]]; do - case $1 in - -h|--help) usage; exit 0 ;; - -d|--dry-run) DRY_RUN=true; shift ;; - -q|--quiet) QUIET=true; shift ;; - full|postgres|redis|sqlite|vault|cleanup) COMMAND="$1"; shift ;; - *) shift ;; - esac -done - -upload_to_s3() { - local file="$1" - local s3_key="$2" - - if [[ "$DRY_RUN" == true ]]; then - log_info "[DRY RUN] Would upload $file to s3://$S3_BUCKET/$s3_key" - return 0 - fi - - log_info "Uploading to S3: s3://$S3_BUCKET/$s3_key" - - local aws_args="" - if [[ -n "$S3_ENDPOINT" ]]; then - aws_args="--endpoint-url $S3_ENDPOINT" - fi - - if command -v aws &> /dev/null; then - aws s3 cp "$file" "s3://$S3_BUCKET/$s3_key" $aws_args --storage-class STANDARD_IA - elif command -v s3cmd &> /dev/null; then - s3cmd put "$file" "s3://$S3_BUCKET/$s3_key" - else - log_warn "No S3 client found. Skipping S3 upload." - return 1 - fi - - log_success "Upload complete: s3://$S3_BUCKET/$s3_key" -} - -compress_and_upload() { - local input="$1" - local s3_path="$2" - - if [[ "$DRY_RUN" == true ]]; then - log_info "[DRY RUN] Would compress and upload $input" - return 0 - fi - - log_info "Compressing $input..." - local output="$input.tar.gz" - tar -czf "$output" -C "$(dirname "$input")" "$(basename "$input")" - rm -rf "$input" - - upload_to_s3 "$output" "$s3_path/$(basename "$output")" - - # Create latest symlink locally - local latest_link="$(dirname "$input")/latest$(echo "$output" | grep -o '\.[^.]*\.tar\.gz$' || echo '.tar.gz')" - ln -sf "$(basename "$output")" "$latest_link" 2>/dev/null || true -} - -send_notification() { - local status="$1" - local message="$2" - - [[ "$QUIET" == true ]] && return 0 - [[ -z "$SLACK_WEBHOOK_URL" ]] && return 0 - - local color="good" - [[ "$status" == "error" ]] && color="danger" - [[ "$status" == "warning" ]] && color="warning" - - curl -s -X POST -H 'Content-type: application/json' \ - --data "{\"attachments\":[{\"color\":\"$color\",\"title\":\"RuneBolt Backup: $status\",\"text\":\"$message\",\"footer\":\"RuneBolt Backup\",\"ts\":$(date +%s)}]}" \ - "$SLACK_WEBHOOK_URL" > /dev/null || true -} - -backup_postgres() { - log_info "Starting PostgreSQL backup..." - - mkdir -p "$BACKUP_DIR/postgres" - local backup_file="$BACKUP_DIR/postgres/runebolt_${TIMESTAMP}.sql" - - if [[ "$DRY_RUN" == true ]]; then - log_info "[DRY RUN] Would backup PostgreSQL to $backup_file" - return 0 - fi - - export PGPASSWORD="$POSTGRES_PASSWORD" - - if ! pg_dump -h "$POSTGRES_HOST" -p "$POSTGRES_PORT" -U "$POSTGRES_USER" -d "$POSTGRES_DB" \ - --verbose --format=custom --file="$backup_file"; then - log_error "PostgreSQL backup failed" - send_notification "error" "PostgreSQL backup failed" - return 1 - fi - - unset PGPASSWORD - compress_and_upload "$backup_file" "postgres" - log_success "PostgreSQL backup completed" -} - -backup_redis() { - log_info "Starting Redis backup..." - - mkdir -p "$BACKUP_DIR/redis" - local backup_file="$BACKUP_DIR/redis/redis_${TIMESTAMP}.rdb" - - if [[ "$DRY_RUN" == true ]]; then - log_info "[DRY RUN] Would backup Redis to $backup_file" - return 0 - fi - - log_info "Triggering Redis BGSAVE..." - if [[ -n "$REDIS_PASSWORD" ]]; then - redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" -a "$REDIS_PASSWORD" BGSAVE - else - redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" BGSAVE - fi - - sleep 5 - local last_save current_save - while true; do - if [[ -n "$REDIS_PASSWORD" ]]; then - last_save=$(redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" -a "$REDIS_PASSWORD" LASTSAVE) - else - last_save=$(redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" LASTSAVE) - fi - sleep 2 - if [[ -n "$REDIS_PASSWORD" ]]; then - current_save=$(redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" -a "$REDIS_PASSWORD" LASTSAVE) - else - current_save=$(redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" LASTSAVE) - fi - [[ "$last_save" != "$current_save" ]] && break - done - - docker cp "runebolt-redis:/data/dump.rdb" "$backup_file" 2>/dev/null || \ - cp "$PROJECT_ROOT/redis-data/dump.rdb" "$backup_file" 2>/dev/null || \ - log_warn "Could not copy Redis RDB file directly" - - if [[ -f "$backup_file" ]]; then - compress_and_upload "$backup_file" "redis" - log_success "Redis backup completed" - else - log_warn "Redis backup file not created" - fi -} - -backup_sqlite() { - log_info "Starting SQLite backup..." - - mkdir -p "$BACKUP_DIR/sqlite" - local backup_file="$BACKUP_DIR/sqlite/runebolt_${TIMESTAMP}.db" - - if [[ "$DRY_RUN" == true ]]; then - log_info "[DRY RUN] Would backup SQLite to $backup_file" - return 0 - fi - - local sqlite_paths=( - "$PROJECT_ROOT/backend/data/runebolt.db" - "$PROJECT_ROOT/data/runebolt.db" - ) - - for db_path in "${sqlite_paths[@]}"; do - if [[ -f "$db_path" ]]; then - log_info "Backing up SQLite: $db_path" - - if command -v sqlite3 &> /dev/null; then - sqlite3 "$db_path" ".backup '$backup_file'" - else - cp "$db_path" "$backup_file" - fi - - compress_and_upload "$backup_file" "sqlite" - log_success "SQLite backup completed" - return 0 - fi - done - - log_warn "No SQLite database found to backup" -} - -backup_vault() { - log_info "Starting Vault backup..." - - mkdir -p "$BACKUP_DIR/vault" - local backup_file="$BACKUP_DIR/vault/vault_${TIMESTAMP}.snap" - - if [[ "$DRY_RUN" == true ]]; then - log_info "[DRY RUN] Would backup Vault to $backup_file" - return 0 - fi - - if ! curl -sf http://localhost:8200/v1/sys/health &> /dev/null; then - log_warn "Vault is not accessible, skipping backup" - return 0 - fi - - local vault_token="${VAULT_TOKEN:-root}" - - if curl -sf -H "X-Vault-Token: $vault_token" \ - http://localhost:8200/v1/sys/storage/raft/snapshot -o "$backup_file"; then - - compress_and_upload "$backup_file" "vault" - log_success "Vault backup completed" - else - log_warn "Vault snapshot failed" - fi -} - -cleanup_backups() { - log_info "Cleaning up backups older than $BACKUP_RETENTION_DAYS days..." - - if [[ "$DRY_RUN" == true ]]; then - log_info "[DRY RUN] Would clean up old backups" - return 0 - fi - - find "$BACKUP_DIR" -type f -name "*.tar.gz" -mtime +$BACKUP_RETENTION_DAYS -delete - log_success "Cleanup completed" -} - -main() { - log_info "RuneBolt Backup Script v1.0.0" - - case "$COMMAND" in - full) - backup_postgres - backup_redis - backup_sqlite - backup_vault - cleanup_backups - send_notification "success" "Full backup completed successfully" - ;; - postgres) - backup_postgres - send_notification "success" "PostgreSQL backup completed" - ;; - redis) - backup_redis - send_notification "success" "Redis backup completed" - ;; - sqlite) - backup_sqlite - send_notification "success" "SQLite backup completed" - ;; - vault) - backup_vault - send_notification "success" "Vault backup completed" - ;; - cleanup) - cleanup_backups - ;; - *) - log_error "Unknown command: $COMMAND" - usage - exit 1 - ;; - esac - - log_success "Backup process completed!" -} - -main "$@" diff --git a/legacy/taproot-assets-era/scripts/deploy.sh b/legacy/taproot-assets-era/scripts/deploy.sh deleted file mode 100755 index 6b6fce6..0000000 --- a/legacy/taproot-assets-era/scripts/deploy.sh +++ /dev/null @@ -1,426 +0,0 @@ -# RuneBolt Production Deployment Script -# Version: 1.0.0 -# Usage: ./scripts/deploy.sh [staging|production] [version] - -#!/bin/bash - -set -euo pipefail - -# ============================================ -# Configuration -# ============================================ -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" -APP_NAME="runebolt" -REGISTRY="ghcr.io/bitmap-asset" - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' # No Color - -# ============================================ -# Logging Functions -# ============================================ -log_info() { - echo -e "${BLUE}[INFO]${NC} $1" -} - -log_success() { - echo -e "${GREEN}[SUCCESS]${NC} $1" -} - -log_warn() { - echo -e "${YELLOW}[WARN]${NC} $1" -} - -log_error() { - echo -e "${RED}[ERROR]${NC} $1" -} - -# ============================================ -# Usage -# ============================================ -usage() { - cat << EOF -RuneBolt Deployment Script - -Usage: $0 [OPTIONS] [version] - -Arguments: - environment Target environment: staging, production, or canary - version Docker image version/tag (default: latest) - -Options: - -h, --help Show this help message - -f, --force Skip confirmation prompts - -s, --skip-tests Skip smoke tests after deployment - -r, --rollback Rollback to previous version - -c, --canary Deploy as canary (5% traffic) - -Examples: - $0 staging # Deploy latest to staging - $0 production v1.2.3 # Deploy v1.2.3 to production - $0 production --canary # Deploy as canary - $0 production --rollback # Rollback production - $0 production v1.2.3 --force # Deploy without confirmation - -EOF -} - -# ============================================ -# Parse Arguments -# ============================================ -ENVIRONMENT="" -VERSION="latest" -FORCE=false -SKIP_TESTS=false -ROLLBACK=false -CANARY=false - -while [[ $# -gt 0 ]]; do - case $1 in - -h|--help) - usage - exit 0 - ;; - -f|--force) - FORCE=true - shift - ;; - -s|--skip-tests) - SKIP_TESTS=true - shift - ;; - -r|--rollback) - ROLLBACK=true - shift - ;; - -c|--canary) - CANARY=true - shift - ;; - staging|production|canary) - ENVIRONMENT="$1" - shift - ;; - *) - if [[ -z "$VERSION" || "$VERSION" == "latest" ]]; then - VERSION="$1" - fi - shift - ;; - esac -done - -# Validate environment -if [[ -z "$ENVIRONMENT" ]]; then - log_error "Environment is required. Use 'staging' or 'production'" - usage - exit 1 -fi - -# ============================================ -# Load Environment Configuration -# ============================================ -load_env_config() { - local env_file="$PROJECT_ROOT/.env.$ENVIRONMENT" - - if [[ -f "$env_file" ]]; then - log_info "Loading environment config from $env_file" - # shellcheck source=/dev/null - source "$env_file" - else - log_warn "Environment file $env_file not found, using defaults" - fi - - # Set defaults - DEPLOY_HOST="${DEPLOY_HOST:-}" - DEPLOY_USER="${DEPLOY_USER:-runebolt}" - DEPLOY_PATH="${DEPLOY_PATH:-/opt/runebolt}" - COMPOSE_FILE="${COMPOSE_FILE:-docker-compose.prod.yml}" -} - -# ============================================ -# Pre-deployment Checks -# ============================================ -pre_deployment_checks() { - log_info "Running pre-deployment checks..." - - # Check if we're in the right directory - if [[ ! -f "$PROJECT_ROOT/$COMPOSE_FILE" ]]; then - log_error "Docker Compose file not found: $COMPOSE_FILE" - exit 1 - fi - - # Check if Docker is available - if ! command -v docker &> /dev/null; then - log_error "Docker is not installed or not in PATH" - exit 1 - fi - - # Check if docker compose is available - if ! docker compose version &> /dev/null; then - log_error "Docker Compose is not available" - exit 1 - fi - - # Check if required env vars are set - if [[ -z "${JWT_SECRET:-}" ]]; then - log_warn "JWT_SECRET not set in environment" - fi - - if [[ -z "${POSTGRES_PASSWORD:-}" ]]; then - log_warn "POSTGRES_PASSWORD not set in environment" - fi - - log_success "Pre-deployment checks passed" -} - -# ============================================ -# Confirm Deployment -# ============================================ -confirm_deployment() { - if [[ "$FORCE" == true ]]; then - return 0 - fi - - echo "" - echo "========================================" - echo "Deployment Configuration:" - echo "========================================" - echo "Environment: $ENVIRONMENT" - echo "Version: $VERSION" - echo "Canary: $CANARY" - echo "Rollback: $ROLLBACK" - echo "Host: ${DEPLOY_HOST:-localhost}" - echo "========================================" - echo "" - - if [[ "$ENVIRONMENT" == "production" && "$ROLLBACK" == false ]]; then - log_warn "You are about to deploy to PRODUCTION!" - read -p "Are you sure you want to continue? (yes/no): " confirm - if [[ "$confirm" != "yes" ]]; then - log_info "Deployment cancelled" - exit 0 - fi - else - read -p "Continue with deployment? (yes/no): " confirm - if [[ "$confirm" != "yes" ]]; then - log_info "Deployment cancelled" - exit 0 - fi - fi -} - -# ============================================ -# Deploy Function -# ============================================ -deploy() { - log_info "Starting deployment to $ENVIRONMENT..." - - export VERSION="$VERSION" - - # Pull latest images - log_info "Pulling Docker images..." - docker pull "$REGISTRY/$APP_NAME-backend:$VERSION" || log_warn "Backend image pull failed, will use local" - docker pull "$REGISTRY/$APP_NAME-frontend:$VERSION" || log_warn "Frontend image pull failed, will use local" - - # Deploy with Docker Compose - log_info "Deploying services..." - cd "$PROJECT_ROOT" - - if [[ "$CANARY" == true ]]; then - log_info "Deploying canary version (5% traffic)..." - # Deploy only one replica of backend as canary - docker compose -f "$COMPOSE_FILE" up -d backend-api-canary --no-deps - else - docker compose -f "$COMPOSE_FILE" up -d --remove-orphans - fi - - # Wait for services to start - log_info "Waiting for services to start..." - sleep 10 - - # Check service health - log_info "Checking service health..." - check_health - - log_success "Deployment to $ENVIRONMENT completed successfully!" -} - -# ============================================ -# Check Health -# ============================================ -check_health() { - local max_attempts=30 - local attempt=1 - - while [[ $attempt -le $max_attempts ]]; do - log_info "Health check attempt $attempt/$max_attempts..." - - # Check backend API - if curl -sf http://localhost:3001/health > /dev/null 2>&1; then - log_success "Backend API is healthy" - - # Check frontend - if curl -sf http://localhost:3000/health > /dev/null 2>&1; then - log_success "Frontend is healthy" - return 0 - fi - fi - - sleep 2 - ((attempt++)) - done - - log_error "Health checks failed after $max_attempts attempts" - - # Show container logs - log_info "Container logs:" - docker compose -f "$COMPOSE_FILE" logs --tail=50 backend-api || true - - exit 1 -} - -# ============================================ -# Smoke Tests -# ============================================ -smoke_tests() { - if [[ "$SKIP_TESTS" == true ]]; then - log_info "Skipping smoke tests" - return 0 - fi - - log_info "Running smoke tests..." - - # Test API health - if ! curl -sf http://localhost:3001/health > /dev/null; then - log_error "API health check failed" - return 1 - fi - - # Test API status endpoint - if ! curl -sf http://localhost:3001/api/status > /dev/null; then - log_warn "API status endpoint check failed" - fi - - # Test frontend - if ! curl -sf http://localhost:3000 > /dev/null; then - log_warn "Frontend check failed" - fi - - # Test database connectivity (via API) - if ! curl -sf http://localhost:3001/api/status | grep -q "database"; then - log_warn "Database connectivity check failed" - fi - - log_success "Smoke tests passed" -} - -# ============================================ -# Rollback Function -# ============================================ -rollback() { - log_warn "Initiating rollback..." - - # Get previous version from deployment log - local prev_version - if [[ -f "$PROJECT_ROOT/.deployment_log" ]]; then - prev_version=$(tail -2 "$PROJECT_ROOT/.deployment_log" | head -1 | cut -d',' -f2) - log_info "Rolling back to version: $prev_version" - else - log_error "No deployment log found, cannot determine previous version" - exit 1 - fi - - # Perform rollback - VERSION="$prev_version" deploy - - log_success "Rollback completed" -} - -# ============================================ -# Post-deployment Tasks -# ============================================ -post_deployment() { - log_info "Running post-deployment tasks..." - - # Cleanup old images - log_info "Cleaning up old Docker images..." - docker image prune -af --filter "until=168h" || true - - # Log deployment - echo "$(date -u +%Y-%m-%dT%H:%M:%SZ),$VERSION,$ENVIRONMENT,$CANARY" >> "$PROJECT_ROOT/.deployment_log" - - # Send notification (if configured) - if command -v curl &> /dev/null && [[ -n "${SLACK_WEBHOOK_URL:-}" ]]; then - send_notification - fi - - log_success "Post-deployment tasks completed" -} - -# ============================================ -# Send Notification -# ============================================ -send_notification() { - local status="success" - local color="good" - - if [[ "$ROLLBACK" == true ]]; then - status="rollback" - color="warning" - fi - - curl -s -X POST -H 'Content-type: application/json' \ - --data "{ - \"attachments\": [{ - \"color\": \"$color\", - \"title\": \"RuneBolt Deployment: $status\", - \"fields\": [ - {\"title\": \"Environment\", \"value\": \"$ENVIRONMENT\", \"short\": true}, - {\"title\": \"Version\", \"value\": \"$VERSION\", \"short\": true}, - {\"title\": \"Canary\", \"value\": \"$CANARY\", \"short\": true} - ], - \"footer\": \"RuneBot Deployment System\", - \"ts\": $(date +%s) - }] - }" \ - "$SLACK_WEBHOOK_URL" > /dev/null || true -} - -# ============================================ -# Main -# ============================================ -main() { - log_info "RuneBolt Deployment Script v1.0.0" - log_info "Target: $ENVIRONMENT, Version: $VERSION" - - load_env_config - - if [[ "$ROLLBACK" == true ]]; then - confirm_deployment - rollback - else - pre_deployment_checks - confirm_deployment - deploy - smoke_tests - post_deployment - fi - - echo "" - log_success "Deployment process completed!" - echo "" - echo "Useful commands:" - echo " View logs: docker compose -f $COMPOSE_FILE logs -f" - echo " Check status: docker compose -f $COMPOSE_FILE ps" - echo " Scale service: docker compose -f $COMPOSE_FILE up -d --scale backend-api=5" - echo "" -} - -# Run main -main "$@" diff --git a/legacy/taproot-assets-era/sdk/.gitignore b/legacy/taproot-assets-era/sdk/.gitignore deleted file mode 100644 index f06235c..0000000 --- a/legacy/taproot-assets-era/sdk/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules -dist diff --git a/legacy/taproot-assets-era/sdk/package-lock.json b/legacy/taproot-assets-era/sdk/package-lock.json deleted file mode 100644 index b87731a..0000000 --- a/legacy/taproot-assets-era/sdk/package-lock.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "name": "@runebolt/sdk", - "version": "0.1.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "@runebolt/sdk", - "version": "0.1.0", - "license": "MIT", - "dependencies": { - "ws": "^8.16.0" - }, - "devDependencies": { - "@types/node": "^20.10.0", - "@types/ws": "^8.5.10", - "typescript": "^5.3.3" - } - }, - "node_modules/@types/node": { - "version": "20.19.37", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.37.tgz", - "integrity": "sha512-8kzdPJ3FsNsVIurqBs7oodNnCEVbni9yUEkaHbgptDACOPW04jimGagZ51E6+lXUwJjgnBw+hyko/lkFWCldqw==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~6.21.0" - } - }, - "node_modules/@types/ws": { - "version": "8.18.1", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", - "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/ws": { - "version": "8.19.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", - "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", - "license": "MIT", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - } - } -} diff --git a/legacy/taproot-assets-era/sdk/package.json b/legacy/taproot-assets-era/sdk/package.json deleted file mode 100644 index 15dd9c5..0000000 --- a/legacy/taproot-assets-era/sdk/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "@runebolt/sdk", - "version": "0.1.0", - "description": "SDK for integrating RuneBolt instant DOG transfers", - "main": "dist/index.js", - "types": "dist/index.d.ts", - "scripts": { - "build": "tsc", - "dev": "tsc --watch" - }, - "dependencies": { - "ws": "^8.16.0" - }, - "devDependencies": { - "typescript": "^5.3.3", - "@types/ws": "^8.5.10", - "@types/node": "^20.10.0" - }, - "files": ["dist"], - "license": "MIT" -} diff --git a/legacy/taproot-assets-era/sdk/src/RuneBoltClient.ts b/legacy/taproot-assets-era/sdk/src/RuneBoltClient.ts deleted file mode 100644 index 14ee513..0000000 --- a/legacy/taproot-assets-era/sdk/src/RuneBoltClient.ts +++ /dev/null @@ -1,202 +0,0 @@ -import WebSocket from 'ws'; -import { RuneBoltConfig, Channel, Transfer, Balance, TransferEvent, ApiResponse, ChannelState } from './types'; - -export class RuneBoltClient { - private config: RuneBoltConfig; - private ws: WebSocket | null = null; - private transferListeners: ((event: TransferEvent) => void)[] = []; - private reconnectTimer: NodeJS.Timeout | null = null; - private isConnecting = false; - - constructor(config: RuneBoltConfig) { - this.config = { - wsUrl: config.apiUrl.replace(/^http/, 'ws'), - ...config, - }; - } - - // Set auth token after authentication - setAuthToken(token: string): void { - this.config.authToken = token; - } - - // Initialize a payment channel - async initChannel(pubkey: string, amount: string): Promise<{ channelId: string; psbt: string; channelAddress: string }> { - const res = await this.request<{ channelId: string; psbt: string; channelAddress: string }>('/channel/open', { - method: 'POST', - body: { pubkey, amount }, - }); - return res; - } - - // Activate channel after user signs the funding PSBT - async activateChannel(channelId: string, signedPsbt: string): Promise { - return this.request('/channel/activate', { - method: 'POST', - body: { channelId, signedPsbt }, - }); - } - - // Send DOG to another user - async sendDOG(params: { fromChannelId: string; recipientPubkey?: string; toChannelId?: string; amount: string; memo?: string }): Promise { - return this.request('/transfer', { - method: 'POST', - body: params, - }); - } - - // Get balance across all channels - async getBalance(pubkey: string): Promise { - const user = await this.request<{ channels: Channel[] }>(`/user/${pubkey}`, { method: 'GET' }); - - const channels = user.channels || []; - const channelBalances = channels - .filter(c => c.state === ChannelState.OPEN) - .map(c => ({ - channelId: c.id, - local: c.localBalance, - remote: c.remoteBalance, - capacity: c.capacity, - })); - - const available = channelBalances.reduce((sum, c) => sum + BigInt(c.local), 0n).toString(); - const locked = channelBalances.reduce((sum, c) => sum + BigInt(c.capacity), 0n).toString(); - - return { - available, - locked, - total: available, - channels: channelBalances, - }; - } - - // Get channel info - async getChannel(channelId: string): Promise { - return this.request(`/channel/${channelId}`, { method: 'GET' }); - } - - // Get transfer history - async getHistory(pubkey: string, limit = 50, offset = 0): Promise { - return this.request(`/history/${pubkey}?limit=${limit}&offset=${offset}`, { method: 'GET' }); - } - - // Close a channel cooperatively - async closeChannel(channelId: string): Promise<{ psbt: string }> { - return this.request<{ psbt: string }>('/channel/close', { - method: 'POST', - body: { channelId }, - }); - } - - // Create a claim link - async createClaimLink(amount: string, memo?: string): Promise<{ claimId: string; url: string }> { - return this.request<{ claimId: string; url: string }>('/claim/create', { - method: 'POST', - body: { amount, memo }, - }); - } - - // Subscribe to real-time transfer events - onTransfer(callback: (event: TransferEvent) => void): () => void { - this.transferListeners.push(callback); - - // Start WebSocket if not connected - if (!this.ws && !this.isConnecting) { - this.connectWebSocket(); - } - - // Return unsubscribe function - return () => { - this.transferListeners = this.transferListeners.filter(cb => cb !== callback); - if (this.transferListeners.length === 0) { - this.disconnectWebSocket(); - } - }; - } - - // Connect WebSocket for real-time events - private connectWebSocket(): void { - if (this.isConnecting || !this.config.wsUrl) return; - this.isConnecting = true; - - const url = new URL(this.config.wsUrl); - if (this.config.authToken) { - url.searchParams.set('token', this.config.authToken); - } - - this.ws = new WebSocket(url.toString()); - - this.ws.on('open', () => { - this.isConnecting = false; - console.log('[RuneBolt SDK] WebSocket connected'); - }); - - this.ws.on('message', (data: Buffer) => { - try { - const event = JSON.parse(data.toString()); - if (event.type === 'transfer') { - this.transferListeners.forEach(cb => cb(event.data as TransferEvent)); - } - } catch (err) { - console.error('[RuneBolt SDK] Failed to parse WebSocket message:', err); - } - }); - - this.ws.on('close', () => { - this.isConnecting = false; - this.ws = null; - // Auto-reconnect if there are active listeners - if (this.transferListeners.length > 0) { - this.reconnectTimer = setTimeout(() => this.connectWebSocket(), 3000); - } - }); - - this.ws.on('error', (err) => { - console.error('[RuneBolt SDK] WebSocket error:', err.message); - this.isConnecting = false; - }); - } - - private disconnectWebSocket(): void { - if (this.reconnectTimer) { - clearTimeout(this.reconnectTimer); - this.reconnectTimer = null; - } - if (this.ws) { - this.ws.close(); - this.ws = null; - } - } - - // Disconnect and clean up - disconnect(): void { - this.disconnectWebSocket(); - this.transferListeners = []; - } - - // Internal HTTP request helper - private async request(path: string, options: { method: string; body?: any }): Promise { - const url = `${this.config.apiUrl}/api/v1${path}`; - const headers: Record = { - 'Content-Type': 'application/json', - }; - - if (this.config.authToken) { - headers['Authorization'] = `Bearer ${this.config.authToken}`; - } - - const res = await fetch(url, { - method: options.method, - headers, - body: options.body ? JSON.stringify(options.body) : undefined, - }); - - const json: ApiResponse = await res.json() as ApiResponse; - - if (!json.success || !json.data) { - throw new Error(json.error || 'Request failed'); - } - - return json.data; - } -} diff --git a/legacy/taproot-assets-era/sdk/src/index.ts b/legacy/taproot-assets-era/sdk/src/index.ts deleted file mode 100644 index 43183ef..0000000 --- a/legacy/taproot-assets-era/sdk/src/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { RuneBoltClient } from './RuneBoltClient'; -export * from './types'; diff --git a/legacy/taproot-assets-era/sdk/src/types.ts b/legacy/taproot-assets-era/sdk/src/types.ts deleted file mode 100644 index d78b1d7..0000000 --- a/legacy/taproot-assets-era/sdk/src/types.ts +++ /dev/null @@ -1,57 +0,0 @@ -export interface RuneBoltConfig { - apiUrl: string; - wsUrl?: string; - authToken?: string; -} - -export interface Channel { - id: string; - userPubkey: string; - capacity: string; - localBalance: string; - remoteBalance: string; - state: ChannelState; - createdAt: string; -} - -export enum ChannelState { - PENDING_OPEN = 'PENDING_OPEN', - OPEN = 'OPEN', - CLOSING = 'CLOSING', - CLOSED = 'CLOSED', - FORCE_CLOSING = 'FORCE_CLOSING' -} - -export interface Transfer { - id: string; - fromChannel: string; - toChannel: string; - amount: string; - memo?: string; - createdAt: string; -} - -export interface Balance { - available: string; - locked: string; - total: string; - channels: ChannelBalance[]; -} - -export interface ChannelBalance { - channelId: string; - local: string; - remote: string; - capacity: string; -} - -export interface TransferEvent { - transfer: Transfer; - newBalance: Balance; -} - -export interface ApiResponse { - success: boolean; - data?: T; - error?: string; -} diff --git a/legacy/taproot-assets-era/sdk/tsconfig.json b/legacy/taproot-assets-era/sdk/tsconfig.json deleted file mode 100644 index 02520be..0000000 --- a/legacy/taproot-assets-era/sdk/tsconfig.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "module": "commonjs", - "lib": ["ES2020"], - "declaration": true, - "outDir": "dist", - "rootDir": "src", - "strict": true, - "esModuleInterop": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "moduleResolution": "node", - "resolveJsonModule": true - }, - "include": ["src"], - "exclude": ["node_modules", "dist"] -}