|
| 1 | +import json |
| 2 | +import uuid |
| 3 | + |
| 4 | +from backend.config import STARTING_BALANCE |
| 5 | +from cryptography.hazmat.backends import default_backend |
| 6 | +from cryptography.hazmat.primitives.asymmetric import ec |
| 7 | +from cryptography.hazmat.primitives import hashes |
| 8 | +from cryptography.exceptions import InvalidSignature |
| 9 | + |
| 10 | +class Wallet: |
| 11 | + """ |
| 12 | + An individual wallet for a miner. |
| 13 | + Keeps track of the miner's balance. |
| 14 | + Allows a miner to authorize transactions. |
| 15 | + """ |
| 16 | + def __init__(self): |
| 17 | + self.address = str(uuid.uuid4())[0:8] |
| 18 | + self.balance = STARTING_BALANCE |
| 19 | + self.private_key = ec.generate_private_key( |
| 20 | + ec.SECP256K1(), |
| 21 | + default_backend() |
| 22 | + ) |
| 23 | + self.public_key = self.private_key.public_key() |
| 24 | + |
| 25 | + def sign(self, data): |
| 26 | + """ |
| 27 | + Generate a signature based on the data using the local private key. |
| 28 | + """ |
| 29 | + return self.private_key.sign( |
| 30 | + json.dumps(data).encode('utf-8'), |
| 31 | + ec.ECDSA(hashes.SHA256()) |
| 32 | + ) |
| 33 | + |
| 34 | + @staticmethod |
| 35 | + def verify(public_key, data, signature): |
| 36 | + """ |
| 37 | + Verify a signature based on the original public key and data. |
| 38 | + """ |
| 39 | + try: |
| 40 | + public_key.verify( |
| 41 | + signature, |
| 42 | + json.dumps(data).encode('utf-8'), |
| 43 | + ec.ECDSA(hashes.SHA256()) |
| 44 | + ) |
| 45 | + return True |
| 46 | + except InvalidSignature: |
| 47 | + return False |
| 48 | + |
| 49 | +def main(): |
| 50 | + wallet = Wallet() |
| 51 | + print(f'wallet.__dict__: {wallet.__dict__}') |
| 52 | + |
| 53 | + data = { 'foo': 'bar' } |
| 54 | + signature = wallet.sign(data) |
| 55 | + print(f'signature: {signature}') |
| 56 | + |
| 57 | + should_be_valid = Wallet.verify(wallet.public_key, data, signature) |
| 58 | + print(f'should_be_valid: {should_be_valid}') |
| 59 | + |
| 60 | + should_be_invalid = Wallet.verify(Wallet().public_key, data, signature) |
| 61 | + print(f'should_be_invalid: {should_be_invalid}') |
| 62 | + |
| 63 | +if __name__ == '__main__': |
| 64 | + main() |
0 commit comments