packages feed

haskoin-store-2.0.0: test/Haskoin/Store/Fleet/RedisSpec.hs

module Haskoin.Store.Fleet.RedisSpec
  ( spec,
    withRedis,

    -- * For the spec of the decisions of the pool
    PoolStep (..),
    txOf,
    block,
    out,
    number,
    address,
    timeOf,
  )
where

import Control.Monad (foldM_, forM_, unless, void)
import Data.ByteString (ByteString)
import Data.ByteString qualified as B
import Data.ByteString.Char8 qualified as C
import Data.Containers.ListUtils (nubOrd, nubOrdOn)
import Data.IORef (atomicModifyIORef', newIORef)
import Data.List (sort, sortOn)
import Data.Map.Strict qualified as Map
import Data.Ord (Down (..))
import Data.Serialize (decode, encode)
import Data.Set qualified as Set
import Data.Word (Word32, Word64)
import Database.Redis qualified as Redis
import Haskoin.Store.Fleet (Time, empty, live, mayReport, move, report)
import Haskoin.Store.Fleet qualified as F
import Haskoin.Store.Fleet.Pool qualified as P
import Haskoin.Store.Fleet.Redis
import Haskoin.Store.Integration.Valkey (redisContainer, redisURL)
import Haskoin.Store.Startup (redisConnectInfo)
import Test.Hspec
import Test.Hspec.QuickCheck (modifyMaxSuccess)
import Test.Podman (podmanUsable, withContainer)
import Test.QuickCheck

-- | A step of a fleet of three stores with blocks numbered from 0 to 9.
data Step
  = -- | a store reports some blocks, having views of some
    Report !Int ![Word32] ![Word32]
  | -- | a store tries to move the tip: from the tip as it is, or from
    -- another block, as one that was beaten to it would
    Shift !(Maybe Word32)
  | -- | milliseconds pass
    Wait !Time
  deriving (Show)

instance Arbitrary Step where
  arbitrary =
    frequency
      [ (5, Report <$> choose (0, 2) <*> blocks <*> blocks),
        (4, pure (Shift Nothing)),
        (1, Shift . Just <$> choose (0, 9)),
        (2, Wait <$> choose (1, 6))
      ]
    where
      blocks = choose (0, 5) >>= \n -> vectorOf n (choose (0, 9))

spec :: Spec
spec = do
  usable <- runIO podmanUsable
  describe "fleet tip in Redis" $ case usable of
    Left why -> it "does what the rules say" (pendingWith why)
    Right () -> aroundAll withRedis $ do
      modifyMaxSuccess (const 300) $
        it "does what the rules say, step by step" $ \(conn, fresh) ->
          property $ \steps -> ioProperty $ do
            keys <- fresh
            foldM_ (check conn keys) (empty :: F.Fleet ByteString ByteString, 1000) (steps :: [Step])
      it "counts leases on the clock of Redis when given no other" $ \(conn, fresh) -> do
        keys <- fresh
        fleetReport conn keys Nothing 60000 "a" [block 2, block 1] [] `shouldReturn` True
        fleetMove conn keys Nothing Nothing `shouldReturn` MovedTo (block 2)
        fleetTip conn keys `shouldReturn` Just (block 2)
        -- a store without a view of the tip is kept out while the first is live
        fleetReport conn keys Nothing 60000 "b" [block 1] [block 1] `shouldReturn` False
        fleetReport conn keys Nothing 60000 "b" [block 2] [block 2] `shouldReturn` True
        map fst <$> fleetLive conn keys `shouldReturn` ["a", "b"]
      modifyMaxSuccess (const 300) $
        it "keeps the shared mempool as the rules say, step by step" $ \(conn, fresh) ->
          property $ \steps -> ioProperty $ do
            keys <- fresh
            foldM_ (pooled conn keys) (P.empty, Nothing, 0, (Map.empty, Map.empty)) (steps :: [PoolStep])
      it "turns away an offer that was checked against another tip" $ \(conn, fresh) -> do
        keys <- fresh
        fleetReport conn keys Nothing 60000 "a" [block 1] [] `shouldReturn` True
        fleetMove conn keys Nothing Nothing `shouldReturn` MovedTo (block 1)
        let seven = (txOf 7 [out 0 0]) {body = "seven"}
        poolOffer conn keys 4 Nothing seven [True] [] `shouldReturn` Late
        poolOffer conn keys 4 (Just (block 1)) seven [True] [] `shouldReturn` Taken
        poolBody conn keys (block 7) `shouldReturn` Just "seven"
        -- the tip does not move to a block that the stores do not agree on
        advancing conn keys 4 Nothing "a" (Just (block 1)) (block 2) (Just nothing) [] `shouldReturn` Raced
        fleetReport conn keys Nothing 60000 "a" [block 2, block 1] [block 1] `shouldReturn` True
        let confirms = nothing {confirmed = [block 7], spent = [out 0 0 <> block 7 <> encode (2 :: Word32)]}
        advancing conn keys 4 Nothing "a" (Just (block 1)) (block 2) (Just confirms) []
          `shouldReturn` MovedTo (block 2)
        poolSpends conn keys `shouldReturn` []
        poolBody conn keys (block 7) `shouldReturn` Nothing
      it "counts as settled what the pool has, and nothing that it had or turned away" $ \(conn, fresh) -> do
        keys <- fresh
        fleetReport conn keys Nothing 60000 "a" [block 1] [] `shouldReturn` True
        fleetMove conn keys Nothing Nothing `shouldReturn` MovedTo (block 1)
        let at = Just (block 1)
        -- what the pool took is settled; what it found in conflict, late
        -- or an orphan is not: a node that names one has it, and the pool
        -- is to be offered it again
        poolOffer conn keys 4 at (txOf 7 [out 0 0]) [True] [] `shouldReturn` Taken
        poolOffer conn keys 4 at (txOf 7 [out 0 0]) [True] [] `shouldReturn` Known
        poolOffer conn keys 4 at (txOf 8 [out 0 0]) [True] [] `shouldReturn` Conflict [block 7]
        poolOffer conn keys 4 Nothing (txOf 9 [out 0 1]) [True] [] `shouldReturn` Late
        poolOffer conn keys 4 at (txOf 10 [out 5 0]) [False] [] `shouldReturn` Orphan [out 5 0]
        fleetSettled conn keys (map block [7 .. 10]) `shouldReturn` [True, False, False, False]
        -- nor is what the pool let go: the fleet remembered that once,
        -- and a server did not take a transaction that its node held
        poolOffer conn keys 4 at (txOf 11 [out 0 2]) [True] [] `shouldReturn` Taken
        fleetSettled conn keys [block 11] `shouldReturn` [True]
        poolWithdraw conn keys 4 [block 11] `shouldReturn` [block 11]
        fleetSettled conn keys [block 11] `shouldReturn` [False]
        fleetSettled conn keys [] `shouldReturn` []
        -- and the pool keeps no list of what it has seen
        (Redis.runRedis conn (Redis.keys (keys.prefix <> "fleet:seen")) >>= either (fail . show) return)
          `shouldReturn` []
      it "takes out a transaction that pays an output of value 0, as an anchor does" $ \(conn, fresh) -> do
        keys <- fresh
        fleetReport conn keys Nothing 60000 "a" [block 1] [] `shouldReturn` True
        fleetMove conn keys Nothing Nothing `shouldReturn` MovedTo (block 1)
        let anchor = (txOf 7 [out 0 0]) {entries = [PoolTouches "anchor", PoolPays "anchor" (out 7 0) 0 "script"]}
        poolOffer conn keys 4 (Just (block 1)) anchor [True] [] `shouldReturn` Taken
        poolWithdraw conn keys 4 [block 7] `shouldReturn` [block 7]
        poolBody conn keys (block 7) `shouldReturn` Nothing
      it "expires what has been in the pool since before a time, choosing it in the same call" $ \(conn, fresh) -> do
        keys <- fresh
        fleetReport conn keys Nothing 60000 "a" [block 1] [] `shouldReturn` True
        fleetMove conn keys Nothing Nothing `shouldReturn` MovedTo (block 1)
        -- the first two times of the tests are 101 and 102
        poolOffer conn keys 4 (Just (block 1)) (txOf 7 [out 0 0]) [True] [] `shouldReturn` Taken
        poolOffer conn keys 4 (Just (block 1)) (txOf 8 [out 0 1]) [True] [] `shouldReturn` Taken
        poolExpire conn keys 4 100 10 `shouldReturn` []
        poolExpire conn keys 4 101 10 `shouldReturn` [block 7]
        poolExpire conn keys 4 200 10 `shouldReturn` [block 8]
        poolSpends conn keys `shouldReturn` []
      it "tells what happens to the pool and to the tip, in the order in which it happens" $ \(conn, fresh) -> do
        keys <- fresh
        fleetReport conn keys Nothing 60000 "a" [block 1] [] `shouldReturn` True
        advancing conn keys 4 Nothing "a" Nothing (block 1) (Just nothing) [] `shouldReturn` MovedTo (block 1)
        -- a store that starts to listen hears what comes after
        start <- fleetEventsEnd conn keys
        let seven = txOf 7 [out 0 0]
            eight = txOf 8 [out 7 0]
            nine = txOf 9 [out 0 1]
        forM_ [seven, eight, nine] $ \t ->
          poolOffer conn keys 4 (Just (block 1)) t [True] [] `shouldReturn` Taken
        -- what spends a transaction that is withdrawn leaves with it
        _ <- poolWithdraw conn keys 4 [block 7]
        -- a block confirms the third, which is not an event of the mempool,
        -- and the tip moves through two blocks
        fleetReport conn keys Nothing 60000 "a" [block 3, block 2, block 1] [block 1] `shouldReturn` True
        let confirms = nothing {confirmed = [block 9], spent = [out 0 1 <> block 9 <> encode (3 :: Word32)]}
        advancing conn keys 4 Nothing "a" (Just (block 1)) (block 3) (Just confirms) [block 2, block 3]
          `shouldReturn` MovedTo (block 3)
        heard <- map snd <$> fleetEventsAfter conn keys start 10
        take 3 heard `shouldBe` map FleetEntered [block 7, block 8, block 9]
        sort (take 2 (drop 3 heard)) `shouldBe` map FleetLeft [block 7, block 8]
        drop 5 heard `shouldBe` map FleetBlock [block 2, block 3]
        -- and nothing twice: from the last event on there is nothing
        end <- fleetEventsEnd conn keys
        fleetEventsAfter conn keys end 10 `shouldReturn` []
      it "empties the pool for a store that is alone and does not know the way" $ \(conn, fresh) -> do
        keys <- fresh
        fleetReport conn keys (Just 0) 10 "a" [block 1] [] `shouldReturn` True
        advancing conn keys 4 (Just 0) "a" Nothing (block 1) Nothing [] `shouldReturn` MovedTo (block 1)
        poolOffer conn keys 4 (Just (block 1)) (txOf 7 [out 0 0]) [True] [] `shouldReturn` Taken
        -- with another store live, the tip waits for one that knows
        fleetReport conn keys (Just 0) 10 "a" [block 2, block 1] [block 1] `shouldReturn` True
        fleetReport conn keys (Just 0) 10 "b" [block 2, block 1] [block 1] `shouldReturn` True
        advancing conn keys 4 (Just 0) "a" (Just (block 1)) (block 2) Nothing [] `shouldReturn` Raced
        map fst <$> poolSpends conn keys `shouldReturn` [block 7]
        -- a store that is not live, whose report was refused, does not
        -- empty the pool however many stores are live
        advancing conn keys 4 (Just 0) "x" (Just (block 1)) (block 2) Nothing [] `shouldReturn` Raced
        -- the other store's lease runs out
        fleetReport conn keys (Just 20) 10 "a" [block 2, block 1] [block 1] `shouldReturn` True
        -- and with "a" the one store live, a store that is not live still
        -- may not empty it: "a" may know the way
        advancing conn keys 4 (Just 20) "x" (Just (block 1)) (block 2) Nothing [] `shouldReturn` Raced
        advancing conn keys 4 (Just 20) "a" (Just (block 1)) (block 2) Nothing [] `shouldReturn` MovedTo (block 2)
        poolSpends conn keys `shouldReturn` []
        (Redis.runRedis conn (Redis.keys (keys.prefix <> "pool:*")) >>= either (fail . show) return)
          `shouldReturn` []
      it "empties the pool for any store when the way is too long" $ \(conn, fresh) -> do
        keys <- fresh
        fleetReport conn keys (Just 0) 10 "a" [block 1] [] `shouldReturn` True
        advancing conn keys 4 (Just 0) "a" Nothing (block 1) Nothing [] `shouldReturn` MovedTo (block 1)
        poolOffer conn keys 4 (Just (block 1)) (txOf 7 [out 0 0]) [True] [] `shouldReturn` Taken
        fleetSettled conn keys [block 7] `shouldReturn` [True]
        fleetRestarts conn keys `shouldReturn` 0
        -- two stores that both have a view of the tip, so both are live,
        -- at a block that neither will say the way to
        fleetReport conn keys (Just 0) 10 "a" [block 2] [block 2, block 1] `shouldReturn` True
        fleetReport conn keys (Just 0) 10 "b" [block 2] [block 2, block 1] `shouldReturn` True
        -- a store that does not know the way waits for one that does
        advancing conn keys 4 (Just 0) "a" (Just (block 1)) (block 2) Nothing [] `shouldReturn` Raced
        fleetTip conn keys `shouldReturn` Just (block 1)
        -- one that knows it and finds it too long does not, or the tip
        -- would never move again
        fleetRestart conn keys 4 (Just 0) (Just (block 1)) (block 2) `shouldReturn` MovedTo (block 2)
        fleetTip conn keys `shouldReturn` Just (block 2)
        poolSpends conn keys `shouldReturn` []
        (Redis.runRedis conn (Redis.keys (keys.prefix <> "pool:*")) >>= either (fail . show) return)
          `shouldReturn` []
        -- the stores fetch its transactions again, and fill it again
        fleetSettled conn keys [block 7] `shouldReturn` [False]
        fleetRestarts conn keys `shouldReturn` 1
        -- still only to the block that the live stores agree on, and only
        -- from the tip that the store saw
        fleetRestart conn keys 4 (Just 0) (Just (block 2)) (block 3) `shouldReturn` Raced
        fleetRestart conn keys 4 (Just 0) (Just (block 1)) (block 2) `shouldReturn` Raced
      it "reads what the pool does to tokens, by address and by category" $ \(conn, fresh) -> do
        keys <- fresh
        fleetReport conn keys (Just 0) 10 "a" [block 1] [] `shouldReturn` True
        advancing conn keys 4 (Just 0) "a" Nothing (block 1) Nothing [] `shouldReturn` MovedTo (block 1)
        -- ten transactions: the fifth spends the first output of the first
        -- two, and the tenth an output of the chain that holds tokens
        let tip = Just (block 1)
            spendsOf t = case t of
              4 -> [out 0 0, out 1 0]
              9 -> [out 21 0]
              _ -> []
            members = [(block t, timeOf t, entriesOf t (spendsOf t)) | t <- [0 .. 9]]
            byToken = P.tokenTotals (B.take 4) members
            byCategory = P.categories (B.take 4) members
            spentInPool = Set.fromList (concatMap spendsOf [0 .. 9 :: Word32])
        forM_ [0 .. 9] $ \t ->
          poolOffer conn keys 4 tip (txOf t (spendsOf t)) [t == 9 | _ <- spendsOf t] [] `shouldReturn` Taken
        [p.spent | p <- Map.elems byCategory] `shouldSatisfy` any (> 0)
        forM_ (map address [0 .. 3]) $ \a -> do
          Just rows <- poolRead conn keys 4 tip "tokens" [a]
          Map.fromList [(c, tokenTotalsOf row) | [c, row] <- chunks 2 rows]
            `shouldBe` Map.fromList [(c, p) | ((c, a'), p) <- Map.toList byToken, a' == a]
        forM_ (map category [0, 1]) $ \c -> do
          let p = byCategory Map.! c
          Just rows <- poolRead conn keys 4 tip "holders" [c]
          Map.fromList [(a, tokenTotalsOf row) | [a, row] <- chunks 2 rows]
            `shouldBe` Map.fromList [(a, t) | ((c', a), t) <- Map.toList byToken, c' == c]
          Just [row] <- poolRead conn keys 4 tip "csum" [c]
          map read (words (C.unpack row)) `shouldBe` [fromIntegral (length p.txs), p.free, p.spent]
          Just txs <- poolRead conn keys 4 tip "ctxs" [c, "", "", "100"]
          pairs txs `shouldBe` [(t, time) | (time, t) <- p.txs]
          Just outs <- poolRead conn keys 4 tip "couts" [c, "", "", "100"]
          [(o, read (C.unpack time), C.unpack flag) | [o, time, _, flag] <- chunks 4 outs]
            `shouldBe` [(o, time, if Set.member o spentInPool then "1" else "0") | (time, o) <- p.outs]
        poolRead conn keys 4 tip "csum" ["no category"] `shouldReturn` Just [""]
      it "reads the pool by the page, as it is at the tip that is asked for" $ \(conn, fresh) -> do
        keys <- fresh
        fleetReport conn keys (Just 0) 10 "a" [block 1] [] `shouldReturn` True
        advancing conn keys 4 (Just 0) "a" Nothing (block 1) Nothing [] `shouldReturn` MovedTo (block 1)
        let tip = Just (block 1)
            a = address 1
        -- nine transactions, of which the fifth spends the first output of
        -- the first two
        forM_ [0 .. 8] $ \t ->
          poolOffer conn keys 4 tip (txOf t [out m 0 | t == 4, m <- [0, 1]]) [False | t == 4, _ <- [0, 1 :: Int]] []
            `shouldReturn` Taken
        poolRead conn keys 4 Nothing "page" ["0", "0"] `shouldReturn` Nothing
        -- the list of the pool: newest first, and by id downwards in a second
        Just listed <- poolRead conn keys 4 tip "page" ["0", "0"]
        pairs listed `shouldBe` [(block t, time) | (time, t) <- sortOn Down [(timeOf t, t) | t <- [0 .. 8]]]
        Just some <- poolRead conn keys 4 tip "page" ["2", "3"]
        pairs some `shouldBe` take 3 (drop 2 (pairs listed))
        -- an address: its sums, and its transactions from the top and from
        -- one of them
        let expected = P.addresses [(block t, timeOf t, entriesOf t [out m 0 | t == 4, m <- [0, 1]]) | t <- [0 .. 8]]
            mine = expected Map.! a
            totalled = P.totals mine
        Just [sums, none] <- poolRead conn keys 4 tip "sums" [a, "nobody"]
        map (read . C.unpack) (C.words sums)
          `shouldBe` [ totalled.txs,
                       totalled.paid,
                       totalled.paidCount,
                       totalled.spent,
                       totalled.spentCount,
                       totalled.both,
                       totalled.bothCount
                     ]
        none `shouldBe` ""
        totalled.bothCount `shouldSatisfy` (> 0)
        Just txs <- poolRead conn keys 4 tip "txs" [a, "", "", "100"]
        pairs txs `shouldBe` [(t, time) | (time, t) <- mine.txs]
        forM_ (zip [0 ..] mine.txs) $ \(i, (time, t)) -> do
          Just from <- poolRead conn keys 4 tip "txs" [a, C.pack (show time), t, "2"]
          pairs from `shouldBe` take 2 (drop i [(t', time') | (time', t') <- mine.txs])
        -- a transaction that is not there: from where it would be
        let (time0, t0) = (fst (last mine.txs), block 99)
        Just later <- poolRead conn keys 4 tip "txs" [a, C.pack (show time0), t0, "100"]
        pairs later `shouldBe` [(t, time) | (time, t) <- mine.txs, (Down time, t) >= (Down time0, t0)]
        -- its outputs, each with whether the pool spends it
        Just outs <- poolRead conn keys 4 tip "outs" [a, "", "", "100"]
        [(o, time, C.unpack flag) | [o, time, _, flag] <- chunks 4 outs]
          `shouldBe` [ (o, C.pack (show time), if Map.member o mine.spent then "1" else "0")
                     | (time, o, _) <- mine.paid
                     ]
        Just [flags] <- poolRead conn keys 4 tip "spent" [a, B.concat [o | (_, o, _) <- mine.paid]]
        C.unpack flags `shouldBe` [if Map.member o mine.spent then '1' else '0' | (_, o, _) <- mine.paid]
        -- bodies, spenders with the number of the input, and ids by prefix
        -- bodies come with what spends their outputs: nothing spends from
        -- the fifth, and the second input of the fifth spends the first
        -- output of the second
        poolRead conn keys 4 tip "bodies" [block 4 <> block 99 <> block 1]
          `shouldReturn` Just ["body", "0", "", "0", "body", "1", out 1 0, block 4, "1"]
        poolRead conn keys 4 tip "spenders" [out 1 0 <> out 0 0 <> out 5 0]
          `shouldReturn` Just [block 4, "1", block 4, "0", "", ""]
        poolRead conn keys 4 tip "ids" [B.take 3 (block 4)] `shouldReturn` Just (map block [0 .. 8])
        poolRead conn keys 4 tip "ids" [block 4] `shouldReturn` Just [block 4]
  where
    -- carry a step out in Redis and in the model, and compare
    check conn keys (model, now) = \case
      Wait ms -> return (model, now + ms)
      Report s recent views -> do
        let name = C.pack (show s)
            allowed = mayReport now name (`elem` map block views) model
        fleetReport conn keys (Just now) lease name (map block recent) (map block views)
          `shouldReturn` allowed
        let model' = if allowed then report now lease name (map block recent) model else model
        same conn keys now model'
        return (model', now)
      Shift wrong -> do
        let seen = maybe model.tip (Just . block) wrong
            (expected, model') = case move now seen model of
              F.Moved next -> (maybe Stays MovedTo next.tip, next)
              F.Stays -> (Stays, model)
              F.Raced -> (Raced, model)
        fleetMove conn keys (Just now) seen `shouldReturn` expected
        same conn keys now model'
        return (model', now)
    nothing = PoolChange {returned = [], gone = [], confirmed = [], spent = [], height = Nothing, lost = []}
    -- carry a step of the pool out in Redis and in the model, and compare
    pooled conn keys (model, tip, n, kept) = \case
      Give t inputs replaced -> do
        -- a transaction spends from those of lower numbers only, as none
        -- can spend from one that spends from it
        let outs = [(out a i, ok) | (a, i, ok) <- nubOrdOn (\(a, i, _) -> (a, i)) inputs, a < t]
            unspent o = lookup o outs == Just True
            (expected, model') = case P.offer maker unspent (block t) (map fst outs) (map block replaced) model of
              P.Taken next -> (Taken, next)
              P.Refused P.Known -> (Known, model)
              P.Refused (P.Conflict rivals) -> (Conflict rivals, model)
              P.Refused (P.Orphan os) -> (Orphan os, model)
        got <- poolOffer conn keys 4 tip (txOf t (map fst outs)) (map snd outs) (map block replaced)
        sorted got `shouldBe` sorted expected
        samePool conn keys model'
        return (model', tip, n, kept)
      Take ts -> do
        let model' = P.withdraw (map block ts) model
        left <- poolWithdraw conn keys 4 (map block ts)
        Set.fromList left `shouldBe` Map.keysSet model.spends `Set.difference` Map.keysSet model'.spends
        samePool conn keys model'
        return (model', tip, n, kept)
      Go back dead done used -> do
        -- one store, which reports a block that no step has had, 700
        -- blocks above the last, so that what was replaced is forgotten
        -- three steps later
        let target = block (1000 + n)
            height = 700 * (n + 1)
            returned' = [(block t, [out a i | (a, i) <- nubOrd ins, a < t]) | (t, ins) <- back]
            -- what spends each output in the blocks, one of the
            -- transactions of the tests, so that it may come back later
            labelled = [(out a i, block ((a * 7 + i * 3 + n) `mod` 12) <> encode height) | (a, i) <- used]
            change = P.Change returned' (map block dead) (map block done) (map fst labelled)
            -- the store names those of the abandoned blocks that it has as
            -- replaced: here one of those that are gone, by a transaction
            -- that the blocks may confirm now, later or never
            lost = [(block t, block w, block w <> encode height) | t <- take 1 dead, let w = (t * 5 + n) `mod` 12]
            sent =
              PoolChange
                [txOf (number t) os | (t, os) <- returned']
                change.gone
                change.confirmed
                [o <> w | (o, w) <- labelled]
                (Just height)
                [t <> w | (t, _, w) <- lost]
        fleetReport conn keys (Just 0) 10 "a" [target] (maybe [] pure tip) `shouldReturn` True
        advancing conn keys 4 (Just 0) "a" tip target (Just sent) [] `shouldReturn` MovedTo target
        let (records, waiting) = kept
            (model', replaced, waiting') = P.advanceReplacing maker change (`lookup` labelled) lost waiting model
            -- what a transaction that comes back had replaced is forgotten
            -- first, then the new, then what is 2016 blocks old
            back' = Set.fromList (map fst returned')
            unwon = Map.filter (\w -> not (Set.member (B.take 4 w) back')) records
            records' = Map.filter fresh (foldl' (\m (t, w) -> Map.insert t w m) unwon replaced)
            waiting'' = Map.filter (fresh . snd) waiting'
            fresh w = height < 2016 || either (const False) (> height - 2016) (decode (B.drop 4 w))
        samePool conn keys model'
        sameReplaced conn keys records' waiting''
        return (model', Just target, n + 1, (records', waiting''))
    maker = B.take 4
    -- what is kept of replaced transactions, with its two indices
    sameReplaced conn keys expected waiting = do
      let key k = keys.prefix <> k
          list :: Redis.Redis (Either Redis.Reply a) -> IO a
          list = fmap (either (error . show) id) . Redis.runRedis conn
      waits <- list (Redis.hgetall (key "pool:lost"))
      Map.fromList waits `shouldBe` Map.map snd waiting
      forM_ (Map.toList waiting) $ \(t, (by, _)) ->
        list (Redis.sismember (key ("pool:lostby:" <> by)) t) `shouldReturn` True
      byWinner <- list (Redis.keys (key "pool:lostby:*"))
      Set.fromList byWinner `shouldBe` Set.fromList [key ("pool:lostby:" <> by) | (by, _) <- Map.elems waiting]
      lostAt <- list (Redis.zcard (key "pool:lostat"))
      lostAt `shouldBe` fromIntegral (Map.size waiting)
      kept <- list (Redis.hgetall (key "pool:rep"))
      Map.fromList kept `shouldBe` expected
      at <- list (Redis.zrangeWithscores (key "pool:repat") 0 (-1))
      let heightOf w = either (const (-1)) fromIntegral (decode (B.drop 4 w) :: Either String Word32)
      Map.fromList at `shouldBe` Map.map heightOf expected
      forM_ (Map.toList expected) $ \(t, w) ->
        list (Redis.sismember (key ("pool:repby:" <> B.take 4 w)) t) `shouldReturn` True
      bys <- list (Redis.keys (key "pool:repby:*"))
      Set.fromList bys `shouldBe` Set.fromList [key ("pool:repby:" <> B.take 4 w) | w <- Map.elems expected]
    sorted = \case
      Conflict rivals -> Conflict (sort rivals)
      other -> other
    samePool conn keys model = do
      let key k = keys.prefix <> k
          list :: Redis.Redis (Either Redis.Reply a) -> IO a
          list = fmap (either (error . show) id) . Redis.runRedis conn
      spends <- poolSpends conn keys
      Map.fromList spends `shouldBe` Map.map B.concat model.spends
      spender <- list (Redis.hgetall (key "pool:spender"))
      Map.fromList spender `shouldBe` model.spender
      kids <- list (Redis.keys (key "pool:kids:*"))
      Set.fromList kids `shouldBe` Set.map (key . ("pool:kids:" <>)) (Map.keysSet model.children)
      forM_ (Map.toList model.children) $ \(t, expected) -> do
        members <- list (Redis.smembers (key ("pool:kids:" <> t)))
        Set.fromList members `shouldBe` expected
      -- which can be replaced by fee is not kept: it is a fact of the
      -- network, and no longer of the transaction and its parents
      list (Redis.keys (key "pool:rbf")) `shouldReturn` []
      list (Redis.keys (key "pool:own")) `shouldReturn` []
      -- and what it holds for each address is what the entries of its
      -- transactions come to
      let members = [(t, timeOf (number t), entriesOf (number t) os) | (t, os) <- Map.toList model.spends]
          expected = P.addresses members
          scored :: [(ByteString, Double)] -> [(Word64, ByteString)]
          scored rows = [(round (negate s), m) | (m, s) <- rows]
      listed <- list (Redis.zrangeWithscores (key "pool:time") 0 (-1))
      [(round s, t) | (t, s) <- listed] `shouldBe` sort [(time, t) | (t, time, _) <- members]
      forM_ (map address [0 .. 3]) $ \a -> do
        txs <- list (Redis.zrangeWithscores (key ("pool:atx:" <> a)) 0 (-1))
        outs <- list (Redis.zrangeWithscores (key ("pool:aout:" <> a)) 0 (-1))
        values <- Map.fromList <$> list (Redis.hgetall (key ("pool:aval:" <> a)))
        spent <- list (Redis.hgetall (key ("pool:aspent:" <> a)))
        sums <- Map.fromList <$> list (Redis.hgetall (key ("pool:asum:" <> a)))
        let amount o = maybe 0 (read . C.unpack . C.takeWhile (/= ' ')) (Map.lookup o values)
            found =
              P.AddressPool
                { txs = scored txs,
                  paid = [(time, o, amount o) | (time, o) <- scored outs],
                  spent = Map.fromList [(o, read (C.unpack v)) | (o, v) <- spent]
                }
            sumOf f = maybe 0 (read . C.unpack) (Map.lookup f sums)
            totalled =
              P.Totals
                { txs = sumOf "txs",
                  paid = sumOf "paid",
                  paidCount = sumOf "paidCount",
                  spent = sumOf "spent",
                  spentCount = sumOf "spentCount",
                  both = sumOf "both",
                  bothCount = sumOf "bothCount"
                }
        case Map.lookup a expected of
          Nothing -> (a, found, Map.null sums) `shouldBe` (a, P.AddressPool [] [] Map.empty, True)
          Just p -> (a, found, totalled) `shouldBe` (a, p, P.totals p)
        Map.keysSet values `shouldBe` Set.fromList [o | (_, o) <- scored outs]
      -- and what it holds for tokens is what the token entries of its
      -- transactions come to
      let byToken = P.tokenTotals (B.take 4) members
          byCategory = P.categories (B.take 4) members
          number' :: Map.Map ByteString ByteString -> ByteString -> Integer
          number' m f = maybe 0 (read . C.unpack) (Map.lookup f m)
          joined m f = fromInteger (number' m (f <> "Hi") * 1000000000 + number' m (f <> "Lo"))
      forM_ (map category [0, 1]) $ \c -> do
        txs <- list (Redis.zrangeWithscores (key ("pool:ctx:" <> c)) 0 (-1))
        outs <- list (Redis.zrangeWithscores (key ("pool:cout:" <> c)) 0 (-1))
        values <- list (Redis.hkeys (key ("pool:cval:" <> c)))
        sums <- Map.fromList <$> list (Redis.hgetall (key ("pool:csum:" <> c)))
        holders <- list (Redis.smembers (key ("pool:chold:" <> c)))
        let found =
              P.CategoryPool
                { txs = scored txs,
                  outs = scored outs,
                  free = fromInteger (number' sums "free"),
                  spent = fromInteger (number' sums "spent")
                }
        case Map.lookup c byCategory of
          Nothing -> (c, found, Map.null sums) `shouldBe` (c, P.CategoryPool [] [] 0 0, True)
          Just p -> (c, found) `shouldBe` (c, p)
        Set.fromList values `shouldBe` Set.fromList [o | (_, o) <- scored outs]
        Set.fromList holders `shouldBe` Set.fromList [a | (c', a) <- Map.keys byToken, c' == c]
        forM_ (map address [0 .. 3]) $ \a -> do
          m <- Map.fromList <$> list (Redis.hgetall (key ("pool:tsum:" <> c <> a)))
          let found' =
                P.TokenTotals
                  { txs = fromInteger (number' m "txs"),
                    free = joined m "free",
                    freeNfts = fromInteger (number' m "freeNfts"),
                    freeOutputs = fromInteger (number' m "freeOutputs"),
                    spent = joined m "spent",
                    spentNfts = fromInteger (number' m "spentNfts"),
                    spentOutputs = fromInteger (number' m "spentOutputs"),
                    received = joined m "received"
                  }
          case Map.lookup (c, a) byToken of
            Nothing -> (c, a, Map.null m) `shouldBe` (c, a, True)
            Just p -> (c, a, found') `shouldBe` (c, a, p)
      forM_ (map address [0 .. 3]) $ \a -> do
        cats <- list (Redis.smembers (key ("pool:acat:" <> a)))
        Set.fromList cats `shouldBe` Set.fromList [c | (c, a') <- Map.keys byToken, a' == a]
    same conn keys now model = do
      fleetTip conn keys `shouldReturn` (model :: F.Fleet ByteString ByteString).tip
      leases <- fleetLive conn keys
      Map.keys (Map.filter (> now) (Map.fromList leases)) `shouldBe` Map.keys (live now model)
    lease = 10

-- | The sums of the tokens of a category at an address, as @read.lua@
-- gives them, each amount in two parts joined again.
tokenTotalsOf :: ByteString -> P.TokenTotals
tokenTotalsOf row = case map read (words (C.unpack row)) :: [Integer] of
  [ txs,
    freeHi,
    freeLo,
    freeNfts,
    freeOutputs,
    spentHi,
    spentLo,
    spentNfts,
    spentOutputs,
    receivedHi,
    receivedLo
    ] ->
      P.TokenTotals
        { txs = fromInteger txs,
          free = joined freeHi freeLo,
          freeNfts = fromInteger freeNfts,
          freeOutputs = fromInteger freeOutputs,
          spent = joined spentHi spentLo,
          spentNfts = fromInteger spentNfts,
          spentOutputs = fromInteger spentOutputs,
          received = joined receivedHi receivedLo
        }
  _ -> error ("Not the sums of tokens: " <> show row)
  where
    joined hi lo = fromInteger (hi * 1000000000 + lo)

-- | The items of a list two by two, each second one a number.
pairs :: [ByteString] -> [(ByteString, Word64)]
pairs rows = [(x, read (C.unpack n)) | [x, n] <- chunks 2 rows]

-- | The items of a list so many at a time.
chunks :: Int -> [a] -> [[a]]
chunks _ [] = []
chunks n xs = take n xs : chunks n (drop n xs)

-- | A block of the tests, or a transaction: four bytes.
block :: Word32 -> ByteString
block = encode

-- | An output of a transaction of the tests.
out :: Word32 -> Word32 -> ByteString
out t i = encode t <> encode i

-- | The number of a block or of a transaction of the tests.
number :: ByteString -> Word32
number = either error id . decode

-- | One of the four addresses of the tests.
address :: Word32 -> ByteString
address n = C.pack ("address " <> show (n `mod` 4))

-- | The address that an output of the tests is paid to, and its amount.
-- Outputs of different transactions go to the same addresses, and a
-- transaction that spends an output does so at the address that it was
-- paid to, so that the pool has addresses with outputs both paid and spent.
paidTo :: ByteString -> (ByteString, Word64)
paidTo o = (address (t + i), fromIntegral (t * 10 + i + 1))
  where
    (t, i) = (number (B.take 4 o), number (B.drop 4 o))

-- | The time at which a transaction of the tests entered a mempool: one of
-- three, so that several have the same.
timeOf :: Word32 -> Word64
timeOf t = fromIntegral (t `mod` 3) + 100

-- | What a transaction of the tests that spends some outputs does at each
-- address: it pays two outputs of its own.
entriesOf :: Word32 -> [ByteString] -> [P.Entry ByteString ByteString ByteString]
entriesOf t spends =
  map P.Touches (nubOrd (map (fst . paidTo) (spends <> made)))
    <> [P.Spends a o v | o <- spends, let (a, v) = paidTo o]
    <> [P.Pays a o v | o <- made, let (a, v) = paidTo o]
    <> [P.Uses k | o <- spends, Just k <- [tokenOf o]]
    <> [P.Makes k | o <- made, Just k <- [tokenOf o]]
  where
    made = [out t 0, out t 1]

-- | The tokens of an output of the tests, if it holds any: two in three
-- do, of one of two categories, some near the largest amount so that the
-- sums of the pool go past what one integer holds, the first output of a
-- transaction with a non-fungible token, and some without an address.
tokenOf :: ByteString -> Maybe (P.TokenOut ByteString ByteString ByteString)
tokenOf o
  | (t + i) `mod` 3 == 2 = Nothing
  | otherwise =
      Just
        P.TokenOut
          { owner = if t `mod` 4 == 1 && i == 1 then Nothing else Just (fst (paidTo o)),
            output = o,
            category = category ((t + i) `mod` 2),
            amount = if even t then 0x7fffffffffffffff - fromIntegral (t * 7 + i) else fromIntegral (t * 1000 + i),
            nft = i == 0
          }
  where
    (t, i) = (number (B.take 4 o), number (B.drop 4 o))

-- | One of the two categories of tokens of the tests.
category :: Word32 -> ByteString
category n = C.pack ("cat " <> show n)

-- | Whether a transaction of the tests says itself that it can be replaced
-- by fee: one in four does.

-- | A transaction of the tests as the pool takes it.
txOf :: Word32 -> [ByteString] -> PoolTx
txOf t spends =
  PoolTx
    { txid = block t,
      time = timeOf t,
      inputs = spends,
      body = "body",
      entries = map entry (entriesOf t spends)
    }
  where
    entry = \case
      P.Touches a -> PoolTouches a
      P.Spends a o v -> PoolSpends a o v
      P.Pays a o v -> PoolPays a o v "script"
      P.Makes k -> PoolMakes (tokenOut k) {coins = Just (snd (paidTo k.output), "script")}
      P.Uses k -> PoolUses (tokenOut k)
    tokenOut k =
      PoolTokenOut
        { address = k.owner,
          output = k.output,
          category = k.category,
          amount = k.amount,
          nft = k.nft,
          coins = Nothing
        }

-- | A step of the shared mempool, with transactions numbered from 0 to 11.
data PoolStep
  = -- | a transaction is offered, spending some outputs, each found unspent
    -- at the tip or not, and replacing some transactions
    Give !Word32 ![(Word32, Word32, Bool)] ![Word32]
  | -- | transactions are withdrawn
    Take ![Word32]
  | -- | the tip moves: some transactions come back with what they spend,
    -- some are gone, some are confirmed, and some outputs are spent
    Go ![(Word32, [(Word32, Word32)])] ![Word32] ![Word32] ![(Word32, Word32)]
  deriving (Show)

instance Arbitrary PoolStep where
  arbitrary =
    frequency
      [ (8, Give <$> tx <*> few ((,,) <$> tx <*> choose (0, 1) <*> arbitrary) <*> few tx),
        (1, Take <$> few tx),
        (3, Go <$> few ((,) <$> tx <*> few output) <*> few tx <*> few tx <*> few output)
      ]
    where
      tx = choose (0, 11)
      output = (,) <$> tx <*> choose (0, 1)
      few :: Gen a -> Gen [a]
      few one = choose (0, 3) >>= (`vectorOf` one)

-- | Move the tip, and then take out of the pool what the move marked as
-- leaving, as the store that moves the tip does
-- (@Haskoin.Store.Fleet.Member.clearLeaving@): the pool is then as the
-- rules say it is after the move.
advancing ::
  Redis.Connection ->
  FleetKeys ->
  Int ->
  Maybe Time ->
  ByteString ->
  Maybe ByteString ->
  ByteString ->
  Maybe PoolChange ->
  [ByteString] ->
  IO Moved
advancing conn keys tsize clock store seen target known path = do
  moved <- fleetAdvance conn keys tsize clock store seen target known path
  marked <- poolLeaving conn keys
  unless (null marked) (void (poolTakeOut conn keys tsize marked))
  return moved

-- | A Redis in a container, reached through a socket of its pod, and a way
-- to get the keys of a fleet that no test has used.
withRedis :: ((Redis.Connection, IO FleetKeys) -> IO ()) -> IO ()
withRedis go =
  withContainer redisContainer $ \p -> do
    conn <- Redis.checkedConnect (either error id (redisConnectInfo (redisURL p)))
    counter <- newIORef (0 :: Int)
    go (conn, (\n -> fleetKeys (C.pack ("t" <> show n <> ":")) 4) <$> atomicModifyIORef' counter (\n -> (n + 1, n)))