Commit Graph
100 Commits
Author SHA1 Message Date
zeekay 21da3d64e0 security: harden internal MPC API, enforce TLS-only transport, restrict egress
- Add bearer token auth to internal MPC API (port 9800): /keygen, /keys,
  /backup now require Authorization header. Token from MPC_INTERNAL_API_KEY
  env (KMS-synced) or derived from Ed25519 node identity.
- Replace DualModeListener with TLSOnlyListener: plaintext peer connections
  are rejected. TLS 1.3 with PQ key exchange is mandatory.
- Add dedicated 20 RPM rate limiter on bridge signing and intent signing
  endpoints (separate from global 100 RPM).
- Add body size limit (1MB), read/write timeouts, and 10 RPM rate limiter
  to internal MPC API server.
- Restrict K8s NetworkPolicy egress for MPC nodes to peers, postgres,
  valkey, DNS, and HTTPS only (was unrestricted).
- Wire cluster-api-key in api-deployment for authenticated proxy to
  internal MPC API. Forward as Authorization: Bearer header.
- Remove hardcoded dev JWT_SECRET default from compose.yml (now required).
- Add internal-api-key to KMSSecret CRD and StatefulSet env.
2026-04-07 14:00:47 -07:00
zeekay 4decb5c091 feat: Base framework + consensus default + minimal ops
- Mount chi handlers on Hanzo Base (lifecycle, health, auth framework)
- Default mode: consensus (ZAP p2p) — NATS/Consul deprecated
- compose.yml: 2 services (api + dashboard), SQLite, no external DB
- config.yaml: consensus mode, SQLite-first
- Makefile: simplified build targets, docker compose format
- K8s: kustomization.yaml for idempotent deploys
- Removed listenAddr from NewServer (Base handles listening)
- Legacy NATS/Consul preserved but not default
2026-04-07 01:18:53 -07:00
zeekay 60fc83b28d fix: remove /api/ prefix from all routes — use /v1/ only
Subdomain routing (mpc.lux.network/v1/) not path prefix (/api/v1/).
Updated: server routes, KMS routes, main.go forwarding, compose,
K8s dashboard config, ingressroute, landing page HTML.
2026-04-07 00:01:47 -07:00
zeekay 04f303dcb2 security: fix 15 custody audit findings, add regression + fuzz tests
Fixes all findings from the Blue Team defensive security review of the
Satschel → Liquidity.io custody architecture transition.

HIGH:
- S-1: Implement P-256 ECDH + AES-256-GCM encryption of passkey backup shards
- W-2: Reject unparseable WebAuthn public keys (was silently skipping verification)
- O-1: Add Ed25519 binary signature verification package (pkg/integrity)

MEDIUM:
- W-1: Validate attestation is a real P-256 curve point, not raw attestation object
- W-3: Add origin validation to all WebAuthn flows (register, verify, trade approve)
- N-2: Remove plaintext TCP fallback from MPC node transport (TLS mandatory)
- K-1: Fail-closed on empty/whitespace orgID (prevents cross-tenant key leakage)
- A-1: Make AuditEntry immutable (Update/Delete return error)
- A-2: Add MPC-level signing audit log (wallet, message hash, intent, trigger)
- O-3: Invalidate backup shards after key reshare (stale shares are useless)
- O-2: Reject env/file password providers in production (require cloud HSM)

LOW:
- T-1: Add error handling + MarkSignFailed to signing goroutine
- T-2: Verify caller authorization in handleTradeSubmit
- K-2: Secret erasure stub now calls runtime.GC() instead of no-op
- N-1: Add VerifyConnection callback to reject peers without TLS certs

Tests: 69 unit + 7 fuzz targets, ~900K fuzz executions, 19/19 packages green.
Makefile: add -tags json1 for SQLite JSON function support in ORM tests.
2026-04-01 09:00:06 -07:00
zeekay 0e90ba3d15 fix: per-org MPC isolation — orgID end-to-end threading + security hardening
- M-1 CRITICAL: Remove legacy key share fallback (cross-tenant leak)
- M-2 HIGH: orgID now required string on all Node methods (not variadic)
- M-3 HIGH: Key material zeroing after signing sessions
- Thread orgID through MPCBackend interface, all API handlers
- Reshare + TFHE sessions use OrgScopedKey for reads/writes
- Remove hardcoded JWT default (fail-hard if not set)
- Add warning log for empty orgID legacy path
- Regression tests: TestGetKeyShareWithFallback_M1_CrossTenantLeak
2026-03-24 16:55:54 -07:00
zeekay 913dfd3778 fix: goimports formatting with local-prefixes (matches golangci-lint) 2026-03-22 13:17:50 -07:00
zeekay cb1bc5ecbc security: add orgID multi-tenancy isolation, rename badger to zapdb
Multi-tenancy isolation (addresses Dragonfire review MPC audit):
- Add OrgID field to all event messages (keygen, sign, reshare)
- Scope session dedup keys as orgID-walletID-txID
- Namespace KVStore keys with org prefix (org:<orgID>:<key>)
- Backward-compatible fallback to legacy unscoped keys
- New org_kvstore.go with OrgScopedKey/GetKeyShareWithFallback

Naming cleanup:
- Rename all badger references to zapdb in code, config, tests
- config.yaml: badger_password → zapdb_password
- AppConfig: BadgerPassword → ZapDBPassword
- Fix MPCiumVersion typo → MPCVersion
2026-03-22 12:02:30 -07:00
zeekay c7f126adbf feat: BLS threshold + security hardening + ZapDB KMS-backing
Security (from red team review):
- Replay protection: request_id + timestamp freshness on sign API
- Ed25519 message auth re-enabled on all protocol messages
- DKG timeout (5min) + signing timeout (30s) with watchdog
- Dedup map TTL cleanup (10min expiry, 2min sweep)

BLS threshold signing:
- KeyTypeBLS + keygen/signing sessions
- TrustedDealer pattern for BLS DKG
- CBOR serialization for BLS config
- 8 tests

ZapDB KMS-backing:
- HSM PasswordProvider wired to ZapDB init
- Supports: AWS KMS, GCP KMS, Azure KV, env, file
- Default env for backward compat
- 19 tests

Also: sr25519 sessions, fixed SignWireMessage build break
2026-03-19 01:15:33 -07:00
zeekay bdd4d05ab0 Wire HSM threshold attestation into MPC daemon
- Add --hsm-attest / MPC_HSM_ATTEST flag for share attestation
- Add --hsm-signer / --hsm-signer-key-id flags for co-signing
- KeyShareVault initialized when attestation enabled
- Bump github.com/luxfi/hsm v1.0.0 → v1.1.0
2026-03-02 23:52:08 -08:00
zeekay 45721d9485 feat: multi-chain address derivation (BTC, SOL), fix policy engine
- Derive Bitcoin P2PKH address from secp256k1 ECDSA pubkey
- Derive Solana address from Ed25519 pubkey (base58)
- Fix loadPolicies: gracefully return empty list instead of error
  when no policies exist (was causing "failed to load policies" error)
- Filter enabled policies in-memory (JSONB boolean filter unreliable)
- Add BTC/SOL address fields to KeygenResult and wallet creation
- Update /info endpoint with full chain support matrix
- Map EVM-compatible chains (Lux, XRP) and Ed25519 chains (TON)
2026-02-24 23:19:15 -08:00
zeekay 45b89f9f86 fix: derive eth_address from 32-byte ECDSA keys, return int for connected_peers
- /health returns connected_peers as int (count) not string array
- /keygen derives eth_address from 32-byte keys (was >= 33, now >= 32)
- Skip initiator verification when no explicit key configured (consensus mode)
2026-02-24 23:02:25 -08:00
zeekay f8a232a907 fix: sign keygen/sign messages in consensus mode, fix API proxy paths
- ConsensusIdentityStore now uses node's own key as initiator key when
  no explicit event_initiator_pubkey is configured (consensus mode)
- /keygen HTTP endpoint signs GenerateKeyMessage with node's Ed25519 key
- ConsensusMPCBackend.TriggerKeygen/TriggerSign sign messages before publish
- apiOnlyMPCBackend forwards to /keygen and /health (internal API paths)
  instead of /api/v1/keygen and /api/v1/status (dashboard API paths)
- mpc-api deployment points to port 9800 (internal API, no auth required)
  instead of port 8081 (dashboard API, auth required)
- /health response uses snake_case keys matching ClusterStatus JSON tags
2026-02-23 22:44:17 -08:00
zeekay a7152aaa0b fix(ci): goimports formatting, no-panic logger test, remove unconvert
- goimports -w on all pkg/api, pkg/db, cmd/mpcd files
- TestError_PanicsOnOddKeyValues → TestError_OddKeyValuesLogsWarning
  (logger was intentionally changed to warn+sentinel instead of panic)
- int(threshold) → threshold (threshold is already int from c.Int())
2026-03-01 18:40:56 -08:00
zeekay fa1466abd9 refactor(kvstore): rename Badger→ZapDB types, clean up package API
- git mv badger.go→zapdb.go, badger_backup.go→zap_backup.go
- BadgerKVStore→Store, BadgerConfig→Config, NewBadgerKVStore→New
- BadgerBackupExecutor→Backup, NewBadgerBackupExecutor→NewBackup
- BadgerBackupMeta→BackupMeta, BadgerBackupVersionInfo→BackupVersion
- Config fields: DBPath→Path, EncryptionKey→Key, BackupEncryptionKey→BackupKey, BackupDir→Dir
- Backup fields: BackupEncryptionKey→Key, BackupDir→Dir
- Store fields: BackupExecutor→Exec, db→DB (exported, fixes e2e compile)
- Updated all callers: transport/factory, transport/state, backup/s3,
  cmd/mpcd/main, cmd/lux-mpc-cli/recovery, scripts/migration/add-key-type,
  e2e/base_test, pkg/kvstore/backup_test
2026-03-01 18:33:01 -08:00
zeekay 0c2a896d67 feat(mpc): key listing, KMS backup/restore, API-only backend, CGGMP21 config serialization 2026-03-01 18:12:18 -08:00
zeekay e0f42e0542 fix(security): Ed25519 initiator verification, proper share verification, no panics
- ConsensusIdentityStore.VerifyInitiatorMessage: implement real Ed25519
  signature verification using the configured event_initiator_pubkey
  instead of blindly accepting all messages
- cggmp21Aggregator.VerifyShare: implement ECDSA partial signature
  verification using secp256k1 curve arithmetic (R' = u1*G + u2*Y_i,
  check R'.x == r mod n) against the party's public key share
- frostAggregator.VerifyShare: implement Schnorr/BIP-340 partial
  signature verification (compute R_i = s_i*G - c*Y_i, verify on curve)
- logger.Error: replace panic on odd keyValues with warning log and
  sentinel value to avoid crashing production
- session.ProcessInboundMessage/ProcessOutboundMessage: replace panics
  with error log and graceful no-op for unoverridden base methods
- eddsaReshareSession: implement ProcessInboundMessage (unmarshal wire
  format, dedup, route to FROST party) and ProcessOutboundMessage (read
  from party Messages channel, wrap in wire format, send)
- cggmp21ReshareSession: implement matching message handlers
- eddsaReshareSession.Reshare: extract actual Ed25519 public key from
  FROST result via GetPublicKeyBytes() instead of empty placeholder
2026-03-01 18:08:14 -08:00
zeekay a509333af0 feat(hsm): AWS/GCP/Azure KMS password providers, CREATE2 address prediction
- Implement CREATE2 address prediction in PredictAccountAddress() using
  keccak256(0xff ++ factory ++ salt ++ keccak256(initCode))[12:] formula.
  Also add general-purpose PredictCreate2Address() with raw [20]byte params.

- Create pkg/hsm package with PasswordProvider interface and 5 implementations:
  - AWSKMSProvider: decrypts ZAPDB_ENCRYPTED_PASSWORD via AWS KMS Decrypt API
    with full SigV4 signing and EC2 instance metadata credential fallback
  - GCPKMSProvider: decrypts via GCP Cloud KMS REST API with GCE metadata OAuth2
  - AzureKVProvider: unwraps via Azure Key Vault REST API with MSI token auth
  - EnvProvider: reads from LUX_MPC_PASSWORD/ZAPDB_PASSWORD env vars (default)
  - FileProvider: reads from file (K8s mounted secrets)

- Add NewPasswordProvider factory (pkg/hsm/factory.go) driven by MPC_HSM_PROVIDER
  env var (values: aws, gcp, azure, env, file)

- Wire HSM provider into mpcd consensus startup, replacing direct env var read
  with graceful fallback chain: HSM provider -> viper config -> dev default

- Add --hsm-provider and --hsm-key-id CLI flags with MPC_HSM_PROVIDER/MPC_HSM_KEY_ID
  env var sources

- 25 tests passing (9 smart + 16 HSM)
2026-03-01 18:05:47 -08:00
zeekay 2e92b3ffa3 refactor: use luxfi/database abstraction for KV storage, rename BadgerDB→ZapDB
- Replace direct github.com/luxfi/zapdb/v4 imports with github.com/luxfi/database
  abstraction in pkg/kvstore/ (zapdb.New + encdb.New for encryption)
- BadgerKVStore now uses database.Database interface internally — backend is
  pluggable (zapdb/leveldb/memdb) without changing MPC code
- Remove custom badger_logger.go (database module handles its own logging)
- Update BadgerBackupExecutor to use database.Database instead of *badger.DB;
  RestoreAllBackupsEncrypted loads into raw zapdb (values are already
  individually encrypted by encdb)
- Rewrite backup_test.go to use KVStore interface instead of raw badger API
- Update migration script to use KVStore Put/Get/Delete/Keys instead of txn API
- Rename all user-visible "BadgerDB"/"Badger" strings to "ZapDB" in logs,
  prompts, and comments across cmd/mpcd/main.go, pkg/kvstore/, pkg/transport/
- Fix backup_test.go type reference: badgerBackupExecutor→BadgerBackupExecutor
  (resolves CI test and lint failures)
2026-03-01 16:00:07 -08:00
zeekay df84005b46 feat: replace BadgerDB with ZapDB, remove local replace directives, vendor mode CI/CD
- Replace github.com/dgraph-io/badger/v4 with github.com/luxfi/zapdb/v4 v4.9.2
  throughout pkg/kvstore/, pkg/transport/, cmd/mpcd/, e2e/, scripts/
- Rename BadgerPath/BadgerPassword → ZapDBPath/ZapDBPassword in FactoryConfig
- Remove local replace directives from go.mod:
  - hanzoai/orm: now uses published v0.3.2 (tagged on GitHub)
  - hanzoai/kv-go/v9: now uses published v9.17.2-hanzo.1
  - Only remaining replace: agl/ed25519 → luxfi/edwards25519
- Add vendor/ directory (GOWORK=off go mod vendor) for reproducible builds
- Update Dockerfile to golang:1.26-alpine + -mod=vendor build flag
- Update CI/CD to use self-hosted linux/amd64 runners (no cross-compilation)
- Add k8s/valkey.yaml for session KV store
- Update k8s manifests: api-kv support, ZapDB password env, fresh secrets
- Dashboard API and MPC nodes all tested running on cluster (3/3 nodes healthy)
2026-03-01 15:27:32 -08:00
zeekay 1d81ef8910 fix: subscribe to correct signing result topic and parse byte fields
TriggerSign was subscribing to mpc_signing_result.{txID} but the
signing session publishes to mpc_signing_result.{walletID}. Also
fixed result parsing: R/S are []byte (base64 in JSON), not hex strings.
2026-03-01 05:52:45 -08:00
zeekay 0db75edc2b fix: populate ParticipantPeerIDs in ConsensusKeyInfoStore for signing
ConsensusKeyInfoStore.Get() was returning empty ParticipantPeerIDs,
causing "Not enough participants to sign" errors. Now populates from
peer registry's ready peers list.
2026-03-01 05:34:02 -08:00
zeekay da6187fe72 fix: normalize ecdsa->secp256k1 key type in signing requests 2026-03-01 05:24:49 -08:00
zeekay 061fa5356c fix: register key type as secp256k1 (not ecdsa) for CGGMP21 signing 2026-03-01 05:17:41 -08:00
zeekay 864b6c217d fix: pass key type in signing requests, increase API timeout to 120s
- TriggerSign now looks up key type from keyInfoStore (was empty, causing
  "CGGMP21 only supports Secp256k1" errors)
- Wire keyInfoStore into ConsensusMPCBackend
- Increase HTTP middleware timeout from 30s to 120s for MPC signing
2026-03-01 05:10:49 -08:00
zeekay c4a3a7b679 fix: derive ETH addresses from 32-byte ECDSA x-coordinates
CGGMP21 keygen returns 32-byte x-coordinate, not 33-byte compressed key.
Added secp256k1 point decompression (y² = x³ + 7 mod p) to recover the
full uncompressed public key for keccak256 address derivation.
2026-02-28 14:15:03 -08:00
zeekay 704959e846 feat: add standalone api subcommand for dashboard-only deployment
mpcd api --db $DATABASE_URL --jwt-secret $JWT_SECRET --listen :8081

Runs the Dashboard API server without MPC transport, suitable for
cloud dashboard deployments where MPC operations are handled by
separate MPC nodes.
2026-02-28 13:41:12 -08:00
zeekay f110e06800 feat: MPC wallet dashboard - full-stack implementation
Complete MPC wallet management platform rivaling Fireblocks/Utila/Fordefi:

Backend (Go):
- REST API with 60+ endpoints on chi router (pkg/api/)
- PostgreSQL schema with 13 tables (pkg/db/)
- JWT + MFA auth, bcrypt passwords, API key management
- Policy engine (deny/approve/require_approval)
- Transaction signing flow with approval workflow
- Subscription scheduler for recurring payments
- Payment requests with public pay pages
- Safe + ERC-4337 smart wallet integration (pkg/smart/)
- Rate limiting, webhook delivery (HMAC-SHA256), audit logging
- 27 passing tests (auth, policy engine, middleware)

Frontend (Next.js 14):
- 27 routes with monochrome dark theme (Tailwind + Geist fonts)
- Full API client with JWT auto-refresh
- React Query hooks for all resources
- Pages: dashboard, vaults, wallets, transactions, policies,
  whitelist, team, settings, API keys, webhooks, audit,
  subscriptions, payments, smart wallets

Infrastructure:
- Dockerfiles for API (Go) and dashboard (Next.js standalone)
- compose.yml for local development (PostgreSQL + API + dashboard)
- K8s manifests for mpc.lux.network + cloud.lux.network
- GitHub Actions deploy workflow (build → push GHCR → kubectl apply)
- TLS via cert-manager, Traefik IngressRoute for both domains
2026-02-28 13:27:34 -08:00
zeekay 113615960a feat: add /keygen HTTP endpoint, PubSub self-delivery, increase keygen timeout
- Add POST /keygen endpoint for triggering MPC keygen via HTTP API
- Fix PubSub self-delivery: Publish now delivers to local subscribers
  before broadcasting to peers (required for consensus mode keygen)
- Increase KeyGenTimeOut from 30s to 120s (Paillier prime generation
  takes 6-15s per node, multi-round protocol needs more time)
- Add pubKeyToEthAddress helper for deriving ETH addresses from ECDSA keys
- Bump version to 0.3.3
2026-02-27 22:25:09 -08:00
zeekay db4c7ea771 feat: add S3 backup integration, keepalive pings, and connection stability
- Add S3 backup manager (pkg/backup/s3.go) for periodic encrypted BadgerDB
  backups with upload to S3-compatible storage (MinIO)
- Add 30s keepalive pings in transport layer to prevent idle read timeouts
- Increase read timeout from 30s to 5 minutes
- Add connection tie-breaking for simultaneous peer connections (lower node
  ID keeps outbound) to prevent connection storms
- Add pointer-specific peer removal (removePeerConn) to prevent orphaned
  goroutines from removing replacement connections
- Export BadgerBackupExecutor type for use by backup package
- Add /backup HTTP endpoint for on-demand backup triggers
- Bump version to 0.3.2
2026-02-27 21:59:49 -08:00
zeekay 9abd19cf43 fix: lint issues - goimports formatting and unnecessary conversion
- Update .golangci.yml to v2 format with formatters section
- Fix goimports for local package grouping (tfhe_session.go, crypto_adapter.go, manager_test.go)
- Remove unnecessary int() conversion in mpcd main.go
2026-02-05 16:56:51 -08:00
zeekay f8f75c732b chore: sync dependencies and format code 2026-02-04 15:47:51 -08:00
zeekay 821bd09da5 chore: remove bridge stub, fix all TODOs with real implementations
- Remove lux-mpc-bridge command (bridge is in T-Chain, not MPC)
- Remove empty pkg/bridge directory
- Fix sign.go: remove stale TODO (ECDSA/EdDSA already supported)
- Fix pubsub.go: remove obsolete subscription TODO
- Fix benchmark_test.go: implement real protocol benchmarks
- Fix xrpl_test.go: implement full XRPL E2E tests
- Update goreleaser: remove bridge build target
- Update docker-compose: remove bridge-compat services

MPC is now a clean standalone threshold signature tool.
2025-12-25 10:44:16 -08:00
zeekay ad3fe8a963 Update scripts, kms integration 2025-08-04 02:21:17 -05:00
zeekay 120566472b Fix final import formatting issues
- Fix imports in cmd and scripts directories
- Ensure consistent import grouping across all Go files
2025-08-02 22:33:01 -05:00
zeekay 721db3ec4a Fix linting issues
- Fix import formatting with goimports
- Remove unnecessary type conversions for syscall.Stdin
- Format imports with correct grouping
2025-08-02 22:27:51 -05:00
zeekay a4385c4754 Fix linting issues and Go version compatibility
- Remove unused imports (os/signal, syscall)
- Fix unused variable warning (msgBytes)
- Set Go version to 1.21 for CI compatibility
2025-08-02 22:21:09 -05:00
zeekay babf7e2c71 Fix CI build errors
- Remove local replace directive for threshold library
- Fix unused directMessaging variable warning
- Replace undefined logger.NewLogger with zap.NewProduction
- Fix GetMessage method call to use Raw()
- Mark bridge implementation as TODO
2025-08-02 22:17:16 -05:00
zeekay 0b8661ced9 Use new threshold lib 2025-08-02 15:49:26 -05:00
zeekay 4ec50522c9 Add benchmarks, tests, updated docs 2025-08-02 15:27:50 -05:00
anhthii 6d96e51197 Enable backup mode by default 2025-07-29 15:57:54 +07:00
anhthii 0cce00a649 Bump version 2025-07-29 15:14:28 +07:00
anhthii 743da6ff42 Validate metadata length 2025-07-28 22:18:33 +07:00
anhthii c03e996579 Customized logger for badger 2025-07-28 21:51:42 +07:00
anhthii defa94434a Implement recovery command for mpcium-cli 2025-07-28 20:35:07 +07:00
anhthii 6d0c657338 Implement backup feature 2025-07-26 21:36:26 +07:00
anhthii df63284a9b Gracefully close consumers 2025-07-11 22:29:31 +07:00
Poseidon-Gandanhthii 160603f299 Remove jetstream pubsub change to message broker 2025-07-10 08:46:22 +07:00
anhthii fa8a42e010 Secure file permission 2025-07-06 15:16:15 +07:00
CodyandGitHub c6e2c3c06f Add integration, unit testing CI pipelines (#48)
* Add comprehensive tests for multiple pkg

* Add db_path to config

* Add e2e testing pipeline

* Add github workflow

* Remove config.test.yaml

* Fix lint issue

* Increase timeout

* Add e2e testing for signing

* Skip signing if node is not in participant list

* Code cleanup

* Add e2e testing for signing and resharing

* Increase timeout

* Add test instructions

* Update github workflow branching

* Add vulnerabilties check in CI

* Fix ci
2025-07-06 14:26:03 +07:00
anhthii f2aaedf8f8 Rename to improve consistent naming 2025-07-03 18:08:20 +07:00