Skip to content

Commit

Permalink
[ETCM-331] Separate RateLimit validation in a different trait
Browse files Browse the repository at this point in the history
  • Loading branch information
SoseMagarian committed Dec 1, 2020
1 parent df265cb commit 16cd9d5
Showing 1 changed file with 25 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package io.iohk.ethereum.jsonrpc.server.http

import java.time.Clock

import akka.http.scaladsl.model.RemoteAddress
import com.twitter.util.LruMap
import io.iohk.ethereum.jsonrpc.server.http.JsonRpcHttpServer.JsonRpcHttpServerConfig
import io.iohk.ethereum.utils.Logger

trait RateLimitValidator extends Logger {

val config: JsonRpcHttpServerConfig

val latestRequestTimestamps = new LruMap[RemoteAddress, Long](config.rateLimit.latestTimestampCacheSize)

val clock: Clock = Clock.systemUTC()

def validate(clientAddress: RemoteAddress):Boolean = {
val timeMillis = clock.instant().toEpochMilli
val latestRequestTimestamp = latestRequestTimestamps.getOrElse(clientAddress, 0L)
val response = latestRequestTimestamp + config.rateLimit.minRequestInterval.toMillis < timeMillis
if(response) latestRequestTimestamps.put(clientAddress, timeMillis)
response
}
}

0 comments on commit 16cd9d5

Please sign in to comment.