/
Transaction.hs
2649 lines (2436 loc) · 96 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 AllowAmbiguousTypes #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE RoleAnnotations #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
{- HLINT ignore "Use <$>" -}
{- HLINT ignore "Use camelCase" -}
-- |
-- Copyright: © 2020 IOHK
-- License: Apache-2.0
--
-- Working with Shelley transactions.
module Cardano.Wallet.Shelley.Transaction
( newTransactionLayer
-- * Updating SealedTx
, TxUpdate (..)
, noTxUpdate
, updateTx
, TxFeeUpdate (..)
-- * For balancing (To be moved)
, estimateKeyWitnessCount
, evaluateMinimumFee
, estimateSignedTxSize
, KeyWitnessCount (..)
, distributeSurplus
, distributeSurplusDelta
, sizeOfCoin
, maximumCostOfIncreasingCoin
, costOfIncreasingCoin
, assignScriptRedeemers
-- * Internals
, TxPayload (..)
, TxSkeleton (..)
, TxWitnessTag (..)
, TxWitnessTagFor (..)
, EraConstraints
, _decodeSealedTx
, mkDelegationCertificates
, calculateMinimumFee
, getFeePerByteFromWalletPParams
, estimateTxCost
, estimateTxSize
, mkByronWitness
, mkShelleyWitness
, mkTx
, mkTxSkeleton
, mkUnsignedTx
, txConstraints
, sizeOf_BootstrapWitnesses
) where
import Prelude
import Cardano.Address.Derivation
( XPrv, toXPub )
import Cardano.Address.Script
( Cosigner
, KeyHash (..)
, KeyRole (..)
, Script (..)
, ScriptHash (..)
, ScriptTemplate (..)
, foldScript
, toScriptHash
)
import Cardano.Api
( AnyCardanoEra (..)
, ByronEra
, CardanoEra (..)
, InAnyCardanoEra (..)
, IsShelleyBasedEra (..)
, NetworkId
, SerialiseAsCBOR (..)
, ShelleyBasedEra (..)
, ToCBOR
)
import Cardano.Binary
( serialize' )
import Cardano.Crypto.Wallet
( XPub )
import Cardano.Ledger.Alonzo.Tools
( evaluateTransactionExecutionUnits )
import Cardano.Ledger.Crypto
( DSIGN )
import Cardano.Ledger.Era
( Crypto )
import Cardano.Ledger.Shelley.API
( StrictMaybe (..) )
import Cardano.Slotting.EpochInfo
( EpochInfo, hoistEpochInfo )
import Cardano.Tx.Balance.Internal.CoinSelection
( SelectionOf (..)
, SelectionOutputTokenQuantityExceedsLimitError (..)
, SelectionSkeleton (..)
, selectionDelta
)
import Cardano.Wallet.Address.Derivation
( Depth (..), RewardAccount (..) )
import Cardano.Wallet.Address.Derivation.SharedKey
( replaceCosignersWithVerKeys )
import Cardano.Wallet.Address.Derivation.Shelley
( toRewardAccountRaw )
import Cardano.Wallet.Address.Discovery.Shared
( estimateMaxWitnessRequiredPerInput )
import Cardano.Wallet.Address.Keys.WalletKey
( getRawKey )
import Cardano.Wallet.Flavor
( KeyFlavorS )
import Cardano.Wallet.Primitive.Passphrase
( Passphrase (..) )
import Cardano.Wallet.Primitive.Types
( Certificate
, FeePolicy (..)
, LinearFunction (..)
, ProtocolParameters (..)
, TxParameters (..)
)
import Cardano.Wallet.Primitive.Types.Address
( Address (..) )
import Cardano.Wallet.Primitive.Types.Coin
( Coin (..) )
import Cardano.Wallet.Primitive.Types.Hash
( Hash (..) )
import Cardano.Wallet.Primitive.Types.Redeemer
( Redeemer, redeemerData )
import Cardano.Wallet.Primitive.Types.TokenBundle
( TokenBundle (..) )
import Cardano.Wallet.Primitive.Types.TokenMap
( AssetId (..), TokenMap )
import Cardano.Wallet.Primitive.Types.TokenPolicy
( TokenName (..) )
import Cardano.Wallet.Primitive.Types.TokenQuantity
( TokenQuantity (..) )
import Cardano.Wallet.Primitive.Types.Tx
( SealedTx (..)
, Tx (..)
, TxMetadata (..)
, cardanoTxIdeallyNoLaterThan
, sealedTxFromCardano'
, sealedTxFromCardanoBody
, withinEra
)
import Cardano.Wallet.Primitive.Types.Tx.Constraints
( TxConstraints (..), TxSize (..), txOutMaxTokenQuantity, txSizeDistance )
import Cardano.Wallet.Primitive.Types.Tx.TxIn
( TxIn (..) )
import Cardano.Wallet.Primitive.Types.Tx.TxOut
( TxOut (..) )
import Cardano.Wallet.Read.Primitive.Tx
( fromCardanoTx )
import Cardano.Wallet.Shelley.Compatibility
( cardanoCertKeysForWitnesses
, fromCardanoAddress
, fromCardanoLovelace
, fromCardanoWdrls
, toCardanoLovelace
, toCardanoPolicyId
, toCardanoSimpleScript
, toCardanoStakeCredential
, toCardanoTxIn
, toCardanoTxOut
, toCardanoValue
, toCostModelsAsArray
, toHDPayloadAddress
, toScriptPurpose
, toStakeKeyDeregCert
, toStakeKeyRegCert
, toStakePoolDlgCert
)
import Cardano.Wallet.Shelley.Compatibility.Ledger
( toBabbageTxOut, toConwayTxOut, toLedger, toWalletCoin, toWalletScript )
import Cardano.Wallet.Shelley.MinimumUTxO
( computeMinimumCoinForUTxO, isBelowMinimumCoinForUTxO )
import Cardano.Wallet.Transaction
( AnyExplicitScript (..)
, AnyScript (..)
, DelegationAction (..)
, ErrAssignRedeemers (..)
, ErrMkTransaction (..)
, ErrMoreSurplusNeeded (ErrMoreSurplusNeeded)
, ErrUpdateSealedTx (..)
, PreSelection (..)
, TokenMapWithScripts
, TransactionCtx (..)
, TransactionLayer (..)
, TxFeeAndChange (..)
, ValidityIntervalExplicit
, Withdrawal (..)
, WitnessCount (..)
, WitnessCountCtx (..)
, mapTxFeeAndChange
, withdrawalToCoin
)
import Cardano.Wallet.TxWitnessTag
( TxWitnessTag (..), TxWitnessTagFor (..) )
import Cardano.Wallet.Util
( HasCallStack, internalError, modifyM )
import Cardano.Wallet.Write.Tx
( FeePerByte (..)
, IsRecentEra (recentEra)
, KeyWitnessCount (..)
, RecentEra (..)
, fromCardanoUTxO
)
import Cardano.Wallet.Write.Tx.TimeTranslation
( TimeTranslation, epochInfo, systemStartTime )
import Codec.Serialise
( deserialiseOrFail )
import Control.Arrow
( left, second )
import Control.Monad
( forM, forM_, guard, when )
import Control.Monad.Trans.Class
( lift )
import Control.Monad.Trans.State.Strict
( StateT (..), execStateT, get, modify' )
import Data.Bifunctor
( bimap )
import Data.Function
( (&) )
import Data.Functor
( ($>), (<&>) )
import Data.Generics.Internal.VL.Lens
( view, (^.) )
import Data.Generics.Labels
()
import Data.IntCast
( intCast )
import Data.Map.Strict
( Map, (!) )
import Data.Maybe
( mapMaybe )
import Data.Quantity
( Quantity (..) )
import Data.Set
( Set )
import Data.Type.Equality
( type (==) )
import Data.Word
( Word64, Word8 )
import GHC.Generics
( Generic )
import Numeric.Natural
( Natural )
import Ouroboros.Consensus.Cardano.Block
( StandardConway )
import Ouroboros.Consensus.Shelley.Eras
( StandardBabbage )
import Ouroboros.Network.Block
( SlotNo )
import qualified Cardano.Address.Style.Shelley as CA
import qualified Cardano.Api as Cardano
import qualified Cardano.Api.Byron as Byron
import qualified Cardano.Api.Shelley as Cardano
import qualified Cardano.Chain.Common as Byron
import qualified Cardano.Crypto as CC
import qualified Cardano.Crypto.DSIGN as DSIGN
import qualified Cardano.Crypto.Hash.Class as Crypto
import qualified Cardano.Crypto.Wallet as Crypto.HD
import qualified Cardano.Ledger.Alonzo.Data as Alonzo
import qualified Cardano.Ledger.Alonzo.PlutusScriptApi as Alonzo
import qualified Cardano.Ledger.Alonzo.PParams as Alonzo
import qualified Cardano.Ledger.Alonzo.Scripts as Alonzo
import qualified Cardano.Ledger.Alonzo.Tx as Alonzo
import qualified Cardano.Ledger.Alonzo.TxWitness as Alonzo
import qualified Cardano.Ledger.Babbage.PParams as Babbage
import qualified Cardano.Ledger.Babbage.Tx as Babbage
import qualified Cardano.Ledger.Coin as Ledger
import qualified Cardano.Ledger.Conway.PParams as Conway
import qualified Cardano.Ledger.Conway.Tx as Conway
import qualified Cardano.Ledger.Conway.TxBody as Conway
import qualified Cardano.Ledger.Core as Ledger
import qualified Cardano.Ledger.Keys.Bootstrap as SL
import qualified Cardano.Ledger.Serialization as Ledger
import qualified Cardano.Wallet.Primitive.Types.Coin as Coin
import qualified Cardano.Wallet.Primitive.Types.TokenBundle as TokenBundle
import qualified Cardano.Wallet.Primitive.Types.TokenMap as TokenMap
import qualified Cardano.Wallet.Primitive.Types.Tx.TxOut as TxOut
import qualified Cardano.Wallet.Shelley.Compatibility as Compatibility
import qualified Cardano.Wallet.Write.Tx as Write
import qualified Codec.CBOR.Encoding as CBOR
import qualified Codec.CBOR.Write as CBOR
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import qualified Data.Foldable as F
import qualified Data.List as L
import qualified Data.Map as Map
import qualified Data.Map.Merge.Strict as Map
import qualified Data.Sequence.Strict as StrictSeq
import qualified Data.Set as Set
import qualified Data.Text as T
-- | Type encapsulating what we need to know to add things -- payloads,
-- certificates -- to a transaction.
--
-- Designed to allow us to have /one/ @mkTx@ which doesn't care whether we
-- include certificates or not.
data TxPayload era = TxPayload
{ _metadata :: Maybe Cardano.TxMetadata
-- ^ User or application-defined metadata to be included in the
-- transaction.
, _certificates :: [Cardano.Certificate]
-- ^ Certificates to be included in the transactions.
, _extraWitnesses :: Cardano.TxBody era -> [Cardano.KeyWitness era]
-- ^ Create payload-specific witnesses given the unsigned transaction body.
--
-- Caller has the freedom and responsibility to provide the correct
-- witnesses for what they're trying to do.
}
type EraConstraints era =
( IsShelleyBasedEra era
, ToCBOR (Ledger.TxBody (Cardano.ShelleyLedgerEra era))
, DSIGN (Crypto (Cardano.ShelleyLedgerEra era)) ~ DSIGN.Ed25519DSIGN
, (era == ByronEra) ~ 'False
)
constructUnsignedTx
:: forall era
. IsShelleyBasedEra era
=> Cardano.NetworkId
-> (Maybe Cardano.TxMetadata, [Cardano.Certificate])
-> (Maybe SlotNo, SlotNo)
-- ^ Slot at which the transaction will optionally start and expire.
-> Withdrawal
-> Either PreSelection (SelectionOf TxOut)
-- ^ Finalized asset selection
-> Coin
-- ^ Explicit fee amount
-> (TokenMap, Map AssetId (Script KeyHash))
-- ^ Assets to be minted
-> (TokenMap, Map AssetId (Script KeyHash))
-- ^ Assets to be burned
-> Map TxIn (Script KeyHash)
-- ^ scripts for inputs
-> Maybe (Script KeyHash)
-- ^ Delegation script
-> ShelleyBasedEra era
-> Either ErrMkTransaction (Cardano.TxBody era)
constructUnsignedTx
networkId (md, certs) ttl wdrl
cs fee toMint toBurn inpScripts stakingScriptM era =
mkUnsignedTx
era ttl cs md wdrls certs (toCardanoLovelace fee)
(fst toMint) (fst toBurn) mintingScripts inpScripts
stakingScriptM
where
wdrls = mkWithdrawals networkId wdrl
mintingScripts = Map.union (snd toMint) (snd toBurn)
mkTx
:: forall k era
. (TxWitnessTagFor k, EraConstraints era)
=> KeyFlavorS k
-> Cardano.NetworkId
-> TxPayload era
-> (Maybe SlotNo, SlotNo)
-- ^ Slot at which the transaction will start and expire.
-> (XPrv, Passphrase "encryption")
-- ^ Reward account
-> (Address -> Maybe (k 'CredFromKeyK XPrv, Passphrase "encryption"))
-- ^ Key store
-> Withdrawal
-- ^ An optional withdrawal
-> SelectionOf TxOut
-- ^ Finalized asset selection
-> Coin
-- ^ Explicit fee amount
-> ShelleyBasedEra era
-> Either ErrMkTransaction (Tx, SealedTx)
mkTx keyF networkId payload ttl (rewardAcnt, pwdAcnt) addrResolver wdrl cs fees era =
do
let TxPayload md certs mkExtraWits = payload
let wdrls = mkWithdrawals networkId wdrl
unsigned <- mkUnsignedTx era ttl (Right cs) md wdrls certs
(toCardanoLovelace fees)
TokenMap.empty TokenMap.empty Map.empty Map.empty Nothing
let signed = signTransaction keyF networkId AnyWitnessCountCtx acctResolver
(const Nothing) (const Nothing) addrResolver inputResolver
(unsigned, mkExtraWits unsigned)
let withResolvedInputs (tx, _, _, _, _, _) = tx
{ resolvedInputs = second Just <$> F.toList (view #inputs cs)
}
Right ( withResolvedInputs (fromCardanoTx AnyWitnessCountCtx signed)
, sealedTxFromCardano' signed
)
where
inputResolver :: TxIn -> Maybe Address
inputResolver i =
let index = Map.fromList (F.toList $ view #inputs cs)
in do
TxOut addr _ <- Map.lookup i index
pure addr
acctResolver :: RewardAccount -> Maybe (XPrv, Passphrase "encryption")
acctResolver acct = do
let acct' = toRewardAccountRaw $ toXPub rewardAcnt
guard (acct == acct') $> (rewardAcnt, pwdAcnt)
-- Adds VK witnesses to an already constructed transactions. The function
-- preserves any existing witnesses on the transaction, and resolve inputs
-- dynamically using the provided lookup function.
--
-- If a key for a given input isn't found, the input is skipped.
signTransaction
:: forall k ktype era
. (EraConstraints era, TxWitnessTagFor k)
=> KeyFlavorS k
-> Cardano.NetworkId
-- ^ Network identifier (e.g. mainnet, testnet)
-> WitnessCountCtx
-> (RewardAccount -> Maybe (XPrv, Passphrase "encryption"))
-- ^ Stake key store / reward account resolution
-> (KeyHash -> Maybe (XPrv, Passphrase "encryption"))
-- ^ Policy key resolution
-> (KeyHash -> Maybe (XPrv, Passphrase "encryption"))
-- ^ Staking script key resolution
-> (Address -> Maybe (k ktype XPrv, Passphrase "encryption"))
-- ^ Payment key store
-> (TxIn -> Maybe Address)
-- ^ Input resolver
-> (Cardano.TxBody era, [Cardano.KeyWitness era])
-- ^ The transaction to sign, possibly with already some existing witnesses
-> Cardano.Tx era
signTransaction
keyF
networkId
witCountCtx
resolveRewardAcct
resolvePolicyKey
resolveStakingKeyInScript
resolveAddress
resolveInput
(body, wits) =
Cardano.makeSignedTransaction wits' body
where
wits' = mconcat
[ wits
, mapMaybe mkTxInWitness inputs
, mapMaybe mkTxInWitness collaterals
, mapMaybe mkWdrlCertWitness wdrls
, mapMaybe mkExtraWitness extraKeys
, mapMaybe mkWdrlCertWitness certs
, mapMaybe mkPolicyWitness mintBurnScriptsKeyHashes
, mapMaybe mkStakingScriptWitness stakingScriptsKeyHashes
]
where
Cardano.TxBody bodyContent = body
inputs =
[ Compatibility.fromCardanoTxIn i
| (i, _) <- Cardano.txIns bodyContent
]
collaterals =
case Cardano.txInsCollateral bodyContent of
Cardano.TxInsCollateralNone ->
[]
Cardano.TxInsCollateral _ is ->
Compatibility.fromCardanoTxIn <$> is
extraKeys =
case Cardano.txExtraKeyWits bodyContent of
Cardano.TxExtraKeyWitnessesNone ->
[]
Cardano.TxExtraKeyWitnesses _ xs ->
xs
wdrls =
[ addr
| (addr, _) <- fromCardanoWdrls $ Cardano.txWithdrawals bodyContent
]
certs = cardanoCertKeysForWitnesses $ Cardano.txCertificates bodyContent
mintBurnScriptsKeyHashes =
let (_, toMint, toBurn, _, _, _) = fromCardanoTx witCountCtx $
Cardano.makeSignedTransaction wits body
in
-- Note that we use 'nub' here because multiple scripts can share
-- the same policyXPub. It's sufficient to have one witness for
-- each.
L.nub $ getScriptsKeyHashes toMint <> getScriptsKeyHashes toBurn
stakingScriptsKeyHashes =
let (_, _, _, _, _, (WitnessCount _ nativeScripts _)) =
fromCardanoTx witCountCtx $
Cardano.makeSignedTransaction wits body
isDelegationKeyHash (KeyHash Delegation _) = True
isDelegationKeyHash (KeyHash _ _) = False
in
filter isDelegationKeyHash $
L.nub $ concatMap retrieveAllKeyHashesE $
filter isTimelockE nativeScripts
retrieveAllKeyHashesE (NativeExplicitScript s _) = foldScript (:) [] s
retrieveAllKeyHashesE _ = []
isTimelockE (NativeExplicitScript _ _) = True
isTimelockE _ = False
retrieveAllKeyHashes (NativeScript s _) = foldScript (:) [] s
retrieveAllKeyHashes _ = []
isTimelock (NativeScript _ _) = True
isTimelock _ = False
getScriptsKeyHashes :: TokenMapWithScripts -> [KeyHash]
getScriptsKeyHashes scripts =
concatMap retrieveAllKeyHashes $
filter isTimelock $
Map.elems $ scripts ^. #txScripts
mkTxInWitness :: TxIn -> Maybe (Cardano.KeyWitness era)
mkTxInWitness i = do
addr <- resolveInput i
(k, pwd) <- resolveAddress addr
let pk = (getRawKey keyF k, pwd)
pure $ case txWitnessTagFor @k of
TxWitnessShelleyUTxO -> mkShelleyWitness body pk
TxWitnessByronUTxO ->
mkByronWitness body networkId addr pk
mkWdrlCertWitness :: RewardAccount -> Maybe (Cardano.KeyWitness era)
mkWdrlCertWitness a =
mkShelleyWitness body <$> resolveRewardAcct a
mkPolicyWitness :: KeyHash -> Maybe (Cardano.KeyWitness era)
mkPolicyWitness a =
mkShelleyWitness body <$> resolvePolicyKey a
mkStakingScriptWitness :: KeyHash -> Maybe (Cardano.KeyWitness era)
mkStakingScriptWitness a =
mkShelleyWitness body <$> resolveStakingKeyInScript a
mkExtraWitness :: Cardano.Hash Cardano.PaymentKey -> Maybe (Cardano.KeyWitness era)
mkExtraWitness vkh = do
-- NOTE: We cannot resolve key hashes directly, so create a one-time
-- temporary address with that key hash which is fine to lookup via the
-- address lookup provided above. It works _fine_ because the discovery
-- of addresses is done properly based on the address constituents (i.e.
-- the key hash) and not the overall address itself.
let addr = Cardano.makeShelleyAddress networkId
(Cardano.PaymentCredentialByKey vkh)
Cardano.NoStakeAddress
(k, pwd) <- resolveAddress (fromCardanoAddress addr)
pure $ mkShelleyWitness body (getRawKey keyF k, pwd)
newTransactionLayer
:: forall k ktype
. TxWitnessTagFor k
=> KeyFlavorS k
-> NetworkId
-> TransactionLayer k ktype SealedTx
newTransactionLayer keyF networkId = TransactionLayer
{ mkTransaction = \era stakeCreds keystore _pp ctx selection -> do
let ttl = txValidityInterval ctx
let wdrl = view #txWithdrawal ctx
let delta = selectionDelta TxOut.coin selection
case view #txDelegationAction ctx of
Nothing -> withShelleyBasedEra era $ do
let payload = TxPayload (view #txMetadata ctx) mempty mempty
mkTx keyF networkId payload ttl stakeCreds keystore wdrl
selection delta
Just action -> withShelleyBasedEra era $ do
let stakeXPub = toXPub $ fst stakeCreds
let certs = mkDelegationCertificates action (Left stakeXPub)
let payload = TxPayload (view #txMetadata ctx) certs (const [])
mkTx keyF networkId payload ttl stakeCreds keystore wdrl
selection delta
, addVkWitnesses =
\era witCountCtx stakeCreds policyCreds scriptStakingCredM addressResolver
inputResolver sealedTx -> do
let acctMap :: Map RewardAccount (XPrv, Passphrase "encryption")
acctMap = Map.fromList $ map
(\(xprv, pwd) -> (toRewardAccountRaw $ toXPub xprv,(xprv, pwd)))
stakeCreds
let acctResolver
:: RewardAccount -> Maybe (XPrv, Passphrase "encryption")
acctResolver acct = Map.lookup acct acctMap
let policyResolver
:: KeyHash -> Maybe (XPrv, Passphrase "encryption")
policyResolver keyhash = do
(keyhash', xprv, encP) <- policyCreds
guard (keyhash == keyhash') $> (xprv, encP)
let stakingScriptResolver
:: KeyHash -> Maybe (XPrv, Passphrase "encryption")
stakingScriptResolver keyhash = case scriptStakingCredM of
Just scriptStakingCred -> do
let (keyhash', xprv, encP) = scriptStakingCred
guard (keyhash == keyhash') $> (xprv, encP)
Nothing -> Nothing
case cardanoTxIdeallyNoLaterThan era sealedTx of
InAnyCardanoEra ByronEra _ ->
sealedTx
InAnyCardanoEra ShelleyEra (Cardano.Tx body wits) ->
signTransaction keyF networkId witCountCtx acctResolver (const Nothing)
(const Nothing) addressResolver inputResolver (body, wits)
& sealedTxFromCardano'
InAnyCardanoEra AllegraEra (Cardano.Tx body wits) ->
signTransaction keyF networkId witCountCtx acctResolver (const Nothing)
(const Nothing) addressResolver inputResolver (body, wits)
& sealedTxFromCardano'
InAnyCardanoEra MaryEra (Cardano.Tx body wits) ->
signTransaction keyF networkId witCountCtx acctResolver policyResolver
stakingScriptResolver addressResolver inputResolver (body, wits)
& sealedTxFromCardano'
InAnyCardanoEra AlonzoEra (Cardano.Tx body wits) ->
signTransaction keyF networkId witCountCtx acctResolver policyResolver
stakingScriptResolver addressResolver inputResolver (body, wits)
& sealedTxFromCardano'
InAnyCardanoEra BabbageEra (Cardano.Tx body wits) ->
signTransaction keyF networkId witCountCtx acctResolver policyResolver
stakingScriptResolver addressResolver inputResolver (body, wits)
& sealedTxFromCardano'
InAnyCardanoEra ConwayEra (Cardano.Tx body wits) ->
signTransaction keyF networkId witCountCtx acctResolver policyResolver
stakingScriptResolver addressResolver inputResolver (body, wits)
& sealedTxFromCardano'
, mkUnsignedTransaction = \stakeCred ctx selection -> do
let ttl = txValidityInterval ctx
let wdrl = view #txWithdrawal ctx
let delta = case selection of
Right selOf -> selectionDelta TxOut.coin selOf
Left _preSel -> Coin 0
let assetsToBeMinted = view #txAssetsToMint ctx
let assetsToBeBurned = view #txAssetsToBurn ctx
let inpsScripts = view #txNativeScriptInputs ctx
let stakingScriptM =
flip (replaceCosignersWithVerKeys CA.Stake) minBound <$>
view #txStakingCredentialScriptTemplate ctx
case view #txDelegationAction ctx of
Nothing -> do
let md = view #txMetadata ctx
let ourRewardAcctM = FromScriptHash . unScriptHash . toScriptHash <$> stakingScriptM
case wdrl of
WithdrawalSelf rewardAcct _ _ ->
if ourRewardAcctM == Just rewardAcct then
constructUnsignedTx networkId (md, []) ttl wdrl
selection delta assetsToBeMinted assetsToBeBurned inpsScripts
stakingScriptM
(Write.shelleyBasedEraFromRecentEra Write.recentEra)
else
constructUnsignedTx networkId (md, []) ttl wdrl
selection delta assetsToBeMinted assetsToBeBurned inpsScripts
Nothing
(Write.shelleyBasedEraFromRecentEra Write.recentEra)
_ ->
constructUnsignedTx networkId (md, []) ttl wdrl
selection delta assetsToBeMinted assetsToBeBurned inpsScripts
Nothing
(Write.shelleyBasedEraFromRecentEra Write.recentEra)
Just action -> do
let certs = case stakeCred of
Left xpub ->
mkDelegationCertificates action (Left xpub)
Right (Just script) ->
mkDelegationCertificates action (Right script)
Right Nothing ->
error $ "stakeCred in mkUnsignedTransaction must be either "
<> "xpub or script when there is delegation action"
let payload = (view #txMetadata ctx, certs)
constructUnsignedTx networkId payload ttl wdrl
selection delta assetsToBeMinted assetsToBeBurned inpsScripts
stakingScriptM
(Write.shelleyBasedEraFromRecentEra Write.recentEra)
, tokenBundleSizeAssessor =
Compatibility.tokenBundleSizeAssessor
, constraints = \era pp -> txConstraints era pp (txWitnessTagFor @k)
, decodeTx = _decodeSealedTx
, transactionWitnessTag = txWitnessTagFor @k
}
_decodeSealedTx
:: AnyCardanoEra
-> WitnessCountCtx
-> SealedTx ->
( Tx
, TokenMapWithScripts
, TokenMapWithScripts
, [Certificate]
, Maybe ValidityIntervalExplicit
, WitnessCount
)
_decodeSealedTx preferredLatestEra witCtx (cardanoTxIdeallyNoLaterThan preferredLatestEra -> Cardano.InAnyCardanoEra _ tx) =
fromCardanoTx witCtx tx
mkDelegationCertificates
:: DelegationAction
-- Pool Id to which we're planning to delegate
-> Either XPub (Script KeyHash)
--Staking credential
-> [Cardano.Certificate]
mkDelegationCertificates da cred =
case da of
Join poolId ->
[ toStakePoolDlgCert cred poolId ]
JoinRegisteringKey poolId ->
[ toStakeKeyRegCert cred
, toStakePoolDlgCert cred poolId
]
Quit -> [toStakeKeyDeregCert cred]
-- | Describes modifications that can be made to a `Tx` using `updateTx`.
data TxUpdate = TxUpdate
{ extraInputs :: [(TxIn, TxOut)]
, extraCollateral :: [TxIn]
-- ^ Only used in the Alonzo era and later. Will be silently ignored in
-- previous eras.
, extraOutputs :: [TxOut]
, extraInputScripts :: [Script KeyHash]
, feeUpdate :: TxFeeUpdate
-- ^ Set a new fee or use the old one.
}
-- | For testing that
-- @
-- forall tx. updateTx noTxUpdate tx
-- == Right tx or Left
-- @
noTxUpdate :: TxUpdate
noTxUpdate = TxUpdate [] [] [] [] UseOldTxFee
-- | Method to use when updating the fee of a transaction.
data TxFeeUpdate
= UseOldTxFee
-- ^ Instead of updating the fee, just use the old fee of the
-- Tx (no-op for fee update).
| UseNewTxFee Coin
-- ^ Specify a new fee to use instead.
deriving (Eq, Show)
-- Used to add inputs and outputs when balancing a transaction.
--
-- If the transaction contains existing key witnesses, it will return `Left`,
-- *even if `noTxUpdate` is used*. This last detail could be changed.
--
-- == Notes on implementation choices
--
-- We cannot rely on cardano-api here because `Cardano.TxBodyContent BuildTx`
-- cannot be extracted from an existing `TxBody`.
--
-- To avoid the need for `ledger -> wallet` conversions, this function can only
-- be used to *add* tx body content.
updateTx
:: forall era. Write.IsRecentEra era
=> Cardano.Tx era
-> TxUpdate
-> Either ErrUpdateSealedTx (Cardano.Tx era)
updateTx (Cardano.Tx body existingKeyWits) extraContent = do
-- NOTE: The script witnesses are carried along with the cardano-api
-- `anyEraBody`.
body' <- modifyTxBody extraContent body
if (null existingKeyWits)
then Right $ Cardano.Tx body' mempty
else Left $ ErrExistingKeyWitnesses $ length existingKeyWits
where
era = recentEra @era
modifyTxBody
:: TxUpdate
-> Cardano.TxBody era
-> Either ErrUpdateSealedTx (Cardano.TxBody era)
modifyTxBody ebc = \case
Cardano.ShelleyTxBody shelleyEra bod scripts scriptData aux val ->
Right $ Cardano.ShelleyTxBody shelleyEra
(modifyShelleyTxBody ebc era bod)
(scripts ++ (flip toLedgerScript era
<$> extraInputScripts))
scriptData
aux
val
Byron.ByronTxBody _ -> case Cardano.shelleyBasedEra @era of {}
TxUpdate _ _ _ extraInputScripts _ = extraContent
toLedgerScript
:: Script KeyHash
-> RecentEra era
-> Ledger.Script (Cardano.ShelleyLedgerEra era)
toLedgerScript walletScript = \case
RecentEraBabbage ->
Cardano.toShelleyScript $ Cardano.ScriptInEra
Cardano.SimpleScriptInBabbage
(Cardano.SimpleScript $ toCardanoSimpleScript walletScript)
RecentEraConway ->
Cardano.toShelleyScript $ Cardano.ScriptInEra
Cardano.SimpleScriptInConway
(Cardano.SimpleScript $ toCardanoSimpleScript walletScript)
-- NOTE: If the ShelleyMA MAClass were exposed, the Allegra and Mary
-- cases could perhaps be joined. It is not however. And we still need
-- to treat Alonzo and Shelley differently.
modifyShelleyTxBody
:: TxUpdate
-> RecentEra era
-> Ledger.TxBody (Cardano.ShelleyLedgerEra era)
-> Ledger.TxBody (Cardano.ShelleyLedgerEra era)
modifyShelleyTxBody txUpdate era ledgerBody = case era of
RecentEraConway -> ledgerBody
{ Conway.outputs = Conway.outputs ledgerBody
<> StrictSeq.fromList
(Ledger.mkSized . toConwayTxOut <$> extraOutputs)
, Conway.inputs = Conway.inputs ledgerBody
<> Set.fromList (Cardano.toShelleyTxIn <$> extraInputs')
, Conway.collateral = Conway.collateral ledgerBody
<> Set.fromList (Cardano.toShelleyTxIn <$> extraCollateral')
, Conway.txfee =
modifyFee $ Conway.txfee ledgerBody
}
RecentEraBabbage -> ledgerBody
{ Babbage.outputs = Babbage.outputs ledgerBody
<> StrictSeq.fromList
(Ledger.mkSized . toBabbageTxOut <$> extraOutputs)
, Babbage.inputs = Babbage.inputs ledgerBody
<> Set.fromList (Cardano.toShelleyTxIn <$> extraInputs')
, Babbage.collateral = Babbage.collateral ledgerBody
<> Set.fromList (Cardano.toShelleyTxIn <$> extraCollateral')
, Babbage.txfee =
modifyFee $ Babbage.txfee ledgerBody
}
where
TxUpdate extraInputs extraCollateral extraOutputs _ feeUpdate
= txUpdate
extraInputs' = toCardanoTxIn . fst <$> extraInputs
extraCollateral' = toCardanoTxIn <$> extraCollateral
modifyFee old = case feeUpdate of
UseNewTxFee new -> toLedgerCoin new
UseOldTxFee -> old
where
toLedgerCoin :: Coin -> Ledger.Coin
toLedgerCoin (Coin c) = Ledger.Coin (intCast c)
-- | Evaluate a minimal fee amount necessary to pay for a given tx
-- using ledger's functionality.
evaluateMinimumFee
:: Cardano.IsShelleyBasedEra era
=> Cardano.BundledProtocolParameters era
-> KeyWitnessCount
-> Cardano.TxBody era
-> Coin
evaluateMinimumFee pp (KeyWitnessCount nWits nBootWits) body =
fromCardanoLovelace (Cardano.evaluateTransactionFee pp body nWits 0)
<> bootWitFees
-- NOTE: Cardano.evaluateTransactionFee will error if passed non-zero
-- nBootWits, so we need to account for it separately.
where
bootWitFees = Coin.fromNatural $
Cardano.protocolParamTxFeePerByte
(Cardano.unbundleProtocolParams pp) * bytes
where
bytes :: Natural
bytes = fromIntegral $ sizeOf_BootstrapWitnesses $ intCast nBootWits
-- | Estimate the size of the transaction (body) when fully signed.
estimateSignedTxSize
:: forall era. Write.IsRecentEra era
=> Write.PParams (Write.ShelleyLedgerEra era)
-> KeyWitnessCount
-> Cardano.TxBody era
-> TxSize
estimateSignedTxSize pparams nWits body =
let
-- Hack which allows us to rely on the ledger to calculate the size of
-- witnesses:
feeOfWits :: Coin
feeOfWits = minfee nWits `Coin.difference` minfee mempty
sizeOfWits :: TxSize
sizeOfWits =
case feeOfWits `coinQuotRem` feePerByte of
(n, 0) -> TxSize n
(_, _) -> error $ unwords
[ "estimateSignedTxSize:"
, "the impossible happened!"
, "Couldn't divide"
, show feeOfWits
, "lovelace (the fee contribution of"
, show nWits
, "witnesses) with"
, show feePerByte
, "lovelace/byte"
]
sizeOfTx :: TxSize
sizeOfTx = TxSize
. fromIntegral
. BS.length
. serialisedTx
$ sealedTxFromCardanoBody body
in
sizeOfTx <> sizeOfWits
where
coinQuotRem :: Coin -> Coin -> (Natural, Natural)
coinQuotRem (Coin p) (Coin q) = quotRem p q
minfee :: KeyWitnessCount -> Coin
minfee witCount = toWalletCoin $ Write.evaluateMinimumFee
(Write.recentEra @era) pparams (toLedgerTx body) witCount
toLedgerTx
:: Cardano.TxBody era -> Write.Tx (Write.ShelleyLedgerEra era)
toLedgerTx b = case Cardano.Tx b [] of
Byron.ByronTx {} -> case Write.recentEra @era of
{}
Cardano.ShelleyTx _era ledgerTx -> ledgerTx
feePerByte :: Coin
feePerByte = Coin.fromNatural $ case Write.recentEra @era of
Write.RecentEraBabbage -> Babbage._minfeeA pparams
Write.RecentEraConway -> Conway._minfeeA pparams
numberOfShelleyWitnesses :: Word -> KeyWitnessCount
numberOfShelleyWitnesses n = KeyWitnessCount n 0
-- | Estimates the required number of Shelley-era witnesses.
--
-- Because we don't take into account whether two pieces of tx content will need
-- the same key for signing, the result may be an overestimate.
--
-- For instance, this may happen if:
-- 1. Multiple inputs share the same payment key (like in a single address
-- wallet)
-- 2. We are updating our delegation and withdrawing rewards at the same time.
--
-- FIXME [ADP-1515] Improve estimation
--
-- NOTE: Similar to 'estimateTransactionKeyWitnessCount' from cardano-api, which
-- we cannot use because it requires a 'TxBodyContent BuildTx era'.
estimateKeyWitnessCount
:: forall era. IsRecentEra era
=> Cardano.UTxO era
-- ^ Must contain all inputs from the 'TxBody' or
-- 'estimateKeyWitnessCount will 'error'.
-> Cardano.TxBody era
-> KeyWitnessCount
estimateKeyWitnessCount utxo txbody@(Cardano.TxBody txbodycontent) =
let txIns = map fst $ Cardano.txIns txbodycontent
txInsCollateral =
case Cardano.txInsCollateral txbodycontent of
Cardano.TxInsCollateral _ ins -> ins
Cardano.TxInsCollateralNone -> []
vkInsUnique = L.nub $ filter (hasVkPaymentCred utxo) $
txIns ++ txInsCollateral
txExtraKeyWits = Cardano.txExtraKeyWits txbodycontent
txExtraKeyWits' = case txExtraKeyWits of
Cardano.TxExtraKeyWitnesses _ khs -> khs
_ -> []
txWithdrawals = Cardano.txWithdrawals txbodycontent
txWithdrawals' = case txWithdrawals of
Cardano.TxWithdrawals _ wdls ->
[ () | (_, _, Cardano.ViewTx) <- wdls ]
_ -> []
txUpdateProposal = Cardano.txUpdateProposal txbodycontent
txUpdateProposal' = case txUpdateProposal of
Cardano.TxUpdateProposal _
(Cardano.UpdateProposal updatePerGenesisKey _) ->
Map.size updatePerGenesisKey
_ -> 0