/
RoundRobin.hs
1535 lines (1402 loc) · 57.8 KB
/
RoundRobin.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 BangPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
-- |
-- Copyright: © 2021 IOHK
-- License: Apache-2.0
--
-- Provides an implementation of the Random-Round-Robin coin selection
-- algorithm for multi-asset UTxO sets.
--
-- See documentation for the 'performSelection' function for more details on
-- how to perform a selection.
--
module Cardano.Wallet.Primitive.CoinSelection.MA.RoundRobin
(
-- * Performing a selection
performSelection
, prepareOutputsWith
, emptySkeleton
, selectionDelta
, SelectionCriteria (..)
, SelectionLimit (..)
, SelectionSkeleton (..)
, SelectionResult (..)
, SelectionError (..)
, BalanceInsufficientError (..)
, SelectionInsufficientError (..)
, InsufficientMinCoinValueError (..)
, UnableToConstructChangeError (..)
-- * Reporting
, SelectionReport (..)
, SelectionReportSummarized (..)
, SelectionReportDetailed (..)
, makeSelectionReport
, makeSelectionReportSummarized
, makeSelectionReportDetailed
-- * Running a selection (without making change)
, runSelection
, SelectionState (..)
-- * Running a selection step
, runSelectionStep
, SelectionLens (..)
, assetSelectionLens
, coinSelectionLens
-- * Making change
, MakeChangeCriteria (..)
, makeChange
, makeChangeForCoin
, makeChangeForUserSpecifiedAsset
, makeChangeForNonUserSpecifiedAsset
, makeChangeForNonUserSpecifiedAssets
, assignCoinsToChangeMaps
, collateNonUserSpecifiedAssetQuantities
-- * Splitting bundles
, splitBundleIfAssetCountExcessive
, splitBundlesWithExcessiveAssetCounts
, splitBundlesWithExcessiveTokenQuantities
-- * Grouping and ungrouping
, groupByKey
, ungroupByKey
-- * Round-robin processing
, runRoundRobin
, runRoundRobinM
-- * Accessors
, fullBalance
-- * Utility classes
, AssetCount (..)
-- * Utility functions
, distance
, mapMaybe
, balanceMissing
) where
import Prelude
import Algebra.PartialOrd
( PartialOrd (..) )
import Cardano.Numeric.Util
( padCoalesce )
import Cardano.Wallet.Primitive.Types.Coin
( Coin (..), addCoin, subtractCoin, sumCoins )
import Cardano.Wallet.Primitive.Types.TokenBundle
( TokenBundle (..) )
import Cardano.Wallet.Primitive.Types.TokenMap
( AssetId, TokenMap )
import Cardano.Wallet.Primitive.Types.TokenQuantity
( TokenQuantity (..) )
import Cardano.Wallet.Primitive.Types.Tx
( TokenBundleSizeAssessment (..)
, TokenBundleSizeAssessor (..)
, TxIn
, TxOut
, txOutCoin
, txOutMaxTokenQuantity
)
import Cardano.Wallet.Primitive.Types.UTxOIndex
( SelectionFilter (..), UTxOIndex (..) )
import Control.Monad.Random.Class
( MonadRandom (..) )
import Data.Function
( (&) )
import Data.Functor.Identity
( Identity (..) )
import Data.Generics.Internal.VL.Lens
( over, view )
import Data.Generics.Labels
()
import Data.List.NonEmpty
( NonEmpty (..) )
import Data.Map.Strict
( Map )
import Data.Maybe
( fromMaybe )
import Data.Ord
( comparing )
import Data.Set
( Set )
import Fmt
( Buildable (..), genericF, nameF, unlinesF )
import GHC.Generics
( Generic )
import GHC.Stack
( HasCallStack )
import Numeric.Natural
( Natural )
import qualified Cardano.Wallet.Primitive.Types.Coin as Coin
import qualified Cardano.Wallet.Primitive.Types.TokenBundle as TokenBundle
import qualified Cardano.Wallet.Primitive.Types.TokenMap as TokenMap
import qualified Cardano.Wallet.Primitive.Types.TokenQuantity as TokenQuantity
import qualified Cardano.Wallet.Primitive.Types.Tx as Tx
import qualified Cardano.Wallet.Primitive.Types.UTxOIndex as UTxOIndex
import qualified Data.Foldable as F
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
--------------------------------------------------------------------------------
-- Performing a selection
--------------------------------------------------------------------------------
-- | Criteria for performing a selection.
--
data SelectionCriteria = SelectionCriteria
{ outputsToCover
:: !(NonEmpty TxOut)
-- ^ The complete set of outputs to be covered.
, utxoAvailable
:: !UTxOIndex
-- ^ A UTxO set from which inputs can be selected.
, selectionLimit
:: !SelectionLimit
-- ^ Specifies a limit to be adhered to when performing selection.
, extraCoinSource
:: !(Maybe Coin)
-- ^ An optional extra source of ada.
}
deriving (Eq, Show)
-- | A skeleton selection that can be used to estimate the cost of a final
-- selection.
--
-- Change outputs are deliberately stripped of their asset quantities, as the
-- fee estimation function must be agnostic to the magnitudes of these
-- quantities.
--
-- Increasing or decreasing the quantity of a particular asset in a change
-- output must not change the estimated cost of a selection.
--
data SelectionSkeleton = SelectionSkeleton
{ skeletonInputCount
:: !Int
, skeletonOutputs
:: ![TxOut]
, skeletonChange
:: ![Set AssetId]
}
deriving (Eq, Generic, Show)
-- | Creates an empty 'SelectionSkeleton' with no inputs, no outputs and no
-- change.
emptySkeleton :: SelectionSkeleton
emptySkeleton = SelectionSkeleton
{ skeletonInputCount = 0
, skeletonOutputs = mempty
, skeletonChange = mempty
}
-- | Specifies a limit to adhere to when performing a selection.
--
data SelectionLimit
= NoLimit
-- ^ Indicates that there is no limit.
| MaximumInputLimit Int
-- ^ Indicates a maximum limit on the number of inputs to select.
deriving (Eq, Show)
-- | The result of performing a successful selection.
--
data SelectionResult change = SelectionResult
{ inputsSelected
:: !(NonEmpty (TxIn, TxOut))
-- ^ A (non-empty) list of inputs selected from 'utxoAvailable'.
, extraCoinSource
:: !(Maybe Coin)
-- ^ An optional extra source of ada.
, outputsCovered
:: ![TxOut]
-- ^ A list of outputs covered.
-- FIXME: Left as a list to allow to work-around the limitation of
-- 'performSelection' which cannot run for no output targets (e.g. in
-- the context of a delegation transaction). This allows callers to
-- specify a dummy 'TxOut' as argument, and remove it later in the
-- result; Ideally, we want to handle this in a better way by allowing
-- 'performSelection' to work with empty output targets. At the moment
-- of writing these lines, I've already been yak-shaving for a while and
-- this is the last remaining obstacle, not worth the effort _yet_.
, changeGenerated
:: ![change]
-- ^ A list of generated change outputs.
, utxoRemaining
:: !UTxOIndex
-- ^ The subset of 'utxoAvailable' that remains after performing
-- the selection.
}
deriving (Generic, Eq, Show)
-- | Calculate the actual difference between the total outputs (incl. change)
-- and total inputs of a particular selection. By construction, this should be
-- greater than total fees and deposits.
selectionDelta
:: (change -> Coin)
-> SelectionResult change
-> Coin
selectionDelta getChangeCoin sel@SelectionResult{inputsSelected,extraCoinSource} =
let
totalOut
= sumCoins (getChangeCoin <$> changeGenerated sel)
& addCoin (sumCoins (txOutCoin <$> outputsCovered sel))
totalIn
= sumCoins (txOutCoin . snd <$> inputsSelected)
& addCoin (fromMaybe (Coin 0) extraCoinSource)
in
Coin.distance totalIn totalOut
-- | Represents the set of errors that may occur while performing a selection.
--
data SelectionError
= BalanceInsufficient
BalanceInsufficientError
| SelectionInsufficient
SelectionInsufficientError
| InsufficientMinCoinValues
(NonEmpty InsufficientMinCoinValueError)
| UnableToConstructChange
UnableToConstructChangeError
deriving (Generic, Eq, Show)
-- | Indicates that the balance of inputs actually selected was insufficient to
-- cover the balance of 'outputsToCover'.
--
data SelectionInsufficientError = SelectionInsufficientError
{ balanceRequired
:: !TokenBundle
-- ^ The balance of 'outputsToCover'.
, inputsSelected
:: ![(TxIn, TxOut)]
-- ^ The inputs that could be selected while satisfying the
-- 'selectionLimit'.
} deriving (Generic, Eq, Show)
-- | Indicates that the balance of 'utxoAvailable' is insufficient to cover the
-- balance of 'outputsToCover'.
--
data BalanceInsufficientError = BalanceInsufficientError
{ balanceAvailable
:: !TokenBundle
-- ^ The balance of 'utxoAvailable'.
, balanceRequired
:: !TokenBundle
-- ^ The balance of 'outputsToCover'.
} deriving (Generic, Eq, Show)
-- | Calculate the missing balance from a @BalanceInsufficientError@.
balanceMissing :: BalanceInsufficientError -> TokenBundle
balanceMissing (BalanceInsufficientError available required) =
TokenBundle.difference required available
-- | Indicates that a particular output does not have the minimum coin quantity
-- expected by the protocol.
--
-- See also: 'prepareOutputs'.
--
data InsufficientMinCoinValueError = InsufficientMinCoinValueError
{ outputWithInsufficientAda
:: !TxOut
-- ^ The particular output that does not have the minimum coin quantity
-- expected by the protocol.
, expectedMinCoinValue
:: !Coin
-- ^ The minimum coin quantity expected for this output.
} deriving (Generic, Eq, Show)
instance Buildable InsufficientMinCoinValueError where
build (InsufficientMinCoinValueError o c) = unlinesF
[ nameF "Expected min coin value" (build c)
, nameF "TxOut" (build o)
]
data UnableToConstructChangeError = UnableToConstructChangeError
{ requiredCost
:: !Coin
-- ^ The minimal required cost needed for the transaction to be
-- considered valid. This does not include min Ada values.
, shortfall
:: !Coin
-- ^ The additional coin quantity that would be required to cover the
-- selection cost and minimum coin quantity of each change output.
} deriving (Generic, Eq, Show)
-- | Transforms a set of outputs (provided by users) into valid Cardano outputs.
--
-- Every output in Cardano needs to have a minimum quantity of ada, in order to
-- prevent attacks that flood the network with worthless UTxOs.
--
-- However, we do not require users to specify the minimum ada quantity
-- themselves. Most users would prefer to send '10 Apple' rather than
-- '10 Apple & 1.2 Ada'.
--
-- Therefore, unless a coin quantity is explicitly specified, we assign a coin
-- quantity manually for each non-ada output. That quantity is the minimum
-- quantity required to make a particular output valid.
--
prepareOutputsWith
:: (TokenMap -> Coin)
-> NonEmpty TxOut
-> NonEmpty TxOut
prepareOutputsWith minCoinValueFor = fmap $ \out ->
out { Tx.tokens = augmentBundle (Tx.tokens out) }
where
augmentBundle bundle =
if TokenBundle.getCoin bundle == Coin 0
then bundle { coin = minCoinValueFor (view #tokens bundle) }
else bundle
-- | Performs a coin selection and generates change bundles in one step.
--
-- Returns 'BalanceInsufficient' if the total balance of 'utxoAvailable' is not
-- strictly greater than or equal to the total balance of 'outputsToCover'.
--
-- Provided that the total balance of 'utxoAvailable' is sufficient to cover
-- the total balance of 'outputsToCover', this function guarantees to return
-- an 'inputsSelected' value that satisfies:
--
-- balance inputsSelected >= balance outputsToCover
-- balance inputsSelected == balance outputsToCover + balance changeGenerated
--
-- Finally, this function guarantees that:
--
-- inputsSelected ∪ utxoRemaining == utxoAvailable
-- inputsSelected ∩ utxoRemaining == ∅
-- outputsCovered == outputsToCover
--
performSelection
:: forall m. (HasCallStack, MonadRandom m)
=> (TokenMap -> Coin)
-- ^ A function that computes the minimum ada quantity required by the
-- protocol for a particular output.
-> (SelectionSkeleton -> Coin)
-- ^ A function that computes the extra cost corresponding to a given
-- selection. This function must not depend on the magnitudes of
-- individual asset quantities held within each change output.
-> TokenBundleSizeAssessor
-- ^ A function that assesses the size of a token bundle. See the
-- documentation for 'TokenBundleSizeAssessor' to learn about the
-- expected properties of this function.
-> SelectionCriteria
-- ^ The selection goal to satisfy.
-> m (Either SelectionError (SelectionResult TokenBundle))
performSelection minCoinFor costFor bundleSizeAssessor criteria
| not (balanceRequired `leq` balanceAvailable) =
pure $ Left $ BalanceInsufficient $ BalanceInsufficientError
{ balanceAvailable, balanceRequired }
| not (null insufficientMinCoinValues) =
pure $ Left $ InsufficientMinCoinValues $
NE.fromList insufficientMinCoinValues
| otherwise = do
state <- runSelection
selectionLimit extraCoinSource utxoAvailable balanceRequired
let balanceSelected = fullBalance (selected state) extraCoinSource
if balanceRequired `leq` balanceSelected then
makeChangeRepeatedly state
else
pure $ Left $ SelectionInsufficient $ SelectionInsufficientError
{ inputsSelected = UTxOIndex.toList (selected state)
, balanceRequired
}
where
SelectionCriteria
{ outputsToCover
, utxoAvailable
, selectionLimit
, extraCoinSource
} = criteria
mkInputsSelected :: UTxOIndex -> NonEmpty (TxIn, TxOut)
mkInputsSelected =
fromMaybe invariantSelectAnyInputs . NE.nonEmpty . UTxOIndex.toList
balanceAvailable :: TokenBundle
balanceAvailable = fullBalance utxoAvailable extraCoinSource
balanceRequired :: TokenBundle
balanceRequired = F.foldMap (view #tokens) outputsToCover
insufficientMinCoinValues :: [InsufficientMinCoinValueError]
insufficientMinCoinValues =
mapMaybe mkInsufficientMinCoinValueError outputsToCover
where
mkInsufficientMinCoinValueError
:: TxOut
-> Maybe InsufficientMinCoinValueError
mkInsufficientMinCoinValueError o
| view (#tokens . #coin) o >= expectedMinCoinValue =
Nothing
| otherwise =
Just $ InsufficientMinCoinValueError
{ expectedMinCoinValue, outputWithInsufficientAda = o }
where
expectedMinCoinValue = minCoinFor (view (#tokens . #tokens) o)
-- Given a UTxO index that corresponds to a valid selection covering
-- 'outputsToCover', 'predictChange' yields a non-empty list of assets
-- expected for change outputs.
--
-- There's a chicken-and-egg situation when it comes to calculating
-- transaction fees. On the one hand, we need to know the shape of the
-- final transaction to calculate its cost. But in order to construct the
-- transaction, we need to know what its cost is.
--
-- So, in order to not duplicate the logic from 'makeChange', we first
-- calculate a pre-selection considering the case where we have no fees to
-- pay, and no minimum value. This is *guaranteed to succeed* and will
-- yield a selection with change outputs in the final shape (modulo
-- amounts).
--
-- The result of calling 'predictChange' with a valid input selection
-- should satisfy:
--
-- length predictedChange === length outputsToCover
--
-- flat predictChange `isSubsetOf` assets selectedInputs
--
-- ∃ criteria. / isRight (performSelection criteria) =>
-- Right predictedChange === assets <$> performSelection criteria
--
-- (That is, the predicted change is necessarily equal to the change
-- assets of the final resulting selection).
--
predictChange
:: UTxOIndex
-> [Set AssetId]
predictChange inputsPreSelected = either
(const $ invariantResultWithNoCost inputsPreSelected)
(fmap (TokenMap.getAssets . view #tokens))
(makeChange MakeChangeCriteria
{ minCoinFor = noMinimumCoin
, bundleSizeAssessor
, requiredCost = noCost
, extraCoinSource
, inputBundles
, outputBundles
}
)
where
inputBundles = view #tokens . snd <$> mkInputsSelected inputsPreSelected
outputBundles = view #tokens <$> outputsToCover
noMinimumCoin :: TokenMap -> Coin
noMinimumCoin = const (Coin 0)
noCost :: Coin
noCost = Coin 0
-- This function takes the given selection skeleton as a way to evaluate
-- the cost of a final selection, and then calls 'makeChange' repeatedly
-- until it succeeds.
--
-- Between each call, it selects an extra ada-only input to inject
-- additional ada to construct change outputs.
--
-- Eventually it returns just a final selection, or 'Nothing' if no more
-- ada-only inputs are available.
--
makeChangeRepeatedly
:: SelectionState
-> m (Either SelectionError (SelectionResult TokenBundle))
makeChangeRepeatedly s = case mChangeGenerated of
Right change | length change >= length outputsToCover ->
-- We've succeeded in making at least the optimal number of change
-- outputs, and can terminate here.
--
-- Note that we can't use an exact length equality check here, as
-- the 'makeChange' function will split up change outputs if they
-- are oversized in any way. (See 'splitOversizedMaps'.)
--
-- It is therefore possible for 'makeChange' to generate more change
-- outputs than the number of user-specified outputs.
--
pure $ Right $ mkSelectionResult change
Right change ->
-- We've succeeded in making change outputs, but the number of
-- change outputs is fewer than optimal, because the supply of ada
-- was insufficient. Try again with more ada to see if it leads to
-- an improvement:
selectOneEntry s >>= \case
Just s' ->
makeChangeRepeatedly s'
Nothing ->
-- There is no more ada available. Terminate with a
-- less-than-optimal number of change outputs.
pure $ Right $ mkSelectionResult change
Left changeErr ->
-- We've failed to make any change outputs, because the supply of
-- ada was insufficient. Try again with more ada.
selectOneEntry s >>= \case
Just s' ->
makeChangeRepeatedly s'
Nothing ->
-- There is no more ada available, and we were unable to
-- make any change. At this point we must simply give up.
pure $ Left $ UnableToConstructChange changeErr
where
mChangeGenerated :: Either UnableToConstructChangeError [TokenBundle]
mChangeGenerated = makeChange MakeChangeCriteria
{ minCoinFor
, bundleSizeAssessor
, requiredCost
, extraCoinSource
, inputBundles = view #tokens . snd <$> inputsSelected
, outputBundles = view #tokens <$> outputsToCover
}
mkSelectionResult :: [TokenBundle] -> SelectionResult TokenBundle
mkSelectionResult changeGenerated = SelectionResult
{ inputsSelected
, extraCoinSource
, changeGenerated = changeGenerated
, outputsCovered = NE.toList outputsToCover
, utxoRemaining = leftover
}
selectOneEntry = selectMatchingQuantity selectionLimit $
WithAdaOnly :| [Any]
SelectionState {selected, leftover} = s
requiredCost = costFor SelectionSkeleton
{ skeletonInputCount = UTxOIndex.size selected
, skeletonOutputs = NE.toList outputsToCover
, skeletonChange
}
skeletonChange = predictChange selected
inputsSelected = mkInputsSelected selected
invariantSelectAnyInputs =
-- This should be impossible, as we have already determined
-- that the UTxO balance is sufficient to cover the outputs.
error $ unlines
[ "performSelection: unable to select any inputs!"
, "balance required:"
, show balanceRequired
, "balance available:"
, show balanceAvailable
]
invariantResultWithNoCost inputs_ = error $ unlines
-- This should be impossible, as the 'makeChange' function should
-- always succeed if there's no extra cost or minimum value to assign.
-- This is because it is called with the result of 'runSelection',
-- which only terminates successfully if the target was satisfied.
[ "performSelection: couldn't construct change for a selection with no "
, "minimum coin value and no cost!"
, "inputs: " <> show inputs_
, "extra input source: " <> show extraCoinSource
, "outputs: " <> show outputsToCover
]
--------------------------------------------------------------------------------
-- Reporting
--------------------------------------------------------------------------------
-- | Includes both summarized and detailed information about a selection.
--
data SelectionReport = SelectionReport
{ summary :: SelectionReportSummarized
, detail :: SelectionReportDetailed
}
deriving (Eq, Generic, Show)
-- | Includes summarized information about a selection.
--
-- Each data point can be serialized as a single line of text.
--
data SelectionReportSummarized = SelectionReportSummarized
{ computedFee :: Coin
, totalAdaBalanceIn :: Coin
, totalAdaBalanceOut :: Coin
, adaBalanceOfSelectedInputs :: Coin
, adaBalanceOfExtraInput :: Coin
, adaBalanceOfRequestedOutputs :: Coin
, adaBalanceOfGeneratedChangeOutputs :: Coin
, numberOfSelectedInputs :: Int
, numberOfRequestedOutputs :: Int
, numberOfGeneratedChangeOutputs :: Int
, numberOfUniqueNonAdaAssetsInSelectedInputs :: Int
, numberOfUniqueNonAdaAssetsInRequestedOutputs :: Int
, numberOfUniqueNonAdaAssetsInGeneratedChangeOutputs :: Int
, sizeOfRemainingUtxoSet :: Int
}
deriving (Eq, Generic, Show)
-- | Includes detailed information about a selection.
--
data SelectionReportDetailed = SelectionReportDetailed
{ selectedInputs :: [(TxIn, TxOut)]
, requestedOutputs :: [TxOut]
, generatedChangeOutputs :: [TokenBundle.Flat TokenBundle]
}
deriving (Eq, Generic, Show)
instance Buildable SelectionReport where
build = genericF
instance Buildable SelectionReportSummarized where
build = genericF
instance Buildable SelectionReportDetailed where
build = genericF
makeSelectionReport
:: SelectionResult TokenBundle -> SelectionReport
makeSelectionReport s = SelectionReport
{ summary = makeSelectionReportSummarized s
, detail = makeSelectionReportDetailed s
}
makeSelectionReportSummarized
:: SelectionResult TokenBundle -> SelectionReportSummarized
makeSelectionReportSummarized s = SelectionReportSummarized {..}
where
computedFee
= Coin.distance totalAdaBalanceIn totalAdaBalanceOut
totalAdaBalanceIn
= adaBalanceOfSelectedInputs <> adaBalanceOfExtraInput
totalAdaBalanceOut
= adaBalanceOfGeneratedChangeOutputs <> adaBalanceOfRequestedOutputs
adaBalanceOfSelectedInputs
= F.foldMap (view (#tokens . #coin) . snd) $ view #inputsSelected s
adaBalanceOfExtraInput
= F.fold (view #extraCoinSource s)
adaBalanceOfGeneratedChangeOutputs
= F.foldMap (view #coin) $ view #changeGenerated s
adaBalanceOfRequestedOutputs
= F.foldMap (view (#tokens . #coin)) $ view #outputsCovered s
numberOfSelectedInputs
= length $ view #inputsSelected s
numberOfRequestedOutputs
= length $ view #outputsCovered s
numberOfGeneratedChangeOutputs
= length $ view #changeGenerated s
numberOfUniqueNonAdaAssetsInSelectedInputs
= Set.size
$ F.foldMap (TokenBundle.getAssets . view #tokens . snd)
$ view #inputsSelected s
numberOfUniqueNonAdaAssetsInRequestedOutputs
= Set.size
$ F.foldMap (TokenBundle.getAssets . view #tokens)
$ view #outputsCovered s
numberOfUniqueNonAdaAssetsInGeneratedChangeOutputs
= Set.size
$ F.foldMap TokenBundle.getAssets
$ view #changeGenerated s
sizeOfRemainingUtxoSet
= UTxOIndex.size $ utxoRemaining s
makeSelectionReportDetailed
:: SelectionResult TokenBundle -> SelectionReportDetailed
makeSelectionReportDetailed s = SelectionReportDetailed
{ selectedInputs
= F.toList $ view #inputsSelected s
, requestedOutputs
= view #outputsCovered s
, generatedChangeOutputs
= TokenBundle.Flat <$> view #changeGenerated s
}
-- A convenience instance for 'Buildable' contexts that include a nested
-- 'SelectionResult' value.
instance Buildable (SelectionResult TokenBundle) where
build = build . makeSelectionReport
-- A convenience instance for 'Buildable' contexts that include a nested
-- 'SelectionResult' value.
instance Buildable (SelectionResult TxOut) where
build = build
. makeSelectionReport
. over #changeGenerated (fmap $ view #tokens)
--------------------------------------------------------------------------------
-- Running a selection (without making change)
--------------------------------------------------------------------------------
data SelectionState = SelectionState
{ selected
:: !UTxOIndex
, leftover
:: !UTxOIndex
}
deriving (Eq, Show)
runSelection
:: forall m. MonadRandom m
=> SelectionLimit
-- ^ A limit to adhere to when performing a selection.
-> Maybe Coin
-- ^ An extra source of ada, which can only be used after at least one
-- input has been selected.
-> UTxOIndex
-- ^ UTxO entries available for selection.
-> TokenBundle
-- ^ Minimum balance to cover.
-> m SelectionState
-- ^ Final selection state.
runSelection limit mExtraCoinSource available minimumBalance =
runRoundRobinM initialState selectors
where
initialState :: SelectionState
initialState = SelectionState
{ selected = UTxOIndex.empty
, leftover = available
}
-- NOTE: We run the 'coinSelector' last, because we know that every input
-- necessarily has a non-zero ada amount. By running the other selectors
-- first, we increase the probability that the coin selector will be able
-- to terminate without needing to select an additional coin.
selectors :: [SelectionState -> m (Maybe SelectionState)]
selectors =
reverse (coinSelector : fmap assetSelector minimumAssetQuantities)
where
assetSelector = runSelectionStep .
assetSelectionLens limit
coinSelector = runSelectionStep $
coinSelectionLens limit mExtraCoinSource minimumCoinQuantity
(minimumCoinQuantity, minimumAssetQuantities) =
TokenBundle.toFlatList minimumBalance
assetSelectionLens
:: MonadRandom m
=> SelectionLimit
-> (AssetId, TokenQuantity)
-> SelectionLens m SelectionState
assetSelectionLens limit (asset, minimumAssetQuantity) = SelectionLens
{ currentQuantity = assetQuantity asset . selected
, minimumQuantity = unTokenQuantity minimumAssetQuantity
, selectQuantity = selectMatchingQuantity limit
(WithAssetOnly asset :| [WithAsset asset])
}
coinSelectionLens
:: MonadRandom m
=> SelectionLimit
-> Maybe Coin
-- An extra source of ada.
-> Coin
-- ^ Minimum coin quantity.
-> SelectionLens m SelectionState
coinSelectionLens limit mExtraCoinSource minimumCoinQuantity = SelectionLens
{ currentQuantity = \s -> coinQuantity (selected s) mExtraCoinSource
, minimumQuantity = fromIntegral $ unCoin minimumCoinQuantity
, selectQuantity = selectMatchingQuantity limit
(WithAdaOnly :| [Any])
}
-- | Selects a UTxO entry that matches one of the specified filters.
--
-- This function traverses the specified list of filters from left to right, in
-- descending order of priority.
--
-- When considering a particular filter:
--
-- - if the function is able to select a UTxO entry that matches, it
-- terminates with an updated selection state that includes the entry.
--
-- - if the function is not able to select a UTxO entry that matches, it
-- traverses to the next filter available.
--
-- This function returns 'Nothing' if (and only if) it traverses the entire
-- list of filters without successfully selecting a UTxO entry.
--
selectMatchingQuantity
:: MonadRandom m
=> SelectionLimit
-- ^ A limit to adhere to when selecting entries.
-> NonEmpty SelectionFilter
-- ^ A list of selection filters to be traversed from left-to-right,
-- in descending order of priority.
-> SelectionState
-- ^ The current selection state.
-> m (Maybe SelectionState)
-- ^ An updated selection state that includes a matching UTxO entry,
-- or 'Nothing' if no such entry could be found.
selectMatchingQuantity limit filters s
| limitReached =
pure Nothing
| otherwise =
fmap updateState <$>
UTxOIndex.selectRandomWithPriority (leftover s) filters
where
limitReached = case limit of
MaximumInputLimit m -> UTxOIndex.size (selected s) >= m
NoLimit -> False
updateState ((i, o), remaining) = SelectionState
{ leftover = remaining
, selected = UTxOIndex.insert i o (selected s)
}
--------------------------------------------------------------------------------
-- Running a selection step
--------------------------------------------------------------------------------
-- | Provides a lens on the current selection state.
--
-- A 'SelectionLens' gives 'runSelectionStep' just the information it needs to
-- make a decision, and no more.
--
data SelectionLens m state = SelectionLens
{ currentQuantity
:: state -> Natural
, selectQuantity
:: state -> m (Maybe state)
, minimumQuantity
:: Natural
}
-- | Runs just a single step of a coin selection.
--
-- It returns an updated state if (and only if) the updated selection
-- represents an improvement over the selection in the previous state.
--
-- An improvement, for a given token quantity, is defined in the following way:
--
-- - If the total selected token quantity of the previous selection had
-- not yet reached 100% of the output token quantity, any additional
-- selection is considered to be an improvement.
--
-- - If the total selected token quantity of the previous selection had
-- already reached or surpassed 100% of the output token quantity, any
-- additional selection is considered to be an improvement if and only
-- if it takens the total selected token quantity closer to 200% of the
-- output token quantity, but not further away.
--
runSelectionStep
:: forall m state. Monad m
=> SelectionLens m state
-> state
-> m (Maybe state)
runSelectionStep lens s
| currentQuantity s < minimumQuantity =
selectQuantity s
| otherwise =
(requireImprovement =<<) <$> selectQuantity s
where
SelectionLens {currentQuantity, selectQuantity, minimumQuantity} = lens
requireImprovement :: state -> Maybe state
requireImprovement s'
| distanceFromTarget s' < distanceFromTarget s = Just s'
| otherwise = Nothing
distanceFromTarget :: state -> Natural
distanceFromTarget = distance targetQuantity . currentQuantity
targetQuantity :: Natural
targetQuantity = minimumQuantity * 2
--------------------------------------------------------------------------------
-- Making change
--------------------------------------------------------------------------------
-- | Criteria for the 'makeChange' function.
--
data MakeChangeCriteria minCoinFor bundleSizeAssessor = MakeChangeCriteria
{ minCoinFor :: minCoinFor
-- ^ A function that computes the minimum required ada quantity for a
-- particular output.
, bundleSizeAssessor :: bundleSizeAssessor
-- ^ A function to assess the size of a token bundle.
, requiredCost :: Coin
-- ^ The minimal (and optimal) delta between the total ada balance
-- of all input bundles and the total ada balance of all output and
-- change bundles, where:
--
-- delta = getCoin (fold inputBundles)
-- - getCoin (fold outputBundles)
-- - getCoin (fold changeBundles)
--
-- This typically captures fees plus key deposits.
, extraCoinSource :: Maybe Coin
-- ^ An optional extra source of ada.
, inputBundles :: NonEmpty TokenBundle
-- ^ Token bundles of selected inputs.
, outputBundles :: NonEmpty TokenBundle
-- ^ Token bundles of original outputs.
} deriving (Eq, Generic, Show)
-- | Indicates 'True' if and only if a token bundle exceeds the maximum size
-- that can be included in a transaction output.
--
tokenBundleSizeExceedsLimit :: TokenBundleSizeAssessor -> TokenBundle -> Bool
tokenBundleSizeExceedsLimit (TokenBundleSizeAssessor assess) b =
case assess b of
TokenBundleSizeWithinLimit->
False
OutputTokenBundleSizeExceedsLimit ->
True
-- | Constructs change bundles for a set of selected inputs and outputs.
--
-- Returns 'Nothing' if the specified inputs do not provide enough ada to
-- satisfy the minimum delta and minimum ada quantities of the change bundles
-- generated.
--
-- This function will generate runtime errors if:
--
-- 1. The total balance of all outputs is not less than or equal to the
-- total balance of all inputs.
--
-- 2. The total ada balance of all outputs is zero.
--
-- Pre-condition (1) should be satisfied by any result produced by the
-- 'runSelection' function.
--
-- Pre-condition (2) should be satisfied by assigning a minimum ada quantity
-- to every output token bundle.
--
makeChange
:: MakeChangeCriteria (TokenMap -> Coin) TokenBundleSizeAssessor
-- ^ Criteria for making change.
-> Either UnableToConstructChangeError [TokenBundle]
-- ^ Generated change bundles.
makeChange criteria
| not (totalOutputValue `leq` totalInputValue) =
totalInputValueInsufficient
| TokenBundle.getCoin totalOutputValue == Coin 0 =
totalOutputCoinValueIsZero
| otherwise =
maybe (Left changeError) Right $ do
adaAvailable <- excessCoin `subtractCoin` requiredCost
assignCoinsToChangeMaps
adaAvailable minCoinFor changeMapOutputCoinPairs
where
MakeChangeCriteria
{ minCoinFor
, bundleSizeAssessor
, requiredCost
, extraCoinSource
, inputBundles
, outputBundles
} = criteria