rand.py 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. '''Instead of sequential shortcodes, generate pseudorandom shortcodes.
  2. See https://github.com/ArchiveTeam/tinyback/blob/master/tinyback/generators.py
  3. for historical details.
  4. '''
  5. import hashlib
  6. import struct
  7. from terroroftinytown.client import alphabet
  8. class BaseRandMixin:
  9. def get_shortcode_width(self):
  10. '''Return the number of characters the shortcode string.'''
  11. raise NotImplementedError('Please override me with an integer.')
  12. class LegacyChainMixin(BaseRandMixin):
  13. def transform_sequence_num(self, sequence_num):
  14. # TODO: write me
  15. raise NotImplementedError('todo: not yet implemented')
  16. class HashRandMixin(BaseRandMixin):
  17. def transform_sequence_num(self, sequence_num):
  18. seed = struct.pack('>Q', sequence_num)
  19. hasher = hashlib.md5(seed)
  20. digest = hasher.digest()
  21. num = struct.unpack('>Q', digest[:8])[0]
  22. shortcode = alphabet.int_to_str(num, self.params['alphabet'])
  23. shortcode = shortcode[-self.get_shortcode_width():]
  24. return shortcode