/
Typed.hs
3146 lines (2547 loc) · 107 KB
/
Typed.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 GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DefaultSignatures #-}
-- The Shelley ledger uses promoted data kinds which we have to use, but we do
-- not export any from this API. We also use them unticked as nature intended.
{-# LANGUAGE DataKinds #-}
{-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-}
-- | This module provides a library interface for interacting with Cardano as
-- a user of the system.
--
-- It is intended to be used to write tools and
--
-- In the interest of simplicity it glosses over some details of the system.
-- Most simple tools should be able to work just using this interface,
-- however you can go deeper and expose the types from the underlying libraries
-- using "Cardano.Api.Byron" or "Cardano.Api.Shelley".
--
module Cardano.Api.Typed (
-- * Eras
Byron,
Shelley,
HasTypeProxy(..),
AsType(..),
-- * Cryptographic key interface
-- $keys
Key,
VerificationKey(..),
SigningKey(..),
getVerificationKey,
verificationKeyHash,
castVerificationKey,
castSigningKey,
-- ** Generating keys
generateSigningKey,
deterministicSigningKey,
deterministicSigningKeySeedSize,
Crypto.Seed,
Crypto.mkSeedFromBytes,
Crypto.readSeedFromSystemEntropy,
-- ** Hashes
-- | In Cardano most keys are identified by their hash, and hashes are
-- used in many other places.
Hash(..),
castHash,
-- * Payment addresses
-- | Constructing and inspecting normal payment addresses
Address(..),
NetworkId(..),
-- * Byron addresses
makeByronAddress,
ByronKey,
-- * Shelley addresses
makeShelleyAddress,
PaymentCredential(..),
StakeAddressReference(..),
PaymentKey,
-- * Stake addresses
-- | Constructing and inspecting stake addresses
StakeAddress(..),
StakeCredential(..),
makeStakeAddress,
StakeKey,
-- * Building transactions
-- | Constructing and inspecting transactions
TxBody(..),
TxId,
getTxId,
TxIn(..),
TxOut(..),
TxIx,
Lovelace(..),
makeByronTransaction,
makeShelleyTransaction,
SlotNo,
TxExtraContent(..),
txExtraContentEmpty,
Certificate,
-- * Signing transactions
-- | Creating transaction witnesses one by one, or all in one go.
Tx(..),
getTxBody,
getTxWitnesses,
-- ** Signing in one go
signByronTransaction,
signShelleyTransaction,
-- ** Incremental signing and separate witnesses
makeSignedTransaction,
Witness(..),
makeByronKeyWitness,
ShelleyWitnessSigningKey(..),
makeShelleyKeyWitness,
makeShelleyBootstrapWitness,
makeShelleyScriptWitness,
-- * Fee calculation
transactionFee,
estimateTransactionFee,
-- * Transaction metadata
-- | Embedding additional structured data within transactions.
TxMetadata,
TxMetadataValue(..),
makeTransactionMetadata,
-- * Registering stake address and delegating
-- | Certificates that are embedded in transactions for registering and
-- unregistering stake address, and for setting the stake pool delegation
-- choice for a stake address.
makeStakeAddressRegistrationCertificate,
makeStakeAddressDeregistrationCertificate,
makeStakeAddressDelegationCertificate,
-- * Registering stake pools
-- | Certificates that are embedded in transactions for registering and
-- retiring stake pools. This incldes updating the stake pool parameters.
makeStakePoolRegistrationCertificate,
makeStakePoolRetirementCertificate,
StakePoolParameters(..),
StakePoolRelay(..),
StakePoolMetadataReference(..),
-- ** Stake pool off-chain metadata
StakePoolMetadata(..),
validateAndHashStakePoolMetadata,
StakePoolMetadataValidationError(..),
-- * Scripts
-- | Both 'PaymentCredential's and 'StakeCredential's can use scripts.
-- Shelley supports multi-signatures via scripts.
-- ** Script addresses
-- | Making addresses from scripts.
-- ** Multi-sig scripts
-- | Making multi-signature scripts.
-- * Serialisation
-- | Support for serialising data in JSON, CBOR and text files.
-- ** CBOR
SerialiseAsCBOR,
ToCBOR,
FromCBOR,
serialiseToCBOR,
deserialiseFromCBOR,
-- ** JSON
ToJSON,
FromJSON,
serialiseToJSON,
deserialiseFromJSON,
-- ** Bech32
SerialiseAsBech32,
Bech32EncodeError(..),
Bech32DecodeError(..),
serialiseToBech32,
deserialiseFromBech32,
renderBech32EncodeError,
renderBech32DecodeError,
-- ** Raw binary
-- | Some types have a natural raw binary format.
SerialiseAsRawBytes,
serialiseToRawBytes,
deserialiseFromRawBytes,
serialiseToRawBytesHex,
deserialiseFromRawBytesHex,
-- ** Text envelope
-- | Support for a envelope file format with text headers and a hex-encoded
-- binary payload.
HasTextEnvelope(..),
TextEnvelope,
TextEnvelopeType,
TextEnvelopeDescr,
TextEnvelopeError,
serialiseToTextEnvelope,
deserialiseFromTextEnvelope,
readFileTextEnvelope,
writeFileTextEnvelope,
-- *** Reading one of several key types
FromSomeType(..),
deserialiseFromTextEnvelopeAnyOf,
readFileTextEnvelopeAnyOf,
-- * Errors
Error(..),
throwErrorAsException,
FileError(..),
-- * Node interaction
-- | Operations that involve talking to a local Cardano node.
-- ** Queries
-- ** Submitting transactions
-- ** Low level protocol interaction with a Cardano node
connectToLocalNode,
LocalNodeClientProtocols(..),
nullLocalNodeClientProtocols,
-- connectToRemoteNode,
-- *** Chain sync protocol
ChainSyncClient(..),
-- *** Local tx submission
LocalTxSubmissionClient(..),
-- *** Local state query
LocalStateQueryClient(..),
-- * Node operation
-- | Support for the steps needed to operate a node, including the
-- operator's offline keys, operational KES and VRF keys, and operational
-- certificates.
-- ** Stake pool operator's keys
StakePoolKey,
PoolId,
-- ** KES keys
KesKey,
-- ** VRF keys
VrfKey,
-- ** Operational certificates
OperationalCertificate(..),
OperationalCertificateIssueCounter(..),
Shelley.KESPeriod(..),
OperationalCertIssueError(..),
issueOperationalCertificate,
-- * Genesis file
-- | Types and functions needed to inspect or create a genesis file.
GenesisKey,
GenesisDelegateKey,
GenesisUTxOKey,
-- * Special transactions
-- | There are various additional things that can be embedded in a
-- transaction for special operations.
makeMIRCertificate,
makeGenesisKeyDelegationCertificate,
-- ** Protocol parameter updates
UpdateProposal,
ProtocolParametersUpdate(..),
makeShelleyUpdateProposal,
) where
import Prelude
import Data.Proxy (Proxy(..))
import Data.Kind (Constraint)
import Data.Void (Void)
import Data.Word
import Data.Maybe
import Data.Bifunctor (first)
import Data.List as List
import qualified Data.List.NonEmpty as NonEmpty
--import Data.Either
import Data.String (IsString(fromString))
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import Numeric.Natural
import Data.IP (IPv4, IPv6)
import Network.Socket (PortNumber)
import qualified Network.URI as URI
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Base16 as Base16
import qualified Data.Set as Set
import qualified Data.Map.Strict as Map
import Data.Map.Strict (Map)
import qualified Data.Sequence.Strict as Seq
import qualified Data.Vector as Vector
import qualified Codec.Binary.Bech32 as Bech32
import Control.Monad
--import Control.Monad.IO.Class
--import Control.Monad.Trans.Except
import Control.Monad.Trans.Except.Extra
import Control.Exception (Exception(..), IOException, throwIO)
import Control.Tracer (nullTracer)
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Types as Aeson
import Data.Aeson (ToJSON(..), FromJSON(..), (.:))
--
-- Common types, consensus, network
--
import qualified Cardano.Binary as CBOR
import Cardano.Binary
(ToCBOR(toCBOR), FromCBOR(fromCBOR),
Annotated(..), reAnnotate, recoverBytes)
import qualified Cardano.Prelude as CBOR (cborError)
import Shelley.Spec.Ledger.Serialization (CBORGroup(..))
import Cardano.Slotting.Slot (SlotNo, EpochNo)
-- TODO: it'd be nice if the network imports needed were a bit more coherent
import Ouroboros.Network.Block (Tip)
import Ouroboros.Network.Magic (NetworkMagic(..))
import Ouroboros.Network.NodeToClient
(NodeToClientProtocols(..), NodeToClientVersionData(..),
NetworkConnectTracers(..), withIOManager, connectTo,
localSnocket, foldMapVersions,
versionedNodeToClientProtocols, chainSyncPeerNull,
localTxSubmissionPeerNull, localStateQueryPeerNull)
import Ouroboros.Network.Mux
(MuxMode(InitiatorMode), MuxPeer(..),
RunMiniProtocol(InitiatorProtocolOnly))
-- TODO: it'd be nice if the consensus imports needed were a bit more coherent
import Ouroboros.Consensus.Cardano (ProtocolClient, protocolClientInfo)
import Ouroboros.Consensus.Block (BlockProtocol)
import Ouroboros.Consensus.Ledger.Abstract (Query)
import Ouroboros.Consensus.Ledger.SupportsMempool (ApplyTxErr, GenTx)
import Ouroboros.Consensus.Network.NodeToClient
(Codecs'(..), clientCodecs)
import Ouroboros.Consensus.Node.ProtocolInfo (ProtocolClientInfo(..))
import Ouroboros.Consensus.Node.NetworkProtocolVersion
(BlockNodeToClientVersion, TranslateNetworkProtocolVersion,
nodeToClientProtocolVersion, supportedNodeToClientVersions)
import Ouroboros.Consensus.Node.Run (SerialiseNodeToClientConstraints)
--
-- Crypto API used by consensus and Shelley (and should be used by Byron)
--
import qualified Cardano.Crypto.Seed as Crypto
import qualified Cardano.Crypto.Hash.Class as Crypto
import qualified Cardano.Crypto.DSIGN.Class as Crypto
import qualified Cardano.Crypto.KES.Class as Crypto
import qualified Cardano.Crypto.VRF.Class as Crypto
--
-- Byron imports
--
import qualified Cardano.Crypto.Hashing as Byron
import qualified Cardano.Crypto.Signing as Byron
import qualified Cardano.Crypto.ProtocolMagic as Byron
import qualified Cardano.Crypto.Wallet as Byron.Crypto.Wallet
import qualified Cardano.Chain.Common as Byron
import qualified Cardano.Chain.Genesis as Byron
import qualified Cardano.Chain.UTxO as Byron
--
-- Shelley imports
--
import qualified Ouroboros.Consensus.Shelley.Protocol.Crypto as Shelley
import qualified Shelley.Spec.Ledger.Address as Shelley
import qualified Shelley.Spec.Ledger.Address.Bootstrap as Shelley
import qualified Shelley.Spec.Ledger.BaseTypes as Shelley
import Shelley.Spec.Ledger.BaseTypes (maybeToStrictMaybe)
import qualified Shelley.Spec.Ledger.Coin as Shelley
import qualified Shelley.Spec.Ledger.Credential as Shelley
import qualified Shelley.Spec.Ledger.LedgerState as Shelley
import qualified Shelley.Spec.Ledger.Keys as Shelley
import qualified Shelley.Spec.Ledger.MetaData as Shelley
import qualified Shelley.Spec.Ledger.OCert as Shelley
import qualified Shelley.Spec.Ledger.PParams as Shelley
import qualified Shelley.Spec.Ledger.Scripts as Shelley
import qualified Shelley.Spec.Ledger.TxData as Shelley
import qualified Shelley.Spec.Ledger.Tx as Shelley
import qualified Shelley.Spec.Ledger.UTxO as Shelley
-- Types we will re-export as-is
import Shelley.Spec.Ledger.TxData
(MIRPot(..))
-- TODO: replace the above with
--import qualified Cardano.Api.Byron as Byron
--import qualified Cardano.Api.Shelley as Shelley
--
-- Other config and common types
--
import qualified Cardano.Api.TextView as TextView
import Ouroboros.Network.Protocol.ChainSync.Client
import Ouroboros.Network.Protocol.LocalTxSubmission.Client
import Ouroboros.Network.Protocol.LocalStateQuery.Client
-- ----------------------------------------------------------------------------
-- Cardano eras, sometimes we have to distinguish them
--
-- | A type used as a tag to distinguish the Byron era.
data Byron
-- | A type used as a tag to distinguish the Shelley era.
data Shelley
class HasTypeProxy t where
-- | A family of singleton types used in this API to indicate which type to
-- use where it would otherwise be ambiguous or merely unclear.
--
-- Values of this type are passed to
--
data AsType t
proxyToAsType :: Proxy t -> AsType t
-- ----------------------------------------------------------------------------
-- Keys key keys!
--
-- $keys
-- Cardano has lots of cryptographic keys used for lots of different purposes.
-- Some keys have different representations, but most are just using keys in
-- different roles.
--
-- To allow for the different representations and to avoid mistakes we
-- distinguish the key /role/. These are type level distinctions, so each of
-- these roles is a type level tag.
--
-- | An interface for cryptographic keys used for signatures with a 'SigningKey'
-- and a 'VerificationKey' key.
--
-- This interface does not provide actual signing or verifying functions since
-- this API is concerned with the management of keys: generating and
-- serialising.
--
class (Eq (VerificationKey keyrole),
Show (VerificationKey keyrole),
Show (SigningKey keyrole),
SerialiseAsRawBytes (Hash keyrole),
HasTextEnvelope (VerificationKey keyrole),
HasTextEnvelope (SigningKey keyrole))
=> Key keyrole where
-- | The type of cryptographic verification key, for each key role.
data VerificationKey keyrole :: *
-- | The type of cryptographic signing key, for each key role.
data SigningKey keyrole :: *
-- | Get the corresponding verification key from a signing key.
getVerificationKey :: SigningKey keyrole -> VerificationKey keyrole
-- | Generate a 'SigningKey' deterministically, given a 'Crypto.Seed'. The
-- required size of the seed is given by 'deterministicSigningKeySeedSize'.
--
deterministicSigningKey :: AsType keyrole -> Crypto.Seed -> SigningKey keyrole
deterministicSigningKeySeedSize :: AsType keyrole -> Word
verificationKeyHash :: VerificationKey keyrole -> Hash keyrole
-- | Generate a 'SigningKey' using a seed from operating system entropy.
--
generateSigningKey :: Key keyrole => AsType keyrole -> IO (SigningKey keyrole)
generateSigningKey keytype = do
seed <- Crypto.readSeedFromSystemEntropy seedSize
return $! deterministicSigningKey keytype seed
where
seedSize = deterministicSigningKeySeedSize keytype
-- | Some key roles share the same representation and it is sometimes
-- legitimate to change the role of a key.
--
class CastKeyRole keyroleA keyroleB where
-- | Change the role of a 'VerificationKey', if the representation permits.
castVerificationKey :: VerificationKey keyroleA -> VerificationKey keyroleB
-- | Change the role of a 'SigningKey', if the representation permits.
castSigningKey :: SigningKey keyroleA -> SigningKey keyroleB
data family Hash keyrole :: *
class CastHash keyroleA keyroleB where
castHash :: Hash keyroleA -> Hash keyroleB
-- ----------------------------------------------------------------------------
-- Addresses
--
data Address era where
-- | Byron addresses are valid in both the Byron and Shelley era.
--
ByronAddress
:: Byron.Address
-> Address era
-- | Shelley addresses are only valid in the Shelley era.
--
ShelleyAddress
:: Shelley.Network
-> Shelley.PaymentCredential ShelleyCrypto
-> Shelley.StakeReference ShelleyCrypto
-> Address Shelley
deriving instance Eq (Address Byron)
deriving instance Show (Address Byron)
deriving instance Eq (Address Shelley)
deriving instance Show (Address Shelley)
data StakeAddress where
StakeAddress
:: Shelley.Network
-> Shelley.StakeCredential ShelleyCrypto
-> StakeAddress
deriving (Eq, Show)
data NetworkId
= Mainnet
| Testnet !NetworkMagic
deriving (Eq, Show)
data PaymentCredential
= PaymentCredentialByKey (Hash PaymentKey)
| PaymentCredentialByScript (Hash Script)
deriving (Eq, Show)
data StakeCredential
= StakeCredentialByKey (Hash StakeKey)
| StakeCredentialByScript (Hash Script)
deriving (Eq, Show)
data StakeAddressReference
= StakeAddressByValue StakeCredential
| StakeAddressByPointer StakeAddressPointer
| NoStakeAddress
deriving (Eq, Show)
type StakeAddressPointer = Shelley.Ptr
instance HasTypeProxy (Address Byron) where
data AsType (Address Byron) = AsByronAddress
proxyToAsType _ = AsByronAddress
instance HasTypeProxy (Address Shelley) where
data AsType (Address Shelley) = AsShelleyAddress
proxyToAsType _ = AsShelleyAddress
instance HasTypeProxy StakeAddress where
data AsType StakeAddress = AsStakeAddress
proxyToAsType _ = AsStakeAddress
instance SerialiseAsRawBytes (Address Byron) where
serialiseToRawBytes (ByronAddress addr) = CBOR.serialize' addr
deserialiseFromRawBytes AsByronAddress bs =
case CBOR.decodeFull' bs of
Left _ -> Nothing
Right addr -> Just (ByronAddress addr)
instance SerialiseAsRawBytes (Address Shelley) where
serialiseToRawBytes (ByronAddress addr) =
Shelley.serialiseAddr
. Shelley.AddrBootstrap
. Shelley.BootstrapAddress
$ addr
serialiseToRawBytes (ShelleyAddress nw pc scr) =
Shelley.serialiseAddr (Shelley.Addr nw pc scr)
deserialiseFromRawBytes AsShelleyAddress bs =
case Shelley.deserialiseAddr bs of
Nothing -> Nothing
Just (Shelley.Addr nw pc scr) ->
Just (ShelleyAddress nw pc scr)
Just (Shelley.AddrBootstrap (Shelley.BootstrapAddress addr)) ->
Just (ByronAddress addr)
instance SerialiseAsRawBytes StakeAddress where
serialiseToRawBytes (StakeAddress nw sc) =
Shelley.serialiseRewardAcnt (Shelley.RewardAcnt nw sc)
deserialiseFromRawBytes AsStakeAddress bs =
case Shelley.deserialiseRewardAcnt bs of
Nothing -> Nothing
Just (Shelley.RewardAcnt nw sc) -> Just (StakeAddress nw sc)
instance SerialiseAsBech32 (Address Shelley) where
humanReadablePrefix (ByronAddress _) =
error "TODO @intricate: What do we do about this?"
humanReadablePrefix (ShelleyAddress nw _ _) =
case Bech32.humanReadablePartFromText prefix of
Left err -> error $ "Impossible: " <> show err
Right hrp -> hrp
where
prefix :: Text
prefix =
case nw of
Shelley.Mainnet -> "addr_"
Shelley.Testnet -> "addr_test_"
instance SerialiseAsBech32 StakeAddress where
humanReadablePrefix (StakeAddress nw _ ) =
case Bech32.humanReadablePartFromText prefix of
Left err -> error $ "Impossible: " <> show err
Right hrp -> hrp
where
prefix :: Text
prefix =
case nw of
Shelley.Mainnet -> "stake_"
Shelley.Testnet -> "stake_test_"
makeByronAddress :: VerificationKey ByronKey
-> NetworkId
-> Address era
makeByronAddress (ByronVerificationKey vk) nid =
ByronAddress $
Byron.makeVerKeyAddress
(toByronNetworkMagic nid)
vk
makeShelleyAddress :: NetworkId
-> PaymentCredential
-> StakeAddressReference
-> Address Shelley
makeShelleyAddress nw pc scr =
ShelleyAddress
(toShelleyNetwork nw)
(toShelleyPaymentCredential pc)
(toShelleyStakeReference scr)
makeStakeAddress :: NetworkId
-> StakeCredential
-> StakeAddress
makeStakeAddress nw sc =
StakeAddress
(toShelleyNetwork nw)
(toShelleyStakeCredential sc)
toByronProtocolMagicId :: NetworkId -> Byron.ProtocolMagicId
toByronProtocolMagicId Mainnet = Byron.mainnetProtocolMagicId
toByronProtocolMagicId (Testnet (NetworkMagic pm)) = Byron.ProtocolMagicId pm
toByronNetworkMagic :: NetworkId -> Byron.NetworkMagic
toByronNetworkMagic Mainnet = Byron.NetworkMainOrStage
toByronNetworkMagic (Testnet (NetworkMagic nm)) = Byron.NetworkTestnet nm
toShelleyNetwork :: NetworkId -> Shelley.Network
toShelleyNetwork Mainnet = Shelley.Mainnet
toShelleyNetwork (Testnet _) = Shelley.Testnet
toNetworkMagic :: NetworkId -> NetworkMagic
toNetworkMagic Mainnet = NetworkMagic 764824073
toNetworkMagic (Testnet nm) = nm
toShelleyAddr :: Address era -> Shelley.Addr ShelleyCrypto
toShelleyAddr (ByronAddress addr) = Shelley.AddrBootstrap
(Shelley.BootstrapAddress addr)
toShelleyAddr (ShelleyAddress nw pc scr) = Shelley.Addr nw pc scr
toShelleyStakeAddr :: StakeAddress -> Shelley.RewardAcnt ShelleyCrypto
toShelleyStakeAddr (StakeAddress nw sc) =
Shelley.RewardAcnt {
Shelley.getRwdNetwork = nw,
Shelley.getRwdCred = sc
}
toShelleyPaymentCredential :: PaymentCredential
-> Shelley.PaymentCredential ShelleyCrypto
toShelleyPaymentCredential (PaymentCredentialByKey (PaymentKeyHash kh)) =
Shelley.KeyHashObj kh
toShelleyPaymentCredential (PaymentCredentialByScript (ScriptHash sh)) =
Shelley.ScriptHashObj sh
toShelleyStakeCredential :: StakeCredential
-> Shelley.StakeCredential ShelleyCrypto
toShelleyStakeCredential (StakeCredentialByKey (StakeKeyHash kh)) =
Shelley.KeyHashObj kh
toShelleyStakeCredential (StakeCredentialByScript (ScriptHash kh)) =
Shelley.ScriptHashObj kh
toShelleyStakeReference :: StakeAddressReference
-> Shelley.StakeReference ShelleyCrypto
toShelleyStakeReference (StakeAddressByValue stakecred) =
Shelley.StakeRefBase (toShelleyStakeCredential stakecred)
toShelleyStakeReference (StakeAddressByPointer ptr) =
Shelley.StakeRefPtr ptr
toShelleyStakeReference NoStakeAddress =
Shelley.StakeRefNull
-- ----------------------------------------------------------------------------
-- Transaction Ids
--
newtype TxId = TxId (Shelley.Hash ShelleyCrypto ())
deriving (Eq, Ord, Show)
-- We use the Shelley representation and convert the Byron one
instance HasTypeProxy TxId where
data AsType TxId = AsTxId
proxyToAsType _ = AsTxId
instance SerialiseAsRawBytes TxId where
serialiseToRawBytes (TxId h) = Crypto.getHash h
deserialiseFromRawBytes AsTxId bs = TxId <$> Crypto.hashFromBytes bs
toByronTxId :: TxId -> Byron.TxId
toByronTxId (TxId (Crypto.UnsafeHash h)) =
Byron.unsafeHashFromBytes h
toShelleyTxId :: TxId -> Shelley.TxId ShelleyCrypto
toShelleyTxId (TxId h) =
Shelley.TxId (Crypto.castHash h)
-- | Calculate the transaction identifier for a 'TxBody'.
--
getTxId :: TxBody era -> TxId
getTxId (ByronTxBody tx) =
TxId
. Crypto.UnsafeHash
. recoverBytes
$ tx
getTxId (ShelleyTxBody tx) =
TxId
. Crypto.castHash
. (\(Shelley.TxId txhash) -> txhash)
. Shelley.txid
$ tx
-- ----------------------------------------------------------------------------
-- Transaction constituent types
--
data TxIn = TxIn TxId TxIx
deriving instance Eq TxIn
deriving instance Show TxIn
newtype TxIx = TxIx Word
deriving stock (Eq, Ord, Show)
deriving newtype (Enum)
data TxOut era = TxOut (Address era) Lovelace
deriving instance Eq (TxOut Byron)
deriving instance Eq (TxOut Shelley)
deriving instance Show (TxOut Byron)
deriving instance Show (TxOut Shelley)
newtype Lovelace = Lovelace Integer
deriving (Eq, Ord, Enum, Show)
toByronTxIn :: TxIn -> Byron.TxIn
toByronTxIn (TxIn txid (TxIx txix)) =
Byron.TxInUtxo (toByronTxId txid) (fromIntegral txix)
toByronTxOut :: TxOut Byron -> Maybe Byron.TxOut
toByronTxOut (TxOut (ByronAddress addr) value) =
Byron.TxOut addr <$> toByronLovelace value
toByronLovelace :: Lovelace -> Maybe Byron.Lovelace
toByronLovelace (Lovelace x) =
case Byron.integerToLovelace x of
Left _ -> Nothing
Right x' -> Just x'
toShelleyTxIn :: TxIn -> Shelley.TxIn ShelleyCrypto
toShelleyTxIn (TxIn txid (TxIx txix)) =
Shelley.TxIn (toShelleyTxId txid) (fromIntegral txix)
toShelleyTxOut :: TxOut era -> Shelley.TxOut ShelleyCrypto
toShelleyTxOut (TxOut addr value) =
Shelley.TxOut (toShelleyAddr addr) (toShelleyLovelace value)
toShelleyLovelace :: Lovelace -> Shelley.Coin
toShelleyLovelace (Lovelace l) = Shelley.Coin l
--TODO: validate bounds
-- ----------------------------------------------------------------------------
-- Unsigned transactions
--
data TxBody era where
ByronTxBody
:: Annotated Byron.Tx ByteString
-> TxBody Byron
ShelleyTxBody
:: Shelley.TxBody ShelleyCrypto
-> TxBody Shelley
instance HasTypeProxy (TxBody Byron) where
data AsType (TxBody Byron) = AsByronTxBody
proxyToAsType _ = AsByronTxBody
instance HasTypeProxy (TxBody Shelley) where
data AsType (TxBody Shelley) = AsShelleyTxBody
proxyToAsType _ = AsShelleyTxBody
instance SerialiseAsCBOR (TxBody Byron) where
serialiseToCBOR (ByronTxBody txbody) =
recoverBytes txbody
deserialiseFromCBOR AsByronTxBody bs = do
ByronTxBody <$>
CBOR.decodeFullAnnotatedBytes
"Byron TxBody"
CBOR.fromCBORAnnotated
(LBS.fromStrict bs)
instance SerialiseAsCBOR (TxBody Shelley) where
serialiseToCBOR (ShelleyTxBody txbody) =
CBOR.serialize' txbody
deserialiseFromCBOR AsShelleyTxBody bs =
ShelleyTxBody <$>
CBOR.decodeAnnotator
"Shelley TxBody"
fromCBOR
(LBS.fromStrict bs)
instance HasTextEnvelope (TxBody Byron) where
textEnvelopeType _ = "TxUnsignedByron"
instance HasTextEnvelope (TxBody Shelley) where
textEnvelopeType _ = "TxUnsignedShelley"
data ByronTxBodyConversionError =
ByronTxBodyEmptyTxIns
| ByronTxBodyEmptyTxOuts
| ByronTxBodyLovelaceOverflow (TxOut Byron)
makeByronTransaction :: [TxIn]
-> [TxOut Byron]
-> Either ByronTxBodyConversionError
(TxBody Byron)
makeByronTransaction ins outs = do
ins' <- NonEmpty.nonEmpty ins ?! ByronTxBodyEmptyTxIns
let ins'' = NonEmpty.map toByronTxIn ins'
outs' <- NonEmpty.nonEmpty outs ?! ByronTxBodyEmptyTxOuts
outs'' <- traverse
(\out -> toByronTxOut out ?! ByronTxBodyLovelaceOverflow out)
outs'
return $
ByronTxBody $
reAnnotate $
Annotated
(Byron.UnsafeTx ins'' outs'' (Byron.mkAttributes ()))
()
data TxExtraContent =
TxExtraContent {
txMetadata :: Maybe TxMetadata,
txWithdrawals :: [(StakeAddress, Lovelace)],
txCertificates :: [Certificate],
txUpdateProposal :: Maybe UpdateProposal
}
txExtraContentEmpty :: TxExtraContent
txExtraContentEmpty =
TxExtraContent {
txMetadata = Nothing,
txWithdrawals = [],
txCertificates = [],
txUpdateProposal = Nothing
}
type TxFee = Lovelace
type TTL = SlotNo
makeShelleyTransaction :: TxExtraContent
-> TTL
-> TxFee
-> [TxIn]
-> [TxOut anyera]
-> TxBody Shelley
makeShelleyTransaction TxExtraContent {
txMetadata,
txWithdrawals,
txCertificates,
txUpdateProposal
} ttl fee ins outs =
--TODO: validate the txins are not empty, and tx out coin values are in range
ShelleyTxBody
(Shelley.TxBody
(Set.fromList (map toShelleyTxIn ins))
(Seq.fromList (map toShelleyTxOut outs))
(Seq.fromList [ cert | Certificate cert <- txCertificates ])
(toShelleyWdrl txWithdrawals)
(toShelleyLovelace fee)
ttl
(toShelleyUpdate <$> maybeToStrictMaybe txUpdateProposal)
(toShelleyMetadataHash <$> maybeToStrictMaybe txMetadata))
where
toShelleyUpdate (UpdateProposal p) = p
toShelleyMetadataHash (TxMetadata m) = Shelley.hashMetaData m
toShelleyWdrl :: [(StakeAddress, Lovelace)] -> Shelley.Wdrl ShelleyCrypto
toShelleyWdrl wdrls =
Shelley.Wdrl $
Map.fromList
[ (toShelleyStakeAddr stakeAddr, toShelleyLovelace value)
| (stakeAddr, value) <- wdrls ]
-- ----------------------------------------------------------------------------
-- Signed transactions
--
data Tx era where
ByronTx
:: Byron.ATxAux ByteString
-> Tx Byron
ShelleyTx
:: Shelley.Tx ShelleyCrypto
-> Tx Shelley
instance HasTypeProxy (Tx Byron) where
data AsType (Tx Byron) = AsByronTx
proxyToAsType _ = AsByronTx
instance HasTypeProxy (Tx Shelley) where
data AsType (Tx Shelley) = AsShelleyTx
proxyToAsType _ = AsShelleyTx
instance SerialiseAsCBOR (Tx Byron) where
serialiseToCBOR (ByronTx tx) = CBOR.recoverBytes tx
deserialiseFromCBOR AsByronTx bs =