-
Notifications
You must be signed in to change notification settings - Fork 219
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Random input selection impl #140
Merged
+610
−243
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
96985b2
Random input selection impl
paweljakubas 2e605ae
Use fallback not per step but optionally in the end
paweljakubas c80a56f
Add unit tests
paweljakubas 55507fe
Add property tests
paweljakubas 1552b7e
remove extra space in module export
KtorZ 0cd5653
remove unecessary orphan instance
KtorZ 35e9564
update docstring comment for 'random' selection to match the specific…
KtorZ e7a3cdb
add comments to 'TargetRange' type
KtorZ c7aa5b2
replace 'Coin' with 'Word64' in the 'TargetRange' type
KtorZ 74e5e07
use of 'MaybeT' to simplify writing of 'processTxOut'
KtorZ 38fecdc
replace 'Map TxIn TxOut' with 'UTxO' to ease transaction signatures
KtorZ fb23bad
re-indent where clause on a 4-space indent (instead of 8-space)
KtorZ 0a9f56d
remove currently useless fee-related options and types definitions
KtorZ cddc877
some minor naming revision: in particular 'atLeast' -> 'coverRandomly'
KtorZ 6596d6e
factor out common test logic in largest first and random coin selection
KtorZ a5bddd3
get system DRG through Hspec bracket mechanism (instead of unsafe IO)
KtorZ File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,234 @@ | ||
{-# LANGUAGE LambdaCase #-} | ||
{-# LANGUAGE RankNTypes #-} | ||
|
||
-- | | ||
-- Copyright: © 2018-2019 IOHK | ||
-- License: MIT | ||
-- | ||
-- This module contains the implementation of random | ||
-- input selection algorithm | ||
|
||
|
||
module Cardano.Wallet.CoinSelection.Random | ||
( random | ||
) where | ||
|
||
import Prelude | ||
|
||
import Cardano.Wallet.CoinSelection | ||
( CoinSelection (..), CoinSelectionError (..), CoinSelectionOptions (..) ) | ||
import Cardano.Wallet.CoinSelection.LargestFirst | ||
( largestFirst ) | ||
import Cardano.Wallet.Primitive.Types | ||
( Coin (..), TxIn, TxOut (..), UTxO (..), balance, invariant ) | ||
import Control.Monad | ||
( foldM ) | ||
import Control.Monad.Trans.Class | ||
( lift ) | ||
import Control.Monad.Trans.Except | ||
( ExceptT (..) ) | ||
import Control.Monad.Trans.Maybe | ||
( MaybeT (..), runMaybeT ) | ||
import Crypto.Number.Generate | ||
( generateBetween ) | ||
import Crypto.Random.Types | ||
( MonadRandom ) | ||
import Data.List.NonEmpty | ||
( NonEmpty (..) ) | ||
import Data.Ord | ||
( comparing ) | ||
import Data.Word | ||
( Word64 ) | ||
|
||
import qualified Data.List as L | ||
import qualified Data.List.NonEmpty as NE | ||
import qualified Data.Map.Strict as Map | ||
|
||
|
||
-- | Target range for picking inputs | ||
data TargetRange = TargetRange | ||
{ targetMin :: Word64 | ||
-- ^ Minimum value to cover: only the requested amount, no change at all | ||
, targetAim :: Word64 | ||
-- ^ Ideal case: change equal to requested amount | ||
, targetMax :: Word64 | ||
-- ^ Maximum value: an arbitrary upper bound (e.g. @2 * targetMin@) | ||
} | ||
|
||
-- | Random-Improve Algorithm | ||
-- | ||
-- 1. Randomly select outputs from the UTxO until the payment value is covered. | ||
-- (In the rare case that this fails because the maximum number of transaction | ||
-- inputs has been exceeded, fall-back on the largest-first algorithm for this | ||
-- step.) | ||
-- | ||
-- 2. Randomly select outputs from the UTxO, considering for each output if that | ||
-- output is animprovement. If it is, add it to the transaction, and keep | ||
-- going. An output is considered an improvement when: | ||
-- | ||
-- (a) It doesn’t exceed a specified upper limit. | ||
-- (b) Adding the new output gets us closer to the ideal change value. | ||
-- (c) It doesn’t exceed a maximum number of transaction inputs. | ||
-- | ||
-- This algorithm follows three principles: | ||
-- | ||
-- @ | ||
-- **Self organisation principle 1** | ||
-- Random selection has a high probability of picking dust outputs precisely | ||
-- when there is a lot of dust in the UTxO. | ||
-- @ | ||
-- | ||
-- @ | ||
-- **Self organisation principle 2** | ||
-- If for each payment request for value `x` we create a change output roughly | ||
-- of the same value `x`, then we will end up with a lot of change outputs in | ||
-- our UTxO of size `x` precisely when we have a lot of payment requests of | ||
-- size `x` | ||
-- @ | ||
-- | ||
-- @ | ||
-- **Self organisation principle 3** | ||
-- Searching the UTxO for additional entries to improve our change output is | ||
-- only useful if the UTxO contains entries that are sufficiently small enough. | ||
-- But precisely when the UTxO contains many small entries, it is less likely | ||
-- that a randomly chosen UTxO entry will push the total above the upper bound | ||
-- we set. | ||
-- @ | ||
random | ||
:: forall m. MonadRandom m | ||
=> CoinSelectionOptions | ||
-> UTxO | ||
-> NonEmpty TxOut | ||
-> ExceptT CoinSelectionError m CoinSelection | ||
random opt utxo outs = do | ||
let descending = NE.toList . NE.sortBy (flip $ comparing coin) | ||
randomMaybe <- lift $ runMaybeT $ foldM | ||
(processTxOut opt) | ||
(utxo, mempty) | ||
(descending outs) | ||
case randomMaybe of | ||
Just (_,res) -> | ||
return res | ||
Nothing -> | ||
largestFirst opt utxo outs | ||
|
||
-- | Perform a random selection on a given output, with improvement. | ||
processTxOut | ||
:: forall m. MonadRandom m | ||
=> CoinSelectionOptions | ||
-> (UTxO, CoinSelection) | ||
-> TxOut | ||
-> MaybeT m (UTxO, CoinSelection) | ||
processTxOut (CoinSelectionOptions maxNumInputs) (utxo0, selection) txout = do | ||
attempt <- coverRandomly ([], utxo0) | ||
(inps, utxo') <- lift (improve attempt) | ||
return | ||
( utxo' | ||
, selection <> CoinSelection | ||
{ inputs = inps | ||
, outputs = [txout] | ||
, change = mkChange txout inps | ||
} | ||
) | ||
where | ||
target :: TargetRange | ||
target = mkTargetRange txout | ||
|
||
coverRandomly | ||
:: forall m. MonadRandom m | ||
=> ([(TxIn, TxOut)], UTxO) | ||
-> MaybeT m ([(TxIn, TxOut)], UTxO) | ||
coverRandomly (inps, utxo) | ||
| L.length inps > (fromIntegral maxNumInputs) = | ||
MaybeT $ return Nothing | ||
| balance' inps >= targetMin target = | ||
MaybeT $ return $ Just (inps, utxo) | ||
| otherwise = do | ||
pickRandom utxo >>= \(io, utxo') -> coverRandomly (io:inps, utxo') | ||
|
||
improve | ||
:: forall m. MonadRandom m | ||
=> ([(TxIn, TxOut)], UTxO) | ||
-> m ([(TxIn, TxOut)], UTxO) | ||
improve (inps, utxo) = | ||
runMaybeT (pickRandom utxo) >>= \case | ||
Nothing -> | ||
return (inps, utxo) | ||
Just (io, utxo') | isImprovement io inps -> do | ||
let inps' = io : inps | ||
if balance' inps' >= targetAim target | ||
then return (inps', utxo') | ||
else improve (inps', utxo') | ||
Just _ -> | ||
return (inps, utxo) | ||
|
||
isImprovement :: (TxIn, TxOut) -> [(TxIn, TxOut)] -> Bool | ||
isImprovement io selected = | ||
let | ||
condA = -- (a) It doesn’t exceed a specified upper limit. | ||
balance' (io : selected) < targetMax target | ||
|
||
condB = -- (b) Addition gets us closer to the ideal change | ||
distance (targetAim target) (balance' (io : selected)) | ||
< | ||
distance (targetAim target) (balance' selected) | ||
|
||
condC = -- (c) Doesn't exceed maximum number of inputs | ||
length (io : selected) <= fromIntegral maxNumInputs | ||
in | ||
condA && condB && condC | ||
|
||
{------------------------------------------------------------------------------- | ||
Internals | ||
-------------------------------------------------------------------------------} | ||
|
||
-- | Compute the target range for a given output | ||
mkTargetRange :: TxOut -> TargetRange | ||
mkTargetRange (TxOut _ (Coin c)) = TargetRange | ||
{ targetMin = c | ||
, targetAim = 2 * c | ||
, targetMax = 3 * c | ||
} | ||
|
||
-- | Compute the balance of a unwrapped UTxO | ||
balance' :: [(TxIn, TxOut)] -> Word64 | ||
balance' = | ||
fromIntegral . balance . UTxO . Map.fromList | ||
|
||
-- | Compute distance between two numeric values |a - b| | ||
distance :: (Ord a, Num a) => a -> a -> a | ||
distance a b = | ||
if a < b then b - a else a - b | ||
|
||
-- | Compute corresponding change outputs from a target output and a selection | ||
-- of inputs. | ||
-- | ||
-- > pre-condition: the output must be smaller (or eq) than the sum of inputs | ||
mkChange :: TxOut -> [(TxIn, TxOut)] -> [Coin] | ||
mkChange (TxOut _ (Coin out)) inps = | ||
let | ||
selected = invariant | ||
"mkChange: output is smaller than selected inputs!" | ||
(balance' inps) | ||
(> out) | ||
Coin maxCoinValue = maxBound | ||
in | ||
case selected - out of | ||
c | c > maxCoinValue -> | ||
let h = (c `div` 2) in [Coin h, Coin (c - h)] | ||
c | c == 0 -> | ||
[] | ||
c -> | ||
[ Coin c ] | ||
|
||
-- Pick a random element from a map, returns 'Nothing' if the map is empty | ||
pickRandom | ||
:: MonadRandom m | ||
=> UTxO | ||
-> MaybeT m ((TxIn, TxOut), UTxO) | ||
pickRandom (UTxO utxo) | ||
| Map.null utxo = | ||
MaybeT $ return Nothing | ||
| otherwise = do | ||
ix <- fromEnum <$> lift (generateBetween 0 (toEnum (Map.size utxo - 1))) | ||
return (Map.elemAt ix utxo, UTxO $ Map.deleteAt ix utxo) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
animprovement -> an improvement