-
Notifications
You must be signed in to change notification settings - Fork 9
/
CoinSelection.hs
369 lines (331 loc) · 11.9 KB
/
CoinSelection.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
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_HADDOCK prune #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- Provides general functions and types relating to coin selection.
--
-- The 'CoinSelection' type represents a __coin selection__, the basis for a
-- /transaction/ in a UTxO-based blockchain.
--
-- The 'CoinSelectionAlgorithm' type provides a __common interface__ to
-- algorithms that generate coin selections.
--
module Cardano.CoinSelection
(
-- * Coin Selections
CoinSelection (..)
, sumInputs
, sumOutputs
, sumChange
-- * Coin Selection Algorithms
, CoinSelectionAlgorithm (..)
, CoinSelectionParameters (..)
, CoinSelectionResult (..)
, CoinSelectionLimit (..)
-- * Coins
, Coin
, coinFromNatural
, coinToNatural
-- * Coin Maps
, CoinMap (..)
, CoinMapEntry (..)
, coinMapFromList
, coinMapToList
, coinMapValue
-- * Coin Selection Errors
, CoinSelectionError (..)
, InputValueInsufficientError (..)
, InputCountInsufficientError (..)
, InputLimitExceededError (..)
, InputsExhaustedError (..)
-- # Internal Functions
, coinMapRandomEntry
) where
import Prelude
import Control.Arrow
( (&&&) )
import Control.Monad.Trans.Except
( ExceptT (..) )
import Crypto.Number.Generate
( generateBetween )
import Crypto.Random.Types
( MonadRandom )
import Data.Map.Strict
( Map )
import Data.Word
( Word8 )
import GHC.Generics
( Generic )
import Internal.Coin
( Coin, coinFromNatural, coinToNatural )
import Numeric.Natural
( Natural )
import Quiet
( Quiet (Quiet) )
import qualified Data.Foldable as F
import qualified Data.Map.Strict as Map
--------------------------------------------------------------------------------
-- Coin Map
--------------------------------------------------------------------------------
-- | A mapping from unique keys to associated 'Coin' values.
--
-- A 'CoinMap' can be used to represent:
--
-- * a UTxO set, where each key within the map refers to an unspent output
-- from a previous transaction.
--
-- * a set of 'inputs' to a 'CoinSelection', where each input is an entry
-- selected from a UTxO set by a 'CoinSelectionAlgorithm'.
--
-- * a set of 'outputs' for a 'CoinSelection', where each key within the map
-- refers to the address of a payment recipient.
--
-- A 'CoinMap' can be constructed with the 'coinMapFromList' function.
--
-- The total value of a 'CoinMap' is given by the 'coinMapValue' function.
--
newtype CoinMap a = CoinMap { unCoinMap :: Map a Coin }
deriving (Eq, Generic)
deriving Show via (Quiet (CoinMap a))
instance Foldable CoinMap where
foldMap f = F.fold . fmap (f . entryKey) . coinMapToList
instance Ord a => Monoid (CoinMap a) where
mempty = CoinMap mempty
instance Ord a => Semigroup (CoinMap a) where
CoinMap a <> CoinMap b = CoinMap $ Map.unionWith (<>) a b
-- | An entry for a 'CoinMap'.
--
data CoinMapEntry a = CoinMapEntry
{ entryKey
:: a
-- ^ The unique key associated with this entry.
, entryValue
:: Coin
-- ^ The coin value associated with this entry.
} deriving (Eq, Generic, Ord, Show)
-- | Constructs a 'CoinMap' from a list of entries.
--
-- See 'CoinMapEntry'.
--
coinMapFromList :: Ord a => [CoinMapEntry a] -> CoinMap a
coinMapFromList = CoinMap
. Map.fromListWith (<>)
. fmap (entryKey &&& entryValue)
-- | Converts a 'CoinMap' to a list of entries.
--
-- See 'CoinMapEntry'.
--
coinMapToList :: CoinMap a -> [CoinMapEntry a]
coinMapToList = fmap (uncurry CoinMapEntry) . Map.toList . unCoinMap
-- | Calculates the total coin value associated with a 'CoinMap'.
--
coinMapValue :: CoinMap a -> Coin
coinMapValue = mconcat . fmap entryValue . coinMapToList
--------------------------------------------------------------------------------
-- Coin Selection
--------------------------------------------------------------------------------
-- | Provides a __common interface__ for coin selection algorithms.
--
-- The function 'selectCoins', when applied to the given
-- 'CoinSelectionParameters' object (with /available inputs/ and /requested/
-- /outputs/), will generate a 'CoinSelectionResult' (with /remaining inputs/
-- and a /coin selection/).
--
newtype CoinSelectionAlgorithm i o m = CoinSelectionAlgorithm
{ selectCoins
:: CoinSelectionParameters i o
-> ExceptT CoinSelectionError m (CoinSelectionResult i o)
}
-- | The complete set of parameters required for a 'CoinSelectionAlgorithm'.
--
-- The 'inputsAvailable' and 'outputsRequested' fields are both maps of unique
-- keys to associated 'Coin' values, where:
--
-- * Each key-value pair in the 'inputsAvailable' map corresponds to an
-- __unspent output__ from a previous transaction that is /available/
-- /for selection as an input/ by the coin selection algorithm. The /key/
-- is a unique reference to that output, and the /value/ is the amount of
-- unspent value associated with it.
--
-- * Each key-value pair in the 'outputsRequested' map corresponds to a
-- __payment__ whose value is /to be paid for/ by the coin selection
-- algorithm. The /key/ is a unique reference to a payment recipient,
-- and the /value/ is the amount of money to pay to that recipient.
--
-- A coin selection algorithm will select a __subset__ of inputs from
-- 'inputsAvailable' in order to pay for __all__ the outputs in
-- 'outputsRequested', where:
--
-- * Inputs __selected__ by the algorithm are included in the 'inputs'
-- set of the generated 'CoinSelection'.
--
-- * Inputs __not__ selected by the algorithm are included in the
-- 'inputsRemaining' set of the 'CoinSelectionResult'.
--
-- The number of inputs that can selected is limited by 'limit'.
--
-- The total value of 'inputsAvailable' must be /greater than or equal to/
-- the total value of 'outputsRequested', as given by the 'coinMapValue'
-- function.
--
data CoinSelectionParameters i o = CoinSelectionParameters
{ inputsAvailable :: CoinMap i
-- ^ The set of inputs available for selection.
, outputsRequested :: CoinMap o
-- ^ The set of outputs requested for payment.
, limit :: CoinSelectionLimit
-- ^ A limit on the number of inputs that can be selected.
}
deriving Generic
-- | Represents the __result__ of running a coin selection algorithm.
--
-- See 'CoinSelectionAlgorithm'.
--
data CoinSelectionResult i o = CoinSelectionResult
{ coinSelection :: CoinSelection i o
-- ^ The generated coin selection.
, inputsRemaining :: CoinMap i
-- ^ The set of inputs that were __not__ selected.
}
-- | A __coin selection__ is the basis for a /transaction/.
--
-- It consists of a selection of 'inputs', 'outputs', and 'change'.
--
-- The 'inputs' and 'outputs' fields are both maps of unique keys to associated
-- 'Coin' values, where:
--
-- * Each key-value pair in the 'inputs' map corresponds to an
-- __unspent output__ from a previous transaction (also known as a UTxO).
-- The /key/ is a unique reference to that output, and the /value/ is the
-- amount of unspent value associated with it.
--
-- * Each key-value pair in the 'outputs' map corresponds to a __payment__.
-- The /key/ is a unique reference to a payment recipient, and the /value/
-- is the amount of money to pay to that recipient.
--
-- The 'change' field is a set of coins to be returned to the originator of the
-- transaction.
--
-- The 'CoinSelectionAlgorithm' type provides a common interface for generating
-- coin selections.
--
data CoinSelection i o = CoinSelection
{ inputs :: CoinMap i
-- ^ The set of inputs.
, outputs :: CoinMap o
-- ^ The set of outputs.
, change :: [Coin]
-- ^ The set of change.
}
deriving (Generic, Show, Eq)
instance (Ord i, Ord o) => Semigroup (CoinSelection i o) where
a <> b = CoinSelection
{ inputs = inputs a <> inputs b
, outputs = outputs a <> outputs b
, change = change a <> change b
}
instance (Ord i, Ord o) => Monoid (CoinSelection i o) where
mempty = CoinSelection mempty mempty mempty
-- | Calculate the total sum of all 'inputs' for the given 'CoinSelection'.
sumInputs :: CoinSelection i o -> Coin
sumInputs = coinMapValue . inputs
-- | Calculate the total sum of all 'outputs' for the given 'CoinSelection'.
sumOutputs :: CoinSelection i o -> Coin
sumOutputs = coinMapValue . outputs
-- | Calculate the total sum of all 'change' for the given 'CoinSelection'.
sumChange :: CoinSelection i o -> Coin
sumChange = mconcat . change
-- | Defines an __inclusive upper bound__ on the /number/ of inputs that
-- a 'CoinSelectionAlgorithm' is allowed to select.
--
newtype CoinSelectionLimit = CoinSelectionLimit
{ calculateLimit
:: Word8 -> Word8
-- ^ Calculate the maximum number of inputs allowed for a given
-- number of outputs.
} deriving Generic
-- | Represents the set of possible failures that can occur when attempting
-- to produce a 'CoinSelection' with a 'CoinSelectionAlgorithm'.
--
-- See 'selectCoins'.
--
data CoinSelectionError
= InputValueInsufficient
InputValueInsufficientError
| InputCountInsufficient
InputCountInsufficientError
| InputLimitExceeded
InputLimitExceededError
| InputsExhausted
InputsExhaustedError
deriving (Eq, Show)
-- | Indicates that the total value of 'inputsAvailable' is less than the total
-- value of 'outputsRequested', making it /impossible/ to cover all payments,
-- /regardless/ of which algorithm is chosen.
--
data InputValueInsufficientError =
InputValueInsufficientError
{ inputValueAvailable :: Coin
-- ^ The total value of 'inputsAvailable'.
, inputValueRequired :: Coin
-- ^ The total value of 'outputsRequested'.
}
deriving (Eq, Show)
-- | Indicates that the total count of entries in 'inputsAvailable' is /fewer/
-- /than/ required by the algorithm. The number required depends on the
-- particular algorithm implementation.
--
data InputCountInsufficientError =
InputCountInsufficientError
{ inputCountAvailable :: Natural
-- ^ The number of entries in 'inputsAvailable'.
, inputCountRequired :: Natural
-- ^ The number of entries required.
}
deriving (Eq, Show)
-- | Indicates that all available entries in 'inputsAvailable' were depleted
-- /before/ all the payments in 'outputsRequested' could be paid for.
--
-- This condition can occur /even if/ the total value of 'inputsAvailable' is
-- greater than or equal to the total value of 'outputsRequested', due to
-- differences in the way that algorithms select inputs.
--
data InputsExhaustedError =
InputsExhaustedError
deriving (Eq, Show)
-- | Indicates that the coin selection algorithm is unable to cover the total
-- value of 'outputsRequested' without exceeding the maximum number of inputs
-- defined by 'limit'.
--
-- See 'calculateLimit'.
--
newtype InputLimitExceededError =
InputLimitExceededError
{ calculatedInputLimit :: Word8 }
deriving (Eq, Show)
--------------------------------------------------------------------------------
-- Internal Functions
--------------------------------------------------------------------------------
-- Selects an entry at random from a 'CoinMap', returning both the selected
-- entry and the map with the entry removed.
--
-- If the given map is empty, this function returns 'Nothing'.
--
coinMapRandomEntry
:: MonadRandom m
=> CoinMap a
-> m (Maybe (CoinMapEntry a), CoinMap a)
coinMapRandomEntry (CoinMap m)
| Map.null m =
return (Nothing, CoinMap m)
| otherwise = do
ix <- fromEnum <$> generateBetween 0 (toEnum (Map.size m - 1))
let entry = uncurry CoinMapEntry $ Map.elemAt ix m
let remainder = CoinMap $ Map.deleteAt ix m
return (Just entry, remainder)