Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions African API.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ This pull request integrates a Nigerian Naira (NGN) exchange rate fetcher into t
### Market Rate Service Improvements

- **New NGNRateFetcher**: Added `src/services/marketRate/ngnFetcher.ts` which implements the `MarketRateFetcher` interface. It uses a tiered strategy for robustness:
- **Binance P2P**: Primary source for direct XLM/NGN or XLM/USDT * USDT/NGN cross rates.
- **CoinGecko**: Reliable aggregator for XLM/NGN.
- **ExchangeRate API**: Fallback source for USD/NGN cross-conversion.
- **Binance P2P**: Primary source for direct XLM/NGN or XLM/USDT \* USDT/NGN cross rates.
- **CoinGecko**: Reliable aggregator for XLM/NGN.
- **ExchangeRate API**: Fallback source for USD/NGN cross-conversion.
- **Service Registration**: Updated `src/services/marketRate/index.ts` and `src/services/marketRate/marketRateService.ts` to include and register the `NGNRateFetcher`.
- **Fault Tolerance**: The new fetcher includes a `CircuitBreaker` and exponential backoff retry logic to handle transient API failures.

Expand Down
42 changes: 39 additions & 3 deletions MULTI_SIG_ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ This document provides a technical overview of the multi-sig implementation and
### 1. Separation of Concerns

**Before:**

- Single StellarService handling all transaction submission
- Direct submission without intermediate approval layer
- No separation between signing and submission

**After:**

- **MultiSigService**: Handles signature collection and aggregation
- **MultiSigSubmissionService**: Background job for approval → submission
- **StellarService**: Enhanced with multi-sig support while maintaining single-sig capabilities
Expand All @@ -22,6 +24,7 @@ This document provides a technical overview of the multi-sig implementation and
### 2. Asynchronous Signature Collection

**Key Optimization:**

```typescript
// Non-blocking signature requests
private async requestRemoteSignaturesAsync(
Expand All @@ -31,6 +34,7 @@ private async requestRemoteSignaturesAsync(
```

**Benefits:**

- Price fetches complete immediately (not blocked waiting for remote signatures)
- Signatures collected in parallel via `Promise.allSettled()`
- Failures on one server don't affect others
Expand All @@ -39,17 +43,19 @@ private async requestRemoteSignaturesAsync(
### 3. Database Schema for Audit Trail

**New Models:**

```
MultiSigPrice (tracks approval state)
MultiSigSignature (individual signer records)

Links to existing:
- PriceReviewService records (for approval history)
- OnChainPrice records (for confirmation)
```

**Audit Benefits:**

- Complete signature history retained
- Signer identity recorded (public key + name)
- Timestamp for each signature
Expand All @@ -58,6 +64,7 @@ Links to existing:
### 4. Network Communication Pattern

**Server-to-Server Communication:**

```
Server A (Primary)
├─ Fetches rate
Expand All @@ -78,6 +85,7 @@ Server A
```

**Optimizations:**

- HTTP endpoints for synchronous signing requests
- Authorization via shared token
- Deterministic message format ensures signature compatibility
Expand All @@ -88,6 +96,7 @@ Server A
### 1. Multi-Sig Transaction Construction

**Before:** Single signature per transaction

```
Transaction
├─ Operations: ManageData (price update)
Expand All @@ -96,6 +105,7 @@ Transaction
```

**After:** Multiple signatures from different servers

```
Transaction
├─ Operations: ManageData (price update)
Expand All @@ -107,6 +117,7 @@ Transaction
```

**Benefits:**

- Soroban contract can verify multiple signatures
- Authorizes price updates only when multiple signers agree
- Prevents single server compromise
Expand All @@ -124,6 +135,7 @@ submitMultiSignedPriceUpdate(
```

**Process:**

1. Build transaction (single sequence account)
2. Sign with local keypair
3. Convert to XDR envelope
Expand All @@ -134,11 +146,13 @@ submitMultiSignedPriceUpdate(
### 3. Fee Optimization for Multi-Sig

**Current Implementation:**

- Uses median fee (p50) from Horizon fee_stats
- Applies fee increment multiplier on retry: 50% per attempt
- Configurable retry limit (default: 3)

**Multi-Sig Consideration:**

- Fee calculated per attempt (accounts for all signatures)
- Fixed fee amount doesn't change with signature count
- Stellar charges per operation, not per signature
Expand All @@ -148,11 +162,13 @@ submitMultiSignedPriceUpdate(
### Time Complexity

**Single Signature:**

```
Fetch (~100ms) → Review (instant) → Sign (instant) → Submit (~2s) = ~2.1s
```

**Multi-Signature:**

```
Fetch (~100ms) → Review (instant) → Sign (instant) + Request Remote (~500ms-5s)
↓ (async, non-blocking)
Expand All @@ -166,31 +182,36 @@ Submit (~2s) = ~2.6s average (if remote responds quickly)
### Space Complexity

**Database:**

- MultiSigPrice: ~500 bytes per record
- MultiSigSignature: ~1KB per signature
- Low space impact: signature aggregation is temporary

**Network:**

- Multi-sig doesn't increase transaction size significantly
- Envelope signatures are compact (64 bytes each)
- Stellar network handles multi-sig natively

## Configuration Flexibility

### Mode 1: Legacy Single-Signature

```bash
# Default behavior - prices submitted immediately
MULTI_SIG_ENABLED=false
```

### Mode 2: Multi-Signature with 2 Servers

```bash
MULTI_SIG_ENABLED=true
MULTI_SIG_REQUIRED_COUNT=2
REMOTE_ORACLE_SERVERS=http://oracle-2.internal:3000
```

### Mode 3: Multi-Signature with 3+ Servers

```bash
MULTI_SIG_ENABLED=true
MULTI_SIG_REQUIRED_COUNT=3
Expand All @@ -202,6 +223,7 @@ REMOTE_ORACLE_SERVERS=http://oracle-2.internal:3000,http://oracle-3.internal:300
### Signature Request Failures

**Scenario:** Remote server is down

```
Action: Request fails silently (logged as warning)
Result: MultiSigPrice waits for timeout (1 hour)
Expand All @@ -213,6 +235,7 @@ After: Cleaned up as EXPIRED
### Partial Signatures

**Scenario:** 1 of 2 signatures collected before expiration

```
Action: MultiSigPrice remains PENDING
Result: Background job skips (not APPROVED)
Expand All @@ -224,6 +247,7 @@ After: Cleaned up as EXPIRED after 1 hour
### Stellar Submission Failures

**Scenario:** Multi-sig transaction fails fee validation

```
Action: StellarService retries with 50% fee increase (up to 3x)
Result: Eventually succeeds or throws after max retries
Expand All @@ -236,6 +260,7 @@ Result: Eventually succeeds or throws after max retries
### 1. Signature Determinism

Using deterministic message format ensures:

```
All servers sign identical message:
"SF-PRICE-NGN-1234.56-CoinGecko"
Expand All @@ -247,14 +272,15 @@ Any difference (rate, currency, source) results in incompatible signatures.

```typescript
// Each signature has a "hint" derived from signer's public key
Keypair.fromPublicKey(signerPublicKey).signatureHint()
Keypair.fromPublicKey(signerPublicKey).signatureHint();
```

Stellar network verifies each signature matches its public key.

### 3. Network Security

Recommendations for production:

- Use HTTPS for all server-to-server communication
- Implement VPN or private network for inter-server calls
- Use short-lived authorization tokens
Expand Down Expand Up @@ -289,6 +315,7 @@ Recommendations for production:
### Logging

Service includes detailed logging at each step:

```
[MultiSig] Created signature request 123 for NGN rate 1234.56
[MultiSig] Added signature 1/2 for MultiSigPrice 123
Expand All @@ -299,23 +326,26 @@ Service includes detailed logging at each step:
## Testing Strategy

### Unit Tests

- MultiSigService signature aggregation
- Message format determinism
- Expiration logic

### Integration Tests

- Server-to-server communication
- Multi-sig transaction submission
- Error recovery scenarios

### Load Tests

- Concurrent price updates
- Remote server latency impact
- Signature queue handling

## Deployment Checklist

- [ ] Update `.env` with MULTI_SIG_* variables
- [ ] Update `.env` with MULTI*SIG*\* variables
- [ ] Run `prisma migrate` to create new tables
- [ ] Update all oracle servers with same MULTI_SIG_AUTH_TOKEN
- [ ] Configure REMOTE_ORACLE_SERVERS on each server
Expand All @@ -327,6 +357,7 @@ Service includes detailed logging at each step:
## Backward Compatibility

✅ **Fully Compatible**

- Existing single-sig code continues to work
- Feature gates based on `MULTI_SIG_ENABLED` env var
- No breaking changes to existing APIs
Expand All @@ -335,16 +366,21 @@ Service includes detailed logging at each step:
## Future Optimizations

### 1. Signature Caching

Pre-fetch and cache recent signatures to reduce latency

### 2. Weighted Voting

Support 2-of-3 or other threshold combinations

### 3. Parallel Submission

Submit approved prices in batches

### 4. WebSocket Updates

Real-time multi-sig status via Socket.io

### 5. Distributed Consensus

Byzantine Fault Tolerance for > 2 signers
Loading
Loading