Created
December 30, 2023 11:41
-
-
Save M0r13n/832dc7fc00c8dce4d41ff56f0627cfbe to your computer and use it in GitHub Desktop.
GIL demo for Python3 using hashcash as a computational challenge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""An example demonstrating the limitations of the GIL (CPython). This example | |
increments a counter for a given challenge so that the first N bits of the SHA1 | |
hash of the challenge are all zeros (0). The computational effort increases | |
exponentially with the number of bits required to be zero. | |
This demo illustrates that this task cannot be sped up by parallelizing the | |
computation.""" | |
import base64 | |
import hashlib | |
import threading | |
import time | |
# send signals between threads. Used to mark when a solution was found | |
solution_found = threading.Event() | |
def are_first_n_bits_zero(byte_string: bytes, n: int) -> bool: | |
"""Return True if the first N bits are zero (0)""" | |
byte_index = (n // 8) # Calculate the byte index of the Nth bit | |
bit_offset = 8 - (n % 8) # Calculate the bit offset within that byte | |
# Check if all the bits before the Nth bit are zero | |
if any(byte_string[:byte_index]): | |
return False | |
# Check if the bits within the Nth byte before the Nth bit are zero | |
if (byte_string[byte_index] >> bit_offset) == 0: | |
return True | |
return False | |
def sha160(challenge: bytes) -> bytes: | |
"""Compute the SHA1 160-bit hash""" | |
return hashlib.sha1(challenge).digest() | |
def to_base64(v: object) -> bytes: | |
"""Encode any object as base64""" | |
return base64.b64encode(str(v).encode()) | |
def to_bin(digest: bytes) -> str: | |
"""Format a byte string as binary""" | |
bits = '' | |
for b in digest: | |
bits += f"{b:08b}" | |
return bits | |
def mint(challenge: str, bits: int) -> tuple[int, bytes]: | |
"""Mint a counter for the challenge, so that the SHA1 has begins | |
with N zeros, where N=bits. Not parallelized.""" | |
counter = 0 | |
encoded_challenge = challenge.encode() | |
while True: | |
digest = sha160(encoded_challenge + to_base64(counter)) | |
if are_first_n_bits_zero(digest, bits): | |
return counter, digest | |
counter += 1 | |
def worker(thread_id: int, challenge: str, bits: int, num_threads: int) -> None: | |
"""Parallelized version of `mint`.""" | |
print(f"Thread {thread_id} is starting search") | |
encoded_challenge = challenge.encode() | |
# Simulate some work | |
for counter in range(thread_id, 2**32, num_threads): | |
digest = sha160(encoded_challenge + to_base64(counter)) | |
if solution_found.is_set(): | |
print(f"Thread {thread_id} is stopping because solution was found") | |
return | |
if are_first_n_bits_zero(digest, bits): | |
print(f"Thread {thread_id} found the solution!") | |
print(f"SOLUTION: {counter}") | |
solution_found.set() | |
return | |
print(f"Thread {thread_id} did not find the solution and is exiting") | |
if __name__ == '__main__': | |
challenge = "Hello, my name is Leon." | |
bits = 21 | |
num_threads = 4 | |
# Single threaded | |
start = time.time() | |
counter, digest = mint(challenge, bits) | |
assert to_bin(digest)[:bits] == '0'*bits | |
print('SOLUTION', counter) | |
print(f'Single thread took: {time.time() - start:2f}s') | |
# Create threads | |
threads = [threading.Thread(target=worker, args=(i, challenge, bits, num_threads)) for i in range(num_threads)] | |
start = time.time() | |
# Start threads | |
for t in threads: | |
t.start() | |
# Wait for all threads to complete | |
for t in threads: | |
t.join() | |
print(f'Multiple thread took: {time.time() - start:2f}s') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment