# Copyright (c) 2014 Jan Varho
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

"""Common variables and functions used by scrypt implementations"""

import numbers


SCRYPT_MCF_PREFIX_7 = b'$7$'
SCRYPT_MCF_PREFIX_s1 = b'$s1$'
SCRYPT_MCF_PREFIX_DEFAULT = b'$s1$'
SCRYPT_MCF_PREFIX_ANY = None

SCRYPT_N = 1<<14
SCRYPT_r = 8
SCRYPT_p = 1

# The last one differs from libscrypt defaults, but matches the 'interactive'
# work factor from the original paper. For long term storage where runtime of
# key derivation is not a problem, you could use 16 as in libscrypt or better
# yet increase N if memory is plentiful.

xrange = xrange if 'xrange' in globals() else range

def check_args(password, salt, N, r, p, olen=64):
    if not isinstance(password, bytes):
        raise TypeError('password must be a byte string')
    if not isinstance(salt, bytes):
        raise TypeError('salt must be a byte string')
    if not isinstance(N, numbers.Integral):
        raise TypeError('N must be an integer')
    if not isinstance(r, numbers.Integral):
        raise TypeError('r must be an integer')
    if not isinstance(p, numbers.Integral):
        raise TypeError('p must be an integer')
    if not isinstance(olen, numbers.Integral):
        raise TypeError('length must be an integer')
    if N > 2**63:
        raise ValueError('N cannot be larger than 2**63')
    if (N & (N - 1)) or N < 2:
        raise ValueError('N must be a power of two larger than 1')
    if r <= 0:
        raise ValueError('r must be positive')
    if p <= 0:
        raise ValueError('p must be positive')
    if r * p >= 2**30:
        raise ValueError('r * p must be less than 2 ** 30')
    if olen <= 0:
        raise ValueError('length must be positive')

