zexus 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/LICENSE +0 -0
  2. package/README.md +2513 -0
  3. package/bin/zexus +2 -0
  4. package/bin/zpics +2 -0
  5. package/bin/zpm +2 -0
  6. package/bin/zx +2 -0
  7. package/bin/zx-deploy +2 -0
  8. package/bin/zx-dev +2 -0
  9. package/bin/zx-run +2 -0
  10. package/package.json +66 -0
  11. package/scripts/README.md +24 -0
  12. package/scripts/postinstall.js +44 -0
  13. package/shared_config.json +24 -0
  14. package/src/README.md +1525 -0
  15. package/src/tests/run_zexus_tests.py +117 -0
  16. package/src/tests/test_all_phases.zx +346 -0
  17. package/src/tests/test_blockchain_features.zx +306 -0
  18. package/src/tests/test_complexity_features.zx +321 -0
  19. package/src/tests/test_core_integration.py +185 -0
  20. package/src/tests/test_phase10_ecosystem.zx +177 -0
  21. package/src/tests/test_phase1_modifiers.zx +87 -0
  22. package/src/tests/test_phase2_plugins.zx +80 -0
  23. package/src/tests/test_phase3_security.zx +97 -0
  24. package/src/tests/test_phase4_vfs.zx +116 -0
  25. package/src/tests/test_phase5_types.zx +117 -0
  26. package/src/tests/test_phase6_metaprogramming.zx +125 -0
  27. package/src/tests/test_phase7_optimization.zx +132 -0
  28. package/src/tests/test_phase9_advanced_types.zx +157 -0
  29. package/src/tests/test_security_features.py +419 -0
  30. package/src/tests/test_security_features.zx +276 -0
  31. package/src/tests/test_simple_zx.zx +1 -0
  32. package/src/tests/test_verification_simple.zx +69 -0
  33. package/src/zexus/__init__.py +28 -0
  34. package/src/zexus/__main__.py +5 -0
  35. package/src/zexus/__pycache__/__init__.cpython-312.pyc +0 -0
  36. package/src/zexus/__pycache__/advanced_types.cpython-312.pyc +0 -0
  37. package/src/zexus/__pycache__/builtin_modules.cpython-312.pyc +0 -0
  38. package/src/zexus/__pycache__/capability_system.cpython-312.pyc +0 -0
  39. package/src/zexus/__pycache__/complexity_system.cpython-312.pyc +0 -0
  40. package/src/zexus/__pycache__/concurrency_system.cpython-312.pyc +0 -0
  41. package/src/zexus/__pycache__/config.cpython-312.pyc +0 -0
  42. package/src/zexus/__pycache__/dependency_injection.cpython-312.pyc +0 -0
  43. package/src/zexus/__pycache__/ecosystem.cpython-312.pyc +0 -0
  44. package/src/zexus/__pycache__/environment.cpython-312.pyc +0 -0
  45. package/src/zexus/__pycache__/error_reporter.cpython-312.pyc +0 -0
  46. package/src/zexus/__pycache__/hybrid_orchestrator.cpython-312.pyc +0 -0
  47. package/src/zexus/__pycache__/lexer.cpython-312.pyc +0 -0
  48. package/src/zexus/__pycache__/metaprogramming.cpython-312.pyc +0 -0
  49. package/src/zexus/__pycache__/module_cache.cpython-312.pyc +0 -0
  50. package/src/zexus/__pycache__/object.cpython-312.pyc +0 -0
  51. package/src/zexus/__pycache__/optimization.cpython-312.pyc +0 -0
  52. package/src/zexus/__pycache__/plugin_system.cpython-312.pyc +0 -0
  53. package/src/zexus/__pycache__/policy_engine.cpython-312.pyc +0 -0
  54. package/src/zexus/__pycache__/security.cpython-312.pyc +0 -0
  55. package/src/zexus/__pycache__/stdlib_integration.cpython-312.pyc +0 -0
  56. package/src/zexus/__pycache__/strategy_recovery.cpython-312.pyc +0 -0
  57. package/src/zexus/__pycache__/syntax_validator.cpython-312.pyc +0 -0
  58. package/src/zexus/__pycache__/type_system.cpython-312.pyc +0 -0
  59. package/src/zexus/__pycache__/virtual_filesystem.cpython-312.pyc +0 -0
  60. package/src/zexus/__pycache__/zexus_ast.cpython-312.pyc +0 -0
  61. package/src/zexus/__pycache__/zexus_token.cpython-312.pyc +0 -0
  62. package/src/zexus/advanced_types.py +401 -0
  63. package/src/zexus/blockchain/__init__.py +40 -0
  64. package/src/zexus/blockchain/__pycache__/__init__.cpython-312.pyc +0 -0
  65. package/src/zexus/blockchain/__pycache__/crypto.cpython-312.pyc +0 -0
  66. package/src/zexus/blockchain/__pycache__/ledger.cpython-312.pyc +0 -0
  67. package/src/zexus/blockchain/__pycache__/transaction.cpython-312.pyc +0 -0
  68. package/src/zexus/blockchain/crypto.py +463 -0
  69. package/src/zexus/blockchain/ledger.py +255 -0
  70. package/src/zexus/blockchain/transaction.py +267 -0
  71. package/src/zexus/builtin_modules.py +284 -0
  72. package/src/zexus/builtin_plugins.py +317 -0
  73. package/src/zexus/capability_system.py +372 -0
  74. package/src/zexus/cli/__init__.py +2 -0
  75. package/src/zexus/cli/__pycache__/__init__.cpython-312.pyc +0 -0
  76. package/src/zexus/cli/__pycache__/main.cpython-312.pyc +0 -0
  77. package/src/zexus/cli/main.py +707 -0
  78. package/src/zexus/cli/zpm.py +203 -0
  79. package/src/zexus/compare_interpreter_compiler.py +146 -0
  80. package/src/zexus/compiler/__init__.py +169 -0
  81. package/src/zexus/compiler/__pycache__/__init__.cpython-312.pyc +0 -0
  82. package/src/zexus/compiler/__pycache__/lexer.cpython-312.pyc +0 -0
  83. package/src/zexus/compiler/__pycache__/parser.cpython-312.pyc +0 -0
  84. package/src/zexus/compiler/__pycache__/zexus_ast.cpython-312.pyc +0 -0
  85. package/src/zexus/compiler/bytecode.py +266 -0
  86. package/src/zexus/compiler/compat_runtime.py +277 -0
  87. package/src/zexus/compiler/lexer.py +257 -0
  88. package/src/zexus/compiler/parser.py +779 -0
  89. package/src/zexus/compiler/semantic.py +118 -0
  90. package/src/zexus/compiler/zexus_ast.py +454 -0
  91. package/src/zexus/complexity_system.py +575 -0
  92. package/src/zexus/concurrency_system.py +493 -0
  93. package/src/zexus/config.py +201 -0
  94. package/src/zexus/crypto_bridge.py +19 -0
  95. package/src/zexus/dependency_injection.py +423 -0
  96. package/src/zexus/ecosystem.py +434 -0
  97. package/src/zexus/environment.py +101 -0
  98. package/src/zexus/environment_manager.py +119 -0
  99. package/src/zexus/error_reporter.py +314 -0
  100. package/src/zexus/evaluator/__init__.py +12 -0
  101. package/src/zexus/evaluator/__pycache__/__init__.cpython-312.pyc +0 -0
  102. package/src/zexus/evaluator/__pycache__/bytecode_compiler.cpython-312.pyc +0 -0
  103. package/src/zexus/evaluator/__pycache__/core.cpython-312.pyc +0 -0
  104. package/src/zexus/evaluator/__pycache__/expressions.cpython-312.pyc +0 -0
  105. package/src/zexus/evaluator/__pycache__/functions.cpython-312.pyc +0 -0
  106. package/src/zexus/evaluator/__pycache__/integration.cpython-312.pyc +0 -0
  107. package/src/zexus/evaluator/__pycache__/statements.cpython-312.pyc +0 -0
  108. package/src/zexus/evaluator/__pycache__/utils.cpython-312.pyc +0 -0
  109. package/src/zexus/evaluator/bytecode_compiler.py +700 -0
  110. package/src/zexus/evaluator/core.py +891 -0
  111. package/src/zexus/evaluator/expressions.py +827 -0
  112. package/src/zexus/evaluator/functions.py +3989 -0
  113. package/src/zexus/evaluator/integration.py +396 -0
  114. package/src/zexus/evaluator/statements.py +4303 -0
  115. package/src/zexus/evaluator/utils.py +126 -0
  116. package/src/zexus/evaluator_original.py +2041 -0
  117. package/src/zexus/external_bridge.py +16 -0
  118. package/src/zexus/find_affected_imports.sh +155 -0
  119. package/src/zexus/hybrid_orchestrator.py +152 -0
  120. package/src/zexus/input_validation.py +259 -0
  121. package/src/zexus/lexer.py +571 -0
  122. package/src/zexus/logging.py +89 -0
  123. package/src/zexus/lsp/__init__.py +9 -0
  124. package/src/zexus/lsp/completion_provider.py +207 -0
  125. package/src/zexus/lsp/definition_provider.py +22 -0
  126. package/src/zexus/lsp/hover_provider.py +71 -0
  127. package/src/zexus/lsp/server.py +269 -0
  128. package/src/zexus/lsp/symbol_provider.py +31 -0
  129. package/src/zexus/metaprogramming.py +321 -0
  130. package/src/zexus/module_cache.py +89 -0
  131. package/src/zexus/module_manager.py +107 -0
  132. package/src/zexus/object.py +973 -0
  133. package/src/zexus/optimization.py +424 -0
  134. package/src/zexus/parser/__init__.py +31 -0
  135. package/src/zexus/parser/__pycache__/__init__.cpython-312.pyc +0 -0
  136. package/src/zexus/parser/__pycache__/parser.cpython-312.pyc +0 -0
  137. package/src/zexus/parser/__pycache__/strategy_context.cpython-312.pyc +0 -0
  138. package/src/zexus/parser/__pycache__/strategy_structural.cpython-312.pyc +0 -0
  139. package/src/zexus/parser/integration.py +86 -0
  140. package/src/zexus/parser/parser.py +3977 -0
  141. package/src/zexus/parser/strategy_context.py +7254 -0
  142. package/src/zexus/parser/strategy_structural.py +1033 -0
  143. package/src/zexus/persistence.py +391 -0
  144. package/src/zexus/plugin_system.py +290 -0
  145. package/src/zexus/policy_engine.py +365 -0
  146. package/src/zexus/profiler/__init__.py +5 -0
  147. package/src/zexus/profiler/profiler.py +233 -0
  148. package/src/zexus/purity_system.py +398 -0
  149. package/src/zexus/runtime/__init__.py +20 -0
  150. package/src/zexus/runtime/async_runtime.py +324 -0
  151. package/src/zexus/search_old_imports.sh +65 -0
  152. package/src/zexus/security.py +1407 -0
  153. package/src/zexus/stack_trace.py +233 -0
  154. package/src/zexus/stdlib/__init__.py +27 -0
  155. package/src/zexus/stdlib/blockchain.py +341 -0
  156. package/src/zexus/stdlib/compression.py +167 -0
  157. package/src/zexus/stdlib/crypto.py +124 -0
  158. package/src/zexus/stdlib/datetime.py +163 -0
  159. package/src/zexus/stdlib/db_mongo.py +199 -0
  160. package/src/zexus/stdlib/db_mysql.py +162 -0
  161. package/src/zexus/stdlib/db_postgres.py +163 -0
  162. package/src/zexus/stdlib/db_sqlite.py +133 -0
  163. package/src/zexus/stdlib/encoding.py +230 -0
  164. package/src/zexus/stdlib/fs.py +195 -0
  165. package/src/zexus/stdlib/http.py +219 -0
  166. package/src/zexus/stdlib/http_server.py +248 -0
  167. package/src/zexus/stdlib/json_module.py +61 -0
  168. package/src/zexus/stdlib/math.py +360 -0
  169. package/src/zexus/stdlib/os_module.py +265 -0
  170. package/src/zexus/stdlib/regex.py +148 -0
  171. package/src/zexus/stdlib/sockets.py +253 -0
  172. package/src/zexus/stdlib/test_framework.zx +208 -0
  173. package/src/zexus/stdlib/test_runner.zx +119 -0
  174. package/src/zexus/stdlib_integration.py +341 -0
  175. package/src/zexus/strategy_recovery.py +256 -0
  176. package/src/zexus/syntax_validator.py +356 -0
  177. package/src/zexus/testing/zpics.py +407 -0
  178. package/src/zexus/testing/zpics_runtime.py +369 -0
  179. package/src/zexus/type_system.py +374 -0
  180. package/src/zexus/validation_system.py +569 -0
  181. package/src/zexus/virtual_filesystem.py +355 -0
  182. package/src/zexus/vm/__init__.py +8 -0
  183. package/src/zexus/vm/__pycache__/__init__.cpython-312.pyc +0 -0
  184. package/src/zexus/vm/__pycache__/async_optimizer.cpython-312.pyc +0 -0
  185. package/src/zexus/vm/__pycache__/bytecode.cpython-312.pyc +0 -0
  186. package/src/zexus/vm/__pycache__/cache.cpython-312.pyc +0 -0
  187. package/src/zexus/vm/__pycache__/jit.cpython-312.pyc +0 -0
  188. package/src/zexus/vm/__pycache__/memory_manager.cpython-312.pyc +0 -0
  189. package/src/zexus/vm/__pycache__/memory_pool.cpython-312.pyc +0 -0
  190. package/src/zexus/vm/__pycache__/optimizer.cpython-312.pyc +0 -0
  191. package/src/zexus/vm/__pycache__/parallel_vm.cpython-312.pyc +0 -0
  192. package/src/zexus/vm/__pycache__/peephole_optimizer.cpython-312.pyc +0 -0
  193. package/src/zexus/vm/__pycache__/profiler.cpython-312.pyc +0 -0
  194. package/src/zexus/vm/__pycache__/register_allocator.cpython-312.pyc +0 -0
  195. package/src/zexus/vm/__pycache__/register_vm.cpython-312.pyc +0 -0
  196. package/src/zexus/vm/__pycache__/ssa_converter.cpython-312.pyc +0 -0
  197. package/src/zexus/vm/__pycache__/vm.cpython-312.pyc +0 -0
  198. package/src/zexus/vm/async_optimizer.py +420 -0
  199. package/src/zexus/vm/bytecode.py +428 -0
  200. package/src/zexus/vm/bytecode_converter.py +297 -0
  201. package/src/zexus/vm/cache.py +532 -0
  202. package/src/zexus/vm/jit.py +720 -0
  203. package/src/zexus/vm/memory_manager.py +520 -0
  204. package/src/zexus/vm/memory_pool.py +511 -0
  205. package/src/zexus/vm/optimizer.py +478 -0
  206. package/src/zexus/vm/parallel_vm.py +899 -0
  207. package/src/zexus/vm/peephole_optimizer.py +452 -0
  208. package/src/zexus/vm/profiler.py +527 -0
  209. package/src/zexus/vm/register_allocator.py +462 -0
  210. package/src/zexus/vm/register_vm.py +520 -0
  211. package/src/zexus/vm/ssa_converter.py +757 -0
  212. package/src/zexus/vm/vm.py +1392 -0
  213. package/src/zexus/zexus_ast.py +1782 -0
  214. package/src/zexus/zexus_token.py +253 -0
  215. package/src/zexus/zpm/__init__.py +15 -0
  216. package/src/zexus/zpm/installer.py +116 -0
  217. package/src/zexus/zpm/package_manager.py +208 -0
  218. package/src/zexus/zpm/publisher.py +98 -0
  219. package/src/zexus/zpm/registry.py +110 -0
  220. package/src/zexus.egg-info/PKG-INFO +2235 -0
  221. package/src/zexus.egg-info/SOURCES.txt +876 -0
  222. package/src/zexus.egg-info/dependency_links.txt +1 -0
  223. package/src/zexus.egg-info/entry_points.txt +3 -0
  224. package/src/zexus.egg-info/not-zip-safe +1 -0
  225. package/src/zexus.egg-info/requires.txt +14 -0
  226. package/src/zexus.egg-info/top_level.txt +2 -0
  227. package/zexus.json +14 -0
@@ -0,0 +1,463 @@
1
+ """
2
+ Zexus Blockchain Cryptographic Primitives Plugin
3
+
4
+ Provides built-in functions for:
5
+ - Cryptographic hashing (SHA256, KECCAK256, etc.)
6
+ - Digital signatures (ECDSA, RSA, etc.)
7
+ - Signature verification
8
+ """
9
+
10
+ import hashlib
11
+ import hmac
12
+ import secrets
13
+ from typing import Any, Optional
14
+
15
+ # Try to import cryptography library (optional for basic hashing)
16
+ try:
17
+ from cryptography.hazmat.primitives import hashes, serialization
18
+ from cryptography.hazmat.primitives.asymmetric import rsa, ec, padding
19
+ from cryptography.hazmat.backends import default_backend
20
+ from cryptography.exceptions import InvalidSignature
21
+ CRYPTO_AVAILABLE = True
22
+ except ImportError:
23
+ CRYPTO_AVAILABLE = False
24
+ print("Warning: cryptography library not installed. Signature features will be limited.")
25
+ print("Install with: pip install cryptography")
26
+
27
+
28
+ class CryptoPlugin:
29
+ """
30
+ Cryptographic primitives for blockchain operations
31
+ """
32
+
33
+ # Supported hash algorithms
34
+ HASH_ALGORITHMS = {
35
+ 'SHA256': hashlib.sha256,
36
+ 'SHA512': hashlib.sha512,
37
+ 'SHA3-256': hashlib.sha3_256,
38
+ 'SHA3-512': hashlib.sha3_512,
39
+ 'BLAKE2B': hashlib.blake2b,
40
+ 'BLAKE2S': hashlib.blake2s,
41
+ 'KECCAK256': lambda: hashlib.sha3_256(), # Ethereum-style Keccak
42
+ }
43
+
44
+ @staticmethod
45
+ def hash_data(data: Any, algorithm: str = 'SHA256') -> str:
46
+ """
47
+ Hash data using specified algorithm
48
+
49
+ Args:
50
+ data: Data to hash (will be converted to string)
51
+ algorithm: Hash algorithm name
52
+
53
+ Returns:
54
+ Hex-encoded hash
55
+ """
56
+ algorithm = algorithm.upper()
57
+ if algorithm not in CryptoPlugin.HASH_ALGORITHMS:
58
+ raise ValueError(f"Unsupported hash algorithm: {algorithm}. "
59
+ f"Supported: {', '.join(CryptoPlugin.HASH_ALGORITHMS.keys())}")
60
+
61
+ # Convert data to bytes
62
+ if isinstance(data, bytes):
63
+ data_bytes = data
64
+ elif isinstance(data, str):
65
+ data_bytes = data.encode('utf-8')
66
+ else:
67
+ data_bytes = str(data).encode('utf-8')
68
+
69
+ # Hash the data
70
+ hash_func = CryptoPlugin.HASH_ALGORITHMS[algorithm]
71
+ hasher = hash_func()
72
+ hasher.update(data_bytes)
73
+ return hasher.hexdigest()
74
+
75
+ @staticmethod
76
+ def generate_keypair(algorithm: str = 'ECDSA') -> tuple:
77
+ """
78
+ Generate a new keypair for signing
79
+
80
+ Args:
81
+ algorithm: Signature algorithm ('ECDSA' or 'RSA')
82
+
83
+ Returns:
84
+ (private_key_pem, public_key_pem) tuple
85
+ """
86
+ if not CRYPTO_AVAILABLE:
87
+ raise RuntimeError("cryptography library not installed. Install with: pip install cryptography")
88
+
89
+ algorithm = algorithm.upper()
90
+
91
+ if algorithm == 'ECDSA':
92
+ # Generate ECDSA keypair (secp256k1 curve - used by Bitcoin/Ethereum)
93
+ private_key = ec.generate_private_key(ec.SECP256K1(), default_backend())
94
+ public_key = private_key.public_key()
95
+
96
+ elif algorithm == 'RSA':
97
+ # Generate RSA keypair
98
+ private_key = rsa.generate_private_key(
99
+ public_exponent=65537,
100
+ key_size=2048,
101
+ backend=default_backend()
102
+ )
103
+ public_key = private_key.public_key()
104
+ else:
105
+ raise ValueError(f"Unsupported signature algorithm: {algorithm}")
106
+
107
+ # Serialize to PEM format
108
+ private_pem = private_key.private_bytes(
109
+ encoding=serialization.Encoding.PEM,
110
+ format=serialization.PrivateFormat.PKCS8,
111
+ encryption_algorithm=serialization.NoEncryption()
112
+ ).decode('utf-8')
113
+
114
+ public_pem = public_key.public_bytes(
115
+ encoding=serialization.Encoding.PEM,
116
+ format=serialization.PublicFormat.SubjectPublicKeyInfo
117
+ ).decode('utf-8')
118
+
119
+ return (private_pem, public_pem)
120
+
121
+ @staticmethod
122
+ def sign_data(data: Any, private_key_pem: str, algorithm: str = 'ECDSA') -> str:
123
+ """
124
+ Create a digital signature
125
+
126
+ Args:
127
+ data: Data to sign
128
+ private_key_pem: Private key in PEM format (or mock key for testing)
129
+ algorithm: Signature algorithm
130
+
131
+ Returns:
132
+ Hex-encoded signature
133
+ """
134
+ algorithm = algorithm.upper()
135
+
136
+ # Check if this is a mock/test key (not PEM format)
137
+ # Real PEM keys start with "-----BEGIN"
138
+ if not private_key_pem.strip().startswith('-----BEGIN'):
139
+ # Use mock signature for testing purposes
140
+ # This is NOT cryptographically secure, only for testing!
141
+ data_str = str(data) if not isinstance(data, (str, bytes)) else data
142
+ data_bytes = data_str.encode('utf-8') if isinstance(data_str, str) else data_str
143
+ key_bytes = private_key_pem.encode('utf-8')
144
+
145
+ # Generate deterministic mock signature
146
+ mock_signature = hmac.new(key_bytes, data_bytes, hashlib.sha256).hexdigest()
147
+ return f"mock_{algorithm.lower()}_{mock_signature}"
148
+
149
+ # Real PEM key - use cryptography library
150
+ if not CRYPTO_AVAILABLE:
151
+ raise RuntimeError("cryptography library not installed. Install with: pip install cryptography")
152
+
153
+ # Convert data to bytes
154
+ if isinstance(data, bytes):
155
+ data_bytes = data
156
+ elif isinstance(data, str):
157
+ data_bytes = data.encode('utf-8')
158
+ else:
159
+ data_bytes = str(data).encode('utf-8')
160
+
161
+ # Load private key
162
+ private_key = serialization.load_pem_private_key(
163
+ private_key_pem.encode('utf-8'),
164
+ password=None,
165
+ backend=default_backend()
166
+ )
167
+
168
+ # Sign data
169
+ if algorithm == 'ECDSA':
170
+ signature = private_key.sign(
171
+ data_bytes,
172
+ ec.ECDSA(hashes.SHA256())
173
+ )
174
+ elif algorithm == 'RSA':
175
+ signature = private_key.sign(
176
+ data_bytes,
177
+ padding.PSS(
178
+ mgf=padding.MGF1(hashes.SHA256()),
179
+ salt_length=padding.PSS.MAX_LENGTH
180
+ ),
181
+ hashes.SHA256()
182
+ )
183
+ else:
184
+ raise ValueError(f"Unsupported signature algorithm: {algorithm}")
185
+
186
+ return signature.hex()
187
+
188
+ @staticmethod
189
+ def verify_signature(data: Any, signature_hex: str, public_key_pem: str,
190
+ algorithm: str = 'ECDSA') -> bool:
191
+ """
192
+ Verify a digital signature
193
+
194
+ Args:
195
+ data: Original data
196
+ signature_hex: Hex-encoded signature (or mock signature for testing)
197
+ public_key_pem: Public key in PEM format (or mock key for testing)
198
+ algorithm: Signature algorithm
199
+
200
+ Returns:
201
+ True if signature is valid, False otherwise
202
+ """
203
+ algorithm = algorithm.upper()
204
+
205
+ # Check if this is a mock signature (for testing)
206
+ if signature_hex.startswith('mock_'):
207
+ # Verify mock signature using HMAC
208
+ try:
209
+ # Extract algorithm and signature parts
210
+ parts = signature_hex.split('_', 2)
211
+ if len(parts) != 3:
212
+ return False
213
+
214
+ sig_algorithm = parts[1] # already lowercase from mock signature
215
+ sig_hash = parts[2]
216
+
217
+ # Verify algorithm matches (compare lowercase to lowercase)
218
+ if sig_algorithm != algorithm.lower():
219
+ return False
220
+
221
+ # Reconstruct signature to verify
222
+ data_str = str(data) if not isinstance(data, (str, bytes)) else data
223
+ data_bytes = data_str.encode('utf-8') if isinstance(data_str, str) else data_str
224
+ # Note: In mock mode, "public key" is actually the same as private key for testing
225
+ key_bytes = public_key_pem.encode('utf-8')
226
+
227
+ expected_sig = hmac.new(key_bytes, data_bytes, hashlib.sha256).hexdigest()
228
+ return sig_hash == expected_sig
229
+ except Exception:
230
+ return False
231
+
232
+ # Real PEM signature - use cryptography library
233
+ if not CRYPTO_AVAILABLE:
234
+ return False
235
+
236
+ # Convert data to bytes
237
+ if isinstance(data, bytes):
238
+ data_bytes = data
239
+ elif isinstance(data, str):
240
+ data_bytes = data.encode('utf-8')
241
+ else:
242
+ data_bytes = str(data).encode('utf-8')
243
+
244
+ # Convert signature from hex
245
+ try:
246
+ signature = bytes.fromhex(signature_hex)
247
+ except ValueError:
248
+ return False
249
+
250
+ # Load public key
251
+ try:
252
+ public_key = serialization.load_pem_public_key(
253
+ public_key_pem.encode('utf-8'),
254
+ backend=default_backend()
255
+ )
256
+ except Exception:
257
+ return False
258
+
259
+ # Verify signature
260
+ try:
261
+ if algorithm == 'ECDSA':
262
+ public_key.verify(
263
+ signature,
264
+ data_bytes,
265
+ ec.ECDSA(hashes.SHA256())
266
+ )
267
+ elif algorithm == 'RSA':
268
+ public_key.verify(
269
+ signature,
270
+ data_bytes,
271
+ padding.PSS(
272
+ mgf=padding.MGF1(hashes.SHA256()),
273
+ salt_length=padding.PSS.MAX_LENGTH
274
+ ),
275
+ hashes.SHA256()
276
+ )
277
+ else:
278
+ return False
279
+ return True
280
+ except InvalidSignature:
281
+ return False
282
+ except Exception:
283
+ return False
284
+
285
+ @staticmethod
286
+ def keccak256(data: Any) -> str:
287
+ """
288
+ Ethereum-style Keccak-256 hash
289
+
290
+ Args:
291
+ data: Data to hash
292
+
293
+ Returns:
294
+ Hex-encoded hash (with '0x' prefix)
295
+ """
296
+ result = CryptoPlugin.hash_data(data, 'KECCAK256')
297
+ return '0x' + result
298
+
299
+ @staticmethod
300
+ def generate_random_bytes(length: int = 32) -> str:
301
+ """
302
+ Generate cryptographically secure random bytes
303
+
304
+ Args:
305
+ length: Number of bytes to generate
306
+
307
+ Returns:
308
+ Hex-encoded random bytes
309
+ """
310
+ return secrets.token_hex(length)
311
+
312
+ @staticmethod
313
+ def derive_address(public_key_pem: str) -> str:
314
+ """
315
+ Derive an Ethereum-style address from a public key
316
+
317
+ Args:
318
+ public_key_pem: Public key in PEM format
319
+
320
+ Returns:
321
+ Address (hex with '0x' prefix)
322
+ """
323
+ if not CRYPTO_AVAILABLE:
324
+ raise RuntimeError("cryptography library not installed. Install with: pip install cryptography")
325
+
326
+ # Load public key
327
+ public_key = serialization.load_pem_public_key(
328
+ public_key_pem.encode('utf-8'),
329
+ backend=default_backend()
330
+ )
331
+
332
+ # Get public key bytes (uncompressed)
333
+ public_bytes = public_key.public_bytes(
334
+ encoding=serialization.Encoding.X962,
335
+ format=serialization.PublicFormat.UncompressedPoint
336
+ )
337
+
338
+ # Keccak256 hash
339
+ hash_result = hashlib.sha3_256(public_bytes[1:]).digest()
340
+
341
+ # Take last 20 bytes as address
342
+ address = hash_result[-20:].hex()
343
+ return '0x' + address
344
+
345
+
346
+ def register_crypto_builtins(env):
347
+ """
348
+ Register cryptographic built-in functions in the Zexus environment
349
+
350
+ Functions registered:
351
+ - hash(data, algorithm) -> string
352
+ - sign(data, private_key, algorithm?) -> string
353
+ - verify_sig(data, signature, public_key, algorithm?) -> boolean
354
+ - keccak256(data) -> string
355
+ - generate_keypair(algorithm?) -> {private_key, public_key}
356
+ - random_bytes(length?) -> string
357
+ - derive_address(public_key) -> string
358
+ """
359
+ from zexus.object import Function, String, Boolean, Hash, Integer, Error
360
+
361
+ # hash(data, algorithm)
362
+ def builtin_hash(args):
363
+ if len(args) < 1:
364
+ return Error("hash expects at least 1 argument: data, [algorithm]")
365
+
366
+ data = args[0].value if hasattr(args[0], 'value') else str(args[0])
367
+ algorithm = args[1].value if len(args) > 1 and hasattr(args[1], 'value') else 'SHA256'
368
+
369
+ try:
370
+ result = CryptoPlugin.hash_data(data, algorithm)
371
+ return String(result)
372
+ except Exception as e:
373
+ return Error(f"Hash error: {str(e)}")
374
+
375
+ # sign(data, private_key, algorithm?)
376
+ def builtin_sign(args):
377
+ if len(args) < 2:
378
+ return Error("sign expects at least 2 arguments: data, private_key, [algorithm]")
379
+
380
+ data = args[0].value if hasattr(args[0], 'value') else str(args[0])
381
+ private_key = args[1].value if hasattr(args[1], 'value') else str(args[1])
382
+ algorithm = args[2].value if len(args) > 2 and hasattr(args[2], 'value') else 'ECDSA'
383
+
384
+ try:
385
+ result = CryptoPlugin.sign_data(data, private_key, algorithm)
386
+ return String(result)
387
+ except Exception as e:
388
+ return Error(f"Signature error: {str(e)}")
389
+
390
+ # verify_sig(data, signature, public_key, algorithm?)
391
+ def builtin_verify_sig(args):
392
+ if len(args) < 3:
393
+ return Error("verify_sig expects at least 3 arguments: data, signature, public_key, [algorithm]")
394
+
395
+ data = args[0].value if hasattr(args[0], 'value') else str(args[0])
396
+ signature = args[1].value if hasattr(args[1], 'value') else str(args[1])
397
+ public_key = args[2].value if hasattr(args[2], 'value') else str(args[2])
398
+ algorithm = args[3].value if len(args) > 3 and hasattr(args[3], 'value') else 'ECDSA'
399
+
400
+ try:
401
+ result = CryptoPlugin.verify_signature(data, signature, public_key, algorithm)
402
+ return Boolean(result)
403
+ except Exception as e:
404
+ return Error(f"Verification error: {str(e)}")
405
+
406
+ # keccak256(data)
407
+ def builtin_keccak256(args):
408
+ if len(args) != 1:
409
+ return Error("keccak256 expects 1 argument: data")
410
+
411
+ data = args[0].value if hasattr(args[0], 'value') else str(args[0])
412
+
413
+ try:
414
+ result = CryptoPlugin.keccak256(data)
415
+ return String(result)
416
+ except Exception as e:
417
+ return Error(f"Keccak256 error: {str(e)}")
418
+
419
+ # generate_keypair(algorithm?)
420
+ def builtin_generate_keypair(args):
421
+ algorithm = args[0].value if len(args) > 0 and hasattr(args[0], 'value') else 'ECDSA'
422
+
423
+ try:
424
+ private_key, public_key = CryptoPlugin.generate_keypair(algorithm)
425
+ return Hash({
426
+ String('private_key'): String(private_key),
427
+ String('public_key'): String(public_key)
428
+ })
429
+ except Exception as e:
430
+ return Error(f"Keypair generation error: {str(e)}")
431
+
432
+ # random_bytes(length?)
433
+ def builtin_random_bytes(args):
434
+ length = args[0].value if len(args) > 0 and hasattr(args[0], 'value') else 32
435
+
436
+ try:
437
+ result = CryptoPlugin.generate_random_bytes(length)
438
+ return String(result)
439
+ except Exception as e:
440
+ return Error(f"Random bytes error: {str(e)}")
441
+
442
+ # derive_address(public_key)
443
+ def builtin_derive_address(args):
444
+ if len(args) != 1:
445
+ return Error("derive_address expects 1 argument: public_key")
446
+
447
+ public_key = args[0].value if hasattr(args[0], 'value') else str(args[0])
448
+
449
+ try:
450
+ result = CryptoPlugin.derive_address(public_key)
451
+ return String(result)
452
+ except Exception as e:
453
+ return Error(f"Address derivation error: {str(e)}")
454
+
455
+ # Register all functions
456
+ env.set("hash", Function(builtin_hash))
457
+ env.set("sign", Function(builtin_sign))
458
+ env.set("signature", Function(builtin_sign)) # Alias for sign
459
+ env.set("verify_sig", Function(builtin_verify_sig))
460
+ env.set("keccak256", Function(builtin_keccak256))
461
+ env.set("generateKeypair", Function(builtin_generate_keypair))
462
+ env.set("randomBytes", Function(builtin_random_bytes))
463
+ env.set("deriveAddress", Function(builtin_derive_address))