hammerlock.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. # The contents of this file are subject to the BitTorrent Open Source License
  2. # Version 1.1 (the License). You may not copy or use this file, in either
  3. # source code or executable form, except in compliance with the License. You
  4. # may obtain a copy of the License at http://www.bittorrent.com/license/.
  5. #
  6. # Software distributed under the License is distributed on an AS IS basis,
  7. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  8. # for the specific language governing rights and limitations under the
  9. # License.
  10. INTERVAL = 60
  11. PERIODS = 5
  12. class Hammerlock:
  13. def __init__(self, rate, call_later):
  14. self.rate = rate
  15. self.call_later = call_later
  16. self.curr = 0
  17. self.buckets = [{} for x in range(PERIODS)]
  18. self.call_later(INTERVAL, self._cycle)
  19. def _cycle(self):
  20. self.curr = (self.curr + 1) % PERIODS
  21. self.buckets[self.curr] = {}
  22. self.call_later(INTERVAL, self._cycle)
  23. def check(self, addr):
  24. x = self.buckets[self.curr].get(addr, 0) + 1
  25. self.buckets[self.curr][addr] = x
  26. x = 0
  27. for bucket in self.buckets:
  28. x += bucket.get(addr, 0)
  29. if x >= self.rate:
  30. return False
  31. else:
  32. return True