-
Notifications
You must be signed in to change notification settings - Fork 721
/
Transaction.hs
1478 lines (1309 loc) · 68.2 KB
/
Transaction.hs
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
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
module Cardano.CLI.Shelley.Run.Transaction
( ShelleyTxCmdError(..)
, renderShelleyTxCmdError
, runTransactionCmd
, readFileTx
, readProtocolParametersSourceSpec
, toTxOutInAnyEra
) where
import Control.Monad (forM, forM_, void)
import Control.Monad.IO.Class (MonadIO (..))
import Control.Monad.Trans (MonadTrans (..))
import Control.Monad.Trans.Except (ExceptT)
import Control.Monad.Trans.Except.Extra (firstExceptT, hoistEither, hoistMaybe, left,
newExceptT, onLeft, onNothing)
import Data.Aeson.Encode.Pretty (encodePretty)
import Data.Bifunctor (Bifunctor (..))
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Data ((:~:) (..))
import Data.Foldable (Foldable (..))
import Data.Function ((&))
import qualified Data.List as List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (catMaybes, fromMaybe)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import Data.Type.Equality (TestEquality (..))
import qualified System.IO as IO
import Cardano.Api
import Cardano.Api.Byron hiding (SomeByronSigningKey (..))
import Cardano.Api.Shelley
import Cardano.CLI.Helpers (printWarning)
import Cardano.CLI.Run.Friendly (friendlyTxBS, friendlyTxBodyBS)
import Cardano.CLI.Shelley.Output
import Cardano.CLI.Shelley.Parsers
import Cardano.CLI.Shelley.Run.Genesis
import Cardano.CLI.Shelley.Run.Read
import Cardano.CLI.Shelley.Run.Validate
import Cardano.CLI.Types
import qualified Control.Monad.Oops as OO
import Ouroboros.Consensus.Cardano.Block (EraMismatch (..))
import qualified Ouroboros.Network.Protocol.LocalTxSubmission.Client as Net.Tx
{- HLINT ignore "Use let" -}
data ShelleyTxCmdError
= ShelleyTxCmdMetadataError MetadataError
| ShelleyTxCmdScriptWitnessError ScriptWitnessError
| ShelleyTxCmdProtocolParamsError ProtocolParamsError
| ShelleyTxCmdScriptFileError (FileError ScriptDecodeError)
| ShelleyTxCmdReadTextViewFileError !(FileError TextEnvelopeError)
| ShelleyTxCmdReadWitnessSigningDataError !ReadWitnessSigningDataError
| ShelleyTxCmdRequiredSignerByronKeyError !SigningKeyFile
| ShelleyTxCmdWriteFileError !(FileError ())
| ShelleyTxCmdEraConsensusModeMismatch
!(Maybe FilePath)
!AnyConsensusMode
!AnyCardanoEra
-- ^ Era
| ShelleyTxCmdBootstrapWitnessError !ShelleyBootstrapWitnessError
| ShelleyTxCmdSocketEnvError !EnvSocketError
| ShelleyTxCmdTxSubmitError !Text
| ShelleyTxCmdTxSubmitErrorEraMismatch !EraMismatch
| ShelleyTxCmdTxFeatureMismatch !AnyCardanoEra !TxFeature
| ShelleyTxCmdTxBodyError !TxBodyError
| ShelleyTxCmdNotImplemented !Text
| ShelleyTxCmdWitnessEraMismatch !AnyCardanoEra !AnyCardanoEra !WitnessFile
| ShelleyTxCmdScriptLanguageNotSupportedInEra !AnyScriptLanguage !AnyCardanoEra
| ShelleyTxCmdReferenceScriptsNotSupportedInEra !AnyCardanoEra
| ShelleyTxCmdPolicyIdsMissing ![PolicyId]
| ShelleyTxCmdPolicyIdsExcess ![PolicyId]
| ShelleyTxCmdUnsupportedMode !AnyConsensusMode
| ShelleyTxCmdByronEra
| ShelleyTxCmdEraConsensusModeMismatchTxBalance
!TxBuildOutputOptions
!AnyConsensusMode
!AnyCardanoEra
| ShelleyTxCmdBalanceTxBody !TxBodyErrorAutoBalance
| ShelleyTxCmdTxInsDoNotExist !TxInsExistError
| ShelleyTxCmdMinimumUTxOErr !MinimumUTxOError
| ShelleyTxCmdPParamsErr !ProtocolParametersError
| ShelleyTxCmdTextEnvCddlError
!(FileError TextEnvelopeError)
!(FileError TextEnvelopeCddlError)
| ShelleyTxCmdTxExecUnitsErr !TransactionValidityError
| ShelleyTxCmdPlutusScriptCostErr !PlutusScriptCostError
| ShelleyTxCmdPParamExecutionUnitsNotAvailable
| ShelleyTxCmdPlutusScriptsRequireCardanoMode
| ShelleyTxCmdProtocolParametersNotPresentInTxBody
| ShelleyTxCmdTxEraCastErr EraCastError
| ShelleyTxCmdQueryConvenienceError !QueryConvenienceError
| ShelleyTxCmdQueryNotScriptLocked !ScriptLockedTxInsError
| ShelleyTxCmdScriptDataError !ScriptDataError
| ShelleyTxCmdCddlError CddlError
| ShelleyTxCmdCddlWitnessError CddlWitnessError
| ShelleyTxCmdRequiredSignerError RequiredSignerError
-- Validation errors
| ShelleyTxCmdAuxScriptsValidationError TxAuxScriptsValidationError
| ShelleyTxCmdTotalCollateralValidationError TxTotalCollateralValidationError
| ShelleyTxCmdReturnCollateralValidationError TxReturnCollateralValidationError
| ShelleyTxCmdTxFeeValidationError TxFeeValidationError
| ShelleyTxCmdTxValidityLowerBoundValidationError TxValidityLowerBoundValidationError
| ShelleyTxCmdTxValidityUpperBoundValidationError TxValidityUpperBoundValidationError
| ShelleyTxCmdRequiredSignersValidationError TxRequiredSignersValidationError
| ShelleyTxCmdProtocolParametersValidationError TxProtocolParametersValidationError
| ShelleyTxCmdTxWithdrawalsValidationError TxWithdrawalsValidationError
| ShelleyTxCmdTxCertificatesValidationError TxCertificatesValidationError
| ShelleyTxCmdTxUpdateProposalValidationError TxUpdateProposalValidationError
| ShelleyTxCmdScriptValidityValidationError TxScriptValidityValidationError
| ShelleyTxCmdUnsupportedNtcVersion !UnsupportedNtcVersionError
renderShelleyTxCmdError :: ShelleyTxCmdError -> Text
renderShelleyTxCmdError err =
case err of
ShelleyTxCmdReadTextViewFileError fileErr -> Text.pack (displayError fileErr)
ShelleyTxCmdScriptFileError fileErr -> Text.pack (displayError fileErr)
ShelleyTxCmdReadWitnessSigningDataError witSignDataErr ->
renderReadWitnessSigningDataError witSignDataErr
ShelleyTxCmdRequiredSignerByronKeyError (SigningKeyFile fp) ->
"Byron key witness was used as a required signer: " <> textShow fp
ShelleyTxCmdWriteFileError fileErr -> Text.pack (displayError fileErr)
ShelleyTxCmdSocketEnvError envSockErr -> renderEnvSocketError envSockErr
ShelleyTxCmdTxSubmitError res -> "Error while submitting tx: " <> res
ShelleyTxCmdTxSubmitErrorEraMismatch EraMismatch{ledgerEraName, otherEraName} ->
"The era of the node and the tx do not match. " <>
"The node is running in the " <> ledgerEraName <>
" era, but the transaction is for the " <> otherEraName <> " era."
ShelleyTxCmdBootstrapWitnessError sbwErr ->
renderShelleyBootstrapWitnessError sbwErr
ShelleyTxCmdTxFeatureMismatch era TxFeatureImplicitFees ->
"An explicit transaction fee must be specified for " <>
renderEra era <> " era transactions."
ShelleyTxCmdTxFeatureMismatch (AnyCardanoEra ShelleyEra)
TxFeatureValidityNoUpperBound ->
"A TTL must be specified for Shelley era transactions."
ShelleyTxCmdTxFeatureMismatch era feature ->
renderFeature feature <> " cannot be used for " <> renderEra era <>
" era transactions."
ShelleyTxCmdTxBodyError err' ->
"Transaction validaton error: " <> Text.pack (displayError err')
ShelleyTxCmdNotImplemented msg ->
"Feature not yet implemented: " <> msg
ShelleyTxCmdWitnessEraMismatch era era' (WitnessFile file) ->
"The era of a witness does not match the era of the transaction. " <>
"The transaction is for the " <> renderEra era <> " era, but the " <>
"witness in " <> textShow file <> " is for the " <> renderEra era' <> " era."
ShelleyTxCmdScriptLanguageNotSupportedInEra (AnyScriptLanguage lang) era ->
"The script language " <> textShow lang <> " is not supported in the " <>
renderEra era <> " era."
ShelleyTxCmdEraConsensusModeMismatch fp mode era ->
"Submitting " <> renderEra era <> " era transaction (" <> textShow fp <>
") is not supported in the " <> renderMode mode <> " consensus mode."
ShelleyTxCmdPolicyIdsMissing policyids -> mconcat
[ "The \"--mint\" flag specifies an asset with a policy Id, but no "
, "corresponding monetary policy script has been provided as a witness "
, "(via the \"--mint-script-file\" flag). The policy Id in question is: "
, Text.intercalate ", " (map serialiseToRawBytesHexText policyids)
]
ShelleyTxCmdPolicyIdsExcess policyids -> mconcat
[ "A script provided to witness minting does not correspond to the policy "
, "id of any asset specified in the \"--mint\" field. The script hash is: "
, Text.intercalate ", " (map serialiseToRawBytesHexText policyids)
]
ShelleyTxCmdUnsupportedMode mode -> "Unsupported mode: " <> renderMode mode
ShelleyTxCmdByronEra -> "This query cannot be used for the Byron era"
ShelleyTxCmdEraConsensusModeMismatchTxBalance fp mode era ->
"Cannot balance " <> renderEra era <> " era transaction body (" <> textShow fp <>
") because is not supported in the " <> renderMode mode <> " consensus mode."
ShelleyTxCmdBalanceTxBody err' -> Text.pack $ displayError err'
ShelleyTxCmdTxInsDoNotExist e ->
renderTxInsExistError e
ShelleyTxCmdMinimumUTxOErr err' -> Text.pack $ displayError err'
ShelleyTxCmdPParamsErr err' -> Text.pack $ displayError err'
ShelleyTxCmdTextEnvCddlError textEnvErr cddlErr -> mconcat
[ "Failed to decode neither the cli's serialisation format nor the ledger's "
, "CDDL serialisation format. TextEnvelope error: " <> Text.pack (displayError textEnvErr) <> "\n"
, "TextEnvelopeCddl error: " <> Text.pack (displayError cddlErr)
]
ShelleyTxCmdTxExecUnitsErr err' -> Text.pack $ displayError err'
ShelleyTxCmdPlutusScriptCostErr err'-> Text.pack $ displayError err'
ShelleyTxCmdPParamExecutionUnitsNotAvailable -> mconcat
[ "Execution units not available in the protocol parameters. This is "
, "likely due to not being in the Alonzo era"
]
ShelleyTxCmdReferenceScriptsNotSupportedInEra (AnyCardanoEra era) ->
"TxCmd: Reference scripts not supported in era: " <> textShow era
ShelleyTxCmdTxEraCastErr (EraCastError value fromEra toEra) ->
"Unable to cast era from " <> textShow fromEra <> " to " <> textShow toEra <> " the value " <> textShow value
ShelleyTxCmdQueryConvenienceError e ->
renderQueryConvenienceError e
ShelleyTxCmdQueryNotScriptLocked e ->
renderNotScriptLockedTxInsError e
ShelleyTxCmdPlutusScriptsRequireCardanoMode ->
"Plutus scripts are only available in CardanoMode"
ShelleyTxCmdProtocolParametersNotPresentInTxBody ->
"Protocol parameters were not found in transaction body"
ShelleyTxCmdMetadataError e -> renderMetadataError e
ShelleyTxCmdScriptWitnessError e -> renderScriptWitnessError e
ShelleyTxCmdScriptDataError e -> renderScriptDataError e
ShelleyTxCmdProtocolParamsError e -> renderProtocolParamsError e
ShelleyTxCmdCddlError e -> Text.pack $ displayError e
ShelleyTxCmdCddlWitnessError e -> Text.pack $ displayError e
ShelleyTxCmdRequiredSignerError e -> Text.pack $ displayError e
-- Validation errors
ShelleyTxCmdAuxScriptsValidationError e ->
Text.pack $ displayError e
ShelleyTxCmdTotalCollateralValidationError e ->
Text.pack $ displayError e
ShelleyTxCmdReturnCollateralValidationError e ->
Text.pack $ displayError e
ShelleyTxCmdTxFeeValidationError e ->
Text.pack $ displayError e
ShelleyTxCmdTxValidityLowerBoundValidationError e ->
Text.pack $ displayError e
ShelleyTxCmdTxValidityUpperBoundValidationError e ->
Text.pack $ displayError e
ShelleyTxCmdRequiredSignersValidationError e ->
Text.pack $ displayError e
ShelleyTxCmdProtocolParametersValidationError e ->
Text.pack $ displayError e
ShelleyTxCmdTxWithdrawalsValidationError e ->
Text.pack $ displayError e
ShelleyTxCmdTxCertificatesValidationError e ->
Text.pack $ displayError e
ShelleyTxCmdTxUpdateProposalValidationError e ->
Text.pack $ displayError e
ShelleyTxCmdScriptValidityValidationError e ->
Text.pack $ displayError e
ShelleyTxCmdUnsupportedNtcVersion (UnsupportedNtcVersionError minNtcVersion ntcVersion) ->
"Unsupported feature for the node-to-client protocol version.\n" <>
"This transaction requires at least " <> textShow minNtcVersion <> " but the node negotiated " <> textShow ntcVersion <> ".\n" <>
"Later node versions support later protocol versions (but development protocol versions are not enabled in the node by default)."
renderFeature :: TxFeature -> Text
renderFeature TxFeatureShelleyAddresses = "Shelley addresses"
renderFeature TxFeatureExplicitFees = "Explicit fees"
renderFeature TxFeatureImplicitFees = "Implicit fees"
renderFeature TxFeatureValidityLowerBound = "A validity lower bound"
renderFeature TxFeatureValidityUpperBound = "A validity upper bound"
renderFeature TxFeatureValidityNoUpperBound = "An absent validity upper bound"
renderFeature TxFeatureTxMetadata = "Transaction metadata"
renderFeature TxFeatureAuxScripts = "Auxiliary scripts"
renderFeature TxFeatureWithdrawals = "Reward account withdrawals"
renderFeature TxFeatureCertificates = "Certificates"
renderFeature TxFeatureMintValue = "Asset minting"
renderFeature TxFeatureMultiAssetOutputs = "Multi-Asset outputs"
renderFeature TxFeatureScriptWitnesses = "Script witnesses"
renderFeature TxFeatureShelleyKeys = "Shelley keys"
renderFeature TxFeatureCollateral = "Collateral inputs"
renderFeature TxFeatureProtocolParameters = "Protocol parameters"
renderFeature TxFeatureTxOutDatum = "Transaction output datums"
renderFeature TxFeatureScriptValidity = "Script validity"
renderFeature TxFeatureExtraKeyWits = "Required signers"
renderFeature TxFeatureInlineDatums = "Inline datums"
renderFeature TxFeatureTotalCollateral = "Total collateral"
renderFeature TxFeatureReferenceInputs = "Reference inputs"
renderFeature TxFeatureReturnCollateral = "Return collateral"
runTransactionCmd :: TransactionCmd -> ExceptT ShelleyTxCmdError IO ()
runTransactionCmd cmd =
case cmd of
TxBuild era consensusModeParams nid mScriptValidity mOverrideWits txins readOnlyRefIns
reqSigners txinsc mReturnColl mTotCollateral txouts changeAddr mValue mLowBound
mUpperBound certs wdrls metadataSchema scriptFiles metadataFiles mPparams
mUpProp outputOptions -> do
runTxBuildCmd era consensusModeParams nid mScriptValidity mOverrideWits txins readOnlyRefIns
reqSigners txinsc mReturnColl mTotCollateral txouts changeAddr mValue mLowBound
mUpperBound certs wdrls metadataSchema scriptFiles metadataFiles mPparams
mUpProp outputOptions
TxBuildRaw era mScriptValidity txins readOnlyRefIns txinsc mReturnColl
mTotColl reqSigners txouts mValue mLowBound mUpperBound fee certs wdrls
metadataSchema scriptFiles metadataFiles mpparams mUpProp out -> do
runTxBuildRawCmd era mScriptValidity txins readOnlyRefIns txinsc mReturnColl
mTotColl reqSigners txouts mValue mLowBound mUpperBound fee certs wdrls
metadataSchema scriptFiles metadataFiles mpparams mUpProp out
TxSign txinfile skfiles network txoutfile ->
runTxSign txinfile skfiles network txoutfile
TxSubmit anyConsensusModeParams network txFp ->
runTxSubmit anyConsensusModeParams network txFp
TxCalculateMinFee txbody mnw pGenesisOrParamsFile nInputs nOutputs
nShelleyKeyWitnesses nByronKeyWitnesses ->
runTxCalculateMinFee txbody mnw pGenesisOrParamsFile nInputs nOutputs
nShelleyKeyWitnesses nByronKeyWitnesses
TxCalculateMinRequiredUTxO era pParamSpec txOuts -> runTxCalculateMinRequiredUTxO era pParamSpec txOuts
TxHashScriptData scriptDataOrFile -> runTxHashScriptData scriptDataOrFile
TxGetTxId txinfile -> runTxGetTxId txinfile
TxView txinfile -> runTxView txinfile
TxMintedPolicyId sFile -> runTxCreatePolicyId sFile
TxCreateWitness txBodyfile witSignData mbNw outFile ->
runTxCreateWitness txBodyfile witSignData mbNw outFile
TxAssembleTxBodyWitness txBodyFile witnessFile outFile ->
runTxSignWitness txBodyFile witnessFile outFile
-- ----------------------------------------------------------------------------
-- Building transactions
--
runTxBuildCmd
:: AnyCardanoEra
-> AnyConsensusModeParams
-> NetworkId
-> Maybe ScriptValidity
-> Maybe Word -- ^ Override the required number of tx witnesses
-> [(TxIn, Maybe (ScriptWitnessFiles WitCtxTxIn))] -- ^ Transaction inputs with optional spending scripts
-> [TxIn] -- ^ Read only reference inputs
-> [RequiredSigner] -- ^ Required signers
-> [TxIn] -- ^ Transaction inputs for collateral, only key witnesses, no scripts.
-> Maybe TxOutAnyEra -- ^ Return collateral
-> Maybe Lovelace -- ^ Total collateral
-> [TxOutAnyEra]
-> TxOutChangeAddress
-> Maybe (Value, [ScriptWitnessFiles WitCtxMint])
-> Maybe SlotNo -- ^ Validity lower bound
-> Maybe SlotNo -- ^ Validity upper bound
-> [(CertificateFile, Maybe (ScriptWitnessFiles WitCtxStake))]
-> [(StakeAddress, Lovelace, Maybe (ScriptWitnessFiles WitCtxStake))] -- ^ Withdrawals with potential script witness
-> TxMetadataJsonSchema
-> [ScriptFile]
-> [MetadataFile]
-> Maybe ProtocolParamsSourceSpec
-> Maybe UpdateProposalFile
-> TxBuildOutputOptions
-> ExceptT ShelleyTxCmdError IO ()
runTxBuildCmd
(AnyCardanoEra cEra) consensusModeParams@(AnyConsensusModeParams cModeParams) nid mScriptValidity mOverrideWits txins readOnlyRefIns
reqSigners txinsc mReturnColl mTotCollateral txouts changeAddr mValue mLowBound
mUpperBound certs wdrls metadataSchema scriptFiles metadataFiles mPparams mUpProp outputOptions = do
-- The user can specify an era prior to the era that the node is currently in.
-- We cannot use the user specified era to construct a query against a node because it may differ
-- from the node's era and this will result in the 'QueryEraMismatch' failure.
SocketPath sockPath <- lift readEnvSocketPath & onLeft (left . ShelleyTxCmdSocketEnvError)
let localNodeConnInfo = LocalNodeConnectInfo
{ localConsensusModeParams = cModeParams
, localNodeNetworkId = nid
, localNodeSocketPath = sockPath
}
AnyCardanoEra nodeEra <- lift (determineEra cModeParams localNodeConnInfo)
& onLeft (left . ShelleyTxCmdQueryConvenienceError . AcqFailure)
inputsAndMaybeScriptWits <- firstExceptT ShelleyTxCmdScriptWitnessError $ readScriptWitnessFiles cEra txins
certFilesAndMaybeScriptWits <- firstExceptT ShelleyTxCmdScriptWitnessError $ readScriptWitnessFiles cEra certs
certsAndMaybeScriptWits <- sequence
[ fmap (,mSwit) (firstExceptT ShelleyTxCmdReadTextViewFileError . newExceptT $
readFileTextEnvelope AsCertificate certFile)
| (CertificateFile certFile, mSwit) <- certFilesAndMaybeScriptWits
]
withdrawalsAndMaybeScriptWits <- firstExceptT ShelleyTxCmdScriptWitnessError
$ readScriptWitnessFilesThruple cEra wdrls
txMetadata <- firstExceptT ShelleyTxCmdMetadataError
. newExceptT $ readTxMetadata cEra metadataSchema metadataFiles
valuesWithScriptWits <- readValueScriptWitnesses cEra $ fromMaybe (mempty, []) mValue
scripts <- firstExceptT ShelleyTxCmdScriptFileError $
mapM (readFileScriptInAnyLang . unScriptFile) scriptFiles
txAuxScripts <- hoistEither $ first ShelleyTxCmdAuxScriptsValidationError $ validateTxAuxScripts cEra scripts
mpparams <- forM mPparams $ \ppFp ->
firstExceptT ShelleyTxCmdProtocolParamsError (readProtocolParametersSourceSpec ppFp)
mProp <- forM mUpProp $ \(UpdateProposalFile upFp) ->
firstExceptT ShelleyTxCmdReadTextViewFileError (newExceptT $ readFileTextEnvelope AsUpdateProposal upFp)
requiredSigners <- mapM (firstExceptT ShelleyTxCmdRequiredSignerError . newExceptT . readRequiredSigner) reqSigners
mReturnCollateral <- forM mReturnColl $ toTxOutInAnyEra cEra
txOuts <- mapM (toTxOutInAnyEra cEra) txouts
-- the same collateral input can be used for several plutus scripts
let filteredTxinsc = Set.toList $ Set.fromList txinsc
-- We need to construct the txBodycontent outside of runTxBuild
BalancedTxBody txBodycontent balancedTxBody _ _
<- runTxBuild cEra consensusModeParams nid mScriptValidity inputsAndMaybeScriptWits readOnlyRefIns filteredTxinsc
mReturnCollateral mTotCollateral txOuts changeAddr valuesWithScriptWits mLowBound
mUpperBound certsAndMaybeScriptWits withdrawalsAndMaybeScriptWits
requiredSigners txAuxScripts txMetadata mpparams mProp mOverrideWits outputOptions
let allReferenceInputs = getAllReferenceInputs
inputsAndMaybeScriptWits
(snd valuesWithScriptWits)
certsAndMaybeScriptWits
withdrawalsAndMaybeScriptWits
readOnlyRefIns
let inputsThatRequireWitnessing = [input | (input,_) <- inputsAndMaybeScriptWits]
allTxInputs = inputsThatRequireWitnessing ++ allReferenceInputs ++ filteredTxinsc
-- TODO: Calculating the script cost should live as a different command.
-- Why? Because then we can simply read a txbody and figure out
-- the script cost vs having to build the tx body each time
case outputOptions of
OutputScriptCostOnly fp -> do
let BuildTxWith mTxProtocolParams = txProtocolParams txBodycontent
pparams <- pure mTxProtocolParams & onNothing (left ShelleyTxCmdProtocolParametersNotPresentInTxBody)
executionUnitPrices <- pure (protocolParamPrices pparams) & onNothing (left ShelleyTxCmdPParamExecutionUnitsNotAvailable)
let consensusMode = consensusModeOnly cModeParams
bpp = bundleProtocolParams cEra pparams
case consensusMode of
CardanoMode -> do
(nodeEraUTxO, _, eraHistory, systemStart, _)
<- queryStateForBalancedTx_ nodeEra nid allTxInputs
& handleQueryConvenienceErrors_
& OO.runOopsInExceptT @QueryConvenienceError
& firstExceptT ShelleyTxCmdQueryConvenienceError
-- Why do we cast the era? The user can specify an era prior to the era that the node is currently in.
-- We cannot use the user specified era to construct a query against a node because it may differ
-- from the node's era and this will result in the 'QueryEraMismatch' failure.
txEraUtxo <- pure (eraCast cEra nodeEraUTxO) & onLeft (left . ShelleyTxCmdTxEraCastErr)
scriptExecUnitsMap <-
firstExceptT ShelleyTxCmdTxExecUnitsErr $ hoistEither
$ evaluateTransactionExecutionUnits
systemStart (toLedgerEpochInfo eraHistory)
bpp txEraUtxo balancedTxBody
scriptCostOutput <-
firstExceptT ShelleyTxCmdPlutusScriptCostErr $ hoistEither
$ renderScriptCosts
txEraUtxo
executionUnitPrices
(collectTxBodyScriptWitnesses txBodycontent)
scriptExecUnitsMap
liftIO $ LBS.writeFile fp $ encodePretty scriptCostOutput
_ -> left ShelleyTxCmdPlutusScriptsRequireCardanoMode
OutputTxBodyOnly (TxBodyFile fpath) ->
let noWitTx = makeSignedTransaction [] balancedTxBody
in lift (writeTxFileTextEnvelopeCddl fpath noWitTx)
& onLeft (left . ShelleyTxCmdWriteFileError)
runTxBuildRawCmd
:: AnyCardanoEra
-> Maybe ScriptValidity
-> [(TxIn, Maybe (ScriptWitnessFiles WitCtxTxIn))]
-> [TxIn] -- ^ Read only reference inputs
-> [TxIn] -- ^ Transaction inputs for collateral, only key witnesses, no scripts.
-> Maybe TxOutAnyEra
-> Maybe Lovelace -- ^ Total collateral
-> [RequiredSigner]
-> [TxOutAnyEra]
-> Maybe (Value, [ScriptWitnessFiles WitCtxMint]) -- ^ Multi-Asset value with script witness
-> Maybe SlotNo -- ^ Validity lower bound
-> Maybe SlotNo -- ^ Validity upper bound
-> Maybe Lovelace -- ^ Tx fee
-> [(CertificateFile, Maybe (ScriptWitnessFiles WitCtxStake))]
-> [(StakeAddress, Lovelace, Maybe (ScriptWitnessFiles WitCtxStake))]
-> TxMetadataJsonSchema
-> [ScriptFile]
-> [MetadataFile]
-> Maybe ProtocolParamsSourceSpec
-> Maybe UpdateProposalFile
-> TxBodyFile
-> ExceptT ShelleyTxCmdError IO ()
runTxBuildRawCmd
(AnyCardanoEra cEra) mScriptValidity txins readOnlyRefIns txinsc mReturnColl
mTotColl reqSigners txouts mValue mLowBound mUpperBound fee certs wdrls
metadataSchema scriptFiles metadataFiles mpparams mUpProp (TxBodyFile out) = do
inputsAndMaybeScriptWits <- firstExceptT ShelleyTxCmdScriptWitnessError
$ readScriptWitnessFiles cEra txins
certFilesAndMaybeScriptWits <- firstExceptT ShelleyTxCmdScriptWitnessError
$ readScriptWitnessFiles cEra certs
certsAndMaybeScriptWits <- sequence
[ fmap (,mSwit) (firstExceptT ShelleyTxCmdReadTextViewFileError . newExceptT $
readFileTextEnvelope AsCertificate certFile)
| (CertificateFile certFile, mSwit) <- certFilesAndMaybeScriptWits
]
withdrawalsAndMaybeScriptWits <- firstExceptT ShelleyTxCmdScriptWitnessError
$ readScriptWitnessFilesThruple cEra wdrls
txMetadata <- firstExceptT ShelleyTxCmdMetadataError
. newExceptT $ readTxMetadata cEra metadataSchema metadataFiles
valuesWithScriptWits <- readValueScriptWitnesses cEra $ fromMaybe (mempty, []) mValue
scripts <- firstExceptT ShelleyTxCmdScriptFileError $
mapM (readFileScriptInAnyLang . unScriptFile) scriptFiles
txAuxScripts <- hoistEither $ first ShelleyTxCmdAuxScriptsValidationError $ validateTxAuxScripts cEra scripts
pparams <- forM mpparams $ \ppFp ->
firstExceptT ShelleyTxCmdProtocolParamsError (readProtocolParametersSourceSpec ppFp)
mProp <- forM mUpProp $ \(UpdateProposalFile upFp) ->
firstExceptT ShelleyTxCmdReadTextViewFileError (newExceptT $ readFileTextEnvelope AsUpdateProposal upFp)
requiredSigners <- mapM (firstExceptT ShelleyTxCmdRequiredSignerError . newExceptT . readRequiredSigner) reqSigners
mReturnCollateral <- forM mReturnColl $ toTxOutInAnyEra cEra
txOuts <- mapM (toTxOutInAnyEra cEra) txouts
-- the same collateral input can be used for several plutus scripts
let filteredTxinsc = Set.toList $ Set.fromList txinsc
txBody <- hoistEither $ runTxBuildRaw cEra mScriptValidity inputsAndMaybeScriptWits readOnlyRefIns filteredTxinsc
mReturnCollateral mTotColl txOuts mLowBound mUpperBound fee valuesWithScriptWits
certsAndMaybeScriptWits withdrawalsAndMaybeScriptWits requiredSigners txAuxScripts
txMetadata pparams mProp
let noWitTx = makeSignedTransaction [] txBody
lift (getIsCardanoEraConstraint cEra $ writeTxFileTextEnvelopeCddl out noWitTx)
& onLeft (left . ShelleyTxCmdWriteFileError)
runTxBuildRaw
:: CardanoEra era
-> Maybe ScriptValidity
-- ^ Mark script as expected to pass or fail validation
-> [(TxIn, Maybe (ScriptWitness WitCtxTxIn era))]
-- ^ TxIn with potential script witness
-> [TxIn]
-- ^ Read only reference inputs
-> [TxIn]
-- ^ TxIn for collateral
-> Maybe (TxOut CtxTx era)
-- ^ Return collateral
-> Maybe Lovelace
-- ^ Total collateral
-> [TxOut CtxTx era]
-> Maybe SlotNo
-- ^ Tx lower bound
-> Maybe SlotNo
-- ^ Tx upper bound
-> Maybe Lovelace
-- ^ Tx fee
-> (Value, [ScriptWitness WitCtxMint era])
-- ^ Multi-Asset value(s)
-> [(Certificate, Maybe (ScriptWitness WitCtxStake era))]
-- ^ Certificate with potential script witness
-> [(StakeAddress, Lovelace, Maybe (ScriptWitness WitCtxStake era))]
-> [Hash PaymentKey]
-- ^ Required signers
-> TxAuxScripts era
-> TxMetadataInEra era
-> Maybe ProtocolParameters
-> Maybe UpdateProposal
-> Either ShelleyTxCmdError (TxBody era)
runTxBuildRaw era
mScriptValidity inputsAndMaybeScriptWits
readOnlyRefIns txinsc
mReturnCollateral mTotCollateral txouts
mLowerBound mUpperBound
mFee valuesWithScriptWits
certsAndMaybeSriptWits withdrawals reqSigners
txAuxScripts txMetadata mpparams mUpdateProp = do
let allReferenceInputs = getAllReferenceInputs
inputsAndMaybeScriptWits
(snd valuesWithScriptWits)
certsAndMaybeSriptWits
withdrawals
readOnlyRefIns
validatedCollateralTxIns <- validateTxInsCollateral era txinsc
validatedRefInputs <- validateTxInsReference era allReferenceInputs
validatedTotCollateral
<- first ShelleyTxCmdTotalCollateralValidationError $ validateTxTotalCollateral era mTotCollateral
validatedRetCol
<- first ShelleyTxCmdReturnCollateralValidationError $ validateTxReturnCollateral era mReturnCollateral
validatedFee
<- first ShelleyTxCmdTxFeeValidationError $ validateTxFee era mFee
validatedBounds <- (,) <$> first ShelleyTxCmdTxValidityLowerBoundValidationError (validateTxValidityLowerBound era mLowerBound)
<*> first ShelleyTxCmdTxValidityUpperBoundValidationError (validateTxValidityUpperBound era mUpperBound)
validatedReqSigners
<- first ShelleyTxCmdRequiredSignersValidationError $ validateRequiredSigners era reqSigners
validatedPParams
<- first ShelleyTxCmdProtocolParametersValidationError $ validateProtocolParameters era mpparams
validatedTxWtdrwls
<- first ShelleyTxCmdTxWithdrawalsValidationError $ validateTxWithdrawals era withdrawals
validatedTxCerts
<- first ShelleyTxCmdTxCertificatesValidationError $ validateTxCertificates era certsAndMaybeSriptWits
validatedTxUpProp
<- first ShelleyTxCmdTxUpdateProposalValidationError $ validateTxUpdateProposal era mUpdateProp
validatedMintValue
<- createTxMintValue era valuesWithScriptWits
validatedTxScriptValidity
<- first ShelleyTxCmdScriptValidityValidationError $ validateTxScriptValidity era mScriptValidity
let txBodyContent = TxBodyContent
(validateTxIns inputsAndMaybeScriptWits)
validatedCollateralTxIns
validatedRefInputs
txouts
validatedTotCollateral
validatedRetCol
validatedFee
validatedBounds
txMetadata
txAuxScripts
validatedReqSigners
validatedPParams
validatedTxWtdrwls
validatedTxCerts
validatedTxUpProp
validatedMintValue
validatedTxScriptValidity
first ShelleyTxCmdTxBodyError $
getIsCardanoEraConstraint era $ createAndValidateTransactionBody txBodyContent
runTxBuild
:: CardanoEra era
-> AnyConsensusModeParams
-> NetworkId
-> Maybe ScriptValidity
-- ^ Mark script as expected to pass or fail validation
-> [(TxIn, Maybe (ScriptWitness WitCtxTxIn era))]
-- ^ Read only reference inputs
-> [TxIn]
-- ^ TxIn with potential script witness
-> [TxIn]
-- ^ TxIn for collateral
-> Maybe (TxOut CtxTx era)
-- ^ Return collateral
-> Maybe Lovelace
-- ^ Total collateral
-> [TxOut CtxTx era]
-- ^ Normal outputs
-> TxOutChangeAddress
-- ^ A change output
-> (Value, [ScriptWitness WitCtxMint era])
-- ^ Multi-Asset value(s)
-> Maybe SlotNo
-- ^ Tx lower bound
-> Maybe SlotNo
-- ^ Tx upper bound
-> [(Certificate, Maybe (ScriptWitness WitCtxStake era))]
-- ^ Certificate with potential script witness
-> [(StakeAddress, Lovelace, Maybe (ScriptWitness WitCtxStake era))]
-> [Hash PaymentKey]
-- ^ Required signers
-> TxAuxScripts era
-> TxMetadataInEra era
-> Maybe ProtocolParameters
-> Maybe UpdateProposal
-> Maybe Word
-> TxBuildOutputOptions
-> ExceptT ShelleyTxCmdError IO (BalancedTxBody era)
runTxBuild era (AnyConsensusModeParams cModeParams) networkId mScriptValidity
inputsAndMaybeScriptWits readOnlyRefIns txinsc mReturnCollateral mTotCollateral txouts
(TxOutChangeAddress changeAddr) valuesWithScriptWits mLowerBound mUpperBound
certsAndMaybeScriptWits withdrawals reqSigners txAuxScripts txMetadata mpparams
mUpdatePropF mOverrideWits outputOptions = do
liftIO $ forM_ mpparams $ \_ ->
printWarning "'--protocol-params-file' for 'transaction build' is deprecated"
let consensusMode = consensusModeOnly cModeParams
dummyFee = Just $ Lovelace 0
inputsThatRequireWitnessing = [input | (input,_) <- inputsAndMaybeScriptWits]
-- Pure
let allReferenceInputs = getAllReferenceInputs
inputsAndMaybeScriptWits
(snd valuesWithScriptWits)
certsAndMaybeScriptWits
withdrawals readOnlyRefIns
validatedCollateralTxIns <- hoistEither $ validateTxInsCollateral era txinsc
validatedRefInputs <- hoistEither $ validateTxInsReference era allReferenceInputs
validatedTotCollateral
<- hoistEither $ first ShelleyTxCmdTotalCollateralValidationError $ validateTxTotalCollateral era mTotCollateral
validatedRetCol
<- hoistEither $ first ShelleyTxCmdReturnCollateralValidationError $ validateTxReturnCollateral era mReturnCollateral
dFee <- hoistEither $ first ShelleyTxCmdTxFeeValidationError $ validateTxFee era dummyFee
validatedBounds <- (,) <$> hoistEither (first ShelleyTxCmdTxValidityLowerBoundValidationError $ validateTxValidityLowerBound era mLowerBound)
<*> hoistEither (first ShelleyTxCmdTxValidityUpperBoundValidationError $ validateTxValidityUpperBound era mUpperBound)
validatedReqSigners <- hoistEither (first ShelleyTxCmdRequiredSignersValidationError $ validateRequiredSigners era reqSigners)
validatedTxWtdrwls <- hoistEither (first ShelleyTxCmdTxWithdrawalsValidationError $ validateTxWithdrawals era withdrawals)
validatedTxCerts <- hoistEither (first ShelleyTxCmdTxCertificatesValidationError $ validateTxCertificates era certsAndMaybeScriptWits)
validatedTxUpProp <- hoistEither (first ShelleyTxCmdTxUpdateProposalValidationError $ validateTxUpdateProposal era mUpdatePropF)
validatedMintValue <- hoistEither $ createTxMintValue era valuesWithScriptWits
validatedTxScriptValidity <- hoistEither (first ShelleyTxCmdScriptValidityValidationError $ validateTxScriptValidity era mScriptValidity)
case (consensusMode, cardanoEraStyle era) of
(CardanoMode, ShelleyBasedEra _sbe) -> do
void $ pure (toEraInMode era CardanoMode)
& onNothing (left (ShelleyTxCmdEraConsensusModeMismatchTxBalance outputOptions
(AnyConsensusMode CardanoMode) (AnyCardanoEra era)))
SocketPath sockPath <- lift readEnvSocketPath & onLeft (left . ShelleyTxCmdSocketEnvError)
let allTxInputs = inputsThatRequireWitnessing ++ allReferenceInputs ++ txinsc
localNodeConnInfo = LocalNodeConnectInfo
{ localConsensusModeParams = CardanoModeParams $ EpochSlots 21600
, localNodeNetworkId = networkId
, localNodeSocketPath = sockPath
}
AnyCardanoEra nodeEra <- lift (determineEra cModeParams localNodeConnInfo)
& onLeft (left . ShelleyTxCmdQueryConvenienceError . AcqFailure)
(nodeEraUTxO, pparams, eraHistory, systemStart, stakePools) <-
queryStateForBalancedTx_ nodeEra networkId allTxInputs
& handleQueryConvenienceErrors_
& OO.runOopsInExceptT @QueryConvenienceError
& firstExceptT ShelleyTxCmdQueryConvenienceError
validatedPParams <- hoistEither $ first ShelleyTxCmdProtocolParametersValidationError
$ validateProtocolParameters era (Just pparams)
let txBodyContent = TxBodyContent
(validateTxIns inputsAndMaybeScriptWits)
validatedCollateralTxIns
validatedRefInputs
txouts
validatedTotCollateral
validatedRetCol
dFee
validatedBounds
txMetadata
txAuxScripts
validatedReqSigners
validatedPParams
validatedTxWtdrwls
validatedTxCerts
validatedTxUpProp
validatedMintValue
validatedTxScriptValidity
firstExceptT ShelleyTxCmdTxInsDoNotExist
. hoistEither $ txInsExistInUTxO allTxInputs nodeEraUTxO
firstExceptT ShelleyTxCmdQueryNotScriptLocked
. hoistEither $ notScriptLockedTxIns txinsc nodeEraUTxO
cAddr <- pure (anyAddressInEra era changeAddr)
& onLeft (error $ "runTxBuild: Byron address used: " <> show changeAddr) -- should this throw instead?
-- Why do we cast the era? The user can specify an era prior to the era that the node is currently in.
-- We cannot use the user specified era to construct a query against a node because it may differ
-- from the node's era and this will result in the 'QueryEraMismatch' failure.
txEraUtxo <- pure (eraCast era nodeEraUTxO) & onLeft (left . ShelleyTxCmdTxEraCastErr)
balancedTxBody@(BalancedTxBody _ _ _ fee) <-
firstExceptT ShelleyTxCmdBalanceTxBody
. hoistEither
$ makeTransactionBodyAutoBalance systemStart (toLedgerEpochInfo eraHistory)
pparams stakePools txEraUtxo txBodyContent
cAddr mOverrideWits
liftIO $ putStrLn $ "Estimated transaction fee: " <> (show fee :: String)
return balancedTxBody
(CardanoMode, LegacyByronEra) -> left ShelleyTxCmdByronEra
(wrongMode, _) -> left (ShelleyTxCmdUnsupportedMode (AnyConsensusMode wrongMode))
-- ----------------------------------------------------------------------------
-- Transaction body validation and conversion
--
-- | An enumeration of era-dependent features where we have to check that it
-- is permissible to use this feature in this era.
--
data TxFeature = TxFeatureShelleyAddresses
| TxFeatureExplicitFees
| TxFeatureImplicitFees
| TxFeatureValidityLowerBound
| TxFeatureValidityUpperBound
| TxFeatureValidityNoUpperBound
| TxFeatureTxMetadata
| TxFeatureAuxScripts
| TxFeatureWithdrawals
| TxFeatureCertificates
| TxFeatureMintValue
| TxFeatureMultiAssetOutputs
| TxFeatureScriptWitnesses
| TxFeatureShelleyKeys
| TxFeatureCollateral
| TxFeatureProtocolParameters
| TxFeatureTxOutDatum
| TxFeatureScriptValidity
| TxFeatureExtraKeyWits
| TxFeatureInlineDatums
| TxFeatureTotalCollateral
| TxFeatureReferenceInputs
| TxFeatureReturnCollateral
deriving Show
txFeatureMismatch :: CardanoEra era
-> TxFeature
-> ExceptT ShelleyTxCmdError IO a
txFeatureMismatch era feature =
hoistEither . Left $ ShelleyTxCmdTxFeatureMismatch (anyCardanoEra era) feature
txFeatureMismatchPure :: CardanoEra era
-> TxFeature
-> Either ShelleyTxCmdError a
txFeatureMismatchPure era feature =
Left (ShelleyTxCmdTxFeatureMismatch (anyCardanoEra era) feature)
validateTxIns
:: [(TxIn, Maybe (ScriptWitness WitCtxTxIn era))]
-> [(TxIn, BuildTxWith BuildTx (Witness WitCtxTxIn era))]
validateTxIns = map convert
where
convert
:: (TxIn, Maybe (ScriptWitness WitCtxTxIn era))
-> (TxIn, BuildTxWith BuildTx (Witness WitCtxTxIn era))
convert (txin, mScriptWitness) =
case mScriptWitness of
Just sWit ->
(txin , BuildTxWith $ ScriptWitness ScriptWitnessForSpending sWit)
Nothing ->
(txin, BuildTxWith $ KeyWitness KeyWitnessForSpending)
validateTxInsCollateral :: CardanoEra era
-> [TxIn]
-> Either ShelleyTxCmdError (TxInsCollateral era)
validateTxInsCollateral _ [] = return TxInsCollateralNone
validateTxInsCollateral era txins =
case collateralSupportedInEra era of
Nothing -> txFeatureMismatchPure era TxFeatureCollateral
Just supported -> return (TxInsCollateral supported txins)
validateTxInsReference
:: CardanoEra era
-> [TxIn]
-> Either ShelleyTxCmdError (TxInsReference BuildTx era)
validateTxInsReference _ [] = return TxInsReferenceNone
validateTxInsReference era allRefIns =
case refInsScriptsAndInlineDatsSupportedInEra era of
Nothing -> txFeatureMismatchPure era TxFeatureReferenceInputs
Just supp -> return $ TxInsReference supp allRefIns
getAllReferenceInputs
:: [(TxIn, Maybe (ScriptWitness WitCtxTxIn era))]
-> [ScriptWitness WitCtxMint era]
-> [(Certificate , Maybe (ScriptWitness WitCtxStake era))]
-> [(StakeAddress, Lovelace, Maybe (ScriptWitness WitCtxStake era))]
-> [TxIn] -- ^ Read only reference inputs
-> [TxIn]
getAllReferenceInputs txins mintWitnesses certFiles withdrawals readOnlyRefIns = do
let txinsWitByRefInputs = [getReferenceInput sWit | (_, Just sWit) <- txins]
mintingRefInputs = map getReferenceInput mintWitnesses
certsWitByRefInputs = [getReferenceInput sWit | (_, Just sWit) <- certFiles]
withdrawalsWitByRefInputs = [getReferenceInput sWit | (_, _, Just sWit) <- withdrawals]
catMaybes $ concat [ txinsWitByRefInputs
, mintingRefInputs
, certsWitByRefInputs
, withdrawalsWitByRefInputs
, map Just readOnlyRefIns
]
where
getReferenceInput
:: ScriptWitness witctx era -> Maybe TxIn
getReferenceInput sWit =
case sWit of
PlutusScriptWitness _ _ (PReferenceScript refIn _) _ _ _ -> Just refIn
PlutusScriptWitness _ _ PScript{} _ _ _ -> Nothing
SimpleScriptWitness _ (SReferenceScript refIn _) -> Just refIn
SimpleScriptWitness _ SScript{} -> Nothing
toAddressInAnyEra
:: CardanoEra era
-> AddressAny
-> Either ShelleyTxCmdError (AddressInEra era)
toAddressInAnyEra era addrAny =
case addrAny of
AddressByron bAddr -> return (AddressInEra ByronAddressInAnyEra bAddr)
AddressShelley sAddr ->
case cardanoEraStyle era of
LegacyByronEra -> txFeatureMismatchPure era TxFeatureShelleyAddresses
ShelleyBasedEra era' ->
return (AddressInEra (ShelleyAddressInEra era') sAddr)
toTxOutValueInAnyEra
:: CardanoEra era
-> Value
-> Either ShelleyTxCmdError (TxOutValue era)
toTxOutValueInAnyEra era val =
case multiAssetSupportedInEra era of
Left adaOnlyInEra ->
case valueToLovelace val of
Just l -> return (TxOutAdaOnly adaOnlyInEra l)
Nothing -> txFeatureMismatchPure era TxFeatureMultiAssetOutputs
Right multiAssetInEra -> return (TxOutValue multiAssetInEra val)
toTxOutInAnyEra :: CardanoEra era
-> TxOutAnyEra
-> ExceptT ShelleyTxCmdError IO (TxOut CtxTx era)
toTxOutInAnyEra era (TxOutAnyEra addr' val' mDatumHash refScriptFp) = do
addr <- hoistEither $ toAddressInAnyEra era addr'
val <- hoistEither $ toTxOutValueInAnyEra era val'
(datum, refScript)
<- case (scriptDataSupportedInEra era, refInsScriptsAndInlineDatsSupportedInEra era) of
(Nothing, Nothing) -> pure (TxOutDatumNone, ReferenceScriptNone)
(Just sup, Nothing)->
(,) <$> toTxAlonzoDatum sup mDatumHash <*> pure ReferenceScriptNone
(Just sup, Just inlineDatumRefScriptSupp) ->
toTxDatumReferenceScriptBabbage sup inlineDatumRefScriptSupp mDatumHash refScriptFp
(Nothing, Just _) ->
-- TODO: Figure out how to make this state unrepresentable
error "toTxOutInAnyEra: Should not be possible that inline datums are allowed but datums are not"
pure $ TxOut addr val datum refScript
where
getReferenceScript
:: ReferenceScriptAnyEra
-> ReferenceTxInsScriptsInlineDatumsSupportedInEra era
-> ExceptT ShelleyTxCmdError IO (ReferenceScript era)
getReferenceScript ReferenceScriptAnyEraNone _ = return ReferenceScriptNone
getReferenceScript (ReferenceScriptAnyEra fp) supp = do
ReferenceScript supp
<$> firstExceptT ShelleyTxCmdScriptFileError (readFileScriptInAnyLang fp)
toTxDatumReferenceScriptBabbage
:: ScriptDataSupportedInEra era
-> ReferenceTxInsScriptsInlineDatumsSupportedInEra era
-> TxOutDatumAnyEra
-> ReferenceScriptAnyEra
-> ExceptT ShelleyTxCmdError IO (TxOutDatum CtxTx era, ReferenceScript era)
toTxDatumReferenceScriptBabbage sDataSupp inlineRefSupp cliDatum refScriptFp' = do
refScript <- getReferenceScript refScriptFp' inlineRefSupp
case cliDatum of
TxOutDatumByNone -> do
pure (TxOutDatumNone, refScript)
TxOutDatumByHashOnly dh -> do
pure (TxOutDatumHash sDataSupp dh, refScript)
TxOutDatumByHashOf fileOrSdata -> do
sData <- firstExceptT ShelleyTxCmdScriptDataError
$ readScriptDataOrFile fileOrSdata
pure (TxOutDatumHash sDataSupp $ hashScriptDataBytes sData, refScript)
TxOutDatumByValue fileOrSdata -> do
sData <- firstExceptT ShelleyTxCmdScriptDataError
$ readScriptDataOrFile fileOrSdata
pure (TxOutDatumInTx sDataSupp sData, refScript)
TxOutInlineDatumByValue fileOrSdata -> do
sData <- firstExceptT ShelleyTxCmdScriptDataError
$ readScriptDataOrFile fileOrSdata
pure (TxOutDatumInline inlineRefSupp sData, refScript)
toTxAlonzoDatum
:: ScriptDataSupportedInEra era
-> TxOutDatumAnyEra
-> ExceptT ShelleyTxCmdError IO (TxOutDatum CtxTx era)
toTxAlonzoDatum supp cliDatum =
case cliDatum of
TxOutDatumByHashOnly h -> pure (TxOutDatumHash supp h)
TxOutDatumByHashOf sDataOrFile -> do
sData <- firstExceptT ShelleyTxCmdScriptDataError
$ readScriptDataOrFile sDataOrFile
pure (TxOutDatumHash supp $ hashScriptDataBytes sData)
TxOutDatumByValue sDataOrFile -> do
sData <- firstExceptT ShelleyTxCmdScriptDataError
$ readScriptDataOrFile sDataOrFile
pure (TxOutDatumInTx supp sData)
TxOutInlineDatumByValue _ ->
txFeatureMismatch era TxFeatureInlineDatums
TxOutDatumByNone -> pure TxOutDatumNone
-- TODO: Currently we specify the policyId with the '--mint' option on the cli
-- and we added a separate '--policy-id' parser that parses the policy id for the
-- given reference input (since we don't have the script in this case). To avoid asking
-- for the policy id twice (in the build command) we can potentially query the UTxO and
-- access the script (and therefore the policy id).
createTxMintValue :: forall era. CardanoEra era
-> (Value, [ScriptWitness WitCtxMint era])
-> Either ShelleyTxCmdError (TxMintValue BuildTx era)
createTxMintValue era (val, scriptWitnesses) =
if List.null (valueToList val) && List.null scriptWitnesses
then return TxMintNone
else do
case multiAssetSupportedInEra era of
Left _ -> txFeatureMismatchPure era TxFeatureMintValue
Right supported -> do
-- The set of policy ids for which we need witnesses:
let witnessesNeededSet :: Set PolicyId