Repository navigation
Expand file tree
/
Copy pathself_test.py
More file actions
1540 lines (1269 loc) · 62.3 KB
/
Copy pathself_test.py
File metadata and controls
1540 lines (1269 loc) · 62.3 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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Knish.IO Python SDK Self-Test Script
=====================================
Tests core SDK functionality and cross-platform compatibility.
Test Suite:
1. Crypto Test - Secret generation and bundle hash
2. Metadata Creation Test - M-type atoms with ContinuID
3. Simple Transfer Test - Full balance transfer
4. Complex Transfer Test - Transfer with remainder
5. Cross-SDK Validation - Validate molecules from other SDKs
"""
import json
import os
import sys
import time
from pathlib import Path
from typing import Dict, List, Optional, Any
# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(__file__))
from knishioclient import __version__ as SDK_VERSION
from knishioclient.libraries import crypto, strings
from knishioclient.models.Wallet import Wallet
from knishioclient.models.Molecule import Molecule
from knishioclient.models.Atom import Atom
from knishioclient.models.AtomMeta import AtomMeta
from knishioclient.models.Meta import Meta
from knishioclient.libraries.check import verify
from knishioclient.exception import *
# Fixed timestamp for deterministic testing (preserves timestamp in hash while ensuring consistency)
FIXED_TEST_TIMESTAMP_BASE = 1700000000000 # Fixed base timestamp for deterministic testing
def set_fixed_timestamps(molecule):
"""Helper function to set fixed timestamps for deterministic testing"""
for i, atom in enumerate(molecule.atoms):
# Set deterministic timestamp: base + (index * 1000) to ensure unique but predictable timestamps
atom.createdAt = str(FIXED_TEST_TIMESTAMP_BASE + (i * 1000))
def create_fixed_remainder_wallet(secret: str, token: str):
"""Helper function to create fixed remainder wallets for deterministic testing"""
return Wallet(
secret=secret,
token=token,
position='bbbb000000000000cccc111111111111dddd222222222222eeee333333333333' # Fixed deterministic position
)
# ANSI color codes for terminal output
class Colors:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
RESET = '\033[0m'
# Global results storage
results = {
'sdk': 'Python',
# Read from the package rather than a literal. This was hardcoded to '1.0.0',
# so every results file claimed a version the project has never published — an
# external audit read it and concluded the Python SDK had no version manifest
# and had never been released. The gauntlet now fails a results file whose
# version disagrees with its manifest, which a literal would trip permanently.
'version': SDK_VERSION,
'timestamp': None,
# Run identity. shared-test-results/ holds one mutable file per SDK with no record of
# which run wrote it, so a later standalone run silently replaces the evidence an
# already-published report was built from.
'runId': os.environ.get('KNISHIO_RUN_ID') or None,
'tests': {},
'molecules': {},
# Starts False. This was True, making "fully cross-SDK compatible" the default state
# before a single peer molecule had been examined — so every early return out of
# test_cross_sdk_validation published a pass. A verdict must be earned; the safe
# default for a check that has not run is "failed".
'crossSdkCompatible': False,
# Coverage behind the verdict. The boolean alone cannot distinguish "validated seven
# peers, all passed" from "validated nothing and so found no failures".
'crossValidation': {'ran': False, 'targetsExpected': 0, 'targetsValidated': 0},
}
def log(message: str, color: str = None):
"""Print colored log message"""
if color:
print(f"{getattr(Colors, color.upper(), '')}{message}{Colors.RESET}")
else:
print(message)
def log_test(test_name: str, passed: bool, error: str = None):
"""Log test result with formatting"""
if passed:
log(f" ✅ PASS: {test_name}", 'green')
else:
error_msg = f" - {error}" if error else ""
log(f" ❌ FAIL: {test_name}{error_msg}", 'red')
def load_config() -> Dict:
"""Load test configuration - embedded for SDK self-containment"""
default_config = {
"tests": {
"crypto": {
"seed": "TESTSEED",
"secret": "e8ffc86d60fc6a73234a834166e7436e21df6c3209dfacc8d0bd6595707872c3799abbf7deee0f9c4b58de1fd89b9abb67a207558208d5ccf550c227d197c24e9fcc3707aeb53c4031d38392020ff72bcaa0f728aa8bc3d47d95ff0afc04d8fcdb69bff638ce56646c154fc92aa517d3c40f550d2ccacbd921724e1d94b82aed2c8e172a8a7ed5a6963f5890157fe77222b97af3787741f9d3cec0b40aec6f07ae4b2b24614f0a20e035aee0df04e176175dc100eb1b00dd7ea95c28cdec47958336945333c3bef24719ed949fa56d1541f24c725d4f374a533bf255cf22f4596147bcd1ba05abcecbe9b12095e1fdddb094616894c366498be0b5785c180100efb3c5b689fc1c01131633fe1775df52a970e9472ab7bc0c19f5742b9e9436753cd16024b2d326b763eca68c414755a0d2fdbb927f007e9413f1190578b2033a03d29387f5aea71b07a5ce80fbfd45be4a15440faadeac50e41846022894fc683a52328b470bc1860c8b038d7258f504178918502b93d84d8b0fbef3e02f89f83cb1ff033a2bdbdf2a2ba78d80c12aa8b2d6c10d76c468186bd4a4e9eacc758546bb50ed7b1ee241cc5b93ff924c7bbee6778b27789e1f9104c917fc93f735eee5b25c07a883788f3d2e0771e751c4f59b76f8426027ac2b07a2ca84534433d0a1b86cef3288e7d79e8b175a3955848cfd1dfbdcd6b5bafcf6789e56e8ef40af09a764147640eb10b426349f6ffc8e299cdcebffc3a9d6be362ba33fbf648bf06ea4c35890c705df479030fd1d0669d289dcbabaaf78f945c37fc69f3823dbfa99bdf3cf7bb7be8f810a7eab5167e26691642c3982aa203687d0e674154c970cfc1822f9917f2100ae8950cf0fcab074bfb578f4f6e78df490f0fd9becdba7151f2a5733cc2a3df845aa17bdc49765163d635de5c3a1c376683e622fe3e0a6092a35dfedc4bc5bc9c120d2ed06d899775bcd16417318f4b5c7ba27fdc0a442884a69e71543a13cb26762a0df4f47807924a15da7895b6c96accb09394fdf0232d922a99f4a9f95d46da7b9050eb661f3329fe98372175a82d5e5296e4a31c040da6407194251b5baa7338071d1edfc51f55ca409ffd885045e47412f97a4bbe2e73794d8b276ccb446843bbc38c7e580dc4dc2ba94556de0d80681f60d1b2953021e08a60e26685adf61eff91d9ca7daa04a72de9dc2822655648f3c0f5016967b0e8104d70add65b9b9ce98b3aaa10106f5f32133775a71ab9b006307e390b697c77bb828c3ad07bfdcc3ecf3149ac98dc8a230c281365719d67fd2450c717ad1391880d9c17cb8ba96b6254ac783aeae04f84f14829e4efc6ee73b77670cb9ea96dc73e5464bc4cf46cdd2ebe75009d9c4ce6097eab2858ef2899b3dcd147c579939f45c4ad2aa283b6e9c8ca2539abd5e2332cff851f4fa8c4767732d7977",
"bundle": "2b77ff69a6d2f8108250389377faa6cbd42caaefa2f966e1b68a4b3fc022c83e"
},
"metaCreation": {
"seed": "TESTSEED",
"token": "USER",
"sourcePosition": "0123456789abcdeffedcba9876543210fedcba9876543210fedcba9876543210",
"metaType": "TestMeta",
"metaId": "TESTMETA123",
"metadata": {
"name": "Test Metadata",
"description": "This is a test metadata for SDK testing."
}
},
"simpleTransfer": {
"sourceSeed": "TESTSEED",
"recipientSeed": "RECIPIENTSEED",
"balance": 1000,
"amount": 1000,
"token": "TEST",
"sourcePosition": "0123456789abcdeffedcba9876543210fedcba9876543210fedcba9876543210",
"recipientPosition": "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
},
"complexTransfer": {
"sourceSeed": "TESTSEED",
"recipient1Seed": "RECIPIENTSEED",
"recipient2Seed": "RECIPIENT2SEED",
"sourceBalance": 1000,
"amount1": 500,
"amount2": 500,
"token": "TEST",
"sourcePosition": "0123456789abcdeffedcba9876543210fedcba9876543210fedcba9876543210",
"recipient1Position": "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210",
"recipient2Position": "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"
},
"mlkem768": {
"seed": "TESTSEED",
"token": "ENCRYPT",
"position": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
"plaintext": "Hello ML-KEM768 cross-platform test message!"
},
"tokenCreation": {
"sourceSeed": "TESTSEED",
"recipientSeed": "RECIPIENTSEED",
"amount": 1000000,
"sourceToken": "USER",
"newToken": "TESTTOKEN",
"sourcePosition": "0123456789abcdeffedcba9876543210fedcba9876543210fedcba9876543210",
"recipientPosition": "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210",
"meta": {"name": "Test Token", "fungibility": "fungible", "supply": "limited", "decimals": "0"}
},
"walletCreation": {
"sourceSeed": "TESTSEED",
"newWalletSeed": "NEWWALLETSEED",
"sourceToken": "USER",
"newToken": "TESTTOKEN",
"sourcePosition": "0123456789abcdeffedcba9876543210fedcba9876543210fedcba9876543210",
"newWalletPosition": "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
},
"shadowWalletClaim": {
"sourceSeed": "TESTSEED",
"claimSeed": "CLAIMSEED",
"sourceToken": "USER",
"claimToken": "TESTTOKEN",
"sourcePosition": "0123456789abcdeffedcba9876543210fedcba9876543210fedcba9876543210",
"claimPosition": "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
}
}
}
# Support optional external config override via environment variable
config_path = os.environ.get('KNISHIO_TEST_CONFIG')
if config_path and Path(config_path).exists():
try:
with open(config_path, 'r') as f:
return json.load(f)
except Exception as e:
log(f"Failed to load external config from {config_path}: {e}", 'red')
log("Using embedded configuration", 'yellow')
return default_config
def generate_secret(seed: str, length: int = 2048) -> str:
"""Generate deterministic secret from seed"""
return crypto.generate_secret(seed, length)
def generate_bundle_hash(secret: str) -> str:
"""Generate bundle hash from secret"""
return crypto.generate_bundle_hash(secret)
def inspect_molecule(molecule: Molecule, name: str = "molecule"):
"""Debug utility to inspect molecule structure"""
log(f"\n🔍 INSPECTING {name.upper()}:", 'blue')
log(f" Molecular Hash: {molecule.molecularHash or 'NOT_SET'}")
# Check if molecule has secret (private attribute)
secret = getattr(molecule, '_Molecule__secret', None)
log(f" Secret: {'SET (length: ' + str(len(secret)) + ')' if secret else 'NOT_SET'}")
log(f" Bundle: {molecule.bundle or 'NOT_SET'}")
source_wallet = molecule.sourceWallet
log(f" Source Wallet: {source_wallet.address[:16] + '...' if source_wallet and source_wallet.address else 'NOT_SET'}")
remainder_wallet = molecule.remainderWallet if hasattr(molecule, 'remainderWallet') else None
log(f" Remainder Wallet: {remainder_wallet.address[:16] + '...' if remainder_wallet and remainder_wallet.address else 'NOT_SET'}")
log(f" Atoms ({len(molecule.atoms)}):")
total_value = 0
for i, atom in enumerate(molecule.atoms):
value_str = str(atom.value) if atom.value else 'null'
if atom.value and atom.isotope == 'V':
try:
total_value += float(atom.value)
except (ValueError, TypeError):
pass
wallet_snippet = (atom.walletAddress[:16] + '...') if atom.walletAddress else ''
log(f" [{i}] {atom.isotope}: {value_str} ({wallet_snippet}) index={atom.index}")
balance_status = "✅ BALANCED" if abs(total_value) < 0.01 else "❌ UNBALANCED"
log(f" Total Value: {total_value} {balance_status}")
log(f" Cell Slug: {molecule.cellSlug or 'NOT_SET'}")
log(f" Status: {molecule.status or 'NOT_SET'}")
def diagnose_validation(molecule: Molecule, sender_wallet: Optional[Wallet], name: str = "molecule"):
"""Step-by-step validation diagnostic"""
log(f"\n🔬 VALIDATING {name.upper()} STEP-BY-STEP:", 'blue')
log(f" Molecule has {len(molecule.atoms)} atoms")
log(f" First atom isotope: {molecule.atoms[0].isotope if molecule.atoms else 'N/A'}")
log(f" Molecular hash present: {bool(molecule.molecularHash)}")
log(f" Source wallet provided: {bool(sender_wallet)}")
# Check atom indices
for i, atom in enumerate(molecule.atoms):
if atom.index is not None:
log(f" ✅ Atom {i} index: {atom.index}", 'green')
else:
log(f" ❌ Atom {i} index: None", 'red')
# Try basic validation
try:
result = molecule.check(sender_wallet)
log(f" Basic validation result: {result}", 'green' if result else 'red')
except Exception as e:
log(f" Validation exception: {str(e)}", 'red')
def test_crypto(config: Dict) -> bool:
"""Test 1: Crypto Test - Secret generation and bundle hash"""
log('\n1. Crypto Test', 'blue')
test_config = config['tests']['crypto']
try:
# Generate secret from seed
secret = generate_secret(test_config['seed'])
secret_match = secret == test_config['secret']
log_test(f'Secret generation (seed: "{test_config["seed"]}")', secret_match)
if not secret_match:
log(f' Expected: {test_config["secret"][:50]}...', 'yellow')
log(f' Got: {secret[:50]}...', 'yellow')
# Generate bundle hash
bundle = generate_bundle_hash(secret)
bundle_match = bundle == test_config['bundle']
log_test('Bundle hash generation', bundle_match)
if not bundle_match:
log(f' Expected: {test_config["bundle"]}', 'yellow')
log(f' Got: {bundle}', 'yellow')
results['tests']['crypto'] = {
'passed': secret_match and bundle_match,
'secret': secret,
'bundle': bundle,
'expectedSecret': test_config['secret'],
'expectedBundle': test_config['bundle']
}
return secret_match and bundle_match
except Exception as e:
log(f" ❌ ERROR: {str(e)}", 'red')
results['tests']['crypto'] = {
'passed': False,
'error': str(e)
}
return False
def test_metadata_creation(config: Dict) -> bool:
"""Test 2: Metadata Creation Test"""
log('\n2. Metadata Creation Test', 'blue')
test_config = config['tests']['metaCreation']
try:
# Create source wallet
source_secret = generate_secret(test_config['seed'])
source_bundle = generate_bundle_hash(source_secret)
source_wallet = Wallet(
secret=source_secret,
bundle=source_bundle,
token=test_config['token'],
position=test_config['sourcePosition']
)
log_test('Source wallet creation', True)
# Create fixed remainder wallet for deterministic testing
remainder_wallet = create_fixed_remainder_wallet(source_secret, test_config['token'])
# Create molecule for metadata with fixed remainder wallet
molecule = Molecule(
secret=source_secret,
source_wallet=source_wallet,
remainder_wallet=remainder_wallet
)
# Initialize metadata molecule
metadata_dict = test_config['metadata']
molecule.init_meta(
meta=metadata_dict,
meta_type=test_config['metaType'],
meta_id=test_config['metaId']
)
# ContinuID atom is already added by init_meta, no need to add again
log_test('Metadata molecule initialization', True)
# Set fixed timestamps for deterministic testing (before signing)
set_fixed_timestamps(molecule)
# Sign the molecule
molecule.sign()
log_test('Molecule signing', True)
# Debug: Inspect molecule
inspect_molecule(molecule, 'metadata molecule')
# Validation diagnostic
diagnose_validation(molecule, source_wallet, 'metadata molecule')
# Validate the molecule
is_valid = False
validation_error = None
try:
is_valid = molecule.check(source_wallet)
if not is_valid:
validation_error = "Validation returned False (no exception thrown)"
except Exception as e:
is_valid = False
validation_error = str(e)
log_test('Molecule validation', is_valid, validation_error)
# Store serialized molecule for cross-SDK verification using centralized method
results['molecules']['metadata'] = json.dumps(molecule.to_json())
results['tests']['metaCreation'] = {
'passed': is_valid,
'molecularHash': molecule.molecularHash,
'atomCount': len(molecule.atoms),
'validationError': validation_error
}
return is_valid
except Exception as e:
log(f" ❌ ERROR: {str(e)}", 'red')
results['tests']['metaCreation'] = {
'passed': False,
'error': str(e)
}
return False
def test_simple_transfer(config: Dict) -> bool:
"""Test 3: Simple Transfer Test"""
log('\n3. Simple Transfer Test', 'blue')
test_config = config['tests']['simpleTransfer']
try:
# Create source wallet
source_secret = generate_secret(test_config['sourceSeed'])
source_bundle = generate_bundle_hash(source_secret)
source_wallet = Wallet(
secret=source_secret,
bundle=source_bundle,
token=test_config['token'],
position=test_config['sourcePosition']
)
# Set balance manually for testing
source_wallet.balance = test_config['balance']
log_test('Source wallet creation', True)
# Create recipient wallet
recipient_secret = generate_secret(test_config['recipientSeed'])
recipient_wallet = Wallet(
secret=recipient_secret,
token=test_config['token'],
position=test_config['recipientPosition']
)
log_test('Recipient wallet creation', True)
# Create fixed remainder wallet for deterministic testing
remainder_wallet = create_fixed_remainder_wallet(source_secret, test_config['token'])
# Create molecule for value transfer with fixed remainder wallet
molecule = Molecule(
secret=source_secret,
bundle=source_bundle,
source_wallet=source_wallet,
remainder_wallet=remainder_wallet
)
# Initialize value transfer (full balance)
molecule.init_value(
recipient=recipient_wallet,
value=test_config['amount']
)
log_test('Value transfer initialization', True)
# Set fixed timestamps for deterministic testing (before signing)
set_fixed_timestamps(molecule)
# Sign the molecule
molecule.sign()
log_test('Molecule signing', True)
# Debug: Inspect molecule
inspect_molecule(molecule, 'simple transfer molecule')
# Validate the molecule
is_valid = False
validation_error = None
try:
is_valid = molecule.check(source_wallet)
if not is_valid:
validation_error = "Validation returned False (no exception thrown)"
except Exception as e:
is_valid = False
validation_error = str(e)
log_test('Molecule validation', is_valid, validation_error)
# Store serialized molecule using centralized method
results['molecules']['simpleTransfer'] = json.dumps(molecule.to_json())
results['tests']['simpleTransfer'] = {
'passed': is_valid,
'molecularHash': molecule.molecularHash,
'atomCount': len(molecule.atoms),
'validationError': validation_error
}
return is_valid
except Exception as e:
log(f" ❌ ERROR: {str(e)}", 'red')
results['tests']['simpleTransfer'] = {
'passed': False,
'error': str(e)
}
return False
def test_complex_transfer(config: Dict) -> bool:
"""Test 4: Complex Transfer Test"""
log('\n4. Complex Transfer Test', 'blue')
test_config = config['tests']['complexTransfer']
try:
# Create source wallet
source_secret = generate_secret(test_config['sourceSeed'])
source_bundle = generate_bundle_hash(source_secret)
source_wallet = Wallet(
secret=source_secret,
bundle=source_bundle,
token=test_config['token'],
position=test_config['sourcePosition']
)
# Set balance manually
source_wallet.balance = test_config['sourceBalance']
log_test('Source wallet creation', True)
# Create fixed remainder wallet for deterministic testing
remainder_wallet = create_fixed_remainder_wallet(source_secret, test_config['token'])
log_test('Remainder wallet creation', True)
# Create first recipient wallet
recipient_secret = generate_secret(test_config['recipient1Seed'])
recipient_wallet = Wallet(
secret=recipient_secret,
token=test_config['token'],
position=test_config['recipient1Position']
)
log_test('Recipient wallet creation', True)
# Create molecule with remainder wallet
molecule = Molecule(
secret=source_secret,
bundle=source_bundle,
source_wallet=source_wallet,
remainder_wallet=remainder_wallet
)
# Initialize value transfer with remainder (sending amount1 to recipient)
molecule.init_value(
recipient=recipient_wallet,
value=test_config['amount1']
)
log_test('Value transfer with remainder initialization', True)
# Set fixed timestamps for deterministic testing (before signing)
set_fixed_timestamps(molecule)
# Sign the molecule
molecule.sign()
log_test('Molecule signing', True)
# Debug: Inspect molecule
inspect_molecule(molecule, 'complex transfer molecule')
# Step-by-step validation diagnostic
diagnose_validation(molecule, source_wallet, 'complex transfer molecule')
# Validate the molecule
is_valid = False
validation_error = None
try:
is_valid = molecule.check(source_wallet)
if not is_valid:
validation_error = "Validation returned False (no exception thrown)"
except Exception as e:
is_valid = False
validation_error = str(e)
log_test('Molecule validation', is_valid, validation_error)
# Store serialized molecule using centralized method
results['molecules']['complexTransfer'] = json.dumps(molecule.to_json())
results['tests']['complexTransfer'] = {
'passed': is_valid,
'molecularHash': molecule.molecularHash,
'atomCount': len(molecule.atoms),
'hasRemainder': True,
'validationError': validation_error
}
return is_valid
except Exception as e:
log(f" ❌ ERROR: {str(e)}", 'red')
results['tests']['complexTransfer'] = {
'passed': False,
'error': str(e)
}
return False
def test_token_creation(config: Dict) -> bool:
"""Test C1: Token Creation Test (cross-SDK parity with JS)"""
log('\nC1. Token Creation Test', 'blue')
test_config = config['tests']['tokenCreation']
try:
# Create source wallet (USER token)
source_secret = generate_secret(test_config['sourceSeed'])
source_bundle = generate_bundle_hash(source_secret)
source_wallet = Wallet(
secret=source_secret,
bundle=source_bundle,
token=test_config['sourceToken'],
position=test_config['sourcePosition']
)
log_test('Source wallet creation', True)
# Create recipient wallet for the new token
recipient_secret = generate_secret(test_config['recipientSeed'])
recipient_wallet = Wallet(
secret=recipient_secret,
token=test_config['newToken'],
position=test_config['recipientPosition']
)
log_test('Recipient wallet creation', True)
# USER-token remainder so add_continue_id_atom's guard keeps the canonical bbbb... wallet
remainder_wallet = create_fixed_remainder_wallet(source_secret, test_config['sourceToken'])
log_test('Remainder wallet creation', True)
molecule = Molecule(
secret=source_secret,
bundle=source_bundle,
source_wallet=source_wallet,
remainder_wallet=remainder_wallet
)
molecule.init_token_creation(
recipient=recipient_wallet,
amount=test_config['amount'],
token_meta=test_config['meta']
)
log_test('Token creation initialization', True)
# Set fixed timestamps for deterministic testing (before signing)
set_fixed_timestamps(molecule)
molecule.sign()
log_test('Molecule signing', True)
inspect_molecule(molecule, 'token creation molecule')
is_valid = False
validation_error = None
try:
is_valid = molecule.check(source_wallet)
if not is_valid:
validation_error = "Validation returned False (no exception thrown)"
except Exception as e:
is_valid = False
validation_error = str(e)
log_test('Molecule validation', is_valid, validation_error)
# Store serialized molecule using centralized method
results['molecules']['tokenCreation'] = json.dumps(molecule.to_json())
results['tests']['tokenCreation'] = {
'passed': is_valid,
'molecularHash': molecule.molecularHash,
'atomCount': len(molecule.atoms),
'validationError': validation_error
}
return is_valid
except Exception as e:
log(f" ❌ ERROR: {str(e)}", 'red')
results['tests']['tokenCreation'] = {
'passed': False,
'error': str(e)
}
return False
def test_wallet_creation(config: Dict) -> bool:
"""Test C2: Wallet Creation Test (cross-SDK parity with JS)"""
log('\nC2. Wallet Creation Test', 'blue')
test_config = config['tests']['walletCreation']
try:
source_secret = generate_secret(test_config['sourceSeed'])
source_bundle = generate_bundle_hash(source_secret)
source_wallet = Wallet(
secret=source_secret,
bundle=source_bundle,
token=test_config['sourceToken'],
position=test_config['sourcePosition']
)
log_test('Source wallet creation', True)
new_wallet = Wallet(
secret=generate_secret(test_config['newWalletSeed']),
token=test_config['newToken'],
position=test_config['newWalletPosition']
)
log_test('New wallet creation', True)
remainder_wallet = create_fixed_remainder_wallet(source_secret, test_config['sourceToken'])
log_test('Remainder wallet creation', True)
molecule = Molecule(
secret=source_secret,
bundle=source_bundle,
source_wallet=source_wallet,
remainder_wallet=remainder_wallet
)
molecule.init_wallet_creation(new_wallet)
log_test('Wallet creation initialization', True)
set_fixed_timestamps(molecule)
molecule.sign()
log_test('Molecule signing', True)
inspect_molecule(molecule, 'wallet creation molecule')
is_valid = False
validation_error = None
try:
is_valid = molecule.check(source_wallet)
if not is_valid:
validation_error = "Validation returned False (no exception thrown)"
except Exception as e:
is_valid = False
validation_error = str(e)
log_test('Molecule validation', is_valid, validation_error)
results['molecules']['walletCreation'] = json.dumps(molecule.to_json())
results['tests']['walletCreation'] = {
'passed': is_valid,
'molecularHash': molecule.molecularHash,
'atomCount': len(molecule.atoms),
'validationError': validation_error
}
return is_valid
except Exception as e:
log(f" ❌ ERROR: {str(e)}", 'red')
results['tests']['walletCreation'] = {'passed': False, 'error': str(e)}
return False
def test_shadow_wallet_claim(config: Dict) -> bool:
"""Test C3: Shadow Wallet Claim Test (cross-SDK parity with JS)"""
log('\nC3. Shadow Wallet Claim Test', 'blue')
test_config = config['tests']['shadowWalletClaim']
try:
source_secret = generate_secret(test_config['sourceSeed'])
source_bundle = generate_bundle_hash(source_secret)
source_wallet = Wallet(
secret=source_secret,
bundle=source_bundle,
token=test_config['sourceToken'],
position=test_config['sourcePosition']
)
log_test('Source wallet creation', True)
claim_wallet = Wallet(
secret=generate_secret(test_config['claimSeed']),
token=test_config['claimToken'],
position=test_config['claimPosition']
)
log_test('Claim wallet creation', True)
remainder_wallet = create_fixed_remainder_wallet(source_secret, test_config['sourceToken'])
log_test('Remainder wallet creation', True)
molecule = Molecule(
secret=source_secret,
bundle=source_bundle,
source_wallet=source_wallet,
remainder_wallet=remainder_wallet
)
molecule.init_shadow_wallet_claim(claim_wallet)
log_test('Shadow wallet claim initialization', True)
set_fixed_timestamps(molecule)
molecule.sign()
log_test('Molecule signing', True)
inspect_molecule(molecule, 'shadow wallet claim molecule')
is_valid = False
validation_error = None
try:
is_valid = molecule.check(source_wallet)
if not is_valid:
validation_error = "Validation returned False (no exception thrown)"
except Exception as e:
is_valid = False
validation_error = str(e)
log_test('Molecule validation', is_valid, validation_error)
results['molecules']['shadowWalletClaim'] = json.dumps(molecule.to_json())
results['tests']['shadowWalletClaim'] = {
'passed': is_valid,
'molecularHash': molecule.molecularHash,
'atomCount': len(molecule.atoms),
'validationError': validation_error
}
return is_valid
except Exception as e:
log(f" ❌ ERROR: {str(e)}", 'red')
results['tests']['shadowWalletClaim'] = {'passed': False, 'error': str(e)}
return False
def find_canonical_vectors_path() -> Optional[Path]:
"""Locate canonical-patent-vectors.json: env override, SDK-vendored fixture, or shared-results dir."""
candidates = []
env_path = os.environ.get('KNISHIO_CANONICAL_VECTORS')
if env_path:
candidates.append(Path(env_path))
candidates.append(Path(os.path.dirname(__file__)) / 'tests' / 'fixtures' / 'canonical-patent-vectors.json')
shared_dir = os.environ.get('KNISHIO_SHARED_RESULTS')
if shared_dir:
candidates.append(Path(shared_dir).resolve() / 'canonical-patent-vectors.json')
for candidate in candidates:
if candidate.exists():
return candidate
return None
def test_buffer_family() -> bool:
"""Test B1: Buffer Family Test (deposit + withdraw, vector-driven)
B-isotope builders (init_deposit_buffer / init_withdraw_buffer) validated against the shared
canonical-patent-vectors.json, matching the other SDKs (JS/TS/PHP/Kotlin/Rust/C++). For each
buffer_deposit_conservation / buffer_withdraw_conservation case we build + sign the molecule and
assert: atom shape/values match the vector, the V+B sum == 0 (full-balance debit conserves even for
a PARTIAL op), AND molecule.check() accepts the molecule. Molecular hashes are NOT frozen (random
positions). Reads the vendored fixture; SKIPS if absent (standalone CI); FAILS if absent AND
KNISHIO_REQUIRE_VECTORS=true (an orchestrated cross-SDK run must not silently skip parity coverage).
"""
log('\nB1. Buffer Family Test (deposit + withdraw, vector-driven)', 'blue')
vectors_path = find_canonical_vectors_path()
if vectors_path is None:
must_have = os.environ.get('KNISHIO_REQUIRE_VECTORS') == 'true'
results['tests']['bufferFamily'] = {
'passed': False,
'skipped': not must_have,
'molecularHash': None,
'atomCount': 0,
'validationError': 'canonical-patent-vectors.json absent'
}
if must_have:
log(' FAILED: canonical-patent-vectors.json absent (KNISHIO_REQUIRE_VECTORS=true)', 'red')
return False
log(' SKIPPED: canonical-patent-vectors.json absent (standalone CI)', 'yellow')
return True # skip, not fail — recorded as skipped, never counted as a pass
try:
with open(vectors_path, 'r') as f:
vectors = json.load(f)['vectors']
secret = generate_secret('buffer-family-self-test-seed')
token = 'BUFTOK'
all_pass = True
last_hash = None
atom_total = 0
# ---- DEPOSIT: V (source -balance) -> B (buffer +amount) -> V (remainder +(balance-amount)) ----
for tv in vectors['buffer_deposit_conservation']['tests']:
source = Wallet.create(secret=secret, token=token)
source.balance = tv['sourceBalance']
molecule = Molecule(secret=secret, bundle=source.bundle, source_wallet=source)
molecule.init_deposit_buffer(tv['amount'], {})
set_fixed_timestamps(molecule)
molecule.sign()
total = sum(int(a.value) for a in molecule.atoms if a.isotope in ('V', 'B'))
shape = (
len(molecule.atoms) == 3
and molecule.atoms[0].isotope == 'V' and molecule.atoms[0].value == tv['expectedSourceValue']
and molecule.atoms[1].isotope == 'B' and molecule.atoms[1].value == tv['expectedBufferValue']
and molecule.atoms[2].isotope == 'V' and molecule.atoms[2].value == tv['expectedRemainderValue']
)
ok = shape and str(total) == tv['expectedSum']
if ok:
try:
ok = molecule.check(source)
except Exception as e:
ok = False
log(f" check() error: {str(e)}", 'red')
log_test(f"deposit {tv['name']} conserves (V+B sum 0; cross-isotope bypass)", ok)
all_pass = all_pass and ok
last_hash = molecule.molecularHash
atom_total += len(molecule.atoms)
# ---- WITHDRAW: B (source -balance) -> V (recipient +amount) -> B (remainder +(balance-amount)) ----
for tv in vectors['buffer_withdraw_conservation']['tests']:
source = Wallet.create(secret=secret, token=token)
source.balance = tv['sourceBalance']
molecule = Molecule(secret=secret, bundle=source.bundle, source_wallet=source)
# Withdraw to the caller's own bundle (single recipient), mirroring the client wrapper.
molecule.init_withdraw_buffer({source.bundle: tv['amount']})
set_fixed_timestamps(molecule)
molecule.sign()
total = sum(int(a.value) for a in molecule.atoms if a.isotope in ('V', 'B'))
shape = (
len(molecule.atoms) == 3
and molecule.atoms[0].isotope == 'B' and molecule.atoms[0].value == tv['expectedSourceValue']
and molecule.atoms[1].isotope == 'V' and molecule.atoms[1].value == tv['expectedRecipientValue']
and molecule.atoms[2].isotope == 'B' and molecule.atoms[2].value == tv['expectedRemainderValue']
)
ok = shape and str(total) == tv['expectedSum']
if ok:
try:
ok = molecule.check(source)
except Exception as e:
ok = False
log(f" check() error: {str(e)}", 'red')
log_test(f"withdraw {tv['name']} conserves (B+V sum 0; cross-isotope bypass)", ok)
all_pass = all_pass and ok
last_hash = molecule.molecularHash
atom_total += len(molecule.atoms)
# ---- NEGATIVE: molecules that must be REJECTED (buffer_conservation_negative) ----
# The two loops above only prove VALID molecules are ACCEPTED; that gap concealed a
# live fail-open defect in Kotlin (V-only conservation gated on B/F presence with no
# isotopeB/isotopeF to own it). Build a VALID molecule with the SDK's own builder,
# apply the vector's single tamper mutation, re-sign, and assert rejection. Absent key
# (older fixture) is handled like the absent-fixture case above: simply no-op, not a crash.
for tv in vectors.get('buffer_conservation_negative', {}).get('tests', []):
source = Wallet.create(secret=secret, token=token)
source.balance = tv['sourceBalance']
molecule = Molecule(secret=secret, bundle=source.bundle, source_wallet=source)
build_from = tv['buildFrom']
if build_from == 'deposit':
molecule.init_deposit_buffer(tv['amount'], {})
elif build_from == 'withdraw':
molecule.init_withdraw_buffer({source.bundle: tv['amount']})
else:
raise ValueError(f"unknown buildFrom '{build_from}' in buffer_conservation_negative")
# Tamper target selects the first/last atom of that isotope in emission order;
# molecule.atoms is still in append order here (pre-sign, pre-sort).
tamper = tv['tamper']
isotope = tamper['target'][-1] # 'firstV'/'lastV' -> 'V'; 'firstB'/'lastB' -> 'B'
matches = [a for a in molecule.atoms if a.isotope == isotope]
target_atom = matches[0] if tamper['target'].startswith('first') else matches[-1]
setattr(target_atom, tamper['field'], tamper['to'])
set_fixed_timestamps(molecule)
molecule.sign()
rejected = False
reject_reason = None
try:
molecule.check(source)
except Exception as e:
rejected = True
reject_reason = f"{type(e).__name__}: {str(e)}"
log_test(f"{tv['name']} rejected ({tv['reason']})", rejected,
None if rejected else 'molecule was NOT rejected')
if rejected:
log(f" rejected via {reject_reason}", 'cyan')
all_pass = all_pass and rejected
last_hash = molecule.molecularHash
atom_total += len(molecule.atoms)
results['tests']['bufferFamily'] = {
'passed': all_pass,
'skipped': False,
'molecularHash': last_hash,
'atomCount': atom_total,
'validationError': None if all_pass else 'buffer family vector validation failed'
}
return all_pass
except Exception as e:
log(f" ❌ ERROR: {str(e)}", 'red')
results['tests']['bufferFamily'] = {
'passed': False,
'skipped': False,
'molecularHash': None,
'atomCount': 0,
'validationError': str(e)
}
return False
def test_mlkem768(config: Dict) -> bool:
"""Test 5: ML-KEM768 Encryption Test"""
log('\n5. ML-KEM768 Encryption Test', 'blue')
test_config = config['tests']['mlkem768']
try:
# Create encryption wallet from seed