Last active
November 9, 2024 11:47
-
-
Save fordnox/a09411e6fe5bffbb8164ca8510030c4e to your computer and use it in GitHub Desktop.
simplified proof of work explanation. demonstrates the fundamental idea: a participant must perform repeated computations until they find a solution that satisfies a specified condition.
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
import base64, hashlib, os | |
print('Searching for a key with valid hash. Hold tight, this might take a minute...') | |
threshold = 2 ** 234 | |
attempts = 0 | |
while True: | |
attempts += 1 | |
seed = os.urandom(50) | |
h = int.from_bytes(hashlib.sha256(seed).digest(), 'big') | |
if attempts % 100_000 == 0: | |
print('.', end='', flush=True) | |
if h < threshold: | |
key = base64.b64encode(seed).decode().rstrip('=') | |
print(f'\nSuccess! Key found after {attempts:,} attempts:\n\n {key}\n') | |
break |
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
import base64 | |
import hashlib | |
# Define the threshold (must match the original threshold) | |
threshold = 2 ** 234 | |
# Function to verify the proof-of-work key | |
def verify_key(proof_key): | |
# Decode the Base64 key (reversing the encoding done earlier) | |
try: | |
seed = base64.b64decode(proof_key + '==') # Add padding back | |
except Exception as e: | |
print("Invalid key format.") | |
return False | |
# Hash the seed and convert to an integer | |
h = int.from_bytes(hashlib.sha256(seed).digest(), 'big') | |
# Check if hash value meets the required threshold | |
if h < threshold: | |
print("Valid key! Proof-of-work verified.") | |
return True | |
else: | |
print("Invalid key! Proof-of-work condition not met.") | |
return False | |
# Example usage: suppose 'key' is the one generated by the original program | |
key = "example_generated_key_from_previous_program" # replace with the actual key | |
verify_key(key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment