/
test_spend_build.py
2957 lines (2525 loc) · 112 KB
/
test_spend_build.py
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
"""Tests for spending with Plutus using `transaction build`."""
import json
import logging
import shutil
from pathlib import Path
from typing import Any
from typing import List
from typing import Optional
from typing import Tuple
import allure
import hypothesis
import hypothesis.strategies as st
import pytest
from _pytest.fixtures import FixtureRequest
from cardano_clusterlib import clusterlib
from cardano_clusterlib import txtools
from cardano_node_tests.cluster_management import cluster_management
from cardano_node_tests.tests import common
from cardano_node_tests.tests import plutus_common
from cardano_node_tests.utils import clusterlib_utils
from cardano_node_tests.utils import configuration
from cardano_node_tests.utils import dbsync_utils
from cardano_node_tests.utils import helpers
from cardano_node_tests.utils import tx_view
from cardano_node_tests.utils.versions import VERSIONS
LOGGER = logging.getLogger(__name__)
# skip all tests if Tx era < alonzo
pytestmark = [
common.SKIPIF_BUILD_UNUSABLE,
pytest.mark.smoke,
]
@pytest.fixture
def payment_addrs(
cluster_manager: cluster_management.ClusterManager,
cluster: clusterlib.ClusterLib,
) -> List[clusterlib.AddressRecord]:
"""Create new payment addresses."""
test_id = common.get_test_id(cluster)
addrs = clusterlib_utils.create_payment_addr_records(
*[f"{test_id}_payment_addr_{i}" for i in range(3)],
cluster_obj=cluster,
)
# fund source address
clusterlib_utils.fund_from_faucet(
addrs[0],
cluster_obj=cluster,
faucet_data=cluster_manager.cache.addrs_data["user1"],
amount=1_000_000_000,
)
return addrs
@pytest.fixture
def pool_users(
cluster_manager: cluster_management.ClusterManager,
cluster: clusterlib.ClusterLib,
) -> List[clusterlib.PoolUser]:
"""Create new pool users."""
test_id = common.get_test_id(cluster)
created_users = clusterlib_utils.create_pool_users(
cluster_obj=cluster,
name_template=f"{test_id}_pool_users",
no_of_addr=2,
)
# fund source address
clusterlib_utils.fund_from_faucet(
created_users[0],
cluster_obj=cluster,
faucet_data=cluster_manager.cache.addrs_data["user1"],
amount=3_000_000_000,
)
return created_users
def _build_fund_script(
temp_template: str,
cluster_obj: clusterlib.ClusterLib,
payment_addr: clusterlib.AddressRecord,
dst_addr: clusterlib.AddressRecord,
plutus_op: plutus_common.PlutusOp,
tokens: Optional[List[plutus_common.Token]] = None, # tokens must already be in `payment_addr`
tokens_collateral: Optional[
List[plutus_common.Token]
] = None, # tokens must already be in `payment_addr`
embed_datum: bool = False,
) -> Tuple[List[clusterlib.UTXOData], List[clusterlib.UTXOData], clusterlib.TxRawOutput]:
"""Fund a Plutus script and create the locked UTxO and collateral UTxO.
Uses `cardano-cli transaction build` command for building the transactions.
"""
assert plutus_op.execution_cost # for mypy
script_fund = 200_000_000
stokens = tokens or ()
ctokens = tokens_collateral or ()
script_address = cluster_obj.g_address.gen_payment_addr(
addr_name=temp_template, payment_script_file=plutus_op.script_file
)
redeem_cost = plutus_common.compute_cost(
execution_cost=plutus_op.execution_cost,
protocol_params=cluster_obj.g_query.get_protocol_params(),
)
# create a Tx output with a datum hash at the script address
tx_files = clusterlib.TxFiles(
signing_key_files=[payment_addr.skey_file],
)
script_txout = plutus_common.txout_factory(
address=script_address,
amount=script_fund,
plutus_op=plutus_op,
embed_datum=embed_datum,
)
txouts = [
script_txout,
# for collateral
clusterlib.TxOut(address=dst_addr.address, amount=redeem_cost.collateral),
]
for token in stokens:
txouts.append(script_txout._replace(amount=token.amount, coin=token.coin))
for token in ctokens:
txouts.append(
clusterlib.TxOut(
address=dst_addr.address,
amount=token.amount,
coin=token.coin,
)
)
tx_output = cluster_obj.g_transaction.build_tx(
src_address=payment_addr.address,
tx_name=f"{temp_template}_step1",
tx_files=tx_files,
txouts=txouts,
fee_buffer=2_000_000,
)
tx_signed = cluster_obj.g_transaction.sign_tx(
tx_body_file=tx_output.out_file,
signing_key_files=tx_files.signing_key_files,
tx_name=f"{temp_template}_step1",
)
cluster_obj.g_transaction.submit_tx(tx_file=tx_signed, txins=tx_output.txins)
out_utxos = cluster_obj.g_query.get_utxo(tx_raw_output=tx_output)
utxo_ix_offset = clusterlib_utils.get_utxo_ix_offset(utxos=out_utxos, txouts=tx_output.txouts)
script_utxos = clusterlib.filter_utxos(utxos=out_utxos, utxo_ix=utxo_ix_offset)
assert script_utxos, "No script UTxO"
assert (
clusterlib.calculate_utxos_balance(utxos=script_utxos) == script_fund
), f"Incorrect balance for script address `{script_address}`"
collateral_utxos = clusterlib.filter_utxos(utxos=out_utxos, utxo_ix=utxo_ix_offset + 1)
assert collateral_utxos, "No collateral UTxO"
assert (
clusterlib.calculate_utxos_balance(utxos=collateral_utxos) == redeem_cost.collateral
), f"Incorrect balance for collateral address `{dst_addr.address}`"
for token in stokens:
assert (
clusterlib.calculate_utxos_balance(utxos=script_utxos, coin=token.coin) == token.amount
), f"Incorrect token balance for script address `{script_address}`"
for token in ctokens:
assert (
clusterlib.calculate_utxos_balance(utxos=collateral_utxos, coin=token.coin)
== token.amount
), f"Incorrect token balance for address `{dst_addr.address}`"
if VERSIONS.transaction_era >= VERSIONS.ALONZO:
dbsync_utils.check_tx(cluster_obj=cluster_obj, tx_raw_output=tx_output)
return script_utxos, collateral_utxos, tx_output
def _build_spend_locked_txin( # noqa: C901
temp_template: str,
cluster_obj: clusterlib.ClusterLib,
payment_addr: clusterlib.AddressRecord,
dst_addr: clusterlib.AddressRecord,
script_utxos: List[clusterlib.UTXOData],
collateral_utxos: List[clusterlib.UTXOData],
plutus_op: plutus_common.PlutusOp,
amount: int,
deposit_amount: int = 0,
txins: clusterlib.OptionalUTXOData = (),
tx_files: Optional[clusterlib.TxFiles] = None,
invalid_hereafter: Optional[int] = None,
invalid_before: Optional[int] = None,
tokens: Optional[List[plutus_common.Token]] = None,
expect_failure: bool = False,
script_valid: bool = True,
submit_tx: bool = True,
) -> Tuple[str, Optional[clusterlib.TxRawOutput], list]:
"""Spend the locked UTxO.
Uses `cardano-cli transaction build` command for building the transactions.
"""
# pylint: disable=too-many-arguments,too-many-locals
tx_files = tx_files or clusterlib.TxFiles()
spent_tokens = tokens or ()
# Change that was calculated manually will be returned to address of the first script.
# The remaining change that is automatically handled by the `build` command will be returned
# to `payment_addr`, because it would be inaccessible on script address without proper
# datum hash (datum hash is not provided for change that is handled by `build` command).
script_change_rec = script_utxos[0]
# spend the "locked" UTxO
plutus_txins = [
clusterlib.ScriptTxIn(
txins=script_utxos,
script_file=plutus_op.script_file,
collaterals=collateral_utxos,
datum_file=plutus_op.datum_file if plutus_op.datum_file else "",
datum_cbor_file=plutus_op.datum_cbor_file if plutus_op.datum_cbor_file else "",
datum_value=plutus_op.datum_value if plutus_op.datum_value else "",
redeemer_file=plutus_op.redeemer_file if plutus_op.redeemer_file else "",
redeemer_cbor_file=plutus_op.redeemer_cbor_file if plutus_op.redeemer_cbor_file else "",
redeemer_value=plutus_op.redeemer_value if plutus_op.redeemer_value else "",
)
]
tx_files = tx_files._replace(
signing_key_files=list({*tx_files.signing_key_files, dst_addr.skey_file}),
)
txouts = [
clusterlib.TxOut(address=dst_addr.address, amount=amount),
]
lovelace_change_needed = False
for token in spent_tokens:
txouts.append(
clusterlib.TxOut(address=dst_addr.address, amount=token.amount, coin=token.coin)
)
# append change
script_token_balance = clusterlib.calculate_utxos_balance(
utxos=script_utxos, coin=token.coin
)
if script_token_balance > token.amount:
lovelace_change_needed = True
txouts.append(
clusterlib.TxOut(
address=script_change_rec.address,
amount=script_token_balance - token.amount,
coin=token.coin,
datum_hash=script_change_rec.datum_hash,
)
)
# add minimum (+ some) required Lovelace to change Tx output
if lovelace_change_needed:
txouts.append(
clusterlib.TxOut(
address=script_change_rec.address,
amount=4_000_000,
coin=clusterlib.DEFAULT_COIN,
datum_hash=script_change_rec.datum_hash,
)
)
if expect_failure:
with pytest.raises(clusterlib.CLIError) as excinfo:
cluster_obj.g_transaction.build_tx(
src_address=payment_addr.address,
tx_name=f"{temp_template}_step2",
tx_files=tx_files,
txins=txins,
txouts=txouts,
script_txins=plutus_txins,
change_address=payment_addr.address,
)
return str(excinfo.value), None, []
tx_output = cluster_obj.g_transaction.build_tx(
src_address=payment_addr.address,
tx_name=f"{temp_template}_step2",
tx_files=tx_files,
txins=txins,
txouts=txouts,
script_txins=plutus_txins,
change_address=payment_addr.address,
invalid_hereafter=invalid_hereafter,
invalid_before=invalid_before,
deposit=deposit_amount,
script_valid=script_valid,
)
tx_signed = cluster_obj.g_transaction.sign_tx(
tx_body_file=tx_output.out_file,
signing_key_files=tx_files.signing_key_files,
tx_name=f"{temp_template}_step2",
)
if not submit_tx:
return "", tx_output, []
dst_init_balance = cluster_obj.g_query.get_address_balance(dst_addr.address)
script_utxos_lovelace = [u for u in script_utxos if u.coin == clusterlib.DEFAULT_COIN]
if not script_valid:
cluster_obj.g_transaction.submit_tx(tx_file=tx_signed, txins=collateral_utxos)
assert (
cluster_obj.g_query.get_address_balance(dst_addr.address)
== dst_init_balance - collateral_utxos[0].amount
), f"Collateral was NOT spent from `{dst_addr.address}`"
for u in script_utxos_lovelace:
assert cluster_obj.g_query.get_utxo(
utxo=u, coins=[clusterlib.DEFAULT_COIN]
), f"Inputs were unexpectedly spent for `{u.address}`"
return "", tx_output, []
# calculate cost of Plutus script
plutus_costs = cluster_obj.g_transaction.calculate_plutus_script_cost(
src_address=payment_addr.address,
tx_name=f"{temp_template}_step2",
tx_files=tx_files,
txouts=txouts,
script_txins=plutus_txins,
change_address=payment_addr.address,
invalid_hereafter=invalid_hereafter,
invalid_before=invalid_before,
deposit=deposit_amount,
script_valid=script_valid,
)
cluster_obj.g_transaction.submit_tx(
tx_file=tx_signed, txins=[t.txins[0] for t in tx_output.script_txins if t.txins]
)
assert (
cluster_obj.g_query.get_address_balance(dst_addr.address) == dst_init_balance + amount
), f"Incorrect balance for destination address `{dst_addr.address}`"
for u in script_utxos_lovelace:
assert not cluster_obj.g_query.get_utxo(
utxo=u, coins=[clusterlib.DEFAULT_COIN]
), f"Inputs were NOT spent for `{u.address}`"
for token in spent_tokens:
script_utxos_token = [u for u in script_utxos if u.coin == token.coin]
for u in script_utxos_token:
assert not cluster_obj.g_query.get_utxo(
utxo=u, coins=[token.coin]
), f"Token inputs were NOT spent for `{u.address}`"
# check tx view
tx_view.check_tx_view(cluster_obj=cluster_obj, tx_raw_output=tx_output)
tx_db_record = dbsync_utils.check_tx(cluster_obj=cluster_obj, tx_raw_output=tx_output)
# compare cost of Plutus script with data from db-sync
if tx_db_record:
dbsync_utils.check_plutus_costs(
redeemer_records=tx_db_record.redeemers, cost_records=plutus_costs
)
return "", tx_output, plutus_costs
@common.SKIPIF_PLUTUS_UNUSABLE
@pytest.mark.testnets
class TestBuildLocking:
"""Tests for Tx output locking using Plutus smart contracts and `transaction build`."""
@allure.link(helpers.get_vcs_link())
@pytest.mark.dbsync
@common.PARAM_PLUTUS_VERSION
def test_txout_locking(
self,
cluster: clusterlib.ClusterLib,
payment_addrs: List[clusterlib.AddressRecord],
plutus_version: str,
):
"""Test locking a Tx output with a Plutus script and spending the locked UTxO.
Uses `cardano-cli transaction build` command for building the transactions.
Corresponds to Exercise 3 for Alonzo Blue.
* create a Tx output with a datum hash at the script address
* check that the expected amount was locked at the script address
* spend the locked UTxO
* check that the expected amount was spent
* check expected fees
* check expected Plutus cost
* (optional) check transactions in db-sync
"""
temp_template = f"{common.get_test_id(cluster)}_{plutus_version}"
plutus_op = plutus_common.PlutusOp(
script_file=plutus_common.ALWAYS_SUCCEEDS[plutus_version].script_file,
datum_file=plutus_common.DATUM_42_TYPED,
redeemer_cbor_file=plutus_common.REDEEMER_42_CBOR,
execution_cost=plutus_common.ALWAYS_SUCCEEDS[plutus_version].execution_cost,
)
script_utxos, collateral_utxos, tx_output_fund = _build_fund_script(
temp_template=temp_template,
cluster_obj=cluster,
payment_addr=payment_addrs[0],
dst_addr=payment_addrs[1],
plutus_op=plutus_op,
)
__, tx_output, plutus_costs = _build_spend_locked_txin(
temp_template=temp_template,
cluster_obj=cluster,
payment_addr=payment_addrs[0],
dst_addr=payment_addrs[1],
script_utxos=script_utxos,
collateral_utxos=collateral_utxos,
plutus_op=plutus_op,
amount=2_000_000,
)
# check expected fees
expected_fee_fund = 168_845
assert helpers.is_in_interval(tx_output_fund.fee, expected_fee_fund, frac=0.15)
expected_fee = 170_782
assert tx_output and helpers.is_in_interval(tx_output.fee, expected_fee, frac=0.15)
plutus_common.check_plutus_costs(
plutus_costs=plutus_costs,
expected_costs=[plutus_common.ALWAYS_SUCCEEDS[plutus_version].execution_cost],
)
@allure.link(helpers.get_vcs_link())
@pytest.mark.skipif(
not shutil.which("create-script-context"),
reason="cannot find `create-script-context` on the PATH",
)
@pytest.mark.dbsync
def test_context_equivalence(
self,
cluster: clusterlib.ClusterLib,
pool_users: List[clusterlib.PoolUser],
):
"""Test context equivalence while spending a locked UTxO.
Uses `cardano-cli transaction build` command for building the transactions.
* create a Tx output with a datum hash at the script address
* check that the expected amount was locked at the script address
* generate a dummy redeemer and a dummy Tx
* derive the correct redeemer from the dummy Tx
* spend the locked UTxO using the derived redeemer
* check that the expected amount was spent
* (optional) check transactions in db-sync
"""
__: Any # mypy workaround
temp_template = common.get_test_id(cluster)
amount = 10_000_000
deposit_amount = cluster.g_query.get_address_deposit()
# create stake address registration cert
stake_addr_reg_cert_file = cluster.g_stake_address.gen_stake_addr_registration_cert(
addr_name=f"{temp_template}_addr2",
stake_vkey_file=pool_users[0].stake.vkey_file,
)
tx_files = clusterlib.TxFiles(certificate_files=[stake_addr_reg_cert_file])
# generate a dummy redeemer in order to create a txbody from which
# we can generate a tx and then derive the correct redeemer
redeemer_file_dummy = Path(f"{temp_template}_dummy_script_context.redeemer")
clusterlib_utils.create_script_context(
cluster_obj=cluster, plutus_version=1, redeemer_file=redeemer_file_dummy
)
plutus_op_dummy = plutus_common.PlutusOp(
script_file=plutus_common.CONTEXT_EQUIVALENCE_PLUTUS_V1,
datum_file=plutus_common.DATUM_42_TYPED,
redeemer_file=redeemer_file_dummy,
execution_cost=plutus_common.CONTEXT_EQUIVALENCE_COST,
)
# fund the script address
script_utxos, collateral_utxos, __ = _build_fund_script(
temp_template=temp_template,
cluster_obj=cluster,
payment_addr=pool_users[0].payment,
dst_addr=pool_users[1].payment,
plutus_op=plutus_op_dummy,
)
invalid_hereafter = cluster.g_query.get_slot_no() + 200
__, tx_output_dummy, __ = _build_spend_locked_txin(
temp_template=f"{temp_template}_dummy",
cluster_obj=cluster,
payment_addr=pool_users[0].payment,
dst_addr=pool_users[1].payment,
script_utxos=script_utxos,
collateral_utxos=collateral_utxos,
plutus_op=plutus_op_dummy,
amount=amount,
deposit_amount=deposit_amount,
tx_files=tx_files,
invalid_before=1,
invalid_hereafter=invalid_hereafter,
script_valid=False,
submit_tx=False,
)
assert tx_output_dummy
# generate the "real" redeemer
redeemer_file = Path(f"{temp_template}_script_context.redeemer")
tx_file_dummy = Path(f"{tx_output_dummy.out_file.with_suffix('')}.signed")
try:
clusterlib_utils.create_script_context(
cluster_obj=cluster,
plutus_version=1,
redeemer_file=redeemer_file,
tx_file=tx_file_dummy,
)
except AssertionError as err:
err_msg = str(err)
if "DeserialiseFailure" in err_msg:
pytest.xfail("DeserialiseFailure: see issue #944")
if "TextEnvelopeTypeError" in err_msg and cluster.use_cddl: # noqa: SIM106
pytest.xfail(
"TextEnvelopeTypeError: `create-script-context` doesn't work with CDDL format"
)
else:
raise
plutus_op = plutus_op_dummy._replace(redeemer_file=redeemer_file)
__, tx_output, __ = _build_spend_locked_txin(
temp_template=temp_template,
cluster_obj=cluster,
payment_addr=pool_users[0].payment,
dst_addr=pool_users[1].payment,
script_utxos=script_utxos,
collateral_utxos=collateral_utxos,
plutus_op=plutus_op,
amount=amount,
deposit_amount=deposit_amount,
tx_files=tx_files,
invalid_before=1,
invalid_hereafter=invalid_hereafter,
)
# check expected fees
if tx_output:
expected_fee = 372_438
assert helpers.is_in_interval(tx_output.fee, expected_fee, frac=0.15)
@allure.link(helpers.get_vcs_link())
@pytest.mark.dbsync
@pytest.mark.parametrize("embed_datum", (True, False), ids=("embedded_datum", "datum"))
@pytest.mark.parametrize(
"variant",
("typed_json", "typed_cbor", "untyped_value", "untyped_json", "untyped_cbor"),
)
@common.PARAM_PLUTUS_VERSION
def test_guessing_game(
self,
cluster: clusterlib.ClusterLib,
payment_addrs: List[clusterlib.AddressRecord],
variant: str,
plutus_version: str,
embed_datum: bool,
request: FixtureRequest,
):
"""Test locking a Tx output with a Plutus script and spending the locked UTxO.
Uses `cardano-cli transaction build` command for building the transactions.
Test with "guessing game" scripts that expect specific datum and redeemer value.
Test both typed and untyped redeemer and datum.
Test passing datum and redeemer to `cardano-cli` as value, json file and cbor file.
* create a Tx output with a datum hash at the script address
* check that the expected amount was locked at the script address
* spend the locked UTxO
* check that the expected amount was spent
* (optional) check transactions in db-sync
"""
__: Any # mypy workaround
temp_template = f"{common.get_test_id(cluster)}_{request.node.callspec.id}"
datum_file: Optional[Path] = None
datum_cbor_file: Optional[Path] = None
datum_value: Optional[str] = None
redeemer_file: Optional[Path] = None
redeemer_cbor_file: Optional[Path] = None
redeemer_value: Optional[str] = None
if variant == "typed_json":
script_file = plutus_common.GUESSING_GAME[plutus_version].script_file
datum_file = plutus_common.DATUM_42_TYPED
redeemer_file = plutus_common.REDEEMER_42_TYPED
elif variant == "typed_cbor":
script_file = plutus_common.GUESSING_GAME[plutus_version].script_file
datum_cbor_file = plutus_common.DATUM_42_TYPED_CBOR
redeemer_cbor_file = plutus_common.REDEEMER_42_TYPED_CBOR
elif variant == "untyped_value":
script_file = plutus_common.GUESSING_GAME_UNTYPED[plutus_version].script_file
datum_value = "42"
redeemer_value = "42"
elif variant == "untyped_json":
script_file = plutus_common.GUESSING_GAME_UNTYPED[plutus_version].script_file
datum_file = plutus_common.DATUM_42
redeemer_file = plutus_common.REDEEMER_42
elif variant == "untyped_cbor": # noqa: SIM106
script_file = plutus_common.GUESSING_GAME_UNTYPED[plutus_version].script_file
datum_cbor_file = plutus_common.DATUM_42_CBOR
redeemer_cbor_file = plutus_common.REDEEMER_42_CBOR
else:
raise AssertionError("Unknown test variant.")
execution_cost = plutus_common.GUESSING_GAME[plutus_version].execution_cost
if script_file == plutus_common.GUESSING_GAME_UNTYPED[plutus_version].script_file:
execution_cost = plutus_common.GUESSING_GAME_UNTYPED[plutus_version].execution_cost
plutus_op = plutus_common.PlutusOp(
script_file=script_file,
datum_file=datum_file,
datum_cbor_file=datum_cbor_file,
datum_value=datum_value,
redeemer_file=redeemer_file,
redeemer_cbor_file=redeemer_cbor_file,
redeemer_value=redeemer_value,
execution_cost=execution_cost,
)
script_utxos, collateral_utxos, tx_output_fund = _build_fund_script(
temp_template=temp_template,
cluster_obj=cluster,
payment_addr=payment_addrs[0],
dst_addr=payment_addrs[1],
plutus_op=plutus_op,
embed_datum=embed_datum,
)
__, __, plutus_costs = _build_spend_locked_txin(
temp_template=temp_template,
cluster_obj=cluster,
payment_addr=payment_addrs[0],
dst_addr=payment_addrs[1],
script_utxos=script_utxos,
collateral_utxos=collateral_utxos,
plutus_op=plutus_op,
amount=2_000_000,
)
# check expected fees
expected_fee_fund = 168_845
assert helpers.is_in_interval(tx_output_fund.fee, expected_fee_fund, frac=0.15)
plutus_common.check_plutus_costs(
plutus_costs=plutus_costs,
expected_costs=[execution_cost],
)
@allure.link(helpers.get_vcs_link())
@pytest.mark.dbsync
@pytest.mark.parametrize(
"plutus_version",
(
"plutus_v1",
pytest.param("mix_v1_v2", marks=common.SKIPIF_PLUTUSV2_UNUSABLE),
pytest.param("mix_v2_v1", marks=common.SKIPIF_PLUTUSV2_UNUSABLE),
pytest.param("plutus_v2", marks=common.SKIPIF_PLUTUSV2_UNUSABLE),
),
)
def test_two_scripts_spending(
self,
cluster: clusterlib.ClusterLib,
payment_addrs: List[clusterlib.AddressRecord],
plutus_version: str,
):
"""Test locking two Tx outputs with two different Plutus scripts in single Tx.
Uses `cardano-cli transaction build` command for building the transactions.
* create a Tx output with a datum hash at the script address
* check that the expected amount was locked at the script address
* spend the locked UTxO
* check that the expected amount was spent
* check expected fees
* check expected Plutus cost
* (optional) check transactions in db-sync
"""
# pylint: disable=too-many-locals,too-many-statements
temp_template = f"{common.get_test_id(cluster)}_{plutus_version}"
amount = 2_000_000
script_fund = 200_000_000
protocol_params = cluster.g_query.get_protocol_params()
script_file1_v1 = plutus_common.ALWAYS_SUCCEEDS_PLUTUS_V1
execution_cost1_v1 = plutus_common.ALWAYS_SUCCEEDS_COST
script_file2_v1 = plutus_common.GUESSING_GAME_PLUTUS_V1
# this is higher than `plutus_common.GUESSING_GAME_COST`, because the script
# context has changed to include more stuff
if configuration.ALONZO_COST_MODEL or VERSIONS.cluster_era == VERSIONS.ALONZO:
execution_cost2_v1 = plutus_common.ExecutionCost(
per_time=388_458_303, per_space=1_031_312, fixed_cost=87_515
)
else:
execution_cost2_v1 = plutus_common.ExecutionCost(
per_time=280_668_068, per_space=1_031_312, fixed_cost=79_743
)
script_file1_v2 = plutus_common.ALWAYS_SUCCEEDS_PLUTUS_V2
execution_cost1_v2 = plutus_common.ALWAYS_SUCCEEDS_V2_COST
script_file2_v2 = plutus_common.GUESSING_GAME_PLUTUS_V2
execution_cost2_v2 = plutus_common.ExecutionCost(
per_time=208_314_784,
per_space=662_274,
fixed_cost=53_233,
)
expected_fee_fund = 174_389
if plutus_version == "plutus_v1":
script_file1 = script_file1_v1
execution_cost1 = execution_cost1_v1
script_file2 = script_file2_v1
execution_cost2 = execution_cost2_v1
expected_fee_redeem = 378_768
elif plutus_version == "mix_v1_v2":
script_file1 = script_file1_v1
execution_cost1 = execution_cost1_v1
script_file2 = script_file2_v2
execution_cost2 = execution_cost2_v2
expected_fee_redeem = 321_739
elif plutus_version == "mix_v2_v1":
script_file1 = script_file1_v2
execution_cost1 = execution_cost1_v2
script_file2 = script_file2_v1
execution_cost2 = execution_cost2_v1
expected_fee_redeem = 378_584
elif plutus_version == "plutus_v2":
script_file1 = script_file1_v2
execution_cost1 = execution_cost1_v2
script_file2 = script_file2_v2
execution_cost2 = execution_cost2_v2
expected_fee_redeem = 321_378
else:
raise AssertionError("Unknown test variant.")
plutus_op1 = plutus_common.PlutusOp(
script_file=script_file1,
datum_file=plutus_common.DATUM_42_TYPED,
redeemer_cbor_file=plutus_common.REDEEMER_42_CBOR,
execution_cost=execution_cost1,
)
plutus_op2 = plutus_common.PlutusOp(
script_file=script_file2,
datum_file=plutus_common.DATUM_42_TYPED,
redeemer_cbor_file=plutus_common.REDEEMER_42_TYPED_CBOR,
execution_cost=execution_cost2,
)
# Step 1: fund the Plutus scripts
assert plutus_op1.execution_cost and plutus_op2.execution_cost # for mypy
script_address1 = cluster.g_address.gen_payment_addr(
addr_name=f"{temp_template}_addr1", payment_script_file=plutus_op1.script_file
)
redeem_cost1 = plutus_common.compute_cost(
execution_cost=plutus_op1.execution_cost, protocol_params=protocol_params
)
datum_hash1 = cluster.g_transaction.get_hash_script_data(
script_data_file=plutus_op1.datum_file
)
script_address2 = cluster.g_address.gen_payment_addr(
addr_name=f"{temp_template}_addr2", payment_script_file=plutus_op2.script_file
)
redeem_cost2 = plutus_common.compute_cost(
execution_cost=plutus_op2.execution_cost, protocol_params=protocol_params
)
datum_hash2 = cluster.g_transaction.get_hash_script_data(
script_data_file=plutus_op2.datum_file
)
# create a Tx output with a datum hash at the script address
tx_files_fund = clusterlib.TxFiles(
signing_key_files=[payment_addrs[0].skey_file],
)
txouts_fund = [
clusterlib.TxOut(
address=script_address1,
amount=script_fund,
datum_hash=datum_hash1,
),
clusterlib.TxOut(
address=script_address2,
amount=script_fund,
datum_hash=datum_hash2,
),
# for collateral
clusterlib.TxOut(address=payment_addrs[1].address, amount=redeem_cost1.collateral),
clusterlib.TxOut(address=payment_addrs[1].address, amount=redeem_cost2.collateral),
]
tx_output_fund = cluster.g_transaction.build_tx(
src_address=payment_addrs[0].address,
tx_name=f"{temp_template}_step1",
tx_files=tx_files_fund,
txouts=txouts_fund,
fee_buffer=2_000_000,
join_txouts=False,
)
tx_signed_fund = cluster.g_transaction.sign_tx(
tx_body_file=tx_output_fund.out_file,
signing_key_files=tx_files_fund.signing_key_files,
tx_name=f"{temp_template}_step1",
)
cluster.g_transaction.submit_tx(tx_file=tx_signed_fund, txins=tx_output_fund.txins)
fund_utxos = cluster.g_query.get_utxo(tx_raw_output=tx_output_fund)
utxo_ix_offset = clusterlib_utils.get_utxo_ix_offset(
utxos=fund_utxos, txouts=tx_output_fund.txouts
)
script_utxos1 = clusterlib.filter_utxos(utxos=fund_utxos, utxo_ix=utxo_ix_offset)
script_utxos2 = clusterlib.filter_utxos(utxos=fund_utxos, utxo_ix=utxo_ix_offset + 1)
collateral_utxos1 = clusterlib.filter_utxos(utxos=fund_utxos, utxo_ix=utxo_ix_offset + 2)
collateral_utxos2 = clusterlib.filter_utxos(utxos=fund_utxos, utxo_ix=utxo_ix_offset + 3)
assert script_utxos1 and script_utxos2, "No script UTxOs"
assert collateral_utxos1 and collateral_utxos2, "No collateral UTxOs"
assert (
script_utxos1[0].amount == script_fund
), f"Incorrect balance for script address `{script_utxos1[0].address}`"
assert (
script_utxos2[0].amount == script_fund
), f"Incorrect balance for script address `{script_utxos2[0].address}`"
# Step 2: spend the "locked" UTxOs
assert plutus_op1.datum_file and plutus_op2.datum_file
assert plutus_op1.redeemer_cbor_file and plutus_op2.redeemer_cbor_file
plutus_txins = [
clusterlib.ScriptTxIn(
txins=script_utxos1,
script_file=plutus_op1.script_file,
collaterals=collateral_utxos1,
datum_file=plutus_op1.datum_file,
redeemer_cbor_file=plutus_op1.redeemer_cbor_file,
),
clusterlib.ScriptTxIn(
txins=script_utxos2,
script_file=plutus_op2.script_file,
collaterals=collateral_utxos2,
datum_file=plutus_op2.datum_file,
redeemer_cbor_file=plutus_op2.redeemer_cbor_file,
),
]
tx_files_redeem = clusterlib.TxFiles(
signing_key_files=[payment_addrs[1].skey_file],
)
txouts_redeem = [
clusterlib.TxOut(address=payment_addrs[1].address, amount=amount * 2),
]
tx_output_redeem = cluster.g_transaction.build_tx(
src_address=payment_addrs[0].address,
tx_name=f"{temp_template}_step2",
tx_files=tx_files_redeem,
txouts=txouts_redeem,
script_txins=plutus_txins,
change_address=payment_addrs[0].address,
)
# calculate cost of Plutus script
plutus_costs = cluster.g_transaction.calculate_plutus_script_cost(
src_address=payment_addrs[0].address,
tx_name=f"{temp_template}_step2",
tx_files=tx_files_redeem,
txouts=txouts_redeem,
script_txins=plutus_txins,
change_address=payment_addrs[0].address,
)
tx_signed_redeem = cluster.g_transaction.sign_tx(
tx_body_file=tx_output_redeem.out_file,
signing_key_files=tx_files_redeem.signing_key_files,
tx_name=f"{temp_template}_step2",
)
dst_init_balance = cluster.g_query.get_address_balance(payment_addrs[1].address)
cluster.g_transaction.submit_tx(
tx_file=tx_signed_redeem,
txins=[t.txins[0] for t in tx_output_redeem.script_txins if t.txins],
)
assert (
cluster.g_query.get_address_balance(payment_addrs[1].address)
== dst_init_balance + amount * 2
), f"Incorrect balance for destination address `{payment_addrs[1].address}`"
script_utxos_lovelace = [
u for u in [*script_utxos1, *script_utxos2] if u.coin == clusterlib.DEFAULT_COIN
]
for u in script_utxos_lovelace:
assert not cluster.g_query.get_utxo(
utxo=u, coins=[clusterlib.DEFAULT_COIN]
), f"Inputs were NOT spent for `{u.address}`"
# check expected fees
assert helpers.is_in_interval(tx_output_fund.fee, expected_fee_fund, frac=0.15)
assert helpers.is_in_interval(tx_output_redeem.fee, expected_fee_redeem, frac=0.15)
plutus_common.check_plutus_costs(
plutus_costs=plutus_costs,
expected_costs=[execution_cost1, execution_cost2],
)
# check tx view
tx_view.check_tx_view(cluster_obj=cluster, tx_raw_output=tx_output_redeem)
# check transactions in db-sync
tx_redeem_record = dbsync_utils.check_tx(
cluster_obj=cluster, tx_raw_output=tx_output_redeem
)
if tx_redeem_record:
dbsync_utils.check_plutus_costs(
redeemer_records=tx_redeem_record.redeemers, cost_records=plutus_costs
)
@allure.link(helpers.get_vcs_link())
def test_always_fails(
self,
cluster: clusterlib.ClusterLib,
payment_addrs: List[clusterlib.AddressRecord],
):
"""Test locking a Tx output with a Plutus script and spending the locked UTxO.
Uses `cardano-cli transaction build` command for building the transactions.
Test with "always fails" script that fails for all datum / redeemer values.
* create a Tx output with a datum hash at the script address
* check that the expected amount was locked at the script address
* try to spend the locked UTxO
* check that the expected error was raised
"""
__: Any # mypy workaround
temp_template = common.get_test_id(cluster)
plutus_op = plutus_common.PlutusOp(
script_file=plutus_common.ALWAYS_FAILS_PLUTUS_V1,
datum_file=plutus_common.DATUM_42_TYPED,
redeemer_file=plutus_common.REDEEMER_42_TYPED,
execution_cost=plutus_common.ALWAYS_FAILS_COST,
)
script_utxos, collateral_utxos, tx_output_fund = _build_fund_script(
temp_template=temp_template,
cluster_obj=cluster,
payment_addr=payment_addrs[0],
dst_addr=payment_addrs[1],
plutus_op=plutus_op,
)
err, __, __ = _build_spend_locked_txin(
temp_template=temp_template,
cluster_obj=cluster,
payment_addr=payment_addrs[0],
dst_addr=payment_addrs[1],
script_utxos=script_utxos,
collateral_utxos=collateral_utxos,
plutus_op=plutus_op,
amount=2_000_000,
expect_failure=True,
)
assert "The Plutus script evaluation failed" in err, err