diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..70128da --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,299 @@ +name: CI Pipeline + +on: + push: + branches: ["*"] + pull_request: + branches: ["*"] + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: "1.23" + + - name: Cache Go modules + uses: actions/cache@v3 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Install dependencies + run: go mod download + + - name: Run unit tests + run: go test -v -race -coverprofile=coverage.out ./... + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v4 + with: + file: ./coverage.out + flags: unittests + name: codecov-umbrella + + lint: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: "1.23" + + - name: Run golangci-lint + uses: golangci/golangci-lint-action@v3 + with: + version: latest + args: --timeout=5m + + # Security vulnerability scanning + security-scan: + runs-on: ubuntu-latest + name: Security Vulnerability Scan + permissions: + actions: read + contents: read + security-events: write + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: "1.23" + + - name: Cache Go modules + uses: actions/cache@v3 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Install dependencies + run: go mod download + + - name: Install govulncheck + run: go install golang.org/x/vuln/cmd/govulncheck@latest + + - name: Run govulncheck and fail if vulnerabilities are found + run: | + govulncheck -json ./... > vuln.json + count=$(jq '[.[] | select(.finding != null and .finding.trace != null)] | length' vuln.json || echo 0) + echo "Found $count vulnerabilities" + if [ "$count" -gt 0 ]; then + echo "โŒ Vulnerabilities found by govulncheck" + cat vuln.json + exit 1 + fi + + - name: Install gosec + run: go install github.com/securego/gosec/v2/cmd/gosec@latest + + - name: Run gosec security scanner + run: | + gosec -fmt sarif -out gosec-results.sarif ./... + continue-on-error: true + + - name: Upload gosec results to GitHub Security tab + uses: github/codeql-action/upload-sarif@v3 + if: always() + with: + sarif_file: gosec-results.sarif + category: gosec + + # CodeQL Analysis + codeql-analysis: + name: CodeQL Analysis + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: ["go"] + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + queries: +security-and-quality + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: "1.23" + + - name: Cache Go modules + uses: actions/cache@v3 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Install dependencies + run: go mod download + + - name: Build for CodeQL + run: | + go build -v ./cmd/mpcium + go build -v ./cmd/mpcium-cli + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 + with: + category: "/language:${{matrix.language}}" + + # SBOM Generation + sbom: + runs-on: ubuntu-latest + name: Generate SBOM + permissions: + actions: read + contents: read + security-events: write + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: "1.23" + + - name: Cache Go modules + uses: actions/cache@v3 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Install dependencies + run: go mod download + + - name: Build binaries + run: | + go build -o mpcium ./cmd/mpcium + go build -o mpcium-cli ./cmd/mpcium-cli + + - name: Generate SBOM with anchore/sbom-action (SPDX-JSON) + uses: anchore/sbom-action@v0 + with: + artifact-name: sbom-spdx.json + output-file: sbom.spdx.json + format: spdx-json + + - name: Generate SBOM with anchore/sbom-action (CycloneDX) + uses: anchore/sbom-action@v0 + with: + artifact-name: sbom-cyclonedx.json + output-file: sbom.cyclonedx.json + format: cyclonedx-json + upload-artifact: false + + - name: Generate SBOM with anchore/sbom-action (Syft JSON) + uses: anchore/sbom-action@v0 + with: + artifact-name: sbom-syft.json + output-file: sbom.syft.json + format: syft-json + upload-artifact: false + + - name: Upload all SBOM artifacts + uses: actions/upload-artifact@v4 + with: + name: sbom-files + path: | + sbom.spdx.json + sbom.cyclonedx.json + sbom.syft.json + retention-days: 30 + + - name: Install Grype + run: | + curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/bin + + - name: Scan SBOM with Grype + run: | + grype sbom.spdx.json -o sarif --file grype-results.sarif + continue-on-error: true + + - name: Upload Grype results to GitHub Security tab + uses: github/codeql-action/upload-sarif@v3 + if: always() + with: + sarif_file: grype-results.sarif + category: grype + + - name: Display SBOM summary + run: | + echo "๐Ÿ“ฆ SBOM Generation Summary" + echo "=========================" + echo "Generated SBOM files:" + ls -la sbom.* + echo "" + echo "SBOM package count:" + echo "SPDX: $(jq '.packages | length' sbom.spdx.json)" + echo "CycloneDX: $(jq '.components | length' sbom.cyclonedx.json)" + echo "Syft: $(jq '.artifacts | length' sbom.syft.json)" + + build: + runs-on: ubuntu-latest + needs: [test, lint, security-scan, codeql-analysis, sbom] + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: "1.23" + + - name: Cache Go modules + uses: actions/cache@v3 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Build mpcium + run: go build -v ./cmd/mpcium + + - name: Build mpcium-cli + run: go build -v ./cmd/mpcium-cli diff --git a/.github/workflows/e2e-tests.yml b/.github/workflows/e2e-tests.yml new file mode 100644 index 0000000..77d2ad1 --- /dev/null +++ b/.github/workflows/e2e-tests.yml @@ -0,0 +1,318 @@ +name: E2E Integration Tests + +on: + push: + branches: [master] + pull_request: + branches: [master] + +jobs: + # Build job that creates the binaries needed by all E2E test jobs + build: + runs-on: ubuntu-latest + outputs: + cache-key: ${{ steps.cache-key.outputs.key }} + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: "1.23" + + - name: Generate cache key + id: cache-key + run: echo "key=${{ runner.os }}-binaries-${{ hashFiles('**/go.sum', '**/*.go') }}" >> $GITHUB_OUTPUT + + - name: Cache binaries + id: cache-binaries + uses: actions/cache@v3 + with: + path: | + ./mpcium + ./mpcium-cli + key: ${{ steps.cache-key.outputs.key }} + + - name: Cache Go modules + if: steps.cache-binaries.outputs.cache-hit != 'true' + uses: actions/cache@v3 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Install dependencies + if: steps.cache-binaries.outputs.cache-hit != 'true' + run: | + go mod download + cd e2e && go mod download + + - name: Build binaries + if: steps.cache-binaries.outputs.cache-hit != 'true' + run: | + go build -o mpcium ./cmd/mpcium + go build -o mpcium-cli ./cmd/mpcium-cli + chmod +x mpcium mpcium-cli + + # Key Generation E2E Tests + e2e-keygen: + runs-on: ubuntu-latest + needs: build + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: "1.23" + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Verify Docker Compose + run: | + docker --version + docker compose version + + - name: Cache Go modules + uses: actions/cache@v3 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Restore binaries + uses: actions/cache@v3 + with: + path: | + ./mpcium + ./mpcium-cli + key: ${{ needs.build.outputs.cache-key }} + + - name: Install binaries + run: | + sudo mv mpcium /usr/local/bin/ + sudo mv mpcium-cli /usr/local/bin/ + + - name: Verify binaries are available + run: | + which mpcium + which mpcium-cli + mpcium --version || echo "mpcium binary ready" + mpcium-cli --version || echo "mpcium-cli binary ready" + + - name: Install E2E dependencies + run: | + cd e2e && go mod download + + - name: Run Key Generation E2E tests + run: | + cd e2e + go test -v -timeout=1200s -run TestKeyGeneration + env: + DOCKER_BUILDKIT: 1 + + - name: Cleanup Docker containers + if: always() + run: | + cd e2e + docker compose -f docker-compose.test.yaml down -v || true + docker system prune -f || true + + - name: Upload keygen test logs + if: failure() + uses: actions/upload-artifact@v4 + with: + name: e2e-keygen-test-logs + path: e2e/logs/ + retention-days: 7 + + # Signing E2E Tests + e2e-signing: + runs-on: ubuntu-latest + needs: build + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: "1.23" + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Verify Docker Compose + run: | + docker --version + docker compose version + + - name: Cache Go modules + uses: actions/cache@v3 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Restore binaries + uses: actions/cache@v3 + with: + path: | + ./mpcium + ./mpcium-cli + key: ${{ needs.build.outputs.cache-key }} + + - name: Install binaries + run: | + sudo mv mpcium /usr/local/bin/ + sudo mv mpcium-cli /usr/local/bin/ + + - name: Verify binaries are available + run: | + which mpcium + which mpcium-cli + mpcium --version || echo "mpcium binary ready" + mpcium-cli --version || echo "mpcium-cli binary ready" + + - name: Install E2E dependencies + run: | + cd e2e && go mod download + + - name: Run Signing E2E tests + run: | + cd e2e + go test -v -timeout=1200s -run TestSigning + env: + DOCKER_BUILDKIT: 1 + + - name: Cleanup Docker containers + if: always() + run: | + cd e2e + docker compose -f docker-compose.test.yaml down -v || true + docker system prune -f || true + + - name: Upload signing test logs + if: failure() + uses: actions/upload-artifact@v4 + with: + name: e2e-signing-test-logs + path: e2e/logs/ + retention-days: 7 + + # Resharing E2E Tests + e2e-resharing: + runs-on: ubuntu-latest + needs: build + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: "1.23" + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Verify Docker Compose + run: | + docker --version + docker compose version + + - name: Cache Go modules + uses: actions/cache@v3 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Restore binaries + uses: actions/cache@v3 + with: + path: | + ./mpcium + ./mpcium-cli + key: ${{ needs.build.outputs.cache-key }} + + - name: Install binaries + run: | + sudo mv mpcium /usr/local/bin/ + sudo mv mpcium-cli /usr/local/bin/ + + - name: Verify binaries are available + run: | + which mpcium + which mpcium-cli + mpcium --version || echo "mpcium binary ready" + mpcium-cli --version || echo "mpcium-cli binary ready" + + - name: Install E2E dependencies + run: | + cd e2e && go mod download + + - name: Run Resharing E2E tests + run: | + cd e2e + go test -v -timeout=1200s -run TestResharing + env: + DOCKER_BUILDKIT: 1 + + - name: Cleanup Docker containers + if: always() + run: | + cd e2e + docker compose -f docker-compose.test.yaml down -v || true + docker system prune -f || true + + - name: Upload resharing test logs + if: failure() + uses: actions/upload-artifact@v4 + with: + name: e2e-resharing-test-logs + path: e2e/logs/ + retention-days: 7 + + # Summary job that depends on all E2E tests + e2e-summary: + runs-on: ubuntu-latest + needs: [e2e-keygen, e2e-signing, e2e-resharing] + if: always() + + steps: + - name: Check E2E test results + run: | + echo "E2E Test Results Summary:" + echo "=========================" + echo "Key Generation Tests: ${{ needs.e2e-keygen.result }}" + echo "Signing Tests: ${{ needs.e2e-signing.result }}" + echo "Resharing Tests: ${{ needs.e2e-resharing.result }}" + echo "" + + # Check if any tests failed + if [[ "${{ needs.e2e-keygen.result }}" != "success" || "${{ needs.e2e-signing.result }}" != "success" || "${{ needs.e2e-resharing.result }}" != "success" ]]; then + echo "โŒ One or more E2E tests failed" + exit 1 + else + echo "โœ… All E2E tests passed successfully" + fi diff --git a/.gitignore b/.gitignore index 751dea4..b09913b 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,15 @@ identity/ event_initiator.identity.json event_initiator.key event_initiator.key.age +coverage.out +coverage.html + +# E2E test artifacts +e2e/test_db/ +e2e/test_node*/ +e2e/test_event_initiator.* +e2e/coverage.out +e2e/coverage.html +e2e/logs/ +# Generated config file (template is tracked) +e2e/config.test.yaml diff --git a/Makefile b/Makefile index c9fefa5..6da06a2 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: all build clean mpcium mpc +.PHONY: all build clean mpcium mpc test test-verbose test-coverage e2e-test e2e-clean cleanup-test-env BIN_DIR := bin @@ -16,6 +16,46 @@ mpcium: mpc: go install ./cmd/mpcium-cli +# Run all tests +test: + go test ./... + +# Run tests with verbose output +test-verbose: + go test -v ./... + +# Run tests with coverage report +test-coverage: + go test -v -coverprofile=coverage.out ./... + go tool cover -html=coverage.out -o coverage.html + +# Run E2E integration tests +e2e-test: build + @echo "Running E2E integration tests..." + cd e2e && make test + +# Run E2E tests with coverage +e2e-test-coverage: build + @echo "Running E2E integration tests with coverage..." + cd e2e && make test-coverage + +# Clean up E2E test artifacts +e2e-clean: + @echo "Cleaning up E2E test artifacts..." + cd e2e && make clean + +# Comprehensive cleanup of test environment (kills processes, removes artifacts) +cleanup-test-env: + @echo "Performing comprehensive test environment cleanup..." + cd e2e && ./cleanup_test_env.sh + +# Run all tests (unit + E2E) +test-all: test e2e-test + # Wipe out manually built binaries if needed (not required by go install) clean: rm -rf $(BIN_DIR) + rm -f coverage.out coverage.html + +# Full clean (including E2E artifacts) +clean-all: clean e2e-clean diff --git a/README.md b/README.md index 7b2ed85..6073f1a 100644 --- a/README.md +++ b/README.md @@ -162,3 +162,15 @@ func main () { logger.Info("CreateWallet sent, awaiting result...", "walletID", walletID) } ``` + +### Testing +## 1. Unit tests +``` +go test ./... -v +``` + +## 2. Integration tests +``` +cd e2e +make test +``` \ No newline at end of file diff --git a/cmd/mpcium/main.go b/cmd/mpcium/main.go index 11808e2..9e3f35e 100644 --- a/cmd/mpcium/main.go +++ b/cmd/mpcium/main.go @@ -181,8 +181,10 @@ func runNode(ctx context.Context, c *cli.Command) error { signingConsumer := eventconsumer.NewSigningConsumer(natsConn, signingStream, pubsub, peerRegistry) // Make the node ready before starting the signing consumer - peerRegistry.Ready() - + if err := peerRegistry.Ready(); err != nil { + logger.Error("Failed to mark peer registry as ready", err) + } + logger.Info("[READY] Node is ready", "nodeID", nodeID) appContext, cancel := context.WithCancel(context.Background()) // Setup signal handling to cancel context on termination signals. go func() { @@ -247,7 +249,9 @@ func promptForSensitiveCredentials() { // Prompt for initiator public key (using regular input since it's not as sensitive) var initiatorKey string fmt.Print("Enter event initiator public key (hex): ") - fmt.Scanln(&initiatorKey) + if _, err := fmt.Scanln(&initiatorKey); err != nil { + logger.Fatal("Failed to read initiator key", err) + } if initiatorKey == "" { logger.Fatal("Initiator public key cannot be empty", nil) @@ -332,7 +336,13 @@ func GetIDFromName(name string, peers []config.Peer) string { func NewBadgerKV(nodeName string) *kvstore.BadgerKVStore { // Badger KV DB - dbPath := filepath.Join(".", "db", nodeName) + // Use configured db_path or default to current directory + "db" + basePath := viper.GetString("db_path") + if basePath == "" { + basePath = filepath.Join(".", "db") + } + dbPath := filepath.Join(basePath, nodeName) + badgerKv, err := kvstore.NewBadgerKVStore( dbPath, []byte(viper.GetString("badger_password")), diff --git a/config.yaml.template b/config.yaml.template index 113904f..e422527 100644 --- a/config.yaml.template +++ b/config.yaml.template @@ -8,3 +8,4 @@ environment: development badger_password: "your_badger_password" event_initiator_pubkey: "event_initiator_pubkey" max_concurrent_keygen: 2 +db_path: "." diff --git a/e2e/Makefile b/e2e/Makefile new file mode 100644 index 0000000..8cfda87 --- /dev/null +++ b/e2e/Makefile @@ -0,0 +1,50 @@ +.PHONY: test setup clean deps + +# Default target +test: deps setup + @echo "Running E2E tests..." + go test -v -timeout=10m ./... + +# Setup test environment +setup: + @echo "๐Ÿ”ง Setting up test environment..." + @if ! command -v mpcium >/dev/null 2>&1; then \ + echo "โŒ mpcium binary not found in PATH. Please run 'make' in the root directory first."; \ + exit 1; \ + fi + @if ! command -v mpcium-cli >/dev/null 2>&1; then \ + echo "โŒ mpcium-cli binary not found in PATH. Please run 'make' in the root directory first."; \ + exit 1; \ + fi + @echo "โœ… Binaries found" + +# Install dependencies +deps: + @echo "๐Ÿ“ฆ Installing dependencies..." + go mod tidy + go mod download + +# Clean up test artifacts +clean: + @echo "๐Ÿงน Cleaning up test artifacts..." + rm -rf test_db/ + rm -rf test_node*/ + rm -f test_event_initiator.* + rm -rf logs + rm -f config.test.yaml + docker compose -f docker-compose.test.yaml down --remove-orphans 2>/dev/null || true + +# Quick test (skip setup) +test-quick: + @echo "โšก Running quick E2E tests..." + go test -v -timeout=10m ./... + +# Help +help: + @echo "Available targets:" + @echo " test - Run E2E tests with full setup" + @echo " test-quick - Run E2E tests without setup" + @echo " setup - Setup test environment" + @echo " deps - Install dependencies" + @echo " clean - Clean up test artifacts" + @echo " help - Show this help message" diff --git a/e2e/README.md b/e2e/README.md new file mode 100644 index 0000000..739ba82 --- /dev/null +++ b/e2e/README.md @@ -0,0 +1,317 @@ +# E2E Testing for MPCium + +This directory contains end-to-end integration tests for the MPCium multi-party computation system. + +## Overview + +The E2E tests verify that the complete MPC system works correctly by: + +1. **Infrastructure Setup**: Using testcontainers to spin up isolated NATS and Consul instances +2. **Node Setup**: Creating 3 test nodes with separate identities and configurations +3. **Key Generation**: Testing concurrent key generation for multiple wallets +4. **Consistency Verification**: Ensuring all generated keys are properly stored across all nodes +5. **Cleanup**: Removing all test artifacts and containers + +## Prerequisites + +Before running the tests, ensure you have: + +- **Docker** installed and running +- **Go** 1.23+ installed +- **mpcium** and **mpcium-cli** binaries built (run `make` in the root directory) + +## Running Tests + +### Quick Start + +```bash +# Run all E2E tests +make test + + +# Clean up test artifacts +make clean +``` + +### Manual Steps + +1. **Build the binaries** (from root directory): + + ```bash + make + ``` + +2. **Run the E2E tests**: + ```bash + cd e2e + make test + ``` + +## Test Structure + +### Files + +- `keygen_test.go` - Main test file with the E2E test suite +- `docker-compose.test.yaml` - Test infrastructure configuration +- `config.test.yaml` - Test node configuration template +- `setup_test_identities.sh` - Script to set up test node identities +- `Makefile` - Build and test automation + +### Test Flow + +1. **Setup Infrastructure** + + - Starts NATS (port 4223) and Consul (port 8501) containers + - Creates service clients for test coordination + +2. **Setup Test Nodes** + + - Creates 3 test nodes (`test_node0`, `test_node1`, `test_node2`) + - Generates unique identities for each node + - Configures separate database paths (`./test_db/`) + - Registers peers in Consul + +3. **Start MPC Nodes** + + - Launches 3 mpcium processes in parallel + - Each node uses its own configuration and identity + +4. **Test Key Generation** + + - Generates 3 random wallet IDs + - Triggers key generation for all wallets simultaneously + - Waits for completion (2 minute timeout) + +5. **Verify Consistency** + + - Stops all nodes safely + - Opens each node's database in read-only mode + - Verifies both ECDSA and EdDSA keys exist for each wallet + - Ensures all nodes have identical key data + +6. **Cleanup** + - Stops all processes + - Removes Docker containers + - Deletes test databases and temporary files + +## Configuration + +### Test Ports + +The tests use different ports to avoid conflicts with running services: + +- **NATS**: 4223 (vs 4222 for main) +- **Consul**: 8501 (vs 8500 for main) + +### Database Path + +Test nodes use a separate database path: `./test_db/` instead of `./db/` + +### Test Credentials + +- **Badger Password**: `test_password_123` +- **Node Names**: `test_node0`, `test_node1`, `test_node2` + +## Troubleshooting + +### Common Issues + +1. **Binary not found** + + ``` + โŒ mpcium binary not found. Please run 'make' in the root directory first. + ``` + + **Solution**: Run `make` in the root directory to build the binaries. + +2. **Port conflicts** + + ``` + Error: port 4223 already in use + ``` + + **Solution**: Run `make clean` to stop any existing test containers. + +3. **Permission errors** + ``` + Error: cannot create test_db directory + ``` + **Solution**: Ensure you have write permissions in the e2e directory. + +### Debugging + +To debug test failures: + +1. **Check container logs**: + + ```bash + docker logs nats-server-test + docker logs consul-test + ``` + +2. **Run with verbose output**: + + ```bash + go test -v -timeout=10m ./... + ``` + +3. **Keep test artifacts** (comment out cleanup in the test): + + ```bash + # Inspect test databases + ls -la test_db/ + + # Check test node configurations + cat test_node0/config.yaml + ``` + +## Expected Output + +A successful test run should show: + +``` +๐Ÿš€ Setting up test infrastructure... +๐Ÿณ Starting docker-compose stack... +โณ Waiting for services to be ready... +๐Ÿ”Œ Setting up service clients... +โœ… Consul client connected +โœ… NATS client connected +๐Ÿ”ง Setting up test nodes... +โœ… Test nodes setup complete +๐Ÿ“‹ Registering peers in Consul... +โœ… Registered peer test_node0 with ID xxx +โœ… Registered peer test_node1 with ID xxx +โœ… Registered peer test_node2 with ID xxx +๐Ÿš€ Starting MPC nodes... +โœ… Started node test_node0 (PID: xxx) +โœ… Started node test_node1 (PID: xxx) +โœ… Started node test_node2 (PID: xxx) +๐Ÿ”‘ Testing key generation... +๐Ÿ“ Generated wallet IDs: [xxx, xxx, xxx] +๐Ÿ” Triggering key generation for wallet xxx +โณ Waiting for key generation to complete... +โœ… Key generation test completed +๐Ÿ” Verifying key consistency across nodes... +๐Ÿ›‘ Stopping MPC nodes... +๐Ÿ” Checking wallet xxx +โœ… Found ECDSA key for wallet xxx in node test_node0 (xxx bytes) +โœ… Found ECDSA key for wallet xxx in node test_node1 (xxx bytes) +โœ… Found ECDSA key for wallet xxx in node test_node2 (xxx bytes) +โœ… Found EdDSA key for wallet xxx in node test_node0 (xxx bytes) +โœ… Found EdDSA key for wallet xxx in node test_node1 (xxx bytes) +โœ… Found EdDSA key for wallet xxx in node test_node2 (xxx bytes) +โœ… Key consistency verification completed +๐Ÿงน Cleaning up test environment... +โœ… Cleanup completed +``` + +## Integration with CI/CD + +To integrate with CI/CD pipelines: + +```yaml +# Example GitHub Actions step +- name: Run E2E Tests + run: | + make + cd e2e + make test +``` + +The tests are designed to be: + +- **Isolated**: No dependencies on external services +- **Deterministic**: Consistent results across runs +- **Self-contained**: All setup and cleanup handled automatically +- **Fast**: Complete in under 10 minutes + +## Test Cleanup and Process Management + +### Problem: Test Process Interference + +E2E tests can sometimes leave behind running processes that interfere with subsequent test runs. This can cause signature verification errors and other unexpected failures. + +### Solution: Comprehensive Cleanup + +The test suite now includes automatic cleanup mechanisms to prevent process interference: + +#### 1. Automatic Cleanup in Tests + +- **Pre-test cleanup**: Every test run starts with `CleanupTestEnvironment()` which: + - Kills any existing MPC processes + - Stops Docker containers + - Removes test artifacts +- **Post-test cleanup**: Tests use `defer` to ensure cleanup happens even if tests fail + +#### 2. Manual Cleanup Options + +If you need to manually clean up the test environment: + +```bash +# Option 1: Use the cleanup script directly +cd e2e +./cleanup_test_env.sh + +# Option 2: Use the Makefile target +make cleanup-test-env + +# Option 3: Manual cleanup commands +cd e2e +# Kill MPC processes +pgrep -f "mpcium" | xargs kill -TERM +# Stop Docker containers +docker compose -f docker-compose.test.yaml down -v --remove-orphans +# Remove test artifacts +rm -rf test_node* *.log +``` + +#### 3. Troubleshooting Process Issues + +If you encounter signature verification errors or other mysterious test failures: + +1. **Check for running processes**: + + ```bash + ps aux | grep mpcium + ``` + +2. **Kill any found processes**: + + ```bash + pkill -f mpcium + ``` + +3. **Clean up completely**: + + ```bash + make cleanup-test-env + ``` + +4. **Run tests again**: + ```bash + go test -v -run TestKeyGeneration + ``` + +### Best Practices + +1. **Always clean up before running tests** - The test suite does this automatically +2. **Use the cleanup script** if you interrupt tests manually (Ctrl+C) +3. **Check for leftover processes** if you see unexpected errors +4. **Don't run multiple test instances** simultaneously in the same directory + +### Test Structure + +- `base_test.go` - Core test infrastructure and cleanup functions +- `keygen_test.go` - Key generation tests +- `cleanup_test_env.sh` - Standalone cleanup script +- `docker-compose.test.yaml` - Test infrastructure (NATS, Consul) + +### Common Issues and Solutions + +| Issue | Cause | Solution | +| ------------------------------------ | ------------------------------- | ------------------------------- | +| "Failed to verify initiator message" | Multiple MPC instances running | Run cleanup script | +| "Port already in use" | Docker containers still running | `docker compose down -v` | +| "Database locked" | Previous test didn't clean up | Remove `test_node*` directories | +| Test hangs during setup | Leftover processes interfering | Kill all `mpcium` processes | + diff --git a/e2e/base_test.go b/e2e/base_test.go new file mode 100644 index 0000000..6d38588 --- /dev/null +++ b/e2e/base_test.go @@ -0,0 +1,663 @@ +package e2e + +import ( + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" + + "github.com/dgraph-io/badger/v4" + "github.com/dgraph-io/badger/v4/options" + "github.com/fystack/mpcium/pkg/client" + "github.com/fystack/mpcium/pkg/event" + "github.com/fystack/mpcium/pkg/kvstore" + "github.com/hashicorp/consul/api" + "github.com/nats-io/nats.go" + "github.com/stretchr/testify/require" + "gopkg.in/yaml.v2" +) + +const ( + numNodes = 3 + keygenTimeout = 15 * time.Minute + signingTimeout = 10 * time.Minute +) + +type TestConfig struct { + Nats struct { + URL string `yaml:"url"` + } `yaml:"nats"` + Consul struct { + Address string `yaml:"address"` + } `yaml:"consul"` + MPCThreshold int `yaml:"mpc_threshold"` + Environment string `yaml:"environment"` + BadgerPassword string `yaml:"badger_password"` + EventInitiatorPubkey string `yaml:"event_initiator_pubkey"` + MPCiumVersion string `yaml:"mpcium_version"` + MaxConcurrentKeygen int `yaml:"max_concurrent_keygen"` + DbPath string `yaml:"db_path"` +} + +type E2ETestSuite struct { + ctx context.Context + consulClient *api.Client + natsConn *nats.Conn + mpcClient client.MPCClient + testDir string + walletIDs []string + mpciumProcesses []*exec.Cmd + keygenResults map[string]*event.KeygenResultEvent + signingResults map[string]*event.SigningResultEvent + resharingResults map[string]*event.ResharingResultEvent + config TestConfig +} + +func NewE2ETestSuite(testDir string) *E2ETestSuite { + ctx, _ := context.WithCancel(context.Background()) + return &E2ETestSuite{ + ctx: ctx, + testDir: testDir, + walletIDs: make([]string, 0), + keygenResults: make(map[string]*event.KeygenResultEvent), + signingResults: make(map[string]*event.SigningResultEvent), + resharingResults: make(map[string]*event.ResharingResultEvent), + } +} + +func (s *E2ETestSuite) LoadConfig() error { + configPath := filepath.Join(s.testDir, "config.test.yaml") + data, err := os.ReadFile(configPath) + if err != nil { + return err + } + + return yaml.Unmarshal(data, &s.config) +} + +func (s *E2ETestSuite) RunMakeClean() error { + cmd := exec.Command("make", "clean") + cmd.Dir = s.testDir + output, err := cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("make clean failed: %v, output: %s", err, string(output)) + } + return nil +} + +// GetNodeIDs reads the node IDs from the peers.json file +func (s *E2ETestSuite) GetNodeIDs() ([]string, error) { + peersPath := filepath.Join(s.testDir, "test_node0", "peers.json") + data, err := os.ReadFile(peersPath) + if err != nil { + return nil, fmt.Errorf("failed to read peers.json: %w", err) + } + + var peers map[string]string + if err := json.Unmarshal(data, &peers); err != nil { + return nil, fmt.Errorf("failed to parse peers.json: %w", err) + } + + var nodeIDs []string + for _, id := range peers { + nodeIDs = append(nodeIDs, id) + } + + return nodeIDs, nil +} + +func (s *E2ETestSuite) SetupInfrastructure(t *testing.T) { + t.Log("Setting up test infrastructure...") + + // Start containers using Docker Compose directly + t.Log("Starting Docker Compose...") + + // Start the compose stack + t.Log("Starting docker-compose stack...") + cmd := exec.Command("docker", "compose", "-f", "docker-compose.test.yaml", "up", "-d") + cmd.Dir = s.testDir + output, err := cmd.CombinedOutput() + if err != nil { + t.Logf("Docker compose output: %s", string(output)) + require.NoError(t, err, "Failed to start docker-compose stack") + } + + t.Log("Docker Compose stack started") + + // Wait for services to be ready + t.Log("Waiting for services to be ready...") + time.Sleep(10 * time.Second) + + // Setup clients immediately to establish connections + s.setupClients(t) + + // Additional wait to ensure stability + time.Sleep(5 * time.Second) + t.Log("Infrastructure setup completed and verified") +} + +func (s *E2ETestSuite) setupClients(t *testing.T) { + var err error + + // Use the fixed ports from docker-compose.test.yaml + consulPort := 8501 // consul-test service maps 8501:8500 + natsPort := 4223 // nats-server-test service maps 4223:4222 + + // Setup Consul client + consulConfig := api.DefaultConfig() + consulConfig.Address = fmt.Sprintf("localhost:%d", consulPort) + s.consulClient, err = api.NewClient(consulConfig) + require.NoError(t, err, "Failed to create Consul client") + + // Test Consul connection + _, err = s.consulClient.Agent().Self() + require.NoError(t, err, "Failed to connect to Consul") + + // Setup NATS client + natsConn, err := nats.Connect(fmt.Sprintf("nats://localhost:%d", natsPort)) + require.NoError(t, err, "Failed to connect to NATS") + s.natsConn = natsConn + + // Test NATS connection + err = s.natsConn.Publish("test", []byte("test")) + require.NoError(t, err, "Failed to publish test message to NATS") + + t.Log("Clients setup completed") +} + +func (s *E2ETestSuite) SetupMPCClient(t *testing.T) { + t.Log("Setting up MPC client...") + + // Setup MPC client + keyPath := filepath.Join(s.testDir, "test_event_initiator.key") + t.Logf("Creating MPC client with key path: %s", keyPath) + + // Check if key file exists + if _, err := os.Stat(keyPath); os.IsNotExist(err) { + t.Fatalf("Key file does not exist: %s. Make sure setupTestNodes ran successfully.", keyPath) + } + + mpcClient := client.NewMPCClient(client.Options{ + NatsConn: s.natsConn, + KeyPath: keyPath, + }) + s.mpcClient = mpcClient + t.Log("MPC client created") +} + +func (s *E2ETestSuite) SetupTestNodes(t *testing.T) { + t.Log("Setting up test nodes...") + + // Run the setup script (it handles password generation and config updates) + cmd := exec.Command("bash", "setup_test_identities.sh") + cmd.Dir = s.testDir + output, err := cmd.CombinedOutput() + if err != nil { + t.Logf("Setup script output: %s", string(output)) + require.NoError(t, err, "Failed to run setup script") + } + t.Log("Test nodes setup complete") +} + +func (s *E2ETestSuite) RegisterPeers(t *testing.T) { + t.Log("Registering peers in Consul...") + + // Check Consul health before proceeding + t.Log("Checking Consul health...") + _, err := s.consulClient.Status().Leader() + require.NoError(t, err, "Consul is not healthy") + t.Log("Consul is healthy") + + // Use mpcium register-peers command instead of manual registration + t.Log("Running mpcium-cli register-peers...") + nodeDir := filepath.Join(s.testDir, "test_node0") + cmd := exec.Command("mpcium-cli", "register-peers") + cmd.Dir = nodeDir + cmd.Env = append(os.Environ(), "MPCIUM_CONFIG=config.yaml") + + output, err := cmd.CombinedOutput() + if err != nil { + t.Logf("register-peers output: %s", string(output)) + require.NoError(t, err, "Failed to register peers") + } + + t.Log("Peers registered in Consul") + + // List current peers to verify registration + t.Log("Listing current peers in Consul...") + kv := s.consulClient.KV() + + // Get all keys under the mpc_peers/ prefix (matches register-peers command) + pairs, _, err := kv.List("mpc_peers/", nil) + if err != nil { + t.Logf("Failed to list peers: %v", err) + } else { + t.Logf("Found %d peer entries in Consul under 'mpc_peers/':", len(pairs)) + for _, pair := range pairs { + t.Logf(" - Key: %s, Value: %s", pair.Key, string(pair.Value)) + } + } + + // Verify we have the expected number of peers + if len(pairs) != numNodes { + t.Logf("Expected %d peers but found %d", numNodes, len(pairs)) + } else { + t.Log("All expected peers are registered") + } + + t.Log("Peer listing completed") +} + +func (s *E2ETestSuite) StartNodes(t *testing.T) { + t.Log("Starting MPC nodes...") + + // Double-check that Consul is still accessible before starting nodes + t.Log("Verifying Consul is still accessible...") + _, err := s.consulClient.Status().Leader() + if err != nil { + t.Logf("Consul connection test failed: %v", err) + } else { + t.Log("Consul is still accessible") + } + + s.mpciumProcesses = make([]*exec.Cmd, numNodes) + + for i := 0; i < numNodes; i++ { + nodeName := fmt.Sprintf("test_node%d", i) + nodeDir := filepath.Join(s.testDir, nodeName) + + // Start node process + cmd := exec.Command("mpcium", "start", "-n", nodeName) + cmd.Dir = nodeDir + cmd.Env = append(os.Environ(), "MPCIUM_CONFIG=config.yaml") + + // Create log files for stdout and stderr + logDir := filepath.Join(s.testDir, "logs") + err := os.MkdirAll(logDir, 0755) + if err != nil { + t.Fatalf("Failed to create log directory: %v", err) + } + + stdoutFile, err := os.Create(filepath.Join(logDir, fmt.Sprintf("%s.stdout.log", nodeName))) + require.NoError(t, err, "Failed to create stdout log file for %s", nodeName) + + stderrFile, err := os.Create(filepath.Join(logDir, fmt.Sprintf("%s.stderr.log", nodeName))) + require.NoError(t, err, "Failed to create stderr log file for %s", nodeName) + + // Set up logging + cmd.Stdout = stdoutFile + cmd.Stderr = stderrFile + + // Start the process + err = cmd.Start() + require.NoError(t, err, "Failed to start node %s", nodeName) + + s.mpciumProcesses[i] = cmd + t.Logf("Started node %s (PID: %d) - logs: %s.stdout.log, %s.stderr.log", + nodeName, cmd.Process.Pid, nodeName, nodeName) + } + + // Wait for nodes to be ready + t.Log("Waiting for nodes to be ready...") + time.Sleep(5 * time.Second) + + // Verify containers are still accessible + t.Log("Final verification that Consul is still accessible...") + _, err = s.consulClient.Status().Leader() + if err != nil { + t.Logf("Consul connection test failed after starting nodes: %v", err) + } else { + t.Log("Consul is still accessible after starting nodes") + } + + // Show recent logs from each node + t.Log("Recent logs from MPC nodes:") + for i := 0; i < numNodes; i++ { + nodeName := fmt.Sprintf("test_node%d", i) + s.ShowRecentLogs(t, nodeName) + } +} + +func (s *E2ETestSuite) ShowRecentLogs(t *testing.T, nodeName string) { + logDir := filepath.Join(s.testDir, "logs") + + // Show last 10 lines of stdout + stdoutPath := filepath.Join(logDir, fmt.Sprintf("%s.stdout.log", nodeName)) + if data, err := os.ReadFile(stdoutPath); err == nil && len(data) > 0 { + lines := strings.Split(strings.TrimSpace(string(data)), "\n") + if len(lines) > 10 { + lines = lines[len(lines)-10:] + } + t.Logf("%s stdout (last %d lines):", nodeName, len(lines)) + for _, line := range lines { + if strings.TrimSpace(line) != "" { + t.Logf(" %s", line) + } + } + } + + // Show last 10 lines of stderr + stderrPath := filepath.Join(logDir, fmt.Sprintf("%s.stderr.log", nodeName)) + if data, err := os.ReadFile(stderrPath); err == nil && len(data) > 0 { + lines := strings.Split(strings.TrimSpace(string(data)), "\n") + if len(lines) > 10 { + lines = lines[len(lines)-10:] + } + t.Logf("%s stderr (last %d lines):", nodeName, len(lines)) + for _, line := range lines { + if strings.TrimSpace(line) != "" { + t.Logf(" %s", line) + } + } + } +} + +func (s *E2ETestSuite) WaitForNodesReady(t *testing.T) { + t.Log("Waiting for all nodes to be ready to accept MPC requests...") + + timeout := time.NewTimer(5 * time.Minute) + defer timeout.Stop() + + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + + for { + select { + case <-timeout.C: + t.Fatal("Timeout waiting for nodes to be ready") + case <-ticker.C: + readyCount := 0 + + for i := 0; i < numNodes; i++ { + nodeName := fmt.Sprintf("test_node%d", i) + if s.isNodeReady(nodeName) { + readyCount++ + } + } + + t.Logf("Nodes ready: %d/%d", readyCount, numNodes) + + if readyCount == numNodes { + t.Log("All nodes are ready to accept MPC requests!") + return + } + } + } +} + +func (s *E2ETestSuite) isNodeReady(nodeName string) bool { + logDir := filepath.Join(s.testDir, "logs") + stderrPath := filepath.Join(logDir, fmt.Sprintf("%s.stderr.log", nodeName)) + + data, err := os.ReadFile(stderrPath) + if err != nil { + return false + } + + logContent := string(data) + // Check for the specific log message that indicates the node is ready + return strings.Contains(logContent, "[READY] Node is ready") +} + +func (s *E2ETestSuite) StopNode(t *testing.T, nodeIndex int) { + if nodeIndex >= len(s.mpciumProcesses) || s.mpciumProcesses[nodeIndex] == nil { + t.Logf("Node %d is not running or doesn't exist", nodeIndex) + return + } + + cmd := s.mpciumProcesses[nodeIndex] + nodeName := fmt.Sprintf("test_node%d", nodeIndex) + + t.Logf("Killing node %s (PID: %d)", nodeName, cmd.Process.Pid) + + // Force kill the process immediately + err := cmd.Process.Kill() + if err != nil { + t.Logf("Failed to kill node %s: %v", nodeName, err) + } else { + // Wait for process cleanup + go func() { + _ = cmd.Wait() + t.Logf("Node %s killed", nodeName) + }() + } + + s.mpciumProcesses[nodeIndex] = nil +} + +func (s *E2ETestSuite) StopNodes(t *testing.T) { + t.Log("Stopping MPC nodes...") + + if len(s.mpciumProcesses) == 0 { + t.Log("No nodes to stop") + return + } + + // Force kill all processes immediately + for i, cmd := range s.mpciumProcesses { + if cmd != nil && cmd.Process != nil { + t.Logf("Force killing node %d (PID: %d)", i, cmd.Process.Pid) + err := cmd.Process.Kill() + if err != nil { + t.Logf("Failed to kill node %d: %v", i, err) + } else { + // Wait for the process to be cleaned up + go func(idx int, process *exec.Cmd) { + _ = process.Wait() + t.Logf("Node %d killed", idx) + }(i, cmd) + } + s.mpciumProcesses[i] = nil + } + } + + // Brief wait for cleanup + time.Sleep(1 * time.Second) + t.Log("All nodes stopped") +} + +func (s *E2ETestSuite) CheckKeyInAllNodes(t *testing.T, walletID, keyType, keyName string) { + key := fmt.Sprintf("%s:%s_v1", keyType, walletID) + t.Logf("Looking for key: %s", key) + + for i := 0; i < numNodes; i++ { + nodeName := fmt.Sprintf("test_node%d", i) + // Skip if node is stopped + if s.mpciumProcesses[i] == nil { + t.Logf("Skipping node %s (stopped)", nodeName) + continue + } + + // Database is located at: test_node0/test_db/test_node0/ + dbPath := filepath.Join(s.testDir, nodeName, s.config.DbPath, nodeName) + t.Logf("Database path for %s: %s", nodeName, dbPath) + + // Check if database directory exists + if _, err := os.Stat(dbPath); os.IsNotExist(err) { + t.Logf("Database directory does not exist: %s", dbPath) + continue + } + + // Open database in read-only mode with recovery options + opts := badger.DefaultOptions(dbPath). + WithCompression(options.ZSTD). + WithEncryptionKey([]byte(s.config.BadgerPassword)). + WithIndexCacheSize(100 << 20). + WithReadOnly(true). + WithBypassLockGuard(true) // Allow opening even if not properly closed + + db, err := badger.Open(opts) + if err != nil { + t.Logf("Could not open database for %s at %s: %v", nodeName, dbPath, err) + + // Try to recover by opening in read-write mode first + t.Logf("Attempting database recovery for %s", nodeName) + recoveryOpts := badger.DefaultOptions(dbPath). + WithCompression(options.ZSTD). + WithEncryptionKey([]byte(s.config.BadgerPassword)). + WithIndexCacheSize(100 << 20) + + recoveryDB, recoveryErr := badger.Open(recoveryOpts) + if recoveryErr != nil { + t.Logf("Failed to recover database for %s: %v", nodeName, recoveryErr) + continue + } + + // Close recovery DB and try read-only again + if err := recoveryDB.Close(); err != nil { + t.Logf("Warning: failed to close recovery database for %s: %v", nodeName, err) + } + time.Sleep(1 * time.Second) + + db, err = badger.Open(opts) + if err != nil { + t.Logf("Still cannot open database for %s after recovery: %v", nodeName, err) + continue + } + t.Logf("Successfully recovered database for %s", nodeName) + } + + kvStore := &kvstore.BadgerKVStore{DB: db} + + // Check if our specific key exists + data, err := kvStore.Get(key) + if err != nil { + t.Logf("Failed to get key %s from node %s: %v", key, nodeName, err) + } else if len(data) == 0 { + t.Logf("Key %s not found in node %s", key, nodeName) + } else { + t.Logf("Found key %s in node %s (%d bytes)", key, nodeName, len(data)) + } + + if err := kvStore.Close(); err != nil { + t.Logf("Warning: failed to close kvStore for %s: %v", nodeName, err) + } + } +} + +func (s *E2ETestSuite) Cleanup(t *testing.T) { + t.Log("Cleaning up test environment...") + + // Stop nodes if still running + s.StopNodes(t) + + // Close MPC client connections + if s.natsConn != nil { + s.natsConn.Close() + } + + // Stop Docker Compose stack + t.Log("Stopping Docker Compose stack...") + cmd := exec.Command("docker", "compose", "-f", "docker-compose.test.yaml", "down", "-v") + cmd.Dir = s.testDir + output, err := cmd.CombinedOutput() + if err != nil { + t.Logf("Failed to stop docker-compose stack: %v", err) + t.Logf("Docker compose down output: %s", string(output)) + } else { + t.Log("Docker Compose stack stopped") + } + + // Clean up test data + testDbPath := filepath.Join(s.testDir, s.config.DbPath) + os.RemoveAll(testDbPath) + + // Clean up log files + logPath := filepath.Join(s.testDir, "logs") + os.RemoveAll(logPath) + + // Clean up test node directories + for i := 0; i < numNodes; i++ { + nodeDir := filepath.Join(s.testDir, fmt.Sprintf("test_node%d", i)) + os.RemoveAll(nodeDir) + } + + // Clean up test initiator files + os.Remove(filepath.Join(s.testDir, "test_event_initiator.identity.json")) + os.Remove(filepath.Join(s.testDir, "test_event_initiator.key")) + + t.Log("Cleanup completed") +} + +// KillAllMPCProcesses kills any existing MPC processes that might be running +func (s *E2ETestSuite) KillAllMPCProcesses(t *testing.T) { + t.Log("Checking for existing MPC processes...") + + // Find all mpcium processes + cmd := exec.Command("pgrep", "-f", "mpcium") + output, err := cmd.Output() + if err != nil { + // pgrep returns exit code 1 if no processes found, which is fine + t.Log("No existing MPC processes found") + return + } + + pids := strings.Split(strings.TrimSpace(string(output)), "\n") + if len(pids) == 0 || (len(pids) == 1 && pids[0] == "") { + t.Log("No existing MPC processes found") + return + } + + t.Logf("Found %d existing MPC processes, killing them...", len(pids)) + + // Force kill all processes immediately + for _, pidStr := range pids { + if pidStr == "" { + continue + } + + pid, err := strconv.Atoi(pidStr) + if err != nil { + t.Logf("Invalid PID: %s", pidStr) + continue + } + + // Kill the process + process, err := os.FindProcess(pid) + if err != nil { + t.Logf("Could not find process %d: %v", pid, err) + continue + } + + err = process.Signal(syscall.SIGKILL) + if err != nil { + t.Logf("Failed to kill process %d: %v", pid, err) + } else { + t.Logf("Killed process %d", pid) + } + } + + // Brief wait for cleanup + time.Sleep(1 * time.Second) + t.Log("MPC process cleanup completed") +} + +// CleanupTestEnvironment performs comprehensive cleanup of test environment +func (s *E2ETestSuite) CleanupTestEnvironment(t *testing.T) { + t.Log("Performing comprehensive test environment cleanup...") + + // 1. Kill any existing MPC processes + s.KillAllMPCProcesses(t) + + // 2. Stop any running Docker containers + t.Log("Stopping Docker containers...") + cmd := exec.Command("docker", "compose", "-f", "docker-compose.test.yaml", "down", "-v", "--remove-orphans") + cmd.Dir = s.testDir + output, err := cmd.CombinedOutput() + if err != nil { + t.Logf("Docker compose down failed (this might be expected): %v", err) + } + t.Logf("Docker compose down output: %s", string(output)) + + // 3. Wait for system to settle + time.Sleep(2 * time.Second) + + t.Log("Test environment cleanup completed") +} diff --git a/e2e/cleanup_test_env.sh b/e2e/cleanup_test_env.sh new file mode 100755 index 0000000..9fe05d0 --- /dev/null +++ b/e2e/cleanup_test_env.sh @@ -0,0 +1,83 @@ +#!/bin/bash + +# cleanup_test_env.sh - Comprehensive cleanup script for MPC test environment + +set -e + +echo "=== MPC Test Environment Cleanup ===" + +# Function to kill MPC processes +kill_mpc_processes() { + echo "Checking for existing MPC processes..." + + # Find all mpcium processes + PIDS=$(pgrep -f "mpcium" || true) + + if [ -z "$PIDS" ]; then + echo "No existing MPC processes found" + return + fi + + echo "Found MPC processes: $PIDS" + echo "Force killing all processes..." + + # Force kill all processes immediately + for pid in $PIDS; do + echo "Killing process $pid" + if kill -KILL "$pid" 2>/dev/null; then + echo "Successfully killed process $pid" + else + echo "Failed to kill process $pid (may already be dead)" + fi + done + + echo "MPC process cleanup completed" +} + +# Function to stop Docker containers +stop_docker_containers() { + echo "Stopping Docker containers..." + + if [ -f "docker-compose.test.yaml" ]; then + docker compose -f docker-compose.test.yaml down -v --remove-orphans || true + echo "Docker containers stopped" + else + echo "No docker-compose.test.yaml found, skipping Docker cleanup" + fi +} + +# Function to clean up test artifacts +cleanup_test_artifacts() { + echo "Cleaning up test artifacts..." + + # Remove test node directories + for i in {0..2}; do + if [ -d "test_node$i" ]; then + rm -rf "test_node$i" + echo "Removed test_node$i directory" + fi + done + + # Remove log files + rm -f *.log + echo "Removed log files" + + # Remove any test database files + rm -rf test_db/ || true + + echo "Test artifacts cleanup completed" +} + +# Main cleanup sequence +main() { + echo "Starting comprehensive test environment cleanup..." + + kill_mpc_processes + stop_docker_containers + cleanup_test_artifacts + + echo "=== Cleanup completed ===" +} + +# Run main function +main "$@" diff --git a/e2e/config.test.yaml.template b/e2e/config.test.yaml.template new file mode 100644 index 0000000..e4e763b --- /dev/null +++ b/e2e/config.test.yaml.template @@ -0,0 +1,11 @@ +badger_password: "{{.BadgerPassword}}" +consul: + address: localhost:8501 +db_path: ./test_db +environment: development +event_initiator_pubkey: "{{.EventInitiatorPubkey}}" +max_concurrent_keygen: 1 +mpc_threshold: 1 +mpcium_version: 1.0.0 +nats: + url: nats://localhost:4223 diff --git a/e2e/docker-compose.test.yaml b/e2e/docker-compose.test.yaml new file mode 100644 index 0000000..f88bd3c --- /dev/null +++ b/e2e/docker-compose.test.yaml @@ -0,0 +1,20 @@ +services: + nats-server-test: + image: nats:latest + container_name: nats-server-test + command: -js --http_port 8223 + ports: + - "4223:4222" + - "8223:8223" + - "6223:6222" + tty: true + restart: always + + consul-test: + image: consul:1.15.4 + container_name: consul-test + ports: + - "8501:8500" + - "8602:8600/udp" + command: "agent -server -ui -node=server-1 -bootstrap-expect=1 -client=0.0.0.0" + restart: always diff --git a/e2e/go.mod b/e2e/go.mod new file mode 100644 index 0000000..74b6b74 --- /dev/null +++ b/e2e/go.mod @@ -0,0 +1,91 @@ +module github.com/fystack/mpcium/e2e + +go 1.23.0 + +require ( + github.com/dgraph-io/badger/v4 v4.2.0 + github.com/fystack/mpcium v0.0.0-00010101000000-000000000000 + github.com/google/uuid v1.6.0 + github.com/hashicorp/consul/api v1.26.1 + github.com/nats-io/nats.go v1.31.0 + github.com/stretchr/testify v1.10.0 + gopkg.in/yaml.v2 v2.4.0 +) + +require ( + filippo.io/age v1.2.1 // indirect + github.com/agl/ed25519 v0.0.0-20200225211852-fd4d107ace12 // indirect + github.com/armon/go-metrics v0.4.1 // indirect + github.com/avast/retry-go v3.0.0+incompatible // indirect + github.com/bnb-chain/tss-lib/v2 v2.0.2 // indirect + github.com/btcsuite/btcd v0.24.2 // indirect + github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect + github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 // indirect + github.com/btcsuite/btcutil v1.0.2 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/decred/dcrd/dcrec/edwards/v2 v2.0.3 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect + github.com/dgraph-io/ristretto v0.1.1 // indirect + github.com/dustin/go-humanize v1.0.0 // indirect + github.com/fatih/color v1.18.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang/glog v1.2.4 // indirect + github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb // indirect + github.com/google/flatbuffers v1.12.1 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/hashicorp/go-cleanhttp v0.5.2 // indirect + github.com/hashicorp/go-hclog v1.6.3 // indirect + github.com/hashicorp/go-immutable-radix v1.3.1 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/hashicorp/go-rootcerts v1.0.2 // indirect + github.com/hashicorp/go-version v1.7.0 // indirect + github.com/hashicorp/golang-lru v0.5.4 // indirect + github.com/hashicorp/hcl v1.0.0 // indirect + github.com/hashicorp/serf v0.10.1 // indirect + github.com/ipfs/go-log v1.0.5 // indirect + github.com/ipfs/go-log/v2 v2.1.3 // indirect + github.com/klauspost/compress v1.17.4 // indirect + github.com/magiconair/properties v1.8.7 // indirect + github.com/mattn/go-colorable v0.1.14 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mitchellh/go-homedir v1.1.0 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/nats-io/nkeys v0.4.6 // indirect + github.com/nats-io/nuid v1.0.1 // indirect + github.com/opentracing/opentracing-go v1.2.0 // indirect + github.com/otiai10/primes v0.0.0-20210501021515-f1b2be525a11 // indirect + github.com/pelletier/go-toml/v2 v2.1.0 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/rs/zerolog v1.31.0 // indirect + github.com/sagikazarmark/locafero v0.4.0 // indirect + github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/samber/lo v1.39.0 // indirect + github.com/sourcegraph/conc v0.3.0 // indirect + github.com/spf13/afero v1.11.0 // indirect + github.com/spf13/cast v1.6.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/spf13/viper v1.18.0 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + go.opencensus.io v0.24.0 // indirect + go.uber.org/atomic v1.9.0 // indirect + go.uber.org/multierr v1.9.0 // indirect + go.uber.org/zap v1.21.0 // indirect + golang.org/x/crypto v0.37.0 // indirect + golang.org/x/exp v0.0.0-20240112132812-db7319d0e0e3 // indirect + golang.org/x/net v0.39.0 // indirect + golang.org/x/sys v0.33.0 // indirect + golang.org/x/term v0.31.0 // indirect + golang.org/x/text v0.24.0 // indirect + google.golang.org/protobuf v1.36.6 // indirect + gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) + +replace github.com/fystack/mpcium => ../ + +replace github.com/agl/ed25519 => github.com/binance-chain/edwards25519 v0.0.0-20200305024217-f36fc4b53d43 diff --git a/e2e/go.sum b/e2e/go.sum new file mode 100644 index 0000000..d8de61d --- /dev/null +++ b/e2e/go.sum @@ -0,0 +1,565 @@ +c2sp.org/CCTV/age v0.0.0-20240306222714-3ec4d716e805 h1:u2qwJeEvnypw+OCPUHmoZE3IqwfuN5kgDfo5MLzpNM0= +c2sp.org/CCTV/age v0.0.0-20240306222714-3ec4d716e805/go.mod h1:FomMrUJ2Lxt5jCLmZkG3FHa72zUprnhd3v/Z18Snm4w= +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +filippo.io/age v1.2.1 h1:X0TZjehAZylOIj4DubWYU1vWQxv9bJpo+Uu2/LGhi1o= +filippo.io/age v1.2.1/go.mod h1:JL9ew2lTN+Pyft4RiNGguFfOpewKwSHm5ayKD/A4004= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= +github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= +github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= +github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJA= +github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4= +github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/avast/retry-go v3.0.0+incompatible h1:4SOWQ7Qs+oroOTQOYnAHqelpCO0biHSxpiH9JdtuBj0= +github.com/avast/retry-go v3.0.0+incompatible/go.mod h1:XtSnn+n/sHqQIpZ10K1qAevBhOOCWBLXXy3hyiqqBrY= +github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= +github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/binance-chain/edwards25519 v0.0.0-20200305024217-f36fc4b53d43 h1:Vkf7rtHx8uHx8gDfkQaCdVfc+gfrF9v6sR6xJy7RXNg= +github.com/binance-chain/edwards25519 v0.0.0-20200305024217-f36fc4b53d43/go.mod h1:TnVqVdGEK8b6erOMkcyYGWzCQMw7HEMCOw3BgFYCFWs= +github.com/bnb-chain/tss-lib/v2 v2.0.2 h1:dL2GJFCSYsYQ0bHkGll+hNM2JWsC1rxDmJJJQEmUy9g= +github.com/bnb-chain/tss-lib/v2 v2.0.2/go.mod h1:s4LRfEqj89DhfNb+oraW0dURt5LtOHWXb9Gtkghn0L8= +github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= +github.com/btcsuite/btcd v0.22.0-beta.0.20220111032746-97732e52810c/go.mod h1:tjmYdS6MLJ5/s0Fj4DbLgSbDHbEqLJrtnHecBFkdz5M= +github.com/btcsuite/btcd v0.23.4/go.mod h1:0QJIIN1wwIXF/3G/m87gIwGniDMDQqjVn4SZgnFpsYY= +github.com/btcsuite/btcd v0.24.2 h1:aLmxPguqxza+4ag8R1I2nnJjSu2iFn/kqtHTIImswcY= +github.com/btcsuite/btcd v0.24.2/go.mod h1:5C8ChTkl5ejr3WHj8tkQSCmydiMEPB0ZhQhehpq7Dgg= +github.com/btcsuite/btcd/btcec/v2 v2.1.0/go.mod h1:2VzYrv4Gm4apmbVVsSq5bqf1Ec8v56E48Vt0Y/umPgA= +github.com/btcsuite/btcd/btcec/v2 v2.1.3/go.mod h1:ctjw4H1kknNJmRN4iP1R7bTQ+v3GJkZBd6mui8ZsAZE= +github.com/btcsuite/btcd/btcec/v2 v2.3.2 h1:5n0X6hX0Zk+6omWcihdYvdAlGf2DfasC0GMf7DClJ3U= +github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04= +github.com/btcsuite/btcd/btcutil v1.0.0/go.mod h1:Uoxwv0pqYWhD//tfTiipkxNfdhG9UrLwaeswfjfdF0A= +github.com/btcsuite/btcd/btcutil v1.1.0/go.mod h1:5OapHB7A2hBBWLm48mmw4MOHNJCcUBTwmWH/0Jn8VHE= +github.com/btcsuite/btcd/chaincfg/chainhash v1.0.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= +github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= +github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 h1:59Kx4K6lzOW5w6nFlA0v5+lk/6sjybR934QNHSJZPTQ= +github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= +github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= +github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= +github.com/btcsuite/btcutil v1.0.2 h1:9iZ1Terx9fMIOtq1VrwdqfsATL9MC2l8ZrUY6YZ2uts= +github.com/btcsuite/btcutil v1.0.2/go.mod h1:j9HUFwoQRsZL3V4n+qG+CUnEGHOarIxfC3Le2Yhbcts= +github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg= +github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY= +github.com/btcsuite/goleveldb v1.0.0/go.mod h1:QiK9vBlgftBg6rWQIj6wFzbPfRjiykIEhBH4obrXJ/I= +github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= +github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= +github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= +github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6Dob7S7YxXgwXpfOuvO54S+tGdZdw9fuRZt25Ag= +github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp5jckzBHf4XRpQvBOLI+I= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= +github.com/decred/dcrd/dcrec/edwards/v2 v2.0.3 h1:l/lhv2aJCUignzls81+wvga0TFlyoZx8QxRMQgXpZik= +github.com/decred/dcrd/dcrec/edwards/v2 v2.0.3/go.mod h1:AKpV6+wZ2MfPRJnTbQ6NPgWrKzbe9RCIlCF/FKzMtM8= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 h1:YLtO71vCjJRCBcrPMtQ9nqBsqpA1m5sE92cU+pd5Mcc= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs= +github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218= +github.com/dgraph-io/badger/v4 v4.2.0 h1:kJrlajbXXL9DFTNuhhu9yCx7JJa4qpYWxtE8BzuWsEs= +github.com/dgraph-io/badger/v4 v4.2.0/go.mod h1:qfCqhPoWDFJRx1gp5QwwyGo8xk1lbHUxvK9nK0OGAak= +github.com/dgraph-io/ristretto v0.1.1 h1:6CWw5tJNgpegArSHpNHJKldNeq03FQCwYvfMVWajOK8= +github.com/dgraph-io/ristretto v0.1.1/go.mod h1:S1GPSBCYCIhmVNfcth17y2zZtQT6wzkzgwUve0VDWWA= +github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA= +github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= +github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= +github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= +github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/glog v1.2.4 h1:CNNw5U8lSiiBk7druxtSHHTsRWcxKoac6kZKm2peBBc= +github.com/golang/glog v1.2.4/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb h1:PBC98N2aIaM3XXiurYmW7fx4GZkL8feAMVq7nEjURHk= +github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.1 h1:gK4Kx5IaGY9CD5sPJ36FHiBJ6ZXl0kilRiiCj+jdYp4= +github.com/google/btree v1.0.1/go.mod h1:xXMiIv4Fb/0kKde4SpL7qlzvu5cMJDRkFDxJfI9uaxA= +github.com/google/flatbuffers v1.12.1 h1:MVlul7pQNoDzWRLTw5imwYsl+usrS1TXG2H4jg6ImGw= +github.com/google/flatbuffers v1.12.1/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/consul/api v1.26.1 h1:5oSXOO5fboPZeW5SN+TdGFP/BILDgBm19OrPZ/pICIM= +github.com/hashicorp/consul/api v1.26.1/go.mod h1:B4sQTeaSO16NtynqrAdwOlahJ7IUDZM9cj2420xYL8A= +github.com/hashicorp/consul/sdk v0.15.0 h1:2qK9nDrr4tiJKRoxPGhm6B7xJjLVIQqkjiab2M4aKjU= +github.com/hashicorp/consul/sdk v0.15.0/go.mod h1:r/OmRRPbHOe0yxNahLw7G9x5WG17E1BIECMtCjcPSNo= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= +github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= +github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= +github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= +github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= +github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc= +github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= +github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= +github.com/hashicorp/go-msgpack v0.5.5 h1:i9R9JSrqIz0QVLz3sz+i3YJdT7TTSLcfLLzJi9aZTuI= +github.com/hashicorp/go-msgpack v0.5.5/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= +github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= +github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5Oi2viEzc= +github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= +github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= +github.com/hashicorp/go-sockaddr v1.0.7 h1:G+pTkSO01HpR5qCxg7lxfsFEZaG+C0VssTy/9dbT+Fw= +github.com/hashicorp/go-sockaddr v1.0.7/go.mod h1:FZQbEYa1pxkQ7WLpyXJ6cbjpT8q0YgQaK/JakXqGyWw= +github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= +github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= +github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY= +github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= +github.com/hashicorp/mdns v1.0.4/go.mod h1:mtBihi+LeNXGtG8L9dX59gAEa12BDtBQSp4v/YAJqrc= +github.com/hashicorp/memberlist v0.5.0 h1:EtYPN8DpAURiapus508I4n9CzHs2W+8NZGbmmR/prTM= +github.com/hashicorp/memberlist v0.5.0/go.mod h1:yvyXLpo0QaGE59Y7hDTsTzDD25JYBZ4mHgHUZ8lrOI0= +github.com/hashicorp/serf v0.10.1 h1:Z1H2J60yRKvfDYAOZLd2MU0ND4AH/WDz7xYHDWQsIPY= +github.com/hashicorp/serf v0.10.1/go.mod h1:yL2t6BqATOLGc5HF7qbFkTfXoPIY0WZdWHfEvMqbG+4= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/ipfs/go-log v1.0.5 h1:2dOuUCB1Z7uoczMWgAyDck5JLb72zHzrMnGnCNNbvY8= +github.com/ipfs/go-log v1.0.5/go.mod h1:j0b8ZoR+7+R99LD9jZ6+AJsrzkPbSXbZfGakb5JPtIo= +github.com/ipfs/go-log/v2 v2.1.3 h1:1iS3IU7aXRlbgUpN8yTTpJ53NXYjAe37vcI5+5nYrzk= +github.com/ipfs/go-log/v2 v2.1.3/go.mod h1:/8d0SH3Su5Ooc31QlL1WysJhvyOTDCjcCZ9Axpmri6g= +github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= +github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4= +github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= +github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= +github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso= +github.com/miekg/dns v1.1.41 h1:WMszZWJG0XmzbK9FEmzH2TVcqYzFesusSIB41b8KHxY= +github.com/miekg/dns v1.1.41/go.mod h1:p6aan82bvRIyn+zDIv9xYNUpwa73JcSh9BKwknJysuI= +github.com/mitchellh/cli v1.1.0/go.mod h1:xcISNoH86gajksDmfB23e/pu+B+GeFRMYmoHXxx3xhI= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/nats-io/nats.go v1.31.0 h1:/WFBHEc/dOKBF6qf1TZhrdEfTmOZ5JzdJ+Y3m6Y/p7E= +github.com/nats-io/nats.go v1.31.0/go.mod h1:di3Bm5MLsoB4Bx61CBTsxuarI36WbhAwOm8QrW39+i8= +github.com/nats-io/nkeys v0.4.6 h1:IzVe95ru2CT6ta874rt9saQRkWfe2nFj1NtvYSLqMzY= +github.com/nats-io/nkeys v0.4.6/go.mod h1:4DxZNzenSVd1cYQoAa8948QY3QDjrHfcfVADymtkpts= +github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= +github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= +github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= +github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= +github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= +github.com/otiai10/jsonindent v0.0.0-20171116142732-447bf004320b/go.mod h1:SXIpH2WO0dyF5YBc6Iq8jc8TEJYe1Fk2Rc1EVYUdIgY= +github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= +github.com/otiai10/mint v1.3.2 h1:VYWnrP5fXmz1MXvjuUvcBrXSjGE6xjON+axB/UrpO3E= +github.com/otiai10/mint v1.3.2/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc= +github.com/otiai10/primes v0.0.0-20210501021515-f1b2be525a11 h1:7x5D/2dkkr27Tgh4WFuX+iCS6OzuE5YJoqJzeqM+5mc= +github.com/otiai10/primes v0.0.0-20210501021515-f1b2be525a11/go.mod h1:1DmRMnU78i/OVkMnHzvhXSi4p8IhYUmtLJWhyOavJc0= +github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= +github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= +github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= +github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4= +github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= +github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.31.0 h1:FcTR3NnLWW+NnTwwhFWiJSZr4ECLpqCm6QsEnyvbV4A= +github.com/rs/zerolog v1.31.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= +github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= +github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= +github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= +github.com/samber/lo v1.39.0 h1:4gTz1wUhNYLhFSKl6O+8peW0v2F4BCY034GRpU9WnuA= +github.com/samber/lo v1.39.0/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA= +github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 h1:nn5Wsu0esKSJiIVhscUtVbo7ada43DJhG55ua/hjS5I= +github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= +github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= +github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= +github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= +github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= +github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.18.0 h1:pN6W1ub/G4OfnM+NR9p7xP9R6TltLUzp5JG9yZD3Qg0= +github.com/spf13/viper v1.18.0/go.mod h1:EKmWIqdnk5lOcmR72yw6hS+8OPYcwD0jteitLMVB+yk= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= +github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= +github.com/urfave/cli v1.22.5/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= +go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= +go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= +go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8= +go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= +golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= +golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE= +golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20240112132812-db7319d0e0e3 h1:hNQpMuAJe5CtcUqCXaWga3FHu+kQvCqcsoVaQgSV60o= +golang.org/x/exp v0.0.0-20240112132812-db7319d0e0e3/go.mod h1:idGWGoKP1toJGkd5/ig9ZLuPcZBC3ewk7SzmH0uou08= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY= +golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190922100055-0a153f010e69/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210303074136-134d130e1a04/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= +golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= +golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o= +golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0= +golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190907020128-2ca718005c18/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= +google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= diff --git a/e2e/keygen_test.go b/e2e/keygen_test.go new file mode 100644 index 0000000..42085ce --- /dev/null +++ b/e2e/keygen_test.go @@ -0,0 +1,185 @@ +package e2e + +import ( + "fmt" + "testing" + "time" + + "github.com/fystack/mpcium/pkg/event" + "github.com/fystack/mpcium/pkg/logger" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestKeyGeneration(t *testing.T) { + suite := NewE2ETestSuite(".") + + // Comprehensive cleanup before starting tests + t.Log("Performing pre-test cleanup...") + suite.CleanupTestEnvironment(t) + + // Ensure cleanup happens even if test fails + defer func() { + t.Log("Performing post-test cleanup...") + suite.Cleanup(t) + }() + + // Setup infrastructure + t.Run("Setup", func(t *testing.T) { + t.Log("Starting setupInfrastructure...") + suite.SetupInfrastructure(t) + t.Log("setupInfrastructure completed") + + t.Log("Starting setupTestNodes...") + suite.SetupTestNodes(t) + t.Log("setupTestNodes completed") + + // Load config after setup script runs + err := suite.LoadConfig() + require.NoError(t, err, "Failed to load config after setup") + + t.Log("Starting registerPeers...") + suite.RegisterPeers(t) + t.Log("registerPeers completed") + + t.Log("Starting startNodes...") + suite.StartNodes(t) + t.Log("startNodes completed") + + t.Log("Waiting for node ready") + // Wait for all nodes to be ready before proceeding + suite.WaitForNodesReady(t) + t.Log("Waiting for node completed") + + t.Log("Starting setupMPCClient...") + suite.SetupMPCClient(t) + t.Log("setupMPCClient completed") + + }) + + // Test key generation + t.Run("KeyGeneration", func(t *testing.T) { + testKeyGeneration(t, suite) + }) + + // Verify consistency + t.Run("VerifyConsistency", func(t *testing.T) { + verifyKeyConsistency(t, suite) + }) +} + +func testKeyGeneration(t *testing.T, suite *E2ETestSuite) { + t.Log("Testing key generation...") + + // Ensure MPC client is initialized + if suite.mpcClient == nil { + t.Fatal("MPC client is not initialized. Make sure Setup subtest runs first.") + } + // Generate 1 wallet ID for testing + walletIDs := make([]string, 0, 10) + for i := 0; i < 1; i++ { + walletIDs = append(walletIDs, uuid.New().String()) + suite.walletIDs = append(suite.walletIDs, walletIDs[i]) + } + + logger.Info(fmt.Sprintf("Generated wallet IDs: %v", walletIDs)) + + // Setup result listener + err := suite.mpcClient.OnWalletCreationResult(func(result event.KeygenResultEvent) { + logger.Info("On wallet creation result", "event", result) + t.Logf("Received keygen result for wallet %s: %s", result.WalletID, result.ResultType) + suite.keygenResults[result.WalletID] = &result + + if result.ResultType == event.ResultTypeError { + t.Logf("Keygen failed for wallet %s: %s (%s)", result.WalletID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("Keygen succeeded for wallet %s", result.WalletID) + } + }) + require.NoError(t, err, "Failed to setup keygen result listener") + + // Add a small delay to ensure the result listener is fully set up + time.Sleep(10 * time.Second) + + // Trigger key generation for all wallets + for _, walletID := range walletIDs { + t.Logf("Triggering key generation for wallet %s", walletID) + + err := suite.mpcClient.CreateWallet(walletID) + require.NoError(t, err, "Failed to trigger key generation for wallet %s", walletID) + + // Small delay between requests to avoid overwhelming the system + time.Sleep(500 * time.Millisecond) + } + + // Wait for key generation to complete + t.Log("Waiting for key generation to complete...") + + // Wait up to keygenTimeout for all results + timeout := time.NewTimer(keygenTimeout) + defer timeout.Stop() + + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + + for { + select { + case <-timeout.C: + t.Logf("Timeout waiting for keygen results. Received %d/%d results", len(suite.keygenResults), len(walletIDs)) + // Don't fail immediately, let's check what we got + goto checkResults + case <-ticker.C: + t.Logf("Still waiting... Received %d/%d keygen results", len(suite.keygenResults), len(walletIDs)) + + // Show recent logs from nodes to debug what's happening + t.Log("Recent logs from MPC nodes:") + for i := 0; i < numNodes; i++ { + nodeName := fmt.Sprintf("test_node%d", i) + suite.ShowRecentLogs(t, nodeName) + } + + if len(suite.keygenResults) >= len(walletIDs) { + goto checkResults + } + } + } + +checkResults: + // Check that we got results for all wallets + for _, walletID := range walletIDs { + result, exists := suite.keygenResults[walletID] + if !exists { + t.Errorf("No keygen result received for wallet %s", walletID) + continue + } + + if result.ResultType == event.ResultTypeError { + t.Errorf("Keygen failed for wallet %s: %s (%s)", walletID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("Keygen succeeded for wallet %s", result.WalletID) + assert.NotEmpty(t, result.ECDSAPubKey, "ECDSA public key should not be empty for wallet %s", walletID) + assert.NotEmpty(t, result.EDDSAPubKey, "EdDSA public key should not be empty for wallet %s", walletID) + } + } + + t.Log("Key generation test completed") +} + +func verifyKeyConsistency(t *testing.T, suite *E2ETestSuite) { + t.Log("Verifying key consistency across nodes...") + + // Stop all nodes first to safely access databases + suite.StopNodes(t) + + // Check each wallet's keys in all node databases + for _, walletID := range suite.walletIDs { + t.Logf("Checking wallet %s", walletID) + + // Check both ECDSA and EdDSA keys + suite.CheckKeyInAllNodes(t, walletID, "ecdsa", "ECDSA") + suite.CheckKeyInAllNodes(t, walletID, "eddsa", "EdDSA") + } + + t.Log("Key consistency verification completed") +} diff --git a/e2e/reshare_test.go b/e2e/reshare_test.go new file mode 100644 index 0000000..86cf670 --- /dev/null +++ b/e2e/reshare_test.go @@ -0,0 +1,446 @@ +package e2e + +import ( + "fmt" + "testing" + "time" + + "github.com/fystack/mpcium/pkg/event" + "github.com/fystack/mpcium/pkg/logger" + "github.com/fystack/mpcium/pkg/types" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + resharingTimeout = 10 * time.Minute +) + +func TestResharing(t *testing.T) { + suite := NewE2ETestSuite(".") + logger.Init("dev", true) + + // Comprehensive cleanup before starting tests + t.Log("Performing pre-test cleanup...") + suite.CleanupTestEnvironment(t) + + // Ensure cleanup happens even if test fails + defer func() { + t.Log("Performing post-test cleanup...") + suite.Cleanup(t) + }() + + // Setup phase + t.Run("Setup", func(t *testing.T) { + suite.RunMakeClean() + suite.SetupInfrastructure(t) + suite.SetupTestNodes(t) + suite.RegisterPeers(t) + suite.StartNodes(t) + suite.SetupMPCClient(t) + suite.LoadConfig() + }) + + // Key generation phase + t.Run("KeyGeneration", func(t *testing.T) { + testKeyGenerationForResharing(t, suite) + }) + + // Resharing tests + t.Run("ResharingAllNodes", func(t *testing.T) { + testResharingAllNodes(t, suite) + }) + + // Signing tests after resharing + t.Run("SigningAfterResharing", func(t *testing.T) { + testSigningAfterResharing(t, suite) + }) +} + +func testKeyGenerationForResharing(t *testing.T, suite *E2ETestSuite) { + t.Log("Testing key generation for resharing tests...") + + // Ensure MPC client is initialized + if suite.mpcClient == nil { + t.Fatal("MPC client is not initialized. Make sure Setup subtest runs first.") + } + + // Wait for all nodes to be ready before proceeding + suite.WaitForNodesReady(t) + + // Generate 1 wallet IDs for testing (one for each key type) + walletIDs := make([]string, 1) + for i := 0; i < 1; i++ { + walletIDs[i] = uuid.New().String() + suite.walletIDs = append(suite.walletIDs, walletIDs[i]) + } + + t.Logf("Generated wallet IDs for resharing: %v", walletIDs) + + // Setup result listener + err := suite.mpcClient.OnWalletCreationResult(func(result event.KeygenResultEvent) { + t.Logf("Received keygen result for wallet %s: %s", result.WalletID, result.ResultType) + suite.keygenResults[result.WalletID] = &result + + if result.ResultType == event.ResultTypeError { + t.Logf("Keygen failed for wallet %s: %s (%s)", result.WalletID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("Keygen succeeded for wallet %s", result.WalletID) + } + }) + require.NoError(t, err, "Failed to setup keygen result listener") + + // Add a small delay to ensure the result listener is fully set up + time.Sleep(2 * time.Second) + + // Trigger key generation for all wallets + for _, walletID := range walletIDs { + t.Logf("Triggering key generation for wallet %s", walletID) + + err := suite.mpcClient.CreateWallet(walletID) + require.NoError(t, err, "Failed to trigger key generation for wallet %s", walletID) + + // Small delay between requests to avoid overwhelming the system + time.Sleep(500 * time.Millisecond) + } + + // Wait for key generation to complete + t.Log("Waiting for key generation to complete...") + + // Wait up to keygenTimeout for all results + timeout := time.NewTimer(keygenTimeout) + defer timeout.Stop() + + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + + for { + select { + case <-timeout.C: + t.Logf("Timeout waiting for keygen results. Received %d/%d results", len(suite.keygenResults), len(walletIDs)) + // Don't fail immediately, let's check what we got + goto checkResults + case <-ticker.C: + t.Logf("Still waiting... Received %d/%d keygen results", len(suite.keygenResults), len(walletIDs)) + + if len(suite.keygenResults) >= len(walletIDs) { + goto checkResults + } + } + } + +checkResults: + // Check that we got results for all wallets + for _, walletID := range walletIDs { + result, exists := suite.keygenResults[walletID] + if !exists { + t.Errorf("No keygen result received for wallet %s", walletID) + continue + } + + if result.ResultType == event.ResultTypeError { + t.Errorf("Keygen failed for wallet %s: %s (%s)", walletID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("Keygen succeeded for wallet %s", result.WalletID) + assert.NotEmpty(t, result.ECDSAPubKey, "ECDSA public key should not be empty for wallet %s", walletID) + assert.NotEmpty(t, result.EDDSAPubKey, "EdDSA public key should not be empty for wallet %s", walletID) + } + } + + t.Log("Key generation for resharing tests completed") +} + +func testResharingAllNodes(t *testing.T, suite *E2ETestSuite) { + t.Log("Testing resharing with all nodes online...") + + if len(suite.walletIDs) == 0 { + t.Fatal("No wallets available for resharing. Make sure key generation ran first.") + } + + // Get node IDs for resharing + nodeIDs, err := suite.GetNodeIDs() + require.NoError(t, err, "Failed to get node IDs") + require.GreaterOrEqual(t, len(nodeIDs), 2, "Need at least 2 nodes for resharing") + + t.Logf("Available node IDs for resharing: %v", nodeIDs) + + // Setup a shared resharing result listener for all resharing tests + err = suite.mpcClient.OnResharingResult(func(result event.ResharingResultEvent) { + t.Logf("Received resharing result for wallet %s: %s", result.WalletID, result.ResultType) + suite.resharingResults[result.WalletID] = &result + + if result.ResultType == event.ResultTypeError { + t.Logf("Resharing failed for wallet %s: %s (%s)", result.WalletID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("Resharing succeeded for wallet %s", result.WalletID) + } + }) + require.NoError(t, err, "Failed to setup resharing result listener") + + // Wait for listener setup + time.Sleep(2 * time.Second) + + // Test resharing for both key types + for i, walletID := range suite.walletIDs { + t.Logf("Testing resharing for wallet %s", walletID) + + // Test ECDSA resharing (first wallet) + if i == 0 { + t.Run(fmt.Sprintf("ECDSA_Resharing_%s", walletID), func(t *testing.T) { + testECDSAResharing(t, suite, walletID, nodeIDs) + }) + } + + // Test EdDSA resharing (second wallet) + if i == 1 { + t.Run(fmt.Sprintf("EdDSA_Resharing_%s", walletID), func(t *testing.T) { + testEdDSAResharing(t, suite, walletID, nodeIDs) + }) + } + } + + t.Log("Resharing with all nodes completed") +} + +func testECDSAResharing(t *testing.T, suite *E2ETestSuite, walletID string, nodeIDs []string) { + t.Logf("Testing ECDSA resharing for wallet %s", walletID) + + // Create resharing message for ECDSA + sessionID := uuid.New().String() + resharingMsg := &types.ResharingMessage{ + SessionID: sessionID, + WalletID: walletID, + NodeIDs: nodeIDs[:2], // Use first 2 nodes for resharing + NewThreshold: 1, // New threshold of 2 + KeyType: types.KeyTypeSecp256k1, + } + + t.Logf("Sending ECDSA resharing message for wallet %s with session ID %s", walletID, sessionID) + t.Logf("New committee: %v, New threshold: %d", resharingMsg.NodeIDs, resharingMsg.NewThreshold) + + // Send resharing message + err := suite.mpcClient.Resharing(resharingMsg) + require.NoError(t, err, "Failed to send ECDSA resharing message") + + // Wait for resharing result + t.Log("Waiting for ECDSA resharing result...") + + timeout := time.NewTimer(resharingTimeout) + defer timeout.Stop() + + ticker := time.NewTicker(10 * time.Second) + defer ticker.Stop() + + for { + select { + case <-timeout.C: + t.Fatalf("Timeout waiting for ECDSA resharing result for wallet %s", walletID) + case <-ticker.C: + t.Logf("Still waiting for ECDSA resharing result for wallet %s...", walletID) + + // Check if we got a result + if _, exists := suite.resharingResults[walletID]; exists { + goto checkECDSAResult + } + } + } + +checkECDSAResult: + // Verify the resharing result + result, exists := suite.resharingResults[walletID] + require.True(t, exists, "No ECDSA resharing result received for wallet %s", walletID) + + if result.ResultType == event.ResultTypeError { + t.Fatalf("ECDSA resharing failed for wallet %s: %s (%s)", walletID, result.ErrorReason, result.ErrorCode) + } + + t.Logf("ECDSA resharing succeeded for wallet %s", walletID) + t.Logf("New public key: %x", result.PubKey) + t.Logf("New threshold: %d", result.NewThreshold) + t.Logf("Key type: %s", result.KeyType) + + // Verify the resharing result + assert.Equal(t, event.ResultTypeSuccess, result.ResultType, "ECDSA resharing should succeed") + assert.Equal(t, walletID, result.WalletID, "Wallet ID should match") + assert.Equal(t, resharingMsg.NewThreshold, result.NewThreshold, "New threshold should match") + assert.Equal(t, types.KeyTypeSecp256k1, result.KeyType, "Key type should be secp256k1") + assert.NotEmpty(t, result.PubKey, "Public key should not be empty") + + t.Log("ECDSA resharing verification completed successfully") +} + +func testEdDSAResharing(t *testing.T, suite *E2ETestSuite, walletID string, nodeIDs []string) { + t.Logf("Testing EdDSA resharing for wallet %s", walletID) + + // Create resharing message for EdDSA + sessionID := uuid.New().String() + resharingMsg := &types.ResharingMessage{ + SessionID: sessionID, + WalletID: walletID, + NodeIDs: nodeIDs[:2], // Use first 2 nodes for resharing + NewThreshold: 1, // New threshold of 2 + KeyType: types.KeyTypeEd25519, + } + + t.Logf("Sending EdDSA resharing message for wallet %s with session ID %s", walletID, sessionID) + t.Logf("New committee: %v, New threshold: %d", resharingMsg.NodeIDs, resharingMsg.NewThreshold) + + // Send resharing message + err := suite.mpcClient.Resharing(resharingMsg) + require.NoError(t, err, "Failed to send EdDSA resharing message") + + // Wait for resharing result + t.Log("Waiting for EdDSA resharing result...") + + timeout := time.NewTimer(resharingTimeout) + defer timeout.Stop() + + ticker := time.NewTicker(10 * time.Second) + defer ticker.Stop() + + for { + select { + case <-timeout.C: + t.Fatalf("Timeout waiting for EdDSA resharing result for wallet %s", walletID) + case <-ticker.C: + t.Logf("Still waiting for EdDSA resharing result for wallet %s...", walletID) + + // Check if we got a result + if _, exists := suite.resharingResults[walletID]; exists { + goto checkEdDSAResult + } + } + } + +checkEdDSAResult: + // Verify the resharing result + result, exists := suite.resharingResults[walletID] + require.True(t, exists, "No EdDSA resharing result received for wallet %s", walletID) + + if result.ResultType == event.ResultTypeError { + t.Fatalf("EdDSA resharing failed for wallet %s: %s (%s)", walletID, result.ErrorReason, result.ErrorCode) + } + + t.Logf("EdDSA resharing succeeded for wallet %s", walletID) + t.Logf("New public key: %x", result.PubKey) + t.Logf("New threshold: %d", result.NewThreshold) + t.Logf("Key type: %s", result.KeyType) + + // Verify the resharing result + assert.Equal(t, event.ResultTypeSuccess, result.ResultType, "EdDSA resharing should succeed") + assert.Equal(t, walletID, result.WalletID, "Wallet ID should match") + assert.Equal(t, resharingMsg.NewThreshold, result.NewThreshold, "New threshold should match") + assert.Equal(t, types.KeyTypeEd25519, result.KeyType, "Key type should be ed25519") + assert.NotEmpty(t, result.PubKey, "Public key should not be empty") + + t.Log("EdDSA resharing verification completed successfully") +} + +func testSigningAfterResharing(t *testing.T, suite *E2ETestSuite) { + t.Log("Testing signing after resharing to verify reshared keys work correctly...") + + if len(suite.walletIDs) == 0 { + t.Fatal("No wallets available for signing after resharing. Make sure resharing ran first.") + } + + // Setup a shared signing result listener for all signing tests + signingResults := make(map[string]*event.SigningResultEvent) + err := suite.mpcClient.OnSignResult(func(result event.SigningResultEvent) { + t.Logf("Received signing result for wallet %s (tx: %s): %s", result.WalletID, result.TxID, result.ResultType) + // Use TxID as key to avoid conflicts between different signing operations + signingResults[result.TxID] = &result + + if result.ResultType == event.ResultTypeError { + t.Logf("Signing failed for wallet %s (tx: %s): %s (%s)", result.WalletID, result.TxID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("Signing succeeded for wallet %s (tx: %s)", result.WalletID, result.TxID) + } + }) + require.NoError(t, err, "Failed to setup signing result listener") + + // Wait for listener setup + time.Sleep(2 * time.Second) + + // Test messages to sign + testMessages := []string{ + "Reshared key test message 1", + "Reshared key test message 2", + } + + for _, walletID := range suite.walletIDs { + t.Logf("Testing signing with reshared keys for wallet %s", walletID) + + for i, message := range testMessages { + t.Logf("Signing message %d: %s", i+1, message) + + // Test ECDSA signing with reshared keys + t.Run(fmt.Sprintf("ECDSA_Reshared_%s_%d", walletID, i), func(t *testing.T) { + testECDSASigningAfterResharing(t, suite, walletID, message, signingResults) + }) + } + } + + t.Log("Signing after resharing completed") +} + +func testECDSASigningAfterResharing(t *testing.T, suite *E2ETestSuite, walletID, message string, signingResults map[string]*event.SigningResultEvent) { + t.Logf("Testing ECDSA signing with reshared keys for wallet %s with message: %s", walletID, message) + + // Wait for listener setup + time.Sleep(1 * time.Second) + + // Create a signing transaction message + txID := uuid.New().String() + signTxMsg := &types.SignTxMessage{ + WalletID: walletID, + TxID: txID, + Tx: []byte(message), + KeyType: types.KeyTypeSecp256k1, + NetworkInternalCode: "test", + } + + // Trigger ECDSA signing + err := suite.mpcClient.SignTransaction(signTxMsg) + require.NoError(t, err, "Failed to trigger ECDSA signing for wallet %s", walletID) + + // Wait for signing result + timeout := time.NewTimer(signingTimeout) + defer timeout.Stop() + + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + + for { + select { + case <-timeout.C: + t.Fatalf("Timeout waiting for ECDSA signing result for wallet %s", walletID) + case <-ticker.C: + if result, exists := signingResults[txID]; exists { + t.Logf("Received ECDSA signing result for wallet %s", walletID) + if result.ResultType == event.ResultTypeError { + t.Errorf("ECDSA signing failed for wallet %s: %s (%s)", walletID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("ECDSA signing with reshared keys succeeded for wallet %s", walletID) + assert.NotEmpty(t, result.R, "ECDSA R value should not be empty for wallet %s", walletID) + assert.NotEmpty(t, result.S, "ECDSA S value should not be empty for wallet %s", walletID) + assert.NotEmpty(t, result.SignatureRecovery, "ECDSA signature recovery should not be empty for wallet %s", walletID) + + // Compose the signature using the proper function + composedSig, err := ComposeSignature(result.SignatureRecovery, result.R, result.S) + if err != nil { + t.Errorf("Failed to compose ECDSA signature for wallet %s: %v", walletID, err) + } else { + t.Logf("Successfully composed ECDSA signature for wallet %s: %d bytes", walletID, len(composedSig)) + assert.Equal(t, 65, len(composedSig), "Composed ECDSA signature should be 65 bytes for wallet %s", walletID) + + // Log the signature components for debugging + t.Logf("ECDSA signature components - R: %d bytes, S: %d bytes, V: %d bytes", + len(result.R), len(result.S), len(result.SignatureRecovery)) + } + } + return + } + } + } +} diff --git a/e2e/setup_test_identities.sh b/e2e/setup_test_identities.sh new file mode 100755 index 0000000..c2a29c6 --- /dev/null +++ b/e2e/setup_test_identities.sh @@ -0,0 +1,135 @@ +#!/bin/bash + +# E2E Test Identity Setup Script +# This script sets up identities for testing with separate test database paths + +set -e + +# Number of test nodes +NUM_NODES=3 +BASE_DIR="$(pwd)" +TEST_DB_PATH="$BASE_DIR/test_db" + +echo "๐Ÿš€ Setting up E2E Test Node Identities..." + +# Generate random password for badger encryption +echo "๐Ÿ” Generating random password for badger encryption..." +BADGER_PASSWORD=$(< /dev/urandom tr -dc 'A-Za-z0-9' | head -c 32) +echo "โœ… Generated password: $BADGER_PASSWORD" + +# Generate config.test.yaml from template +echo "๐Ÿ“ Generating config.test.yaml from template..." +if [ ! -f "config.test.yaml.template" ]; then + echo "โŒ Template file config.test.yaml.template not found" + exit 1 +fi + +# Create a temporary config with placeholder values (will be updated later with real pubkey) +TEMP_PUBKEY="0000000000000000000000000000000000000000000000000000000000000000" + +# Escape special characters in password for sed +ESCAPED_PASSWORD=$(printf '%s\n' "$BADGER_PASSWORD" | sed 's/[[\.*^$()+?{|]/\\&/g') + +sed -e "s/{{\.BadgerPassword}}/$ESCAPED_PASSWORD/g" \ + -e "s/{{\.EventInitiatorPubkey}}/$TEMP_PUBKEY/g" \ + config.test.yaml.template > config.test.yaml + +echo "โœ… Generated config.test.yaml from template" + +# Clean up any existing test data +echo "๐Ÿงน Cleaning up existing test data..." +rm -rf "$TEST_DB_PATH" +rm -rf "$BASE_DIR"/test_node* + +# Create test node directories +echo "๐Ÿ“ Creating test node directories..." +# Generate UUIDs for the nodes +NODE0_UUID=$(uuidgen) +NODE1_UUID=$(uuidgen) +NODE2_UUID=$(uuidgen) + +for i in $(seq 0 $((NUM_NODES-1))); do + mkdir -p "$BASE_DIR/test_node$i/identity" + cp "$BASE_DIR/config.test.yaml" "$BASE_DIR/test_node$i/config.yaml" + + # Create peers.json with proper UUIDs + cat > "$BASE_DIR/test_node$i/peers.json" << EOF +{ + "test_node0": "$NODE0_UUID", + "test_node1": "$NODE1_UUID", + "test_node2": "$NODE2_UUID" +} +EOF +done + +# Generate identity for each test node +echo "๐Ÿ”‘ Generating identities for each test node..." +for i in $(seq 0 $((NUM_NODES-1))); do + echo "๐Ÿ“ Generating identity for test_node$i..." + cd "$BASE_DIR/test_node$i" + + # Generate identity using mpcium-cli + mpcium-cli generate-identity --node "test_node$i" + + cd - > /dev/null +done + +# Distribute identity files to all test nodes +echo "๐Ÿ”„ Distributing identity files across test nodes..." +for i in $(seq 0 $((NUM_NODES-1))); do + for j in $(seq 0 $((NUM_NODES-1))); do + if [ $i != $j ]; then + echo "๐Ÿ“‹ Copying test_node${i}_identity.json to test_node$j..." + cp "$BASE_DIR/test_node$i/identity/test_node${i}_identity.json" "$BASE_DIR/test_node$j/identity/" + fi + done +done + +# Generate test event initiator +echo "๐Ÿ” Generating test event initiator..." +cd "$BASE_DIR" +mpcium-cli generate-initiator --node-name test_event_initiator --output-dir . --overwrite + +# Extract the public key from the generated identity +if [ -f "test_event_initiator.identity.json" ]; then + PUBKEY=$(cat test_event_initiator.identity.json | jq -r '.public_key') + echo "๐Ÿ“ Updating config files with event initiator public key and password..." + + # Update all test node config files with the actual public key and password + for i in $(seq 0 $((NUM_NODES-1))); do + # Update public key using sed with | as delimiter (safer than /) + sed -i "s|event_initiator_pubkey:.*|event_initiator_pubkey: $PUBKEY|g" "$BASE_DIR/test_node$i/config.yaml" + # Update password using sed with | as delimiter and escaped password + sed -i "s|badger_password:.*|badger_password: $ESCAPED_PASSWORD|g" "$BASE_DIR/test_node$i/config.yaml" + done + + # Also update the main config.test.yaml + sed -i "s|event_initiator_pubkey:.*|event_initiator_pubkey: $PUBKEY|g" "$BASE_DIR/config.test.yaml" + sed -i "s|badger_password:.*|badger_password: $ESCAPED_PASSWORD|g" "$BASE_DIR/config.test.yaml" + + echo "โœ… Event initiator public key updated: $PUBKEY" + echo "โœ… Badger password updated: $BADGER_PASSWORD" +else + echo "โŒ Failed to generate event initiator identity" + exit 1 +fi + +cd - > /dev/null + +echo "โœจ E2E Test identities setup complete!" +echo +echo "๐Ÿ“‚ Created test folder structure:" +echo "โ”œโ”€โ”€ test_node0" +echo "โ”‚ โ”œโ”€โ”€ config.yaml" +echo "โ”‚ โ”œโ”€โ”€ identity/" +echo "โ”‚ โ””โ”€โ”€ peers.json" +echo "โ”œโ”€โ”€ test_node1" +echo "โ”‚ โ”œโ”€โ”€ config.yaml" +echo "โ”‚ โ”œโ”€โ”€ identity/" +echo "โ”‚ โ””โ”€โ”€ peers.json" +echo "โ””โ”€โ”€ test_node2" +echo " โ”œโ”€โ”€ config.yaml" +echo " โ”œโ”€โ”€ identity/" +echo " โ””โ”€โ”€ peers.json" +echo +echo "โœ… Test nodes are ready for E2E testing!" diff --git a/e2e/sign_test.go b/e2e/sign_test.go new file mode 100644 index 0000000..c5d454f --- /dev/null +++ b/e2e/sign_test.go @@ -0,0 +1,561 @@ +package e2e + +import ( + "errors" + "fmt" + "math/big" + "testing" + "time" + + "github.com/fystack/mpcium/pkg/event" + "github.com/fystack/mpcium/pkg/logger" + "github.com/fystack/mpcium/pkg/types" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var ErrInvalidSig = errors.New("invalid signature") + +// ComposeSignature composes a signature from v, r, s components +func ComposeSignature(v, r, s []byte) ([]byte, error) { + V := v[0] + if !validateSignatureValues( + V, + new(big.Int).SetBytes(r), + new(big.Int).SetBytes(s), false) { + return nil, ErrInvalidSig + } + // encode the signature in uncompressed format + sig := make([]byte, 65) + copy(sig[32-len(r):32], r) + copy(sig[64-len(s):64], s) + sig[64] = V + return sig, nil +} + +// validateSignatureValues verifies whether the signature values are valid +func validateSignatureValues(v uint8, r, s *big.Int, homestead bool) bool { + if r.Cmp(big.NewInt(1)) < 0 || s.Cmp(big.NewInt(1)) < 0 { + return false + } + // reject upper range of s values (ECDSA malleability) + // see discussion in secp256k1/libsecp256k1/include/secp256k1.h + if homestead && s.Cmp(secp256k1halfN) > 0 { + return false + } + // Frontier: allow s to be in full N range + return r.Cmp(secp256k1N) < 0 && s.Cmp(secp256k1N) < 0 && (v == 0 || v == 1) +} + +var ( + secp256k1N, _ = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16) + secp256k1halfN = new(big.Int).Div(secp256k1N, big.NewInt(2)) +) + +func TestSigning(t *testing.T) { + suite := NewE2ETestSuite(".") + logger.Init("dev", true) + + // Comprehensive cleanup before starting tests + t.Log("Performing pre-test cleanup...") + suite.CleanupTestEnvironment(t) + + // Ensure cleanup happens even if test fails + defer func() { + t.Log("Performing post-test cleanup...") + suite.Cleanup(t) + }() + + // Setup infrastructure + t.Run("Setup", func(t *testing.T) { + // Run make clean first to ensure a clean build + t.Log("Running make clean to ensure clean build...") + err := suite.RunMakeClean() + require.NoError(t, err, "Failed to run make clean") + t.Log("make clean completed") + + t.Log("Starting setupInfrastructure...") + suite.SetupInfrastructure(t) + t.Log("setupInfrastructure completed") + + t.Log("Starting setupTestNodes...") + suite.SetupTestNodes(t) + t.Log("setupTestNodes completed") + + // Load config after setup script runs + err = suite.LoadConfig() + require.NoError(t, err, "Failed to load config after setup") + + t.Log("Starting registerPeers...") + suite.RegisterPeers(t) + t.Log("registerPeers completed") + + t.Log("Starting setupMPCClient...") + suite.SetupMPCClient(t) + t.Log("setupMPCClient completed") + + t.Log("Starting startNodes...") + suite.StartNodes(t) + t.Log("startNodes completed") + }) + + // Test key generation first + t.Run("KeyGenerationForSigning", func(t *testing.T) { + testKeyGenerationForSigning(t, suite) + }) + + // Test signing with all nodes + t.Run("SigningAllNodes", func(t *testing.T) { + testSigningAllNodes(t, suite) + }) + + // // Test signing with one node offline + // t.Run("SigningOneNodeOffline", func(t *testing.T) { + // testSigningOneNodeOffline(t, suite) + // }) +} + +func testKeyGenerationForSigning(t *testing.T, suite *E2ETestSuite) { + t.Log("Testing key generation for signing tests...") + + // Ensure MPC client is initialized + if suite.mpcClient == nil { + t.Fatal("MPC client is not initialized. Make sure Setup subtest runs first.") + } + + // Wait for all nodes to be ready before proceeding + suite.WaitForNodesReady(t) + + // Generate 1 wallet ID for testing + walletIDs := make([]string, 1) + for i := 0; i < 1; i++ { + walletIDs[i] = uuid.New().String() + suite.walletIDs = append(suite.walletIDs, walletIDs[i]) + } + + t.Logf("Generated wallet IDs: %v", walletIDs) + + // Setup result listener + err := suite.mpcClient.OnWalletCreationResult(func(result event.KeygenResultEvent) { + t.Logf("Received keygen result for wallet %s: %s", result.WalletID, result.ResultType) + suite.keygenResults[result.WalletID] = &result + + if result.ResultType == event.ResultTypeError { + t.Logf("Keygen failed for wallet %s: %s (%s)", result.WalletID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("Keygen succeeded for wallet %s", result.WalletID) + } + }) + require.NoError(t, err, "Failed to setup keygen result listener") + + // Add a small delay to ensure the result listener is fully set up + time.Sleep(2 * time.Second) + + // Trigger key generation for all wallets + for _, walletID := range walletIDs { + t.Logf("Triggering key generation for wallet %s", walletID) + + err := suite.mpcClient.CreateWallet(walletID) + require.NoError(t, err, "Failed to trigger key generation for wallet %s", walletID) + + // Small delay between requests to avoid overwhelming the system + time.Sleep(500 * time.Millisecond) + } + + // Wait for key generation to complete + t.Log("Waiting for key generation to complete...") + + // Wait up to keygenTimeout for all results + timeout := time.NewTimer(keygenTimeout) + defer timeout.Stop() + + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + + for { + select { + case <-timeout.C: + t.Logf("Timeout waiting for keygen results. Received %d/%d results", len(suite.keygenResults), len(walletIDs)) + // Don't fail immediately, let's check what we got + goto checkResults + case <-ticker.C: + t.Logf("Still waiting... Received %d/%d keygen results", len(suite.keygenResults), len(walletIDs)) + + if len(suite.keygenResults) >= len(walletIDs) { + goto checkResults + } + } + } + +checkResults: + // Check that we got results for all wallets + for _, walletID := range walletIDs { + result, exists := suite.keygenResults[walletID] + if !exists { + t.Errorf("No keygen result received for wallet %s", walletID) + continue + } + + if result.ResultType == event.ResultTypeError { + t.Errorf("Keygen failed for wallet %s: %s (%s)", walletID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("Keygen succeeded for wallet %s", result.WalletID) + assert.NotEmpty(t, result.ECDSAPubKey, "ECDSA public key should not be empty for wallet %s", walletID) + assert.NotEmpty(t, result.EDDSAPubKey, "EdDSA public key should not be empty for wallet %s", walletID) + } + } + + t.Log("Key generation for signing tests completed") +} + +func testSigningAllNodes(t *testing.T, suite *E2ETestSuite) { + t.Log("Testing signing with all nodes online...") + + if len(suite.walletIDs) == 0 { + t.Fatal("No wallets available for signing. Make sure key generation ran first.") + } + + // Setup a shared signing result listener for all signing tests + signingResults := make(map[string]*event.SigningResultEvent) + err := suite.mpcClient.OnSignResult(func(result event.SigningResultEvent) { + t.Logf("Received signing result for wallet %s (tx: %s): %s", result.WalletID, result.TxID, result.ResultType) + // Use TxID as key to avoid conflicts between different signing operations + signingResults[result.TxID] = &result + + if result.ResultType == event.ResultTypeError { + t.Logf("Signing failed for wallet %s (tx: %s): %s (%s)", result.WalletID, result.TxID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("Signing succeeded for wallet %s (tx: %s)", result.WalletID, result.TxID) + } + }) + require.NoError(t, err, "Failed to setup signing result listener") + + // Wait for listener setup + time.Sleep(2 * time.Second) + + // Test messages to sign + testMessages := []string{ + "Hello, MPC World!", + "Test message 2", + "Test message 3", + } + + for _, walletID := range suite.walletIDs { + t.Logf("Testing signing for wallet %s", walletID) + + for i, message := range testMessages { + t.Logf("Signing message %d: %s", i+1, message) + + // Test ECDSA signing + t.Run(fmt.Sprintf("ECDSA_%s_%d", walletID, i), func(t *testing.T) { + testECDSASigningWithSharedListener(t, suite, walletID, message, signingResults) + }) + + // Test EdDSA signing + t.Run(fmt.Sprintf("EdDSA_%s_%d", walletID, i), func(t *testing.T) { + testEdDSASigningWithSharedListener(t, suite, walletID, message, signingResults) + }) + } + } + + t.Log("Signing with all nodes completed") +} + +func testSigningOneNodeOffline(t *testing.T, suite *E2ETestSuite) { + t.Log("Testing signing with one node offline...") + + if len(suite.walletIDs) == 0 { + t.Fatal("No wallets available for signing. Make sure key generation ran first.") + } + + // Stop one node (node 2) + nodeToStop := 2 + t.Logf("Stopping node %d to test fault tolerance...", nodeToStop) + + if nodeToStop < len(suite.mpciumProcesses) && suite.mpciumProcesses[nodeToStop] != nil { + err := suite.mpciumProcesses[nodeToStop].Process.Kill() + if err != nil { + t.Logf("Failed to stop node %d: %v", nodeToStop, err) + } else { + t.Logf("Successfully stopped node %d", nodeToStop) + // Mark as stopped + suite.mpciumProcesses[nodeToStop] = nil + } + } + + // Wait a bit for the network to adjust + time.Sleep(5 * time.Second) + + // Test signing with reduced nodes + walletID := suite.walletIDs[0] // Use first wallet + message := "Fault tolerance test message" + + t.Logf("Testing signing with wallet %s and one node offline", walletID) + + // Test ECDSA signing with one node offline + t.Run("ECDSA_OneNodeOffline", func(t *testing.T) { + testECDSASigning(t, suite, walletID, message) + }) + + // Test EdDSA signing with one node offline + t.Run("EdDSA_OneNodeOffline", func(t *testing.T) { + testEdDSASigning(t, suite, walletID, message) + }) + + t.Log("Signing with one node offline completed") +} + +func testECDSASigning(t *testing.T, suite *E2ETestSuite, walletID, message string) { + t.Logf("Testing ECDSA signing for wallet %s with message: %s", walletID, message) + + // Setup signing result listener + signingResults := make(map[string]*event.SigningResultEvent) + err := suite.mpcClient.OnSignResult(func(result event.SigningResultEvent) { + t.Logf("Received ECDSA signing result for wallet %s: %s", result.WalletID, result.ResultType) + signingResults[result.WalletID] = &result + + if result.ResultType == event.ResultTypeError { + t.Logf("ECDSA signing failed for wallet %s: %s (%s)", result.WalletID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("ECDSA signing succeeded for wallet %s", result.WalletID) + } + }) + require.NoError(t, err, "Failed to setup ECDSA signing result listener") + + // Wait for listener setup + time.Sleep(1 * time.Second) + + // Create a signing transaction message + txID := uuid.New().String() + signTxMsg := &types.SignTxMessage{ + WalletID: walletID, + TxID: txID, + Tx: []byte(message), + KeyType: types.KeyTypeSecp256k1, + NetworkInternalCode: "test", + } + + // Trigger ECDSA signing + err = suite.mpcClient.SignTransaction(signTxMsg) + require.NoError(t, err, "Failed to trigger ECDSA signing for wallet %s", walletID) + + // Wait for signing result + timeout := time.NewTimer(signingTimeout) + defer timeout.Stop() + + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + + for { + select { + case <-timeout.C: + t.Fatalf("Timeout waiting for ECDSA signing result for wallet %s", walletID) + case <-ticker.C: + if result, exists := signingResults[txID]; exists { + logger.Info("Received ECDSA signing result for wallet", "result", result) + if result.ResultType == event.ResultTypeError { + t.Errorf("ECDSA signing failed for wallet %s: %s (%s)", walletID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("ECDSA signing succeeded for wallet %s", walletID) + assert.NotEmpty(t, result.R, "ECDSA R value should not be empty for wallet %s", walletID) + assert.NotEmpty(t, result.S, "ECDSA S value should not be empty for wallet %s", walletID) + assert.NotEmpty(t, result.SignatureRecovery, "ECDSA signature recovery should not be empty for wallet %s", walletID) + + // Compose the signature using the proper function + composedSig, err := ComposeSignature(result.SignatureRecovery, result.R, result.S) + if err != nil { + t.Errorf("Failed to compose ECDSA signature for wallet %s: %v", walletID, err) + } else { + t.Logf("Successfully composed ECDSA signature for wallet %s: %d bytes", walletID, len(composedSig)) + assert.Equal(t, 65, len(composedSig), "Composed ECDSA signature should be 65 bytes for wallet %s", walletID) + + // Log the signature components for debugging + t.Logf("ECDSA signature components - R: %d bytes, S: %d bytes, V: %d bytes", + len(result.R), len(result.S), len(result.SignatureRecovery)) + } + } + return + } + } + } +} + +func testEdDSASigning(t *testing.T, suite *E2ETestSuite, walletID, message string) { + t.Logf("Testing EdDSA signing for wallet %s with message: %s", walletID, message) + + // Setup signing result listener + signingResults := make(map[string]*event.SigningResultEvent) + err := suite.mpcClient.OnSignResult(func(result event.SigningResultEvent) { + t.Logf("Received EdDSA signing result for wallet %s: %s", result.WalletID, result.ResultType) + signingResults[result.WalletID] = &result + + if result.ResultType == event.ResultTypeError { + t.Logf("EdDSA signing failed for wallet %s: %s (%s)", result.WalletID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("EdDSA signing succeeded for wallet %s", result.WalletID) + } + }) + require.NoError(t, err, "Failed to setup EdDSA signing result listener") + + // Wait for listener setup + time.Sleep(1 * time.Second) + + // Create a signing transaction message + txID := uuid.New().String() + signTxMsg := &types.SignTxMessage{ + WalletID: walletID, + TxID: txID, + Tx: []byte(message), + KeyType: types.KeyTypeEd25519, + NetworkInternalCode: "test", + } + + // Trigger EdDSA signing + err = suite.mpcClient.SignTransaction(signTxMsg) + require.NoError(t, err, "Failed to trigger EdDSA signing for wallet %s", walletID) + + // Wait for signing result + timeout := time.NewTimer(signingTimeout) + defer timeout.Stop() + + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + + for { + select { + case <-timeout.C: + t.Fatalf("Timeout waiting for EdDSA signing result for wallet %s", walletID) + case <-ticker.C: + if result, exists := signingResults[walletID]; exists { + logger.Info("Received EdDSA signing result for wallet", "result", result) + if result.ResultType == event.ResultTypeError { + t.Errorf("EdDSA signing failed for wallet %s: %s (%s)", walletID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("EdDSA signing succeeded for wallet %s", walletID) + assert.NotEmpty(t, result.Signature, "EdDSA signature should not be empty for wallet %s", walletID) + + // EdDSA signatures are typically 64 bytes (32 bytes R + 32 bytes S) + t.Logf("EdDSA signature length: %d bytes", len(result.Signature)) + if len(result.Signature) > 0 { + assert.Equal(t, 64, len(result.Signature), "EdDSA signature should be 64 bytes for wallet %s", walletID) + } + } + return + } + } + } +} + +func testECDSASigningWithSharedListener(t *testing.T, suite *E2ETestSuite, walletID, message string, signingResults map[string]*event.SigningResultEvent) { + t.Logf("Testing ECDSA signing for wallet %s with message: %s", walletID, message) + + // Wait for listener setup + time.Sleep(1 * time.Second) + + // Create a signing transaction message + txID := uuid.New().String() + signTxMsg := &types.SignTxMessage{ + WalletID: walletID, + TxID: txID, + Tx: []byte(message), + KeyType: types.KeyTypeSecp256k1, + NetworkInternalCode: "test", + } + + // Trigger ECDSA signing + err := suite.mpcClient.SignTransaction(signTxMsg) + require.NoError(t, err, "Failed to trigger ECDSA signing for wallet %s", walletID) + + // Wait for signing result + timeout := time.NewTimer(signingTimeout) + defer timeout.Stop() + + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + + for { + select { + case <-timeout.C: + t.Fatalf("Timeout waiting for ECDSA signing result for wallet %s", walletID) + case <-ticker.C: + if result, exists := signingResults[txID]; exists { + logger.Info("Received ECDSA signing result for wallet", "result", result) + if result.ResultType == event.ResultTypeError { + t.Errorf("ECDSA signing failed for wallet %s: %s (%s)", walletID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("ECDSA signing succeeded for wallet %s", walletID) + assert.NotEmpty(t, result.R, "ECDSA R value should not be empty for wallet %s", walletID) + assert.NotEmpty(t, result.S, "ECDSA S value should not be empty for wallet %s", walletID) + assert.NotEmpty(t, result.SignatureRecovery, "ECDSA signature recovery should not be empty for wallet %s", walletID) + + // Compose the signature using the proper function + composedSig, err := ComposeSignature(result.SignatureRecovery, result.R, result.S) + if err != nil { + t.Errorf("Failed to compose ECDSA signature for wallet %s: %v", walletID, err) + } else { + t.Logf("Successfully composed ECDSA signature for wallet %s: %d bytes", walletID, len(composedSig)) + assert.Equal(t, 65, len(composedSig), "Composed ECDSA signature should be 65 bytes for wallet %s", walletID) + + // Log the signature components for debugging + t.Logf("ECDSA signature components - R: %d bytes, S: %d bytes, V: %d bytes", + len(result.R), len(result.S), len(result.SignatureRecovery)) + } + } + return + } + } + } +} + +func testEdDSASigningWithSharedListener(t *testing.T, suite *E2ETestSuite, walletID, message string, signingResults map[string]*event.SigningResultEvent) { + t.Logf("Testing EdDSA signing for wallet %s with message: %s", walletID, message) + + // Wait for listener setup + time.Sleep(1 * time.Second) + + // Create a signing transaction message + txID := uuid.New().String() + signTxMsg := &types.SignTxMessage{ + WalletID: walletID, + TxID: txID, + Tx: []byte(message), + KeyType: types.KeyTypeEd25519, + NetworkInternalCode: "test", + } + + // Trigger EdDSA signing + err := suite.mpcClient.SignTransaction(signTxMsg) + require.NoError(t, err, "Failed to trigger EdDSA signing for wallet %s", walletID) + + // Wait for signing result + timeout := time.NewTimer(signingTimeout) + defer timeout.Stop() + + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + + for { + select { + case <-timeout.C: + t.Fatalf("Timeout waiting for EdDSA signing result for wallet %s", walletID) + case <-ticker.C: + if result, exists := signingResults[txID]; exists { + logger.Info("Received EdDSA signing result for wallet", "result", result) + if result.ResultType == event.ResultTypeError { + t.Errorf("EdDSA signing failed for wallet %s: %s (%s)", walletID, result.ErrorReason, result.ErrorCode) + } else { + t.Logf("EdDSA signing succeeded for wallet %s", walletID) + assert.NotEmpty(t, result.Signature, "EdDSA signature should not be empty for wallet %s", walletID) + + // EdDSA signatures are typically 64 bytes (32 bytes R + 32 bytes S) + t.Logf("EdDSA signature length: %d bytes", len(result.Signature)) + if len(result.Signature) > 0 { + assert.Equal(t, 64, len(result.Signature), "EdDSA signature should be 64 bytes for wallet %s", walletID) + } + } + return + } + } + } +} diff --git a/go.mod b/go.mod index 2d96a3e..664af48 100644 --- a/go.mod +++ b/go.mod @@ -83,7 +83,7 @@ require ( golang.org/x/crypto v0.37.0 // indirect golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect golang.org/x/net v0.39.0 // indirect - golang.org/x/sys v0.32.0 // indirect + golang.org/x/sys v0.33.0 // indirect golang.org/x/text v0.24.0 // indirect google.golang.org/protobuf v1.36.6 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect diff --git a/go.sum b/go.sum index df1895b..9b616a2 100644 --- a/go.sum +++ b/go.sum @@ -308,8 +308,6 @@ github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= -github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= @@ -375,6 +373,8 @@ go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= +go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= @@ -481,8 +481,8 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= -golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= +golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= diff --git a/pkg/common/errors/errors_test.go b/pkg/common/errors/errors_test.go new file mode 100644 index 0000000..388b5fa --- /dev/null +++ b/pkg/common/errors/errors_test.go @@ -0,0 +1,69 @@ +package errors + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestWrap(t *testing.T) { + originalErr := errors.New("original error") + wrappingMessage := "additional context" + + wrappedErr := Wrap(originalErr, wrappingMessage) + + assert.Error(t, wrappedErr) + assert.Contains(t, wrappedErr.Error(), wrappingMessage) + assert.Contains(t, wrappedErr.Error(), "original error") + assert.True(t, errors.Is(wrappedErr, originalErr)) +} + +func TestWrap_NilError(t *testing.T) { + wrappingMessage := "additional context" + + wrappedErr := Wrap(nil, wrappingMessage) + + assert.Error(t, wrappedErr) + assert.Contains(t, wrappedErr.Error(), wrappingMessage) + assert.Contains(t, wrappedErr.Error(), "") +} + +func TestNew(t *testing.T) { + message := "test error message" + + err := New(message) + + assert.Error(t, err) + assert.Equal(t, message, err.Error()) +} + +func TestNew_EmptyMessage(t *testing.T) { + err := New("") + + assert.Error(t, err) + assert.Equal(t, "", err.Error()) +} + +func TestWrap_ChainedErrors(t *testing.T) { + baseErr := errors.New("base error") + firstWrap := Wrap(baseErr, "first wrap") + secondWrap := Wrap(firstWrap, "second wrap") + + assert.Error(t, secondWrap) + assert.Contains(t, secondWrap.Error(), "second wrap") + assert.Contains(t, secondWrap.Error(), "first wrap") + assert.Contains(t, secondWrap.Error(), "base error") + assert.True(t, errors.Is(secondWrap, baseErr)) + assert.True(t, errors.Is(secondWrap, firstWrap)) +} + +func TestWrap_ErrorFormatting(t *testing.T) { + originalErr := errors.New("database connection failed") + context := "failed to initialize user repository" + + wrappedErr := Wrap(originalErr, context) + expectedMessage := "failed to initialize user repository: database connection failed" + + assert.Equal(t, expectedMessage, wrappedErr.Error()) +} \ No newline at end of file diff --git a/pkg/common/generation/generation.go b/pkg/common/generation/generation.go deleted file mode 100644 index 84bce9d..0000000 --- a/pkg/common/generation/generation.go +++ /dev/null @@ -1,13 +0,0 @@ -package generation - -import "github.com/google/uuid" - -func generateUniqueID() (string, error) { - id, err := uuid.NewRandom() - if err != nil { - return "", err - } - - sessionID := id.String() - return sessionID, nil -} diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go new file mode 100644 index 0000000..9de41e3 --- /dev/null +++ b/pkg/config/config_test.go @@ -0,0 +1,123 @@ +package config + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestAppConfig_MarshalJSONMask(t *testing.T) { + config := AppConfig{ + Consul: &ConsulConfig{ + Address: "localhost:8500", + Username: "admin", + Password: "secret123", + Token: "token456", + }, + NATs: &NATsConfig{ + URL: "nats://localhost:4222", + Username: "nats_user", + Password: "nats_pass", + }, + BadgerPassword: "badger_secret", + } + + masked := config.MarshalJSONMask() + + // Verify that sensitive data is masked + assert.Contains(t, masked, "localhost:8500") // Address should not be masked + assert.Contains(t, masked, "admin") // Username should not be masked + assert.Contains(t, masked, "nats_user") // Username should not be masked + assert.Contains(t, masked, "nats://localhost:4222") // URL should not be masked + + // Verify that passwords are masked + assert.NotContains(t, masked, "secret123") + assert.NotContains(t, masked, "token456") + assert.NotContains(t, masked, "nats_pass") + assert.NotContains(t, masked, "badger_secret") + + // Check that asterisks are present for masked fields + assert.Contains(t, masked, strings.Repeat("*", len("secret123"))) + assert.Contains(t, masked, strings.Repeat("*", len("token456"))) + assert.Contains(t, masked, strings.Repeat("*", len("nats_pass"))) + assert.Contains(t, masked, strings.Repeat("*", len("badger_secret"))) +} + +func TestAppConfig_MarshalJSONMask_EmptyPasswords(t *testing.T) { + config := AppConfig{ + Consul: &ConsulConfig{ + Address: "localhost:8500", + Username: "admin", + Password: "", + Token: "", + }, + NATs: &NATsConfig{ + URL: "nats://localhost:4222", + Username: "nats_user", + Password: "", + }, + BadgerPassword: "", + } + + masked := config.MarshalJSONMask() + + // Should not crash with empty passwords + assert.NotEmpty(t, masked) + assert.Contains(t, masked, "localhost:8500") + assert.Contains(t, masked, "admin") + assert.Contains(t, masked, "nats_user") +} + +func TestConsulConfig(t *testing.T) { + config := ConsulConfig{ + Address: "consul.example.com:8500", + Username: "consul_user", + Password: "consul_pass", + Token: "consul_token", + } + + assert.Equal(t, "consul.example.com:8500", config.Address) + assert.Equal(t, "consul_user", config.Username) + assert.Equal(t, "consul_pass", config.Password) + assert.Equal(t, "consul_token", config.Token) +} + +func TestNATsConfig(t *testing.T) { + config := NATsConfig{ + URL: "nats://nats.example.com:4222", + Username: "nats_user", + Password: "nats_pass", + } + + assert.Equal(t, "nats://nats.example.com:4222", config.URL) + assert.Equal(t, "nats_user", config.Username) + assert.Equal(t, "nats_pass", config.Password) +} + +func TestAppConfig_DefaultValues(t *testing.T) { + config := AppConfig{ + Consul: &ConsulConfig{}, // Initialize with empty struct instead of nil + NATs: &NATsConfig{}, // Initialize with empty struct instead of nil + } + + // Should handle default/empty values gracefully + masked := config.MarshalJSONMask() + assert.NotEmpty(t, masked) +} + +func TestAppConfig_PartialConfig(t *testing.T) { + config := AppConfig{ + Consul: &ConsulConfig{ + Address: "localhost:8500", + }, + NATs: &NATsConfig{}, // Initialize to avoid nil pointer + BadgerPassword: "test", + } + + // Should handle partial configuration + masked := config.MarshalJSONMask() + assert.Contains(t, masked, "localhost:8500") + assert.NotContains(t, masked, "test") + assert.Contains(t, masked, "****") // masked badger password +} \ No newline at end of file diff --git a/pkg/encoding/encoding_test.go b/pkg/encoding/encoding_test.go new file mode 100644 index 0000000..ccbdf58 --- /dev/null +++ b/pkg/encoding/encoding_test.go @@ -0,0 +1,168 @@ +package encoding + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "math/big" + "testing" + + "github.com/decred/dcrd/dcrec/edwards/v2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestEncodeS256PubKey(t *testing.T) { + // Generate a test ECDSA key pair + privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + + pubKey := &privateKey.PublicKey + + // Test encoding + encoded, err := EncodeS256PubKey(pubKey) + require.NoError(t, err) + assert.NotEmpty(t, encoded) + + // The encoded key should contain both X and Y coordinates appended together + xBytes := pubKey.X.Bytes() + yBytes := pubKey.Y.Bytes() + expectedLength := len(xBytes) + len(yBytes) + assert.Equal(t, expectedLength, len(encoded)) + + // Verify the encoded data contains the coordinates + assert.Equal(t, xBytes, encoded[:len(xBytes)]) + assert.Equal(t, yBytes, encoded[len(xBytes):]) +} + +func TestEncodeS256PubKey_SpecificValues(t *testing.T) { + // Create a public key with specific values + x := big.NewInt(12345) + y := big.NewInt(67890) + pubKey := &ecdsa.PublicKey{ + Curve: elliptic.P256(), + X: x, + Y: y, + } + + encoded, err := EncodeS256PubKey(pubKey) + require.NoError(t, err) + + // Verify the encoding - should be X bytes followed by Y bytes + xBytes := x.Bytes() + yBytes := y.Bytes() + expected := append(xBytes, yBytes...) + + assert.Equal(t, expected, encoded) +} + +func TestEncodeEDDSAPubKey(t *testing.T) { + // Generate a test EdDSA key pair using the correct API + privateKey, err := edwards.GeneratePrivateKey() + require.NoError(t, err) + + pubKey := privateKey.PubKey() + + // Test encoding + encoded, err := EncodeEDDSAPubKey(pubKey) + require.NoError(t, err) + assert.NotEmpty(t, encoded) + + // EdDSA compressed public key should be 32 bytes (not 33 as initially assumed) + assert.Equal(t, 32, len(encoded)) +} + +func TestDecodeEDDSAPubKey(t *testing.T) { + // Generate a test EdDSA key pair + privateKey, err := edwards.GeneratePrivateKey() + require.NoError(t, err) + + originalPubKey := privateKey.PubKey() + + // Encode the public key + encoded, err := EncodeEDDSAPubKey(originalPubKey) + require.NoError(t, err) + + // Decode the public key + decodedPubKey, err := DecodeEDDSAPubKey(encoded) + require.NoError(t, err) + assert.NotNil(t, decodedPubKey) + + // Verify the decoded key matches the original by comparing serialized forms + originalSerialized := originalPubKey.SerializeCompressed() + decodedSerialized := decodedPubKey.SerializeCompressed() + assert.Equal(t, originalSerialized, decodedSerialized) +} + +func TestDecodeEDDSAPubKey_InvalidData(t *testing.T) { + // Test with invalid data + invalidData := []byte("invalid key data") + + _, err := DecodeEDDSAPubKey(invalidData) + assert.Error(t, err) +} + +func TestDecodeEDDSAPubKey_EmptyData(t *testing.T) { + // Test with empty data + emptyData := []byte{} + + _, err := DecodeEDDSAPubKey(emptyData) + assert.Error(t, err) +} + +func TestEncodeDecodeEDDSA_RoundTrip(t *testing.T) { + // Test multiple round trips to ensure consistency + for i := 0; i < 10; i++ { + // Generate a new key pair + privateKey, err := edwards.GeneratePrivateKey() + require.NoError(t, err) + + originalPubKey := privateKey.PubKey() + + // Encode + encoded, err := EncodeEDDSAPubKey(originalPubKey) + require.NoError(t, err) + + // Decode + decodedPubKey, err := DecodeEDDSAPubKey(encoded) + require.NoError(t, err) + + // Verify they match by comparing serialized forms + originalSerialized := originalPubKey.SerializeCompressed() + decodedSerialized := decodedPubKey.SerializeCompressed() + assert.Equal(t, originalSerialized, decodedSerialized, "Round trip %d failed", i) + } +} + +func TestEncodeS256PubKey_NilPublicKey(t *testing.T) { + // Test with nil public key - this should panic or return an error + // depending on the implementation + defer func() { + if r := recover(); r != nil { + // Expected panic due to nil pointer + t.Log("Correctly panicked on nil public key") + } + }() + + _, err := EncodeS256PubKey(nil) + if err == nil { + t.Error("Expected error or panic with nil public key") + } +} + +func TestEncodeS256PubKey_ZeroCoordinates(t *testing.T) { + // Test with zero coordinates + x := big.NewInt(0) + y := big.NewInt(0) + pubKey := &ecdsa.PublicKey{ + Curve: elliptic.P256(), + X: x, + Y: y, + } + + encoded, err := EncodeS256PubKey(pubKey) + require.NoError(t, err) + + // Should still work, though the result will be a very short byte array + assert.NotNil(t, encoded) +} diff --git a/pkg/eventconsumer/event_consumer.go b/pkg/eventconsumer/event_consumer.go index 085699e..dd1a965 100644 --- a/pkg/eventconsumer/event_consumer.go +++ b/pkg/eventconsumer/event_consumer.go @@ -127,6 +127,7 @@ func (ec *eventConsumer) handleKeyGenEvent(natMsg *nats.Msg) { ec.handleKeygenSessionError(msg.WalletID, err, "Failed to unmarshal keygen message") return } + if err := ec.identityStore.VerifyInitiatorMessage(&msg); err != nil { logger.Error("Failed to verify initiator message", err) ec.handleKeygenSessionError(msg.WalletID, err, "Failed to verify initiator message") @@ -216,7 +217,6 @@ func (ec *eventConsumer) handleKeyGenEvent(natMsg *nats.Msg) { return } - logger.Info("Closing session successfully!", "event", successEvent) payload, err := json.Marshal(successEvent) if err != nil { logger.Error("Failed to marshal keygen success event", err) @@ -351,6 +351,16 @@ func (ec *eventConsumer) consumeTxSigningEvent() error { } if err != nil { + // Check if the error is due to node not being in participant list + if errors.Is(err, mpc.ErrNotInParticipantList) { + logger.Info("Node is not in participant list for this wallet, skipping signing", + "walletID", msg.WalletID, + "txID", msg.TxID, + "nodeID", ec.node.ID(), + ) + return // Skip signing instead of treating as error + } + logger.Error("Failed to create signing session", err) ec.handleSigningSessionError( msg.WalletID, @@ -721,14 +731,6 @@ func (ec *eventConsumer) addSession(walletID, txID string) { ec.sessionsLock.Unlock() } -// Remove a session from tracking -func (ec *eventConsumer) removeSession(walletID, txID string) { - sessionID := fmt.Sprintf("%s-%s", walletID, txID) - ec.sessionsLock.Lock() - delete(ec.activeSessions, sessionID) - ec.sessionsLock.Unlock() -} - // checkAndTrackSession checks if a session already exists and tracks it if new. // Returns true if the session is a duplicate. func (ec *eventConsumer) checkDuplicateSession(walletID, txID string) bool { diff --git a/pkg/identity/identity.go b/pkg/identity/identity.go index 4d281c2..d5edf61 100644 --- a/pkg/identity/identity.go +++ b/pkg/identity/identity.go @@ -4,6 +4,7 @@ import ( "crypto/ed25519" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "os" @@ -252,8 +253,8 @@ func (s *fileStore) VerifyInitiatorMessage(msg types.InitiatorMessage) error { // Get the signature signature := msg.Sig() - if signature == nil || len(signature) == 0 { - return fmt.Errorf("message has no signature") + if len(signature) == 0 { + return errors.New("signature is empty") } // Verify the signature using the initiator's public key diff --git a/pkg/logger/logger_test.go b/pkg/logger/logger_test.go new file mode 100644 index 0000000..ab41fc3 --- /dev/null +++ b/pkg/logger/logger_test.go @@ -0,0 +1,142 @@ +package logger + +import ( + "bytes" + "errors" + "testing" + + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" +) + +func TestInit_DoesNotPanic(t *testing.T) { + // This test ensures Init can be called without panicking + assert.NotPanics(t, func() { + Init("test", false) + }) +} + +func TestInit_SetsDebugLevel(t *testing.T) { + Init("test", true) + assert.Equal(t, zerolog.DebugLevel, zerolog.GlobalLevel()) +} + +func TestInit_SetsInfoLevel(t *testing.T) { + Init("test", false) + assert.Equal(t, zerolog.InfoLevel, zerolog.GlobalLevel()) +} + +func TestError_WithError(t *testing.T) { + // Capture log output + var buf bytes.Buffer + Log = zerolog.New(&buf).With().Timestamp().Logger() + + err := errors.New("test error") + Error("test error message", err) + + output := buf.String() + assert.Contains(t, output, "test error message") + assert.Contains(t, output, "level\":\"error\"") + assert.Contains(t, output, "test error") +} + +func TestError_WithoutError(t *testing.T) { + // Capture log output + var buf bytes.Buffer + Log = zerolog.New(&buf).With().Timestamp().Logger() + + Error("test error message without error", nil) + + output := buf.String() + assert.Contains(t, output, "test error message without error") + assert.Contains(t, output, "level\":\"error\"") +} + +func TestError_WithKeyValues(t *testing.T) { + // Capture log output + var buf bytes.Buffer + Log = zerolog.New(&buf).With().Timestamp().Logger() + + Error("test error with context", nil, "key1", "value1", "key2", 42) + + output := buf.String() + assert.Contains(t, output, "test error with context") + assert.Contains(t, output, "level\":\"error\"") + assert.Contains(t, output, "key1") + assert.Contains(t, output, "value1") + assert.Contains(t, output, "key2") + assert.Contains(t, output, "42") +} + +func TestInfo_BasicMessage(t *testing.T) { + // Capture log output + var buf bytes.Buffer + Log = zerolog.New(&buf).With().Timestamp().Logger() + + Info("test info message") + + output := buf.String() + assert.Contains(t, output, "test info message") + assert.Contains(t, output, "level\":\"info\"") +} + +func TestInfo_WithKeyValues(t *testing.T) { + // Capture log output + var buf bytes.Buffer + Log = zerolog.New(&buf).With().Timestamp().Logger() + + Info("test info with context", "user", "john", "action", "login") + + output := buf.String() + assert.Contains(t, output, "test info with context") + assert.Contains(t, output, "level\":\"info\"") + assert.Contains(t, output, "user") + assert.Contains(t, output, "john") + assert.Contains(t, output, "action") + assert.Contains(t, output, "login") +} + +func TestDebug_BasicMessage(t *testing.T) { + // Capture log output + var buf bytes.Buffer + Log = zerolog.New(&buf).With().Timestamp().Logger() + zerolog.SetGlobalLevel(zerolog.DebugLevel) + + Debug("test debug message") + + output := buf.String() + assert.Contains(t, output, "test debug message") + assert.Contains(t, output, "level\":\"debug\"") +} + +func TestWarn_BasicMessage(t *testing.T) { + // Capture log output + var buf bytes.Buffer + Log = zerolog.New(&buf).With().Timestamp().Logger() + + Warn("test warning message") + + output := buf.String() + assert.Contains(t, output, "test warning message") + assert.Contains(t, output, "level\":\"warn\"") +} + +func TestInfof_FormattedMessage(t *testing.T) { + // Capture log output + var buf bytes.Buffer + Log = zerolog.New(&buf).With().Timestamp().Logger() + + Infof("formatted message: %s=%d", "count", 42) + + output := buf.String() + assert.Contains(t, output, "formatted message: count=42") + assert.Contains(t, output, "level\":\"info\"") +} + +func TestError_PanicsOnOddKeyValues(t *testing.T) { + Init("test", false) + + assert.Panics(t, func() { + Error("test error", nil, "odd_key", "value", "another_odd_key") //nolint:staticcheck // intentionally testing odd number of key-value pairs + }) +} diff --git a/pkg/messaging/message_queue.go b/pkg/messaging/message_queue.go index c2aeef9..32ed3f9 100644 --- a/pkg/messaging/message_queue.go +++ b/pkg/messaging/message_queue.go @@ -130,12 +130,16 @@ func (mq *msgQueue) Dequeue(topic string, handler func(message []byte) error) er if err != nil { if errors.Is(err, ErrPermament) { logger.Info("Permanent error on message", "meta", meta) - msg.Term() + if err := msg.Term(); err != nil { + logger.Error("Failed to terminate message", err) + } return } logger.Error("Error handling message: ", err) - msg.Nak() + if err := msg.Nak(); err != nil { + logger.Error("Failed to nak message", err) + } return } @@ -155,7 +159,3 @@ func (mq *msgQueue) Close() { mq.consumerContext.Stop() } } - -func (n *msgQueue) handleReconnect(nc *nats.Conn) { - logger.Info("NATS: Reconnected to NATS") -} diff --git a/pkg/messaging/point2point.go b/pkg/messaging/point2point.go index a9af8f7..6919c05 100644 --- a/pkg/messaging/point2point.go +++ b/pkg/messaging/point2point.go @@ -47,7 +47,9 @@ func (d *natsDirectMessaging) Send(id string, message []byte) error { func (d *natsDirectMessaging) Listen(id string, handler func(data []byte)) (Subscription, error) { sub, err := d.natsConn.Subscribe(id, func(m *nats.Msg) { handler(m.Data) - m.Respond([]byte("OK")) + if err := m.Respond([]byte("OK")); err != nil { + logger.Error("Failed to respond to message", err) + } }) if err != nil { return nil, err diff --git a/pkg/mpc/node.go b/pkg/mpc/node.go index 720741d..4daf65d 100644 --- a/pkg/mpc/node.go +++ b/pkg/mpc/node.go @@ -261,7 +261,7 @@ func (p *Node) getReadyPeersForSession(keyInfo *keyinfo.KeyInfo, readyPeers []st func (p *Node) ensureNodeIsParticipant(keyInfo *keyinfo.KeyInfo) error { if !slices.Contains(keyInfo.ParticipantPeerIDs, p.nodeID) { - return fmt.Errorf("this node %s is not in the participant list", p.nodeID) + return ErrNotInParticipantList } return nil } diff --git a/pkg/mpc/node_test.go b/pkg/mpc/node_test.go index 3e9f889..cfd7294 100644 --- a/pkg/mpc/node_test.go +++ b/pkg/mpc/node_test.go @@ -6,36 +6,112 @@ import ( "github.com/stretchr/testify/assert" ) -// func TestCreateKeyGenSession(t *testing.T) { -// nodeID := uuid.NewString() +func TestPartyIDToNodeID(t *testing.T) { + partyID := createPartyID("4d8cb873-dc86-4776-b6f6-cf5c668f6468", "keygen", 1) + nodeID := PartyIDToRoutingDest(partyID) + assert.Equal(t, nodeID, "4d8cb873-dc86-4776-b6f6-cf5c668f6468:1", "NodeID should be equal") +} -// peerIDs := []string{ -// nodeID, -// uuid.NewString(), -// uuid.NewString(), -// } -// ctrl := gomock.NewController(t) -// defer ctrl.Finish() -// pubsub := mock.NewMockPubSub(ctrl) -// direct := mock.NewMockDirectMessaging(ctrl) +func TestCreatePartyID_Structure(t *testing.T) { + sessionID := "test-session-123" + keyType := "keygen" + version := 5 -// node := NewNode(nodeID, peerIDs, pubsub, direct) + partyID := createPartyID(sessionID, keyType, version) -// session, err := node.CreateKeyGenSession() + assert.NotNil(t, partyID) + // The party ID has a random UUID as the ID + assert.NotEmpty(t, partyID.Id) + // The Moniker should contain the keyType + assert.Equal(t, keyType, partyID.Moniker) + // The Key should be derived from sessionID and version + assert.NotNil(t, partyID.Key) +} -// assert.NoError(t, err) -// assert.Len(t, session.PartyIDs(), 3, "Length of partyIDs should be equal") -// assert.NotNil(t, session.PartyID()) +func TestCreatePartyID_DifferentVersions(t *testing.T) { + sessionID := "test-session-456" + keyType := "keygen" -// for i, partyID := range session.PartyIDs() { -// // check sortedID -// assert.Equal(t, partyID.Index, i, "Index should be equal") -// } + // Test version 0 (backward compatible) + partyID0 := createPartyID(sessionID, keyType, BackwardCompatibleVersion) + assert.NotNil(t, partyID0) + assert.Equal(t, keyType, partyID0.Moniker) -// } + // Test version 1 (default) + partyID1 := createPartyID(sessionID, keyType, DefaultVersion) + assert.NotNil(t, partyID1) + assert.Equal(t, keyType, partyID1.Moniker) -func TestPartyIDToNodeID(t *testing.T) { - partyID := createPartyID("4d8cb873-dc86-4776-b6f6-cf5c668f6468", "keygen", 1) + // Different versions should have different keys + assert.NotEqual(t, partyID0.Key, partyID1.Key) +} + +func TestPartyIDToRoutingDest_BackwardCompatible(t *testing.T) { + sessionID := "test-session-789" + keyType := "signing" + + partyID := createPartyID(sessionID, keyType, BackwardCompatibleVersion) nodeID := PartyIDToRoutingDest(partyID) - assert.Equal(t, nodeID, "4d8cb873-dc86-4776-b6f6-cf5c668f6468:1", "NodeID should be equal") + + // For backward compatible version, should just be the sessionID + assert.Equal(t, sessionID, nodeID) +} + +func TestPartyIDToRoutingDest_DefaultVersion(t *testing.T) { + sessionID := "test-session-999" + keyType := "signing" + + partyID := createPartyID(sessionID, keyType, DefaultVersion) + nodeID := PartyIDToRoutingDest(partyID) + + // For default version, should include the version number + expected := sessionID + ":1" + assert.Equal(t, expected, nodeID) +} + +func TestCreatePartyID_EmptyValues(t *testing.T) { + // Test with empty session ID + partyID := createPartyID("", "keygen", 0) + assert.NotNil(t, partyID) + assert.Equal(t, "keygen", partyID.Moniker) + + // Test with empty key type + partyID = createPartyID("session", "", 1) + assert.NotNil(t, partyID) + assert.Equal(t, "", partyID.Moniker) +} + +func TestPartyIDToRoutingDest_Consistency(t *testing.T) { + sessionID := "consistent-session" + keyType := "keygen" + version := 3 + + // Create the same party ID multiple times + partyID1 := createPartyID(sessionID, keyType, version) + partyID2 := createPartyID(sessionID, keyType, version) + + nodeID1 := PartyIDToRoutingDest(partyID1) + nodeID2 := PartyIDToRoutingDest(partyID2) + + // Should produce consistent results based on sessionID and version + assert.Equal(t, nodeID1, nodeID2, "Same parameters should produce same routing destinations") +} + +func TestCreatePartyID_UniqueIDs(t *testing.T) { + sessionID := "test-session" + keyType := "keygen" + version := 1 + + // Create multiple party IDs with same parameters + partyID1 := createPartyID(sessionID, keyType, version) + partyID2 := createPartyID(sessionID, keyType, version) + + // IDs should be different (random UUIDs) + assert.NotEqual(t, partyID1.Id, partyID2.Id, "Party IDs should have unique random IDs") + + // But monikers should be the same + assert.Equal(t, partyID1.Moniker, partyID2.Moniker) + + // And keys should be the same (derived from sessionID and version) + assert.Equal(t, partyID1.Key, partyID2.Key) } diff --git a/pkg/mpc/session.go b/pkg/mpc/session.go index 9b73e71..855308f 100644 --- a/pkg/mpc/session.go +++ b/pkg/mpc/session.go @@ -29,6 +29,7 @@ const ( var ( ErrNotEnoughParticipants = errors.New("Not enough participants to sign") + ErrNotInParticipantList = errors.New("Node is not in the participant list") ) type TopicComposer struct { diff --git a/pkg/types/initiator_msg.go b/pkg/types/initiator_msg.go index 6684058..d56b554 100644 --- a/pkg/types/initiator_msg.go +++ b/pkg/types/initiator_msg.go @@ -6,7 +6,7 @@ type KeyType string const ( KeyTypeSecp256k1 KeyType = "secp256k1" - KeyTypeEd25519 = "ed25519" + KeyTypeEd25519 KeyType = "ed25519" ) // InitiatorMessage is anything that carries a payload to verify and its signature. diff --git a/pkg/types/initiator_msg_test.go b/pkg/types/initiator_msg_test.go new file mode 100644 index 0000000..741e577 --- /dev/null +++ b/pkg/types/initiator_msg_test.go @@ -0,0 +1,211 @@ +package types + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestKeyTypeConstants(t *testing.T) { + assert.Equal(t, "secp256k1", string(KeyTypeSecp256k1)) + assert.Equal(t, "ed25519", string(KeyTypeEd25519)) +} + +func TestGenerateKeyMessage_Raw(t *testing.T) { + msg := &GenerateKeyMessage{ + WalletID: "test-wallet-123", + Signature: []byte("test-signature"), + } + + raw, err := msg.Raw() + require.NoError(t, err) + assert.Equal(t, []byte("test-wallet-123"), raw) +} + +func TestGenerateKeyMessage_Sig(t *testing.T) { + signature := []byte("test-signature-bytes") + msg := &GenerateKeyMessage{ + WalletID: "test-wallet", + Signature: signature, + } + + assert.Equal(t, signature, msg.Sig()) +} + +func TestGenerateKeyMessage_InitiatorID(t *testing.T) { + walletID := "test-wallet-456" + msg := &GenerateKeyMessage{ + WalletID: walletID, + Signature: []byte("signature"), + } + + assert.Equal(t, walletID, msg.InitiatorID()) +} + +func TestSignTxMessage_Raw(t *testing.T) { + msg := &SignTxMessage{ + KeyType: KeyTypeSecp256k1, + WalletID: "wallet-123", + NetworkInternalCode: "BTC", + TxID: "tx-456", + Tx: []byte("transaction-data"), + Signature: []byte("signature-data"), + } + + raw, err := msg.Raw() + require.NoError(t, err) + assert.NotEmpty(t, raw) + + // Verify the raw data is valid JSON and doesn't contain signature + assert.NotContains(t, string(raw), "signature-data") + assert.Contains(t, string(raw), "wallet-123") + assert.Contains(t, string(raw), "secp256k1") + assert.Contains(t, string(raw), "BTC") + assert.Contains(t, string(raw), "tx-456") +} + +func TestSignTxMessage_Sig(t *testing.T) { + signature := []byte("transaction-signature") + msg := &SignTxMessage{ + KeyType: KeyTypeEd25519, + WalletID: "wallet", + NetworkInternalCode: "ETH", + TxID: "tx", + Tx: []byte("tx-data"), + Signature: signature, + } + + assert.Equal(t, signature, msg.Sig()) +} + +func TestSignTxMessage_InitiatorID(t *testing.T) { + txID := "transaction-789" + msg := &SignTxMessage{ + KeyType: KeyTypeSecp256k1, + WalletID: "wallet", + NetworkInternalCode: "BTC", + TxID: txID, + Tx: []byte("data"), + Signature: []byte("sig"), + } + + assert.Equal(t, txID, msg.InitiatorID()) +} + +func TestResharingMessage_Raw(t *testing.T) { + msg := &ResharingMessage{ + NodeIDs: []string{"node1", "node2", "node3"}, + NewThreshold: 2, + KeyType: KeyTypeEd25519, + WalletID: "reshare-wallet", + Signature: []byte("reshare-signature"), + } + + raw, err := msg.Raw() + require.NoError(t, err) + + type data struct { + SessionID string `json:"session_id"` + NodeIDs []string `json:"node_ids"` // new peer IDs + NewThreshold int `json:"new_threshold"` + KeyType KeyType `json:"key_type"` + WalletID string `json:"wallet_id"` + } + + d := data{ + SessionID: msg.SessionID, + NodeIDs: msg.NodeIDs, + NewThreshold: msg.NewThreshold, + KeyType: msg.KeyType, + WalletID: msg.WalletID, + } + + expectedBytes, err := json.Marshal(d) + require.NoError(t, err) + assert.Equal(t, expectedBytes, raw) +} + +func TestResharingMessage_Sig(t *testing.T) { + signature := []byte("resharing-signature") + msg := &ResharingMessage{ + NodeIDs: []string{"node1", "node2"}, + NewThreshold: 1, + KeyType: KeyTypeSecp256k1, + WalletID: "wallet", + Signature: signature, + } + + assert.Equal(t, signature, msg.Sig()) +} + +func TestResharingMessage_InitiatorID(t *testing.T) { + walletID := "reshare-wallet-123" + msg := &ResharingMessage{ + NodeIDs: []string{"node1"}, + NewThreshold: 0, + KeyType: KeyTypeEd25519, + WalletID: walletID, + Signature: []byte("sig"), + } + + assert.Equal(t, walletID, msg.InitiatorID()) +} + +func TestSignTxMessage_RawConsistency(t *testing.T) { + msg := &SignTxMessage{ + KeyType: KeyTypeSecp256k1, + WalletID: "consistent-wallet", + NetworkInternalCode: "BTC", + TxID: "consistent-tx", + Tx: []byte("consistent-data"), + Signature: []byte("signature1"), + } + + raw1, err1 := msg.Raw() + require.NoError(t, err1) + + // Change signature and verify raw data remains the same + msg.Signature = []byte("different-signature") + raw2, err2 := msg.Raw() + require.NoError(t, err2) + + assert.Equal(t, raw1, raw2, "Raw data should be consistent regardless of signature") +} + +func TestAllMessageTypesImplementInitiatorMessage(t *testing.T) { + var _ InitiatorMessage = &GenerateKeyMessage{} + var _ InitiatorMessage = &SignTxMessage{} + var _ InitiatorMessage = &ResharingMessage{} +} + +func TestSignTxMessage_EmptyValues(t *testing.T) { + msg := &SignTxMessage{ + KeyType: "", + WalletID: "", + NetworkInternalCode: "", + TxID: "", + Tx: nil, + Signature: nil, + } + + raw, err := msg.Raw() + require.NoError(t, err) + assert.NotEmpty(t, raw) // Should still produce valid JSON + + assert.Empty(t, msg.Sig()) + assert.Empty(t, msg.InitiatorID()) +} + +func TestGenerateKeyMessage_EmptyWallet(t *testing.T) { + msg := &GenerateKeyMessage{ + WalletID: "", + Signature: []byte("sig"), + } + + raw, err := msg.Raw() + require.NoError(t, err) + assert.Equal(t, []byte(""), raw) + assert.Equal(t, "", msg.InitiatorID()) +} diff --git a/pkg/types/tss_test.go b/pkg/types/tss_test.go new file mode 100644 index 0000000..702ac07 --- /dev/null +++ b/pkg/types/tss_test.go @@ -0,0 +1,196 @@ +package types + +import ( + "testing" + + "github.com/bnb-chain/tss-lib/v2/tss" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNewTssMessage(t *testing.T) { + walletID := "test-wallet-123" + msgBytes := []byte("test message") + isBroadcast := true + from := &tss.PartyID{ + MessageWrapper_PartyID: &tss.MessageWrapper_PartyID{ + Id: "party1", + Moniker: "moniker1", + }, + Index: 0, + } + to := []*tss.PartyID{ + { + MessageWrapper_PartyID: &tss.MessageWrapper_PartyID{ + Id: "party2", + Moniker: "moniker2", + }, + Index: 1, + }, + } + + tssMsg := NewTssMessage(walletID, msgBytes, isBroadcast, from, to) + + assert.Equal(t, walletID, tssMsg.WalletID) + assert.Equal(t, msgBytes, tssMsg.MsgBytes) + assert.Equal(t, isBroadcast, tssMsg.IsBroadcast) + assert.Equal(t, from, tssMsg.From) + assert.Equal(t, to, tssMsg.To) + assert.False(t, tssMsg.IsToOldCommittee) + assert.False(t, tssMsg.IsToOldAndNewCommittees) + assert.Nil(t, tssMsg.Signature) +} + +func TestMarshalUnmarshalTssMessage(t *testing.T) { + from := &tss.PartyID{ + MessageWrapper_PartyID: &tss.MessageWrapper_PartyID{ + Id: "party1", + Moniker: "moniker1", + }, + Index: 0, + } + to := []*tss.PartyID{ + { + MessageWrapper_PartyID: &tss.MessageWrapper_PartyID{ + Id: "party2", + Moniker: "moniker2", + }, + Index: 1, + }, + } + + originalMsg := NewTssMessage("wallet-123", []byte("test data"), true, from, to) + originalMsg.Signature = []byte("test-signature") + + // Test marshaling + msgBytes, err := MarshalTssMessage(&originalMsg) + require.NoError(t, err) + assert.NotEmpty(t, msgBytes) + + // Test unmarshaling + unmarshaled, err := UnmarshalTssMessage(msgBytes) + require.NoError(t, err) + assert.Equal(t, originalMsg.WalletID, unmarshaled.WalletID) + assert.Equal(t, originalMsg.MsgBytes, unmarshaled.MsgBytes) + assert.Equal(t, originalMsg.IsBroadcast, unmarshaled.IsBroadcast) + assert.Equal(t, originalMsg.Signature, unmarshaled.Signature) +} + +func TestMarshalTssResharingMessage(t *testing.T) { + msgBytes := []byte("resharing message") + isToOldCommittee := true + isBroadcast := false + isToOldAndNewCommittees := true + from := &tss.PartyID{ + MessageWrapper_PartyID: &tss.MessageWrapper_PartyID{ + Id: "party1", + Moniker: "moniker1", + }, + Index: 0, + } + to := []*tss.PartyID{ + { + MessageWrapper_PartyID: &tss.MessageWrapper_PartyID{ + Id: "party2", + Moniker: "moniker2", + }, + Index: 1, + }, + } + + result, err := MarshalTssResharingMessage(msgBytes, isToOldCommittee, isBroadcast, isToOldAndNewCommittees, from, to) + require.NoError(t, err) + assert.NotEmpty(t, result) + + // Unmarshal to verify structure + unmarshaled, err := UnmarshalTssMessage(result) + require.NoError(t, err) + assert.Equal(t, msgBytes, unmarshaled.MsgBytes) + assert.Equal(t, isToOldCommittee, unmarshaled.IsToOldCommittee) + assert.Equal(t, isBroadcast, unmarshaled.IsBroadcast) + assert.Equal(t, isToOldAndNewCommittees, unmarshaled.IsToOldAndNewCommittees) +} + +func TestMarshalUnmarshalStartMessage(t *testing.T) { + params := []byte("start parameters") + + // Test marshaling + msgBytes, err := MarshalStartMessage(params) + require.NoError(t, err) + assert.NotEmpty(t, msgBytes) + + // Test unmarshaling + unmarshaled, err := UnmarshalStartMessage(msgBytes) + require.NoError(t, err) + assert.Equal(t, params, unmarshaled.Params) +} + +func TestMarshalForSigning(t *testing.T) { + from := &tss.PartyID{ + MessageWrapper_PartyID: &tss.MessageWrapper_PartyID{ + Id: "party1", + Moniker: "moniker1", + }, + Index: 0, + } + to := []*tss.PartyID{ + { + MessageWrapper_PartyID: &tss.MessageWrapper_PartyID{ + Id: "party2", + Moniker: "moniker2", + }, + Index: 1, + }, + } + + msg := NewTssMessage("wallet-123", []byte("test data"), true, from, to) + msg.IsToOldCommittee = true + msg.IsToOldAndNewCommittees = false + + signingBytes, err := msg.MarshalForSigning() + require.NoError(t, err) + assert.NotEmpty(t, signingBytes) + + // Test deterministic output - same message should produce same bytes + signingBytes2, err := msg.MarshalForSigning() + require.NoError(t, err) + assert.Equal(t, signingBytes, signingBytes2) +} + +func TestUnmarshalTssMessage_InvalidJSON(t *testing.T) { + invalidJSON := []byte("invalid json") + + _, err := UnmarshalTssMessage(invalidJSON) + assert.Error(t, err) +} + +func TestUnmarshalStartMessage_InvalidJSON(t *testing.T) { + invalidJSON := []byte("invalid json") + + _, err := UnmarshalStartMessage(invalidJSON) + assert.Error(t, err) +} + +func TestGetPartyIDs(t *testing.T) { + parties := []*tss.PartyID{ + { + MessageWrapper_PartyID: &tss.MessageWrapper_PartyID{ + Id: "party3", + }, + }, + { + MessageWrapper_PartyID: &tss.MessageWrapper_PartyID{ + Id: "party1", + }, + }, + { + MessageWrapper_PartyID: &tss.MessageWrapper_PartyID{ + Id: "party2", + }, + }, + } + + ids := getPartyIDs(parties) + expected := []string{"party1", "party2", "party3"} + assert.Equal(t, expected, ids) +} diff --git a/scripts/migration/add-key-type/main.go b/scripts/migration/add-key-type/main.go index 9891243..87c47ce 100644 --- a/scripts/migration/add-key-type/main.go +++ b/scripts/migration/add-key-type/main.go @@ -5,13 +5,13 @@ import ( "fmt" "strings" + "github.com/dgraph-io/badger/v4" "github.com/fystack/mpcium/pkg/kvstore" "github.com/fystack/mpcium/pkg/logger" - "github.com/dgraph-io/badger/v4" ) func main() { - logger.Init("production") + logger.Init("production", false) nodeName := flag.String("name", "", "Provide node name") flag.Parse() if *nodeName == "" { @@ -21,15 +21,15 @@ func main() { dbPath := fmt.Sprintf("./db/%s", *nodeName) badgerKv, err := kvstore.NewBadgerKVStore( dbPath, - []byte("1JwFmsc9lxlLfkPl"), + []byte(""), ) if err != nil { logger.Fatal("Failed to create badger kv store", err) } - err = badgerKv.DB.View(func(txn *badger.Txn) error { + if err := badgerKv.DB.View(func(txn *badger.Txn) error { opts := badger.DefaultIteratorOptions - opts.PrefetchValues = false + opts.PrefetchSize = 10 it := txn.NewIterator(opts) defer it.Close() @@ -37,24 +37,32 @@ func main() { item := it.Item() key := item.Key() var result []byte - item.Value(func(val []byte) error { - result = append([]byte{}, val...) + + if err := item.Value(func(val []byte) error { + result = append(result, val...) return nil - }) + }); err != nil { + return err + } if !strings.HasPrefix(string(key), "eddsa:") { if !strings.HasPrefix(string(key), "ecdsa:") { - badgerKv.DB.Update(func(txn *badger.Txn) error { - txn.Set([]byte(fmt.Sprintf("ecdsa:%s", key)), result) - txn.Delete(key) - return nil - }) + if err := badgerKv.DB.Update(func(txn *badger.Txn) error { + if err := txn.Set([]byte(fmt.Sprintf("ecdsa:%s", key)), result); err != nil { + return err + } + return txn.Delete(key) + }); err != nil { + return err + } } - } } return nil - }) + }); err != nil { + logger.Fatal("Failed to migrate keys", err) + } + keys, err := badgerKv.Keys() if err != nil { logger.Fatal("Failed to get keys from badger kv store", err) diff --git a/scripts/migration/update-keyinfo/main.go b/scripts/migration/update-keyinfo/main.go index 704ff5a..f96283c 100644 --- a/scripts/migration/update-keyinfo/main.go +++ b/scripts/migration/update-keyinfo/main.go @@ -13,7 +13,7 @@ import ( // script to add key type prefix ecdsa for existing keys func main() { config.InitViperConfig() - logger.Init("production") + logger.Init("production", false) appConfig := config.LoadConfig() logger.Info("App config", "config", appConfig) @@ -47,9 +47,12 @@ func main() { } if walletID != "" { - kv.Put(&api.KVPair{Key: fmt.Sprintf("threshold_keyinfo/ecdsa:%s", walletID), Value: pair.Value}, nil) - kv.Delete(key, nil) - + if _, err := kv.Put(&api.KVPair{Key: fmt.Sprintf("threshold_keyinfo/ecdsa:%s", walletID), Value: pair.Value}, nil); err != nil { + log.Printf("Failed to put key for wallet %s: %v", walletID, err) + } + if _, err := kv.Delete(key, nil); err != nil { + log.Printf("Failed to delete key %s: %v", key, err) + } } }