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

refactor(core-p2p): peer rate limiter #4310

Closed
wants to merge 6 commits into from
Closed
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Unit-testable rate limit plugin
  • Loading branch information
rainydio committed Feb 10, 2021
commit 1be81e0d2a2e9bdec8deed88c00e904fdc641f8f
36 changes: 22 additions & 14 deletions packages/core-p2p/src/socket-server/plugins/rate-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,33 @@ export class RateLimitPlugin {
@Container.inject(Container.Identifiers.PeerRateLimiter)
private readonly rateLimiter!: Contracts.P2P.PeerRateLimiter;

public register(server) {
const allRoutesConfigByPath = {
private readonly endpointByPath: Map<string, string> = new Map<string, string>();

@Container.postConstruct()
public initialize(): void {
const configs = {
...this.app.resolve(InternalRoute).getRoutesConfigByPath(),
...this.app.resolve(PeerRoute).getRoutesConfigByPath(),
...this.app.resolve(BlocksRoute).getRoutesConfigByPath(),
...this.app.resolve(TransactionsRoute).getRoutesConfigByPath(),
};

server.ext({
type: "onPreAuth",
method: async (request, h) => {
const endpoint = allRoutesConfigByPath[request.path].id;

if (await this.rateLimiter.consumeIncoming(request.info.remoteAddress, endpoint)) {
return h.continue;
} else {
return Boom.tooManyRequests("Rate limit exceeded");
}
},
});
for (const [path, config] of Object.entries(configs)) {
this.endpointByPath.set(path, config.id);
}
}

public register(server) {
server.ext({ type: "onPreAuth", method: this.onPreAuth.bind(this) });
}

public async onPreAuth(request, h) {
const endpoint: string | undefined = this.endpointByPath.get(request.path);

if (await this.rateLimiter.consumeIncoming(request.info.remoteAddress, endpoint)) {
return h.continue;
} else {
return Boom.tooManyRequests("Rate limit exceeded");
}
}
}