|
| 1 | +# secp256k1_compat.py: Compatibility layer for secp256k1.py to use MicroPython's usecp256k1 module |
| 2 | +# Mimics cffi's ffi and lib objects |
| 3 | + |
| 4 | +import usecp256k1 # Your MicroPython C module |
| 5 | + |
| 6 | +# Constants (from libsecp256k1) |
| 7 | +SECP256K1_CONTEXT_SIGN = 1 << 8 # 256 |
| 8 | +SECP256K1_CONTEXT_VERIFY = 1 << 9 # 512 |
| 9 | +SECP256K1_EC_COMPRESSED = 1 << 1 # 2 |
| 10 | +SECP256K1_EC_UNCOMPRESSED = 0 |
| 11 | + |
| 12 | +# Dummy ffi class to mimic cffi |
| 13 | +class FFI: |
| 14 | + def new(self, type_str): |
| 15 | + # For 'unsigned char[74]' or 'size_t *' |
| 16 | + if 'unsigned char' in type_str: |
| 17 | + size = int(type_str.split('[')[1].rstrip(']')) |
| 18 | + return bytearray(size) |
| 19 | + elif 'size_t *' in type_str: |
| 20 | + return [0] # Simulate pointer to size_t |
| 21 | + raise ValueError(f"Unsupported ffi type: {type_str}") |
| 22 | + |
| 23 | + def buffer(self, obj, size=None): |
| 24 | + # Return bytes from bytearray or slice |
| 25 | + if isinstance(obj, list): |
| 26 | + return bytes(obj) |
| 27 | + return bytes(obj[:size] if size is not None else obj) |
| 28 | + |
| 29 | +# Dummy lib class to map to usecp256k1 functions |
| 30 | +class Lib: |
| 31 | + # Constants |
| 32 | + SECP256K1_EC_COMPRESSED = SECP256K1_EC_COMPRESSED |
| 33 | + SECP256K1_EC_UNCOMPRESSED = SECP256K1_EC_UNCOMPRESSED |
| 34 | + SECP256K1_CONTEXT_SIGN = SECP256K1_CONTEXT_SIGN |
| 35 | + SECP256K1_CONTEXT_VERIFY = SECP256K1_CONTEXT_VERIFY |
| 36 | + |
| 37 | + def secp256k1_context_create(self, flags): |
| 38 | + # Context is managed by usecp256k1, return dummy object |
| 39 | + return object() |
| 40 | + |
| 41 | + def secp256k1_ecdsa_signature_serialize_der(self, ctx, output, outputlen, raw_sig): |
| 42 | + # Call usecp256k1_ecdsa_signature_serialize_der |
| 43 | + try: |
| 44 | + result = usecp256k1.usecp256k1_ecdsa_signature_serialize_der(raw_sig) |
| 45 | + if result is None: |
| 46 | + return 0 # Mimic libsecp256k1 failure |
| 47 | + # Copy result to output buffer |
| 48 | + output[:len(result)] = result |
| 49 | + outputlen[0] = len(result) |
| 50 | + return 1 # Mimic libsecp256k1 success |
| 51 | + except ValueError: |
| 52 | + return 0 # Handle errors like invalid signature length |
| 53 | + |
| 54 | +# Instantiate ffi and lib |
| 55 | +ffi = FFI() |
| 56 | +lib = Lib() |
| 57 | + |
| 58 | +# Feature flags (set based on your usecp256k1 module's capabilities) |
| 59 | +HAS_RECOVERABLE = hasattr(usecp256k1, 'usecp256k1_ecdsa_sign_recoverable') |
| 60 | +HAS_SCHNORR = hasattr(usecp256k1, 'usecp256k1_schnorrsig_sign') |
| 61 | +HAS_ECDH = hasattr(usecp256k1, 'usecp256k1_ecdh') |
| 62 | +HAS_EXTRAKEYS = hasattr(usecp256k1, 'usecp256k1_keypair_create') |
0 commit comments