packages feed

haskoin-store-2.0.0: src/Haskoin/Store/Fleet/Pool.hs

-- |
-- Module      : Haskoin.Store.Fleet.Pool
-- Copyright   : (c) Haskoin Developers
-- License     : MIT
-- Maintainer  : jprupp@protonmail.ch
-- Stability   : experimental
-- Portability : POSIX
--
-- The mempool that stores sharing one Redis answer from, as pure decisions,
-- beside the fleet tip of "Haskoin.Store.Fleet". It is described in
-- @docs\/fleet-mempool.md@, and the design around it in
-- @docs\/one-fleet.md@. "Haskoin.Store.Fleet.Redis" carries it out.
--
-- = The problem
--
-- A mempool of each store's own would be filled in the order in which its
-- peers sent it transactions, and no two would be the same. Stores that
-- answer from the same block would still answer differently if each laid
-- its own mempool on top.
--
-- = One pool, the mempool as of the fleet tip
--
-- The stores keep one pool in Redis and all answer from it. It goes with
-- the fleet tip: it holds transactions that are valid on top of the chain
-- up to that block, and it changes with the tip in the same step, so that
-- no request sees a block without what it did to the pool.
--
-- No store keeps a mempool of its own. A store offers the pool what its
-- peers send it, and while Redis is down it answers 503 rather than from
-- anything else.
--
-- = The rules
--
-- * __A store offers what it has__ ('offer'). Each input of the transaction
--   must spend an output of a transaction of the pool, or one that the store
--   finds unspent in its view at the fleet tip. A store that is ahead of the
--   tip holds back what only makes sense after its newer blocks.
--
-- * __The first of two that spend the same output stays__, unless the store
--   that offers the second names the first as replaced, having replaced it
--   by its own rules. This is a rule, not a truth, as it is for a node that
--   keeps the first of two conflicting transactions that it hears of.
--
-- * __A transaction leaves only for a reason__ ('withdraw', 'advance'): it
--   was replaced, it is too old, or the tip moved to a block that confirms
--   it or spends what it spends. A store that simply does not have a
--   transaction leaves it alone, because another store has it.
--
-- * __Whatever goes takes along what spends it.__ A transaction whose
--   parent left unconfirmed spends an output that does not exist.
--
-- * __The pool follows the tip__ ('advance'). The store that moves the tip
--   says what the blocks in between did: which transactions they confirmed
--   and which outputs they spent, and, across a reorganisation, which
--   transactions of the abandoned blocks come back and which are gone for
--   good, as their coinbases are.
--
-- Transactions and outputs can be of any type that can be compared; the
-- pool only needs to know which transaction made an output.
module Haskoin.Store.Fleet.Pool
  ( -- * The pool
    Pool (..),
    empty,
    member,
    descendants,

    -- * Offering and withdrawing
    Offer (..),
    Refusal (..),
    offer,
    withdraw,

    -- * Following the tip
    Change (..),
    advance,
    advanceReplacing,

    -- * What the pool holds for each address
    Entry (..),
    AddressPool (..),
    Totals (..),
    addresses,
    totals,

    -- * What the pool holds for tokens
    TokenOut (..),
    TokenTotals (..),
    CategoryPool (..),
    tokenTotals,
    categories,

    -- * Replacing by fee
  )
where

import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (mapMaybe)
import Data.Ord (Down (..))
import Data.Set (Set)
import Data.Set qualified as Set
import Data.Word (Word64)
import Haskoin.Store.Fleet.Pool.Order (Core (..), removeCore)

-- | The shared mempool, for transactions of type @t@ and outputs of type
-- @o@. The second and third fields follow from the first, and are kept so
-- that nothing has to be searched for.
data Pool t o = Pool
  { -- | the outputs that each transaction spends
    spends :: !(Map t [o]),
    -- | the transaction that spends each output that is spent
    spender :: !(Map o t),
    -- | the transactions of the pool that spend outputs of each transaction,
    -- whether that one is in the pool or in the chain: a confirmed
    -- transaction can come back in a reorganisation, and what spends it must
    -- then be found again
    children :: !(Map t (Set t))
  }
  deriving (Eq, Show)

-- | A pool with nothing in it.
empty :: Pool t o
empty = Pool {spends = Map.empty, spender = Map.empty, children = Map.empty}

-- | Whether a transaction is in the pool.
member :: (Ord t) => t -> Pool t o -> Bool
member t pool = Map.member t pool.spends

-- | The transactions of the pool that spend outputs of the given ones, or
-- of those in turn, with the given ones that are in the pool.
descendants :: (Ord t) => [t] -> Pool t o -> Set t
descendants from pool = go Set.empty (filter (`member` pool) from)
  where
    go seen [] = seen
    go seen (t : rest)
      | Set.member t seen = go seen rest
      | otherwise = go (Set.insert t seen) (maybe [] Set.toList (Map.lookup t pool.children) <> rest)

-- | Why a transaction was not taken.
data Refusal t o
  = -- | it is in the pool already, which is no harm
    Known
  | -- | these transactions of the pool spend what it spends, and were there
    -- first
    Conflict ![t]
  | -- | these inputs spend outputs that are neither made by the pool nor
    -- unspent at the tip
    Orphan ![o]
  deriving (Eq, Show)

-- | What became of an offer.
data Offer t o
  = Taken !(Pool t o)
  | Refused !(Refusal t o)
  deriving (Eq, Show)

-- | Offer a transaction to the pool, given the transaction that made each
-- output, a test for the outputs that the offering store finds unspent in
-- its view at the fleet tip, the outputs that the transaction spends, and
-- the transactions of the pool that the store replaced with it.
--
-- Those leave first, with what spends them. The transaction is then taken
-- if nothing left in the pool spends what it spends, and if each of its
-- inputs is made by the pool or unspent at the tip.
offer :: (Ord t, Ord o) => (o -> t) -> (o -> Bool) -> t -> [o] -> [t] -> Pool t o -> Offer t o
offer maker unspent t inputs replaced pool0
  | member t pool0 = Refused Known
  | not (null rivals) = Refused (Conflict rivals)
  | not (null orphans) = Refused (Orphan orphans)
  | otherwise = Taken (insert maker t inputs pool)
  where
    pool = withdraw replaced pool0
    rivals = Set.toList (Set.fromList (mapMaybe (`Map.lookup` pool.spender) inputs))
    orphans = [o | o <- inputs, not (member (maker o) pool), not (unspent o)]

-- | Put a transaction in, without asking.
insert :: (Ord t, Ord o) => (o -> t) -> t -> [o] -> Pool t o -> Pool t o
insert maker t inputs pool =
  Pool
    { spends = Map.insert t inputs pool.spends,
      spender = foldl' (\m o -> Map.insert o t m) pool.spender inputs,
      children = foldl' (\m o -> Map.insertWith Set.union (maker o) (Set.singleton t) m) pool.children inputs
    }

-- | Take transactions out of the pool, with everything that spends them.
withdraw :: (Ord t, Ord o) => [t] -> Pool t o -> Pool t o
withdraw ts pool = foldl' (flip remove) pool (Set.toList (descendants ts pool))

-- | Take one transaction out, leaving what spends it.
--
-- Taking several out leaves the same pool in whatever order they are
-- taken: that is proved, for every pool and every two transactions, of
-- the function that does it ('removeCore' and @anyOrder@ in
-- "Haskoin.Store.Fleet.Pool.Order", which Liquid Haskell checks). A move
-- of the tip relies on it: what it marks is taken out afterwards, by
-- whoever gets to it (@docs\/tip-first.md@).
remove :: (Ord t, Ord o) => t -> Pool t o -> Pool t o
remove t pool = case removeCore t (Core pool.spends pool.spender pool.children) of
  Core spends spender children -> Pool {spends, spender, children}

-- | What the blocks between two tips did, as far as the pool is concerned.
data Change t o = Change
  { -- | transactions of abandoned blocks that can be unconfirmed again, with
    -- what they spend, in an order in which each comes after those it spends
    returned :: ![(t, [o])],
    -- | transactions of abandoned blocks that cannot, such as coinbases:
    -- their outputs no longer exist
    gone :: ![t],
    -- | transactions that the new blocks confirm
    confirmed :: ![t],
    -- | outputs that the transactions of the new blocks spend
    spent :: ![o]
  }
  deriving (Eq, Show)

-- | Bring the pool from one tip to another.
--
-- The abandoned blocks come first: their transactions that can come back
-- do, putting out whatever in the pool spends what they spend, and what
-- spends the others leaves. Then the new blocks: what they
-- confirm leaves the pool, alone, since what spends it now spends an output
-- of the chain; and what spends an output that they spend leaves with
-- everything that spends it.
advance :: (Ord t, Ord o) => (o -> t) -> Change t o -> Pool t o -> Pool t o
advance maker change pool = let (p, _, _) = advanceReplacing maker change (const Nothing) [] Map.empty pool in p

-- | 'advance', and what the new blocks replaced. Given a label for each
-- output that they spend, transactions of the abandoned blocks that the
-- store has as replaced, each with the transaction that replaced it and a
-- label, and those of earlier moves that still wait for theirs. Gives the
-- pool, what was replaced, each with its label, and what still waits.
--
-- * A transaction of the pool that leaves because it, or an unconfirmed
--   ancestor of it, spent an output that the new blocks spend, was
--   replaced, with the label of the output. The outputs are taken in
--   order, and one that left for two of them has the label of the first.
--
-- * A transaction of an abandoned block that the store has as replaced is
--   not in the pool and does not come back to it: the store has imported
--   the new blocks by then, and deleted it. Every store had it confirmed,
--   so every store says the same of it. It was replaced once the tip
--   reaches the block that confirms the transaction that replaced it, which
--   may be in this move or in a later one: the tip may stop at the fork
--   before it goes on.
--
-- The store labels with the transaction that won and the height of its
-- block, and the pool keeps them for a while, so that a wallet that asks
-- for a transaction that lost is told what won.
advanceReplacing ::
  (Ord t, Ord o) =>
  (o -> t) ->
  Change t o ->
  (o -> Maybe w) ->
  [(t, t, w)] ->
  Map t (t, w) ->
  Pool t o ->
  (Pool t o, [(t, w)], Map t (t, w))
advanceReplacing maker change label lost waiting pool0 = (final, now <> clashed, still)
  where
    back = foldl' comeBack pool0 change.returned
    -- a transaction that was confirmed has the better claim to what it
    -- spends: a transaction of the pool that spends the same cannot have
    -- been valid, and leaves
    comeBack p (t, inputs)
      | member t p = p
      | otherwise = insert maker t inputs (withdraw (mapMaybe (`Map.lookup` p.spender) inputs) p)
    orphaned = concatMap (\t -> maybe [] Set.toList (Map.lookup t back.children)) change.gone
    alive = withdraw orphaned back
    settled = foldl' (flip remove) alive change.confirmed
    -- what waits for a transaction that the new blocks confirm was replaced
    confirmed = Set.fromList change.confirmed
    waitingNow = foldl' (\m (t, by, w) -> Map.insert t (by, w) m) waiting lost
    (reached, still) = Map.partition (\(by, _) -> Set.member by confirmed) waitingNow
    now = [(t, w) | (t, (_, w)) <- Map.toList reached]
    -- what spends an output that the blocks spend leaves, with all that
    -- spends it
    (final, clashed) = foldl' clash (settled, []) change.spent
    clash (p, replaced) o = case Map.lookup o p.spender of
      Nothing -> (p, replaced)
      Just s ->
        let leaving = Set.toList (descendants [s] p)
         in (withdraw [s] p, replaced <> maybe [] (\w -> [(t, w) | t <- leaving]) (label o))

-- | What a transaction does at an address, for addresses of type @a@, and
-- to tokens of categories of type @c@, which a store works out from the
-- transaction alone and gives to the pool with it
-- ('Haskoin.Store.Fleet.Member.poolTx').
data Entry a o c
  = -- | it spends from the address or pays to it
    Touches !a
  | -- | it spends this output of the address, of this amount
    Spends !a !o !Word64
  | -- | it pays this output to the address, with this amount
    Pays !a !o !Word64
  | -- | it makes an output that holds tokens (CashTokens)
    Makes !(TokenOut a o c)
  | -- | it uses up an output that holds tokens
    Uses !(TokenOut a o c)
  deriving (Eq, Show)

-- | An output that holds tokens.
data TokenOut a o c = TokenOut
  { -- | its address, if it has one
    owner :: !(Maybe a),
    output :: !o,
    category :: !c,
    -- | fungible tokens
    amount :: !Word64,
    -- | whether it holds a non-fungible token
    nft :: !Bool
  }
  deriving (Eq, Show)

-- | What the pool holds for an address: the union of the entries of its
-- transactions at that address, in the order in which queries list them.
data AddressPool t o = AddressPool
  { -- | the transactions that touch it with the time each entered a
    -- mempool, newest first, and in the order of their ids within a time
    txs :: ![(Word64, t)],
    -- | the outputs paid to it, in the same order, with their amounts
    paid :: ![(Word64, o, Word64)],
    -- | the outputs of it that are spent, with their amounts
    spent :: !(Map o Word64)
  }
  deriving (Eq, Show)

-- | The sums that the pool keeps for an address, so that a balance does
-- not take reading its entries: the summary of
-- 'Haskoin.Store.Database.Types.MemSummary'.
data Totals = Totals
  { txs :: !Word64,
    paid :: !Word64,
    paidCount :: !Word64,
    spent :: !Word64,
    spentCount :: !Word64,
    -- | amount of the outputs that the pool both pays and spends
    both :: !Word64,
    bothCount :: !Word64
  }
  deriving (Eq, Show)

-- | What a pool holds for each address, given its transactions, each with
-- the time it entered a mempool and its entries. This is the specification
-- of what "Haskoin.Store.Fleet.Redis" keeps up to date as transactions come
-- and go: it depends on which transactions are in the pool and on nothing
-- else, so the tests work it out again after every step and compare.
addresses :: (Ord a, Ord t, Ord o) => [(t, Word64, [Entry a o c])] -> Map a (AddressPool t o)
addresses members = Map.map ordered (Map.fromListWith merge (concatMap single members))
  where
    single (t, time, entries) = mapMaybe (one t time) entries
    one t time = \case
      Touches a -> Just (a, AddressPool [(time, t)] [] Map.empty)
      Spends a o v -> Just (a, AddressPool [] [] (Map.singleton o v))
      Pays a o v -> Just (a, AddressPool [] [(time, o, v)] Map.empty)
      _ -> Nothing
    merge x y = AddressPool (x.txs <> y.txs) (x.paid <> y.paid) (Map.union x.spent y.spent)
    ordered p =
      AddressPool
        (Map.elems (Map.fromList [((Down time, t), (time, t)) | (time, t) <- p.txs]))
        (Map.elems (Map.fromList [((Down time, o), (time, o, v)) | (time, o, v) <- p.paid]))
        p.spent

-- | The sums of what a pool holds for an address.
totals :: (Ord o) => AddressPool t o -> Totals
totals p =
  Totals
    { txs = fromIntegral (length p.txs),
      paid = sum [v | (_, _, v) <- p.paid],
      paidCount = fromIntegral (length p.paid),
      spent = sum (Map.elems p.spent),
      spentCount = fromIntegral (Map.size p.spent),
      both = sum inside,
      bothCount = fromIntegral (length inside)
    }
  where
    inside = [v | (_, o, v) <- p.paid, Map.member o p.spent]

-- | The sums that the pool keeps for the tokens of a category at an
-- address: what 'Haskoin.Store.Database.Types.PoolTokens' reads.
data TokenTotals = TokenTotals
  { txs :: !Word64,
    -- | fungible tokens, non-fungible tokens and number of the outputs that
    -- the pool makes and does not use up
    free :: !Word64,
    freeNfts :: !Word64,
    freeOutputs :: !Word64,
    -- | the same of the outputs that the pool uses up and does not make
    spent :: !Word64,
    spentNfts :: !Word64,
    spentOutputs :: !Word64,
    -- | fungible tokens of every output that the pool makes
    received :: !Word64
  }
  deriving (Eq, Show)

-- | What the pool holds for a category of tokens.
data CategoryPool t o = CategoryPool
  { -- | the transactions that move it, newest first, and in the order of
    -- their ids within a time
    txs :: ![(Word64, t)],
    -- | the outputs that hold it and that the pool makes, in the same order
    outs :: ![(Word64, o)],
    -- | how many of those the pool does not use up
    free :: !Word64,
    -- | how many outputs that hold it the pool uses up and does not make
    spent :: !Word64
  }
  deriving (Eq, Show)

-- | The sums of what a pool does to each category at each address, given
-- which transaction made an output and the pool's transactions with their
-- times and entries. Only the outputs with an address count. A
-- transaction moves the tokens of a category at an address when it makes
-- or uses up an output of the address that holds some.
tokenTotals :: (Ord a, Ord t, Ord o, Ord c) => (o -> t) -> [(t, Word64, [Entry a o c])] -> Map (c, a) TokenTotals
tokenTotals maker members = Map.fromListWith plus (moved <> concatMap sums made <> concatMap sums' used)
  where
    ids = Set.fromList [t | (t, _, _) <- members]
    made = [k | (_, _, es) <- members, Makes k <- es]
    used = [k | (_, _, es) <- members, Uses k <- es]
    usedUp = Set.fromList (map (.output) used)
    -- in the order of the fields: txs, the three that are free, the three
    -- that are spent, received
    nfts k = if k.nft then 1 else 0
    moved =
      [ ((c, a), TokenTotals 1 0 0 0 0 0 0 0)
      | (_, _, es) <- members,
        (c, a) <- Set.toList (Set.fromList [(k.category, a) | e <- es, Just k <- [token e], Just a <- [k.owner]])
      ]
    sums k = case k.owner of
      Nothing -> []
      Just a
        | Set.member k.output usedUp -> [((k.category, a), TokenTotals 0 0 0 0 0 0 0 k.amount)]
        | otherwise ->
            [((k.category, a), TokenTotals 0 k.amount (nfts k) 1 0 0 0 k.amount)]
    sums' k = case k.owner of
      Just a
        | not (Set.member (maker k.output) ids) ->
            [((k.category, a), TokenTotals 0 0 0 0 k.amount (nfts k) 1 0)]
      _ -> []
    plus x y =
      TokenTotals
        { txs = x.txs + y.txs,
          free = x.free + y.free,
          freeNfts = x.freeNfts + y.freeNfts,
          freeOutputs = x.freeOutputs + y.freeOutputs,
          spent = x.spent + y.spent,
          spentNfts = x.spentNfts + y.spentNfts,
          spentOutputs = x.spentOutputs + y.spentOutputs,
          received = x.received + y.received
        }

-- | What the pool holds for each category, given which transaction made an
-- output and the pool's transactions with their times and entries.
categories :: (Ord t, Ord o, Ord c) => (o -> t) -> [(t, Word64, [Entry a o c])] -> Map c (CategoryPool t o)
categories maker members = Map.map ordered (Map.fromListWith merge (concatMap single members))
  where
    ids = Set.fromList [t | (t, _, _) <- members]
    usedUp = Set.fromList [k.output | (_, _, es) <- members, Uses k <- es]
    single (t, time, es) =
      [(c, CategoryPool [(time, t)] [] 0 0) | c <- Set.toList (Set.fromList [k.category | Just k <- map token es])]
        <> [ (k.category, CategoryPool [] [(time, k.output)] (if Set.member k.output usedUp then 0 else 1) 0)
           | Makes k <- es
           ]
        <> [(k.category, CategoryPool [] [] 0 1) | Uses k <- es, not (Set.member (maker k.output) ids)]
    merge x y = CategoryPool (x.txs <> y.txs) (x.outs <> y.outs) (x.free + y.free) (x.spent + y.spent)
    ordered p =
      p
        { txs = Map.elems (Map.fromList [((Down time, t), (time, t)) | (time, t) <- p.txs]),
          outs = Map.elems (Map.fromList [((Down time, o), (time, o)) | (time, o) <- p.outs])
        }

-- | The output that holds tokens of an entry, if it is one.
token :: Entry a o c -> Maybe (TokenOut a o c)
token = \case
  Makes k -> Just k
  Uses k -> Just k
  _ -> Nothing