import requests


def check_hash(h):
	"""
	Do the heavy lifting. Take the hash, poll the haveibeenpwned API, and check results.
	:param h: The sha1 hash to check
	:return: The number of times the password has been found (0 is good!)
	"""
	if len(h) != 40:
		raise ValueError("A sha1 hash should be 30 characters.")
	h = h.upper()

	chk = h[:5]
	r = requests.get("https://api.pwnedpasswords.com/range/%s" % chk)
	if r.status_code != 200:
		raise EnvironmentError("Unable to retrieve password hashes from server.")
	matches = {m: int(v) for (m, v) in [ln.split(':') for ln in r.content.decode('utf-8').split("\r\n")]}
	#print("Prefix search returned %d potential matches." % len(matches))
	for m in matches.keys():
		if m == h[5:]:
			return matches[m]
	return 0