-
Notifications
You must be signed in to change notification settings - Fork 214
/
Transaction.hs
2468 lines (2259 loc) · 87.6 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 RecordWildCards #-}
{-# LANGUAGE RoleAnnotations #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
-- |
-- Copyright: © 2020 IOHK
-- License: Apache-2.0
--
-- Working with Shelley transactions.
module Cardano.Wallet.Shelley.Transaction
( newTransactionLayer
-- * Updating SealedTx
, TxUpdate (..)
, noTxUpdate
, updateSealedTx
-- * Internals
, TxPayload (..)
, TxSkeleton (..)
, TxWitnessTag (..)
, TxWitnessTagFor (..)
, _decodeSealedTx
, _estimateMaxNumberOfInputs
, _maxScriptExecutionCost
, mkDelegationCertificates
, estimateTxCost
, estimateTxSize
, mkByronWitness
, mkShelleyWitness
, mkTx
, mkTxSkeleton
, mkUnsignedTx
, txConstraints
, costOfIncreasingCoin
, _distributeSurplus
, distributeSurplusDelta
, sizeOfCoin
, maximumCostOfIncreasingCoin
) where
import Prelude
import Cardano.Address.Derivation
( XPrv, toXPub )
import Cardano.Address.Script
( KeyHash, Script (..), foldScript )
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, Era, ValidateScript (..) )
import Cardano.Ledger.Shelley.API
( StrictMaybe (..) )
import Cardano.Slotting.EpochInfo
( EpochInfo )
import Cardano.Slotting.EpochInfo.API
( hoistEpochInfo )
import Cardano.Wallet.CoinSelection
( SelectionLimitOf (..)
, SelectionOf (..)
, SelectionSkeleton (..)
, selectionDelta
)
import Cardano.Wallet.Primitive.AddressDerivation
( Depth (..), RewardAccount (..), WalletKey (..) )
import Cardano.Wallet.Primitive.AddressDerivation.Byron
( ByronKey )
import Cardano.Wallet.Primitive.AddressDerivation.Icarus
( IcarusKey )
import Cardano.Wallet.Primitive.AddressDerivation.Shelley
( ShelleyKey, toRewardAccountRaw )
import Cardano.Wallet.Primitive.Passphrase
( Passphrase (..) )
import Cardano.Wallet.Primitive.Slotting
( PastHorizonException, TimeInterpreter, getSystemStart, toEpochInfo )
import Cardano.Wallet.Primitive.Types
( Certificate
, ExecutionUnitPrices (..)
, ExecutionUnits (..)
, 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 (..)
, TxConstraints (..)
, TxIn
, TxMetadata (..)
, TxOut (..)
, TxSize (..)
, sealedTxFromCardano'
, sealedTxFromCardanoBody
, txOutAddCoin
, txOutCoin
, txSizeDistance
)
import Cardano.Wallet.Primitive.Types.UTxO
( UTxO (..) )
import Cardano.Wallet.Shelley.Compatibility
( cardanoCertKeysForWitnesses
, fromCardanoAddress
, fromCardanoLovelace
, fromCardanoTx
, fromCardanoTxIn
, fromCardanoWdrls
, fromShelleyTxIn
, toCardanoLovelace
, toCardanoPolicyId
, toCardanoSimpleScript
, toCardanoStakeCredential
, toCardanoTxIn
, toCardanoTxOut
, toCardanoValue
, toCostModelsAsArray
, toHDPayloadAddress
, toScriptPurpose
, toStakeKeyDeregCert
, toStakeKeyRegCert
, toStakePoolDlgCert
)
import Cardano.Wallet.Shelley.Compatibility.Ledger
( computeMinimumAdaQuantity, toAlonzoTxOut, toBabbageTxOut )
import Cardano.Wallet.Transaction
( AnyScript (..)
, DelegationAction (..)
, ErrAssignRedeemers (..)
, ErrMkTransaction (..)
, ErrMoreSurplusNeeded (ErrMoreSurplusNeeded)
, ErrUpdateSealedTx (..)
, TokenMapWithScripts
, TransactionCtx (..)
, TransactionLayer (..)
, TxFeeAndChange (..)
, TxFeeUpdate (..)
, TxUpdate (..)
, ValidityIntervalExplicit
, mapTxFeeAndChange
, withdrawalToCoin
)
import Cardano.Wallet.Util
( internalError, modifyM )
import Codec.Serialise
( deserialiseOrFail )
import Control.Arrow
( left, second )
import Control.Monad
( forM, guard )
import Control.Monad.Trans.Class
( lift )
import Control.Monad.Trans.Except
( runExceptT )
import Control.Monad.Trans.State.Strict
( StateT (..), execStateT, get, modify' )
import Data.Bifunctor
( bimap )
import Data.Either
( fromRight )
import Data.Function
( (&) )
import Data.Functor
( ($>), (<&>) )
import Data.Functor.Identity
( runIdentity )
import Data.Generics.Internal.VL.Lens
( view, (^.) )
import Data.Generics.Labels
()
import Data.IntCast
( intCast )
import Data.Kind
( Type )
import Data.Map.Strict
( Map, (!) )
import Data.Maybe
( fromMaybe, mapMaybe )
import Data.Quantity
( Quantity (..) )
import Data.Set
( Set )
import Data.Type.Equality
( type (==) )
import Data.Word
( Word16, Word64, Word8 )
import GHC.Generics
( Generic )
import Numeric.Natural
( Natural )
import Ouroboros.Network.Block
( SlotNo )
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.Core as Ledger
import qualified Cardano.Ledger.Serialization as Ledger
import qualified Cardano.Ledger.Shelley.Address.Bootstrap as SL
import qualified Cardano.Ledger.Shelley.Tx as Shelley
import qualified Cardano.Ledger.Shelley.UTxO as Ledger
import qualified Cardano.Ledger.ShelleyMA.TxBody as ShelleyMA
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.Shelley.Compatibility as Compatibility
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.
}
data TxWitnessTag
= TxWitnessByronUTxO WalletStyle
| TxWitnessShelleyUTxO
deriving (Show, Eq)
data WalletStyle
= Icarus
| Byron
deriving (Show, Eq)
type EraConstraints era =
( IsShelleyBasedEra era
, ToCBOR (Ledger.TxBody (Cardano.ShelleyLedgerEra era))
, Era (Cardano.ShelleyLedgerEra era)
, DSIGN (Crypto (Cardano.ShelleyLedgerEra era)) ~ DSIGN.Ed25519DSIGN
, (era == ByronEra) ~ 'False
)
-- | Provide a transaction witness for a given private key. The type of witness
-- is different between types of keys and, with backward-compatible support, we
-- need to support many types for one backend target.
class TxWitnessTagFor (k :: Depth -> Type -> Type) where
txWitnessTagFor :: TxWitnessTag
instance TxWitnessTagFor ShelleyKey where
txWitnessTagFor = TxWitnessShelleyUTxO
instance TxWitnessTagFor IcarusKey where
txWitnessTagFor = TxWitnessByronUTxO Icarus
instance TxWitnessTagFor ByronKey where
txWitnessTagFor = TxWitnessByronUTxO Byron
constructUnsignedTx
:: forall era.
( EraConstraints era
)
=> Cardano.NetworkId
-> (Maybe Cardano.TxMetadata, [Cardano.Certificate])
-> (Maybe SlotNo, SlotNo)
-- ^ Slot at which the transaction will optionally start and expire.
-> RewardAccount
-- ^ Reward account
-> Coin
-- ^ An optional withdrawal amount, can be zero
-> 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
-> ShelleyBasedEra era
-> Either ErrMkTransaction SealedTx
constructUnsignedTx
networkId (md, certs) ttl rewardAcnt wdrl cs fee toMint toBurn era =
sealedTxFromCardanoBody <$> tx
where
tx = mkUnsignedTx era ttl cs md wdrls certs (toCardanoLovelace fee)
(fst toMint) (fst toBurn) allScripts
wdrls = mkWithdrawals networkId rewardAcnt wdrl
allScripts = Map.union (snd toMint) (snd toBurn)
mkTx
:: forall k era.
( TxWitnessTagFor k
, WalletKey k
, EraConstraints era
)
=> Cardano.NetworkId
-> TxPayload era
-> (Maybe SlotNo, SlotNo)
-- ^ Slot at which the transaction will start and expire.
-> (XPrv, Passphrase "encryption")
-- ^ Reward account
-> (Address -> Maybe (k 'AddressK XPrv, Passphrase "encryption"))
-- ^ Key store
-> Coin
-- ^ An optional withdrawal amount, can be zero
-> SelectionOf TxOut
-- ^ Finalized asset selection
-> Coin
-- ^ Explicit fee amount
-> ShelleyBasedEra era
-> Either ErrMkTransaction (Tx, SealedTx)
mkTx networkId payload ttl (rewardAcnt, pwdAcnt) addrResolver wdrl cs fees era = do
let TxPayload md certs mkExtraWits = payload
let wdrls = mkWithdrawals
networkId
(toRewardAccountRaw . toXPub $ rewardAcnt)
wdrl
unsigned <- mkUnsignedTx era ttl cs md wdrls certs (toCardanoLovelace fees)
TokenMap.empty TokenMap.empty Map.empty
let signed = signTransaction networkId acctResolver (const Nothing)
addrResolver inputResolver (unsigned, mkExtraWits unsigned)
let withResolvedInputs (tx, _, _, _, _) = tx
{ resolvedInputs = second txOutCoin <$> F.toList (view #inputs cs)
}
Right ( withResolvedInputs (fromCardanoTx 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 era.
( EraConstraints era
, TxWitnessTagFor k
, WalletKey k
)
=> Cardano.NetworkId
-- ^ Network identifier (e.g. mainnet, testnet)
-> (RewardAccount -> Maybe (XPrv, Passphrase "encryption"))
-- ^ Stake key store / reward account resolution
-> (KeyHash -> Maybe (XPrv, Passphrase "encryption"))
-- ^ Policy key resolution
-> (Address -> Maybe (k 'AddressK 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
networkId
resolveRewardAcct
resolvePolicyKey
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 mintBurnScripts
]
where
Cardano.TxBody bodyContent = body
inputs =
[ fromCardanoTxIn i
| (i, _) <- Cardano.txIns bodyContent
]
collaterals =
case Cardano.txInsCollateral bodyContent of
Cardano.TxInsCollateralNone ->
[]
Cardano.TxInsCollateral _ is ->
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
mintBurnScripts =
let (_, toMint, toBurn, _, _) = fromCardanoTx $
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 $ getScripts toMint <> getScripts toBurn
getScripts :: TokenMapWithScripts -> [KeyHash]
getScripts scripts =
let retrieveAllKeyHashes (NativeScript s) = foldScript (:) [] s
retrieveAllKeyHashes _ = []
isTimelock (NativeScript _) = True
isTimelock _ = False
in concatMap retrieveAllKeyHashes $
filter isTimelock $
Map.elems $ scripts ^. #txScripts
mkTxInWitness :: TxIn -> Maybe (Cardano.KeyWitness era)
mkTxInWitness i = do
addr <- resolveInput i
(k, pwd) <- resolveAddress addr
pure $ case (txWitnessTagFor @k) of
TxWitnessShelleyUTxO ->
mkShelleyWitness body (getRawKey k, pwd)
TxWitnessByronUTxO{} ->
mkByronWitness body networkId addr (getRawKey k, pwd)
mkWdrlCertWitness :: RewardAccount -> Maybe (Cardano.KeyWitness era)
mkWdrlCertWitness a =
mkShelleyWitness body <$> resolveRewardAcct a
mkPolicyWitness :: KeyHash -> Maybe (Cardano.KeyWitness era)
mkPolicyWitness a =
mkShelleyWitness body <$> resolvePolicyKey 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 k, pwd)
newTransactionLayer
:: forall k.
( TxWitnessTagFor k
, WalletKey k
)
=> NetworkId
-> TransactionLayer k SealedTx
newTransactionLayer networkId = TransactionLayer
{ mkTransaction = \era stakeCreds keystore _pp ctx selection -> do
let ttl = txValidityInterval ctx
let wdrl = withdrawalToCoin $ view #txWithdrawal ctx
let delta = selectionDelta txOutCoin selection
case view #txDelegationAction ctx of
Nothing -> do
withShelleyBasedEra era $ do
let payload = TxPayload (view #txMetadata ctx) mempty mempty
mkTx networkId payload ttl stakeCreds keystore wdrl
selection delta
Just action -> do
withShelleyBasedEra era $ do
let stakeXPub = toXPub $ fst stakeCreds
let certs = mkDelegationCertificates action stakeXPub
let payload = TxPayload (view #txMetadata ctx) certs (const [])
mkTx networkId payload ttl stakeCreds keystore wdrl
selection delta
, addVkWitnesses =
\_era stakeCreds policyCreds addressResolver inputResolver sealedTx ->
do
let acctResolver
:: RewardAccount -> Maybe (XPrv, Passphrase "encryption")
acctResolver acct = do
let acct' = toRewardAccountRaw $ toXPub $ fst stakeCreds
guard (acct == acct') $> stakeCreds
let policyResolver
:: KeyHash -> Maybe (XPrv, Passphrase "encryption")
policyResolver keyhash = do
let (keyhash', xprv, encP) = policyCreds
guard (keyhash == keyhash') $> (xprv, encP)
case cardanoTx sealedTx of
InAnyCardanoEra ByronEra _ ->
sealedTx
InAnyCardanoEra ShelleyEra (Cardano.Tx body wits) ->
signTransaction networkId acctResolver (const Nothing)
addressResolver inputResolver (body, wits)
& sealedTxFromCardano'
InAnyCardanoEra AllegraEra (Cardano.Tx body wits) ->
signTransaction networkId acctResolver (const Nothing)
addressResolver inputResolver (body, wits)
& sealedTxFromCardano'
InAnyCardanoEra MaryEra (Cardano.Tx body wits) ->
signTransaction networkId acctResolver policyResolver
addressResolver inputResolver (body, wits)
& sealedTxFromCardano'
InAnyCardanoEra AlonzoEra (Cardano.Tx body wits) ->
signTransaction networkId acctResolver policyResolver
addressResolver inputResolver (body, wits)
& sealedTxFromCardano'
InAnyCardanoEra BabbageEra (Cardano.Tx body wits) ->
signTransaction networkId acctResolver policyResolver
addressResolver inputResolver (body, wits)
& sealedTxFromCardano'
, mkUnsignedTransaction = \era stakeXPub _pp ctx selection -> do
let ttl = txValidityInterval ctx
let wdrl = withdrawalToCoin $ view #txWithdrawal ctx
let delta = selectionDelta txOutCoin selection
let rewardAcct = toRewardAccountRaw stakeXPub
let assetsToBeMinted = view #txAssetsToMint ctx
let assetsToBeBurned = view #txAssetsToBurn ctx
case view #txDelegationAction ctx of
Nothing -> do
withShelleyBasedEra era $ do
let md = view #txMetadata ctx
constructUnsignedTx networkId (md, []) ttl rewardAcct wdrl
selection delta assetsToBeMinted assetsToBeBurned
Just action -> do
withShelleyBasedEra era $ do
let certs = mkDelegationCertificates action stakeXPub
let payload = (view #txMetadata ctx, certs)
constructUnsignedTx networkId payload ttl rewardAcct wdrl
selection delta assetsToBeMinted assetsToBeBurned
, estimateSignedTxSize = \pp (Cardano.Tx body _) -> do
_estimateSignedTxSize pp body
, calcMinimumCost = \pp ctx skeleton ->
estimateTxCost pp (mkTxSkeleton (txWitnessTagFor @k) ctx skeleton)
<>
txFeePadding ctx
, maxScriptExecutionCost =
_maxScriptExecutionCost
, distributeSurplus = _distributeSurplus
, assignScriptRedeemers =
_assignScriptRedeemers
, evaluateMinimumFee =
_evaluateMinimumFee
, evaluateTransactionBalance = _evaluateTransactionBalance
, computeSelectionLimit = \pp ctx outputsToCover ->
let txMaxSize = getTxMaxSize $ txParameters pp in
MaximumInputLimit $
_estimateMaxNumberOfInputs @k txMaxSize ctx outputsToCover
, tokenBundleSizeAssessor =
Compatibility.tokenBundleSizeAssessor
, constraints = \pp -> txConstraints pp (txWitnessTagFor @k)
, decodeTx = _decodeSealedTx
, updateTx = updateSealedTx
}
_decodeSealedTx
:: SealedTx ->
( Tx
, TokenMapWithScripts
, TokenMapWithScripts
, [Certificate]
, Maybe ValidityIntervalExplicit
)
_decodeSealedTx (cardanoTx -> InAnyCardanoEra _era tx) = fromCardanoTx tx
_evaluateTransactionBalance
:: forall era. IsShelleyBasedEra era
=> Cardano.Tx era
-> Cardano.ProtocolParameters
-> UTxO
-> [(TxIn, TxOut, Maybe (Hash "Datum"))]
-> Cardano.Value
_evaluateTransactionBalance (Cardano.Tx body _) pp utxo extraUTxO =
let
utxo' = Map.fromList
. map (bimap toCardanoTxIn (toCardanoTxOut era))
. Map.toList
$ unUTxO utxo
extraUTxO' = Map.fromList
. map (\(i, o, mDatumHash) ->
(toCardanoTxIn i
, setDatumHash era mDatumHash (toCardanoTxOut era o))
)
$ extraUTxO
in
lovelaceFromCardanoTxOutValue
$ Cardano.evaluateTransactionBalance
pp
mempty
(Cardano.UTxO $ utxo' <> extraUTxO')
-- The two UTxO sets could overlap here. When called by
-- 'balanceTransaction' the user-specified input resolution
-- will overwrite the wallet UTxO (if in conflict).
--
-- If the overridden outputs are incorrect, the wallet will
-- incorrectly calculate the balance, and the transaction
-- will ultimately be rejected by the node.
--
-- If the overwridden outputs simply adds datum hashes
-- (which the wallet cannot currently represent), this
-- shouldn't affect the balance.
--
-- Ultimately, however, it might be be wiser to error out of
-- caution.
--
-- NOTE: There is a similar case in the 'resolveInput' of
-- 'balanceTransaction'.
body
where
era = Cardano.shelleyBasedEra @era
setDatumHash
:: ShelleyBasedEra era
-> Maybe (Hash "Datum")
-> Cardano.TxOut ctx era
-> Cardano.TxOut ctx era
setDatumHash _era Nothing o = o
setDatumHash _era
(Just (Hash datumHash)) (Cardano.TxOut addr val _ refScript) =
Cardano.TxOut addr val
(Cardano.TxOutDatumHash scriptDataSupported hash) refScript
where
scriptDataSupported = case era of
ShelleyBasedEraBabbage -> Cardano.ScriptDataInBabbageEra
ShelleyBasedEraAlonzo -> Cardano.ScriptDataInAlonzoEra
ShelleyBasedEraMary -> errBadEra
ShelleyBasedEraAllegra -> errBadEra
ShelleyBasedEraShelley -> errBadEra
where
-- FIXME [ADP-1479] Proper error handling
errBadEra = error $ unwords
[ "evaluateTransactionBalance:"
, "cannot add a datum hash to the transaction body of an"
, "era that doesn't support datum hashes."
]
hash = fromMaybe errBadHash $ Cardano.deserialiseFromRawBytes
(Cardano.AsHash Cardano.AsScriptData)
datumHash
where
-- FIXME [ADP-1479] Proper error handling
errBadHash = error $ unwords
[ "evaluateTransactionBalance: couldn't convert hash "
, show datumHash
]
lovelaceFromCardanoTxOutValue
:: Cardano.TxOutValue era -> Cardano.Value
lovelaceFromCardanoTxOutValue = \case
Cardano.TxOutAdaOnly _ ada -> Cardano.lovelaceToValue ada
Cardano.TxOutValue _ val -> val
mkDelegationCertificates
:: DelegationAction
-- Pool Id to which we're planning to delegate
-> XPub
-- Reward account public key
-> [Cardano.Certificate]
mkDelegationCertificates da accXPub =
case da of
Join poolId ->
[ toStakePoolDlgCert accXPub poolId ]
RegisterKeyAndJoin poolId ->
[ toStakeKeyRegCert accXPub
, toStakePoolDlgCert accXPub poolId
]
Quit -> [toStakeKeyDeregCert accXPub]
-- | For testing that
-- @
-- forall tx. updateSealedTx noTxUpdate tx
-- == Right tx or Left
-- @
noTxUpdate :: TxUpdate
noTxUpdate = TxUpdate [] [] [] UseOldTxFee
-- 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.
updateSealedTx
:: forall era. Cardano.IsShelleyBasedEra era
=> Cardano.Tx era
-> TxUpdate
-> Either ErrUpdateSealedTx (Cardano.Tx era)
updateSealedTx (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
modifyTxBody
:: TxUpdate
-> Cardano.TxBody era
-> Either ErrUpdateSealedTx (Cardano.TxBody era)
modifyTxBody ebc txBody@(Cardano.ShelleyTxBody {}) =
let Cardano.ShelleyTxBody shelleyEra bod scripts scriptData aux val
= txBody
in
Right $ Cardano.ShelleyTxBody shelleyEra
(modifyShelleyTxBody ebc shelleyEra bod)
scripts
scriptData
aux
val
modifyTxBody _ (Byron.ByronTxBody _) =
case Cardano.shelleyBasedEra @era of {}
-- 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
-> ShelleyBasedEra era
-> Ledger.TxBody (Cardano.ShelleyLedgerEra era)
-> Ledger.TxBody (Cardano.ShelleyLedgerEra era)
modifyShelleyTxBody txUpdate era ledgerBody = case era of
ShelleyBasedEraBabbage -> ledgerBody
{ Babbage.outputs = Babbage.outputs ledgerBody
<> StrictSeq.fromList
( Ledger.mkSized
. Cardano.toShelleyTxOut era
. Cardano.toCtxUTxOTxOut
. toCardanoTxOut era <$> 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
}
ShelleyBasedEraAlonzo -> ledgerBody
{ Alonzo.outputs = Alonzo.outputs ledgerBody
<> StrictSeq.fromList
( Cardano.toShelleyTxOut era
. Cardano.toCtxUTxOTxOut
. toCardanoTxOut era <$> extraOutputs
)
, Alonzo.inputs = Alonzo.inputs ledgerBody
<> Set.fromList (Cardano.toShelleyTxIn <$> extraInputs')
, Alonzo.collateral = Alonzo.collateral ledgerBody
<> Set.fromList (Cardano.toShelleyTxIn <$> extraCollateral')
, Alonzo.txfee =
modifyFee $ Alonzo.txfee ledgerBody
}
ShelleyBasedEraMary ->
let
ShelleyMA.TxBody
inputs outputs certs wdrls txfee vldt update adHash mint
= ledgerBody
toTxOut
= Cardano.toShelleyTxOut era
. Cardano.toCtxUTxOTxOut
. toCardanoTxOut era
in
ShelleyMA.TxBody
(inputs <> Set.fromList (Cardano.toShelleyTxIn <$> extraInputs'))
(outputs <> StrictSeq.fromList (toTxOut <$> extraOutputs))
certs
wdrls
(modifyFee txfee)
vldt
update
adHash
mint
ShelleyBasedEraAllegra ->
let
ShelleyMA.TxBody
inputs outputs certs wdrls txfee vldt update adHash mint
= ledgerBody
toTxOut
= Cardano.toShelleyTxOut era
. Cardano.toCtxUTxOTxOut
. toCardanoTxOut era
in
ShelleyMA.TxBody
(inputs <> Set.fromList (Cardano.toShelleyTxIn <$> extraInputs'))
(outputs <> StrictSeq.fromList (toTxOut <$> extraOutputs))
certs
wdrls
(modifyFee txfee)
vldt
update
adHash
mint
ShelleyBasedEraShelley ->
let
Shelley.TxBody inputs outputs certs wdrls txfee ttl txUpdate' mdHash
= ledgerBody
toTxOut
= Cardano.toShelleyTxOut era
. Cardano.toCtxUTxOTxOut
. toCardanoTxOut era
in
Shelley.TxBody
(inputs <> Set.fromList (Cardano.toShelleyTxIn <$> extraInputs'))
(outputs <> StrictSeq.fromList (toTxOut <$> extraOutputs))
certs
wdrls
(modifyFee txfee)
ttl
txUpdate'
mdHash
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)
-- NOTE / FIXME: This is an 'estimation' because it is actually quite hard to
-- estimate what would be the cost of a selecting a particular input. Indeed, an
-- input may contain any arbitrary assets, which has a direct impact on the
-- shape of change outputs. In practice, this should work out pretty well
-- because of other approximations done along the way which should compensate
-- for possible extra assets in inputs not counted as part of this estimation.
--
-- Worse that may happen here is the wallet generating a transaction that is
-- slightly too big, For a better user experience, we could detect that earlier
-- before submitting the transaction and return a more user-friendly error.
--
-- Or... to be even better, the 'SelectionLimit' from the RoundRobin module
-- could be a function of the 'SelectionState' already selected. With this
-- information and the shape of the requested output, we can get down to a
-- pretty accurate result.
_estimateMaxNumberOfInputs
:: forall k. TxWitnessTagFor k
=> Quantity "byte" Word16
-- ^ Transaction max size in bytes
-> TransactionCtx
-- ^ An additional transaction context
-> [TxOut]
-- ^ A list of outputs being considered.
-> Int
_estimateMaxNumberOfInputs txMaxSize ctx outs =
fromIntegral $ findLargestUntil ((> maxSize) . txSizeGivenInputs) 0
where
-- | Find the largest amount of inputs that doesn't make the tx too big.
-- Tries in sequence from 0 and upward (up to 255, but smaller than 50 in
-- practice because of the max transaction size).
findLargestUntil :: (Integer -> Bool) -> Integer -> Integer
findLargestUntil isTxTooLarge inf
| inf == maxNInps = maxNInps
| isTxTooLarge (inf + 1) = inf
| otherwise = findLargestUntil isTxTooLarge (inf + 1)
maxSize = toInteger (getQuantity txMaxSize)
maxNInps = 255 -- Arbitrary, but large enough.
txSizeGivenInputs nInps = fromIntegral size
where
TxSize size = estimateTxSize $ mkTxSkeleton
(txWitnessTagFor @k) ctx sel
sel = dummySkeleton (fromIntegral nInps) outs
dummySkeleton :: Int -> [TxOut] -> SelectionSkeleton
dummySkeleton inputCount outputs = SelectionSkeleton
{ skeletonInputCount =
inputCount
, skeletonOutputs =
outputs
, skeletonChange =
TokenBundle.getAssets . view #tokens <$> outputs
}
-- ^ Evaluate a minimal fee amount necessary to pay for a given tx
-- using ledger's functionality
--
-- Will estimate how many witnesses there /should be/, so it works even