Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Counterfactual Safes creation rate limit #1801

Merged
merged 3 commits into from
Aug 7, 2024
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
4 changes: 4 additions & 0 deletions src/config/entities/__tests__/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ export default (): ReturnType<typeof configuration> => ({
accounts: {
creationRateLimitPeriodSeconds: faker.number.int(),
creationRateLimitCalls: faker.number.int(),
counterfactualSafes: {
creationRateLimitPeriodSeconds: faker.number.int(),
creationRateLimitCalls: faker.number.int(),
},
},
amqp: {
url: faker.internet.url({ appendSlash: false }),
Expand Down
10 changes: 10 additions & 0 deletions src/config/entities/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,16 @@ export default () => ({
creationRateLimitCalls: parseInt(
process.env.ACCOUNT_CREATION_RATE_LIMIT_CALLS_BY_PERIOD ?? `${1}`,
),
counterfactualSafes: {
creationRateLimitPeriodSeconds: parseInt(
process.env.COUNTERFACTUAL_SAFES_CREATION_RATE_LIMIT_PERIOD_SECONDS ??
`${3600}`,
),
creationRateLimitCalls: parseInt(
process.env.COUNTERFACTUAL_SAFES_CREATION_RATE_LIMIT_CALLS_BY_PERIOD ??
`${10}`,
),
},
},
amqp: {
url: process.env.AMQP_URL || 'amqp://localhost:5672',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,118 @@ describe('CounterfactualSafesDatasource tests', () => {
);
});

it('should create a Counterfactual Safe if the rate limit is not hit', async () => {
const address = getAddress(faker.finance.ethereumAddress());
const [account] = await sql<
Account[]
>`INSERT INTO accounts (address) VALUES (${address}) RETURNING *`;
const creationRateLimitCalls = faker.number.int({ min: 5, max: 10 });
const createCounterfactualSafes = Array.from(
{ length: creationRateLimitCalls },
(_, i) =>
createCounterfactualSafeDtoBuilder()
.with('chainId', i.toString())
.build(),
);

mockConfigurationService.getOrThrow.mockImplementation((key) => {
switch (key) {
case 'expirationTimeInSeconds.default':
return faker.number.int();
case 'accounts.counterfactualSafes.creationRateLimitPeriodSeconds':
return faker.number.int({ min: 10 });
case 'accounts.counterfactualSafes.creationRateLimitCalls':
return creationRateLimitCalls;
}
});

target = new CounterfactualSafesDatasource(
fakeCacheService,
sql,
new CachedQueryResolver(mockLoggingService, fakeCacheService),
mockLoggingService,
mockConfigurationService,
);

for (let i = 0; i < creationRateLimitCalls - 1; i++) {
await target.createCounterfactualSafe({
account,
createCounterfactualSafeDto: createCounterfactualSafes[i],
});
}

const lastCounterfactualSafe =
createCounterfactualSafes[createCounterfactualSafes.length - 1];
const actual = await target.createCounterfactualSafe({
account,
createCounterfactualSafeDto: lastCounterfactualSafe,
});
expect(actual).toStrictEqual(
expect.objectContaining({
id: expect.any(Number),
chain_id: lastCounterfactualSafe.chainId,
creator: account.address,
fallback_handler: lastCounterfactualSafe.fallbackHandler,
owners: lastCounterfactualSafe.owners,
predicted_address: lastCounterfactualSafe.predictedAddress,
salt_nonce: lastCounterfactualSafe.saltNonce,
singleton_address: lastCounterfactualSafe.singletonAddress,
threshold: lastCounterfactualSafe.threshold,
account_id: account.id,
}),
);
});

it('should fail if the rate limit is hit', async () => {
const address = getAddress(faker.finance.ethereumAddress());
const [account] = await sql<
Account[]
>`INSERT INTO accounts (address) VALUES (${address}) RETURNING *`;
const creationRateLimitCalls = faker.number.int({ min: 5, max: 10 });
const createCounterfactualSafes = Array.from(
{ length: creationRateLimitCalls },
(_, i) =>
createCounterfactualSafeDtoBuilder()
.with('chainId', i.toString())
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

chainId is set as a discriminator to avoid the DTO properties collision edge case.

.build(),
);

mockConfigurationService.getOrThrow.mockImplementation((key) => {
switch (key) {
case 'expirationTimeInSeconds.default':
return faker.number.int();
case 'accounts.counterfactualSafes.creationRateLimitPeriodSeconds':
return faker.number.int({ min: 10 });
case 'accounts.counterfactualSafes.creationRateLimitCalls':
return creationRateLimitCalls;
}
});

target = new CounterfactualSafesDatasource(
fakeCacheService,
sql,
new CachedQueryResolver(mockLoggingService, fakeCacheService),
mockLoggingService,
mockConfigurationService,
);

for (let i = 0; i < creationRateLimitCalls; i++) {
await target.createCounterfactualSafe({
account,
createCounterfactualSafeDto: createCounterfactualSafes[i],
});
}

await expect(
target.createCounterfactualSafe({
account,
createCounterfactualSafeDto: createCounterfactualSafeDtoBuilder()
.with('chainId', '11')
.build(),
}),
).rejects.toThrow('Rate limit reached');
});

it('should delete the cache for the account Counterfactual Safes', async () => {
const address = getAddress(faker.finance.ethereumAddress());
const [account] = await sql<
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from '@/datasources/cache/cache.service.interface';
import { CachedQueryResolver } from '@/datasources/db/cached-query-resolver';
import { ICachedQueryResolver } from '@/datasources/db/cached-query-resolver.interface';
import { LimitReachedError } from '@/datasources/network/entities/errors/limit-reached.error';
import { CounterfactualSafe } from '@/domain/accounts/counterfactual-safes/entities/counterfactual-safe.entity';
import { CreateCounterfactualSafeDto } from '@/domain/accounts/counterfactual-safes/entities/create-counterfactual-safe.dto.entity';
import { Account } from '@/domain/accounts/entities/account.entity';
Expand All @@ -18,7 +19,13 @@ import postgres from 'postgres';
export class CounterfactualSafesDatasource
implements ICounterfactualSafesDatasource
{
private static readonly COUNTERFACTUAL_SAFES_CREATION_CACHE_PREFIX =
'counterfactual_safes_creation';
private readonly defaultExpirationTimeInSeconds: number;
// Number of seconds for each rate-limit cycle
private readonly counterfactualSafesCreationRateLimitPeriodSeconds: number;
// Number of allowed calls on each rate-limit cycle
private readonly counterfactualSafesCreationRateLimitCalls: number;

constructor(
@Inject(CacheService) private readonly cacheService: ICacheService,
Expand All @@ -33,12 +40,21 @@ export class CounterfactualSafesDatasource
this.configurationService.getOrThrow<number>(
'expirationTimeInSeconds.default',
);
this.counterfactualSafesCreationRateLimitPeriodSeconds =
configurationService.getOrThrow(
'accounts.counterfactualSafes.creationRateLimitPeriodSeconds',
);
this.counterfactualSafesCreationRateLimitCalls =
configurationService.getOrThrow(
'accounts.counterfactualSafes.creationRateLimitCalls',
);
}

async createCounterfactualSafe(args: {
account: Account;
createCounterfactualSafeDto: CreateCounterfactualSafeDto;
}): Promise<CounterfactualSafe> {
await this.checkCreationRateLimit(args.account);
const [counterfactualSafe] = await this.sql<CounterfactualSafe[]>`
INSERT INTO counterfactual_safes
${this.sql([this.mapCreationDtoToRow(args.account, args.createCounterfactualSafeDto)])}
Expand Down Expand Up @@ -144,6 +160,21 @@ export class CounterfactualSafesDatasource
}
}

private async checkCreationRateLimit(account: Account): Promise<void> {
const current = await this.cacheService.increment(
CacheRouter.getRateLimitCacheKey(
`${CounterfactualSafesDatasource.COUNTERFACTUAL_SAFES_CREATION_CACHE_PREFIX}_${account.address}`,
),
this.counterfactualSafesCreationRateLimitPeriodSeconds,
);
if (current > this.counterfactualSafesCreationRateLimitCalls) {
this.loggingService.warn(
`Limit of ${this.counterfactualSafesCreationRateLimitCalls} reached for account ${account.address}`,
);
throw new LimitReachedError();
}
}

private mapCreationDtoToRow(
account: Account,
createCounterfactualSafeDto: CreateCounterfactualSafeDto,
Expand Down
Loading