/
Types.hs
1989 lines (1686 loc) · 63.7 KB
/
Types.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
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ViewPatterns #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- This module contains the core primitive of a Wallet. This is roughly a
-- Haskell translation of the [Formal Specification for a Cardano Wallet](https://github.com/input-output-hk/cardano-wallet/blob/master/specifications/wallet/formal-specification-for-a-cardano-wallet.pdf)
--
-- It doesn't contain any particular business-logic code, but defines a few
-- primitive operations on Wallet core types as well.
module Cardano.Wallet.Primitive.Types
(
-- * Block
Block(..)
, BlockHeader(..)
-- * Tx
, Tx (..)
, TxIn(..)
, TxOut(..)
, TxMeta(..)
, TxMetadata(..)
, TxMetadataValue(..)
, Direction(..)
, TxStatus(..)
, SealedTx (..)
, TransactionInfo (..)
, UnsignedTx (..)
, txIns
, isPending
, inputs
, fromTransactionInfo
, toTxHistory
, txMetadataIsNull
-- * Address
, Address (..)
, AddressState (..)
, DerivationIndex (..)
-- * Delegation and stake pools
, CertificatePublicationTime (..)
, ChimericAccount (..)
, DelegationCertificate (..)
, dlgCertAccount
, dlgCertPoolId
, PoolLifeCycleStatus (..)
, PoolRegistrationCertificate (..)
, PoolRetirementCertificate (..)
, PoolCertificate (..)
, getPoolCertificatePoolId
, setPoolCertificatePoolId
, getPoolRegistrationCertificate
, getPoolRetirementCertificate
-- * Coin
, Coin (..)
, isValidCoin
-- * UTxO
, UTxO (..)
, balance
, balance'
, pickRandom
, excluding
, isSubsetOf
, restrictedBy
, restrictedTo
, Dom(..)
, UTxOStatistics (..)
, HistogramBar (..)
, BoundType
, computeUtxoStatistics
, computeStatistics
, log10
-- * Network Parameters
, NetworkParameters (..)
, GenesisParameters (..)
, SlottingParameters (..)
, ProtocolParameters (..)
, TxParameters (..)
, ActiveSlotCoefficient (..)
, DecentralizationLevel (..)
, EpochLength (..)
, EpochNo (..)
, unsafeEpochNo
, isValidEpochNo
, FeePolicy (..)
, SlotId (..)
, SlotNo (..)
, SlotLength (..)
, SlotInEpoch (..)
, StartTime (..)
-- * Wallet Metadata
, WalletMetadata(..)
, WalletId(..)
, WalletName(..)
, walletNameMinLength
, walletNameMaxLength
, WalletDelegation (..)
, WalletDelegationStatus (..)
, WalletDelegationNext (..)
, WalletPassphraseInfo(..)
, PassphraseScheme(..)
, WalletBalance(..)
, IsDelegatingTo (..)
-- * Stake Pools
, StakePool(..)
, PoolId(..)
, PoolOwner(..)
, StakeDistribution (..)
, poolIdBytesLength
, decodePoolIdBech32
, encodePoolIdBech32
, StakePoolMetadata (..)
, StakePoolMetadataHash (..)
, StakePoolMetadataUrl (..)
, StakePoolTicker (..)
, StakeKeyCertificate (..)
-- * Querying
, SortOrder (..)
-- * Ranges
, Range (..)
, RangeBound (..)
, wholeRange
, isAfterRange
, isBeforeRange
, isSubrangeOf
, isWithinRange
, mapRangeLowerBound
, mapRangeUpperBound
, rangeIsFinite
, rangeIsSingleton
, rangeIsValid
, rangeHasLowerBound
, rangeHasUpperBound
, rangeLowerBound
, rangeUpperBound
-- * ProtocolMagic
, ProtocolMagic (..)
, mainnetMagic
, testnetMagic
-- * Polymorphic
, Hash (..)
, ShowFmt (..)
, invariant
, distance
, hashFromText
-- * Settings
, Settings(..)
, SmashServer
, unSmashServer
, PoolMetadataSource( .. )
, defaultSettings
, unsafeToPMS
) where
import Prelude
import Cardano.Api.Typed
( TxMetadata (..), TxMetadataValue (..) )
import Cardano.Slotting.Slot
( SlotNo (..) )
import Cardano.Wallet.Orphans
()
import Control.Arrow
( left, right )
import Control.DeepSeq
( NFData (..) )
import Control.Monad
( guard, (<=<), (>=>) )
import Crypto.Hash
( Blake2b_160, Digest, digestFromByteString )
import Data.Aeson
( FromJSON (..), ToJSON (..), withObject, (.:), (.:?) )
import Data.Bifunctor
( bimap )
import Data.ByteArray
( ByteArrayAccess )
import Data.ByteArray.Encoding
( Base (Base16), convertFromBase, convertToBase )
import Data.ByteString
( ByteString )
import Data.Generics.Internal.VL.Lens
( set, view, (^.) )
import Data.Generics.Labels
()
import Data.Int
( Int32 )
import Data.List
( foldl', intercalate )
import Data.List.NonEmpty
( NonEmpty (..) )
import Data.Map.Strict
( Map )
import Data.Maybe
( isJust )
import Data.Proxy
( Proxy (..) )
import Data.Quantity
( Percentage (..), Quantity (..) )
import Data.Set
( Set )
import Data.String
( fromString )
import Data.Text
( Text )
import Data.Text.Class
( CaseStyle (..)
, FromText (..)
, TextDecodingError (..)
, ToText (..)
, fromTextToBoundedEnum
, toTextFromBoundedEnum
)
import Data.Time.Clock
( NominalDiffTime, UTCTime )
import Data.Time.Format
( defaultTimeLocale, formatTime )
import Data.Word
( Word16, Word32, Word64 )
import Data.Word.Odd
( Word31 )
import Fmt
( Buildable (..)
, blockListF
, blockListF'
, fixedF
, fmt
, indentF
, listF'
, nameF
, ordinalF
, padRightF
, prefixF
, pretty
, suffixF
, tupleF
)
import GHC.Generics
( Generic )
import GHC.Stack
( HasCallStack )
import GHC.TypeLits
( KnownNat, KnownSymbol, Symbol, natVal, symbolVal )
import Network.URI
( URI, parseAbsoluteURI, uriScheme, uriToString )
import Numeric.Natural
( Natural )
import System.Random
( randomRIO )
import qualified Codec.Binary.Bech32 as Bech32
import qualified Codec.Binary.Bech32.TH as Bech32
import qualified Control.Foldl as F
import qualified Data.ByteString as BS
import qualified Data.Char as C
import qualified Data.List as L
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy.Builder as Builder
{-------------------------------------------------------------------------------
Wallet Metadata
-------------------------------------------------------------------------------}
-- | Additional information about a wallet that can't simply be derived from
-- the blockchain like @Wallet s@ is.
--
-- Whereas @Wallet s@ in 'Cardano.Wallet.Primitive' can be updated using
-- @applyBlock@, @WalletMetadata@ can not*.
--
-- *) Except for possibly 'status' and 'delegation'...
data WalletMetadata = WalletMetadata
{ name
:: !WalletName
, creationTime
:: !UTCTime
, passphraseInfo
:: !(Maybe WalletPassphraseInfo)
, delegation
:: !WalletDelegation
} deriving (Eq, Show, Generic)
instance NFData WalletMetadata
formatUTCTime :: UTCTime -> Text
formatUTCTime =
T.pack . formatTime defaultTimeLocale "%Y-%m-%d %H:%M:%S %Z"
instance Buildable WalletMetadata where
build (WalletMetadata wName wTime _ wDelegation) = mempty
<> build wName <> ", "
<> "created at " <> build (formatUTCTime wTime) <> ", "
<> build wDelegation
-- | Length-restricted name of a wallet
newtype WalletName = WalletName { getWalletName :: Text }
deriving (Generic, Eq, Show)
instance NFData WalletName
instance FromText WalletName where
fromText t
| T.length t < walletNameMinLength =
Left $ TextDecodingError $
"name is too short: expected at least "
<> show walletNameMinLength <> " character"
| T.length t > walletNameMaxLength =
Left $ TextDecodingError $
"name is too long: expected at most "
<> show walletNameMaxLength <> " characters"
| otherwise =
return $ WalletName t
instance ToText WalletName where
toText = getWalletName
instance Buildable WalletName where
build = build . toText
-- | Calling 'fromText @WalletName' on shorter string will fail.
walletNameMinLength :: Int
walletNameMinLength = 1
-- | Calling 'fromText @WalletName' on a longer string will fail.
walletNameMaxLength :: Int
walletNameMaxLength = 255
newtype WalletId = WalletId { getWalletId :: Digest Blake2b_160 }
deriving (Generic, Eq, Ord, Show)
instance NFData WalletId
instance FromText WalletId where
fromText txt = maybe
(Left $ TextDecodingError msg)
(Right . WalletId)
(decodeHex txt >>= digestFromByteString @_ @ByteString)
where
msg = "wallet id should be a hex-encoded string of 40 characters"
decodeHex =
either (const Nothing) Just . convertFromBase Base16 . T.encodeUtf8
instance ToText WalletId where
toText = T.decodeUtf8 . convertToBase Base16 . getWalletId
instance Buildable WalletId where
build wid = prefixF 8 widF <> "..." <> suffixF 8 widF
where
widF = toText wid
data WalletDelegationStatus
= NotDelegating
| Delegating !PoolId
deriving (Generic, Eq, Show)
instance NFData WalletDelegationStatus
instance Buildable WalletDelegationStatus where
build = \case
NotDelegating -> "∅"
Delegating poolId -> build poolId
data WalletDelegationNext = WalletDelegationNext
{ changesAt :: !EpochNo
, status :: !WalletDelegationStatus
} deriving (Eq, Generic, Show)
instance NFData WalletDelegationNext
instance Buildable WalletDelegationNext where
build (WalletDelegationNext e st) =
build st <> " (in epoch: " <> build e <> ")"
data WalletDelegation = WalletDelegation
{ active :: !WalletDelegationStatus
, next :: ![WalletDelegationNext]
} deriving (Eq, Generic, Show)
instance NFData WalletDelegation
instance Buildable WalletDelegation where
build (WalletDelegation act []) =
"delegating to " <> build act
build (WalletDelegation act xs) =
build (WalletDelegation act []) <> " → "
<> build (T.intercalate " → " $ pretty <$> xs)
class IsDelegatingTo a where
isDelegatingTo :: (PoolId -> Bool) -> a -> Bool
instance IsDelegatingTo WalletDelegationStatus where
isDelegatingTo predicate = \case
Delegating pid -> predicate pid
NotDelegating -> False
instance IsDelegatingTo WalletDelegationNext where
isDelegatingTo predicate WalletDelegationNext{status} =
isDelegatingTo predicate status
instance IsDelegatingTo WalletDelegation where
isDelegatingTo predicate WalletDelegation{active,next} =
isDelegatingTo predicate active || any (isDelegatingTo predicate) next
data WalletPassphraseInfo = WalletPassphraseInfo
{ lastUpdatedAt :: UTCTime
, passphraseScheme :: PassphraseScheme
} deriving (Generic, Eq, Ord, Show)
instance NFData WalletPassphraseInfo
-- | A type to capture which encryption scheme should be used
data PassphraseScheme
= EncryptWithScrypt
-- ^ Legacy encryption scheme for passphrases
| EncryptWithPBKDF2
-- ^ Encryption scheme used since cardano-wallet
deriving (Generic, Eq, Ord, Show, Read)
instance NFData PassphraseScheme
data WalletBalance = WalletBalance
{ available :: !(Quantity "lovelace" Natural)
, total :: !(Quantity "lovelace" Natural)
, reward :: !(Quantity "lovelace" Natural)
} deriving (Eq, Generic, Show)
{-------------------------------------------------------------------------------
Queries
-------------------------------------------------------------------------------}
-- | Represents a sort order, applicable to the results returned by a query.
data SortOrder
= Ascending
-- ^ Sort in ascending order.
| Descending
-- ^ Sort in descending order.
deriving (Bounded, Enum, Eq, Generic, Show)
instance ToText SortOrder where
toText = toTextFromBoundedEnum SnakeLowerCase
instance FromText SortOrder where
fromText = fromTextToBoundedEnum SnakeLowerCase
-- | Represents a range of values.
--
-- A range is defined by two /optional/ bounds:
--
-- 1. an /inclusive/ lower bound
-- 2. an /inclusive/ upper bound
--
-- There are four cases:
--
-- +---------------------------------+-------------+---------------------------+
-- | Value | Range | Membership |
-- | | Represented | Function |
-- +=================================+=============+===========================+
-- | @'Range' ('Just' x) ('Just' y)@ | @[ x, y ]@ | @\\p -> p >= x && p <= y@ |
-- +---------------------------------+-------------+---------------------------+
-- | @'Range' ('Just' x) 'Nothing' @ | @[ x, ∞ )@ | @\\p -> p >= x @ |
-- +---------------------------------+-------------+---------------------------+
-- | @'Range' 'Nothing' ('Just' y)@ | @(−∞, y ]@ | @\\p -> p <= y @ |
-- +---------------------------------+-------------+---------------------------+
-- | @'Range' 'Nothing' 'Nothing' @ | @(−∞, ∞ )@ | @\\p -> True @ |
-- +---------------------------------+-------------+---------------------------+
--
data Range a = Range
{ inclusiveLowerBound :: Maybe a
, inclusiveUpperBound :: Maybe a
} deriving (Eq, Functor, Show)
-- | Apply a function to the lower bound of a range.
mapRangeLowerBound :: (a -> a) -> Range a -> Range a
mapRangeLowerBound f (Range x y) = Range (f <$> x) y
-- | Apply a function to the upper bound of a range.
mapRangeUpperBound :: (a -> a) -> Range a -> Range a
mapRangeUpperBound f (Range x y) = Range x (f <$> y)
-- | Represents a range boundary.
data RangeBound a
= NegativeInfinity
| InclusiveBound a
| PositiveInfinity
deriving (Eq, Ord)
-- | The range that includes everything.
wholeRange :: Range a
wholeRange = Range Nothing Nothing
-- | Returns 'True' if (and only if) the given range has an upper bound and the
-- specified value is greater than the upper bound.
isAfterRange :: Ord a => a -> Range a -> Bool
isAfterRange x (Range _ high) =
maybe False (x >) high
-- | Returns 'True' if (and only if) the given range has a lower bound and the
-- specified value is smaller than the lower bound.
isBeforeRange :: Ord a => a -> Range a -> Bool
isBeforeRange x (Range low _) =
maybe False (x <) low
-- | Returns 'True' if (and only if) the given value is not smaller than the
-- lower bound (if present) of the given range and is not greater than the
-- upper bound (if present) of the given range.
isWithinRange :: Ord a => a -> Range a -> Bool
isWithinRange x (Range low high) =
(maybe True (x >=) low) &&
(maybe True (x <=) high)
-- | Returns 'True' if (and only if) the given range has a lower bound.
rangeHasLowerBound :: Range a -> Bool
rangeHasLowerBound = isJust . inclusiveLowerBound
-- | Returns 'True' if (and only if) the given range has an upper bound.
rangeHasUpperBound :: Range a -> Bool
rangeHasUpperBound = isJust . inclusiveUpperBound
-- | Returns 'True' if (and only if) the given range has both a lower and upper
-- bound.
rangeIsFinite :: Range a -> Bool
rangeIsFinite r = rangeHasLowerBound r && rangeHasUpperBound r
-- | Returns 'True' if (and only if) the range covers exactly one value.
rangeIsSingleton :: Eq a => Range a -> Bool
rangeIsSingleton (Range a b) = ((==) <$> a <*> b) == Just True
-- | Returns 'True' if (and only if) the lower bound of a range is not greater
-- than its upper bound.
rangeIsValid :: Ord a => Range a -> Bool
rangeIsValid (Range a b) = ((<=) <$> a <*> b) /= Just False
-- | Get the lower bound of a 'Range'.
rangeLowerBound :: Range a -> RangeBound a
rangeLowerBound = maybe NegativeInfinity InclusiveBound . inclusiveLowerBound
-- | Get the upper bound of a 'Range'.
rangeUpperBound :: Range a -> RangeBound a
rangeUpperBound = maybe PositiveInfinity InclusiveBound . inclusiveUpperBound
-- | Returns 'True' if (and only if) the first given range is a subrange of the
-- second given range.
isSubrangeOf :: Ord a => Range a -> Range a -> Bool
isSubrangeOf r1 r2 =
rangeLowerBound r1 >= rangeLowerBound r2 &&
rangeUpperBound r1 <= rangeUpperBound r2
{-------------------------------------------------------------------------------
Stake Pools
-------------------------------------------------------------------------------}
data StakePool = StakePool
{ poolId :: PoolId
, stake :: Quantity "lovelace" Word64
, production :: Quantity "block" Word64
, performance :: Double
, desirability :: Double
, cost :: Quantity "lovelace" Word64
, margin :: Percentage
, pledge :: Quantity "lovelace" Word64
, saturation :: Double
} deriving (Show, Generic)
-- | A newtype to wrap metadata hash.
--
-- NOTE: not using the 'Hash' type as this newtype is primarily for database
-- interop which doesn't quite like DataKinds.
newtype StakePoolMetadataHash = StakePoolMetadataHash ByteString
deriving (Eq, Ord, Show, Generic)
instance NFData StakePoolMetadataHash
instance ToText StakePoolMetadataHash where
toText (StakePoolMetadataHash bytes) =
toText (Hash bytes)
instance FromText StakePoolMetadataHash where
fromText = fmap (StakePoolMetadataHash . getHash @"_") . hashFromText 32
instance Buildable StakePoolMetadataHash where
build (StakePoolMetadataHash hash) = build (Hash hash)
-- | A newtype to wrap metadata Url, mostly needed for database lookups and
-- signature clarity.
newtype StakePoolMetadataUrl = StakePoolMetadataUrl Text
deriving (Eq, Ord, Show, Generic)
instance NFData StakePoolMetadataUrl
instance ToText StakePoolMetadataUrl where
toText (StakePoolMetadataUrl url) = url
instance FromText StakePoolMetadataUrl where
fromText = pure . StakePoolMetadataUrl
-- | Information about a stake pool.
--
-- The metadata information is not used directly by cardano-wallet, but rather
-- passed straight through to API consumers.
data StakePoolMetadata = StakePoolMetadata
{ ticker :: StakePoolTicker
-- ^ Very short human-readable ID for the stake pool.
, name :: Text
-- ^ Name of the stake pool.
, description :: Maybe Text
-- ^ Short description of the stake pool.
, homepage :: Text
-- ^ Absolute URL for the stake pool's homepage link.
} deriving (Eq, Ord, Show, Generic)
instance FromJSON StakePoolMetadata where
parseJSON = withObject "StakePoolMetadta" $ \obj -> do
ticker <- obj .: "ticker"
name <- obj .: "name"
guard (T.length name <= 50)
description <- obj .:? "description"
guard ((T.length <$> description) <= Just 250)
homepage <- obj .: "homepage"
guard (T.length homepage <= 100)
pure $ StakePoolMetadata{ticker,name,description,homepage}
-- | Very short name for a stake pool.
newtype StakePoolTicker = StakePoolTicker { unStakePoolTicker :: Text }
deriving stock (Generic, Show, Eq, Ord)
deriving newtype (ToText)
instance FromText StakePoolTicker where
fromText t
| T.length t >= 3 && T.length t <= 5
= Right $ StakePoolTicker t
| otherwise
= Left . TextDecodingError $
"stake pool ticker length must be 3-5 characters"
-- Here to avoid needless orphan instances in the API types.
instance FromJSON StakePoolTicker where
parseJSON = parseJSON >=> either (fail . show . ShowFmt) pure . fromText
instance ToJSON StakePoolTicker where
toJSON = toJSON . toText
-- | Identifies a stake pool.
-- For Jörmungandr a 'PoolId' is the blake2b-256 hash of the stake pool
-- registration certificate.
newtype PoolId = PoolId { getPoolId :: ByteString }
deriving (Generic, Eq, Show, Ord)
poolIdBytesLength :: [Int]
poolIdBytesLength = [28, 32]
instance NFData PoolId
instance Buildable PoolId where
build poolId = mempty
<> prefixF 8 poolIdF
where
poolIdF = build (toText poolId)
instance ToText PoolId where
toText = T.decodeUtf8
. convertToBase Base16
. getPoolId
instance FromText PoolId where
fromText t = case convertFromBase Base16 $ T.encodeUtf8 t of
Left _ ->
textDecodingError
Right bytes | BS.length bytes `elem` poolIdBytesLength ->
Right $ PoolId bytes
Right _ ->
textDecodingError
where
textDecodingError = Left $ TextDecodingError $ unwords
[ "Invalid stake pool id: expecting a hex-encoded value that is"
, intercalate " or " (show <$> poolIdBytesLength)
, "bytes in length."
]
-- | Encode 'PoolId' as Bech32 with "pool" hrp.
encodePoolIdBech32 :: PoolId -> T.Text
encodePoolIdBech32 =
Bech32.encodeLenient hrp
. Bech32.dataPartFromBytes
. getPoolId
where
hrp = [Bech32.humanReadablePart|pool|]
-- | Decode a Bech32 encoded 'PoolId'.
decodePoolIdBech32 :: T.Text -> Either TextDecodingError PoolId
decodePoolIdBech32 t =
case fmap Bech32.dataPartToBytes <$> Bech32.decodeLenient t of
Left _ -> Left textDecodingError
Right (_, Just bytes) ->
Right $ PoolId bytes
Right _ -> Left textDecodingError
where
textDecodingError = TextDecodingError $ unwords
[ "Invalid stake pool id: expecting a Bech32 encoded value with human readable part of 'pool'."
]
-- | A stake pool owner, which is a public key encoded in bech32 with prefix
-- ed25519_pk.
newtype PoolOwner = PoolOwner { getPoolOwner :: ByteString }
deriving (Generic, Eq, Show, Ord)
poolOwnerPrefix :: Bech32.HumanReadablePart
poolOwnerPrefix = [Bech32.humanReadablePart|ed25519_pk|]
instance NFData PoolOwner
instance Buildable PoolOwner where
build poolId = build (toText poolId)
instance ToText PoolOwner where
toText = Bech32.encodeLenient poolOwnerPrefix
. Bech32.dataPartFromBytes
. getPoolOwner
instance FromText PoolOwner where
fromText t = case fmap Bech32.dataPartToBytes <$> Bech32.decode t of
Left err ->
Left $ TextDecodingError $
"Stake pool owner is not a valid bech32 string: "
<> show err
Right (hrp, Just bytes)
| hrp == poolOwnerPrefix ->
Right $ PoolOwner bytes
| otherwise ->
Left $ TextDecodingError $
"Stake pool owner has wrong prefix:"
<> " expected "
<> T.unpack (Bech32.humanReadablePartToText poolOwnerPrefix)
<> " but got "
<> show hrp
Right (_, Nothing) ->
Left $ TextDecodingError "Stake pool owner is invalid"
instance FromJSON PoolOwner where
parseJSON = parseJSON >=> either (fail . show . ShowFmt) pure . fromText
instance ToJSON PoolOwner where
toJSON = toJSON . toText
data StakeDistribution = StakeDistribution
{ dangling :: Quantity "lovelace" Word64
, pools :: [(PoolId, Quantity "lovelace" Word64)]
, unassigned :: Quantity "lovelace" Word64
} deriving (Eq, Show, Generic)
{-------------------------------------------------------------------------------
Block
-------------------------------------------------------------------------------}
data Block = Block
{ header
:: !BlockHeader
, transactions
:: ![Tx]
, delegations
:: ![DelegationCertificate]
} deriving (Show, Eq, Ord, Generic)
instance NFData Block
instance Buildable (Block) where
build (Block h txs _) = mempty
<> build h
<> if null txs then " ∅" else "\n" <> indentF 4 (blockListF txs)
data BlockHeader = BlockHeader
{ slotNo
:: SlotNo
, blockHeight
:: Quantity "block" Word32
, headerHash
:: !(Hash "BlockHeader")
, parentHeaderHash
:: !(Hash "BlockHeader")
} deriving (Show, Eq, Ord, Generic)
instance NFData BlockHeader
instance Buildable BlockHeader where
build (BlockHeader s (Quantity bh) hh ph) =
prefixF 8 phF
<> "<-["
<> prefixF 8 hhF
<> "-"
<> build s
<> "#" <> build (show bh)
<> "]"
where
hhF = build $ T.decodeUtf8 $ convertToBase Base16 $ getHash hh
phF = build $ T.decodeUtf8 $ convertToBase Base16 $ getHash ph
{-------------------------------------------------------------------------------
Tx
-------------------------------------------------------------------------------}
-- | Primitive @Tx@-type.
--
-- Currently tailored for jormungandr in that inputs are @(TxIn, Coin)@
-- instead of @TxIn@. We might have to revisit this when supporting another
-- node.
data Tx = Tx
{ txId
:: Hash "Tx"
-- ^ Jörmungandr computes transaction id by hashing the full content of
-- the transaction, which includes witnesses. Therefore, we need either
-- to keep track of the witnesses to be able to re-compute the tx id
-- every time, or, simply keep track of the id itself.
, resolvedInputs
:: ![(TxIn, Coin)]
-- ^ NOTE: Order of inputs matters in the transaction representation. The
-- transaction id is computed from the binary representation of a tx,
-- for which inputs are serialized in a specific order.
, outputs
:: ![TxOut]
-- ^ NOTE: Order of outputs matters in the transaction representations. Outputs
-- are used as inputs for next transactions which refer to them using
-- their indexes. It matters also for serialization.
, withdrawals
:: !(Map ChimericAccount Coin)
-- ^ Withdrawals (of funds from a registered reward account) embedded in
-- a transaction. The order does not matter.
, metadata
:: !(Maybe TxMetadata)
-- ^ Semi-structured application-specific extension data stored in the
-- transaction on chain.
--
-- This is not to be confused with 'TxMeta', which is information about
-- a transaction derived from the ledger.
--
-- See Appendix E of <https://hydra.iohk.io/job/Cardano/cardano-ledger-specs/delegationDesignSpec/latest/download-by-type/doc-pdf/delegation_design_spec Shelley Ledger: Delegation/Incentives Design Spec>.
} deriving (Show, Generic, Ord, Eq)
instance NFData Tx
instance Buildable Tx where
build (Tx tid ins outs ws md) = mempty
<> build tid
<> build ("\n" :: String)
<> blockListF' "inputs" build (fst <$> ins)
<> blockListF' "outputs" build outs
<> blockListF' "withdrawals" tupleF (Map.toList ws)
<> nameF "metadata" (maybe "" build md)
txIns :: Set Tx -> Set TxIn
txIns = foldMap (Set.fromList . inputs)
inputs :: Tx -> [TxIn]
inputs = map fst . resolvedInputs
data TxIn = TxIn
{ inputId
:: !(Hash "Tx")
, inputIx
:: !Word32
} deriving (Show, Generic, Eq, Ord)
instance NFData TxIn
instance Buildable TxIn where
build txin = mempty
<> ordinalF (inputIx txin + 1)
<> " "
<> build (inputId txin)
data TxOut = TxOut
{ address
:: !Address
, coin
:: !Coin
} deriving (Show, Generic, Eq, Ord)
instance NFData TxOut
instance Buildable TxOut where
build txout = mempty
<> build (coin txout)
<> " @ "
<> prefixF 8 addrF
<> "..."
<> suffixF 8 addrF
where
addrF = build $ address txout
instance Buildable (TxIn, TxOut) where
build (txin, txout) = build txin <> " ==> " <> build txout
data TxMeta = TxMeta
{ status :: !TxStatus
, direction :: !Direction
, slotNo :: !SlotNo
, blockHeight :: !(Quantity "block" Word32)
, amount :: !(Quantity "lovelace" Natural)
, expiry :: !(Maybe SlotNo)
} deriving (Show, Eq, Ord, Generic)
instance NFData TxMeta
instance Buildable TxMeta where
build (TxMeta s d sl (Quantity bh) (Quantity a) mex) = mempty
<> (case d of; Incoming -> "+"; Outgoing -> "-")
<> fixedF @Double 6 (fromIntegral a / 1e6)
<> " " <> build s
<> " since " <> build sl <> "#" <> build bh
<> maybe mempty (\ex -> " (expires slot " <> build ex <> ")") mex
data TxStatus
= Pending
| InLedger
| Expired
deriving (Show, Eq, Ord, Bounded, Enum, Generic)
instance NFData TxStatus
instance Buildable TxStatus where
build = Builder.fromText . toTextFromBoundedEnum SpacedLowerCase
instance FromText TxStatus where
fromText = fromTextToBoundedEnum SnakeLowerCase
instance ToText TxStatus where
toText = toTextFromBoundedEnum SnakeLowerCase
-- | An unsigned transaction.
--
-- See 'Tx' for a signed transaction.
--
data UnsignedTx input = UnsignedTx
{ unsignedInputs
:: NonEmpty input
, unsignedOutputs
:: NonEmpty TxOut
}
deriving (Eq, Show)
-- | The effect of a @Transaction@ on the wallet balance.
data Direction
= Outgoing -- ^ The wallet balance decreases.
| Incoming -- ^ The wallet balance increases or stays the same.
deriving (Show, Bounded, Enum, Eq, Ord, Generic)
instance NFData Direction
instance Buildable Direction where
build = Builder.fromText . toTextFromBoundedEnum SpacedLowerCase
instance FromText Direction where
fromText = fromTextToBoundedEnum SnakeLowerCase
instance ToText Direction where
toText = toTextFromBoundedEnum SnakeLowerCase
-- | @SealedTx@ is a serialised transaction that is ready to be submitted
-- to the node.
newtype SealedTx = SealedTx { getSealedTx :: ByteString }
deriving stock (Show, Eq, Generic)
deriving newtype (ByteArrayAccess)