-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_server.py
More file actions
1682 lines (1356 loc) · 76.7 KB
/
Copy pathtest_server.py
File metadata and controls
1682 lines (1356 loc) · 76.7 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
from __future__ import annotations
import importlib.metadata
import json
import shutil
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any
from stellar_sdk import Account, Address, Asset, Keypair, Network, StrKey, TransactionBuilder, xdr
from stellar_sdk.utils import sha256
from stellar_sdk.xdr.sc_val_type import SCValType
from komet_node.__main__ import build_server
from komet_node.scval import scval_from_json
from .conftest import (
PASSPHRASE,
_is_hex64,
_is_int_string,
_is_number,
_post,
_post_raw,
_rpc,
contract_address_from_deployer,
deploy_and_get_invoker,
deploy_contract,
fund_account,
make_invoker,
send_tx,
wat_to_wasm,
)
if TYPE_CHECKING:
from stellar_sdk import TransactionEnvelope
from komet_node.server import StellarRpcServer
EMPTY_CONTRACT_WAT = (Path(__file__).parent / 'data' / 'wasm' / 'empty.wat').resolve(strict=True)
ARGS_CONTRACT_WAT = (Path(__file__).parent / 'data' / 'wasm' / 'args.wat').resolve(strict=True)
ADDER_CONTRACT_WAT = (Path(__file__).parent / 'data' / 'wasm' / 'adder.wat').resolve(strict=True)
BYTES_CONTRACT_WAT = (Path(__file__).parent / 'data' / 'wasm' / 'bytes.wat').resolve(strict=True)
STORAGE_CONTRACT_WAT = (Path(__file__).parent / 'data' / 'wasm' / 'storage.wat').resolve(strict=True)
def _assert_ledger_bounds(result: dict[str, Any]) -> None:
"""Check the latest/oldest ledger-range fields required on every getTransaction response."""
assert _is_number(result['latestLedger'])
assert _is_int_string(result['latestLedgerCloseTime'])
assert _is_number(result['oldestLedger'])
assert _is_int_string(result['oldestLedgerCloseTime'])
assert result['oldestLedger'] <= result['latestLedger']
# The full field surface of GetTransactionResponse (Go struct, v22 + optional v23 extras).
_GET_TRANSACTION_KEYS = {
'status',
'txHash',
'applicationOrder',
'feeBump',
'envelopeXdr',
'resultXdr',
'resultMetaXdr',
'diagnosticEventsXdr',
'events',
'ledger',
'createdAt',
'latestLedger',
'latestLedgerCloseTime',
'oldestLedger',
'oldestLedgerCloseTime',
}
def _create_account_xdr(keypair: Keypair, account: Account) -> str:
"""Build and sign a minimal create-account transaction, returned as base64 XDR."""
envelope = (
TransactionBuilder(account, Network.TESTNET_NETWORK_PASSPHRASE)
.append_create_account_op(destination=keypair.public_key, starting_balance='1000')
.set_timeout(30)
.build()
)
envelope.sign(keypair)
return envelope.to_xdr()
def test_default_io_dir_is_a_fresh_temp_dir() -> None:
"""With no io_dir, the composition root provisions a fresh temporary directory and seeds it."""
srv = build_server(port=0)
try:
assert srv.io_dir.exists()
assert srv.io_dir.resolve() != Path.cwd()
assert srv.state_file == srv.io_dir / 'state.kore'
assert srv.state_file.exists()
assert (srv.io_dir / 'metadata.json').exists()
# The per-item artifact directories are created up front (the K hooks won't).
assert (srv.io_dir / 'receipts').is_dir()
assert (srv.io_dir / 'traces').is_dir()
assert (srv.io_dir / 'requests').is_dir()
finally:
shutil.rmtree(srv.io_dir, ignore_errors=True)
def test_get_health(server: StellarRpcServer) -> None:
"""getHealth returns the spec shape: status plus the ledger range, all sequences as numbers."""
result = _rpc(server.port(), 'getHealth', {})['result']
assert result['status'] == 'healthy'
assert _is_number(result['latestLedger'])
assert _is_number(result['oldestLedger'])
assert _is_number(result['ledgerRetentionWindow'])
assert result['oldestLedger'] <= result['latestLedger']
assert result['ledgerRetentionWindow'] >= 1
# The close-time fields are always emitted by real stellar-rpc but are not part of this
# node's required surface; when present they must use the int64-as-string encoding.
for key in ('latestLedgerCloseTime', 'oldestLedgerCloseTime'):
if key in result:
assert _is_int_string(result[key])
assert set(result) <= {
'status',
'latestLedger',
'latestLedgerCloseTime',
'oldestLedger',
'oldestLedgerCloseTime',
'ledgerRetentionWindow',
}
def test_get_network(server: StellarRpcServer) -> None:
"""getNetwork: protocolVersion is a JSON number; friendbotUrl is omitted (no friendbot here)."""
result = _rpc(server.port(), 'getNetwork', {})['result']
assert result['passphrase'] == Network.TESTNET_NETWORK_PASSPHRASE
assert _is_number(result['protocolVersion'])
assert result['protocolVersion'] == 22
# friendbotUrl is `omitempty` in real stellar-rpc: unset means absent, not null.
assert 'friendbotUrl' not in result
assert set(result) == {'passphrase', 'protocolVersion'}
def test_get_latest_ledger_initial(server: StellarRpcServer) -> None:
"""getLatestLedger on a fresh chain: sequence 0, protocolVersion as number, 64-hex id."""
result = _rpc(server.port(), 'getLatestLedger', {})['result']
assert result['sequence'] == 0
assert _is_number(result['sequence'])
assert _is_number(result['protocolVersion'])
assert result['protocolVersion'] == 22
assert _is_hex64(result['id'])
# closeTime/headerXdr/metadataXdr are protocol-23 extras; when present, closeTime uses
# the int64-as-string encoding.
if 'closeTime' in result:
assert _is_int_string(result['closeTime'])
assert set(result) <= {'id', 'protocolVersion', 'sequence', 'closeTime', 'headerXdr', 'metadataXdr'}
def test_get_latest_ledger_id_changes_per_ledger(server: StellarRpcServer) -> None:
"""The ledger id is not a constant: each ledger reports its own hash."""
keypair = Keypair.random()
account = Account(keypair.public_key, sequence=0)
first = _rpc(server.port(), 'getLatestLedger', {})['result']
_rpc(server.port(), 'sendTransaction', {'transaction': _create_account_xdr(keypair, account)})
second = _rpc(server.port(), 'getLatestLedger', {})['result']
assert second['sequence'] == first['sequence'] + 1
assert _is_hex64(first['id'])
assert _is_hex64(second['id'])
assert first['id'] != second['id']
def test_get_transaction_not_found(server: StellarRpcServer) -> None:
"""A NOT_FOUND response still carries the full ledger range, with spec-conformant types."""
result = _rpc(server.port(), 'getTransaction', {'hash': '0' * 64})['result']
assert result['status'] == 'NOT_FOUND'
_assert_ledger_bounds(result)
assert set(result) <= _GET_TRANSACTION_KEYS
def test_get_transaction_malformed_hash_returns_invalid_params(server: StellarRpcServer) -> None:
"""The hash param must be a 64-character hex string; anything else is Invalid params."""
for bad_hash in ('deadbeef', '0' * 63, '0' * 65, 'x' * 64, '0' * 63 + 'g'):
response = _rpc(server.port(), 'getTransaction', {'hash': bad_hash})
assert 'result' not in response, f'expected an error for hash {bad_hash!r}'
assert response['error']['code'] == -32602, f'hash {bad_hash!r}'
def test_unknown_method_returns_method_not_found(server: StellarRpcServer) -> None:
result = _rpc(server.port(), 'noSuchMethod', {})
assert result['error']['code'] == -32601
def test_k_unknown_method_fallback_returns_method_not_found(server: StellarRpcServer) -> None:
"""The K semantics' own unknown-method fallback answers with JSON-RPC error -32601.
The Python layer filters unknown methods before they reach K, so this drives the
interpreter directly with an envelope for a method the semantics do not implement.
The fallback must produce an error response, not ``result: null``.
"""
envelope = {'method': 'noSuchMethod', 'id': 7, 'now': str(int(time.time()))}
raw = server.interpreter.run(server.state_file, server.io_dir, envelope, None)
assert raw is not None
response = json.loads(raw)
assert 'result' not in response
assert response['error']['code'] == -32601
assert response['id'] == 7
def test_send_transaction_missing_params_returns_invalid_params(server: StellarRpcServer) -> None:
result = _rpc(server.port(), 'sendTransaction', {})
assert result['error']['code'] == -32602
def test_send_transaction_bad_xdr_returns_invalid_params(server: StellarRpcServer) -> None:
result = _rpc(server.port(), 'sendTransaction', {'transaction': 'not-valid-xdr'})
assert result['error']['code'] == -32602
def test_get_transaction_missing_hash_returns_invalid_params(server: StellarRpcServer) -> None:
result = _rpc(server.port(), 'getTransaction', {})
assert result['error']['code'] == -32602
def test_malformed_body_returns_parse_error(server: StellarRpcServer) -> None:
result = _post(server.port(), b'{ this is not json')
assert result['error']['code'] == -32700
def test_non_object_frame_returns_invalid_request(server: StellarRpcServer) -> None:
result = _post(server.port(), b'"just a string"')
assert result['error']['code'] == -32600
def test_missing_method_returns_invalid_request(server: StellarRpcServer) -> None:
result = _post(server.port(), b'{"jsonrpc": "2.0", "id": 1}')
assert result['error']['code'] == -32600
def test_non_string_method_returns_invalid_request(server: StellarRpcServer) -> None:
result = _post(server.port(), b'{"jsonrpc": "2.0", "id": 1, "method": 123}')
assert result['error']['code'] == -32600
def test_wrong_jsonrpc_version_returns_invalid_request(server: StellarRpcServer) -> None:
result = _post(server.port(), b'{"jsonrpc": "1.0", "id": 1, "method": "getHealth"}')
assert result['error']['code'] == -32600
def test_non_object_params_returns_invalid_params(server: StellarRpcServer) -> None:
result = _post(server.port(), b'{"jsonrpc": "2.0", "id": 1, "method": "getHealth", "params": "oops"}')
assert result['error']['code'] == -32602
def test_send_transaction_and_get_result(server: StellarRpcServer) -> None:
"""Send a CreateAccount transaction through the HTTP server and poll for the result.
Asserts the exact spec shape of both responses: ledger sequences are JSON numbers,
close times are string-encoded int64s, and the receipt carries the transaction details
required for a SUCCESS status (ledger, createdAt, applicationOrder, feeBump).
"""
keypair = Keypair.random()
account = Account(keypair.public_key, sequence=0)
xdr_str = _create_account_xdr(keypair, account)
# sendTransaction returns PENDING for a fresh transaction
send_result = _rpc(server.port(), 'sendTransaction', {'transaction': xdr_str})['result']
assert send_result['status'] == 'PENDING'
assert _is_hex64(send_result['hash'])
assert _is_number(send_result['latestLedger'])
assert _is_int_string(send_result['latestLedgerCloseTime'])
assert set(send_result) == {'hash', 'status', 'latestLedger', 'latestLedgerCloseTime'}
tx_hash = send_result['hash']
# since the interpreter runs synchronously, the result is already stored
get_result = _rpc(server.port(), 'getTransaction', {'hash': tx_hash})['result']
assert get_result['status'] == 'SUCCESS'
assert get_result['envelopeXdr'] == xdr_str
_assert_ledger_bounds(get_result)
assert _is_number(get_result['ledger'])
assert get_result['ledger'] == 1
# createdAt is a string on getTransaction (singular) — a known quirk of real stellar-rpc.
assert _is_int_string(get_result['createdAt'])
assert _is_number(get_result['applicationOrder'])
assert get_result['applicationOrder'] == 1
assert get_result['feeBump'] is False
assert set(get_result) <= _GET_TRANSACTION_KEYS
def test_send_transaction_unsupported_operation_returns_error_status(server: StellarRpcServer) -> None:
"""A transaction that decodes but cannot be processed is rejected with status ERROR.
Mirrors real stellar-rpc's admission-time rejection: the response carries a txMALFORMED
TransactionResult in errorResultXdr, the transaction never reaches the ledger (no
receipt, no ledger bump), and getTransaction stays NOT_FOUND.
"""
keypair = Keypair.random()
account = Account(keypair.public_key, sequence=0)
envelope = (
TransactionBuilder(account, Network.TESTNET_NETWORK_PASSPHRASE)
.append_payment_op(destination=Keypair.random().public_key, asset=Asset.native(), amount='1')
.set_timeout(30)
.build()
)
envelope.sign(keypair)
result = _rpc(server.port(), 'sendTransaction', {'transaction': envelope.to_xdr()})['result']
assert result['status'] == 'ERROR'
assert result['hash'] == envelope.hash_hex()
assert _is_number(result['latestLedger'])
assert _is_int_string(result['latestLedgerCloseTime'])
assert set(result) == {'hash', 'status', 'errorResultXdr', 'latestLedger', 'latestLedgerCloseTime'}
tx_result = xdr.TransactionResult.from_xdr(result['errorResultXdr'])
assert tx_result.result.code == xdr.TransactionResultCode.txMALFORMED
assert tx_result.fee_charged.int64 == 0
# The rejected transaction never reached the ledger.
assert _rpc(server.port(), 'getLatestLedger', {})['result']['sequence'] == 0
get_result = _rpc(server.port(), 'getTransaction', {'hash': envelope.hash_hex()})['result']
assert get_result['status'] == 'NOT_FOUND'
def test_send_transaction_duplicate_is_not_reexecuted(server: StellarRpcServer) -> None:
"""Resubmitting an already-executed transaction returns DUPLICATE and leaves the chain alone."""
keypair = Keypair.random()
account = Account(keypair.public_key, sequence=0)
xdr_str = _create_account_xdr(keypair, account)
first = _rpc(server.port(), 'sendTransaction', {'transaction': xdr_str})['result']
assert first['status'] == 'PENDING'
assert _rpc(server.port(), 'getLatestLedger', {})['result']['sequence'] == 1
second = _rpc(server.port(), 'sendTransaction', {'transaction': xdr_str})['result']
assert second['status'] == 'DUPLICATE'
assert second['hash'] == first['hash']
assert _is_number(second['latestLedger'])
assert _is_int_string(second['latestLedgerCloseTime'])
assert set(second) == {'hash', 'status', 'latestLedger', 'latestLedgerCloseTime'}
# The duplicate was not re-executed: the ledger did not advance and the original
# SUCCESS receipt is untouched.
assert _rpc(server.port(), 'getLatestLedger', {})['result']['sequence'] == 1
get_result = _rpc(server.port(), 'getTransaction', {'hash': first['hash']})['result']
assert get_result['status'] == 'SUCCESS'
assert get_result['ledger'] == 1
def test_io_dir_splits_into_per_item_files(server: StellarRpcServer) -> None:
"""Each receipt, trace, and request lands in its own file; there is no transactions.json."""
keypair = Keypair.random()
account = Account(keypair.public_key, sequence=0)
envelope = (
TransactionBuilder(account, Network.TESTNET_NETWORK_PASSPHRASE)
.append_create_account_op(destination=keypair.public_key, starting_balance='1000')
.set_timeout(30)
.build()
)
envelope.sign(keypair)
# sendTransaction is the first RPC call in this test, so it is archived as request_0.json.
tx_hash = _rpc(server.port(), 'sendTransaction', {'transaction': envelope.to_xdr()})['result']['hash']
assert (server.io_dir / 'receipts' / f'receipt_{tx_hash}.json').exists()
assert (server.io_dir / 'traces' / f'trace_{tx_hash}.jsonl').exists()
assert not (server.io_dir / 'transactions.json').exists()
# Each incoming request is archived under its own monotonic index.
assert (server.io_dir / 'requests' / 'request_0.json').exists()
_rpc(server.port(), 'getTransaction', {'hash': tx_hash})
assert (server.io_dir / 'requests' / 'request_1.json').exists()
def test_failed_transaction_records_failed_receipt(server: StellarRpcServer) -> None:
"""A transaction that gets stuck in the semantics is recorded as FAILED in Python.
Invoking a contract that was never deployed traps in the semantics, so no response.json
is produced and the server synthesises the FAILED receipt (the _failure_response path).
"""
keypair = Keypair.random()
account = Account(keypair.public_key, sequence=0)
missing_contract = StrKey.encode_contract(b'\x11' * 32) # valid C-strkey, never deployed
envelope = (
TransactionBuilder(account, Network.TESTNET_NETWORK_PASSPHRASE)
.append_invoke_contract_function_op(missing_contract, 'foo', [])
.set_timeout(30)
.build()
)
envelope.sign(keypair)
xdr_str = envelope.to_xdr()
# sendTransaction still returns PENDING, even though the tx will fail. The response
# keeps the spec types: latestLedger a number, latestLedgerCloseTime a string.
send_result = _rpc(server.port(), 'sendTransaction', {'transaction': xdr_str})['result']
assert send_result['status'] == 'PENDING'
assert _is_number(send_result['latestLedger'])
assert _is_int_string(send_result['latestLedgerCloseTime'])
tx_hash = send_result['hash']
# The synthesised receipt is FAILED and echoes the envelope; the ledger-range fields
# are required for every status, and any transaction details keep the spec types.
get_result = _rpc(server.port(), 'getTransaction', {'hash': tx_hash})['result']
assert get_result['status'] == 'FAILED'
assert get_result['envelopeXdr'] == xdr_str
_assert_ledger_bounds(get_result)
if 'ledger' in get_result:
assert _is_number(get_result['ledger'])
if 'createdAt' in get_result:
assert _is_int_string(get_result['createdAt'])
assert set(get_result) <= _GET_TRANSACTION_KEYS
# A failed transaction must not advance the ledger.
assert _rpc(server.port(), 'getLatestLedger', {})['result']['sequence'] == 0
def test_ledger_seq_increments(server: StellarRpcServer) -> None:
"""The ledger sequence increments by 1 for each successful transaction."""
keypair = Keypair.random()
account = Account(keypair.public_key, sequence=0)
def send_create_account() -> None:
tb = TransactionBuilder(account, PASSPHRASE).append_create_account_op(
destination=keypair.public_key, starting_balance='1000'
)
send_tx(server, keypair, tb)
send_create_account()
assert _rpc(server.port(), 'getLatestLedger', {})['result']['sequence'] == 1
send_create_account()
assert _rpc(server.port(), 'getLatestLedger', {})['result']['sequence'] == 2
def test_full_lifecycle_over_http(server: StellarRpcServer) -> None:
"""Full contract lifecycle through the HTTP server: account → upload → deploy → invoke.
Each step asserts SUCCESS inside the shared helpers; this is the end-to-end smoke test
that the whole pipeline works over HTTP, independent of any trace/return-value assertions.
"""
invoke = deploy_and_get_invoker(server, EMPTY_CONTRACT_WAT)
invoke('foo')
def test_trace_transaction_retrieves_trace_by_hash(server: StellarRpcServer) -> None:
"""traceTransaction returns the trace of a previously submitted transaction, keyed by hash."""
keypair = Keypair.random()
account = Account(keypair.public_key, sequence=0)
envelope = (
TransactionBuilder(account, Network.TESTNET_NETWORK_PASSPHRASE)
.append_create_account_op(destination=keypair.public_key, starting_balance='1000')
.set_timeout(30)
.build()
)
envelope.sign(keypair)
send_result = _rpc(server.port(), 'sendTransaction', {'transaction': envelope.to_xdr()})['result']
assert send_result['status'] == 'PENDING'
# The trace is keyed by the same hash getTransaction uses. A create-account op runs no
# wasm instructions, so the stored trace is an empty array (resolved, not null/NOT_FOUND).
trace = _rpc(server.port(), 'traceTransaction', {'hash': send_result['hash']})['result']
assert trace == []
def test_trace_transaction_unknown_hash_returns_null(server: StellarRpcServer) -> None:
"""traceTransaction returns null when no transaction with that hash exists.
Uses a well-formed (64-hex) hash so this stays a lookup-miss test regardless of any
hash-format validation on the shared hash parameter.
"""
result = _rpc(server.port(), 'traceTransaction', {'hash': 'ab' * 32})['result']
assert result is None
def test_trace_transaction_missing_hash_returns_invalid_params(server: StellarRpcServer) -> None:
result = _rpc(server.port(), 'traceTransaction', {})
assert result['error']['code'] == -32602
def test_trace_transaction_returns_full_instruction_trace_for_foo(server: StellarRpcServer) -> None:
"""traceTransaction returns the complete, ordered trace of an invocation: a ``callContract``
entry frame, the executed WebAssembly instructions, and an ``endWasm`` exit frame.
empty.wat's ``foo()`` body is a single ``i64.const 2`` (the Void return); the three leading
instruction records are the contract's global initialisation and the ``block`` is the
function frame. The instruction records are asserted record-for-record (the exact trace
shown in the README) so any drift in format, ordering, or the array-vs-string shape of the
result is caught. The entry/exit frames carry per-run contract and account ids, so they are
checked structurally rather than by value.
"""
invoke = deploy_and_get_invoker(server, EMPTY_CONTRACT_WAT)
tx_hash = invoke('foo')
trace = _rpc(server.port(), 'traceTransaction', {'hash': tx_hash})['result']
# A callContract entry frame opens the trace: the account calls foo() on the contract with
# no arguments at call depth 1.
entry = trace[0]
assert entry['instr'] == ['callContract']
assert entry['function'] == 'foo'
assert entry['args'] == []
assert entry['depth'] == 1
assert entry['from']['addrType'] == 'account'
assert entry['to']['addrType'] == 'contract'
# The executed WebAssembly instructions, exactly as shown in the README.
assert trace[1:-1] == [
{'pos': 3, 'instr': ['const', 'i32', 1048576], 'stack': [], 'locals': {}, 'mem': None},
{'pos': 11, 'instr': ['const', 'i32', 1048576], 'stack': [], 'locals': {}, 'mem': None},
{'pos': 19, 'instr': ['const', 'i32', 1048576], 'stack': [], 'locals': {}, 'mem': None},
{'pos': None, 'instr': ['block'], 'stack': [], 'locals': {}, 'mem': None},
{'pos': 3, 'instr': ['const', 'i64', 2], 'stack': [], 'locals': {}, 'mem': None},
]
# An endWasm exit frame closes the trace: the call succeeded and returned Void.
exit_frame = trace[-1]
assert exit_frame['instr'] == ['endWasm']
assert exit_frame['success'] is True
assert exit_frame['result'] == {'type': 'void'}
assert exit_frame['depth'] == 1
def test_trace_records_have_expected_structure_and_reflect_arguments(server: StellarRpcServer) -> None:
"""The trace opens with a ``callContract`` frame that echoes the decoded arguments, and each
WebAssembly instruction record is a ``{pos, instr, stack, locals}`` object. For a call that
takes arguments the arguments are bound as locals while intermediate values build up on the
stack — exercising a richer trace than the argument-less ``foo()`` case.
"""
invoke = deploy_and_get_invoker(server, ARGS_CONTRACT_WAT)
tx_hash = invoke(
'test_integers',
[
xdr.SCVal(type=SCValType.SCV_U32, u32=xdr.Uint32(42)),
xdr.SCVal(type=SCValType.SCV_I32, i32=xdr.Int32(-7)),
xdr.SCVal(type=SCValType.SCV_U64, u64=xdr.Uint64(100)),
xdr.SCVal(type=SCValType.SCV_I64, i64=xdr.Int64(-200)),
],
)
trace = _rpc(server.port(), 'traceTransaction', {'hash': tx_hash})['result']
assert isinstance(trace, list)
assert len(trace) > 0
# The callContract entry frame echoes the call target and its decoded arguments.
entry = trace[0]
assert entry['instr'] == ['callContract']
assert entry['function'] == 'test_integers'
assert entry['args'] == [
{'type': 'u32', 'value': 42},
{'type': 'i32', 'value': -7},
{'type': 'u64', 'value': 100},
{'type': 'i64', 'value': -200},
]
# The instruction records (everything between the call-boundary frames) share one shape.
instr_records = [record for record in trace if 'locals' in record]
assert instr_records
for record in instr_records:
assert set(record) == {'pos', 'instr', 'stack', 'locals', 'mem'}
assert record['pos'] is None or isinstance(record['pos'], int)
# mem is null when linear memory is unchanged since the previous record, else a list of runs.
assert record['mem'] is None or isinstance(record['mem'], list)
assert isinstance(record['instr'], list) and record['instr']
assert isinstance(record['instr'][0], str) # opcode mnemonic
# stack and locals hold [type, value] pairs.
assert isinstance(record['stack'], list)
assert all(isinstance(e, list) and len(e) == 2 and isinstance(e[0], str) for e in record['stack'])
assert isinstance(record['locals'], dict)
assert all(isinstance(e, list) and len(e) == 2 and isinstance(e[0], str) for e in record['locals'].values())
# The four call arguments are bound as locals 0..3 by the time the body runs.
locals_seen = {key for record in instr_records for key in record['locals']}
assert {'0', '1', '2', '3'} <= locals_seen
# Intermediate computation puts values on the stack at some point.
assert any(record['stack'] for record in instr_records)
# The function body returns Void: the final instruction pushes the i64 constant 2.
assert instr_records[-1]['instr'] == ['const', 'i64', 2]
def test_call_tx_with_args(server: StellarRpcServer) -> None:
"""The scval_to_json / #decodeArg pipeline decodes each supported SCVal arg type correctly.
Uses a minimal contract (args.wat) whose functions accept various arg types and return
Void. For each call the arguments echoed in the trace's ``callContract`` frame must
round-trip back to the exact SCVals that were sent — so a decoding bug is caught even
when the transaction still succeeds. Covers: bool, u32, i32, u64, i64, u128, i128, symbol.
"""
invoke = deploy_and_get_invoker(server, ARGS_CONTRACT_WAT)
def assert_args_round_trip(func: str, args: list[xdr.SCVal]) -> None:
tx_hash = invoke(func, args)
entry = _rpc(server.port(), 'traceTransaction', {'hash': tx_hash})['result'][0]
assert entry['function'] == func
assert [scval_from_json(arg) for arg in entry['args']] == args
assert_args_round_trip('test_bool', [xdr.SCVal(type=SCValType.SCV_BOOL, b=True)])
assert_args_round_trip(
'test_integers',
[
xdr.SCVal(type=SCValType.SCV_U32, u32=xdr.Uint32(42)),
xdr.SCVal(type=SCValType.SCV_I32, i32=xdr.Int32(-7)),
xdr.SCVal(type=SCValType.SCV_U64, u64=xdr.Uint64(100)),
xdr.SCVal(type=SCValType.SCV_I64, i64=xdr.Int64(-200)),
],
)
assert_args_round_trip(
'test_wide_integers',
[
xdr.SCVal(type=SCValType.SCV_U128, u128=xdr.UInt128Parts(hi=xdr.Uint64(0), lo=xdr.Uint64(999))),
xdr.SCVal(type=SCValType.SCV_I128, i128=xdr.Int128Parts(hi=xdr.Int64(0), lo=xdr.Uint64(888))),
],
)
assert_args_round_trip('test_symbol', [xdr.SCVal(type=SCValType.SCV_SYMBOL, sym=xdr.SCSymbol(sc_symbol=b'hello'))])
def test_call_tx_with_return_value(server: StellarRpcServer) -> None:
"""A contract invocation that returns a non-Void value succeeds.
Regression test: transactions used to be decoded into ``callTx(..., Void)``, which
asserts the call returns Void. Invoking ``add(2, 3)`` (returning U32(5)) therefore got
stuck in the semantics and was recorded as FAILED. ``uncheckedCallTx`` drops the return
value check.
"""
keypair, account = fund_account(server) # ledger 1
deployed = deploy_contract(server, keypair, account, ADDER_CONTRACT_WAT) # ledgers 2, 3
invoke = make_invoker(server, keypair, account, deployed.address)
# add(2, 3) returns U32(5), not Void — make_invoker asserts the call reaches SUCCESS.
invoke(
'add',
[
xdr.SCVal(type=SCValType.SCV_U32, u32=xdr.Uint32(2)),
xdr.SCVal(type=SCValType.SCV_U32, u32=xdr.Uint32(3)),
],
)
# All four transactions, including the non-Void invocation, advanced the ledger.
assert _rpc(server.port(), 'getLatestLedger', {})['result']['sequence'] == 4
# ----------------------------------------------------------------------
# getLedgerEntries
# ----------------------------------------------------------------------
#
# Spec: stellar-docs OpenRPC getLedgerEntries.json + stellar-rpc's Go serialization
# (GetLedgerEntriesResponse). Result is {entries, latestLedger}; latestLedger and
# lastModifiedLedgerSeq are JSON numbers; liveUntilLedgerSeq is optional (omitted when the
# entry has no TTL); only found entries are returned; `key`/`xdr` are base64 LedgerKey /
# LedgerEntryData strings.
def _account_ledger_key(public_key: str) -> str:
return xdr.LedgerKey(
type=xdr.LedgerEntryType.ACCOUNT,
account=xdr.LedgerKeyAccount(account_id=Keypair.from_public_key(public_key).xdr_account_id()),
).to_xdr()
def _contract_code_ledger_key(wasm_hash: bytes) -> str:
return xdr.LedgerKey(
type=xdr.LedgerEntryType.CONTRACT_CODE,
contract_code=xdr.LedgerKeyContractCode(hash=xdr.Hash(wasm_hash)),
).to_xdr()
def _contract_data_ledger_key(contract_address: str, key: xdr.SCVal, durability: xdr.ContractDataDurability) -> str:
return xdr.LedgerKey(
type=xdr.LedgerEntryType.CONTRACT_DATA,
contract_data=xdr.LedgerKeyContractData(
contract=Address(contract_address).to_xdr_sc_address(),
key=key,
durability=durability,
),
).to_xdr()
def _assert_ledger_entry_shape(entry: dict[str, Any], expected_key: str) -> None:
"""Assert one entry matches the Go LedgerEntryResult serialization (base64 format)."""
assert {'key', 'xdr', 'lastModifiedLedgerSeq'} <= set(entry)
assert set(entry) <= {'key', 'xdr', 'lastModifiedLedgerSeq', 'liveUntilLedgerSeq'}
assert entry['key'] == expected_key
assert type(entry['xdr']) is str and entry['xdr'] != ''
assert type(entry['lastModifiedLedgerSeq']) is int # JSON number, not string
if 'liveUntilLedgerSeq' in entry: # optional; only Soroban entries carry a TTL
assert type(entry['liveUntilLedgerSeq']) is int
def test_get_ledger_entries_account(server: StellarRpcServer) -> None:
"""An ACCOUNT ledger key resolves to an AccountEntry; unknown keys are silently dropped."""
keypair = Keypair.random()
account = Account(keypair.public_key, sequence=0)
send_tx(
server,
keypair,
TransactionBuilder(account, Network.TESTNET_NETWORK_PASSPHRASE).append_create_account_op(
destination=keypair.public_key, starting_balance='1000'
),
)
account_key = _account_ledger_key(keypair.public_key)
missing_key = _account_ledger_key(Keypair.random().public_key)
result = _rpc(server.port(), 'getLedgerEntries', {'keys': [account_key, missing_key]})['result']
assert set(result) == {'entries', 'latestLedger'}
assert result['latestLedger'] == 1
assert type(result['latestLedger']) is int # JSON number, not string
# Only the found entry is returned; the unknown key is not an error, just absent.
assert len(result['entries']) == 1
entry = result['entries'][0]
_assert_ledger_entry_shape(entry, account_key)
assert 0 <= entry['lastModifiedLedgerSeq'] <= result['latestLedger']
data = xdr.LedgerEntryData.from_xdr(entry['xdr'])
assert data.type == xdr.LedgerEntryType.ACCOUNT
assert data.account is not None
assert data.account.account_id == Keypair.from_public_key(keypair.public_key).xdr_account_id()
assert data.account.balance.int64 == 10_000_000_000 # 1000 XLM in stroops
def test_get_ledger_entries_contract_code_and_data(server: StellarRpcServer) -> None:
"""CONTRACT_CODE, the CONTRACT_DATA instance entry, and persistent CONTRACT_DATA storage."""
# Set up: create account, upload storage.wat, deploy, invoke store() which writes the
# persistent storage entry U32(7) -> U32(42).
keypair, account = fund_account(server)
deployed = deploy_contract(server, keypair, account, STORAGE_CONTRACT_WAT)
wasm_hash, wasm_bytecode, contract_address = deployed.wasm_hash, deployed.wasm_bytecode, deployed.address
make_invoker(server, keypair, account, contract_address)('store')
code_key = _contract_code_ledger_key(wasm_hash)
instance_key = _contract_data_ledger_key(
contract_address,
xdr.SCVal(type=SCValType.SCV_LEDGER_KEY_CONTRACT_INSTANCE),
xdr.ContractDataDurability.PERSISTENT,
)
storage_key_scval = xdr.SCVal(type=SCValType.SCV_U32, u32=xdr.Uint32(7))
storage_key = _contract_data_ledger_key(contract_address, storage_key_scval, xdr.ContractDataDurability.PERSISTENT)
result = _rpc(server.port(), 'getLedgerEntries', {'keys': [code_key, instance_key, storage_key]})['result']
assert set(result) == {'entries', 'latestLedger'}
assert result['latestLedger'] == 4
assert type(result['latestLedger']) is int
entries = {entry['key']: entry for entry in result['entries']}
assert set(entries) == {code_key, instance_key, storage_key}
for key, entry in entries.items():
_assert_ledger_entry_shape(entry, key)
# CONTRACT_CODE: the uploaded wasm bytecode round-trips through the ledger entry.
code_data = xdr.LedgerEntryData.from_xdr(entries[code_key]['xdr'])
assert code_data.type == xdr.LedgerEntryType.CONTRACT_CODE
assert code_data.contract_code is not None
assert code_data.contract_code.hash.hash == wasm_hash
assert code_data.contract_code.code == wasm_bytecode
# CONTRACT_DATA (instance): the deployed contract's instance entry points at the wasm.
instance_data = xdr.LedgerEntryData.from_xdr(entries[instance_key]['xdr'])
assert instance_data.type == xdr.LedgerEntryType.CONTRACT_DATA
assert instance_data.contract_data is not None
assert instance_data.contract_data.contract == Address(contract_address).to_xdr_sc_address()
assert instance_data.contract_data.durability == xdr.ContractDataDurability.PERSISTENT
assert instance_data.contract_data.key.type == SCValType.SCV_LEDGER_KEY_CONTRACT_INSTANCE
assert instance_data.contract_data.val.type == SCValType.SCV_CONTRACT_INSTANCE
instance = instance_data.contract_data.val.instance
assert instance is not None
assert instance.executable.type == xdr.ContractExecutableType.CONTRACT_EXECUTABLE_WASM
assert instance.executable.wasm_hash is not None
assert instance.executable.wasm_hash.hash == wasm_hash
# CONTRACT_DATA (persistent): the value written by store() is readable.
storage_data = xdr.LedgerEntryData.from_xdr(entries[storage_key]['xdr'])
assert storage_data.type == xdr.LedgerEntryType.CONTRACT_DATA
assert storage_data.contract_data is not None
assert storage_data.contract_data.contract == Address(contract_address).to_xdr_sc_address()
assert storage_data.contract_data.durability == xdr.ContractDataDurability.PERSISTENT
assert storage_data.contract_data.key == storage_key_scval
assert storage_data.contract_data.val == xdr.SCVal(type=SCValType.SCV_U32, u32=xdr.Uint32(42))
def test_get_ledger_entries_no_matches_returns_empty_entries(server: StellarRpcServer) -> None:
"""Unknown keys are not an error: the result is an empty entries array."""
result = _rpc(server.port(), 'getLedgerEntries', {'keys': [_account_ledger_key(Keypair.random().public_key)]})[
'result'
]
assert result['entries'] == []
assert result['latestLedger'] == 0
assert type(result['latestLedger']) is int
def test_get_ledger_entries_unsupported_entry_type_is_not_found(server: StellarRpcServer) -> None:
"""A well-formed key of a type komet-node does not track (DATA) is simply not found."""
data_key = xdr.LedgerKey(
type=xdr.LedgerEntryType.DATA,
data=xdr.LedgerKeyData(
account_id=Keypair.random().xdr_account_id(),
data_name=xdr.String64(b'config'),
),
).to_xdr()
result = _rpc(server.port(), 'getLedgerEntries', {'keys': [data_key]})['result']
assert result['entries'] == []
def test_get_ledger_entries_xdr_format_base64_accepted(server: StellarRpcServer) -> None:
"""xdrFormat 'base64' is the explicit spelling of the default and must be accepted."""
keys = [_account_ledger_key(Keypair.random().public_key)]
result = _rpc(server.port(), 'getLedgerEntries', {'keys': keys, 'xdrFormat': 'base64'})
assert 'error' not in result
assert result['result']['entries'] == []
def test_get_ledger_entries_xdr_format_json_rejected(server: StellarRpcServer) -> None:
"""komet-node does not support the JSON XDR format; asking for it is an invalid-params error."""
keys = [_account_ledger_key(Keypair.random().public_key)]
result = _rpc(server.port(), 'getLedgerEntries', {'keys': keys, 'xdrFormat': 'json'})
assert result['error']['code'] == -32602
assert type(result['error']['message']) is str and result['error']['message'] != ''
def test_get_ledger_entries_invalid_xdr_format_rejected(server: StellarRpcServer) -> None:
keys = [_account_ledger_key(Keypair.random().public_key)]
result = _rpc(server.port(), 'getLedgerEntries', {'keys': keys, 'xdrFormat': 'xml'})
assert result['error']['code'] == -32602
def test_get_ledger_entries_missing_keys_returns_invalid_params(server: StellarRpcServer) -> None:
result = _rpc(server.port(), 'getLedgerEntries', {})
assert result['error']['code'] == -32602
def test_get_ledger_entries_non_array_keys_returns_invalid_params(server: StellarRpcServer) -> None:
result = _rpc(server.port(), 'getLedgerEntries', {'keys': 'AAAAAA=='})
assert result['error']['code'] == -32602
def test_get_ledger_entries_non_string_key_returns_invalid_params(server: StellarRpcServer) -> None:
result = _rpc(server.port(), 'getLedgerEntries', {'keys': [42]})
assert result['error']['code'] == -32602
def test_get_ledger_entries_invalid_key_xdr_returns_invalid_params(server: StellarRpcServer) -> None:
result = _rpc(server.port(), 'getLedgerEntries', {'keys': ['not-a-ledger-key']})
assert result['error']['code'] == -32602
def test_get_ledger_entries_too_many_keys_returns_invalid_params(server: StellarRpcServer) -> None:
"""The spec caps a request at 200 ledger keys."""
key = _account_ledger_key(Keypair.random().public_key)
result = _rpc(server.port(), 'getLedgerEntries', {'keys': [key] * 201})
assert result['error']['code'] == -32602
# ---------------------------------------------------------------------------
# getTransactions / getLedgers (transaction history)
#
# Ground truth: the official OpenRPC spec (stellar-docs, methods/getTransactions.json and
# methods/getLedgers.json) and the Go serialization structs from stellar/go-stellar-sdk
# protocols/rpc, which is what real stellar-rpc emits. Notable serialization traps asserted
# below:
# - ledger sequences and the top-level close-time fields are JSON numbers,
# - per-transaction `createdAt` in getTransactions is a JSON *number* (upstream quirk;
# the singular getTransaction returns it as a string),
# - per-ledger `ledgerCloseTime` in getLedgers is a *string* (Go int64 `,string`),
# - XDR fields are `omitempty`: real base64 XDR or absent, never empty strings.
# ---------------------------------------------------------------------------
def _rpc_result(port: int, method: str, params: dict[str, Any]) -> dict[str, Any]:
"""Call an RPC method and return its result, failing the test on a JSON-RPC error."""
response = _rpc(port, method, params)
assert 'error' not in response, f'{method} returned an error: {response["error"]}'
return response['result']
def _send_create_accounts(server: StellarRpcServer, count: int) -> list[tuple[str, str]]:
"""Submit ``count`` successful create-account transactions; return (hash, envelopeXdr) pairs.
Each successful transaction closes its own ledger, so after this call the latest ledger
is ``count`` and transaction ``i`` (1-based) sits alone in ledger ``i``.
"""
keypair = Keypair.random()
account = Account(keypair.public_key, sequence=0)
sent: list[tuple[str, str]] = []
for _ in range(count):
envelope = (
TransactionBuilder(account, Network.TESTNET_NETWORK_PASSPHRASE)
.append_create_account_op(destination=keypair.public_key, starting_balance='1000')
.set_timeout(30)
.build()
)
envelope.sign(keypair)
xdr_str = envelope.to_xdr()
send_res = _rpc(server.port(), 'sendTransaction', {'transaction': xdr_str})
assert send_res['result']['status'] == 'PENDING'
tx_hash = send_res['result']['hash']
assert _rpc(server.port(), 'getTransaction', {'hash': tx_hash})['result']['status'] == 'SUCCESS'
sent.append((tx_hash, xdr_str))
return sent
def test_get_transactions_spec_shape(server: StellarRpcServer) -> None:
"""getTransactions returns the response shape of GetTransactionsResponse (Go SDK)."""
before = int(time.time())
sent = _send_create_accounts(server, 3)
after = int(time.time())
result = _rpc_result(server.port(), 'getTransactions', {'startLedger': 1})
# All six top-level fields lack `omitempty` in the Go struct, so all must be present.
required_keys = {
'transactions',
'latestLedger',
'latestLedgerCloseTimestamp',
'oldestLedger',
'oldestLedgerCloseTimestamp',
'cursor',
}
assert required_keys <= result.keys(), f'missing keys: {required_keys - result.keys()}'
assert type(result['latestLedger']) is int
assert result['latestLedger'] == 3
assert type(result['latestLedgerCloseTimestamp']) is int
assert type(result['oldestLedger']) is int
assert 0 <= result['oldestLedger'] <= 1
assert type(result['oldestLedgerCloseTimestamp']) is int
assert isinstance(result['cursor'], str)
txs = result['transactions']
assert isinstance(txs, list)
# All three transactions, in chain order (ascending ledger, then application order).
assert [tx['txHash'] for tx in txs] == [tx_hash for tx_hash, _ in sent]
for i, tx in enumerate(txs, start=1):
assert tx['status'] == 'SUCCESS'
assert _is_hex64(tx['txHash'])
assert type(tx['applicationOrder']) is int
assert tx['applicationOrder'] == 1 # one transaction per ledger on this node
assert tx['feeBump'] is False
assert type(tx['ledger']) is int
assert tx['ledger'] == i
# Upstream quirk: createdAt is a JSON number here (int64 without `,string` in Go),
# unlike getTransaction (singular) where it is a string.
assert type(tx['createdAt']) is int
assert before <= tx['createdAt'] <= after
assert tx['envelopeXdr'] == sent[i - 1][1]
# omitempty: XDR fields carry real base64 XDR or are absent — never empty strings.
for optional in ('resultXdr', 'resultMetaXdr'):
if optional in tx:
assert isinstance(tx[optional], str) and tx[optional] != ''
# xdrFormat: 'base64' is the default and must be accepted; unknown values are rejected.
with_format = _rpc_result(server.port(), 'getTransactions', {'startLedger': 1, 'xdrFormat': 'base64'})
assert [tx['txHash'] for tx in with_format['transactions']] == [tx_hash for tx_hash, _ in sent]
assert _rpc(server.port(), 'getTransactions', {'startLedger': 1, 'xdrFormat': 'bogus'})['error']['code'] == -32602
# The limit for getTransactions ranges from 1 to 200.
bad_limit = _rpc(server.port(), 'getTransactions', {'startLedger': 1, 'pagination': {'limit': 201}})
assert bad_limit['error']['code'] == -32602
def test_get_transactions_pagination(server: StellarRpcServer) -> None:
"""A limited page returns a cursor from which the next page resumes without overlap."""
sent = _send_create_accounts(server, 3)
page1 = _rpc_result(server.port(), 'getTransactions', {'startLedger': 1, 'pagination': {'limit': 2}})
assert [tx['txHash'] for tx in page1['transactions']] == [sent[0][0], sent[1][0]]
cursor = page1['cursor']
assert isinstance(cursor, str) and cursor != ''
# Resume from the cursor; startLedger must be omitted on cursor requests.
page2 = _rpc_result(server.port(), 'getTransactions', {'pagination': {'cursor': cursor, 'limit': 2}})
assert [tx['txHash'] for tx in page2['transactions']] == [sent[2][0]]
def test_get_transactions_invalid_params(server: StellarRpcServer) -> None:
port = server.port()
# startLedger beyond the latest ledger (0 on a fresh chain) is out of retention range.
assert _rpc(port, 'getTransactions', {'startLedger': 999})['error']['code'] == -32602
# startLedger and cursor are mutually exclusive.
both = _rpc(port, 'getTransactions', {'startLedger': 1, 'pagination': {'cursor': '1'}})
assert both['error']['code'] == -32602
# startLedger must be a number.
assert _rpc(port, 'getTransactions', {'startLedger': 'one'})['error']['code'] == -32602
def test_get_ledgers_spec_shape(server: StellarRpcServer) -> None:
"""getLedgers returns the response shape of GetLedgersResponse (Go SDK)."""
_send_create_accounts(server, 2)
result = _rpc_result(server.port(), 'getLedgers', {'startLedger': 1})
required_keys = {
'ledgers',
'latestLedger',
'latestLedgerCloseTime',
'oldestLedger',
'oldestLedgerCloseTime',
'cursor',
}
assert required_keys <= result.keys(), f'missing keys: {required_keys - result.keys()}'
assert type(result['latestLedger']) is int
assert result['latestLedger'] == 2