pylibswarm

Python3 wrapper for libswarm-ng
git clone git://git.defalsify.org/pylibswarm.git
Info | Log | Files | Refs | Submodules | README | LICENSE

bmt.py (1708B)


      1 # standard imports
      2 import argparse
      3 import sys
      4 import logging
      5 import select
      6 
      7 # local imports
      8 from pylibswarm.arg import stdin_arg
      9 
     10 
     11 logging.basicConfig(level=logging.WARNING)
     12 logg = logging.getLogger()
     13 
     14 argparser = argparse.ArgumentParser()
     15 argparser.add_argument('-n', action='store_true', help='skip newline at end of output')
     16 argparser.add_argument('-b', action='store_true', help='output raw bytes')
     17 argparser.add_argument('-l', dest='data_length', type=int, help='length of data represented by preimage')
     18 argparser.add_argument('-v', action='store_true', help='verbose output')
     19 argparser.add_argument('-u', action='store_true', help='treat input as utf-8 string')
     20 argparser.add_argument('data', nargs='?', type=str, help='data input for BMT hasher')
     21 largs = argparser.parse_args(sys.argv[1:])
     22 
     23 
     24 if largs.v:
     25     logg.setLevel(logging.DEBUG)
     26 
     27 data = largs.data
     28 if data == None:
     29     data = stdin_arg()
     30 
     31 input_data = data
     32 if not largs.u:
     33     input_data.rstrip()
     34     if isinstance(input_data, str):
     35         input_data = data.encode('utf-8')
     36 
     37 input_data_length = 0
     38 input_data_length = len(input_data)
     39 data_length = input_data_length
     40 if largs.data_length != None:
     41     data_length = largs.data_length
     42 
     43 logg.info('hashing {} bytes input with {} length prefix'.format(int(input_data_length), int(data_length)))
     44 
     45 
     46 def main():
     47     # TODO: why does this segfault just one line before? - probably refcount related
     48     import swarm
     49     r = swarm.bmt_hash(input_data, input_data_length, data_length)
     50 
     51     if largs.b:
     52         sys.stdout.buffer.write(r[:32])
     53     else:
     54         s = '{}'.format(r[:32].hex())
     55         if not largs.n:
     56             s += '\n'
     57         sys.stdout.write(s)
     58 
     59 
     60 if __name__ == '__main__':
     61     main()