-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_signer_example.py
More file actions
429 lines (344 loc) · 14.1 KB
/
Copy pathpython_signer_example.py
File metadata and controls
429 lines (344 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
"""
Python integration example for the Solana Secure Signer.
This module demonstrates three methods of integration:
1. FFI (ctypes) - Direct library calls (fastest)
2. CLI subprocess - Using the binary (most portable)
3. Combined approach - Fallback mechanism
Security guarantees:
- Private keys are never exposed in Python
- All key operations happen in Rust's secure memory
- Memory is locked and zeroized in Rust
"""
import json
import subprocess
import sys
from ctypes import *
from pathlib import Path
from typing import Optional, Tuple
import base64
# ============================================================================
# Method 1: FFI Integration (ctypes)
# ============================================================================
class FFIErrorCode:
"""FFI error codes from Rust."""
SUCCESS = 0
INVALID_INPUT = 1
MEMORY_ERROR = 2
DECRYPTION_ERROR = 3
SIGNING_ERROR = 4
SERIALIZATION_ERROR = 5
class FFIResult(Structure):
"""FFI result structure matching Rust's FFIResult."""
_fields_ = [
("error_code", c_int),
("data", POINTER(c_ubyte)),
("data_len", c_size_t),
("error_message", c_char_p),
]
class SolanaSecureSigner:
"""
Python wrapper for the Rust signing library using FFI.
This provides a Pythonic interface to the secure signing core
while ensuring all key operations happen in Rust's secure memory.
"""
def __init__(self, lib_path: Optional[str] = None):
"""
Initialize the signer with the Rust library.
Args:
lib_path: Path to the compiled Rust library.
If None, will search in common locations.
"""
if lib_path is None:
lib_path = self._find_library()
self.lib = CDLL(str(lib_path))
self._setup_functions()
def _find_library(self) -> str:
"""Find the compiled Rust library."""
possible_paths = [
Path(__file__).parent / "rust_signer" / "target" / "release" / "libsolana_secure_signer.so",
Path(__file__).parent / "rust_signer" / "target" / "release" / "libsolana_secure_signer.dylib",
Path(__file__).parent / "rust_signer" / "target" / "release" / "solana_secure_signer.dll",
]
for path in possible_paths:
if path.exists():
return str(path)
raise FileNotFoundError(
"Could not find Rust library. Please compile it first:\n"
" cd rust_signer && cargo build --release"
)
def _setup_functions(self):
"""Set up ctypes function signatures."""
# sign_transaction_ffi
self.lib.sign_transaction_ffi.argtypes = [
c_char_p, # encrypted_json
c_char_p, # passphrase
POINTER(c_ubyte), # transaction
c_size_t, # transaction_len
]
self.lib.sign_transaction_ffi.restype = FFIResult
# create_encrypted_container_ffi
self.lib.create_encrypted_container_ffi.argtypes = [
POINTER(c_ubyte), # private_key
c_size_t, # private_key_len
c_char_p, # passphrase
]
self.lib.create_encrypted_container_ffi.restype = FFIResult
# free_buffer
self.lib.free_buffer.argtypes = [POINTER(c_ubyte), c_size_t]
self.lib.free_buffer.restype = None
# free_error_message
self.lib.free_error_message.argtypes = [c_char_p]
self.lib.free_error_message.restype = None
# get_version
self.lib.get_version.argtypes = []
self.lib.get_version.restype = c_char_p
def get_version(self) -> str:
"""Get the library version."""
return self.lib.get_version().decode('utf-8')
def create_encrypted_container(
self,
private_key: bytes,
passphrase: str
) -> dict:
"""
Create an encrypted key container.
Args:
private_key: 32-byte Ed25519 private key
passphrase: Passphrase for encryption
Returns:
Dictionary containing the encrypted container
Raises:
RuntimeError: If encryption fails
"""
if len(private_key) != 32:
raise ValueError(f"Private key must be 32 bytes, got {len(private_key)}")
# Convert to ctypes
key_array = (c_ubyte * len(private_key))(*private_key)
passphrase_bytes = passphrase.encode('utf-8')
# Call FFI
result = self.lib.create_encrypted_container_ffi(
key_array,
len(private_key),
passphrase_bytes
)
# Handle result
if result.error_code != FFIErrorCode.SUCCESS:
error_msg = result.error_message.decode('utf-8')
self.lib.free_error_message(result.error_message)
raise RuntimeError(f"Encryption failed: {error_msg}")
# Extract data
data_bytes = bytes(result.data[:result.data_len])
self.lib.free_buffer(result.data, result.data_len)
return json.loads(data_bytes)
def sign_transaction(
self,
encrypted_container: dict,
passphrase: str,
transaction: bytes
) -> Tuple[bytes, bytes]:
"""
Sign a Solana transaction.
SECURITY: This is the critical security function. The private key:
- Is decrypted in Rust's locked memory
- Never enters Python's memory space
- Is zeroized immediately after signing
- Cannot be swapped to disk
Args:
encrypted_container: Encrypted key container (from create_encrypted_container)
passphrase: Passphrase for decryption
transaction: Unsigned transaction bytes
Returns:
Tuple of (signature, signed_transaction)
Raises:
RuntimeError: If signing fails
"""
# Serialize container
container_json = json.dumps(encrypted_container).encode('utf-8')
passphrase_bytes = passphrase.encode('utf-8')
# Convert transaction to ctypes
tx_array = (c_ubyte * len(transaction))(*transaction)
# Call FFI
result = self.lib.sign_transaction_ffi(
container_json,
passphrase_bytes,
tx_array,
len(transaction)
)
# Handle result
if result.error_code != FFIErrorCode.SUCCESS:
error_msg = result.error_message.decode('utf-8')
self.lib.free_error_message(result.error_message)
raise RuntimeError(f"Signing failed: {error_msg}")
# Extract data
data_bytes = bytes(result.data[:result.data_len])
self.lib.free_buffer(result.data, result.data_len)
# Parse result
signed_data = json.loads(data_bytes)
signature = base64.b64decode(signed_data['signature']) if isinstance(signed_data['signature'], str) else bytes(signed_data['signature'])
signed_tx = base64.b64decode(signed_data['signed_transaction']) if isinstance(signed_data['signed_transaction'], str) else bytes(signed_data['signed_transaction'])
return signature, signed_tx
# ============================================================================
# Method 2: CLI Subprocess Integration
# ============================================================================
class SolanaSignerCLI:
"""
Python wrapper for the Rust signing CLI using subprocess.
This is useful when FFI is not available or as a fallback.
Slightly slower than FFI but more portable.
"""
def __init__(self, binary_path: Optional[str] = None):
"""
Initialize the CLI wrapper.
Args:
binary_path: Path to the compiled Rust binary.
If None, will search in common locations.
"""
if binary_path is None:
binary_path = self._find_binary()
self.binary_path = binary_path
def _find_binary(self) -> str:
"""Find the compiled Rust binary."""
possible_paths = [
Path(__file__).parent / "rust_signer" / "target" / "release" / "solana-signer",
Path(__file__).parent / "rust_signer" / "target" / "release" / "solana-signer.exe",
]
for path in possible_paths:
if path.exists():
return str(path)
raise FileNotFoundError(
"Could not find Rust binary. Please compile it first:\n"
" cd rust_signer && cargo build --release"
)
def sign_transaction_stdin(
self,
encrypted_container: dict,
passphrase: str,
transaction: bytes
) -> Tuple[bytes, bytes]:
"""
Sign a transaction using the CLI via stdin/stdout.
Args:
encrypted_container: Encrypted key container
passphrase: Passphrase for decryption
transaction: Unsigned transaction bytes
Returns:
Tuple of (signature, signed_transaction)
Raises:
RuntimeError: If signing fails
"""
# Prepare input
container_json = json.dumps(encrypted_container)
tx_hex = transaction.hex()
input_data = f"{container_json}\n{tx_hex}\n"
# Run CLI
try:
result = subprocess.run(
[self.binary_path, "sign-stdin", "-p", passphrase],
input=input_data,
capture_output=True,
text=True,
check=True
)
# Parse output
output_data = json.loads(result.stdout)
signature = base64.b64decode(output_data['signature']) if isinstance(output_data['signature'], str) else bytes(output_data['signature'])
signed_tx = base64.b64decode(output_data['signed_transaction']) if isinstance(output_data['signed_transaction'], str) else bytes(output_data['signed_transaction'])
return signature, signed_tx
except subprocess.CalledProcessError as e:
raise RuntimeError(f"CLI signing failed: {e.stderr}")
# ============================================================================
# Example Usage
# ============================================================================
def example_ffi():
"""Example using FFI integration."""
print("=" * 70)
print("Example 1: FFI Integration")
print("=" * 70)
# Initialize signer
signer = SolanaSecureSigner()
print(f"Library version: {signer.get_version()}")
# Generate a test private key (in production, use proper key generation)
private_key = bytes([42] * 32) # DO NOT use this in production!
# Create encrypted container
passphrase = "super_secure_passphrase_123"
print("\n1. Creating encrypted container...")
container = signer.create_encrypted_container(private_key, passphrase)
print(f" ✓ Container created with salt: {container['salt'][:20]}...")
# Create a test transaction
test_transaction = b"Hello, Solana! This is a test transaction."
print(f"\n2. Signing transaction ({len(test_transaction)} bytes)...")
# Sign the transaction
# SECURITY: The private key is decrypted in Rust's locked memory
# and never enters Python's memory space
signature, signed_tx = signer.sign_transaction(
container,
passphrase,
test_transaction
)
print(f" ✓ Transaction signed!")
print(f" Signature: {signature.hex()[:32]}...")
print(f" Signed TX length: {len(signed_tx)} bytes")
# Demonstrate wrong passphrase
print("\n3. Testing wrong passphrase...")
try:
signer.sign_transaction(container, "wrong_passphrase", test_transaction)
print(" ✗ Should have failed!")
except RuntimeError as e:
print(f" ✓ Correctly rejected: {str(e)[:50]}...")
print("\n" + "=" * 70)
print("FFI Integration Example Complete")
print("=" * 70)
def example_cli():
"""Example using CLI integration."""
print("\n\n")
print("=" * 70)
print("Example 2: CLI Subprocess Integration")
print("=" * 70)
# Initialize CLI wrapper
try:
cli = SolanaSignerCLI()
# Use the same container from FFI example
signer = SolanaSecureSigner()
private_key = bytes([42] * 32)
passphrase = "super_secure_passphrase_123"
container = signer.create_encrypted_container(private_key, passphrase)
# Sign via CLI
test_transaction = b"Hello from CLI!"
print(f"\n1. Signing transaction via CLI...")
signature, signed_tx = cli.sign_transaction_stdin(
container,
passphrase,
test_transaction
)
print(f" ✓ Transaction signed via CLI!")
print(f" Signature: {signature.hex()[:32]}...")
print("\n" + "=" * 70)
print("CLI Integration Example Complete")
print("=" * 70)
except FileNotFoundError as e:
print(f"\n⚠ CLI binary not found: {e}")
print(" Skipping CLI example. Compile with: cd rust_signer && cargo build --release")
if __name__ == "__main__":
print("\n")
print("╔" + "=" * 68 + "╗")
print("║" + " " * 15 + "SOLANA SECURE SIGNER - PYTHON INTEGRATION" + " " * 11 + "║")
print("╚" + "=" * 68 + "╝")
print()
print("This demonstrates secure transaction signing with:")
print(" • Private keys locked in RAM (mlock/VirtualLock)")
print(" • Automatic zeroization of sensitive data")
print(" • No key exposure to Python memory space")
print(" • Panic-safe cleanup guarantees")
print()
try:
example_ffi()
except FileNotFoundError as e:
print(f"\n⚠ Error: {e}")
print("\nPlease compile the Rust library first:")
print(" cd rust_signer")
print(" cargo build --release")
sys.exit(1)
try:
example_cli()
except Exception as e:
print(f"\nCLI example error: {e}")