forked from SmartDropLabs/smartdrop-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfeeBumpGuard.ts
More file actions
113 lines (96 loc) · 3.73 KB
/
Copy pathfeeBumpGuard.ts
File metadata and controls
113 lines (96 loc) · 3.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
* Server-side validation for /api/sign-fee-bump (issue #124).
*
* The route sponsors real XLM spend, so before it fee-bumps and signs an
* inner transaction it must independently confirm — not just trust the
* client's advisory `isFeeSponsored` check — that the inner transaction is
* actually a SmartDrop lock/unlock call against a known pool, and that it
* already carries a valid signature from its own source account.
*/
import { Address, Keypair, StrKey, Transaction } from '@stellar/stellar-sdk';
export const SPONSORABLE_FUNCTIONS = new Set(['lock_assets', 'unlock_assets']);
/**
* Throws if `innerTx` is not exactly one invokeHostFunction call to
* `lock_assets`/`unlock_assets` on one of `knownPoolContractIds`, or if it
* isn't already validly signed by its own declared source account.
*/
export function assertSponsorableInnerTransaction(
innerTx: Transaction,
knownPoolContractIds: ReadonlySet<string>,
): void {
const operations = innerTx.operations;
if (operations.length !== 1) {
throw new Error(
`Inner transaction must contain exactly one operation, got ${operations.length}.`,
);
}
const op = operations[0];
if (op.type !== 'invokeHostFunction') {
throw new Error(
`Inner transaction operation type "${op.type}" is not sponsorable; only invokeHostFunction is allowed.`,
);
}
const hostFn = op.func;
if (hostFn.switch().name !== 'hostFunctionTypeInvokeContract') {
throw new Error('Inner transaction must invoke a contract function.');
}
const invocation = hostFn.invokeContract();
const contractId = Address.fromScAddress(invocation.contractAddress()).toString();
const rawFunctionName = invocation.functionName();
const functionName =
typeof rawFunctionName === 'string' ? rawFunctionName : rawFunctionName.toString('utf8');
if (!knownPoolContractIds.has(contractId)) {
throw new Error(`Inner transaction targets an unrecognized pool contract: ${contractId}.`);
}
if (!SPONSORABLE_FUNCTIONS.has(functionName)) {
throw new Error(
`Inner transaction calls "${functionName}", which is not a sponsorable function.`,
);
}
if (innerTx.signatures.length === 0) {
throw new Error('Inner transaction is not signed.');
}
if (!StrKey.isValidEd25519PublicKey(innerTx.source)) {
throw new Error('Inner transaction source account is not a supported address type.');
}
const sourceKeypair = Keypair.fromPublicKey(innerTx.source);
const hash = innerTx.hash();
const hasValidSourceSignature = innerTx.signatures.some((sig) => {
try {
return sourceKeypair.verify(hash, sig.signature());
} catch {
return false;
}
});
if (!hasValidSourceSignature) {
throw new Error(
'Inner transaction does not carry a valid signature from its own source account.',
);
}
}
/**
* Minimal in-memory sliding-window rate limiter, keyed by caller (source
* account, IP, etc). Per-process only — fine for a single-instance deploy;
* a multi-instance deploy should replace this with a shared store (e.g.
* Redis/edge KV) keyed the same way.
*/
export class RateLimiter {
private hits = new Map<string, number[]>();
constructor(
private readonly maxRequests: number,
private readonly windowMs: number,
) {}
/** Returns true and records the hit if `key` is within its limit, false if throttled. */
tryConsume(key: string, now: number = Date.now()): boolean {
const windowStart = now - this.windowMs;
const recent = (this.hits.get(key) ?? []).filter((t) => t > windowStart);
if (recent.length >= this.maxRequests) {
this.hits.set(key, recent);
return false;
}
recent.push(now);
this.hits.set(key, recent);
return true;
}
}
export const feeBumpRateLimiter = new RateLimiter(5, 60_000);