packages feed

haskoin-store 1.16.7 → 2.0.0

raw patch · 87 files changed

+20528/−3826 lines, 87 filesdep +http-clientdep +podman-testdep ~fast-loggerdep ~haskoin-coredep ~haskoin-nodePVP ok

version bump matches the API change (PVP)

Dependencies added: http-client, podman-test

Dependency ranges changed: fast-logger, haskoin-core, haskoin-node, haskoin-store-data

API changes (from Hackage documentation)

- Haskoin.Store.BlockStore: [explicitPeers] :: BlockStoreConfig -> ![String]
- Haskoin.Store.BlockStore: [onTx] :: BlockStoreConfig -> !UnixTime -> Tx -> IO ()
- Haskoin.Store.BlockStore: [seen] :: BlockStoreConfig -> ![TxHash] -> IO (HashSet TxHash)
- Haskoin.Store.BlockStore: asksMempool :: Network -> [SockAddr] -> SockAddr -> Bool
- Haskoin.Store.BlockStore: blockStorePendingTxs :: BlockStore -> IO Int
- Haskoin.Store.BlockStore: blockStorePendingTxsSTM :: BlockStore -> STM Int
- Haskoin.Store.BlockStore: blockStoreRefill :: BlockStore -> IO ()
- Haskoin.Store.BlockStore: blockStoreTx :: Peer -> Tx -> BlockStore -> IO ()
- Haskoin.Store.BlockStore: blockStoreTxHash :: Peer -> [TxHash] -> BlockStore -> IO ()
- Haskoin.Store.BlockStore: blockStoreTxHashSTM :: Peer -> [TxHash] -> BlockStore -> STM ()
- Haskoin.Store.BlockStore: blockStoreTxSTM :: Peer -> Tx -> BlockStore -> STM ()
- Haskoin.Store.BlockStore: toFetch :: (TxHash -> IO Bool) -> ([TxHash] -> IO (HashSet TxHash)) -> (TxHash -> IO Bool) -> [TxHash] -> IO [TxHash]
- Haskoin.Store.BlockStore.Pending: answered :: TxHash -> Pending -> Pending
- Haskoin.Store.BlockStore.Pending: data Pending
- Haskoin.Store.BlockStore.Pending: empty :: Pending
- Haskoin.Store.BlockStore.Pending: instance GHC.Classes.Eq Haskoin.Store.BlockStore.Pending.Pending
- Haskoin.Store.BlockStore.Pending: instance GHC.Internal.Show.Show Haskoin.Store.BlockStore.Pending.Pending
- Haskoin.Store.BlockStore.Pending: isPending :: TxHash -> Pending -> Bool
- Haskoin.Store.BlockStore.Pending: prune :: UTCTime -> Pending -> Pending
- Haskoin.Store.BlockStore.Pending: requestTimeout :: NominalDiffTime
- Haskoin.Store.BlockStore.Pending: requested :: UTCTime -> [TxHash] -> Pending -> Pending
- Haskoin.Store.BlockStore.Pending: size :: Pending -> Int
- Haskoin.Store.BlockStore.Sync: release :: Eq p => p -> Sync p -> (Bool, Sync p)
- Haskoin.Store.Database.Stalls: Delayed :: Writes
- Haskoin.Store.Database.Stalls: Flowing :: Writes
- Haskoin.Store.Database.Stalls: Stall :: !Writes -> !Integer -> !Integer -> Stall
- Haskoin.Store.Database.Stalls: Stopped :: Writes
- Haskoin.Store.Database.Stalls: [pending] :: Stall -> !Integer
- Haskoin.Store.Database.Stalls: [rate] :: Stall -> !Integer
- Haskoin.Store.Database.Stalls: [writes] :: Stall -> !Writes
- Haskoin.Store.Database.Stalls: data Stall
- Haskoin.Store.Database.Stalls: data Writes
- Haskoin.Store.Database.Stalls: instance GHC.Classes.Eq Haskoin.Store.Database.Stalls.Stall
- Haskoin.Store.Database.Stalls: instance GHC.Classes.Eq Haskoin.Store.Database.Stalls.Writes
- Haskoin.Store.Database.Stalls: instance GHC.Classes.Ord Haskoin.Store.Database.Stalls.Writes
- Haskoin.Store.Database.Stalls: instance GHC.Internal.Enum.Bounded Haskoin.Store.Database.Stalls.Writes
- Haskoin.Store.Database.Stalls: instance GHC.Internal.Enum.Enum Haskoin.Store.Database.Stalls.Writes
- Haskoin.Store.Database.Stalls: instance GHC.Internal.Show.Show Haskoin.Store.Database.Stalls.Stall
- Haskoin.Store.Database.Stalls: instance GHC.Internal.Show.Show Haskoin.Store.Database.Stalls.Writes
- Haskoin.Store.Fleet.Member: [waiting] :: Member -> !TVar (HashMap TxHash (UnixTime, Tx))
- Haskoin.Store.Fleet.Member: memberReceived :: Member -> UnixTime -> Tx -> IO ()
- Haskoin.Store.Fleet.Member: memberSeen :: Member -> [TxHash] -> IO (HashSet TxHash)
- Haskoin.Store.Fleet.Member: mostSeen :: Int
- Haskoin.Store.Fleet.Member: offerMempool :: Member -> IO ()
- Haskoin.Store.Fleet.Pool: instance (GHC.Classes.Eq a, GHC.Classes.Eq o) => GHC.Classes.Eq (Haskoin.Store.Fleet.Pool.Entry a o)
- Haskoin.Store.Fleet.Pool: instance (GHC.Internal.Show.Show a, GHC.Internal.Show.Show o) => GHC.Internal.Show.Show (Haskoin.Store.Fleet.Pool.Entry a o)
- Haskoin.Store.Fleet.Pool: replaceable :: Ord t => (t -> Bool) -> (o -> t) -> Pool t o -> Set t
- Haskoin.Store.Fleet.Redis: [signals] :: PoolTx -> !Bool
- Haskoin.Store.Fleet.Redis: fleetSeen :: Connection -> FleetKeys -> [ByteString] -> IO [Bool]
- Haskoin.Store.Fleet.Redis: fleetTrimSeen :: Connection -> FleetKeys -> Int -> IO Integer
- Haskoin.Store.Fleet.Redis: instance GHC.Classes.Eq Haskoin.Store.Fleet.Redis.Moved
- Haskoin.Store.Fleet.Redis: instance GHC.Classes.Eq Haskoin.Store.Fleet.Redis.Offered
- Haskoin.Store.Fleet.Redis: instance GHC.Classes.Eq Haskoin.Store.Fleet.Redis.PoolChange
- Haskoin.Store.Fleet.Redis: instance GHC.Classes.Eq Haskoin.Store.Fleet.Redis.PoolEntry
- Haskoin.Store.Fleet.Redis: instance GHC.Classes.Eq Haskoin.Store.Fleet.Redis.PoolTx
- Haskoin.Store.Fleet.Redis: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Redis.Moved
- Haskoin.Store.Fleet.Redis: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Redis.Offered
- Haskoin.Store.Fleet.Redis: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Redis.PoolChange
- Haskoin.Store.Fleet.Redis: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Redis.PoolEntry
- Haskoin.Store.Fleet.Redis: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Redis.PoolTx
- Haskoin.Store.Web: withDatabase :: Stall -> HealthCheck -> Value
- Haskoin.Store.Web.Publish: instance GHC.Classes.Eq Haskoin.Store.Web.Publish.Coin
- Haskoin.Store.Web.Publish: instance GHC.Classes.Eq Haskoin.Store.Web.Publish.Refusal
- Haskoin.Store.Web.Publish: instance GHC.Internal.Show.Show Haskoin.Store.Web.Publish.Coin
- Haskoin.Store.Web.Publish: instance GHC.Internal.Show.Show Haskoin.Store.Web.Publish.Refusal
+ Haskoin.Store: [foreignPeers] :: StoreConfig -> !Bool
+ Haskoin.Store: [getAddressTokens] :: StoreRead -> Address -> IO [TokenBalance]
+ Haskoin.Store: [getTokenHolders] :: StoreRead -> TxHash -> Limits -> IO [TokenBalance]
+ Haskoin.Store: [getTokenTxs] :: StoreRead -> TxHash -> Limits -> IO [TxRef]
+ Haskoin.Store: [getTokenUnspents] :: StoreRead -> TxHash -> Limits -> IO [Unspent]
+ Haskoin.Store: [ingest] :: Store -> !Ingester
+ Haskoin.Store: [nodePeerRpcSocket] :: StoreConfig -> !Maybe FilePath
+ Haskoin.Store: [nodePeerRpc] :: StoreConfig -> !Maybe String
+ Haskoin.Store: [nodePeerZmq] :: StoreConfig -> !Maybe String
+ Haskoin.Store: [peerPermissions] :: StoreConfig -> !Permissions
+ Haskoin.Store.BlockStore.Sync: finish :: Eq p => UTCTime -> p -> Sync p -> (Bool, Sync p)
+ Haskoin.Store.BlockStore.Sync: forget :: Eq p => p -> Sync p -> (Bool, Sync p)
+ Haskoin.Store.Common: [getAddressTokens] :: StoreRead -> Address -> IO [TokenBalance]
+ Haskoin.Store.Common: [getTokenHolders] :: StoreRead -> TxHash -> Limits -> IO [TokenBalance]
+ Haskoin.Store.Common: [getTokenTxs] :: StoreRead -> TxHash -> Limits -> IO [TxRef]
+ Haskoin.Store.Common: [getTokenUnspents] :: StoreRead -> TxHash -> Limits -> IO [Unspent]
+ Haskoin.Store.Database.Migrate: mergesVersion :: Word32
+ Haskoin.Store.Database.Migrate.Tokens: migrateTokens :: (Text -> IO ()) -> BlockHeight -> DatabaseReader -> IO Int
+ Haskoin.Store.Database.Migrate.Tokens: tokenActivation :: DatabaseReader -> IO BlockHeight
+ Haskoin.Store.Database.Migrate.Tokens: tokenUpgradeTime :: Word64
+ Haskoin.Store.Database.Query: getAddressTokens :: DatabaseReader -> Address -> IO [(TxHash, TokBalVal)]
+ Haskoin.Store.Database.Query: getCategoryHolders :: DatabaseReader -> TxHash -> Limits -> IO [(Address, TokBalVal)]
+ Haskoin.Store.Database.Query: getCategoryTxs :: DatabaseReader -> TxHash -> Limits -> IO [TxRef]
+ Haskoin.Store.Database.Query: getCategoryUnspents :: DatabaseReader -> TxHash -> Limits -> IO [Unspent]
+ Haskoin.Store.Database.Query: getTokBal :: DatabaseReader -> Address -> TxHash -> IO (Maybe TokBalVal)
+ Haskoin.Store.Database.Query.Pooled: [addressTokens] :: PoolReads -> Address -> IO [(TxHash, PoolTokens)]
+ Haskoin.Store.Database.Query.Pooled: [categoryHolders] :: PoolReads -> TxHash -> IO [(Address, PoolTokens)]
+ Haskoin.Store.Database.Query.Pooled: [categoryOuts] :: PoolReads -> TxHash -> Maybe (UnixTime, OutPoint) -> Int -> IO [(Unspent, Bool)]
+ Haskoin.Store.Database.Query.Pooled: [categorySummary] :: PoolReads -> TxHash -> IO (Maybe CategorySummary)
+ Haskoin.Store.Database.Query.Pooled: [categoryTxs] :: PoolReads -> TxHash -> Maybe (UnixTime, TxHash) -> Int -> IO [(UnixTime, TxHash)]
+ Haskoin.Store.Database.Reader: catOutCF :: DB -> ColumnFamily
+ Haskoin.Store.Database.Reader: catTxCF :: DB -> ColumnFamily
+ Haskoin.Store.Database.Reader: holderCF :: DB -> ColumnFamily
+ Haskoin.Store.Database.Reader: tokBalCF :: DB -> ColumnFamily
+ Haskoin.Store.Database.Reader: tokenFamilyConfig :: Bool -> Bool -> [(String, Config)]
+ Haskoin.Store.Database.Table: instance Haskoin.Store.Database.Table.TableKey (Haskoin.Address.Address, Haskoin.Transaction.Common.TxHash)
+ Haskoin.Store.Database.Table: instance Haskoin.Store.Database.Table.TableKey (Haskoin.Transaction.Common.TxHash, Haskoin.Store.Data.BlockRef, Haskoin.Transaction.Common.OutPoint)
+ Haskoin.Store.Database.Table: instance Haskoin.Store.Database.Table.TableKey (Haskoin.Transaction.Common.TxHash, Haskoin.Store.Data.TxRef)
+ Haskoin.Store.Database.Types: CatOutKey :: !TxHash -> !BlockRef -> !OutPoint -> CatOutKey
+ Haskoin.Store.Database.Types: CatOutKeyB :: !TxHash -> !BlockRef -> CatOutKey
+ Haskoin.Store.Database.Types: CatOutKeyC :: !TxHash -> CatOutKey
+ Haskoin.Store.Database.Types: CatTxKey :: !TxHash -> !TxRef -> CatTxKey
+ Haskoin.Store.Database.Types: CatTxKeyB :: !TxHash -> !BlockRef -> CatTxKey
+ Haskoin.Store.Database.Types: CatTxKeyC :: !TxHash -> CatTxKey
+ Haskoin.Store.Database.Types: CategorySummary :: !Word64 -> !Word64 -> !Word64 -> CategorySummary
+ Haskoin.Store.Database.Types: HolderKey :: !TxHash -> !Address -> HolderKey
+ Haskoin.Store.Database.Types: HolderKeyC :: !TxHash -> HolderKey
+ Haskoin.Store.Database.Types: PoolTokens :: !Word64 -> !Word64 -> !Word64 -> !Word64 -> !Word64 -> !Word64 -> !Word64 -> !Word64 -> PoolTokens
+ Haskoin.Store.Database.Types: TokBalKey :: !Address -> !TxHash -> TokBalKey
+ Haskoin.Store.Database.Types: TokBalKeyA :: !Address -> TokBalKey
+ Haskoin.Store.Database.Types: TokBalVal :: !Word64 -> !Word64 -> !Word64 -> !Word64 -> !Word64 -> TokBalVal
+ Haskoin.Store.Database.Types: [amount] :: TokBalVal -> !Word64
+ Haskoin.Store.Database.Types: [count] :: TokBalVal -> !Word64
+ Haskoin.Store.Database.Types: [freeNfts] :: PoolTokens -> !Word64
+ Haskoin.Store.Database.Types: [freeOutputs] :: PoolTokens -> !Word64
+ Haskoin.Store.Database.Types: [free] :: CategorySummary -> !Word64
+ Haskoin.Store.Database.Types: [nfts] :: TokBalVal -> !Word64
+ Haskoin.Store.Database.Types: [outputs] :: TokBalVal -> !Word64
+ Haskoin.Store.Database.Types: [spentNfts] :: PoolTokens -> !Word64
+ Haskoin.Store.Database.Types: [spentOutputs] :: PoolTokens -> !Word64
+ Haskoin.Store.Database.Types: addTokBalVal :: TokBalVal -> TokBalVal -> TokBalVal
+ Haskoin.Store.Database.Types: data CatOutKey
+ Haskoin.Store.Database.Types: data CatTxKey
+ Haskoin.Store.Database.Types: data CategorySummary
+ Haskoin.Store.Database.Types: data HolderKey
+ Haskoin.Store.Database.Types: data PoolTokens
+ Haskoin.Store.Database.Types: data TokBalKey
+ Haskoin.Store.Database.Types: data TokBalVal
+ Haskoin.Store.Database.Types: instance Control.DeepSeq.NFData Haskoin.Store.Database.Types.CategorySummary
+ Haskoin.Store.Database.Types: instance Control.DeepSeq.NFData Haskoin.Store.Database.Types.PoolTokens
+ Haskoin.Store.Database.Types: instance Control.DeepSeq.NFData Haskoin.Store.Database.Types.TokBalVal
+ Haskoin.Store.Database.Types: instance Data.Default.Internal.Default Haskoin.Store.Database.Types.TokBalVal
+ Haskoin.Store.Database.Types: instance Data.Hashable.Class.Hashable Haskoin.Store.Database.Types.CatOutKey
+ Haskoin.Store.Database.Types: instance Data.Hashable.Class.Hashable Haskoin.Store.Database.Types.CatTxKey
+ Haskoin.Store.Database.Types: instance Data.Hashable.Class.Hashable Haskoin.Store.Database.Types.CategorySummary
+ Haskoin.Store.Database.Types: instance Data.Hashable.Class.Hashable Haskoin.Store.Database.Types.HolderKey
+ Haskoin.Store.Database.Types: instance Data.Hashable.Class.Hashable Haskoin.Store.Database.Types.PoolTokens
+ Haskoin.Store.Database.Types: instance Data.Hashable.Class.Hashable Haskoin.Store.Database.Types.TokBalKey
+ Haskoin.Store.Database.Types: instance Data.Hashable.Class.Hashable Haskoin.Store.Database.Types.TokBalVal
+ Haskoin.Store.Database.Types: instance Data.Serialize.Serialize Haskoin.Store.Database.Types.CatOutKey
+ Haskoin.Store.Database.Types: instance Data.Serialize.Serialize Haskoin.Store.Database.Types.CatTxKey
+ Haskoin.Store.Database.Types: instance Data.Serialize.Serialize Haskoin.Store.Database.Types.CategorySummary
+ Haskoin.Store.Database.Types: instance Data.Serialize.Serialize Haskoin.Store.Database.Types.HolderKey
+ Haskoin.Store.Database.Types: instance Data.Serialize.Serialize Haskoin.Store.Database.Types.PoolTokens
+ Haskoin.Store.Database.Types: instance Data.Serialize.Serialize Haskoin.Store.Database.Types.TokBalKey
+ Haskoin.Store.Database.Types: instance Data.Serialize.Serialize Haskoin.Store.Database.Types.TokBalVal
+ Haskoin.Store.Database.Types: instance Database.RocksDB.Query.Key Haskoin.Store.Database.Types.CatOutKey
+ Haskoin.Store.Database.Types: instance Database.RocksDB.Query.Key Haskoin.Store.Database.Types.CatTxKey
+ Haskoin.Store.Database.Types: instance Database.RocksDB.Query.Key Haskoin.Store.Database.Types.HolderKey
+ Haskoin.Store.Database.Types: instance Database.RocksDB.Query.Key Haskoin.Store.Database.Types.TokBalKey
+ Haskoin.Store.Database.Types: instance Database.RocksDB.Query.KeyValue Haskoin.Store.Database.Types.CatOutKey Haskoin.Store.Database.Types.OutVal
+ Haskoin.Store.Database.Types: instance Database.RocksDB.Query.KeyValue Haskoin.Store.Database.Types.CatTxKey ()
+ Haskoin.Store.Database.Types: instance Database.RocksDB.Query.KeyValue Haskoin.Store.Database.Types.HolderKey Haskoin.Store.Database.Types.TokBalVal
+ Haskoin.Store.Database.Types: instance Database.RocksDB.Query.KeyValue Haskoin.Store.Database.Types.TokBalKey Haskoin.Store.Database.Types.TokBalVal
+ Haskoin.Store.Database.Types: instance GHC.Classes.Eq Haskoin.Store.Database.Types.CatOutKey
+ Haskoin.Store.Database.Types: instance GHC.Classes.Eq Haskoin.Store.Database.Types.CatTxKey
+ Haskoin.Store.Database.Types: instance GHC.Classes.Eq Haskoin.Store.Database.Types.CategorySummary
+ Haskoin.Store.Database.Types: instance GHC.Classes.Eq Haskoin.Store.Database.Types.HolderKey
+ Haskoin.Store.Database.Types: instance GHC.Classes.Eq Haskoin.Store.Database.Types.PoolTokens
+ Haskoin.Store.Database.Types: instance GHC.Classes.Eq Haskoin.Store.Database.Types.TokBalKey
+ Haskoin.Store.Database.Types: instance GHC.Classes.Eq Haskoin.Store.Database.Types.TokBalVal
+ Haskoin.Store.Database.Types: instance GHC.Classes.Ord Haskoin.Store.Database.Types.CatOutKey
+ Haskoin.Store.Database.Types: instance GHC.Classes.Ord Haskoin.Store.Database.Types.CatTxKey
+ Haskoin.Store.Database.Types: instance GHC.Classes.Ord Haskoin.Store.Database.Types.CategorySummary
+ Haskoin.Store.Database.Types: instance GHC.Classes.Ord Haskoin.Store.Database.Types.HolderKey
+ Haskoin.Store.Database.Types: instance GHC.Classes.Ord Haskoin.Store.Database.Types.PoolTokens
+ Haskoin.Store.Database.Types: instance GHC.Classes.Ord Haskoin.Store.Database.Types.TokBalKey
+ Haskoin.Store.Database.Types: instance GHC.Classes.Ord Haskoin.Store.Database.Types.TokBalVal
+ Haskoin.Store.Database.Types: instance GHC.Internal.Generics.Generic Haskoin.Store.Database.Types.CatOutKey
+ Haskoin.Store.Database.Types: instance GHC.Internal.Generics.Generic Haskoin.Store.Database.Types.CatTxKey
+ Haskoin.Store.Database.Types: instance GHC.Internal.Generics.Generic Haskoin.Store.Database.Types.CategorySummary
+ Haskoin.Store.Database.Types: instance GHC.Internal.Generics.Generic Haskoin.Store.Database.Types.HolderKey
+ Haskoin.Store.Database.Types: instance GHC.Internal.Generics.Generic Haskoin.Store.Database.Types.PoolTokens
+ Haskoin.Store.Database.Types: instance GHC.Internal.Generics.Generic Haskoin.Store.Database.Types.TokBalKey
+ Haskoin.Store.Database.Types: instance GHC.Internal.Generics.Generic Haskoin.Store.Database.Types.TokBalVal
+ Haskoin.Store.Database.Types: instance GHC.Internal.Read.Read Haskoin.Store.Database.Types.CatOutKey
+ Haskoin.Store.Database.Types: instance GHC.Internal.Read.Read Haskoin.Store.Database.Types.CategorySummary
+ Haskoin.Store.Database.Types: instance GHC.Internal.Read.Read Haskoin.Store.Database.Types.HolderKey
+ Haskoin.Store.Database.Types: instance GHC.Internal.Read.Read Haskoin.Store.Database.Types.PoolTokens
+ Haskoin.Store.Database.Types: instance GHC.Internal.Read.Read Haskoin.Store.Database.Types.TokBalKey
+ Haskoin.Store.Database.Types: instance GHC.Internal.Read.Read Haskoin.Store.Database.Types.TokBalVal
+ Haskoin.Store.Database.Types: instance GHC.Internal.Show.Show Haskoin.Store.Database.Types.CatOutKey
+ Haskoin.Store.Database.Types: instance GHC.Internal.Show.Show Haskoin.Store.Database.Types.CatTxKey
+ Haskoin.Store.Database.Types: instance GHC.Internal.Show.Show Haskoin.Store.Database.Types.CategorySummary
+ Haskoin.Store.Database.Types: instance GHC.Internal.Show.Show Haskoin.Store.Database.Types.HolderKey
+ Haskoin.Store.Database.Types: instance GHC.Internal.Show.Show Haskoin.Store.Database.Types.PoolTokens
+ Haskoin.Store.Database.Types: instance GHC.Internal.Show.Show Haskoin.Store.Database.Types.TokBalKey
+ Haskoin.Store.Database.Types: instance GHC.Internal.Show.Show Haskoin.Store.Database.Types.TokBalVal
+ Haskoin.Store.Database.Writer: deleteCatTx :: Writer -> TxHash -> TxRef -> IO ()
+ Haskoin.Store.Database.Writer: deleteCatUnspent :: Writer -> TxHash -> Unspent -> IO ()
+ Haskoin.Store.Database.Writer: getTokBal :: Writer -> Address -> TxHash -> IO (Maybe TokBalVal)
+ Haskoin.Store.Database.Writer: insertCatTx :: Writer -> TxHash -> TxRef -> IO ()
+ Haskoin.Store.Database.Writer: insertCatUnspent :: Writer -> TxHash -> Unspent -> IO ()
+ Haskoin.Store.Database.Writer: mergeTokBal :: Writer -> Address -> TxHash -> TokBalVal -> IO ()
+ Haskoin.Store.Database.Writer: setTokBal :: Writer -> Address -> TxHash -> Maybe TokBalVal -> IO ()
+ Haskoin.Store.Database.Writer: writeRaw :: Writer -> BatchOp -> IO ()
+ Haskoin.Store.Fleet: Wake :: !Bool -> !Bool -> !Bool -> !Bool -> Wake
+ Haskoin.Store.Fleet: [block] :: Wake -> !Bool
+ Haskoin.Store.Fleet: [due] :: Wake -> !Bool
+ Haskoin.Store.Fleet: [owed] :: Wake -> !Bool
+ Haskoin.Store.Fleet: [well] :: Wake -> !Bool
+ Haskoin.Store.Fleet: data Wake
+ Haskoin.Store.Fleet: instance GHC.Classes.Eq Haskoin.Store.Fleet.Wake
+ Haskoin.Store.Fleet: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Wake
+ Haskoin.Store.Fleet: mayEmptyAlone :: Eq s => Time -> s -> Fleet s b -> Bool
+ Haskoin.Store.Fleet: turn :: Wake -> Bool
+ Haskoin.Store.Fleet.Atomic: Ahead :: !Query -> (Answer -> [Ahead]) -> Ahead
+ Haskoin.Store.Fleet.Atomic: At :: !Score -> Bound
+ Haskoin.Store.Fleet.Atomic: Backend :: ![Query] -> m [Answer] -> !m Integer -> Backend (m :: Type -> Type)
+ Haskoin.Store.Fleet.Atomic: Bytes :: !ByteString -> Value
+ Haskoin.Store.Fleet.Atomic: Count :: !Integer -> Answer
+ Haskoin.Store.Fleet.Atomic: Decided :: a -> ![(Query, Answer)] -> ![Op] -> !Int -> Outcome a
+ Haskoin.Store.Fleet.Atomic: Del :: !Key -> Op
+ Haskoin.Store.Fleet.Atomic: Exists :: !Key -> Query
+ Haskoin.Store.Fleet.Atomic: Fields :: !Map ByteString ByteString -> Answer
+ Haskoin.Store.Fleet.Atomic: Flag :: !Bool -> Answer
+ Haskoin.Store.Fleet.Atomic: Get :: !Key -> Query
+ Haskoin.Store.Fleet.Atomic: Group :: !Map ByteString () -> Value
+ Haskoin.Store.Fleet.Atomic: HAbove :: !Key -> !Integer -> Query
+ Haskoin.Store.Fleet.Atomic: HDel :: !Key -> !ByteString -> Op
+ Haskoin.Store.Fleet.Atomic: HExists :: !Key -> !ByteString -> Query
+ Haskoin.Store.Fleet.Atomic: HGet :: !Key -> !ByteString -> Query
+ Haskoin.Store.Fleet.Atomic: HGetAll :: !Key -> Query
+ Haskoin.Store.Fleet.Atomic: HIncrBy :: !Key -> !ByteString -> !Integer -> Op
+ Haskoin.Store.Fleet.Atomic: HKeys :: !Key -> Query
+ Haskoin.Store.Fleet.Atomic: HSet :: !Key -> !ByteString -> !ByteString -> Op
+ Haskoin.Store.Fleet.Atomic: Hash :: !Map ByteString ByteString -> Value
+ Haskoin.Store.Fleet.Atomic: IncrBy :: !Key -> !Integer -> Op
+ Haskoin.Store.Fleet.Atomic: Members :: !Set ByteString -> Answer
+ Haskoin.Store.Fleet.Atomic: MinusInf :: Bound
+ Haskoin.Store.Fleet.Atomic: PlusInf :: Bound
+ Haskoin.Store.Fleet.Atomic: Ranked :: ![(ByteString, Score)] -> Answer
+ Haskoin.Store.Fleet.Atomic: SAdd :: !Key -> !ByteString -> Op
+ Haskoin.Store.Fleet.Atomic: SIsMember :: !Key -> !ByteString -> Query
+ Haskoin.Store.Fleet.Atomic: SMembers :: !Key -> Query
+ Haskoin.Store.Fleet.Atomic: SRem :: !Key -> !ByteString -> Op
+ Haskoin.Store.Fleet.Atomic: Scored :: !Maybe Score -> Answer
+ Haskoin.Store.Fleet.Atomic: Set :: !Key -> !ByteString -> Op
+ Haskoin.Store.Fleet.Atomic: Sorted :: !Map ByteString Score -> Value
+ Haskoin.Store.Fleet.Atomic: Stream :: !Seq [(ByteString, ByteString)] -> Value
+ Haskoin.Store.Fleet.Atomic: Stuck :: !Unanswerable -> Outcome a
+ Haskoin.Store.Fleet.Atomic: Text :: !Maybe ByteString -> Answer
+ Haskoin.Store.Fleet.Atomic: Unanswerable :: !Query -> !String -> Unanswerable
+ Haskoin.Store.Fleet.Atomic: Wipe :: !ByteString -> Op
+ Haskoin.Store.Fleet.Atomic: XAdd :: !Key -> !Int -> ![(ByteString, ByteString)] -> Op
+ Haskoin.Store.Fleet.Atomic: ZAdd :: !Key -> !Score -> !ByteString -> Op
+ Haskoin.Store.Fleet.Atomic: ZAddNX :: !Key -> !Score -> !ByteString -> Op
+ Haskoin.Store.Fleet.Atomic: ZCard :: !Key -> Query
+ Haskoin.Store.Fleet.Atomic: ZRangeByScore :: !Key -> !Bound -> !Bound -> !Maybe Int -> Query
+ Haskoin.Store.Fleet.Atomic: ZRem :: !Key -> !ByteString -> Op
+ Haskoin.Store.Fleet.Atomic: ZRemRangeByRank :: !Key -> !Integer -> !Integer -> Op
+ Haskoin.Store.Fleet.Atomic: ZScore :: !Key -> !ByteString -> Query
+ Haskoin.Store.Fleet.Atomic: [fetch] :: Backend (m :: Type -> Type) -> ![Query] -> m [Answer]
+ Haskoin.Store.Fleet.Atomic: [time] :: Backend (m :: Type -> Type) -> !m Integer
+ Haskoin.Store.Fleet.Atomic: ahead :: forall (m :: Type -> Type). Monad m => [Ahead] -> Atomic m Bool
+ Haskoin.Store.Fleet.Atomic: answer :: Db -> Query -> Answer
+ Haskoin.Store.Fleet.Atomic: clock :: forall (m :: Type -> Type). Monad m => Atomic m Integer
+ Haskoin.Store.Fleet.Atomic: data Ahead
+ Haskoin.Store.Fleet.Atomic: data Answer
+ Haskoin.Store.Fleet.Atomic: data Atomic (m :: Type -> Type) a
+ Haskoin.Store.Fleet.Atomic: data Backend (m :: Type -> Type)
+ Haskoin.Store.Fleet.Atomic: data Bound
+ Haskoin.Store.Fleet.Atomic: data Op
+ Haskoin.Store.Fleet.Atomic: data Outcome a
+ Haskoin.Store.Fleet.Atomic: data Query
+ Haskoin.Store.Fleet.Atomic: data Unanswerable
+ Haskoin.Store.Fleet.Atomic: data Value
+ Haskoin.Store.Fleet.Atomic: emptyDb :: Db
+ Haskoin.Store.Fleet.Atomic: exists :: forall (m :: Type -> Type). Monad m => Key -> Atomic m Bool
+ Haskoin.Store.Fleet.Atomic: get :: forall (m :: Type -> Type). Monad m => Key -> Atomic m (Maybe ByteString)
+ Haskoin.Store.Fleet.Atomic: guarding :: forall (m :: Type -> Type). Monad m => Key -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic: habove :: forall (m :: Type -> Type). Monad m => Key -> Integer -> Atomic m (Set ByteString)
+ Haskoin.Store.Fleet.Atomic: heldByMark :: Unanswerable -> Bool
+ Haskoin.Store.Fleet.Atomic: hexists :: forall (m :: Type -> Type). Monad m => Key -> ByteString -> Atomic m Bool
+ Haskoin.Store.Fleet.Atomic: hget :: forall (m :: Type -> Type). Monad m => Key -> ByteString -> Atomic m (Maybe ByteString)
+ Haskoin.Store.Fleet.Atomic: hgetall :: forall (m :: Type -> Type). Monad m => Key -> Atomic m (Map ByteString ByteString)
+ Haskoin.Store.Fleet.Atomic: hkeys :: forall (m :: Type -> Type). Monad m => Key -> Atomic m (Set ByteString)
+ Haskoin.Store.Fleet.Atomic: instance GHC.Classes.Eq Haskoin.Store.Fleet.Atomic.Answer
+ Haskoin.Store.Fleet.Atomic: instance GHC.Classes.Eq Haskoin.Store.Fleet.Atomic.Bound
+ Haskoin.Store.Fleet.Atomic: instance GHC.Classes.Eq Haskoin.Store.Fleet.Atomic.Op
+ Haskoin.Store.Fleet.Atomic: instance GHC.Classes.Eq Haskoin.Store.Fleet.Atomic.Query
+ Haskoin.Store.Fleet.Atomic: instance GHC.Classes.Eq Haskoin.Store.Fleet.Atomic.Unanswerable
+ Haskoin.Store.Fleet.Atomic: instance GHC.Classes.Eq Haskoin.Store.Fleet.Atomic.Value
+ Haskoin.Store.Fleet.Atomic: instance GHC.Classes.Ord Haskoin.Store.Fleet.Atomic.Answer
+ Haskoin.Store.Fleet.Atomic: instance GHC.Classes.Ord Haskoin.Store.Fleet.Atomic.Bound
+ Haskoin.Store.Fleet.Atomic: instance GHC.Classes.Ord Haskoin.Store.Fleet.Atomic.Op
+ Haskoin.Store.Fleet.Atomic: instance GHC.Classes.Ord Haskoin.Store.Fleet.Atomic.Query
+ Haskoin.Store.Fleet.Atomic: instance GHC.Internal.Base.Functor m => GHC.Internal.Base.Functor (Haskoin.Store.Fleet.Atomic.Atomic m)
+ Haskoin.Store.Fleet.Atomic: instance GHC.Internal.Base.Monad m => GHC.Internal.Base.Applicative (Haskoin.Store.Fleet.Atomic.Atomic m)
+ Haskoin.Store.Fleet.Atomic: instance GHC.Internal.Base.Monad m => GHC.Internal.Base.Monad (Haskoin.Store.Fleet.Atomic.Atomic m)
+ Haskoin.Store.Fleet.Atomic: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Atomic.Answer
+ Haskoin.Store.Fleet.Atomic: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Atomic.Bound
+ Haskoin.Store.Fleet.Atomic: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Atomic.Op
+ Haskoin.Store.Fleet.Atomic: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Atomic.Query
+ Haskoin.Store.Fleet.Atomic: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Atomic.Unanswerable
+ Haskoin.Store.Fleet.Atomic: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Atomic.Value
+ Haskoin.Store.Fleet.Atomic: opKey :: Op -> Either ByteString Key
+ Haskoin.Store.Fleet.Atomic: perform :: Op -> Db -> Db
+ Haskoin.Store.Fleet.Atomic: prefetch :: forall (m :: Type -> Type). Monad m => [Query] -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic: queries :: forall (m :: Type -> Type). Monad m => [Query] -> Atomic m [Answer]
+ Haskoin.Store.Fleet.Atomic: query :: forall (m :: Type -> Type). Monad m => Query -> Atomic m Answer
+ Haskoin.Store.Fleet.Atomic: queryKey :: Query -> Key
+ Haskoin.Store.Fleet.Atomic: replay :: Query -> Answer -> [Op] -> Either Unanswerable Answer
+ Haskoin.Store.Fleet.Atomic: runAtomic :: Monad m => Backend m -> Atomic m a -> m (Outcome a)
+ Haskoin.Store.Fleet.Atomic: runPure :: Integer -> (forall (m :: Type -> Type). Monad m => Atomic m a) -> Db -> Either Unanswerable (a, Db)
+ Haskoin.Store.Fleet.Atomic: sismember :: forall (m :: Type -> Type). Monad m => Key -> ByteString -> Atomic m Bool
+ Haskoin.Store.Fleet.Atomic: smembers :: forall (m :: Type -> Type). Monad m => Key -> Atomic m (Set ByteString)
+ Haskoin.Store.Fleet.Atomic: tidy :: [Op] -> [Op]
+ Haskoin.Store.Fleet.Atomic: type Db = Map Key Value
+ Haskoin.Store.Fleet.Atomic: type Key = ByteString
+ Haskoin.Store.Fleet.Atomic: type Score = Double
+ Haskoin.Store.Fleet.Atomic: unguarded :: forall (m :: Type -> Type). Monad m => Atomic m ()
+ Haskoin.Store.Fleet.Atomic: write :: forall (m :: Type -> Type). Monad m => Op -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic: zcard :: forall (m :: Type -> Type). Monad m => Key -> Atomic m Integer
+ Haskoin.Store.Fleet.Atomic: zrangeByScore :: forall (m :: Type -> Type). Monad m => Key -> Bound -> Bound -> Maybe Int -> Atomic m [(ByteString, Score)]
+ Haskoin.Store.Fleet.Atomic: zscore :: forall (m :: Type -> Type). Monad m => Key -> ByteString -> Atomic m (Maybe Score)
+ Haskoin.Store.Fleet.Atomic.Cells: All :: MapOp p k c
+ Haskoin.Store.Fleet.Atomic.Cells: Clear :: CellOp b
+ Haskoin.Store.Fleet.Atomic.Cells: On :: k -> c -> MapOp p k c
+ Haskoin.Store.Fleet.Atomic.Cells: Plus :: Integer -> CellOp b
+ Haskoin.Store.Fleet.Atomic.Cells: Put :: b -> CellOp b
+ Haskoin.Store.Fleet.Atomic.Cells: Rank :: s -> RankOp s
+ Haskoin.Store.Fleet.Atomic.Cells: RankNew :: s -> RankOp s
+ Haskoin.Store.Fleet.Atomic.Cells: Under :: p -> MapOp p k c
+ Haskoin.Store.Fleet.Atomic.Cells: Unrank :: RankOp s
+ Haskoin.Store.Fleet.Atomic.Cells: at :: Eq k => (p -> k -> Bool) -> (c -> Maybe v -> Maybe v) -> k -> MapOp p k c -> Maybe v -> Maybe v
+ Haskoin.Store.Fleet.Atomic.Cells: atAll :: Eq k => (p -> k -> Bool) -> (c -> Maybe v -> Maybe v) -> k -> [MapOp p k c] -> Maybe v -> Maybe v
+ Haskoin.Store.Fleet.Atomic.Cells: cellAfter :: Add b -> CellOp b -> Maybe b -> Maybe b
+ Haskoin.Store.Fleet.Atomic.Cells: cellAfterAll :: Ord k => (p -> k -> Bool) -> (c -> Maybe v -> Maybe v) -> k -> [MapOp p k c] -> Map k v -> Maybe v
+ Haskoin.Store.Fleet.Atomic.Cells: data CellOp b
+ Haskoin.Store.Fleet.Atomic.Cells: data MapOp p k c
+ Haskoin.Store.Fleet.Atomic.Cells: data RankOp s
+ Haskoin.Store.Fleet.Atomic.Cells: isAll :: MapOp p k c -> Bool
+ Haskoin.Store.Fleet.Atomic.Cells: isOn :: MapOp p k c -> Bool
+ Haskoin.Store.Fleet.Atomic.Cells: isUnder :: MapOp p k c -> Bool
+ Haskoin.Store.Fleet.Atomic.Cells: mapAfter :: Ord k => (p -> k -> Bool) -> (c -> Maybe v -> Maybe v) -> MapOp p k c -> Map k v -> Map k v
+ Haskoin.Store.Fleet.Atomic.Cells: onCell :: MapOp p k c -> c
+ Haskoin.Store.Fleet.Atomic.Cells: onKey :: MapOp p k c -> k
+ Haskoin.Store.Fleet.Atomic.Cells: onlyAt :: Eq k => k -> [MapOp p k c] -> [MapOp p k c]
+ Haskoin.Store.Fleet.Atomic.Cells: rankAfter :: RankOp s -> Maybe s -> Maybe s
+ Haskoin.Store.Fleet.Atomic.Cells: reaches :: Eq k => k -> MapOp p k c -> Bool
+ Haskoin.Store.Fleet.Atomic.Cells: selLess :: (p -> k -> Bool) -> Map k v -> p -> k -> ()
+ Haskoin.Store.Fleet.Atomic.Cells: selNone :: Map k v -> k -> ()
+ Haskoin.Store.Fleet.Atomic.Cells: selOther :: Map k v -> k -> Maybe v -> k -> ()
+ Haskoin.Store.Fleet.Atomic.Cells: selSame :: Map k v -> k -> Maybe v -> ()
+ Haskoin.Store.Fleet.Atomic.Cells: skipOthers :: Eq k => (p -> k -> Bool) -> (c -> Maybe v -> Maybe v) -> k -> [MapOp p k c] -> Maybe v -> ()
+ Haskoin.Store.Fleet.Atomic.Cells: skipOthersThere :: Eq k => (p -> k -> Bool) -> k -> [MapOp p k (CellOp b)] -> Bool -> ()
+ Haskoin.Store.Fleet.Atomic.Cells: step :: Ord k => (p -> k -> Bool) -> (c -> Maybe v -> Maybe v) -> k -> MapOp p k c -> Map k v -> Map k v -> ()
+ Haskoin.Store.Fleet.Atomic.Cells: thereAfter :: CellOp b -> Bool -> Bool
+ Haskoin.Store.Fleet.Atomic.Cells: thereAt :: Eq k => (p -> k -> Bool) -> k -> MapOp p k (CellOp b) -> Bool -> Bool
+ Haskoin.Store.Fleet.Atomic.Cells: thereAtAll :: Eq k => (p -> k -> Bool) -> k -> [MapOp p k (CellOp b)] -> Bool -> Bool
+ Haskoin.Store.Fleet.Atomic.Cells: thereAtAllSame :: Eq k => (p -> k -> Bool) -> Add b -> k -> [MapOp p k (CellOp b)] -> Maybe b -> ()
+ Haskoin.Store.Fleet.Atomic.Cells: thereAtStep :: Eq k => (p -> k -> Bool) -> Add b -> k -> MapOp p k (CellOp b) -> Maybe b -> ()
+ Haskoin.Store.Fleet.Atomic.Cells: thereStep :: Add b -> CellOp b -> Maybe b -> ()
+ Haskoin.Store.Fleet.Atomic.Cells: type Add b = Integer -> Maybe b -> b
+ Haskoin.Store.Fleet.Atomic.Cells: underWhat :: MapOp p k c -> p
+ Haskoin.Store.Fleet.Atomic.Keys: At :: !Score -> Bound
+ Haskoin.Store.Fleet.Atomic.Keys: Counts :: Kind
+ Haskoin.Store.Fleet.Atomic.Keys: Group :: Kind
+ Haskoin.Store.Fleet.Atomic.Keys: Hash :: Kind
+ Haskoin.Store.Fleet.Atomic.Keys: MinusInf :: Bound
+ Haskoin.Store.Fleet.Atomic.Keys: Number :: Kind
+ Haskoin.Store.Fleet.Atomic.Keys: PlusInf :: Bound
+ Haskoin.Store.Fleet.Atomic.Keys: Sorted :: Kind
+ Haskoin.Store.Fleet.Atomic.Keys: Stream :: Kind
+ Haskoin.Store.Fleet.Atomic.Keys: Text :: Kind
+ Haskoin.Store.Fleet.Atomic.Keys: ahead :: forall (m :: Type -> Type). Monad m => [Ahead] -> Atomic m Bool
+ Haskoin.Store.Fleet.Atomic.Keys: asking :: K 'Text -> Query
+ Haskoin.Store.Fleet.Atomic.Keys: askingCount :: K 'Counts -> ByteString -> Query
+ Haskoin.Store.Fleet.Atomic.Keys: askingField :: K 'Hash -> ByteString -> Query
+ Haskoin.Store.Fleet.Atomic.Keys: askingMember :: K 'Group -> ByteString -> Query
+ Haskoin.Store.Fleet.Atomic.Keys: askingMembers :: K 'Group -> Query
+ Haskoin.Store.Fleet.Atomic.Keys: askingNumber :: K 'Number -> Query
+ Haskoin.Store.Fleet.Atomic.Keys: askingRange :: K 'Sorted -> Bound -> Bound -> Maybe Int -> Query
+ Haskoin.Store.Fleet.Atomic.Keys: askingScore :: K 'Sorted -> ByteString -> Query
+ Haskoin.Store.Fleet.Atomic.Keys: askingWhether :: forall (kind :: Kind). K kind -> Query
+ Haskoin.Store.Fleet.Atomic.Keys: askingWhetherField :: K 'Hash -> ByteString -> Query
+ Haskoin.Store.Fleet.Atomic.Keys: clock :: forall (m :: Type -> Type). Monad m => Atomic m Integer
+ Haskoin.Store.Fleet.Atomic.Keys: data Ahead
+ Haskoin.Store.Fleet.Atomic.Keys: data Atomic (m :: Type -> Type) a
+ Haskoin.Store.Fleet.Atomic.Keys: data Bound
+ Haskoin.Store.Fleet.Atomic.Keys: data Family (kind :: Kind)
+ Haskoin.Store.Fleet.Atomic.Keys: data K (kind :: Kind)
+ Haskoin.Store.Fleet.Atomic.Keys: data Kind
+ Haskoin.Store.Fleet.Atomic.Keys: data Query
+ Haskoin.Store.Fleet.Atomic.Keys: del :: forall (m :: Type -> Type) (kind :: Kind). Monad m => K kind -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: exists :: forall (m :: Type -> Type) (kind :: Kind). Monad m => K kind -> Atomic m Bool
+ Haskoin.Store.Fleet.Atomic.Keys: family :: forall (kind :: Kind). ByteString -> Family kind
+ Haskoin.Store.Fleet.Atomic.Keys: get :: forall (m :: Type -> Type). Monad m => K 'Text -> Atomic m (Maybe ByteString)
+ Haskoin.Store.Fleet.Atomic.Keys: getNumber :: forall (m :: Type -> Type). Monad m => K 'Number -> Atomic m Integer
+ Haskoin.Store.Fleet.Atomic.Keys: guarded :: forall (kind :: Kind). ByteString -> ByteString -> K kind
+ Haskoin.Store.Fleet.Atomic.Keys: guardedFamily :: forall (kind :: Kind). ByteString -> ByteString -> Family kind
+ Haskoin.Store.Fleet.Atomic.Keys: hdel :: forall (m :: Type -> Type). Monad m => K 'Hash -> ByteString -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: hexists :: forall (m :: Type -> Type). Monad m => K 'Hash -> ByteString -> Atomic m Bool
+ Haskoin.Store.Fleet.Atomic.Keys: hfieldsAbove :: forall (m :: Type -> Type). Monad m => K 'Counts -> Integer -> Atomic m (Set ByteString)
+ Haskoin.Store.Fleet.Atomic.Keys: hget :: forall (m :: Type -> Type). Monad m => K 'Hash -> ByteString -> Atomic m (Maybe ByteString)
+ Haskoin.Store.Fleet.Atomic.Keys: hgetNumber :: forall (m :: Type -> Type). Monad m => K 'Counts -> ByteString -> Atomic m (Maybe Integer)
+ Haskoin.Store.Fleet.Atomic.Keys: hgetall :: forall (m :: Type -> Type). Monad m => K 'Hash -> Atomic m (Map ByteString ByteString)
+ Haskoin.Store.Fleet.Atomic.Keys: hincrBy :: forall (m :: Type -> Type). Monad m => K 'Counts -> ByteString -> Integer -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: hkeys :: forall (m :: Type -> Type). Monad m => K 'Hash -> Atomic m (Set ByteString)
+ Haskoin.Store.Fleet.Atomic.Keys: hset :: forall (m :: Type -> Type). Monad m => K 'Hash -> ByteString -> ByteString -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: hsetNumber :: forall (m :: Type -> Type). Monad m => K 'Counts -> ByteString -> Integer -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: incrBy :: forall (m :: Type -> Type). Monad m => K 'Number -> Integer -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: instance GHC.Classes.Eq (Haskoin.Store.Fleet.Atomic.Keys.K kind)
+ Haskoin.Store.Fleet.Atomic.Keys: instance GHC.Internal.Show.Show (Haskoin.Store.Fleet.Atomic.Keys.K kind)
+ Haskoin.Store.Fleet.Atomic.Keys: keyName :: forall (kind :: Kind). K kind -> ByteString
+ Haskoin.Store.Fleet.Atomic.Keys: named :: forall (kind :: Kind). ByteString -> K kind
+ Haskoin.Store.Fleet.Atomic.Keys: only :: Query -> Ahead
+ Haskoin.Store.Fleet.Atomic.Keys: prefetch :: forall (m :: Type -> Type). Monad m => [Query] -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: sadd :: forall (m :: Type -> Type). Monad m => K 'Group -> ByteString -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: set :: forall (m :: Type -> Type). Monad m => K 'Text -> ByteString -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: setNumber :: forall (m :: Type -> Type). Monad m => K 'Number -> Integer -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: sismember :: forall (m :: Type -> Type). Monad m => K 'Group -> ByteString -> Atomic m Bool
+ Haskoin.Store.Fleet.Atomic.Keys: smembers :: forall (m :: Type -> Type). Monad m => K 'Group -> Atomic m (Set ByteString)
+ Haskoin.Store.Fleet.Atomic.Keys: srem :: forall (m :: Type -> Type). Monad m => K 'Group -> ByteString -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: thenAbove :: K 'Counts -> Integer -> (Set ByteString -> [Ahead]) -> Ahead
+ Haskoin.Store.Fleet.Atomic.Keys: thenField :: K 'Hash -> ByteString -> (Maybe ByteString -> [Ahead]) -> Ahead
+ Haskoin.Store.Fleet.Atomic.Keys: thenMember :: K 'Group -> ByteString -> (Bool -> [Ahead]) -> Ahead
+ Haskoin.Store.Fleet.Atomic.Keys: thenMembers :: K 'Group -> (Set ByteString -> [Ahead]) -> Ahead
+ Haskoin.Store.Fleet.Atomic.Keys: thenText :: K 'Text -> (Maybe ByteString -> [Ahead]) -> Ahead
+ Haskoin.Store.Fleet.Atomic.Keys: type Score = Double
+ Haskoin.Store.Fleet.Atomic.Keys: under :: forall (kind :: Kind). Family kind -> ByteString -> K kind
+ Haskoin.Store.Fleet.Atomic.Keys: unguarded :: forall (m :: Type -> Type). Monad m => Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: wipe :: forall (m :: Type -> Type). Monad m => ByteString -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: xadd :: forall (m :: Type -> Type). Monad m => K 'Stream -> Int -> [(ByteString, ByteString)] -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: zadd :: forall (m :: Type -> Type). Monad m => K 'Sorted -> Score -> ByteString -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: zaddNew :: forall (m :: Type -> Type). Monad m => K 'Sorted -> Score -> ByteString -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: zcard :: forall (m :: Type -> Type). Monad m => K 'Sorted -> Atomic m Integer
+ Haskoin.Store.Fleet.Atomic.Keys: zrangeByScore :: forall (m :: Type -> Type). Monad m => K 'Sorted -> Bound -> Bound -> Maybe Int -> Atomic m [(ByteString, Score)]
+ Haskoin.Store.Fleet.Atomic.Keys: zrem :: forall (m :: Type -> Type). Monad m => K 'Sorted -> ByteString -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: zremRangeByRank :: forall (m :: Type -> Type). Monad m => K 'Sorted -> Integer -> Integer -> Atomic m ()
+ Haskoin.Store.Fleet.Atomic.Keys: zscore :: forall (m :: Type -> Type). Monad m => K 'Sorted -> ByteString -> Atomic m (Maybe Score)
+ Haskoin.Store.Fleet.Atomic.Redis: Attempt :: !Int -> !Int -> !Int -> !Word64 -> !Word64 -> !Word64 -> !Maybe Query -> Attempt
+ Haskoin.Store.Fleet.Atomic.Redis: Bytes' :: !ByteString -> Told
+ Haskoin.Store.Fleet.Atomic.Redis: Faulty :: !Unanswerable -> Failure
+ Haskoin.Store.Fleet.Atomic.Redis: Listed :: ![Told] -> Told
+ Haskoin.Store.Fleet.Atomic.Redis: None :: Told
+ Haskoin.Store.Fleet.Atomic.Redis: Number :: !Integer -> Told
+ Haskoin.Store.Fleet.Atomic.Redis: Planned :: a -> ![(Query, ByteString)] -> ![Op] -> !Int -> !Word64 -> Planned a
+ Haskoin.Store.Fleet.Atomic.Redis: Unheard :: !String -> Failure
+ Haskoin.Store.Fleet.Atomic.Redis: [answers] :: Attempt -> !Int
+ Haskoin.Store.Fleet.Atomic.Redis: [carrying] :: Attempt -> !Word64
+ Haskoin.Store.Fleet.Atomic.Redis: [changed] :: Attempt -> !Maybe Query
+ Haskoin.Store.Fleet.Atomic.Redis: [guards] :: Planned a -> ![(Query, ByteString)]
+ Haskoin.Store.Fleet.Atomic.Redis: [passes] :: Attempt -> !Int
+ Haskoin.Store.Fleet.Atomic.Redis: [planning] :: Attempt -> !Word64
+ Haskoin.Store.Fleet.Atomic.Redis: [result] :: Planned a -> a
+ Haskoin.Store.Fleet.Atomic.Redis: [rounds] :: Planned a -> !Int
+ Haskoin.Store.Fleet.Atomic.Redis: [waited] :: Planned a -> !Word64
+ Haskoin.Store.Fleet.Atomic.Redis: [waiting] :: Attempt -> !Word64
+ Haskoin.Store.Fleet.Atomic.Redis: [writes] :: Planned a -> ![Op]
+ Haskoin.Store.Fleet.Atomic.Redis: [written] :: Attempt -> !Int
+ Haskoin.Store.Fleet.Atomic.Redis: asked :: Query -> [ByteString]
+ Haskoin.Store.Fleet.Atomic.Redis: atomicScript :: Script
+ Haskoin.Store.Fleet.Atomic.Redis: carry :: Connection -> Planned a -> IO (Either Query ())
+ Haskoin.Store.Fleet.Atomic.Redis: command :: Op -> [ByteString]
+ Haskoin.Store.Fleet.Atomic.Redis: commit :: Connection -> Planned a -> IO Bool
+ Haskoin.Store.Fleet.Atomic.Redis: data Attempt
+ Haskoin.Store.Fleet.Atomic.Redis: data Failure
+ Haskoin.Store.Fleet.Atomic.Redis: data Planned a
+ Haskoin.Store.Fleet.Atomic.Redis: data Told
+ Haskoin.Store.Fleet.Atomic.Redis: insist :: Connection -> (forall (m :: Type -> Type). Monad m => Atomic m a) -> IO a
+ Haskoin.Store.Fleet.Atomic.Redis: instance GHC.Classes.Eq Haskoin.Store.Fleet.Atomic.Redis.Told
+ Haskoin.Store.Fleet.Atomic.Redis: instance GHC.Internal.Exception.Type.Exception Haskoin.Store.Fleet.Atomic.Redis.Failure
+ Haskoin.Store.Fleet.Atomic.Redis: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Atomic.Redis.Attempt
+ Haskoin.Store.Fleet.Atomic.Redis: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Atomic.Redis.Failure
+ Haskoin.Store.Fleet.Atomic.Redis: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Atomic.Redis.Told
+ Haskoin.Store.Fleet.Atomic.Redis: plan :: Connection -> (forall (m :: Type -> Type). Monad m => Atomic m a) -> IO (Planned a)
+ Haskoin.Store.Fleet.Atomic.Redis: readAnswer :: Query -> ByteString -> Either String Answer
+ Haskoin.Store.Fleet.Atomic.Redis: told :: ByteString -> Either String Told
+ Haskoin.Store.Fleet.Atomic.Redis: transact :: Connection -> Int -> (forall (m :: Type -> Type). Monad m => Atomic m a) -> IO (Maybe a)
+ Haskoin.Store.Fleet.Atomic.Redis: transactTelling :: Connection -> Int -> (Attempt -> IO ()) -> (forall (m :: Type -> Type). Monad m => Atomic m a) -> IO (Maybe a)
+ Haskoin.Store.Fleet.Member: OfferCost :: !Word64 -> !Word64 -> !Word64 -> !Word64 -> !Word64 -> !Word64 -> OfferCost
+ Haskoin.Store.Fleet.Member: Unreadable :: Way
+ Haskoin.Store.Fleet.Member: [askedBlock] :: OfferCost -> !Word64
+ Haskoin.Store.Fleet.Member: [decided] :: OfferCost -> !Word64
+ Haskoin.Store.Fleet.Member: [judged] :: OfferCost -> !Word64
+ Haskoin.Store.Fleet.Member: [newBest] :: Member -> !TVar Bool
+ Haskoin.Store.Fleet.Member: [owed] :: Member -> !TVar Bool
+ Haskoin.Store.Fleet.Member: [readDb] :: OfferCost -> !Word64
+ Haskoin.Store.Fleet.Member: [readPool] :: OfferCost -> !Word64
+ Haskoin.Store.Fleet.Member: [readUnspent] :: OfferCost -> !Word64
+ Haskoin.Store.Fleet.Member: [refused] :: Member -> !TVar Int
+ Haskoin.Store.Fleet.Member: clearLeaving :: Member -> IO ()
+ Haskoin.Store.Fleet.Member: data OfferCost
+ Haskoin.Store.Fleet.Member: instance GHC.Classes.Eq Haskoin.Store.Fleet.Member.OfferCost
+ Haskoin.Store.Fleet.Member: instance GHC.Internal.Base.Monoid Haskoin.Store.Fleet.Member.OfferCost
+ Haskoin.Store.Fleet.Member: instance GHC.Internal.Base.Semigroup Haskoin.Store.Fleet.Member.OfferCost
+ Haskoin.Store.Fleet.Member: instance GHC.Internal.Exception.Type.Exception Haskoin.Store.Fleet.Member.NotBuilt
+ Haskoin.Store.Fleet.Member: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Member.NotBuilt
+ Haskoin.Store.Fleet.Member: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Member.OfferCost
+ Haskoin.Store.Fleet.Member: memberOffer :: Member -> UnixTime -> Tx -> IO (Verdict TxHash)
+ Haskoin.Store.Fleet.Member: memberOfferTimed :: Member -> Bool -> UnixTime -> Tx -> IO (Verdict TxHash, OfferCost)
+ Haskoin.Store.Fleet.Member: memberSettled :: Member -> [TxHash] -> IO (Maybe [Bool])
+ Haskoin.Store.Fleet.Member: setHealthy :: Member -> Bool -> STM ()
+ Haskoin.Store.Fleet.Pool: CategoryPool :: ![(Word64, t)] -> ![(Word64, o)] -> !Word64 -> !Word64 -> CategoryPool t o
+ Haskoin.Store.Fleet.Pool: Makes :: !TokenOut a o c -> Entry a o c
+ Haskoin.Store.Fleet.Pool: TokenOut :: !Maybe a -> !o -> !c -> !Word64 -> !Bool -> TokenOut a o c
+ Haskoin.Store.Fleet.Pool: TokenTotals :: !Word64 -> !Word64 -> !Word64 -> !Word64 -> !Word64 -> !Word64 -> !Word64 -> !Word64 -> TokenTotals
+ Haskoin.Store.Fleet.Pool: Uses :: !TokenOut a o c -> Entry a o c
+ Haskoin.Store.Fleet.Pool: [amount] :: TokenOut a o c -> !Word64
+ Haskoin.Store.Fleet.Pool: [category] :: TokenOut a o c -> !c
+ Haskoin.Store.Fleet.Pool: [freeNfts] :: TokenTotals -> !Word64
+ Haskoin.Store.Fleet.Pool: [freeOutputs] :: TokenTotals -> !Word64
+ Haskoin.Store.Fleet.Pool: [free] :: CategoryPool t o -> !Word64
+ Haskoin.Store.Fleet.Pool: [nft] :: TokenOut a o c -> !Bool
+ Haskoin.Store.Fleet.Pool: [output] :: TokenOut a o c -> !o
+ Haskoin.Store.Fleet.Pool: [outs] :: CategoryPool t o -> ![(Word64, o)]
+ Haskoin.Store.Fleet.Pool: [owner] :: TokenOut a o c -> !Maybe a
+ Haskoin.Store.Fleet.Pool: [received] :: TokenTotals -> !Word64
+ Haskoin.Store.Fleet.Pool: [spentNfts] :: TokenTotals -> !Word64
+ Haskoin.Store.Fleet.Pool: [spentOutputs] :: TokenTotals -> !Word64
+ Haskoin.Store.Fleet.Pool: categories :: (Ord t, Ord o, Ord c) => (o -> t) -> [(t, Word64, [Entry a o c])] -> Map c (CategoryPool t o)
+ Haskoin.Store.Fleet.Pool: data CategoryPool t o
+ Haskoin.Store.Fleet.Pool: data TokenOut a o c
+ Haskoin.Store.Fleet.Pool: data TokenTotals
+ Haskoin.Store.Fleet.Pool: instance (GHC.Classes.Eq a, GHC.Classes.Eq o, GHC.Classes.Eq c) => GHC.Classes.Eq (Haskoin.Store.Fleet.Pool.Entry a o c)
+ Haskoin.Store.Fleet.Pool: instance (GHC.Classes.Eq a, GHC.Classes.Eq o, GHC.Classes.Eq c) => GHC.Classes.Eq (Haskoin.Store.Fleet.Pool.TokenOut a o c)
+ Haskoin.Store.Fleet.Pool: instance (GHC.Classes.Eq t, GHC.Classes.Eq o) => GHC.Classes.Eq (Haskoin.Store.Fleet.Pool.CategoryPool t o)
+ Haskoin.Store.Fleet.Pool: instance (GHC.Internal.Show.Show a, GHC.Internal.Show.Show o, GHC.Internal.Show.Show c) => GHC.Internal.Show.Show (Haskoin.Store.Fleet.Pool.Entry a o c)
+ Haskoin.Store.Fleet.Pool: instance (GHC.Internal.Show.Show a, GHC.Internal.Show.Show o, GHC.Internal.Show.Show c) => GHC.Internal.Show.Show (Haskoin.Store.Fleet.Pool.TokenOut a o c)
+ Haskoin.Store.Fleet.Pool: instance (GHC.Internal.Show.Show t, GHC.Internal.Show.Show o) => GHC.Internal.Show.Show (Haskoin.Store.Fleet.Pool.CategoryPool t o)
+ Haskoin.Store.Fleet.Pool: instance GHC.Classes.Eq Haskoin.Store.Fleet.Pool.TokenTotals
+ Haskoin.Store.Fleet.Pool: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Pool.TokenTotals
+ Haskoin.Store.Fleet.Pool: tokenTotals :: (Ord a, Ord t, Ord o, Ord c) => (o -> t) -> [(t, Word64, [Entry a o c])] -> Map (c, a) TokenTotals
+ Haskoin.Store.Fleet.Pool.Decide: AloneNotKnowing :: !ByteString -> How
+ Haskoin.Store.Fleet.Pool.Decide: AtOnce :: !PoolChange -> How
+ Haskoin.Store.Fleet.Pool.Decide: Changing :: !PoolChange -> How
+ Haskoin.Store.Fleet.Pool.Decide: Keys :: !ByteString -> !Int -> !K 'Text -> !K 'Number -> !K 'Number -> !K 'Counts -> !K 'Hash -> !K 'Stream -> !K 'Number -> !K 'Hash -> !K 'Hash -> !K 'Hash -> !Family 'Group -> !K 'Hash -> !K 'Sorted -> !K 'Sorted -> !Family 'Sorted -> !Family 'Sorted -> !Family 'Hash -> !Family 'Hash -> !Family 'Counts -> !Family 'Counts -> !Family 'Group -> !Family 'Group -> !Family 'Sorted -> !Family 'Sorted -> !Family 'Hash -> !Family 'Counts -> !K 'Hash -> !Family 'Group -> !K 'Sorted -> !K 'Hash -> !Family 'Group -> !K 'Sorted -> !K 'Hash -> !K 'Text -> !K 'Text -> !K 'Number -> !K 'Group -> !Family 'Group -> !ByteString -> Keys
+ Haskoin.Store.Fleet.Pool.Decide: TooLong :: How
+ Haskoin.Store.Fleet.Pool.Decide: [acat] :: Keys -> !Family 'Group
+ Haskoin.Store.Fleet.Pool.Decide: [aout] :: Keys -> !Family 'Sorted
+ Haskoin.Store.Fleet.Pool.Decide: [aspent] :: Keys -> !Family 'Hash
+ Haskoin.Store.Fleet.Pool.Decide: [asum] :: Keys -> !Family 'Counts
+ Haskoin.Store.Fleet.Pool.Decide: [atx] :: Keys -> !Family 'Sorted
+ Haskoin.Store.Fleet.Pool.Decide: [aval] :: Keys -> !Family 'Hash
+ Haskoin.Store.Fleet.Pool.Decide: [beat] :: Keys -> !K 'Number
+ Haskoin.Store.Fleet.Pool.Decide: [body] :: Keys -> !K 'Hash
+ Haskoin.Store.Fleet.Pool.Decide: [chold] :: Keys -> !Family 'Group
+ Haskoin.Store.Fleet.Pool.Decide: [cout] :: Keys -> !Family 'Sorted
+ Haskoin.Store.Fleet.Pool.Decide: [csum] :: Keys -> !Family 'Counts
+ Haskoin.Store.Fleet.Pool.Decide: [ctx] :: Keys -> !Family 'Sorted
+ Haskoin.Store.Fleet.Pool.Decide: [cval] :: Keys -> !Family 'Hash
+ Haskoin.Store.Fleet.Pool.Decide: [entries] :: Keys -> !K 'Hash
+ Haskoin.Store.Fleet.Pool.Decide: [entry] :: Keys -> !ByteString
+ Haskoin.Store.Fleet.Pool.Decide: [events] :: Keys -> !K 'Stream
+ Haskoin.Store.Fleet.Pool.Decide: [ids] :: Keys -> !K 'Sorted
+ Haskoin.Store.Fleet.Pool.Decide: [kids] :: Keys -> !Family 'Group
+ Haskoin.Store.Fleet.Pool.Decide: [lease] :: Keys -> !K 'Counts
+ Haskoin.Store.Fleet.Pool.Decide: [leaving] :: Keys -> !K 'Hash
+ Haskoin.Store.Fleet.Pool.Decide: [lost] :: Keys -> !K 'Hash
+ Haskoin.Store.Fleet.Pool.Decide: [lostat] :: Keys -> !K 'Sorted
+ Haskoin.Store.Fleet.Pool.Decide: [lostby] :: Keys -> !Family 'Group
+ Haskoin.Store.Fleet.Pool.Decide: [marked] :: Keys -> !K 'Group
+ Haskoin.Store.Fleet.Pool.Decide: [moves] :: Keys -> !K 'Number
+ Haskoin.Store.Fleet.Pool.Decide: [moving] :: Keys -> !K 'Text
+ Haskoin.Store.Fleet.Pool.Decide: [prefix] :: Keys -> !ByteString
+ Haskoin.Store.Fleet.Pool.Decide: [recent] :: Keys -> !K 'Hash
+ Haskoin.Store.Fleet.Pool.Decide: [rep] :: Keys -> !K 'Hash
+ Haskoin.Store.Fleet.Pool.Decide: [repat] :: Keys -> !K 'Sorted
+ Haskoin.Store.Fleet.Pool.Decide: [repby] :: Keys -> !Family 'Group
+ Haskoin.Store.Fleet.Pool.Decide: [restarts] :: Keys -> !K 'Number
+ Haskoin.Store.Fleet.Pool.Decide: [spender] :: Keys -> !K 'Hash
+ Haskoin.Store.Fleet.Pool.Decide: [spends] :: Keys -> !K 'Hash
+ Haskoin.Store.Fleet.Pool.Decide: [time] :: Keys -> !K 'Sorted
+ Haskoin.Store.Fleet.Pool.Decide: [tip] :: Keys -> !K 'Text
+ Haskoin.Store.Fleet.Pool.Decide: [tsize] :: Keys -> !Int
+ Haskoin.Store.Fleet.Pool.Decide: [tsum] :: Keys -> !Family 'Counts
+ Haskoin.Store.Fleet.Pool.Decide: [watchers] :: Keys -> !Family 'Group
+ Haskoin.Store.Fleet.Pool.Decide: [xtip] :: Keys -> !K 'Text
+ Haskoin.Store.Fleet.Pool.Decide: [xver] :: Keys -> !K 'Number
+ Haskoin.Store.Fleet.Pool.Decide: advance :: forall (m :: Type -> Type). Monad m => Keys -> Maybe ByteString -> ByteString -> Maybe Integer -> Int -> How -> [ByteString] -> ByteString -> Atomic m Moved
+ Haskoin.Store.Fleet.Pool.Decide: data How
+ Haskoin.Store.Fleet.Pool.Decide: data Keys
+ Haskoin.Store.Fleet.Pool.Decide: entryKey :: forall (kind :: Kind). Keys -> ByteString -> K kind
+ Haskoin.Store.Fleet.Pool.Decide: entryMeta :: Keys -> ByteString -> K 'Counts
+ Haskoin.Store.Fleet.Pool.Decide: entryOuts :: Keys -> ByteString -> K 'Sorted
+ Haskoin.Store.Fleet.Pool.Decide: entryOval :: Keys -> ByteString -> K 'Hash
+ Haskoin.Store.Fleet.Pool.Decide: entryTxs :: Keys -> ByteString -> K 'Sorted
+ Haskoin.Store.Fleet.Pool.Decide: expire :: forall (m :: Type -> Type). Monad m => Keys -> Integer -> Int -> Atomic m [ByteString]
+ Haskoin.Store.Fleet.Pool.Decide: floorHeld :: forall (m :: Type -> Type). Monad m => Keys -> Atomic m Bool
+ Haskoin.Store.Fleet.Pool.Decide: leavingHeld :: forall (m :: Type -> Type). Monad m => Keys -> Atomic m Bool
+ Haskoin.Store.Fleet.Pool.Decide: offer :: forall (m :: Type -> Type). Monad m => Keys -> Maybe ByteString -> [Bool] -> [ByteString] -> PoolTx -> Atomic m Offered
+ Haskoin.Store.Fleet.Pool.Decide: poolKeys :: ByteString -> Int -> Keys
+ Haskoin.Store.Fleet.Pool.Decide: takeOut :: forall (m :: Type -> Type). Monad m => Keys -> [ByteString] -> Atomic m Int
+ Haskoin.Store.Fleet.Pool.Decide: withdraw :: forall (m :: Type -> Type). Monad m => Keys -> [ByteString] -> Atomic m [ByteString]
+ Haskoin.Store.Fleet.Pool.Order: Core :: Map t [o] -> Map o t -> Map t (Set t) -> Core t o
+ Haskoin.Store.Fleet.Pool.Order: anyOrder :: (Ord t, Ord o) => t -> t -> Core t o -> (Core t o, Core t o)
+ Haskoin.Store.Fleet.Pool.Order: data Core t o
+ Haskoin.Store.Fleet.Pool.Order: removeCore :: (Ord t, Ord o) => t -> Core t o -> Core t o
+ Haskoin.Store.Fleet.Pool.Types: Conflict :: ![ByteString] -> Offered
+ Haskoin.Store.Fleet.Pool.Types: Known :: Offered
+ Haskoin.Store.Fleet.Pool.Types: Late :: Offered
+ Haskoin.Store.Fleet.Pool.Types: Leaving :: Moved
+ Haskoin.Store.Fleet.Pool.Types: MovedTo :: !ByteString -> Moved
+ Haskoin.Store.Fleet.Pool.Types: Orphan :: ![ByteString] -> Offered
+ Haskoin.Store.Fleet.Pool.Types: PoolChange :: ![PoolTx] -> ![ByteString] -> ![ByteString] -> ![ByteString] -> !Maybe Word32 -> ![ByteString] -> PoolChange
+ Haskoin.Store.Fleet.Pool.Types: PoolMakes :: !PoolTokenOut -> PoolEntry
+ Haskoin.Store.Fleet.Pool.Types: PoolPays :: !ByteString -> !ByteString -> !Word64 -> !ByteString -> PoolEntry
+ Haskoin.Store.Fleet.Pool.Types: PoolSpends :: !ByteString -> !ByteString -> !Word64 -> PoolEntry
+ Haskoin.Store.Fleet.Pool.Types: PoolTokenOut :: !Maybe ByteString -> !ByteString -> !ByteString -> !Word64 -> !Bool -> !Maybe (Word64, ByteString) -> PoolTokenOut
+ Haskoin.Store.Fleet.Pool.Types: PoolTouches :: !ByteString -> PoolEntry
+ Haskoin.Store.Fleet.Pool.Types: PoolTx :: !ByteString -> !Word64 -> ![ByteString] -> !ByteString -> ![PoolEntry] -> PoolTx
+ Haskoin.Store.Fleet.Pool.Types: PoolUses :: !PoolTokenOut -> PoolEntry
+ Haskoin.Store.Fleet.Pool.Types: Raced :: Moved
+ Haskoin.Store.Fleet.Pool.Types: Stays :: Moved
+ Haskoin.Store.Fleet.Pool.Types: Taken :: Offered
+ Haskoin.Store.Fleet.Pool.Types: [address] :: PoolTokenOut -> !Maybe ByteString
+ Haskoin.Store.Fleet.Pool.Types: [amount] :: PoolTokenOut -> !Word64
+ Haskoin.Store.Fleet.Pool.Types: [body] :: PoolTx -> !ByteString
+ Haskoin.Store.Fleet.Pool.Types: [category] :: PoolTokenOut -> !ByteString
+ Haskoin.Store.Fleet.Pool.Types: [coins] :: PoolTokenOut -> !Maybe (Word64, ByteString)
+ Haskoin.Store.Fleet.Pool.Types: [confirmed] :: PoolChange -> ![ByteString]
+ Haskoin.Store.Fleet.Pool.Types: [entries] :: PoolTx -> ![PoolEntry]
+ Haskoin.Store.Fleet.Pool.Types: [gone] :: PoolChange -> ![ByteString]
+ Haskoin.Store.Fleet.Pool.Types: [height] :: PoolChange -> !Maybe Word32
+ Haskoin.Store.Fleet.Pool.Types: [inputs] :: PoolTx -> ![ByteString]
+ Haskoin.Store.Fleet.Pool.Types: [lost] :: PoolChange -> ![ByteString]
+ Haskoin.Store.Fleet.Pool.Types: [nft] :: PoolTokenOut -> !Bool
+ Haskoin.Store.Fleet.Pool.Types: [output] :: PoolTokenOut -> !ByteString
+ Haskoin.Store.Fleet.Pool.Types: [returned] :: PoolChange -> ![PoolTx]
+ Haskoin.Store.Fleet.Pool.Types: [spent] :: PoolChange -> ![ByteString]
+ Haskoin.Store.Fleet.Pool.Types: [time] :: PoolTx -> !Word64
+ Haskoin.Store.Fleet.Pool.Types: [txid] :: PoolTx -> !ByteString
+ Haskoin.Store.Fleet.Pool.Types: data Moved
+ Haskoin.Store.Fleet.Pool.Types: data Offered
+ Haskoin.Store.Fleet.Pool.Types: data PoolChange
+ Haskoin.Store.Fleet.Pool.Types: data PoolEntry
+ Haskoin.Store.Fleet.Pool.Types: data PoolTokenOut
+ Haskoin.Store.Fleet.Pool.Types: data PoolTx
+ Haskoin.Store.Fleet.Pool.Types: instance GHC.Classes.Eq Haskoin.Store.Fleet.Pool.Types.Moved
+ Haskoin.Store.Fleet.Pool.Types: instance GHC.Classes.Eq Haskoin.Store.Fleet.Pool.Types.Offered
+ Haskoin.Store.Fleet.Pool.Types: instance GHC.Classes.Eq Haskoin.Store.Fleet.Pool.Types.PoolChange
+ Haskoin.Store.Fleet.Pool.Types: instance GHC.Classes.Eq Haskoin.Store.Fleet.Pool.Types.PoolEntry
+ Haskoin.Store.Fleet.Pool.Types: instance GHC.Classes.Eq Haskoin.Store.Fleet.Pool.Types.PoolTokenOut
+ Haskoin.Store.Fleet.Pool.Types: instance GHC.Classes.Eq Haskoin.Store.Fleet.Pool.Types.PoolTx
+ Haskoin.Store.Fleet.Pool.Types: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Pool.Types.Moved
+ Haskoin.Store.Fleet.Pool.Types: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Pool.Types.Offered
+ Haskoin.Store.Fleet.Pool.Types: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Pool.Types.PoolChange
+ Haskoin.Store.Fleet.Pool.Types: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Pool.Types.PoolEntry
+ Haskoin.Store.Fleet.Pool.Types: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Pool.Types.PoolTokenOut
+ Haskoin.Store.Fleet.Pool.Types: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.Pool.Types.PoolTx
+ Haskoin.Store.Fleet.Redis: Attempt :: !Int -> !Int -> !Int -> !Word64 -> !Word64 -> !Word64 -> !Maybe Query -> Attempt
+ Haskoin.Store.Fleet.Redis: Leaving :: Moved
+ Haskoin.Store.Fleet.Redis: PoolMakes :: !PoolTokenOut -> PoolEntry
+ Haskoin.Store.Fleet.Redis: PoolTokenOut :: !Maybe ByteString -> !ByteString -> !ByteString -> !Word64 -> !Bool -> !Maybe (Word64, ByteString) -> PoolTokenOut
+ Haskoin.Store.Fleet.Redis: PoolUses :: !PoolTokenOut -> PoolEntry
+ Haskoin.Store.Fleet.Redis: [address] :: PoolTokenOut -> !Maybe ByteString
+ Haskoin.Store.Fleet.Redis: [amount] :: PoolTokenOut -> !Word64
+ Haskoin.Store.Fleet.Redis: [answers] :: Attempt -> !Int
+ Haskoin.Store.Fleet.Redis: [carrying] :: Attempt -> !Word64
+ Haskoin.Store.Fleet.Redis: [category] :: PoolTokenOut -> !ByteString
+ Haskoin.Store.Fleet.Redis: [changed] :: Attempt -> !Maybe Query
+ Haskoin.Store.Fleet.Redis: [coins] :: PoolTokenOut -> !Maybe (Word64, ByteString)
+ Haskoin.Store.Fleet.Redis: [nft] :: PoolTokenOut -> !Bool
+ Haskoin.Store.Fleet.Redis: [output] :: PoolTokenOut -> !ByteString
+ Haskoin.Store.Fleet.Redis: [passes] :: Attempt -> !Int
+ Haskoin.Store.Fleet.Redis: [planning] :: Attempt -> !Word64
+ Haskoin.Store.Fleet.Redis: [waiting] :: Attempt -> !Word64
+ Haskoin.Store.Fleet.Redis: [written] :: Attempt -> !Int
+ Haskoin.Store.Fleet.Redis: data Attempt
+ Haskoin.Store.Fleet.Redis: data PoolTokenOut
+ Haskoin.Store.Fleet.Redis: fleetCommitTelling :: (Attempt -> IO ()) -> Connection -> FleetKeys -> Int -> Maybe Time -> ByteString -> Maybe ByteString -> ByteString -> Maybe PoolChange -> [ByteString] -> ByteString -> IO Moved
+ Haskoin.Store.Fleet.Redis: fleetSettled :: Connection -> FleetKeys -> [ByteString] -> IO [Bool]
+ Haskoin.Store.Fleet.Redis: poolExpire :: Connection -> FleetKeys -> Int -> Integer -> Int -> IO [ByteString]
+ Haskoin.Store.Fleet.Redis: poolLeaving :: Connection -> FleetKeys -> IO [ByteString]
+ Haskoin.Store.Fleet.Redis: poolTakeOut :: Connection -> FleetKeys -> Int -> [ByteString] -> IO Int
+ Haskoin.Store.Fleet.Script: data Script
+ Haskoin.Store.Fleet.Script: evalScript :: RedisResult a => Script -> [ByteString] -> [ByteString] -> Redis (Either Reply a)
+ Haskoin.Store.Fleet.Script: script :: ByteString -> Script
+ Haskoin.Store.Fleet.XPub: cacheBeat :: Connection -> FleetKeys -> ByteString -> IO Bool
+ Haskoin.Store.Fleet.XPub.Decide: Addition :: !ByteString -> !ByteString -> !ByteString -> ![(ByteString, Score)] -> ![Row] -> Addition
+ Haskoin.Store.Fleet.XPub.Decide: BeganMove :: Began
+ Haskoin.Store.Fleet.XPub.Decide: Keys :: !K 'Text -> !K 'Number -> !K 'Number -> !K 'Text -> !K 'Sorted -> !K 'Number -> !K 'Number -> !Family 'Group -> !Keys -> !K 'Text -> !K 'Number -> !K 'Group -> !Family 'Sorted -> !Family 'Sorted -> !Family 'Hash -> Keys
+ Haskoin.Store.Fleet.XPub.Decide: OtherMoving :: Began
+ Haskoin.Store.Fleet.XPub.Decide: Piece :: !ByteString -> !ByteString -> ![ByteString] -> ![(ByteString, Score)] -> ![ByteString] -> ![Row] -> Piece
+ Haskoin.Store.Fleet.XPub.Decide: StepAdded :: Step
+ Haskoin.Store.Fleet.XPub.Decide: StepBehind :: Step
+ Haskoin.Store.Fleet.XPub.Decide: StepBusy :: Step
+ Haskoin.Store.Fleet.XPub.Decide: StepChanged :: Step
+ Haskoin.Store.Fleet.XPub.Decide: StepRaced :: Step
+ Haskoin.Store.Fleet.XPub.Decide: TipElsewhere :: Began
+ Haskoin.Store.Fleet.XPub.Decide: [abandoned] :: Piece -> ![ByteString]
+ Haskoin.Store.Fleet.XPub.Decide: [added] :: Piece -> ![(ByteString, Score)]
+ Haskoin.Store.Fleet.XPub.Decide: [address] :: Piece -> !ByteString
+ Haskoin.Store.Fleet.XPub.Decide: [addrs] :: Keys -> !K 'Number
+ Haskoin.Store.Fleet.XPub.Decide: [aout] :: Keys -> !Family 'Sorted
+ Haskoin.Store.Fleet.XPub.Decide: [atx] :: Keys -> !Family 'Sorted
+ Haskoin.Store.Fleet.XPub.Decide: [aval] :: Keys -> !Family 'Hash
+ Haskoin.Store.Fleet.XPub.Decide: [balance] :: Piece -> !ByteString
+ Haskoin.Store.Fleet.XPub.Decide: [beat] :: Keys -> !K 'Number
+ Haskoin.Store.Fleet.XPub.Decide: [fleet] :: Keys -> !K 'Text
+ Haskoin.Store.Fleet.XPub.Decide: [gone] :: Piece -> ![ByteString]
+ Haskoin.Store.Fleet.XPub.Decide: [level] :: Keys -> !K 'Number
+ Haskoin.Store.Fleet.XPub.Decide: [marked] :: Keys -> !K 'Group
+ Haskoin.Store.Fleet.XPub.Decide: [moves] :: Keys -> !K 'Number
+ Haskoin.Store.Fleet.XPub.Decide: [moving] :: Keys -> !K 'Text
+ Haskoin.Store.Fleet.XPub.Decide: [outs] :: Addition -> ![Row]
+ Haskoin.Store.Fleet.XPub.Decide: [path] :: Addition -> !ByteString
+ Haskoin.Store.Fleet.XPub.Decide: [place] :: Keys -> !K 'Text
+ Haskoin.Store.Fleet.XPub.Decide: [pool] :: Keys -> !Keys
+ Haskoin.Store.Fleet.XPub.Decide: [prio] :: Keys -> !K 'Sorted
+ Haskoin.Store.Fleet.XPub.Decide: [txs] :: Addition -> ![(ByteString, Score)]
+ Haskoin.Store.Fleet.XPub.Decide: [unspent] :: Piece -> ![Row]
+ Haskoin.Store.Fleet.XPub.Decide: [watchers] :: Keys -> !Family 'Group
+ Haskoin.Store.Fleet.XPub.Decide: [xver] :: Keys -> !K 'Number
+ Haskoin.Store.Fleet.XPub.Decide: abort :: forall (m :: Type -> Type). Monad m => Keys -> ByteString -> Atomic m ()
+ Haskoin.Store.Fleet.XPub.Decide: beat :: forall (m :: Type -> Type). Monad m => Keys -> ByteString -> Atomic m Bool
+ Haskoin.Store.Fleet.XPub.Decide: begin :: forall (m :: Type -> Type). Monad m => Keys -> ByteString -> ByteString -> Atomic m Began
+ Haskoin.Store.Fleet.XPub.Decide: build :: forall (m :: Type -> Type). Monad m => Keys -> ByteString -> ByteString -> (Integer, Integer) -> Integer -> [Addition] -> Atomic m Step
+ Haskoin.Store.Fleet.XPub.Decide: cacheKeys :: ByteString -> Keys
+ Haskoin.Store.Fleet.XPub.Decide: data Addition
+ Haskoin.Store.Fleet.XPub.Decide: data Began
+ Haskoin.Store.Fleet.XPub.Decide: data Keys
+ Haskoin.Store.Fleet.XPub.Decide: data Piece
+ Haskoin.Store.Fleet.XPub.Decide: data Step
+ Haskoin.Store.Fleet.XPub.Decide: drop :: forall (m :: Type -> Type). Monad m => Keys -> ByteString -> Atomic m ()
+ Haskoin.Store.Fleet.XPub.Decide: evict :: forall (m :: Type -> Type). Monad m => Keys -> Int -> Atomic m Integer
+ Haskoin.Store.Fleet.XPub.Decide: instance GHC.Classes.Eq Haskoin.Store.Fleet.XPub.Decide.Began
+ Haskoin.Store.Fleet.XPub.Decide: instance GHC.Classes.Eq Haskoin.Store.Fleet.XPub.Decide.Step
+ Haskoin.Store.Fleet.XPub.Decide: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.XPub.Decide.Began
+ Haskoin.Store.Fleet.XPub.Decide: instance GHC.Internal.Show.Show Haskoin.Store.Fleet.XPub.Decide.Step
+ Haskoin.Store.Fleet.XPub.Decide: piece :: forall (m :: Type -> Type). Monad m => Keys -> ByteString -> ByteString -> [Piece] -> Atomic m Bool
+ Haskoin.Store.Fleet.XPub.Decide: type Row = (ByteString, Score, ByteString, ByteString)
+ Haskoin.Store.Ingest: Again :: Verdict h
+ Haskoin.Store.Ingest: Asked :: !p -> !Tick -> !Set p -> Place p h b
+ Haskoin.Store.Ingest: Body :: !Maybe p -> !h -> !b -> Input p h b
+ Haskoin.Store.Ingest: Check :: !p -> ![h] -> Output p h b
+ Haskoin.Store.Ingest: Checked :: !p -> ![h] -> ![h] -> Input p h b
+ Haskoin.Store.Ingest: Config :: !Int -> !Int -> !Int -> !Int -> !Tick -> !Tick -> !Tick -> !Tick -> !Tick -> !Tick -> Config
+ Haskoin.Store.Ingest: Done :: End
+ Haskoin.Store.Ingest: Doubted :: !Tick -> Hold h
+ Haskoin.Store.Ingest: Emptied :: Input p h b
+ Haskoin.Store.Ingest: Forged :: Verdict h
+ Haskoin.Store.Ingest: GaveUp :: !Reason -> End
+ Haskoin.Store.Ingest: Get :: !p -> ![h] -> Output p h b
+ Haskoin.Store.Ingest: Gone :: !h -> !End -> Output p h b
+ Haskoin.Store.Ingest: Held :: !b -> !Tick -> !Hold h -> Place p h b
+ Haskoin.Store.Ingest: IsForged :: Reason
+ Haskoin.Store.Ingest: Later :: Hold h
+ Haskoin.Store.Ingest: Missing :: !p -> ![h] -> Input p h b
+ Haskoin.Store.Ingest: Named :: !p -> ![h] -> Input p h b
+ Haskoin.Store.Ingest: NoRoom :: Reason
+ Haskoin.Store.Ingest: NodeHasNot :: Reason
+ Haskoin.Store.Ingest: NotVouched :: Reason
+ Haskoin.Store.Ingest: Offer :: !h -> !b -> Output p h b
+ Haskoin.Store.Ingest: Offered :: !h -> !Verdict h -> Input p h b
+ Haskoin.Store.Ingest: Offering :: Hold h
+ Haskoin.Store.Ingest: Orphan :: ![h] -> Verdict h
+ Haskoin.Store.Ingest: Own :: !p -> Input p h b
+ Haskoin.Store.Ingest: PeerDown :: !p -> Input p h b
+ Haskoin.Store.Ingest: PeerGone :: Reason
+ Haskoin.Store.Ingest: PeerUp :: !p -> !Bool -> Input p h b
+ Haskoin.Store.Ingest: PoolSynced :: Standing
+ Haskoin.Store.Ingest: PoolSyncing :: Standing
+ Haskoin.Store.Ingest: PoolUnknown :: Standing
+ Haskoin.Store.Ingest: Ready :: Hold h
+ Haskoin.Store.Ingest: Settled :: Verdict h
+ Haskoin.Store.Ingest: Sweep :: !p -> Output p h b
+ Haskoin.Store.Ingest: Synced :: !Bool -> Input p h b
+ Haskoin.Store.Ingest: Tick :: !Tick -> Input p h b
+ Haskoin.Store.Ingest: Unanswered :: Reason
+ Haskoin.Store.Ingest: Unchecked :: !p -> ![h] -> Input p h b
+ Haskoin.Store.Ingest: Unjudged :: Reason
+ Haskoin.Store.Ingest: Unverified :: Verdict h
+ Haskoin.Store.Ingest: WaitedTooLong :: Reason
+ Haskoin.Store.Ingest: Waiting :: !Set h -> !Tick -> Hold h
+ Haskoin.Store.Ingest: Wanted :: !Map p Tick -> Place p h b
+ Haskoin.Store.Ingest: [heldRoom] :: Config -> !Int
+ Haskoin.Store.Ingest: [maxWindow] :: Config -> !Int
+ Haskoin.Store.Ingest: [minWindow] :: Config -> !Int
+ Haskoin.Store.Ingest: [orphanLife] :: Config -> !Tick
+ Haskoin.Store.Ingest: [patience] :: Config -> !Tick
+ Haskoin.Store.Ingest: [retry] :: Config -> !Tick
+ Haskoin.Store.Ingest: [room] :: Config -> !Int
+ Haskoin.Store.Ingest: [sweepEvery] :: Config -> !Tick
+ Haskoin.Store.Ingest: [sweepFast] :: Config -> !Tick
+ Haskoin.Store.Ingest: [sweepGap] :: Config -> !Tick
+ Haskoin.Store.Ingest: data Config
+ Haskoin.Store.Ingest: data End
+ Haskoin.Store.Ingest: data Hold h
+ Haskoin.Store.Ingest: data Ingest p h b
+ Haskoin.Store.Ingest: data Input p h b
+ Haskoin.Store.Ingest: data Output p h b
+ Haskoin.Store.Ingest: data Place p h b
+ Haskoin.Store.Ingest: data Reason
+ Haskoin.Store.Ingest: data Standing
+ Haskoin.Store.Ingest: data Verdict h
+ Haskoin.Store.Ingest: defaultConfig :: Config
+ Haskoin.Store.Ingest: hasSource :: Ingest p h b -> Bool
+ Haskoin.Store.Ingest: holding :: Ingest p h b -> Int
+ Haskoin.Store.Ingest: idCount :: Ingest p h b -> Int
+ Haskoin.Store.Ingest: ids :: Ingest p h b -> Set h
+ Haskoin.Store.Ingest: instance (GHC.Classes.Eq b, GHC.Classes.Eq p, GHC.Classes.Eq h) => GHC.Classes.Eq (Haskoin.Store.Ingest.Input p h b)
+ Haskoin.Store.Ingest: instance (GHC.Classes.Eq h, GHC.Classes.Eq p, GHC.Classes.Eq b) => GHC.Classes.Eq (Haskoin.Store.Ingest.Ingest p h b)
+ Haskoin.Store.Ingest: instance (GHC.Classes.Ord b, GHC.Classes.Ord p, GHC.Classes.Ord h) => GHC.Classes.Ord (Haskoin.Store.Ingest.Input p h b)
+ Haskoin.Store.Ingest: instance (GHC.Classes.Ord h, GHC.Classes.Ord p, GHC.Classes.Ord b) => GHC.Classes.Ord (Haskoin.Store.Ingest.Ingest p h b)
+ Haskoin.Store.Ingest: instance (GHC.Internal.Show.Show b, GHC.Internal.Show.Show p, GHC.Internal.Show.Show h) => GHC.Internal.Show.Show (Haskoin.Store.Ingest.Input p h b)
+ Haskoin.Store.Ingest: instance (GHC.Internal.Show.Show h, GHC.Internal.Show.Show p, GHC.Internal.Show.Show b) => GHC.Internal.Show.Show (Haskoin.Store.Ingest.Ingest p h b)
+ Haskoin.Store.Ingest: instance GHC.Classes.Eq Haskoin.Store.Ingest.Config
+ Haskoin.Store.Ingest: instance GHC.Classes.Eq Haskoin.Store.Ingest.Standing
+ Haskoin.Store.Ingest: instance GHC.Classes.Eq h => GHC.Classes.Eq (Haskoin.Store.Ingest.Link h)
+ Haskoin.Store.Ingest: instance GHC.Classes.Eq h => GHC.Classes.Eq (Haskoin.Store.Ingest.Verdict h)
+ Haskoin.Store.Ingest: instance GHC.Classes.Ord Haskoin.Store.Ingest.Config
+ Haskoin.Store.Ingest: instance GHC.Classes.Ord Haskoin.Store.Ingest.Standing
+ Haskoin.Store.Ingest: instance GHC.Classes.Ord h => GHC.Classes.Ord (Haskoin.Store.Ingest.Link h)
+ Haskoin.Store.Ingest: instance GHC.Classes.Ord h => GHC.Classes.Ord (Haskoin.Store.Ingest.Verdict h)
+ Haskoin.Store.Ingest: instance GHC.Internal.Show.Show Haskoin.Store.Ingest.Config
+ Haskoin.Store.Ingest: instance GHC.Internal.Show.Show Haskoin.Store.Ingest.Standing
+ Haskoin.Store.Ingest: instance GHC.Internal.Show.Show h => GHC.Internal.Show.Show (Haskoin.Store.Ingest.Link h)
+ Haskoin.Store.Ingest: instance GHC.Internal.Show.Show h => GHC.Internal.Show.Show (Haskoin.Store.Ingest.Verdict h)
+ Haskoin.Store.Ingest: isDirty :: Ingest p h b -> Bool
+ Haskoin.Store.Ingest: pending :: Ingest p h b -> Int
+ Haskoin.Store.Ingest: placeOf :: Ord h => h -> Ingest p h b -> Maybe (Place p h b)
+ Haskoin.Store.Ingest: rebase :: Ord h => Tick -> Ingest p h b -> Ingest p h b
+ Haskoin.Store.Ingest: sourceCount :: Ingest p h b -> Int
+ Haskoin.Store.Ingest: standing :: Ingest p h b -> Standing
+ Haskoin.Store.Ingest: start :: Config -> Tick -> Ingest p h b
+ Haskoin.Store.Ingest: step :: (Ord p, Ord h) => (b -> [h]) -> Input p h b -> Ingest p h b -> (Ingest p h b, [Output p h b])
+ Haskoin.Store.Ingest: type Tick = Int
+ Haskoin.Store.Ingest: vouchedFor :: Ord h => h -> Ingest p h b -> Bool
+ Haskoin.Store.Ingest: wellFormed :: (Ord p, Ord h) => Ingest p h b -> [String]
+ Haskoin.Store.Ingest: windowOf :: Ord p => p -> Ingest p h b -> Maybe Int
+ Haskoin.Store.Ingest.Ledger: Asked :: !p -> !Tick -> !Set p -> Place p h b
+ Haskoin.Store.Ingest.Ledger: Check :: !p -> ![h] -> Output p h b
+ Haskoin.Store.Ingest.Ledger: Done :: End
+ Haskoin.Store.Ingest.Ledger: Doubted :: !Tick -> Hold h
+ Haskoin.Store.Ingest.Ledger: GaveUp :: !Reason -> End
+ Haskoin.Store.Ingest.Ledger: Get :: !p -> ![h] -> Output p h b
+ Haskoin.Store.Ingest.Ledger: Gone :: !h -> !End -> Output p h b
+ Haskoin.Store.Ingest.Ledger: Held :: !b -> !Tick -> !Hold h -> Place p h b
+ Haskoin.Store.Ingest.Ledger: IsForged :: Reason
+ Haskoin.Store.Ingest.Ledger: Later :: Hold h
+ Haskoin.Store.Ingest.Ledger: NoRoom :: Reason
+ Haskoin.Store.Ingest.Ledger: NodeHasNot :: Reason
+ Haskoin.Store.Ingest.Ledger: NotVouched :: Reason
+ Haskoin.Store.Ingest.Ledger: Offer :: !h -> !b -> Output p h b
+ Haskoin.Store.Ingest.Ledger: Offering :: Hold h
+ Haskoin.Store.Ingest.Ledger: PeerGone :: Reason
+ Haskoin.Store.Ingest.Ledger: Ready :: Hold h
+ Haskoin.Store.Ingest.Ledger: Sweep :: !p -> Output p h b
+ Haskoin.Store.Ingest.Ledger: Unanswered :: Reason
+ Haskoin.Store.Ingest.Ledger: Unjudged :: Reason
+ Haskoin.Store.Ingest.Ledger: WaitedTooLong :: Reason
+ Haskoin.Store.Ingest.Ledger: Waiting :: !Set h -> !Tick -> Hold h
+ Haskoin.Store.Ingest.Ledger: Wanted :: !Map p Tick -> Place p h b
+ Haskoin.Store.Ingest.Ledger: data End
+ Haskoin.Store.Ingest.Ledger: data Hold h
+ Haskoin.Store.Ingest.Ledger: data Ledger p h b
+ Haskoin.Store.Ingest.Ledger: data Output p h b
+ Haskoin.Store.Ingest.Ledger: data Place p h b
+ Haskoin.Store.Ingest.Ledger: data Reason
+ Haskoin.Store.Ingest.Ledger: goneOf :: Output p h b -> Set h
+ Haskoin.Store.Ingest.Ledger: hasPlace :: Ord h => h -> Ledger p h b -> Bool
+ Haskoin.Store.Ingest.Ledger: heldOf :: Ledger p h b -> Int
+ Haskoin.Store.Ingest.Ledger: instance (GHC.Classes.Eq h, GHC.Classes.Eq p, GHC.Classes.Eq b) => GHC.Classes.Eq (Haskoin.Store.Ingest.Ledger.Ledger p h b)
+ Haskoin.Store.Ingest.Ledger: instance (GHC.Classes.Eq p, GHC.Classes.Eq b, GHC.Classes.Eq h) => GHC.Classes.Eq (Haskoin.Store.Ingest.Ledger.Output p h b)
+ Haskoin.Store.Ingest.Ledger: instance (GHC.Classes.Eq p, GHC.Classes.Eq b, GHC.Classes.Eq h) => GHC.Classes.Eq (Haskoin.Store.Ingest.Ledger.Place p h b)
+ Haskoin.Store.Ingest.Ledger: instance (GHC.Classes.Ord h, GHC.Classes.Ord p, GHC.Classes.Ord b) => GHC.Classes.Ord (Haskoin.Store.Ingest.Ledger.Ledger p h b)
+ Haskoin.Store.Ingest.Ledger: instance (GHC.Classes.Ord p, GHC.Classes.Ord b, GHC.Classes.Ord h) => GHC.Classes.Ord (Haskoin.Store.Ingest.Ledger.Output p h b)
+ Haskoin.Store.Ingest.Ledger: instance (GHC.Classes.Ord p, GHC.Classes.Ord b, GHC.Classes.Ord h) => GHC.Classes.Ord (Haskoin.Store.Ingest.Ledger.Place p h b)
+ Haskoin.Store.Ingest.Ledger: instance (GHC.Internal.Show.Show h, GHC.Internal.Show.Show p, GHC.Internal.Show.Show b) => GHC.Internal.Show.Show (Haskoin.Store.Ingest.Ledger.Ledger p h b)
+ Haskoin.Store.Ingest.Ledger: instance (GHC.Internal.Show.Show p, GHC.Internal.Show.Show b, GHC.Internal.Show.Show h) => GHC.Internal.Show.Show (Haskoin.Store.Ingest.Ledger.Output p h b)
+ Haskoin.Store.Ingest.Ledger: instance (GHC.Internal.Show.Show p, GHC.Internal.Show.Show b, GHC.Internal.Show.Show h) => GHC.Internal.Show.Show (Haskoin.Store.Ingest.Ledger.Place p h b)
+ Haskoin.Store.Ingest.Ledger: instance GHC.Classes.Eq Haskoin.Store.Ingest.Ledger.End
+ Haskoin.Store.Ingest.Ledger: instance GHC.Classes.Eq Haskoin.Store.Ingest.Ledger.Reason
+ Haskoin.Store.Ingest.Ledger: instance GHC.Classes.Eq h => GHC.Classes.Eq (Haskoin.Store.Ingest.Ledger.Hold h)
+ Haskoin.Store.Ingest.Ledger: instance GHC.Classes.Ord Haskoin.Store.Ingest.Ledger.End
+ Haskoin.Store.Ingest.Ledger: instance GHC.Classes.Ord Haskoin.Store.Ingest.Ledger.Reason
+ Haskoin.Store.Ingest.Ledger: instance GHC.Classes.Ord h => GHC.Classes.Ord (Haskoin.Store.Ingest.Ledger.Hold h)
+ Haskoin.Store.Ingest.Ledger: instance GHC.Internal.Enum.Bounded Haskoin.Store.Ingest.Ledger.Reason
+ Haskoin.Store.Ingest.Ledger: instance GHC.Internal.Enum.Enum Haskoin.Store.Ingest.Ledger.Reason
+ Haskoin.Store.Ingest.Ledger: instance GHC.Internal.Show.Show Haskoin.Store.Ingest.Ledger.End
+ Haskoin.Store.Ingest.Ledger: instance GHC.Internal.Show.Show Haskoin.Store.Ingest.Ledger.Reason
+ Haskoin.Store.Ingest.Ledger: instance GHC.Internal.Show.Show h => GHC.Internal.Show.Show (Haskoin.Store.Ingest.Ledger.Hold h)
+ Haskoin.Store.Ingest.Ledger: leave :: Ord h => h -> End -> Ledger p h b -> [Output p h b] -> (Ledger p h b, [Output p h b])
+ Haskoin.Store.Ingest.Ledger: newLedger :: Int -> Int -> Ledger p h b
+ Haskoin.Store.Ingest.Ledger: placesOf :: Ledger p h b -> Map h (Place p h b)
+ Haskoin.Store.Ingest.Ledger: put :: Ord h => h -> Place p h b -> Ledger p h b -> Maybe (Ledger p h b)
+ Haskoin.Store.Ingest.Ledger: rehold :: Ord h => h -> Hold h -> Ledger p h b -> Ledger p h b
+ Haskoin.Store.Ingest.Ledger: retarget :: Ord h => h -> Place p h b -> Ledger p h b -> Ledger p h b
+ Haskoin.Store.Ingest.Ledger: retime :: (Tick -> Tick) -> Ledger p h b -> Ledger p h b
+ Haskoin.Store.Ingest.Ledger: type Tick = Int
+ Haskoin.Store.Ingest.Run: Feed :: !Text -> !IO [TxHash] -> ![TxHash] -> IO [Maybe Tx] -> Feed
+ Haskoin.Store.Ingest.Run: IngestConfig :: !Network -> !Config -> !Maybe Member -> !IO Bool -> !Peer -> IO Bool -> !Peer -> IO Bool -> !Maybe Stats -> !Logger -> IngestConfig
+ Haskoin.Store.Ingest.Run: IngestState :: !Int -> !Int -> !Int -> !Bool -> !Int -> !Standing -> IngestState
+ Haskoin.Store.Ingest.Run: [bodies] :: Feed -> ![TxHash] -> IO [Maybe Tx]
+ Haskoin.Store.Ingest.Run: [config] :: IngestConfig -> !Config
+ Haskoin.Store.Ingest.Run: [dirty] :: IngestState -> !Bool
+ Haskoin.Store.Ingest.Run: [held] :: IngestState -> !Int
+ Haskoin.Store.Ingest.Run: [inSync] :: IngestConfig -> !IO Bool
+ Haskoin.Store.Ingest.Run: [known] :: IngestState -> !Int
+ Haskoin.Store.Ingest.Run: [label] :: Feed -> !Text
+ Haskoin.Store.Ingest.Run: [logger] :: IngestConfig -> !Logger
+ Haskoin.Store.Ingest.Run: [member] :: IngestConfig -> !Maybe Member
+ Haskoin.Store.Ingest.Run: [names] :: Feed -> !IO [TxHash]
+ Haskoin.Store.Ingest.Run: [net] :: IngestConfig -> !Network
+ Haskoin.Store.Ingest.Run: [own] :: IngestConfig -> !Peer -> IO Bool
+ Haskoin.Store.Ingest.Run: [pending] :: IngestState -> !Int
+ Haskoin.Store.Ingest.Run: [source] :: IngestConfig -> !Peer -> IO Bool
+ Haskoin.Store.Ingest.Run: [sources] :: IngestState -> !Int
+ Haskoin.Store.Ingest.Run: [standing] :: IngestState -> !Standing
+ Haskoin.Store.Ingest.Run: [stats] :: IngestConfig -> !Maybe Stats
+ Haskoin.Store.Ingest.Run: data Feed
+ Haskoin.Store.Ingest.Run: data IngestConfig
+ Haskoin.Store.Ingest.Run: data IngestState
+ Haskoin.Store.Ingest.Run: data Ingester
+ Haskoin.Store.Ingest.Run: ingestEmptiedSTM :: Ingester -> STM ()
+ Haskoin.Store.Ingest.Run: ingestFeed :: Ingester -> Feed -> IO a
+ Haskoin.Store.Ingest.Run: ingestLookSTM :: Ingester -> STM ()
+ Haskoin.Store.Ingest.Run: ingestMissingSTM :: Peer -> [TxHash] -> Ingester -> STM ()
+ Haskoin.Store.Ingest.Run: ingestNamedSTM :: Peer -> [TxHash] -> Ingester -> STM ()
+ Haskoin.Store.Ingest.Run: ingestPeerDownSTM :: Peer -> Ingester -> STM ()
+ Haskoin.Store.Ingest.Run: ingestPeerUpSTM :: Peer -> Ingester -> STM ()
+ Haskoin.Store.Ingest.Run: ingestState :: Ingester -> STM IngestState
+ Haskoin.Store.Ingest.Run: ingestTxSTM :: Peer -> Tx -> Ingester -> STM ()
+ Haskoin.Store.Ingest.Run: instance GHC.Classes.Eq Haskoin.Store.Ingest.Run.IngestState
+ Haskoin.Store.Ingest.Run: instance GHC.Classes.Eq Haskoin.Store.Ingest.Run.Link
+ Haskoin.Store.Ingest.Run: instance GHC.Internal.Show.Show Haskoin.Store.Ingest.Run.IngestState
+ Haskoin.Store.Ingest.Run: withIngest :: IngestConfig -> (Ingester -> IO a) -> IO a
+ Haskoin.Store.Logic: [tokens] :: PreparedTx -> ![Maybe TokenData]
+ Haskoin.Store.Manager: [foreignPeers] :: StoreConfig -> !Bool
+ Haskoin.Store.Manager: [ingest] :: Store -> !Ingester
+ Haskoin.Store.Manager: [nodePeerRpcSocket] :: StoreConfig -> !Maybe FilePath
+ Haskoin.Store.Manager: [nodePeerRpc] :: StoreConfig -> !Maybe String
+ Haskoin.Store.Manager: [nodePeerZmq] :: StoreConfig -> !Maybe String
+ Haskoin.Store.Manager: [peerPermissions] :: StoreConfig -> !Permissions
+ Haskoin.Store.NodePeer: NodePeer :: !Network -> !Session -> !String -> !Maybe ZmqAddress -> !IO Bool -> !Logger -> NodePeer
+ Haskoin.Store.NodePeer: [alone] :: NodePeer -> !IO Bool
+ Haskoin.Store.NodePeer: [logger] :: NodePeer -> !Logger
+ Haskoin.Store.NodePeer: [net] :: NodePeer -> !Network
+ Haskoin.Store.NodePeer: [session] :: NodePeer -> !Session
+ Haskoin.Store.NodePeer: [url] :: NodePeer -> !String
+ Haskoin.Store.NodePeer: [zmq] :: NodePeer -> !Maybe ZmqAddress
+ Haskoin.Store.NodePeer: data NodePeer
+ Haskoin.Store.NodePeer: fresh :: Ord h => Set h -> [h] -> [h]
+ Haskoin.Store.NodePeer: lacksZmq :: Text
+ Haskoin.Store.NodePeer: nodePeerAddress :: SockAddr
+ Haskoin.Store.NodePeer: nodePeerConnect :: NodePeer -> WithConnection
+ Haskoin.Store.NodePeer: nodePeerName :: String
+ Haskoin.Store.NodePeer: pollEvery :: Int
+ Haskoin.Store.NodeRpc: RpcFailure :: String -> RpcFailure
+ Haskoin.Store.NodeRpc: instance GHC.Internal.Exception.Type.Exception Haskoin.Store.NodeRpc.RpcFailure
+ Haskoin.Store.NodeRpc: instance GHC.Internal.Show.Show Haskoin.Store.NodeRpc.RpcFailure
+ Haskoin.Store.NodeRpc: newtype RpcFailure
+ Haskoin.Store.NodeRpc: nodeAnswers :: Session -> String -> [(Text, [Value])] -> IO [Either Value Value]
+ Haskoin.Store.NodeRpc: nodeFeed :: Session -> String -> Feed
+ Haskoin.Store.NodeRpc: nodeOptions :: Options
+ Haskoin.Store.NodeRpc: nodeSession :: Maybe FilePath -> IO Session
+ Haskoin.Store.NodeRpc: unixSocketManager :: FilePath -> ManagerSettings
+ Haskoin.Store.NodeZmq: HeardBlock :: !BlockHash -> Heard
+ Haskoin.Store.NodeZmq: HeardTxs :: ![TxHash] -> Heard
+ Haskoin.Store.NodeZmq: Missed :: Heard
+ Haskoin.Store.NodeZmq: ZmqMessage :: !ByteString -> !ByteString -> !Word32 -> ZmqMessage
+ Haskoin.Store.NodeZmq: ZmqTcp :: !String -> !Int -> ZmqAddress
+ Haskoin.Store.NodeZmq: ZmqUnix :: !FilePath -> ZmqAddress
+ Haskoin.Store.NodeZmq: [body] :: ZmqMessage -> !ByteString
+ Haskoin.Store.NodeZmq: [number] :: ZmqMessage -> !Word32
+ Haskoin.Store.NodeZmq: [topic] :: ZmqMessage -> !ByteString
+ Haskoin.Store.NodeZmq: data Heard
+ Haskoin.Store.NodeZmq: data ZmqAddress
+ Haskoin.Store.NodeZmq: data ZmqMessage
+ Haskoin.Store.NodeZmq: hearNode :: ZmqAddress -> (Heard -> IO ()) -> IO a
+ Haskoin.Store.NodeZmq: instance GHC.Classes.Eq Haskoin.Store.NodeZmq.Heard
+ Haskoin.Store.NodeZmq: instance GHC.Classes.Eq Haskoin.Store.NodeZmq.ZmqAddress
+ Haskoin.Store.NodeZmq: instance GHC.Classes.Eq Haskoin.Store.NodeZmq.ZmqMessage
+ Haskoin.Store.NodeZmq: instance GHC.Internal.Exception.Type.Exception Haskoin.Store.NodeZmq.ZmqError
+ Haskoin.Store.NodeZmq: instance GHC.Internal.Show.Show Haskoin.Store.NodeZmq.Heard
+ Haskoin.Store.NodeZmq: instance GHC.Internal.Show.Show Haskoin.Store.NodeZmq.ZmqAddress
+ Haskoin.Store.NodeZmq: instance GHC.Internal.Show.Show Haskoin.Store.NodeZmq.ZmqError
+ Haskoin.Store.NodeZmq: instance GHC.Internal.Show.Show Haskoin.Store.NodeZmq.ZmqMessage
+ Haskoin.Store.NodeZmq: parseZmqAddress :: String -> Either String ZmqAddress
+ Haskoin.Store.NodeZmq: zmqSubscribe :: ZmqAddress -> [ByteString] -> IO () -> (ZmqMessage -> IO ()) -> IO a
+ Haskoin.Store.Startup: redisConnectInfo :: String -> Either String ConnectInfo
+ Haskoin.Store.Web: [nodeRpcSocket] :: WebConfig -> !Maybe FilePath
+ Haskoin.Store.Web: [nodeZmq] :: WebConfig -> !Maybe String
+ Haskoin.Store.Web: unixSocketManager :: FilePath -> ManagerSettings
+ Haskoin.Store.Web.Publish: Kept :: Delivery
+ Haskoin.Store.Web.Publish: asked :: UTCTime -> TxHash -> HashMap TxHash (UTCTime, [NominalDiffTime]) -> HashMap TxHash (UTCTime, [NominalDiffTime])
- Haskoin.Store: Store :: !PeerMgr -> !Chain -> !BlockStore -> !DatabaseReader -> !Maybe Member -> !Publisher StoreEvent -> !Publisher StoreEvent -> !Network -> !SockAddr -> WithConnection -> !TVar Stall -> Store
+ Haskoin.Store: Store :: !PeerMgr -> !Chain -> !BlockStore -> !Ingester -> !DatabaseReader -> !Maybe Member -> !Publisher StoreEvent -> !Publisher StoreEvent -> !Network -> !SockAddr -> WithConnection -> !TVar DatabaseHealth -> Store
- Haskoin.Store: StoreConfig :: !Int -> ![String] -> !Bool -> !FilePath -> !Network -> !Maybe String -> !Word32 -> !Word32 -> !Int -> !XPubConfig -> !Int -> !Int -> !NominalDiffTime -> !NominalDiffTime -> !NominalDiffTime -> !NominalDiffTime -> !SockAddr -> WithConnection -> !Maybe Stats -> !Bool -> !Maybe Int -> !Maybe Int -> !Maybe Int -> !Maybe Int -> !Maybe Int -> !Logger -> StoreConfig
+ Haskoin.Store: StoreConfig :: !Int -> ![String] -> !Permissions -> !Bool -> !Bool -> !FilePath -> !Network -> !Maybe String -> !Word32 -> !Word32 -> !Int -> !XPubConfig -> !Int -> !Int -> !NominalDiffTime -> !NominalDiffTime -> !NominalDiffTime -> !NominalDiffTime -> !SockAddr -> WithConnection -> !Maybe String -> !Maybe FilePath -> !Maybe String -> !Maybe Stats -> !Bool -> !Maybe Int -> !Maybe Int -> !Maybe Int -> !Maybe Int -> !Maybe Int -> !Logger -> StoreConfig
- Haskoin.Store: StoreRead :: !Network -> IO (Maybe BlockHash) -> (BlockHeight -> IO [BlockHash]) -> (BlockHash -> IO (Maybe BlockData)) -> (TxHash -> IO (Maybe TxData)) -> ([TxHash] -> IO [Maybe TxData]) -> ([TxHash] -> IO [Maybe ByteString]) -> (OutPoint -> IO (Maybe Spender)) -> (Address -> IO (Maybe Balance)) -> (OutPoint -> IO (Maybe Unspent)) -> IO [(UnixTime, TxHash)] -> (Limits -> IO [(UnixTime, TxHash)]) -> ([Address] -> Limits -> IO [TxRef]) -> ([Address] -> Limits -> IO [Unspent]) -> !Word32 -> !Word32 -> (Word64 -> IO [TxData]) -> ([Address] -> IO [Balance]) -> (Address -> Limits -> IO [TxRef]) -> (Address -> Limits -> IO [Unspent]) -> (XPubSpec -> IO [XPubBal]) -> (XPubSpec -> [XPubBal] -> Limits -> IO [XPubUnspent]) -> (XPubSpec -> [XPubBal] -> Limits -> IO [TxRef]) -> (XPubSpec -> [XPubBal] -> IO Word32) -> ([Address] -> IO Word32) -> (TxHash -> IO (Maybe Replaced)) -> StoreRead
+ Haskoin.Store: StoreRead :: !Network -> IO (Maybe BlockHash) -> (BlockHeight -> IO [BlockHash]) -> (BlockHash -> IO (Maybe BlockData)) -> (TxHash -> IO (Maybe TxData)) -> ([TxHash] -> IO [Maybe TxData]) -> ([TxHash] -> IO [Maybe ByteString]) -> (OutPoint -> IO (Maybe Spender)) -> (Address -> IO (Maybe Balance)) -> (OutPoint -> IO (Maybe Unspent)) -> IO [(UnixTime, TxHash)] -> (Limits -> IO [(UnixTime, TxHash)]) -> ([Address] -> Limits -> IO [TxRef]) -> ([Address] -> Limits -> IO [Unspent]) -> !Word32 -> !Word32 -> (Word64 -> IO [TxData]) -> ([Address] -> IO [Balance]) -> (Address -> Limits -> IO [TxRef]) -> (Address -> Limits -> IO [Unspent]) -> (XPubSpec -> IO [XPubBal]) -> (XPubSpec -> [XPubBal] -> Limits -> IO [XPubUnspent]) -> (XPubSpec -> [XPubBal] -> Limits -> IO [TxRef]) -> (XPubSpec -> [XPubBal] -> IO Word32) -> ([Address] -> IO Word32) -> (Address -> IO [TokenBalance]) -> (TxHash -> Limits -> IO [TokenBalance]) -> (TxHash -> Limits -> IO [TxRef]) -> (TxHash -> Limits -> IO [Unspent]) -> (TxHash -> IO (Maybe Replaced)) -> StoreRead
- Haskoin.Store: [writes] :: Store -> !TVar Stall
+ Haskoin.Store: [writes] :: Store -> !TVar DatabaseHealth
- Haskoin.Store.BlockStore: BlockStoreConfig :: !PeerMgr -> !Chain -> !Publisher StoreEvent -> !DatabaseReader -> !Network -> ![String] -> !BlockHash -> IO () -> !UnixTime -> Tx -> IO () -> ![TxHash] -> IO (HashSet TxHash) -> !Int -> !NominalDiffTime -> !NominalDiffTime -> !NominalDiffTime -> !Maybe Stats -> !Logger -> BlockStoreConfig
+ Haskoin.Store.BlockStore: BlockStoreConfig :: !PeerMgr -> !Chain -> !Publisher StoreEvent -> !DatabaseReader -> !Network -> !BlockHash -> IO () -> !Int -> !NominalDiffTime -> !NominalDiffTime -> !NominalDiffTime -> !Maybe Stats -> !Logger -> BlockStoreConfig
- Haskoin.Store.Common: StoreRead :: !Network -> IO (Maybe BlockHash) -> (BlockHeight -> IO [BlockHash]) -> (BlockHash -> IO (Maybe BlockData)) -> (TxHash -> IO (Maybe TxData)) -> ([TxHash] -> IO [Maybe TxData]) -> ([TxHash] -> IO [Maybe ByteString]) -> (OutPoint -> IO (Maybe Spender)) -> (Address -> IO (Maybe Balance)) -> (OutPoint -> IO (Maybe Unspent)) -> IO [(UnixTime, TxHash)] -> (Limits -> IO [(UnixTime, TxHash)]) -> ([Address] -> Limits -> IO [TxRef]) -> ([Address] -> Limits -> IO [Unspent]) -> !Word32 -> !Word32 -> (Word64 -> IO [TxData]) -> ([Address] -> IO [Balance]) -> (Address -> Limits -> IO [TxRef]) -> (Address -> Limits -> IO [Unspent]) -> (XPubSpec -> IO [XPubBal]) -> (XPubSpec -> [XPubBal] -> Limits -> IO [XPubUnspent]) -> (XPubSpec -> [XPubBal] -> Limits -> IO [TxRef]) -> (XPubSpec -> [XPubBal] -> IO Word32) -> ([Address] -> IO Word32) -> (TxHash -> IO (Maybe Replaced)) -> StoreRead
+ Haskoin.Store.Common: StoreRead :: !Network -> IO (Maybe BlockHash) -> (BlockHeight -> IO [BlockHash]) -> (BlockHash -> IO (Maybe BlockData)) -> (TxHash -> IO (Maybe TxData)) -> ([TxHash] -> IO [Maybe TxData]) -> ([TxHash] -> IO [Maybe ByteString]) -> (OutPoint -> IO (Maybe Spender)) -> (Address -> IO (Maybe Balance)) -> (OutPoint -> IO (Maybe Unspent)) -> IO [(UnixTime, TxHash)] -> (Limits -> IO [(UnixTime, TxHash)]) -> ([Address] -> Limits -> IO [TxRef]) -> ([Address] -> Limits -> IO [Unspent]) -> !Word32 -> !Word32 -> (Word64 -> IO [TxData]) -> ([Address] -> IO [Balance]) -> (Address -> Limits -> IO [TxRef]) -> (Address -> Limits -> IO [Unspent]) -> (XPubSpec -> IO [XPubBal]) -> (XPubSpec -> [XPubBal] -> Limits -> IO [XPubUnspent]) -> (XPubSpec -> [XPubBal] -> Limits -> IO [TxRef]) -> (XPubSpec -> [XPubBal] -> IO Word32) -> ([Address] -> IO Word32) -> (Address -> IO [TokenBalance]) -> (TxHash -> Limits -> IO [TokenBalance]) -> (TxHash -> Limits -> IO [TxRef]) -> (TxHash -> Limits -> IO [Unspent]) -> (TxHash -> IO (Maybe Replaced)) -> StoreRead
- Haskoin.Store.Database.Query.Pooled: PoolReads :: ([Address] -> IO [Maybe MemSummary]) -> (Address -> Maybe (UnixTime, TxHash) -> Int -> IO [(UnixTime, TxHash)]) -> (Address -> Maybe (UnixTime, OutPoint) -> Int -> IO [(Unspent, Bool)]) -> (Address -> [OutPoint] -> IO [Bool]) -> ([TxHash] -> IO [(Maybe TxData, IntMap Spender)]) -> ([OutPoint] -> IO [Maybe Spender]) -> (Word32 -> Word32 -> IO [(UnixTime, TxHash)]) -> ((Word32, Word16) -> IO [TxHash]) -> (TxHash -> IO (Maybe Replaced)) -> PoolReads
+ Haskoin.Store.Database.Query.Pooled: PoolReads :: ([Address] -> IO [Maybe MemSummary]) -> (Address -> Maybe (UnixTime, TxHash) -> Int -> IO [(UnixTime, TxHash)]) -> (Address -> Maybe (UnixTime, OutPoint) -> Int -> IO [(Unspent, Bool)]) -> (Address -> [OutPoint] -> IO [Bool]) -> ([TxHash] -> IO [(Maybe TxData, IntMap Spender)]) -> ([OutPoint] -> IO [Maybe Spender]) -> (Word32 -> Word32 -> IO [(UnixTime, TxHash)]) -> ((Word32, Word16) -> IO [TxHash]) -> (TxHash -> IO (Maybe Replaced)) -> (Address -> IO [(TxHash, PoolTokens)]) -> (TxHash -> IO [(Address, PoolTokens)]) -> (TxHash -> IO (Maybe CategorySummary)) -> (TxHash -> Maybe (UnixTime, TxHash) -> Int -> IO [(UnixTime, TxHash)]) -> (TxHash -> Maybe (UnixTime, OutPoint) -> Int -> IO [(Unspent, Bool)]) -> PoolReads
- Haskoin.Store.Database.Stalls: noStall :: Stall
+ Haskoin.Store.Database.Stalls: noStall :: DatabaseHealth
- Haskoin.Store.Database.Stalls: readStall :: DB -> IO Stall
+ Haskoin.Store.Database.Stalls: readStall :: DB -> IO DatabaseHealth
- Haskoin.Store.Database.Stalls: stallNote :: Writes -> Stall -> Maybe (LogLevel, Text)
+ Haskoin.Store.Database.Stalls: stallNote :: DatabaseWrites -> DatabaseHealth -> Maybe (LogLevel, Text)
- Haskoin.Store.Database.Stalls: watchStalls :: (LogLevel -> Text -> IO ()) -> Maybe Stats -> DB -> TVar Stall -> IO ()
+ Haskoin.Store.Database.Stalls: watchStalls :: (LogLevel -> Text -> IO ()) -> Maybe Stats -> DB -> TVar DatabaseHealth -> IO ()
- Haskoin.Store.Database.Types: [spent] :: MemSummary -> !Word64
+ Haskoin.Store.Database.Types: [spent] :: CategorySummary -> !Word64
- Haskoin.Store.Database.Views: keepViews :: Ord b => Views b -> [b] -> IO ()
+ Haskoin.Store.Database.Views: keepViews :: Ord b => Views b -> STM [b] -> IO ()
- Haskoin.Store.Fleet.Member: Member :: !MemberConfig -> !Connection -> !FleetKeys -> !DatabaseReader -> !Views BlockHash -> !TVar [BlockHash] -> !TVar [BlockHash] -> !TVar (Maybe BlockHash) -> !TVar (HashMap TxHash (UnixTime, Tx)) -> !TVar Bool -> !Indexer XPubSpec () -> !Lock XPubSpec -> !TVar (HashMap ByteString Int) -> !XPubs -> !Maybe CacheMetrics -> !Outage -> !TVar (Maybe ByteString) -> !TVar (Maybe Integer) -> !TVar Int -> !IORef (ByteString, Word64) -> Member
+ Haskoin.Store.Fleet.Member: Member :: !MemberConfig -> !Connection -> !FleetKeys -> !DatabaseReader -> !Views BlockHash -> !TVar [BlockHash] -> !TVar [BlockHash] -> !TVar (Maybe BlockHash) -> !TVar Bool -> !TVar Bool -> !TVar Bool -> !Indexer XPubSpec () -> !Lock XPubSpec -> !TVar (HashMap ByteString (Int, Int)) -> !XPubs -> !Maybe CacheMetrics -> !Outage -> !TVar (Maybe ByteString) -> !TVar (Maybe Integer) -> !TVar Int -> !TVar Int -> !IORef (ByteString, Word64) -> Member
- Haskoin.Store.Fleet.Member: [built] :: Member -> !TVar (HashMap ByteString Int)
+ Haskoin.Store.Fleet.Member: [built] :: Member -> !TVar (HashMap ByteString (Int, Int))
- Haskoin.Store.Fleet.Member: memberLoop :: Member -> IO () -> IO a
+ Haskoin.Store.Fleet.Member: memberLoop :: Member -> IO a
- Haskoin.Store.Fleet.Member: redisPool :: Connection -> FleetKeys -> ByteString -> IO () -> PoolReads
+ Haskoin.Store.Fleet.Member: redisPool :: Network -> Connection -> FleetKeys -> ByteString -> IO () -> PoolReads
- Haskoin.Store.Fleet.Member: report :: Member -> IO ()
+ Haskoin.Store.Fleet.Member: report :: Member -> IO Bool
- Haskoin.Store.Fleet.Pool: Pays :: !a -> !o -> !Word64 -> Entry a o
+ Haskoin.Store.Fleet.Pool: Pays :: !a -> !o -> !Word64 -> Entry a o c
- Haskoin.Store.Fleet.Pool: Spends :: !a -> !o -> !Word64 -> Entry a o
+ Haskoin.Store.Fleet.Pool: Spends :: !a -> !o -> !Word64 -> Entry a o c
- Haskoin.Store.Fleet.Pool: Touches :: !a -> Entry a o
+ Haskoin.Store.Fleet.Pool: Touches :: !a -> Entry a o c
- Haskoin.Store.Fleet.Pool: [spent] :: Totals -> !Word64
+ Haskoin.Store.Fleet.Pool: [spent] :: CategoryPool t o -> !Word64
- Haskoin.Store.Fleet.Pool: [txs] :: Totals -> !Word64
+ Haskoin.Store.Fleet.Pool: [txs] :: CategoryPool t o -> ![(Word64, t)]
- Haskoin.Store.Fleet.Pool: addresses :: (Ord a, Ord t, Ord o) => [(t, Word64, [Entry a o])] -> Map a (AddressPool t o)
+ Haskoin.Store.Fleet.Pool: addresses :: (Ord a, Ord t, Ord o) => [(t, Word64, [Entry a o c])] -> Map a (AddressPool t o)
- Haskoin.Store.Fleet.Pool: data Entry a o
+ Haskoin.Store.Fleet.Pool: data Entry a o c
- Haskoin.Store.Fleet.Redis: PoolTx :: !ByteString -> !Word64 -> ![ByteString] -> !ByteString -> !Bool -> ![PoolEntry] -> PoolTx
+ Haskoin.Store.Fleet.Redis: PoolTx :: !ByteString -> !Word64 -> ![ByteString] -> !ByteString -> ![PoolEntry] -> PoolTx
- Haskoin.Store.Fleet.Redis: fleetAdvance :: Connection -> FleetKeys -> Int -> Maybe Time -> Maybe ByteString -> ByteString -> Maybe PoolChange -> [ByteString] -> IO Moved
+ Haskoin.Store.Fleet.Redis: fleetAdvance :: Connection -> FleetKeys -> Int -> Maybe Time -> ByteString -> Maybe ByteString -> ByteString -> Maybe PoolChange -> [ByteString] -> IO Moved
- Haskoin.Store.Fleet.Redis: fleetCommit :: Connection -> FleetKeys -> Int -> Maybe Time -> Maybe ByteString -> ByteString -> Maybe PoolChange -> [ByteString] -> ByteString -> IO Moved
+ Haskoin.Store.Fleet.Redis: fleetCommit :: Connection -> FleetKeys -> Int -> Maybe Time -> ByteString -> Maybe ByteString -> ByteString -> Maybe PoolChange -> [ByteString] -> ByteString -> IO Moved
- Haskoin.Store.Logic: PreparedTx :: !Tx -> !TxHash -> ![OutPoint] -> ![Maybe Address] -> !Int -> !Int -> PreparedTx
+ Haskoin.Store.Logic: PreparedTx :: !Tx -> !TxHash -> ![OutPoint] -> ![Maybe Address] -> ![Maybe TokenData] -> !Int -> !Int -> PreparedTx
- Haskoin.Store.Manager: Store :: !PeerMgr -> !Chain -> !BlockStore -> !DatabaseReader -> !Maybe Member -> !Publisher StoreEvent -> !Publisher StoreEvent -> !Network -> !SockAddr -> WithConnection -> !TVar Stall -> Store
+ Haskoin.Store.Manager: Store :: !PeerMgr -> !Chain -> !BlockStore -> !Ingester -> !DatabaseReader -> !Maybe Member -> !Publisher StoreEvent -> !Publisher StoreEvent -> !Network -> !SockAddr -> WithConnection -> !TVar DatabaseHealth -> Store
- Haskoin.Store.Manager: StoreConfig :: !Int -> ![String] -> !Bool -> !FilePath -> !Network -> !Maybe String -> !Word32 -> !Word32 -> !Int -> !XPubConfig -> !Int -> !Int -> !NominalDiffTime -> !NominalDiffTime -> !NominalDiffTime -> !NominalDiffTime -> !SockAddr -> WithConnection -> !Maybe Stats -> !Bool -> !Maybe Int -> !Maybe Int -> !Maybe Int -> !Maybe Int -> !Maybe Int -> !Logger -> StoreConfig
+ Haskoin.Store.Manager: StoreConfig :: !Int -> ![String] -> !Permissions -> !Bool -> !Bool -> !FilePath -> !Network -> !Maybe String -> !Word32 -> !Word32 -> !Int -> !XPubConfig -> !Int -> !Int -> !NominalDiffTime -> !NominalDiffTime -> !NominalDiffTime -> !NominalDiffTime -> !SockAddr -> WithConnection -> !Maybe String -> !Maybe FilePath -> !Maybe String -> !Maybe Stats -> !Bool -> !Maybe Int -> !Maybe Int -> !Maybe Int -> !Maybe Int -> !Maybe Int -> !Logger -> StoreConfig
- Haskoin.Store.Manager: [writes] :: Store -> !TVar Stall
+ Haskoin.Store.Manager: [writes] :: Store -> !TVar DatabaseHealth
- Haskoin.Store.Web: WebConfig :: !String -> !Int -> !Store -> !Int -> !Int -> !Int -> !WebLimits -> !String -> !Maybe Stats -> !Int -> !String -> !String -> !Bool -> !Int -> !Bool -> !Maybe String -> !Maybe (FilePath, FilePath) -> !Logger -> WebConfig
+ Haskoin.Store.Web: WebConfig :: !String -> !Int -> !Store -> !Int -> !Int -> !Int -> !WebLimits -> !String -> !Maybe Stats -> !Int -> !String -> !String -> !Bool -> !Int -> !Bool -> !Maybe String -> !Maybe FilePath -> !Maybe String -> !Maybe (FilePath, FilePath) -> !Logger -> WebConfig

Files

CHANGELOG.md view
@@ -4,6 +4,694 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html) +## [Unreleased]++## [2.0.0] - 2026-11-25++This release brings the tokens of Bitcoin Cash (CashTokens,+`docs/cashtokens.md`): the store reads the tokens of every output, keeps the+token balance of every address and category, indexes each category, and+answers four new endpoints, counting the mempool. Outputs with tokens now+have their addresses, so the history and the balances of those addresses+are whole.++Before upgrading, take a copy of the database: the migration to version 24+cannot be undone, and on Bitcoin Cash it reads every block since May 2023,+which takes hours. Upgrade every store of a fleet together, since the+scripts of the shared pool take token entries. It needs haskoin-core 3.0,+haskoin-store-data 4.0 and haskoin-node 2.7. A store whose `--peer` nodes+whitelist it must now say what they grant (`--peer-permission`, or+`PEER_PERMISSIONS=mempool,noban` for `whitebind=mempool,noban@…`): without+`mempool` there, a Bitcoin store no longer asks them for their mempools.++### Added+- **The path of a transaction into the shared mempool is one machine,+  specified and checked** (`docs/mempool-ingestion.md`,+  `Haskoin.Store.Ingest`, run by `Haskoin.Store.Ingest.Run`). It replaces+  five stages that each lost transactions in a way of their own: the queue+  of announcements, the set of requests, the member's list of what waited,+  its offers by turn, and the question to the peers at the start.+  - Every transaction id has one place, and leaves it settled or given up+    for a counted reason (`ingest.given_up.*`). A store that gave+    something up reads the whole mempool of its **sources** again: the+    RPC of its node (`--node-rpc`), and the peers whose node gives its+    mempool when asked. It also reads them when+    one connects, when the pool lost what it had, and every ten minutes.+    So a loss is temporary, where it lasted until a block: a node+    announces a transaction to a peer once.+  - What a peer names is asked of the pool before anything is fetched, so+    reading a mempool that the pool has costs the list of its ids.+  - Each peer has a window of requests out, from 16 to 4,096, that grows+    as the peer answers and halves when it does not, in place of asking a+    node for its whole mempool at once.+  - A transaction is offered when it arrives, each after those that it+    spends from: a chain enters root first, in any order of arrival.+  - What peers name while the store is a block behind is kept, and asked+    for once it is in sync, where it was dropped.+  The document says what the path guarantees and how each claim is+  established: by construction, proved by Liquid Haskell for every state+  (`proofs/`: that nothing leaves in silence, the bounds on memory, and+  that every step ends, with where each id is kept in a module of its+  own, `Haskoin.Store.Ingest.Ledger`),+  checked through every order of events of small worlds by a model+  checker in the test suite (`Haskoin.Store.Ingest.Model`,+  `scripts/check-ingest.sh`), or tested against Bitcoin Core and Bitcoin+  Cash Node in Podman (`Haskoin.Store.MempoolSpec`, and+  `Haskoin.Store.NodeAxiomsSpec` for what is assumed of a node). A store+  with no source, as one whose peers are all strangers on Bitcoin and+  that has no RPC, says so in its log and in `/health`.+- **The RPC of the node is a source of that path** (`--node-rpc`,+  `Haskoin.Store.NodeRpc`): the store reads the node's whole mempool+  through it when it starts, whenever it may have missed a transaction,+  when the pool lost what it had, and every ten minutes, as it does of a+  peer that gives its mempool. So a store of Bitcoin Core that its node+  does not whitelist no longer needs a block to get back what it missed.+  To the machine the RPC is one more peer that is a source, asked within+  a window that follows what the node delivers, so nothing of the machine+  or of its proofs is particular to it. Before, the RPC was read only+  after the pool had been emptied, 2,000 transactions every two seconds,+  and a call that failed was taken for an empty mempool: a node that does+  not answer now says nothing about what it has, and is tried again after+  a second, then two, up to a minute.+- **`/health` says in words what it found.** Each check has a `text`,+  such as "The database is 4 blocks behind the best header, at height+  688,798, more than the 2 allowed: the store is syncing, or cannot import+  blocks fast enough.", and the top a `text` for the whole store: that it is+  healthy, with its height and peers, or what is wrong. They come from+  haskoin-store-data 4.0 (`healthText`), so a client writes the same.+- **`/health` says how the store stands with the mempool of its nodes**,+  in `mempool`: how many sources it has to read a whole mempool from+  again, whether it may have missed transactions and has not read a+  source since, and what is on its way to the pool. A store with no+  source is healthy, and the `text` at the top says that what it misses+  stays missed until a block.+- **The check of the database says more**: beside the state of writes, the+  compactions and flushes running, the full tables in memory waiting for a+  flush, the size of the files and of their live data, and the errors in+  the background since the database opened, which say why writes are+  slow. It is now a field of `HealthCheck` in haskoin-store-data+  (`DatabaseHealth`), so the client reads it; the store added it to its+  JSON outside the type before.+- **Tokens of Bitcoin Cash (CashTokens).** Outputs that hold tokens have+  their addresses now, with haskoin-core 3.0, and so are in the history,+  the balance and the unspent outputs of those addresses. Outputs, inputs+  and unspent outputs have a `token` field on Bitcoin Cash. New endpoints:+  `/address/{address}/tokens`, the token balances of an address, and+  `/token/{category}/holders`, `/unspent` and `/transactions`+  (`docs/cashtokens.md`). They count the mempool, as an address's balance+  does: the fleet's pool in Redis keeps, for each category, its+  transactions and outputs, and for each address and category the sums of+  a token balance. Every store of a fleet must run this version, since+  the pool's scripts take token entries.++- **Unix sockets for Redis, the node and its RPC.** `--redis-url+  unix:PATH` reaches a Redis on a Unix socket; a peer written `unix:PATH`+  is a Unix socket, with haskoin-node's peers on sockets; and+  `--node-rpc-socket` sends the requests of `--node-rpc` through a Unix+  socket, with the user and password of its URL. Neither node listens on a+  socket itself, so it is something that joins one to the node, such as+  socat. The courier of a published transaction gives such a peer the zero+  address in its version message, where haskoin-core's `sockToHostAddress`+  stopped on it.++- **The store asks what each peer's node allows.** With haskoin-node 2.7,+  every peer runs a model of its node: the state machine of Bitcoin Core+  32.1 or Bitcoin Cash Node 29.2.0 that haskoin-core translates from their+  source. A message that the node would punish is not sent, and the log+  says why, with the upstream line. When the pool fills again, the store+  asks for the mempool only the peers whose node takes the request: one+  that serves Bloom filters, as its version message says, or one that+  whitelists the store with `mempool`. That replaces a rule of the store's+  own, which asked every peer on Bitcoin Cash and only the `--peer` peers+  on Bitcoin. That rule lost a Bitcoin Cash peer that served no Bloom+  filters, and assumed that every `--peer` node whitelisted the store.+  `--peer-permission` (`PEER_PERMISSIONS`) says what the nodes of `--peer`+  grant, by the names of `-whitelist`.+- **The courier knows which nodes say when they refuse.** The model of the+  node says whether it answers a refused transaction with a `reject`. A+  `pong` with no `reject` before it now means that a Bitcoin Cash Node kept+  the transaction (`Kept`), and still only that a Bitcoin Core node is done+  with it (`Took`).++- **Documentation of the tokens.** The README has a section on the token+  endpoints, with their answers and what each field means, one on how the+  store keeps tokens, notes on upgrading to 2.0.0, and an example of the+  Haskell client for tokens. `swagger.yaml` has an example answer of each+  token endpoint, taken from a regtest chain.++### Changed+- The tests accept fast-logger 3.3 (`>= 3.2.9 && < 3.4`), as haskoin-node+  2.7.0 does for+  [stackage#8183](https://github.com/commercialhaskell/stackage/issues/8183).+  The store logs through haskoin-node, whose suite passes with 3.3.0. The+  store's own suite was not run with it: `stack.yaml` builds with 3.2.9.+- **The shared mempool is changed by decisions made in Haskell, each+  carried out in Redis in one step or not at all**+  (`Haskoin.Store.Fleet.Atomic`, `Haskoin.Store.Fleet.Pool.Decide`,+  `docs/concurrency.md`). Its rules were a Lua script of eight hundred+  lines, which had two faults. A script that fails after its first write+  keeps what it wrote, so an error in it left the pool half changed, as+  the output of value 0 did on 19 November; and the rules were kept+  twice, in Lua to run and in Haskell to test against.+  - A decision can only ask Redis questions and list writes, which its+    type says. One small script that decides nothing asks the questions+    again and carries out the writes only if every answer is the same;+    otherwise it writes nothing and the decision is made again. An error+    in a decision is an exception in Haskell before Redis is told+    anything.+  - The decisions are held to the script that they replace, which no+    store runs any more: the two side by side in one Valkey, through+    drawn sequences of offers, withdrawals, expiries and moves of the+    tip, with all that Redis has compared after every step+    (`Haskoin.Store.Fleet.DecideSpec`).+  - **The store that moves the tip has the floor.** A move of the tip+    over a block reads for a second or more, and a decision is carried+    out only if nothing that it read has changed: with transactions+    offered all the time it would lose every race. So while a store moves+    the tip, an offer is late and is made again, and withdrawals,+    expiries, and drops and evictions of the cache wait for the next+    turn. A move costs in proportion to its block. A store whose move is+    refused five turns in a row warns in its log, with how long the last+    took and which answer of Redis had changed.+  - **The floor lasts as long as the move.** The store says every two+    seconds that it is at its move, in a key of its own (`fx:beat`), and+    has the floor for ten seconds from each time. The floor lasted ten+    seconds from when it was taken, and the move over a block of Bitcoin+    took longer than that to decide on a server: it was refused at every+    turn, the tip staying where it was while the database went on. A+    decision also judges time by one clock, read at its start, where it+    read the clock again each time it asked Redis, and so found its own+    lease of ten seconds run out. A store says in its log when a move+    took a second or more, since transactions wait meanwhile, and+    where the time went: reading the blocks, reading and writing the+    cache, deciding, the calls to Redis, carrying it out, and the+    garbage collector.+  - **`haskoin-store-bench decide`** times what the move of the tip over+    a block costs to decide, without Redis: each pass over the decision,+    its answers and writes, and what it allocates. Run it with+    `+RTS -T -A64m`, as a store runs. The figures of this section were+    measured without `-A64m`, where the collector goes over the model of+    Redis three hundred times in a move: they compare one build with+    another, and are more than twice what the move costs. With it the+    move over 4,000 transactions is decided in 0.8 seconds.+  - **The move of the tip is gone through once.** It names what it will+    ask before it starts, in steps, where it found its questions as it+    went and was gone through from its start for each step: five times+    through a block in the benchmark, and more on a server. Deciding the+    move over 4,000 transactions takes 1.3 seconds where it took 4.4,+    on a desktop, and decides the same. What it asks of the transactions+    of the pool that a block is in conflict with is named ahead too: on+    a server, blocks with such transactions took nine and fifteen+    seconds where the others took under five, and sixty of them made the+    benchmark go from 1.1 seconds to 5.4; it is 1.2 with them named.+  - **A store takes whatever its node has.** A transaction that a node+    names is fetched and offered unless the pool has it. It was also left+    alone if the fleet remembered having seen it, among the newest+    100,000: a transaction that the pool had let go, for another that+    took its place, and that the node took again later, stayed out of+    the store for as long, through every reading of the node's mempool.+    On a server one stayed out for hours. Two stores of a fleet whose+    nodes hold transactions in conflict now each offer their own again+    at every reading; the pool holds the one offered last. The set of+    what the fleet saw (`fleet:seen`) is no longer kept: an offer writes+    one thing less, and a member no longer trims it at each turn. The+    key of an older store is left unread, and can be deleted.+  - **A store asks its node for what a transaction spends from** when+    the pool lacks it, at once. It waited for it to come by itself,+    trying the transaction again after two seconds, four, eight, up to+    twenty minutes, and a node names a transaction to a peer once: a+    parent that a store had lost kept everything that spent from it out+    of the pool until the next reading of the node's mempool. Bitcoin+    Core sends a transaction that it never named to the peer; Bitcoin+    Cash Node says that it has it not, and there the store waits as it+    did. The rule is in the model of the path, with a check that a+    machine without it fails, and Liquid Haskell passes.+  - **A store that has the RPC of its node reads it again when it+    connects to the node as a peer.** A node names to a peer nothing+    that it took before the peer connected, and its RPC announces+    nothing: what the node took between the reading of the RPC and the+    connection was in neither, and stayed out of the store until the+    next reading, ten minutes later. It lost four transactions in one+    run of a test in about forty. A peer that connects and is no source+    now makes the sources owe a reading. The model of the path has a+    node with its RPC and a peer, and fails without the rule.+  - **A Grafana dashboard for the store's metrics**, read from InfluxDB+    as Telegraf's statsd input writes them, for a store that sends its+    own statistics (`--statsd-aggregates --statsd-no-events`):+    `tools/grafana/haskoin-store.json`, with the script that generates+    it. Nine rows and 46 panels: requests, one kind of request,+    overload, blocks and peers, the database, the path into the+    mempool, the cache of xpubs and the runtime. Telegraf sums the+    store's statistics up a second time, which leaves counts, sums and+    the longest right, and means, rates and percentiles wrong: the+    dashboard reads the first and works the rest out, and+    `docs/grafana.md` says how. Checked on a real Telegraf and InfluxDB+    with a known load, which `tools/grafana/check/run.sh` does again,+    and not yet against a store in production. The README now lists the+    metrics of the web server and of the reads of the database, which+    the store sent and the README did not name, and what the statistics+    of `--statsd-aggregates` are called.+  - **A test of a store whose Valkey is emptied while it runs**, as by+    `FLUSHALL`, against Bitcoin Core and Bitcoin Cash Node+    (`valkeyFlush` in `Haskoin.Store.MempoolSpec`). Valkey goes on+    answering, so nothing fails, and only the epoch tells the store that+    the pool is gone. The store must say so once, and have the mempool+    of its node again within fifteen seconds, without being started+    again. A store also reads the mempool of its node by the clock,+    which alone brought the pool back after 26 seconds in a store made+    unable to notice: the test empties Valkey right after that reading,+    so that only the noticing meets its limit. It fails for a store+    that does not notice, and for one that notices and does not read+    again. Tried once on servers too, under stores answering the+    public, none of which was started again: Bitcoin Cash and the+    testnets had the mempool of their node again in under three+    seconds, and Bitcoin, with 65,962 transactions, in 233+    (`docs/fleet-mempool.md`).+  - **A store at the head of the chain is healthy, whatever the state of+    its mempool.** `ok` of `/health`, and its status, no longer depend+    on the two checks that look at transactions: `last-tx`, that one+    came lately, and `pending-txs`, that few are asked for and not+    received. A store that had every block was unhealthy, and taken out+    of service, when its node went quiet or while it fetched a large+    mempool. Both checks are still made and still say whether they+    pass. `--tx-timeout` and `--max-pending-txs` set their limits as+    before, and no longer decide anything.+  - **A store takes no mempool transaction in until it has the+    blocks.** While it takes its blocks, a store hears of new+    transactions and cannot place one: what they spend is in blocks+    that it has not yet. A store that took 160,000 blocks in half an+    hour fetched what its node named meanwhile, held thousands, and+    gave them up for seven minutes after it had its blocks, saying+    `syncing` all that time. Until a store first has its blocks, the+    path into the pool now keeps nothing that a peer names or sends+    and asks for nothing; then it reads its sources. And a store first+    has its blocks only once its node has the headers of its peers+    (`chainHasHeaders`, of haskoin-node 2.7.0): the+    database caught up with the last header again and again while the+    headers came, two thousand at a time. A rule of the machine (`begun`), with a check+    in the model and two planted bugs that it finds; that a transaction+    sent unasked is not kept either is tested by an example and not+    checked; tested against both nodes on+    a chain of 2,500 blocks, with a test that failed before.+  - **A store no longer shows the coinbase of a block that its node+    took back.** A node publishes over ZeroMQ the ids of the+    transactions of a block that stops being part of its chain, the+    coinbase too, and gives that coinbase when asked, since it keeps+    the block. A store with its node as a peer through the RPC and+    ZeroMQ took it on the word of its node: an unconfirmed transaction+    that could never confirm, until something emptied the pool. Two+    were seen on each store of a testnet of a server, after a+    reorganisation of two blocks. A coinbase is no longer taken in+    when it arrives, whoever sent it: to the path into the pool, the+    peer does not have it. And one that is not in the chain of the+    store is never offered to the pool. Tested against both+    nodes, with a test that failed before (`staleCoinbase`). One that+    is in a pool already stays there until the pool is emptied.+  - **`/health` says how the mempool stands, in one word**+    (`mempool.sync`): `syncing`, `synced` or `unknown`. After a start,+    or after Redis lost its data, a store has its blocks at once and+    its mempool a minute later, on Bitcoin: it is healthy meanwhile and+    shows fewer unconfirmed transactions than its node. A deploy that+    waited for `/health` gave a store traffic 70 seconds before its+    mempool was full: it can wait for `synced`.+    - The mempool is measured against the nodes of the operator only.+      It is `syncing` until each was asked for its mempool and had+      twenty seconds to answer, the store has missed nothing of it+      since, and the pool has decided on all that they named. A store+      with no such node says `unknown`: what a stranger names is+      nothing to measure a mempool against.+    - It was a boolean, `filling`, for a few hours, measured against+      every source. A store whose peers were all strangers said that it+      was filling for ever: a transaction that it could not verify kept+      its place for twenty minutes, and another came before it left.+    - In the machine of the path as T9 of `docs/mempool-ingestion.md`:+      three checks in the model, and five planted bugs that it finds.+      That a store comes to say `synced` is tested and not checked,+      also on both nodes while transactions come without a pause.+    - Needs haskoin-store-data 4.0.0.+  - **A source is read every minute at least**, where it was every ten+    minutes. While transactions come it is read every thirty seconds,+    as before.+  - **A node as a peer, through its RPC and its ZeroMQ socket**+    (`--node-rpc` with `--node-zmq`, `NODE_ZMQ`; `docs/node-peer.md`).+    The peer-to-peer protocol is made for strangers: a node names what+    it takes to a peer at its own pace, Bitcoin Core about fourteen a+    second after a first batch, and in a burst a store was behind until+    it next read the mempool, every thirty seconds. Somebody who runs+    the node has its RPC, which answers anything, and its ZeroMQ+    socket, which says what the node takes as it takes it.+    - With both, the store has that node as one more peer+      (`Haskoin.Store.NodePeer`): a pipe in memory, with a thread at+      the other end that answers the messages of the peer-to-peer+      protocol from the RPC (headers, blocks, transactions, the+      mempool) and announces what the node publishes (`hashtx`,+      `hashblock`, which both Bitcoin Core and Bitcoin Cash Node have).+      Nothing else of the store changes: the node counts as a peer in+      `/health`, it is a node of the operator, and it is a source.+    - A store can run on it alone, with no `--peer` and no+      `--discover`: discovery is no longer turned on for such a store.+    - Both connections are the peer. If the RPC fails or the socket+      closes, the peer is gone; a ping is answered only once the node+      answered a call, so a node that hangs is a peer that is silent;+      and the node is asked for its best block every thirty seconds, in+      case the socket went quiet. When messages may have been lost, the+      whole mempool is named.+    - The store speaks the protocol of ZeroMQ itself (ZMTP 3.0,+      `Haskoin.Store.NodeZmq`), with no library of the system. A Unix+      socket works as an address (`ipc://PATH`).+    - Tested against both nodes: the subscriber; a store with no other+      peer that has 150 blocks, the mempool, what the node takes next+      and its next block; the same store when its node hangs and goes+      on; and on Bitcoin Core, 800 transactions that the node took in+      seconds, there within five seconds of the last with no reading,+      where the peer-to-peer protocol alone is late. Not tested: a+      first sync of a real chain this way, which takes one RPC call for+      each block.+    - **The RPC alone makes the node a peer too** (`--node-rpc` without+      `--node-zmq`). Nothing publishes then, so the peer asks the node+      every five seconds: for its best block, and, while no other node+      of the operator is a peer of the store, for the ids of its+      mempool, of which it names those that are new. While every other+      peer is a stranger, that keeps the store at most five seconds+      behind a node that it trusts. Such a store runs with no+      peer-to-peer connection as well, and discovery is not turned on+      for it. Tested against both nodes (`polls`: three batches and a+      block, each there within twelve seconds, which fails when the+      peer asks every sixty). Not measured: what asking a mempool of+      sixty thousand transactions every five seconds costs the node.+    - **A store can run without ever connecting to a peer**, from no+      chain at all: with the RPC of its node, and its ZeroMQ socket or+      not. Tested on both nodes, each way, on a chain of more than+      2,500 blocks, which is more than a node gives of headers in one+      answer (`noPeerEver`). Not tested on a real chain.+    - **A store that has the RPC and not the ZeroMQ socket warns of+      it**: the two are expected together. In the log, when the store+      starts and when the peer connects, and in `/health`, as a+      sentence in the new `warnings` and in `text`. A warning decides+      nothing: `ok` and the status stay as they are. It needs+      haskoin-store-data 4.0.0.+    - The web server no longer reads the RPC as a source of its own+      (`nodeFeedLoop`): the node peer is that source.+    - The node of `--node-rpc` is a node of the operator with+      `--foreign-peers` too, which speaks of the nodes of `--peer`. It+      was taken for a stranger.+  - **The peers that the operator gave are kept** (`--peer`, and the+    node of `--node-rpc`). They are the ones whose word the store takes,+    and the only reason for one to have no connection is now that it+    takes none. From haskoin-node's branch `sticky-peers`:+    - never dropped for its age: `--max-peer-life` is for peers found by+      discovery;+    - tried again every ten seconds at most when its connection ends,+      for ever, where it waited up to ten minutes;+    - a slot kept for it while it is away: with `--discover`, peers+      found on the network filled every slot meanwhile, and the node of+      the operator found none when it came back.+    Tested in haskoin-node, the first against both nodes. Not tested end+    to end: a store with discovery whose own node is away.+  - **A stranger is not taken at its word.** A store verifies no script:+    it takes a transaction because a node took it. It did so of every+    peer, and a peer found by discovery is anybody: it could send a+    spend of somebody's coins with a signature that does not verify,+    and the store showed it, as a payment that was never made or as+    coins spent that were not. A test offers such a transaction as the+    store offered every one: it is taken.+    - The store now takes the nodes of `--peer`, and the node of+      `--node-rpc`, for nodes of its operator, and takes their word as+      before. `--foreign-peers` (`FOREIGN_PEERS`) says that the nodes+      of `--peer` are not.+    - What only strangers name is looked at before it is offered. If+      every signature of a coin locked to one key verifies, it is+      taken. If one does not, or it spends more than it has, or its+      tokens come from nowhere, it is given up with all that spends+      from it (`ingest.given_up.forged`). If it spends a coin locked by+      a script, which only a full node can judge, it is held until a+      node of the operator names it, twenty minutes at most, and not+      shown meanwhile (`ingest.given_up.not_vouched`).+    - So a store with a node of its operator among its peers misses+      nothing, and one with only strangers shows a spend of a script+      when a block confirms it.+    - The checks are in haskoin-core (`Haskoin.Transaction.Judge`,+      `judgeRelayed`), with those of `POST /transactions`, which moved+      there from this package: they say nothing of a store, and other+      programs can use them. Only what no node can take is refused: a+      rule of relay is the node's own.+    - The rule is in the machine of the path (T8 of+      `docs/mempool-ingestion.md`), and the model has seven worlds for+      it, 26 in all, with five planted bugs that it finds; its first+      version had two of them. Liquid Haskell passes. Tested with real+      signatures against a real pool, and against Bitcoin Core: a store+      whose only peer is a stranger takes what the wallet of the node+      signed and not what a script spends, and takes both once the peer+      is a node of its operator.+    - It builds on haskoin-core's branch `judge-transactions`.+  - **A store of Bitcoin has a whole mempool again in a minute and a+    half, where it took over three.** After each transaction that came,+    the path into the pool said how many ids it knew, and counted them+    by making a set of them all: 0.8 milliseconds for 65,000 on a+    desktop, for each of 65,000 transactions. A store whose Redis had+    lost its data, or that started on a new pool, took in 380+    transactions a second with a core busy, its Redis idle and requests+    out to its node all the time: 233 and 259 seconds on a server+    answering the public, 191 on one answering nobody. The count is the+    size of a map now, and the same store took in 2,300 a second and had+    the 65,314 transactions of its node after 87 seconds, 294 a second+    from the first seconds and over 1,000 from the second minute. What+    remains is the offers, one at a time.+  - **A store that is slow to fill its pool says where its time goes.**+    Every ten seconds in which the path into the pool was busy for five+    or more, it says in its log how many events, offers and questions to+    the pool it went through, and how many milliseconds went to the+    machine, to the offers, to the questions, to sending requests and to+    saying its state, with the offers split into what each reads: whether+    a block has the transaction, the outputs that it spends from the+    database and from the pool, which of them are unspent, and the+    pool's decision. Nothing outside the store could tell. That line is+    what found the count above, after a cause reasoned from the shape of+    a curve had been wrong.+  - **A store that takes a whole mempool at once offers each+    transaction to the pool once.** A transaction that spends from one+    that the store is still fetching waits for it, and was offered to+    the pool all the same two seconds later, then four, eight and so+    on, in case that one had been given up. The pool could only refuse+    it. A held transaction is now offered at its time only if one of+    those that it waits for has no place any more, which is what the+    time is for (`docs/mempool-ingestion.md`). Given 65,000+    transactions in chains of 24 at once, with a millisecond for each+    offer, the machine made 103,862 futile offers and took 169 seconds;+    it makes none now, and takes the 65 seconds of the offers+    (`Haskoin.Store.IngestSpec`, in three seconds). Against Bitcoin+    Core with 24,000, a store with an empty pool made 44,000 futile+    offers and had them all in 18 seconds; none and 13 seconds now. On a+    server with 65,000 it changed nothing that could be measured: this+    was not what made the store slow there. The model checks the rule+    both ways, with a planted bug for each, and Liquid Haskell passes.+  - **The tip moves at once, and the pool lets go of the block's+    transactions after it.** A move of the tip over a full block took+    what the block confirmed out of the pool in the same step: more than+    a hundred thousand writes, for which the tip waited five to fifteen+    seconds on a server, nearly one of them inside Redis, which answers+    nobody else meanwhile, and more with every cached extended key. The+    move now marks those transactions, one write for each, and they+    leave afterwards, two hundred at a time. A request that would read+    one of them takes it out first, so every answer is that of a pool+    that has let go of everything; nothing enters the pool until it has.+    In the benchmark the move over 4,000 transactions is decided in 0.12+    seconds where it took 0.8, and 2.7 with a cached key at every+    address. A move that undoes a block is as it was.+    `scripts/check-pool.sh` checks the three rules in small worlds, with+    the decisions themselves: every pool, every block and every order of+    taking out (`docs/tip-first.md`). And no decision can write to the+    pool or to the cache while a transaction is marked: every write to+    one of their keys asks first, whatever the decision does for+    itself. That taking transactions out leaves the same pool in any+    order is proved by Liquid Haskell for the pool as a pure value+    (`Haskoin.Store.Fleet.Pool.Order`).+  - **A store reads the mempool of its node every thirty seconds while+    transactions come**, and twice as long after each reading that+    follows none, up to the ten minutes that it was. Bitcoin Core names+    transactions to a peer at fourteen a second after a first batch, to+    a peer that it whitelists too, so a store was minutes and thousands+    of transactions behind its node whenever the node took more: nothing+    was lost, and all of it was late. Asked for its mempool, the node+    names everything at once. A store says in its log when going through+    what a node named at once took a second or more.+  - **`rbf` is true for every unconfirmed transaction on Bitcoin, and+    false elsewhere.** The nodes of Bitcoin take a replacement of any+    unconfirmed transaction, whatever it signals, since Bitcoin Core 28,+    and Bitcoin Cash has no such rule. The field said whether a+    transaction signalled replace-by-fee (BIP 125) or spent an+    unconfirmed one that did, which the pool worked out for every+    transaction and kept right as parents were confirmed and came back:+    two sets in Redis, and questions about the children of every+    transaction that a block confirmed. None of that is kept or asked+    any more; the sets `pool:own` and `pool:rbf` of an older store are+    left unread. The move over 4,000 transactions is decided in 1.1+    seconds.+  - **A decision of any size is carried out.** Its questions and writes+    go to Redis a thousand to an argument, without the writes that a+    later delete undoes and with one command for many members of a key.+    They went as an argument for each word, 1,008,352 for the move of+    the tip over one block of Bitcoin, and Redis closes the connection of+    a command with more than 1,048,576.+  - **It costs Redis more:** an offer that is taken is two calls where it+    was one, and about 137 microseconds of Redis where the script took 74+    (Valkey's own count). That leaves room for some seven thousand offers+    a second.+  - **Breaking for a fleet: keys start with `hs3:<network>:`**, where they+    started with `hs2:`. Stores of this version and older ones on one+    Redis are two fleets, each with its own pool. Upgrade every store of+    a fleet together; the keys under `hs2:` can be deleted afterwards.+  - **The cache of extended public keys is written the same way**+    (`Haskoin.Store.Fleet.XPub.Decide`): building an entry, moving it+    with the tip in pieces, dropping and evicting. A script that failed+    among the thousands of rows of a build left an entry half written. A+    build of a key with 20 addresses costs Redis about 1.5 milliseconds+    where it cost 1.0. Its reads are still one script and one call, and+    write nothing but the note that a key was used: a move of the tip+    that its store left for ten seconds is no longer ended by a read, but+    by the build that follows the miss.+  - **That a decision sees its own writes rightly is proved** for what it+    asks about one cell: a field of a hash, a member of a set, the score+    of a member, what a key holds. What a write does to a cell is written+    once (`Haskoin.Store.Fleet.Atomic.Cells`), for the model of Redis and+    for the decision, and Liquid Haskell checks, for every list of+    writes, that the cell in the model after them is what the decision+    works out (`proofs/`). It assumes four facts of `Data.Map`. The rest+    of what a decision can ask is tested, as before.+  - **A write of the wrong kind to a key does not compile.** The script+    that carries out a decision cannot fail half way unless Redis+    refuses a command, which it does for a key of another kind and for an+    addition to what is no number. A key now has its kind in its type+    (`Haskoin.Store.Fleet.Atomic.Keys`), and the decisions are written+    with questions and writes that each take keys of one kind.+  The scripts of the reports and of the move of the tip without the pool+  are as they were.+- **The testnet3 of Bitcoin Cash is `--net bchtest3`**, no longer+  `bchtest`, as haskoin-core 3.0 renames it after `bchtest4`. Bitcoin Cash+  Node still runs testnet3, and the store keeps it, as it keeps Bitcoin+  testnet3 (`btctest`), which haskoin-core deprecates. The name is also+  the store's data directory, its prefix in Redis, its StatsD namespace+  and its `network` in the API: before upgrading a store of testnet3,+  rename `DIR/bchtest` to `DIR/bchtest3`, and set `NET=bchtest3`. Its+  shared mempool fills again under the new prefix. Addresses keep the+  CashAddr prefix `bchtest`. `hsq -n bchtest3` follows.+- **The tests name no address or port, and use only real nodes in+  Podman.** The tests of downloading that a mock peer served in memory+  (`StoreSpec`) now sync from Bitcoin Cash Node in Podman+  (`Haskoin.Store.DownloadSpec`): the blocks asked 64 at a time, every+  transaction of a block as the node has it, a second node taking over from+  one frozen with `SIGSTOP`, and a heap that stays flat over 5000 blocks.+  The web servers of the integration tests listen on Unix sockets, which the+  tests, the WebSocket client and the client of haskoin-store-data reach;+  the price service is a name that never resolves, and the RPC that does+  not answer is a socket that nothing listens on. The test of HTTPS makes+  its certificate with openssl and its requests with curl in a container of+  the test image, not with the programs of the machine. The mock peer of+  the benchmark, and the peers of the tests of publishing, are named by+  Unix sockets. The benchmark compiles again: it lacked the field+  `nodeRpcSocket` of its web server, and now the permissions of its peer.+- **The test of tokens queries the four endpoints** through the client of+  haskoin-store-data, with the transactions in the mempool and then+  confirmed: the balance of the address, the holders, the unspent outputs+  and the transactions of the category, and the amounts as strings in the+  JSON.+- **A store that does not sync in the integration tests explains+  itself.** The tests keep the last 400 lines of the log of each store,+  whether they print it or not, and when a store does not reach the best+  block of its node in time they print them, with what the node says of its+  chain and of its peers and what the store says of its health and peers.+  A store stopped short of its node a few times on Bitcoin Cash Node, too+  seldom to be run again with its log.+- **The example of the client in the README compiles**: it needed+  `OverloadedStrings` for the text of its address.+- **The integration tests run their containers through+  [podman-test](https://github.com/jprupp/podman-test)**, in place of the+  code of their own in `integration/`: each environment is a pod with+  Valkey on a Unix socket and the node's RPC and peer-to-peer ports bridged+  to sockets, and the store reaches all three through them, so the pod has+  no network. The tests are skipped with `PODMAN_TEST_SKIP`, in place of+  `HASKOIN_STORE_NO_PODMAN`. The Bitcoin Core node that does not whitelist the+  store now gives it its mempool, and the store is told so: without it the+  node closed the store's connection over the request, now and then during+  a test. The test of+  the Haskell client mines a block at each look until the client hears+  one, where it mined one and waited: a client whose stream opened after+  that block heard nothing.+- **Database version 24.** On Bitcoin Cash the migration from version 23+  indexes the outputs that hold tokens since the upgrade of May 2023: hours,+  once, and it carries on where it was if stopped. On Bitcoin it writes the+  new version. Four new column families keep older stores out.+- The checks of a published transaction read the token prefix with+  haskoin-core's parser.+- **Builds on haskoin-core 3.0**, which reads the token prefix and adds a+  field to `Network`, with haskoin-node and haskoin-store-data 4.0 on it+  too. Until they are on Hackage, `stack.yaml` pins commits of their+  GitHub repositories. The Blockchain.info API gives the legacy addresses of the+  Bitcoin Cash test networks with the prefixes of testnet4, which are+  those of testnet3, now that haskoin-core marks testnet3 as deprecated.+- **Releasing and formatting moved to+  [jprupp/tools](https://github.com/jprupp/tools)**, shared by the Haskell+  packages of this family. `haskell-release` builds and tests the package,+  builds the source and documentation archives, then tags the commit,+  pushes the tag and uploads both to Hackage. It leaves out the+  documentation of the internal library `integration`, whose file+  `haskoin-store:integration.txt` made Hackage refuse the archive, so a+  release needs no step by hand. `haskell-format` replaces `scripts/format`.+- **CI runs through the workflow that the packages share** in jprupp/tools,+  which also keeps the cache of the Nix build per release of nixpkgs.+  `check-stack-paths` from there replaces `scripts/check-local-deps.sh`.+- **`haskell-dev`, from jprupp/tools, is the fast loop of work on the+  code**: `build`, `test` and `docs`, without optimisation and with the+  tests in eight processes, about 75 seconds in place of four minutes. The+  five environments of `Haskoin.Store.IntegrationSpec`, each a node, a+  Valkey and a store in Podman, are now groups at the top of the module, and+  `haskell-dev.toml` names it, so that they run at the same time.++### Fixed+- **Races found by an audit of every protocol that runs at once**+  (`docs/concurrency.md`, new, has each protocol, its machine, its owner,+  the invariants and what changed):+  - a peer passed over during a stall was disconnected for a block it was+    asked for once another brought the store in sync (`Sync.finish`);+  - the refill ran the block store's in-sync check on the web thread; it+    goes through the mailbox now;+  - a peer could owe a block twice; a block of a branch the node had left+    could be imported; a revert published no best block;+  - two threads pruning views could let go of the newest block's view;+  - a store that was not live could empty the fleet's pool while one other+    store was live; a store emptied it where the documentation said it+    waits (`Unreadable`); a transaction in conflict could be lost for the+    fleet; expiry could withdraw a transaction that had just come back;+  - a request interrupted while it took the lock of an xpub left the job+    reserved for good; the listener of builds spun while Redis was down,+    grew without bound and woke requests for builds that never happened;+  - one slow answer from Redis made every store answer 503; background+    loops could die in silence; an error skipped the asking of published+    transactions;+  - announcements of transactions held up blocks on the block store's+    thread; the transactions waiting to be offered had no bound.+- **New transactions and blocks show at once again.** Since the pool moved+  to Redis, a transaction from a peer waited for the member's next turn,+  up to two seconds, before it was in the pool and listed; it is offered+  as soon as it comes now (`Haskoin.Store.Ingest`). A store that a block+  made well, as after a sync, took no turn for up to two seconds either:+  the block woke the member before the health check had run, and the+  member slept until its timer. It now takes a turn as soon as the store+  is well (`Haskoin.Store.Fleet.turn`). Measured in a downstream regtest+  suite: 1.3 to 2.0 seconds for a transaction against 0.3 to 0.4 on+  1.12.1, and 2.0 seconds for 101 blocks after a start against 0.01.+- **A store no longer falls behind the mempool of its node.** On a server,+  a Bitcoin store fell 17,000 transactions behind its node: chains of 24+  transactions that the node took in one second were offered child first+  and took 23 rounds; announcements were dropped from a full queue, or+  while the store was a block behind; and nothing asked the node again+  for what was missed. The path into the pool is a new machine (see+  Added).+- **A Bitcoin Cash Node with `--node-rpc` no longer waits half a minute+  when it stops.** The store kept its RPC connection open, and the node+  waited until it had been idle for `-rpcservertimeout`. Every RPC request+  closes its connection now.+ ## [1.16.7] - 2026-11-20  ### Fixed
README.md view
@@ -82,6 +82,7 @@ | Networks        | Bitcoin and Bitcoin Cash: mainnet, testnets and regtest                                     | | Addresses       | Balances, transactions and unspent outputs (UTXO) of any address, alone or many at once      | | Xpubs           | Balances, transactions and UTXO of extended public keys, for legacy, nested SegWit and native SegWit addresses, from the fleet's cache in Redis |+| Tokens          | CashTokens on Bitcoin Cash: the tokens of every output, token balances of addresses, and the holders, transactions and UTXO of each category | | Blocks and txs  | Lookup by hash, height or time; raw serialized forms; transactions of a block               | | Mempool         | One pool in Redis shared by the fleet, by arrival time, with replace-by-fee on BTC and expiry | | Formats         | JSON                                                                                         |@@ -161,7 +162,8 @@ ```  Give it either `--discover` or at least one `--peer`; with neither it turns-discovery on by itself. Data goes in a directory named after the network inside+discovery on by itself, unless it has your node as a peer through its RPC+(`--node-rpc`, which is meant to come with `--node-zmq`). Data goes in a directory named after the network inside `--dir`, so one data directory can hold several networks.  It needs a Redis or Valkey server, at `redis://localhost:6379` unless@@ -322,15 +324,17 @@  | Option | Environment | Default | Meaning | | --- | --- | --- | --- |-| `-n`, `--net` | `NET` | `bch` | Network: `btc`, `bch`, or a test network (see `--help`) |+| `-n`, `--net` | `NET` | `bch` | Network: `btc`, `bch`, the testnets `btctest4`, `bchtest4`, `bchtest3` and `btctest` (Bitcoin testnet3, deprecated), or regtest `btcreg`, `bchreg` | | `-d`, `--dir` | `DIR` | `~/.haskoin-store` | Data directory | | `--discover` | `DISCOVER` | off | Discover peers through DNS seeds and relayed addresses; on regtest it finds none, so name a `--peer` |-| `-p`, `--peer` | `PEER` | none | Connect to `HOST[:PORT]`; repeat for more, space-separated in `PEER`. On Bitcoin, only these peers are asked for their mempools when the pool fills again: whitelist the store on them (`whitebind=mempool@…`) |+| `-p`, `--peer` | `PEER` | none | Connect to `HOST[:PORT]`, or to the Unix socket `unix:PATH`; repeat for more, space-separated in `PEER` |+| `--peer-permission` | `PEER_PERMISSIONS` | none | A permission that the nodes of `--peer` grant the store with `-whitelist` or `-whitebind`, by its name there: `mempool`, `noban`, `relay`, `forcerelay`, `download`, `bloomfilter`, `addr`; repeat for more, comma- or space-separated in `PEER_PERMISSIONS`. With `mempool`, the store asks them for their mempools when it starts and when the pool fills again |+| `--foreign-peers` | `FOREIGN_PEERS` | off | The nodes of `--peer` are not yours. The store takes a node of yours at its word, and looks first at what only strangers name: it does not take a transaction that it cannot verify from them (see [Whose word is taken](#whose-word-is-taken)) | | `--max-peers` | `MAX_PEERS` | `20` | Most peers to connect to | | `--peer-timeout` | `PEER_TIMEOUT` | `30` | Seconds before a peer that is silent, or that owes blocks, is dropped | | `--block-stall` | `BLOCK_STALL` | `10` | Longest wait, in seconds, for a block from the syncing peer before another peer is asked too; a quick peer gets four of its recent gaps between blocks, at least 2 s | | `--block-ping` | `BLOCK_PING` | `5` | Seconds that a peer has to answer a ping to be asked for blocks, unless none answers in time |-| `--max-peer-life` | `MAX_PEER_LIFE` | `172800` | Seconds after which a peer is dropped, so connections rotate |+| `--max-peer-life` | `MAX_PEER_LIFE` | `172800` | Seconds after which a peer is dropped, so connections rotate. Not the peers of `--peer`, which are kept | | `--block-window` | `BLOCK_WINDOW` | `64` | Blocks to request from the syncing peer at a time |  ### Mempool@@ -358,7 +362,9 @@ | `--target-delay` | `TARGET_DELAY` | `25` | Milliseconds that a thread ready to run may wait for a core before the limit comes down | | `--request-queue` | `REQUEST_QUEUE` | `64` | Long requests that may wait for a slot; more are refused with 429 | | `--request-wait` | `REQUEST_WAIT` | `1` | Seconds that a long request may wait for a slot; then it is refused with 429 |-| `--node-rpc` | `NODE_RPC` | none | JSON-RPC URL of a full node, such as `http://user:password@127.0.0.1:8332/`, to publish transactions through, and to fill the shared mempool from again after it is emptied; without it, or when it does not answer, transactions go to the peers |+| `--node-rpc` | `NODE_RPC` | none | JSON-RPC URL of a full node, such as `http://user:password@127.0.0.1:8332/`, to publish transactions through, and to have that node as one more peer of the store: headers, blocks, transactions and the mempool come over it, and the store needs no peer-to-peer connection (`docs/node-peer.md`). Give `--node-zmq` with it: without it the store asks the node every five seconds, and warns of it in its log and in `/health`. Without `--node-rpc`, or when it does not answer, transactions go to the peers |+| `--node-rpc-socket` | `NODE_RPC_SOCKET` | none | Unix socket to send the requests of `--node-rpc` through, in place of the host and port of its URL; the URL still gives the user and password. Neither node listens on one itself: it is something that joins it to the node, such as socat |+| `--node-zmq` | `NODE_ZMQ` | none | Where the node of `--node-rpc` publishes over ZeroMQ, such as `tcp://127.0.0.1:28332` or `ipc:///run/node/zmq.sock`. Start the node with `-zmqpubhashtx` and `-zmqpubhashblock` at that address; for a Unix socket, Bitcoin Core wants it written `unix:/run/node/zmq.sock` and does not start with `ipc://` (`docs/node-peer.md`). The store then hears of a transaction and of a block as the node takes them, and does not have to ask (`docs/node-peer.md`). It needs `--node-rpc`, and is expected with it | | `--def-item-count` | `DEF_ITEM_COUNT` | `100` | Items in a list when no `limit` is given | | `--xpub-gap` | `XPUB_GAP` | `32` | Unused addresses kept after the last used one of each chain of an xpub; payments further away are not seen | | `--xpub-gap-init` | `XPUB_GAP_INIT` | `20` | Addresses looked at for an xpub with no transactions; an xpub with none used among them counts as unused |@@ -379,11 +385,11 @@  | Option | Environment | Default | Meaning | | --- | --- | --- | --- |-| `--redis-url` | `REDIS_URL` | `redis://localhost:6379` | Redis of the fleet, which every store needs: its tip, mempool and xpub cache |+| `--redis-url` | `REDIS_URL` | `redis://localhost:6379` | Redis of the fleet, which every store needs: its tip, mempool and xpub cache; `unix:PATH` for a Redis on a Unix socket | | `--redis-max-xpubs` | `REDIS_MAX_XPUBS` | `10000` | Size of the xpub cache, at least 1; evicted by cost to index again and by use |  Redis is how stores agree, and every store is a member of a fleet, even a-fleet of one. Every key starts with `hs2:<network>:`.+fleet of one. Every key starts with `hs3:<network>:`.  - **The block** is the newest that every live store has. A request is   answered from it, from the store's view of its database at that block.@@ -399,25 +405,108 @@   built again as requests ask for them. - **When the pool starts again**, after a reorganisation deeper than 50   blocks, the stores fill it again too.-- **Filling the pool again** works best with `--node-rpc`: each store reads-  its node's mempool (`getrawmempool`), 2,000 transactions every two-  seconds. Each also asks its peers for their mempools, once: every peer on-  Bitcoin Cash, whose nodes answer anyone, and on Bitcoin only the peers-  given with `--peer`, since Bitcoin Core disconnects a store that asks-  unless it whitelists it (`docs/fleet-mempool.md`).+- **Filling the pool again** is reading the whole mempool of a+  **source**, which a store does when it starts, whenever it may have+  missed a transaction, when the pool lost what it had, and every+  minute at least. With `--node-rpc` the node is a peer through its RPC, and a+  source, whatever the node allows its peers. A peer is one when its node takes the request,+  which a node closes the connection over unless it offers Bloom filters+  or whitelists the store with `mempool`. The store knows which from a+  model of each peer's node (`docs/fleet-mempool.md`): tell it what your+  nodes grant with `--peer-permission`. A store with no source says so in+  `/health`.+- **Your node as a peer, through its RPC and its ZeroMQ socket.** The+  peer-to-peer protocol is made for strangers: a node names what it+  takes to a peer at its own pace, Bitcoin Core about fourteen a second+  after a first batch, so that in a burst a store is behind its node+  until it next reads the mempool, every thirty seconds. With+  `--node-rpc` and `--node-zmq` together, the store has that node as+  one more peer, with no peer-to-peer connection to it: it asks it what+  it asks any peer, and the answers come from the RPC and from what the+  node publishes (`-zmqpubhashtx`, `-zmqpubhashblock`). It hears of a+  transaction and of a block as the node takes them. With `--node-rpc`+  alone the node is a peer too, and the store asks it every five+  seconds for its best block and, while no other node of yours is a+  peer, for its mempool. That works, costs the node a reading of its+  whole mempool each time, and makes the store warn in its log and in+  the `warnings` of `/health`: the two are meant to be given together. That peer counts+  in `/health`, it is a node of yours, and a store can run on it alone,+  with no `--peer` and no `--discover`. The ZeroMQ socket only+  publishes, has no password, and drops what a slow subscriber does not+  read: keep it on the machine of the node, and the store reads the+  mempool again whenever something may have been lost. The store speaks+  the protocol itself, and needs no ZeroMQ library.+  [docs/node-peer.md](docs/node-peer.md) has the whole of it.+- <a id="whose-word-is-taken"></a>**Whose word is taken.** A store+  verifies no script: it takes a transaction because a node took it.+  That is right of a node of yours, and the store takes the nodes of+  `--peer`, and the node of `--node-rpc`, for yours. Any other peer is a+  stranger, as every peer found by `--discover` is. Of what only+  strangers name, the store verifies what it can, which is every+  signature of a coin locked to one key:++  | A transaction that only strangers name | What the store does |+  | --- | --- |+  | Every signature verifies | Takes it |+  | A signature does not verify, it spends more than it has, or its tokens come from nowhere | Refuses it, with all that spends from it (`ingest.given_up.forged`) |+  | It spends a coin locked by a script, such as a multisig wallet | Holds it until a node of yours names it, for twenty minutes, and does not show it (`ingest.given_up.not_vouched`) |++  The peers that you give are kept. A peer of `--peer`, and the node of+  `--node-rpc`, is never dropped for its age, is tried again every ten+  seconds at most when its connection ends, for as long as it takes,+  and has a slot kept for it meanwhile: with `--discover` too, a peer+  found on the network never takes the place of one of yours. The only+  reason for one of them to have no connection is that it takes none.++  So a store with a node of yours among its peers misses nothing, and a+  store with only strangers shows a spend of a script when a block+  confirms it. The node of `--node-rpc` is a node of yours, always. If the nodes that you give with `--peer` are not yours,+  say so with `--foreign-peers`. Without this a stranger could show a+  wallet a payment that was never made. The store says in its log, of+  each peer that connects, which of the two it takes it for: check that+  it knows your node. - **`/events` is the same stream on every store**, written to Redis with   each change of the pool and each move of the tip. - **Xpubs** are cached for the whole fleet (`docs/xpub-indexing.md`).  ### Health check +A store is healthy when it has the blocks of the network: its database+keeps up with the headers, the best header is recent, it has enough+peers, and its database takes writes. `/health` answers 503 otherwise.++Nothing of the mempool decides it. A store that is at the head of the+chain answers every request rightly from what it has. `/health` still+says when the last transaction came and how many are asked for and not+received, each with an `ok` of its own, and the health of the store does+not depend on them.++What to know of the mempool is in the `mempool` object of `/health`:++| Field | What it says |+| --- | --- |+| `sources` | How many nodes the store can read a whole mempool from |+| `sync` | How the mempool stands with the mempools of your nodes, in one word. `syncing`: the store has not yet read your node and taken in all that it named, since it started or since Redis lost its data, and shows fewer unconfirmed transactions than the node meanwhile; for twenty seconds at least after a start. `synced`: it has. `unknown`: the store has no node of yours to read a whole mempool from, only strangers or nobody, and cannot tell |+| `known`, `held` | How many transactions are on their way to the mempool, and how many of them the store holds |+| `dirty` | Whether the store gave something up and is about to read its sources again |++To give a new store traffic only once its mempool is full, wait for+`sync` to say `synced`. A store that has only strangers for peers never+says it: what a stranger names is nothing to measure a mempool against.++`/health` also has `warnings`, when there are any: what you should put+right in how the store is set up, a sentence each. A warning decides+nothing, and a store with warnings is as healthy as one without. There+is one so far: the store has the RPC of its node (`--node-rpc`) and not+its ZeroMQ socket (`--node-zmq`). The store logs the same as a warning.+ | Option | Environment | Default | Meaning | | --- | --- | --- | --- | | `--max-lagging-blocks` | `MAX_LAGGING_BLOCKS` | `3` | Most blocks the index may lag behind the headers |-| `--max-pending-txs` | `MAX_PENDING_TXS` | `10000` | Most transactions requested from peers and not received yet |+| `--max-pending-txs` | `MAX_PENDING_TXS` | `10000` | Most transactions requested from peers and not received yet, for the check `pending-txs`, which does not decide the health of the store | | `--min-peers` | `MIN_PEERS` | `1` | Fewest connected peers | | `--block-timeout` | `BLOCK_TIMEOUT` | `14400` | Most seconds since the last block |-| `--tx-timeout` | `TX_TIMEOUT` | `1800` | Most seconds since the last transaction |+| `--tx-timeout` | `TX_TIMEOUT` | `1800` | Most seconds since the last transaction, for the check `last-tx`, which does not decide the health of the store | | `--health-check-interval` | `HEALTH_CHECK_INTERVAL` | `1` | Seconds between checks; there is one at each new block too |  ### Metrics and logging@@ -632,6 +721,7 @@ | Mempool | `/mempool` | | Addresses | `/address/:addr/{transactions,transactions/full,balance,unspent}` and the multi-address forms `/address/{transactions,transactions/full,balances,unspent}?addresses=…` | | Xpubs | `/xpub/:xpub`, `/xpub/:xpub/{transactions,transactions/full,balances,unspent}`, `DELETE /xpub/:xpub` (drop from cache); `derive=legacy\|compat\|segwit` picks the address type (`normal`, the old name of `legacy`, still works) |+| Tokens | `/address/:addr/tokens`, `/token/:category/{holders,unspent,transactions}`; outputs, inputs and UTXO have a `token` field on Bitcoin Cash (`docs/cashtokens.md`) | | Network | `/peers`, `/health` (503 when unhealthy, Redis included), `/dbstats` | | Events | `/events`, as JSON lines over HTTP or as a WebSocket; `after=` resumes, and a WebSocket client can filter by address, xpub or Bloom filter | | Blockchain.info | `/blockchain/multiaddr`, `/blockchain/balance`, `/blockchain/rawaddr/:addr`, `/blockchain/unspent`, `/blockchain/rawtx/:txid`, `/blockchain/rawblock/:hash`, `/blockchain/latestblock`, `/blockchain/unconfirmed-transactions`, `/blockchain/export-history`, `/blockchain/q/…` |@@ -639,6 +729,85 @@ Turn off the Blockchain.info endpoints with `--no-blockchain-info`. The xpub endpoints are always on: they answer from the fleet's cache in Redis. +### Tokens of Bitcoin Cash++Since May 2023 an output on Bitcoin Cash can hold tokens (CashTokens): a+fungible amount of one category, a non-fungible token, or both. The store+reads them from every output, keeps a token balance for each address and+category, and indexes each category. On Bitcoin there are no tokens: the+token endpoints answer with empty lists, and the JSON has no `token` field.++The token balances of an address, one per category:++```sh+curl http://localhost:3000/address/bitcoincash:qz.../tokens+```++```json+[+  {+    "address": "bitcoincash:qz...",+    "category": "084c...93ae",+    "confirmed": "1000",+    "unconfirmed": "0",+    "nfts": 0,+    "utxo": 1,+    "txs": 2,+    "received": "2000"+  }+]+```++- **Amounts are strings**, since a category can have up to 2^63 − 1 tokens,+  more than a JSON number holds exactly in many languages.+- **They count the mempool**, as the balance of an address does: `confirmed`+  is what blocks hold and the mempool does not spend, and `unconfirmed` what+  the mempool adds. Their sum is what the address holds now.+- **`nfts`** is the number of non-fungible tokens, **`utxo`** the number of+  unspent outputs that hold the category, **`txs`** the number of+  transactions that moved it to or from the address, and **`received`**+  every fungible token that the address ever received, spent ones included.++The category is the id of the transaction whose output 0 the first+transaction of the tokens spent. Its endpoints:++```sh+curl 'http://localhost:3000/token/084c...93ae/holders?limit=10&offset=0'+curl 'http://localhost:3000/token/084c...93ae/unspent?limit=10'+curl 'http://localhost:3000/token/084c...93ae/transactions?limit=10'+```++- **`/holders`**: a token balance for each address that holds the+  category, in the order of the addresses' bytes, a page at a time with+  `limit` and `offset`. Tokens in outputs without an address are in no+  one's balance.+- **`/unspent`**: the unspent outputs that hold it, newest first: those of+  the mempool, then those of blocks that the mempool does not spend. Pages+  as an address's unspent outputs, with `limit`, `offset` and `height`.+- **`/transactions`**: the transactions that created, moved or burned it,+  newest first, those of the mempool first, paged the same way.++Every output, input (the output it spends) and unspent output has a `token`+field on Bitcoin Cash: `null` without tokens, and otherwise the tokens as the+CashTokens test vectors and Bitcoin Cash Node's RPC write them:++```json+"token": {+  "category": "084c...93ae",+  "amount": "1000",+  "nft": {"capability": "minting", "commitment": "01"}+}+```++`nft` is there only for an output that holds a non-fungible token. The+tokens are written at the front of an output's script, so its `pkscript`+has them too. The Haskell client of+[haskoin-store-data](https://github.com/jprupp/haskoin-store-data) has a+request for each endpoint (`GetAddrTokens`, `GetTokenHolders`,+`GetTokenUnspent` and `GetTokenTxs`), and `scriptTokens` reads the tokens of+a script. `swagger.yaml` describes every field, with an example of each+answer.+ ## How it works  ```@@ -738,8 +907,7 @@ 189 to 148 ms, and from 433 to 398 ms at the tip. Without the reads that checked a mined block, in a later set, a block of chains of transactions went from 161 to 138 ms. These were measured while the database still had-a mempool of its own, which it no longer has. `docs/block-import.md` has-the sets of numbers.+a mempool of its own, which it no longer has.  A store of mainnet gains more than the benchmark shows. In the benchmark a read is 30 microseconds of CPU, as the files are in memory. On the@@ -748,9 +916,8 @@ at a time: its reads are slower than the benchmark's, and gain more from being made together. -`docs/block-import.md` has the design, what was measured, and what is left.-`docs/block-import.md` says what could bring a block well below a-second, and what each step would do to reads.+`docs/block-import.md` has the design, what was measured, and what was+not done, with the reason for each. The stages are timed for StatsD: see [StatsD](#statsd).  ### Publishing@@ -781,13 +948,17 @@   unless there is an RPC to send it over; and so are the transactions that   were measured to cost the store its connections. - **Whitelist the store on your nodes** (`-whitelist` in Bitcoin Core and-  Bitcoin Cash Node). A node announces to a whitelisted peer without+  Bitcoin Cash Node), and tell the store what they grant+  (`--peer-permission`). A node announces to a whitelisted peer without   delay, so the transaction shows in the store at once; otherwise Bitcoin-  Core takes five seconds on average. And a node never closes the+  Core takes five seconds on average. When a node takes transactions+  faster than it names them, which for Bitcoin Core is more than+  fourteen a second for a while, the store has them at its next reading+  of the node's mempool, every thirty seconds while transactions come. And a node never closes the   connections of a whitelisted peer. -`docs/publishing.md` has the design, what was measured on Bitcoin Core and-Bitcoin Cash Node, and how it differs from earlier versions.+`docs/publishing.md` has the design, and what was measured on Bitcoin+Core and Bitcoin Cash Node.  ### The database @@ -808,23 +979,54 @@ - **Each request reads one snapshot** of the database, at the fleet tip, so   everything in an answer is of the same moment. -`docs/one-fleet.md` has the reasons, and `docs/fleet-mempool.md` the pool-in detail and its tests.+`docs/README.md` lists every page about how the store works inside, the+question that each answers, and the words they use. Start with+`docs/one-fleet.md`, which has the reasons, then `docs/tip-first.md`,+which says what happens when a block arrives, and+`docs/fleet-mempool.md`, the pool in detail and its tests.+`docs/concurrency.md` says, for everything that runs at the same time,+in a store and across a fleet, who may change what, and why nothing+breaks. The layout of the keys is described in `Haskoin.Store.Database.Types`.  ### Upgrading an existing database -This is version 23 of the database. The store migrates an older database+This is version 24 of the database. The store migrates an older database the first time it opens it. **There is no way back**: an older store cannot open the database afterwards, so take a copy first. +**Upgrading to 2.0.0**, which brings the tokens of Bitcoin Cash:++- **Take a copy of the database first.** The migration from version 23 is+  the one below; on Bitcoin Cash it reads every block since May 2023, which+  takes hours, and carries on where it was if it is stopped.+- **Upgrade every store of a fleet together.** The stores of 2.0.0 keep+  the shared pool under keys that start with `hs3:`, where older stores+  use `hs2:`: on one Redis the two are separate fleets, each with a pool+  of its own, and their answers differ until all are upgraded. The new+  pool starts empty and fills from the nodes. Once no older store runs,+  the keys under `hs2:` are of no use: flush that Redis, or delete them+  (`redis-cli --scan --pattern 'hs2:*' | xargs redis-cli unlink`).+- **Clients** that do not know the `token` field ignore it; on Bitcoin the+  JSON is as it was.+ | From | What the migration does | How long | | --- | --- | --- | | 18, 19 | Not migrated: sync again | | | 20 | Takes the unconfirmed transactions out of the chain's indices; the pool gets them again from the peers | Seconds to minutes | | 21 | Reads every transaction and writes nearly every one again | Many hours for Bitcoin | | 22 | Writes the new version | At once |+| 23 | Bitcoin Cash: indexes the outputs that hold tokens, under their addresses and in the token indexes, from the upgrade of May 2023 (`docs/cashtokens.md`). Others: writes the new version | Bitcoin Cash: hours, it reads every transaction since then. Others: at once | +**From 23 to 24 on Bitcoin Cash, outputs with tokens get their+addresses.** Until version 24 an output that holds tokens had no address,+so the addresses that held tokens were missing their history and part of+their balance. The migration walks the blocks since CashTokens began and+adds them, with the token balances and the indexes of each category. It+works in batches of 200 blocks, each written at once with its place, so+it can be stopped and carries on where it was. The four new column+families keep an older store out, as `merge-operators` does.+ **From 22 to 23 nothing in the database changes, and it is still one way.** From version 23 a block writes the balances of its addresses and the spenders of the outputs that it spends as RocksDB merge records, which@@ -875,6 +1077,20 @@   microseconds where it took 11.5. Lists by address and by xpub cost the   same as before. +### Tokens++An output with tokens has the address of its locking script, read by+haskoin-core 3.0 after it takes off the token prefix, so the coins of one+script stay under one address with or without tokens. Importing a block+writes what its transactions do to tokens next to what they do to coins:+the token balance of each address and category, and for each category its+transactions and its unspent outputs, in column families of their own. The+holders of a category are the same balances under a second key, in a+column family of their own, so that listing them reads no other address. The shared mempool in Redis keeps the+same token entries for the transactions of the pool, which the endpoints+lay over those of the blocks. `docs/cashtokens.md` has the details, and why+each part is built as it is.+ ### Extended public keys  **The gap.** Addresses are derived up to an exact gap: every address up to@@ -943,7 +1159,12 @@ | `Haskoin.Store.XPub.Service` | The door to the fleet's cache of xpubs: a hit answers, a miss asks the indexer | | `Haskoin.Store.Fleet.Member`, `Haskoin.Store.Fleet.XPub` | A fleet, and its cache | | `Haskoin.Store.Fleet`, `Haskoin.Store.Fleet.Pool` | The rules of the fleet tip and of the pool, as pure decisions |-| `Haskoin.Store.Fleet.Redis` | Those rules carried out in Redis, one Lua script per step |+| `Haskoin.Store.Fleet.Redis` | Those rules carried out in Redis, each change in one step |+| `Haskoin.Store.Fleet.Atomic` | A decision made in Haskell from what Redis says, and carried out only if Redis still says the same |+| `Haskoin.Store.Fleet.Atomic.Cells` | What a write does to one cell, said once, with the proof that a decision sees its own writes as the model of Redis has them |+| `Haskoin.Store.Fleet.Atomic.Keys` | The questions and writes of a decision, with the kind of each key in its type |+| `Haskoin.Store.Fleet.Pool.Decide` | Every change to the shared mempool, as such decisions |+| `Haskoin.Store.Fleet.XPub.Decide` | Every change to the cache of extended public keys, the same way | | `Haskoin.Store.Web`, `Haskoin.Store.Web.Events` | The web server, and `/events` | | `Haskoin.Store.Web.Router` | Routing of requests to handlers, directly over WAI | | `Haskoin.Store.Web.Docs` | The API reference that the server serves at its root |@@ -991,15 +1212,44 @@  The checks are: how far the index is behind the headers, the age of the last block and of the last transaction, the transactions waiting to be-imported, the connected peers, and Redis (`"redis"` in the JSON).+imported, the connected peers, the database, and Redis (`"redis"` in the+JSON). -**Writes to the database** are in `"database"`: `"writes"` is `flowing`,-`delayed` or `stopped`, with `"pending-compaction-bytes"` and-`"delayed-write-rate"` (bytes a second, 0 when not delayed). RocksDB-delays writes and then stops them when its compactions fall behind-([RocksDB](#rocksdb)); the store reads this every five seconds, and logs a-warning when writes are delayed or stopped and a line when they recover.+**Each check says in words what it found**, in its `"text"`, and the+`"text"` at the top says what that means for the whole store, such as: +> The store is not healthy. The database is 4 blocks behind the best+> header, at height 688,798, more than the 2 allowed: the store is+> syncing, or cannot import blocks fast enough.++They are for people looking at a store; a program should read `"ok"` and+the numbers, as the wording may change.++**The mempool of the nodes** is in `"mempool"`: `"sources"` is how many+things the store can read a whole mempool from again, `"dirty"` whether it+may have missed transactions and has not read a source since, and `"known"`+and `"held"` how many transaction ids are on their way to the shared+mempool and how many are held. It is no check and has no `"ok"`: a store+with no source is healthy. But a node announces a transaction to a peer+once, so such a store shows fewer unconfirmed transactions than its node+after it missed some, until a block has them, and the `"text"` at the top+says so. A source is the RPC of a node (`--node-rpc`), or a peer whose node+gives its mempool when asked: for Bitcoin Core, one that whitelists the+store with the permission `mempool`, named with `--peer` and declared with+`--peer-permission mempool` (`docs/mempool-ingestion.md`).++**The database** is in `"database"`, as RocksDB reports it every five+seconds: `"writes"` is `flowing`, `delayed` or `stopped`, with+`"pending-compaction-bytes"` and `"delayed-write-rate"` (bytes a second, 0+when not delayed), and the work that explains it: `"running-compactions"`,+`"running-flushes"`, `"immutable-memtables"` (full tables in memory waiting+to be flushed), `"size-bytes"` and `"live-data-bytes"` of the files, and+`"background-errors"` since the database opened. RocksDB delays writes and+then stops them when its compactions fall behind ([RocksDB](#rocksdb)).+Only stopped writes fail the check, as the store then imports nothing. The+store logs a warning when writes are delayed or stopped and a line when+they recover.+ - **Stopped writes make the store unhealthy:** it imports nothing until   they flow again. - **Delayed writes do not.** RocksDB slows writes for seconds at a time@@ -1080,6 +1330,46 @@ | `fleet.cache.*` | What a server of a fleet does with the fleet's cache of xpubs | | `rts.*` | GHC's garbage collector | +Every name starts with the prefix and the network: `web.reruns` of a+store of Bitcoin is `haskoin_store.btc.web.reruns`.++With `--statsd-aggregates` the store also works out statistics of each+metric, every second, and sends those: a counter's count as+`stats.counters.<metric>.count`, a gauge as `stats.gauges.<metric>`,+and of a timing its count, sum, mean, longest, shortest and+percentiles, as `stats.timers.<metric>.count`, `.sum`, `.mean`,+`.upper`, `.lower`, `.upper_90` and so on+([statsd-rupp](https://github.com/jprupp/statsd-rupp) has all of+them). `--statsd-no-events` leaves the single samples out, so that only+the statistics are sent: that is for a collector that keeps every line+it is given.++The metrics of the web server:++| Metric | Kind | Meaning |+| --- | --- | --- |+| `web.<kind>` | timing | Milliseconds to answer a request of one kind, one metric for each: `web.address_balance`, `web.xpub_balances`, `web.transaction`, `web.blockchain_multiaddr` and so on |+| `web.server_errors` | counter | Requests that failed with a server error |+| `web.client_errors` | counter | Requests that failed with a client error |+| `web.reruns` | counter | Requests answered again because a cached xpub that they read changed meanwhile |+| `web.events_connected` | gauge | Clients connected to the stream of events |++The reads of the database, each a count of the items read:++| Metric | Kind | Meaning |+| --- | --- | --- |+| `db.best_block` | counter | Reads of the best block |+| `db.blocks` | counter | Blocks |+| `db.txs` | counter | Transactions |+| `db.balances` | counter | Balances |+| `db.unspents` | counter | Unspent outputs |+| `db.address_txs` | counter | Address transactions |+| `db.xpub_balances` | counter | Xpub balances |+| `db.xpub_unspents` | counter | Xpub unspent outputs |+| `db.xpub_txs` | counter | Xpub transactions |+| `db.xpub_tx_count` | counter | Xpub transaction counts |+| `db.iterators` | gauge | Iterators open on RocksDB |+ The metrics of the block store:  | Metric | Kind | Meaning |@@ -1112,6 +1402,12 @@  | Metric | Kind | Meaning | | --- | --- | --- |+| `ingest.settled` | counter | Transactions that peers named and that the pool decided on, or already had |+| `ingest.given_up.REASON` | counter | Transactions given up on their way to the pool, by reason: `node_has_not`, `unanswered`, `no_room`, `peer_gone`, `waited_too_long`, `unjudged`, `forged`, `not_vouched` (`docs/mempool-ingestion.md`). All but the first and the last two make the server read its sources again |+| `ingest.dropped` | counter | Messages of peers dropped because the path into the pool was behind; the sources are read again |+| `ingest.ids` | gauge | Transaction ids on their way to the pool: wanted, asked for, or held |+| `ingest.pending` | gauge | Transactions asked of peers and not received, what `/health` counts |+| `ingest.held` | gauge | Transactions held: being offered, or waiting for one that they spend from | | `fleet.cache.hits` | counter | Requests about an xpub whose balances the cache gave | | `fleet.cache.misses` | counter | Requests about an xpub that the cache did not have | | `fleet.cache.builds` | counter | Entries that this server built, or added addresses to |@@ -1187,6 +1483,13 @@ | `web.cap.<route>.held` | timing | Milliseconds that a request held its slot, to the last byte | | `web.cap.<route>.refused` | counter | Requests refused | +`tools/grafana/haskoin-store.json` is a Grafana dashboard for these,+read from InfluxDB, for a store that sends its own statistics+(`--statsd-aggregates --statsd-no-events`) to+[Telegraf](https://github.com/influxdata/telegraf). `docs/grafana.md`+says what it needs, how to install it, and what becomes of the store's+statistics when Telegraf sums them up a second time.+ ### Database statistics  `/dbstats` returns the memory that RocksDB uses for each column family, and@@ -1263,6 +1566,8 @@ Query a running server with `haskoin-store-data`:  ```haskell+{-# LANGUAGE OverloadedStrings #-}+ import Data.Default (def) import Haskoin (btc, textToAddr) import Haskoin.Store.WebClient@@ -1278,6 +1583,30 @@ `apiCall` answers `Right` the result or `Left` an error. `apiEvents` listens to `/events`, and `apiEventsAfter` takes up from an event. +The tokens of Bitcoin Cash, by address and by category:++```haskell+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}++import Data.Default (def)+import Haskoin (bch, hexToTxHash, textToAddr)+import Haskoin.Store.Data (SerialList (..), TokenBalance (..))+import Haskoin.Store.WebClient++main :: IO ()+main = do+  let cfg = def {net = bch}+      Just addr = textToAddr bch "bitcoincash:qz…"+      Just category = hexToTxHash "084c…93ae"+  -- the fungible tokens of each category that the address holds now+  Right (SerialList balances) <- apiCall cfg (GetAddrTokens addr)+  mapM_ (\b -> print (b.category, b.confirmedTokens + b.unconfirmedTokens)) balances+  -- the first page of the holders of a category+  Right (SerialList holders) <- apiCall cfg (GetTokenHolders category Nothing (OffsetParam 0))+  print (length holders)+```+ The client appends the network name to `host`, as in the layout of api.haskoin.com. To reach your own server, put it behind a proxy that maps `/btc/` (or the name of your network) to it.@@ -1289,6 +1618,9 @@ - The functions of `Haskoin.Store.Database.Query` query the chain in its   database in `IO`, such as `getBalance store.db addr`, and `chainRead`   gives them as a `StoreRead`.+- The token queries of a `StoreRead` (`getAddressTokens`,+  `getTokenHolders`, `getTokenTxs` and `getTokenUnspents`) answer for the+  tokens of Bitcoin Cash. - Subscribe to `Store.pub` to receive `StoreEvent`s.  Every module has Haddock documentation; build it with `stack haddock`.@@ -1313,15 +1645,90 @@ ```sh stack build --test --no-run-tests stack test                     # includes a 6000-block heap-growth test-scripts/format                 # ormolu, the code style used here+haskell-format                 # ormolu, the code style used here (jprupp/tools) scripts/bench-web.sh           # load-test the API with wrk stack bench haskoin-store:bench:haskoin-store-bench \   --ba 'import +RTS -N4 -A64m' # time the import of full blocks scripts/heap-profile-summary.py FILE.hp  # what grew in a heap profile-scripts/check-local-deps.sh    # what CI checks: no local paths in stack.yaml+check-stack-paths              # what CI checks: no local paths in stack.yaml scripts/install-system-libraries.sh  # the C libraries, on Ubuntu or Debian+haskell-release --dry-run      # build and check a release, upload nothing ``` +`haskell-format`, `check-stack-paths`, `haskell-release` and `haskell-dev`+are scripts of [jprupp/tools](https://github.com/jprupp/tools), shared by the+Haskell packages of this family. Clone that repository once and put its+folder on your `PATH`, for example in `~/.bashrc`; a terminal opened before+the change needs `source ~/.bashrc`.++```sh+git clone https://github.com/jprupp/tools.git ~/Source/tools+echo 'export PATH="$HOME/Source/tools:$PATH"' >> ~/.bashrc+```++The Stack commands build the store as it is released, with optimisation,+which takes minutes. For the time between two commits there is a faster+loop, `haskell-dev`. Run it from the top folder of haskoin-store:++```sh+haskell-dev test                     # build, then run all the tests+haskell-dev test Fleet.Redis         # the specs with Fleet.Redis in their module name+haskell-dev test Fleet.Redis Web     # the specs of several modules+haskell-dev test --match "/Haskoin.Store.Integration/Regtest Bitcoin Core/"+                                     # one path, in one process+haskell-dev test --seed 12345        # run a failure again+haskell-dev test --jobs 4            # fewer processes, to save memory+haskell-dev build                    # build without optimisation+haskell-dev docs                     # build the documentation and check its comments+```++`test` builds first, so a separate `build` is not needed. A run of all the+tests takes about 70 seconds in eight processes, against about four minutes+for `stack test`. `haskell-dev.toml` names the slow spec modules,+`Haskoin.Store.Integration` (`test/Haskoin/Store/IntegrationSpec.hs`), whose+five environments then run at the same time, each with its own node, Valkey+and store in Podman, and `Haskoin.Store.Download`, the downloads of a store+from real nodes, one of them frozen with `SIGSTOP` to hang as a bad peer+does.++The tests name no address or port of the machine. The nodes, Valkey, and+openssl and curl for the test of HTTPS, run in containers of+[podman-test](https://github.com/jprupp/podman-test), reached through Unix+sockets of their pods; the web servers of the store listen on Unix sockets+of their own, which the tests and the client of haskoin-store-data reach;+and what stands for a peer in memory is named by a Unix socket. Nothing in+the tests uses a Bitcoin Core or a Bitcoin Cash Node of the machine.++When a test fails, the output gives the seed: run the+test again alone with `--seed` and `--match` on its path, which prints the+usual output of hspec.++The integration tests, and those of the fleet, need rootless Podman (see+below); without it they are pending, and the others run. Now and then a test+fails with `InsecureConnectionDenied`, an exception of the HTTP client, and+passes when run again with the same seed: its cause is not known yet, so run+such a failure again before taking it for a fault of a change.++Do not mix the two kinds of build in one folder. When no source has changed,+Stack does not see that the flags have, and keeps the objects of the other+build: a plain `stack build` or `stack test` right after `haskell-dev build`+uses code without optimisation. Only what runs from this folder uses it, such+as the tests and `stack exec haskoin-store`: a package that depends on+haskoin-store builds its own copy. After the next change to a source,+everything compiles again. `stack bench` configures the package again and+compiles it with optimisation. Never time the store with `haskell-dev`: the+benchmarks run with `stack bench`.++A release is made with `haskell-release`, once the version in+`package.yaml` is bumped, its CHANGELOG entry written and the commit pushed.+It builds and tests the package, builds the source and documentation+archives, and only if all of that works tags the commit, pushes the tag and+uploads both archives to Hackage. It uploads the documentation itself,+because `stack upload --documentation` fails here: the internal library+`integration` gets a documentation file named `haskoin-store:integration.txt`,+and Hackage refuses a colon in a file name. The script leaves the+documentation of the internal libraries out, as they are only for the tests.+ `stack.yaml` must pin released versions, or git commits, of every dependency. Pointing `extra-deps` at a sibling checkout such as `../haskoin-core` is fine for@@ -1334,15 +1741,22 @@ exact gap, spends and change, mempool order, multiaddr counts, reorganisations, and that the cache answers exactly like the database on every xpub endpoint. +- The containers run through+  [podman-test](https://github.com/jprupp/podman-test), in a pod for each+  environment. The store reaches Valkey, the RPC of the node and the node+  itself through Unix sockets of the pod (`--redis-url unix:PATH`,+  `--node-rpc-socket` and the peer `unix:PATH`), so the pod has no network,+  and environments that run at once never meet. - They are skipped if Podman cannot run containers, or if-  `HASKOIN_STORE_NO_PODMAN` is set.+  `PODMAN_TEST_SKIP` is set. - The first run builds the image `localhost/haskoin-store-test`, which needs   network access: Ubuntu 26.04 pinned by digest, Valkey from a fixed snapshot of   the Ubuntu archive, and the release tarballs of both nodes, checked against   SHA-256 hashes pinned in `integration/Haskoin/Store/Integration/Image.hs`. No   third-party image is used.-- Containers are removed when the tests end, data lives in tmpfs mounts and-  under `/dev/shm`, and every container has a memory limit.+- Pods are removed when the tests end, and those of a run that was killed+  by the next run. Data lives in tmpfs mounts and under `/dev/shm`, and every+  container has a memory limit. - Set `HASKOIN_TEST_LOG=1` to print the log of the store under test.  The test suite runs with at most four cores and a 4 GiB heap, so that a@@ -1386,11 +1800,54 @@ and six, each in a table file of its own, and then the same keys once compacted. +### Measurements for moving the fleet tip++`haskoin-store-bench decide [TXS [POOL [INPUTS [OUTPUTS [RIVALS [WATCHED]]]]]]`+(`bench/Decide.hs`) times what the move of the fleet tip over a block+costs to decide, without Redis: transactions that are offered wait for as+long as a move takes (`docs/concurrency.md`, "The floor"). It fills the+pure model of Redis with a pool of 20,000 transactions and decides the+move over a block of 4,000 of them, some in chains, as on Bitcoin. It+prints the time of each pass over+the decision, its answers and writes, the time for each of those in a+pass, which is the number to compare between two builds, and what was+allocated. Run it with `+RTS -T -A64m`: `-T` for the last, and `-A64m`+because a store runs with it. Without it the collector runs three+hundred times in a move, and each time goes over the model of Redis,+which a store does not have in its memory: the move then takes nearly+three times as long, and most of what is timed is the collector. With+RIVALS, the block+is also in conflict with so many transactions of the pool, which leave+with what spends from them. With WATCHED, so many transactions in a+hundred have their addresses watched by a cached extended public key.++It times the move twice: taking everything out of the pool in one step,+as a move that undoes a block does, and marking what leaves, as every+other move does, with the taking out that follows, two hundred+transactions at a time (`docs/fleet-mempool.md`, "The tip first").++On a desktop of 2026 the move over 4,000 transactions of three inputs and+three outputs is decided in about 0.8 seconds: four passes, one of which+goes through the whole block and takes 0.66 seconds of them, for 94,000+answers and 205,000 writes, which is about two microseconds for each in+that pass. It took four times as long in+eight passes, five of them through the block, before the move named its+questions ahead and while the pool worked out which transactions could+be replaced by fee (`docs/concurrency.md`, "The floor").++Marking the same 4,000 transactions is decided in 0.12 seconds, with+20,000 answers and 8,000 writes, and the taking out that follows takes+0.8 seconds in twenty steps of 45 milliseconds at most. With a cached+key at every address, the move in one step takes 2.7 seconds, the+marking the same 0.12, and the taking out 1.3 seconds in steps of 65+milliseconds, one of 0.2 seconds in three runs: what a block costs the+tip no longer grows with the keys that a server has cached.+ ### Contributing  Pull requests are welcome. -- Format the code with `scripts/format` (Ormolu), and keep every line of+- Format the code with `haskell-format` (Ormolu, from jprupp/tools), and keep every line of   code shorter than 120 columns. - Put scripts in files of their own rather than embedding them: Lua for   Redis under `src/Haskoin/Store/Fleet/lua/` or `src/Haskoin/Store/XPub/lua/`,
app/Main.hs view
@@ -12,6 +12,7 @@ import Data.Default (Default (..)) import Data.List (intercalate) import Data.Maybe (fromMaybe)+import Data.Set qualified as Set import Data.String.Conversions (cs) import Data.Text qualified as T import GHC.Conc (getNumProcessors)@@ -22,6 +23,7 @@   ) import Haskoin.Node   ( LogLevel (..),+    Permission (..),     logInfo,     withConnection,     withLogger,@@ -40,6 +42,7 @@   ) import Haskoin.Store.Common (loopForever) import Haskoin.Store.Database.Stalls (defaultBackgroundJobs)+import Haskoin.Store.NodeZmq (parseZmqAddress) import Haskoin.Store.Runtime (runtimeMetrics) import Haskoin.Store.Startup (StartupError (..), checkReadable, makeDataDirectory) import Haskoin.Store.Web.Listen (parseMode, systemdSocket, withUnixSocket)@@ -111,6 +114,8 @@     net :: !String,     discover :: !Bool,     peers :: ![String],+    peerPermissions :: ![Permission],+    foreignPeers :: !Bool,     version :: !Bool,     debug :: !Bool,     maxPendingTxs :: !Int,@@ -143,6 +148,8 @@     healthCheckInterval :: !Int,     accessLog :: !Bool,     nodeRpc :: !String,+    nodeRpcSocket :: !String,+    nodeZmq :: !String,     tlsCert :: !String,     tlsKey :: !String,     bloom :: !Bool,@@ -179,6 +186,10 @@     env "DISCOVER" False parseBool   peers <-     env "PEER" [] (pure . words)+  peerPermissions <-+    env "PEER_PERMISSIONS" [] (mapM parsePermission . words . map (\x -> if x == ',' then ' ' else x))+  foreignPeers <-+    env "FOREIGN_PEERS" False parseBool   debug <-     env "DEBUG" False parseBool   maxPendingTxs <-@@ -241,6 +252,10 @@     env "ACCESS_LOG" False parseBool   nodeRpc <-     env "NODE_RPC" "" pure+  nodeRpcSocket <-+    env "NODE_RPC_SOCKET" "" pure+  nodeZmq <-+    env "NODE_ZMQ" "" pure   bloom <-     env "BLOOM" True parseBool   noWeb <-@@ -327,6 +342,19 @@   "0" -> Just False   _ -> Nothing +-- | A permission that a node grants with @-whitelist@ or @-whitebind@, by+-- the name that Bitcoin Core and Bitcoin Cash Node give it there.+parsePermission :: String -> Maybe Permission+parsePermission str = case map toLower str of+  "bloomfilter" -> Just PermBloomFilter+  "relay" -> Just PermRelay+  "forcerelay" -> Just PermForceRelay+  "download" -> Just PermDownload+  "noban" -> Just PermNoBan+  "mempool" -> Just PermMempool+  "addr" -> Just PermAddr+  _ -> Nothing+ -- | The help of an option, with the environment variable that sets its -- default: every option has one, and someone who runs the store in a -- container reads the help to find its name.@@ -393,10 +421,33 @@             <> helpEnv               "PEER"               ( unwords-                  [ "Network peer (as many as required); on Bitcoin, only these are asked for their mempools",-                    "when the pool fills again, so whitelist the store on them"+                  [ "Network peer (as many as required); a node that whitelists the store here says so",+                    "with --peer-permission"                   ]               )+  peerPermissions <-+    fmap (mappend c.peerPermissions) $+      many $+        option (maybeReader parsePermission) $+          metavar "PERMISSION"+            <> long "peer-permission"+            <> helpEnv+              "PEER_PERMISSIONS"+              ( unwords+                  [ "A permission that the nodes of --peer grant the store with -whitelist or -whitebind,",+                    "as they name it (as many as they grant): mempool to ask them for their mempools"+                  ]+              )+  foreignPeers <-+    flag c.foreignPeers True $+      long "foreign-peers"+        <> helpEnv+          "FOREIGN_PEERS"+          ( unwords+              [ "The nodes of --peer are not the operator's own: a transaction that only they name",+                "and that the store cannot verify is not taken"+              ]+          )   version <-     switch $       long "version"@@ -630,7 +681,7 @@     option auto $       metavar "SECONDS"         <> long "max-peer-life"-        <> helpEnv "MAX_PEER_LIFE" "Maximum peer connection time"+        <> helpEnv "MAX_PEER_LIFE" "Longest connection to a peer found by discovery; the peers of --peer are kept"         <> showDefault         <> value c.maxPeerLife   maxPeers <-@@ -717,10 +768,32 @@           "NODE_RPC"           ( unwords               [ "Publish transactions over the JSON-RPC of this full node, and through the peers when it fails;",-                "fill the shared mempool from it again after it is emptied"+                "have the node as a peer over it, for headers, blocks, transactions and the mempool.",+                "Give --node-zmq with it: without it the node is asked every five seconds, with a warning"               ]           )         <> value c.nodeRpc+  nodeRpcSocket <-+    strOption $+      metavar "PATH"+        <> long "node-rpc-socket"+        <> helpEnv+          "NODE_RPC_SOCKET"+          "Send the requests of --node-rpc through this Unix socket, in place of the host and port of its URL"+        <> value c.nodeRpcSocket+  nodeZmq <-+    strOption $+      metavar "ADDRESS"+        <> long "node-zmq"+        <> helpEnv+          "NODE_ZMQ"+          ( unwords+              [ "Where the node of --node-rpc publishes over ZeroMQ (its -zmqpubhashtx and -zmqpubhashblock),",+                "such as tcp://127.0.0.1:28332 or ipc:///run/node/zmq.sock: the store hears of a transaction",+                "and of a block as the node takes them. Expected with --node-rpc"+              ]+          )+        <> value c.nodeZmq   tlsCert <-     strOption $       metavar "FILE"@@ -804,7 +877,9 @@     Nothing -> Left ("--net " <> s <> ": unknown network; use one of " <> intercalate ", " (map (.name) allNets))  -- | Parse the command line and run the store. If no peers are given and discovery--- is off, discovery is turned on.+-- is off, discovery is turned on, unless the store has its node as a peer+-- through its RPC (@--node-rpc@, which is meant to come with+-- @--node-zmq@). -- -- A mistake of configuration, or something that the store needs and does -- not find (Redis, a free port, a database that no other store holds), is@@ -819,12 +894,23 @@   -- the cache of xpubs cannot be turned off: its size is all that is set   when (c.redisMaxXPubs < 1) $     misconfigured "--redis-max-xpubs (or REDIS_MAX_XPUBS) must be at least 1"+  -- the ZeroMQ socket announces, and what it announces is fetched over+  -- the RPC: one without the other is no peer+  when (not (null c.nodeZmq) && null c.nodeRpc) $+    misconfigured . T.unwords $+      [ "--node-zmq (or NODE_ZMQ) needs --node-rpc (or NODE_RPC):",+        "what the node publishes is fetched over its RPC"+      ]+  when (not (null c.nodeZmq)) $+    either (misconfigured . T.pack) (const (return ())) (parseZmqAddress c.nodeZmq)   case (c.tlsCert, c.tlsKey) of     ("", "") -> return ()     ("", _) -> misconfigured "--tls-key needs --tls-cert: give both, or neither for plain HTTP"     (_, "") -> misconfigured "--tls-cert needs --tls-key: give both, or neither for plain HTTP"     (certificate, key) -> checkReadable "--tls-cert" certificate >> checkReadable "--tls-key" key-  if null c.peers && not c.discover+  -- a store that has its node through its RPC has a peer, and needs no+  -- other+  if null c.peers && not c.discover && null c.nodeRpc     then run $ let Config {..} = c in Config {discover = True, ..}     else run c   where@@ -870,6 +956,8 @@         StoreConfig           { maxPeers = cfg.maxPeers,             initPeers = cfg.peers,+            peerPermissions = Set.fromList cfg.peerPermissions,+            foreignPeers = cfg.foreignPeers,             discover = cfg.discover,             db = dir </> "db",             net = net,@@ -894,6 +982,9 @@             blockPing = fromIntegral cfg.blockPing,             maxPeerLife = fromIntegral cfg.maxPeerLife,             connect = withConnection,+            nodePeerRpc = if null cfg.nodeRpc then Nothing else Just cfg.nodeRpc,+            nodePeerRpcSocket = if null cfg.nodeRpcSocket then Nothing else Just cfg.nodeRpcSocket,+            nodePeerZmq = if null cfg.nodeZmq then Nothing else Just cfg.nodeZmq,             stats = stats,             bloom = cfg.bloom,             maxOpenFiles = if cfg.maxOpenFiles > 0 then Just cfg.maxOpenFiles else Nothing,@@ -942,6 +1033,8 @@               healthCheckInterval = cfg.healthCheckInterval,               accessLog = cfg.accessLog,               nodeRpc = if null cfg.nodeRpc then Nothing else Just cfg.nodeRpc,+              nodeRpcSocket = if null cfg.nodeRpcSocket then Nothing else Just cfg.nodeRpcSocket,+              nodeZmq = if null cfg.nodeZmq then Nothing else Just cfg.nodeZmq,               -- both or neither, which 'main' checked               tls = case (cfg.tlsCert, cfg.tlsKey) of                 ("", _) -> Nothing
+ bench/Decide.hs view
@@ -0,0 +1,354 @@+-- | What the move of the tip over a block costs to decide, without Redis.+--+-- > haskoin-store-bench decide [TXS [POOL [INPUTS [OUTPUTS [RIVALS [WATCHED]]]]]]+--+-- A move of the tip is one decision ("Haskoin.Store.Fleet.Pool.Decide",+-- @advance@) that takes the transactions of a block out of the shared+-- mempool. Transactions that are offered wait for as long as it takes.+-- On a server it took thirteen to eighteen seconds for a block of three+-- to four thousand transactions, and the store said where the time went:+-- nine tenths of it deciding, in Haskell, and less than a tenth in Redis+-- and in the database together. This times the deciding alone, so that+-- what would shorten it can be tried and measured here, and not on a+-- server.+--+-- It fills the model of Redis ("Haskoin.Store.Fleet.Atomic", @Db@) with a+-- pool of POOL transactions (20,000) by the decision that offers one, and+-- then decides, and does not carry out, the move over a block that+-- confirms TXS of them (4,000), three times over, and the same over a+-- half and a quarter of them, to show how the cost grows. The model+-- answers from maps in memory, so what is timed is the decision, gone+-- through once for each time that it has questions to ask, as against a+-- Redis.+--+-- A transaction has INPUTS inputs (3) and OUTPUTS outputs (3), each at an+-- address of its own. One in five spends an output of the one before it,+-- which the block confirms too, and one in ten has a child that stays in+-- the pool, as blocks of Bitcoin have.+--+-- A block also confirms RIVALS transactions (0) that the pool does not+-- have, each spending what a transaction of the pool spends: that one+-- leaves with its child, and is kept as replaced. A node drops such a+-- transaction when the block comes, and a store that had it takes it out+-- in the move.+--+-- WATCHED transactions in a hundred (0) have every address of theirs+-- watched by a cached extended public key, one of a thousand: taking+-- such a transaction out of the pool takes it out of the lists of the+-- key too, and gives the key a new version. A server with many keys+-- pays that for each block, and a benchmark without them does not show+-- it.+--+-- For each run it prints how long each pass over the decision took and+-- how many questions it ended with, the answers that the decision depends+-- on and its writes, and, with @+RTS -T@, how much it allocated and how+-- long the garbage collector ran. The time for each question or write of+-- a pass is the number to compare between two builds.+--+-- Run it with @+RTS -T -A64m@, as a store runs. With the allocation area+-- that GHC gives by default the collector runs three hundred times in a+-- move of 4,000 transactions, and each time goes over the model of Redis,+-- which is in the memory of this program and not of a store: the move+-- took 2.1 seconds then and 0.8 with it, on the same machine.+module Decide (decideBench) where++import Control.Exception (evaluate)+import Control.Monad (foldM, forM_, unless, when)+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.ByteString.Char8 qualified as C+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.Serialize (encode)+import Data.Word (Word32, Word64)+import GHC.Clock (getMonotonicTimeNSec)+import GHC.Stats (RTSStats (..), getRTSStats, getRTSStatsEnabled)+import Haskoin.Store.Fleet.Atomic+  ( Atomic,+    Backend (..),+    Db,+    Op (..),+    Outcome (..),+    answer,+    emptyDb,+    perform,+    runAtomic,+    runPure,+    tidy,+  )+import Haskoin.Store.Fleet.Pool.Decide qualified as D+import Haskoin.Store.Fleet.Pool.Types+import Text.Printf (printf)++decideBench :: [String] -> IO ()+decideBench args = do+  let numbers = map read args <> drop (length args) [4000, 20000, 3, 3, 0, 0] :: [Int]+      (txs, pool, ins, outs, rivals, watched) = case numbers of+        a : b : c : d : e : f : _ -> (a, max a b, c, d, e, f)+        _ -> error "usage: haskoin-store-bench decide [TXS [POOL [INPUTS [OUTPUTS [RIVALS [WATCHED]]]]]]"+      shape = Shape {ins, outs, rivals, watched}+  printf "A pool of %d transactions of %d inputs and %d outputs, and a block of %d of them\n" pool ins outs txs+  when (rivals > 0) $+    printf "The block also confirms %d transactions that each spend what one of the pool spends\n" rivals+  when (watched > 0) $+    printf "A cached key watches every address of %d transactions in a hundred\n" watched+  began <- getMonotonicTimeNSec+  db <- evaluate (filled shape pool)+  -- all of it, and not what the first questions happen to look at+  _ <- evaluate (length (show db))+  ended <- getMonotonicTimeNSec+  printf "The pool was filled in %d ms\n\n" (millis (ended - began))+  forM_ [txs `div` 4, txs `div` 2, txs] $ \n -> do+    printf "A block of %d transactions:\n" n+    forM_ [1 .. 3 :: Int] $ \_ -> decided shape pool db n+    putStrLn ""++-- | How many inputs and outputs a transaction has, how many+-- transactions of the pool a block is in conflict with, and how many+-- transactions in a hundred have their addresses watched by a cached+-- key.+data Shape = Shape {ins :: !Int, outs :: !Int, rivals :: !Int, watched :: !Int}++-- | The cached keys that watch an address of a transaction, as writes to+-- the model: one key of a thousand for all the addresses of a+-- transaction that is watched.+watching :: Shape -> Int -> [Op]+watching shape c+  | c `mod` 100 < shape.watched =+      [ SAdd ("hs3:btc:fx:of:" <> a) (C.pack ("key" <> show (c `mod` 1000)))+      | a <- [address 0 c i | i <- [0 .. shape.ins - 1]] <> [address 1 c i | i <- [0 .. shape.outs - 1]]+      ]+  | otherwise = []++-- | The number of a transaction of the pool that a block conflicts with:+-- the last ones of the pool, which no block here confirms, those that+-- have a child.+rival :: Int -> Int -> Int+rival pool i = 10 * ((pool `div` 10) - i)++keys :: D.Keys+keys = D.poolKeys "hs3:btc:" 32++now :: Integer+now = 1795000000000++target :: ByteString+target = B.replicate 32 0xbb++-- | Thirty-two bytes for a number: the id of a transaction.+txid :: Int -> ByteString+txid c = B.replicate 24 0xaa <> encode (fromIntegral c :: Word64)++-- | An output of a transaction.+output :: ByteString -> Int -> ByteString+output t i = t <> encode (fromIntegral i :: Word32)++-- | An address as a store names it: a byte for its kind and twenty more.+address :: Int -> Int -> Int -> ByteString+address side c i =+  B.singleton (fromIntegral side) <> B.take 20 (C.pack (show c <> ":" <> show i) <> B.replicate 20 0x2e)++-- | A transaction of the pool. Its first input is an output of the+-- chain, or the first output of the transaction before it for one in+-- five.+poolTx :: Shape -> Int -> PoolTx+poolTx shape c =+  PoolTx+    { txid = t,+      time = 1795000000 + fromIntegral c,+      inputs = map fst spent,+      body = B.replicate 400 7,+      entries =+        [PoolTouches a | (_, a) <- spent]+          <> [PoolTouches (address 1 c i) | i <- [0 .. shape.outs - 1]]+          <> [PoolSpends a o 1000 | (o, a) <- spent]+          <> [PoolPays (address 1 c i) (output t i) 1000 script | i <- [0 .. shape.outs - 1]]+    }+  where+    t = txid c+    script = B.replicate 25 0x76+    spent =+      [ if i == 0 && chained c+          then (output (txid (c - 1)) 0, address 1 (c - 1) 0)+          else (output (txid (1000000000 + c)) i, address 0 c i)+      | i <- [0 .. shape.ins - 1]+      ]++-- | Whether a transaction spends from the one before it.+chained :: Int -> Bool+chained c = c > 1 && c `mod` 5 == 0++-- | Whether each input of a transaction is unspent in the chain: all but+-- the one that spends from the pool.+unspent :: Shape -> Int -> [Bool]+unspent shape c = [not (i == 0 && chained c) | i <- [0 .. shape.ins - 1]]++-- | The child of a transaction, which no block confirms here.+child :: Int -> PoolTx+child c =+  PoolTx+    { txid = t,+      time = 1795000900,+      inputs = [o],+      body = B.replicate 250 7,+      entries =+        [ PoolTouches (address 1 c 1),+          PoolTouches (address 2 c 0),+          PoolSpends (address 1 c 1) o 1000,+          PoolPays (address 2 c 0) (output t 0) 900 (B.replicate 25 0x76)+        ]+    }+  where+    t = txid (2000000000 + c)+    o = output (txid c) 1++-- | The model of Redis with one live store that reported the block, and+-- a pool of so many transactions, one in ten with a child.+filled :: Shape -> Int -> Db+filled shape pool = foldl' offered start [1 .. pool]+  where+    start =+      foldl'+        (flip perform)+        emptyDb+        [ HSet "hs3:btc:fleet:lease" "a" (C.pack (show (now + 10000))),+          HSet "hs3:btc:fleet:recent" "a" target+        ]+    offered db0 c =+      let db = foldl' (flip perform) db0 (watching shape c)+          with = offer (unspent shape c) (poolTx shape c) db+       in if shape.outs > 1 && c `mod` 10 == 0 then offer [False] (child c) with else with+    offer :: [Bool] -> PoolTx -> Db -> Db+    offer oks tx db = case runPure now (D.offer keys Nothing oks [] tx) db of+      Right (Taken, after) -> after+      Right (other, _) -> error ("A transaction was not taken: " <> show other)+      Left why -> error (show why)++-- | Decide the move over the first so many transactions of the pool, and+-- say what it cost.+decided :: Shape -> Int -> Db -> Int -> IO ()+decided shape pool db n = do+  marks <- newIORef []+  let fetch qs = do+        from <- getMonotonicTimeNSec+        answers <- evaluate (map (answer db) qs)+        -- every answer, all of it, before the clock is read again+        unless (and (zipWith (==) answers answers)) (error "An answer differs from itself")+        to <- getMonotonicTimeNSec+        answers <$ modifyIORef' marks ((from, to, length qs) :)+      -- the transactions of the block that the pool never had, each+      -- with the output that it spends and that one of the pool spends+      strangers =+        [ (txid (3000000000 + i), o)+        | i <- [1 .. shape.rivals],+          let r = rival pool i,+          r > n,+          o <- take 1 (poolTx shape r).inputs+        ]+      confirmed = map txid [1 .. n] <> map fst strangers+      change =+        PoolChange+          { returned = [],+            gone = [],+            confirmed,+            spent =+              [ o <> tx.txid <> encode (978000 :: Word32)+              | c <- [1 .. n],+                let tx = poolTx shape c,+                o <- tx.inputs+              ]+                <> [o <> t <> encode (978000 :: Word32) | (t, o) <- strangers],+            height = Just 978000,+            lost = []+          }+      move :: (Monad m) => Atomic m Moved+      move = D.advance keys Nothing target (Just now) 32 (D.AtOnce change) [] ""+      mark :: (Monad m) => Atomic m Moved+      mark = D.advance keys Nothing target (Just now) 32 (D.Changing change) [] ""+  before <- stats+  began <- getMonotonicTimeNSec+  outcome <- runAtomic Backend {fetch, time = return now} move+  (answers, written, kept) <- case outcome of+    Decided (MovedTo _) depends writes _ -> do+      a <- evaluate (length depends)+      w <- evaluate (length writes)+      k <- evaluate (length (tidy writes))+      return (a, w, k)+    Decided other _ _ _ -> error ("The tip did not move: " <> show other)+    Stuck why -> error (show why)+  ended <- getMonotonicTimeNSec+  after <- stats+  passes <- reverse <$> readIORef marks+  let -- a pass goes from the end of the answers before it to its own+      -- questions, and the last to the end+      starts = began : [to | (_, to, _) <- passes]+      stops = [from | (from, _, _) <- passes] <> [ended]+      asked = [qs | (_, _, qs) <- passes] <> [0]+      answering = sum [to - from | (from, to, _) <- passes]+      deciding = (ended - began) - answering+      steps = (length passes + 1) * (answers + written)+  printf+    "  %d ms deciding and %d answering, %d passes, %d answers, %d writes (%d sent)\n"+    (millis deciding)+    (millis answering)+    (length passes + 1)+    answers+    written+    kept+  printf+    "    for each transaction %.0f us, for each answer or write of a pass %.2f us\n"+    (micros deciding / fromIntegral n)+    (micros deciding / fromIntegral (max 1 steps))+  putStrLn . ("    the passes, in ms, with the questions that each ended with: " <>) . unwords $+    [show (millis (stop - start)) <> " (" <> show qs <> ")" | (start, stop, qs) <- zip3 starts stops asked]+  forM_ ((,) <$> before <*> after) $ \(b, a) ->+    printf+      "    allocated %d MB, %.0f bytes for each answer or write of a pass; the collector ran %d ms in %d collections\n"+      ((a.allocated_bytes - b.allocated_bytes) `div` 1000000)+      (fromIntegral (a.allocated_bytes - b.allocated_bytes) / fromIntegral (max 1 steps) :: Double)+      ((a.gc_elapsed_ns - b.gc_elapsed_ns) `div` 1000000)+      (a.gcs - b.gcs)+  when (answers == 0) (error "A move that asked nothing")+  -- the same move with what leaves only marked, and then taken out a+  -- few transactions at a time+  (ms, asked, wrote, calls, after1) <- step db mark+  printf "  marked: %d ms, %d answers, %d writes, in %d calls\n" ms asked wrote calls+  let chunks = pieces 200 confirmed+      go (total, longest, most, d) chunk = do+        (t, _, w, _, d') <- step d (D.takeOut keys chunk)+        return (total + t, max longest t, max most w, d')+  (total, longest, most, _) <- foldM go (0, 0, 0 :: Int, after1) chunks+  printf+    "  taken out: %d ms in %d steps of 200 transactions, the longest %d ms and %d writes\n"+    total+    (length chunks)+    longest+    most+  where+    pieces n xs = case splitAt n xs of+      (a, []) -> [a]+      (a, rest) -> a : pieces n rest+    -- decide against a model, and carry out: how long the deciding took,+    -- its answers, its writes, how many times the model was asked, and+    -- the model after it+    step :: Db -> (forall m. (Monad m) => Atomic m a) -> IO (Word64, Int, Int, Int, Db)+    step d decision = do+      from <- getMonotonicTimeNSec+      outcome <- runAtomic Backend {fetch = return . map (answer d), time = return now} decision+      case outcome of+        Decided _ depends writes calls -> do+          a <- evaluate (length depends)+          let kept' = tidy writes+          w <- evaluate (length kept')+          to <- getMonotonicTimeNSec+          return (millis (to - from), a, w, calls, foldl' (flip perform) d kept')+        Stuck why -> error (show why)+    stats =+      getRTSStatsEnabled >>= \case+        True -> Just <$> getRTSStats+        False -> return Nothing++millis :: Word64 -> Word64+millis = (`div` 1000000)++micros :: Word64 -> Double+micros n = fromIntegral n / 1000
bench/Main.hs view
@@ -6,13 +6,14 @@ -- -- > haskoin-store-bench PORT BLOCKS [REDIS_URL] ----- Four other things are measured without a server: @haskoin-store-bench+-- Five other things are measured without a server: @haskoin-store-bench -- micro@ times the pure functions that encode a response, -- @haskoin-store-bench import@ the import of full blocks ("Import"), -- @haskoin-store-bench merge@ what the merge records of those blocks cost--- the readers of the database ("Merge"), and @haskoin-store-bench+-- the readers of the database ("Merge"), @haskoin-store-bench -- admission@ how the limit on long requests behaves under load--- ("Admission").+-- ("Admission"), and @haskoin-store-bench decide@ what the move of the+-- fleet tip over a block costs to decide ("Decide"). -- -- Set @BENCH_LOG=1@ to print the log of the store, such as to see why it -- does not sync.@@ -63,9 +64,11 @@ import Data.Time.Clock.POSIX (getPOSIXTime) import Data.Vector qualified as V import Data.Word (Word32)+import Decide (decideBench) import GHC.Clock (getMonotonicTimeNSec) import Haskoin import Haskoin.Node+import Haskoin.Node.Address (peerHostAddress) import Haskoin.Store import Haskoin.Store.Database.Query qualified as Q import Haskoin.Store.Integration.Temp (withSystemTempDirectory)@@ -85,6 +88,7 @@     "import" : more -> importBench more     "merge" : more -> mergeBench more     "admission" : more -> admissionBench more+    "decide" : more -> decideBench more     _ -> server args  server :: [String] -> IO ()@@ -192,9 +196,11 @@ storeConfig net dir redis blocks mock logger cache buffer =   StoreConfig     { maxPeers = 20,-      -- the mock peer, by name: since haskoin-node 2.5 the seed of a regtest-      -- network is not an address that discovery takes-      initPeers = ["127.0.0.1:18444"],+      -- the mock peer, which lives in memory ('mockPeer'), by a name: a Unix+      -- socket, so that no address or port of the machine is named+      initPeers = ["unix:mock-peer"],+      peerPermissions = mempty,+      foreignPeers = False,       discover = False,       db = dir,       net = net,@@ -210,6 +216,9 @@       blockPing = 5,       maxPeerLife = 48 * 3600,       connect = mockPeer blocks mock net ad,+      nodePeerRpc = Nothing,+      nodePeerRpcSocket = Nothing,+      nodePeerZmq = Nothing,       stats = Nothing,       bloom = True,       maxOpenFiles = Nothing,@@ -245,6 +254,8 @@       accessLog = False,       tls = Nothing,       nodeRpc = Nothing,+      nodeRpcSocket = Nothing,+      nodeZmq = Nothing,       logger = quiet     } @@ -402,7 +413,7 @@     go r s = do       nonce <- randomIO       now <- round <$> getPOSIXTime-      let rmt = NetworkAddress 0 (sockToHostAddress sa)+      let rmt = NetworkAddress 0 (peerHostAddress sa)           ver = buildVersion net nonce 0 ad rmt now       runPut (putMessage net (MVersion ver)) `send` s       runConduit $
+ docs/concurrency.md view
@@ -0,0 +1,660 @@+# Concurrency in haskoin-store++What runs at the same time in a store and across a fleet, who may change+what, and why no order of events breaks it. It ends with the rules that+an audit of November 2026 left, and with the known limits. The threads+of haskoin-node, on which the store runs, are in that package's own+`docs/concurrency.md`.++Read the part about a protocol before you change it, and keep this page+in step with the code.++## In short++A store is a few dozen threads, a RocksDB database that one of them+writes, and a Redis that every store of a fleet shares. Such a program+breaks when two parts change the same thing at once, or when one acts on+what another has just changed.++So whatever runs beside something else is decided by a pure function,+by a change to Redis that is carried out in one step, or by a short+script that Redis runs alone. Every piece of shared state has one owner,+or changes in one step with what the change depends on. A thread only+carries out what a rule says, so the rules are tested without threads.++It has a cost. A change to Redis takes two calls where a script took+one. And the longest change, a move of the tip, has to be given the+right to go first: new transactions wait meanwhile.++## Words used here++The shared words (store, fleet, the pool, the tip, view, the cache,+entry, turn) are in [README.md](README.md). This page adds these.++| Word | What it means here |+| --- | --- |+| **machine** | A pure function: from what it knew and what just happened, it says what to do. A thread carries that out. |+| **owner** | The one thread that may change a piece of state. |+| **mailbox** | A queue of messages that one thread reads, in order. |+| **decision** | As in the README: one change to Redis, worked out in Haskell and applied in one step. |+| **question** | One command that reads Redis and changes nothing. |+| **answer** | What Redis said to a question. |+| **write** | One command that changes Redis. A decision only lists its writes. |+| **the script** | `lua/atomic.lua`: it carries out the writes of a decision if every answer is still the same. Any other Lua script is named as such. |+| **refused** | A decision whose answers changed: nothing was written, and it is made again. |+| **pass** | One run through the code of a decision, from its start. |+| **the model of Redis** | The part of Redis that the fleet uses, as a pure value. The tests run decisions against it. |+| **the model of the fleet** | The rules of the fleet as pure functions. |+| **Valkey** | The Redis that the tests run, in a container. |+| **cell** | A field of a hash, a member of a set, the score of a member, or what a key holds. |+| **lease** | The time until which a store is **live**. The store renews it at every turn, for ten seconds. |+| **report** | What a store tells Redis at every turn: its newest blocks. |+| **the agreed block** | The newest block that every live store reported. The tip moves only there. |+| **move** | Taking the tip to the agreed block, with the pool and the cache (`moveTip`). The store that does it is the **mover**. |+| **the way** | The blocks between the old tip and the new one, and what they did. |+| **token** | A random number that a mover picks for one move. |+| **piece** | A part of what a move writes to the cache before the tip moves. |+| **the floor** | The right of the mover to go first (the keys `fx:moving` and `fx:beat`). |+| **beat** | The time that the mover writes every two seconds, to say that it is still at its move. |+| **gives way** | What a decision does when it has to wait: it writes nothing. |+| **mark** | A field of the hash `pool:leaving`: its transaction has to leave the pool, and is still in. |+| **take out** | Remove a marked transaction from the pool and from all that mentions it, with its mark. |+| **offer** | A store asks the pool to take one transaction. |+| **withdrawal**, **expiry** | Removing a transaction from the pool with all that spends from it; an expiry is that of the old ones. |+| **build**, **drop**, **eviction** | Writing the entry of an xpub into the cache; deleting one; deleting those of lowest priority. |+| **member** | The part of a store that takes its turns in the fleet (`Haskoin.Store.Fleet.Member`). |++## The rule++Whatever runs at the same time as something else is one of three things:++1. A **machine**, in a module of its own, tested with QuickCheck on+   random sequences of events.+2. A **decision** about what Redis holds.+3. A short **Lua script** that Redis runs alone, tested against a model+   of it.++The threads keep the state and carry out what these say.++A race is ruled out in one of four ways. Each piece of state below names+its way.++| Way | What it means |+| --- | --- |+| **A single owner** | One thread changes the state. Others at most read it. |+| **One STM transaction per change** | The state is read, the change worked out and the new state written in one STM transaction. |+| **One step in Redis** | A change to Redis and what it depends on are one step. A Lua script reads again what it depends on (the tip, the agreed block, the token of a move) and answers `raced` if that changed. For the pool and the cache it is a decision ("Decisions in one step", below). |+| **The order of one queue** | Events that must keep their order go through one mailbox that one thread reads. |++## The block store++One thread, the block store's, reads one mailbox. Node events, blocks+from peers, pongs and a clock tick all come through it. That thread+owns:++| State | Machine | Rule |+| --- | --- | --- |+| `sync`, the block download | `Haskoin.Store.BlockStore.Sync` | single owner |+| `knows`, what each peer said it has | read and written by the owner | single owner |+| the reservation of the syncing peer | haskoin-node's `Lock`, by the store's own `owner` | single owner |+| the database | the writer, one RocksDB batch per block | single owner |++The store asks one peer at a time for blocks, the syncing peer. A peer+that is too slow is passed over, and the next is asked. The rules of the+machine (`Sync`), each a property of `SyncSpec`:++- **One syncing peer at most.** Only `start` and `pass` set one.+- **A block is accepted only from a peer that was asked for it.**+- **A peer that was asked is not forgotten.** While it is connected, it+  is never taken for a peer that was not asked. It is the syncing peer,+  or among those passed over, until it delivers or the timeout runs out.+  `forget` is for a peer that disconnected. `finish` is for one that is+  still connected, and keeps what it owes.+- **Once each.** A peer owes each block once, and a block is wanted once.++A reader of the database never sees half a block: a batch is one write,+and the web server reads through a snapshot that the block store's+thread takes right after the write (`noteBest`).++## The path of a transaction into the pool++The block store has nothing to do with the transactions that peers+announce and send. One thread, the runner (`Haskoin.Store.Ingest.Run`),+owns one machine, `Haskoin.Store.Ingest`. The runner gives the machine+everything that happens, in the order of one queue:++- a peer that comes or goes;+- what a peer announces, a transaction, a `notfound`;+- the clock, and whether the store is in sync;+- the answers of the pool to what the machine asked.++The machine decides. The runner carries out.++The runner can also be given a feed (`ingestFeed`): something that is+no peer and that a whole mempool can be read from, with a thread of its+own. The store starts none since it has the node of its RPC as a peer+(`Haskoin.Store.NodePeer`). To the machine a feed is a peer. It comes+when it is started, goes when a call fails, and comes again, as a new+peer, when it is tried again. The feed decides nothing either: it makes the+calls that the machine asked for, and puts the answers in the queue of+events.++[mempool-ingestion.md](mempool-ingestion.md) says what the machine+guarantees, and whether each guarantee is proved, checked or tested.++| State | Owner | Rule |+| --- | --- | --- |+| the machine: where each id is, and the window of each peer (the most requests out to it) | the runner | single owner; every change is `step` |+| the queue of events | written by the thread that reads the node's events, read by the runner | events of peers are dropped past 20,000, and the machine is told that something was lost |+| `state`, what `/health` reads | written by the runner after each step | one STM transaction per write |+| what is asked of the RPC of the node | written by the runner, read by the feed | a queue for each time the RPC is reached, named in the event that tells the machine of it; what the feed answers goes into the queue of events, and waits for room there |+| the number of the next feed | the feed | read and added to in the STM transaction that tells the machine of the feed, so no number is used twice (U1) |++## The fleet++Every store is a member of a fleet, alone or not. The fleet keeps in+Redis the tip, the pool, the leases and reports, the cache and the+events. All of it is written only in single steps, and each step reads+again what it depends on.++| What is written | By what |+| --- | --- |+| the pool, its events, and the move of the tip with the pool | the decisions of `Haskoin.Store.Fleet.Pool.Decide` |+| the cache | the decisions of `Haskoin.Store.Fleet.XPub.Decide` |+| the reports, and the move of the tip alone | two short Lua scripts of `src/Haskoin/Store/Fleet/lua` |+| only the note that an entry of the cache was used | the reads of the pool and of the cache, which are Lua scripts too |++The model of the fleet is `Haskoin.Store.Fleet` (which block the stores+agree on, leases, who may empty the pool) and `Haskoin.Store.Fleet.Pool`+(the pool). `RedisSpec` runs what is done in Redis against it, step by+step.++### Decisions in one step++**The problem.** The changes to the pool were one Lua script of eight+hundred lines. Redis ran it alone, which made each change one step. It+had two faults:++- **Redis undoes nothing.** A script that fails after its first write+  keeps what it wrote. A field that was not there, or a number that+  Redis did not take, left the pool half changed.+- **The rules were kept twice**, in Lua to run and in Haskell to test+  against, joined only by tests on random sequences. A bug of+  19 November was in that gap.++**What is done now.** A change is a decision+(`Haskoin.Store.Fleet.Atomic`):++1. The decision runs in Haskell. It can only ask Redis questions and+   add to a list of writes. It runs in any monad, so its type says that+   it does nothing else. Every question is kept with its answer.+2. The script (`lua/atomic.lua`) is given the questions with their+   answers, and the writes. It asks every question again.+3. If one answer differs, the script writes nothing and says so. The+   decision is refused, and is made again.+4. If all are the same, the script carries out the writes.++For example, the offer of a transaction asks "is the tip still block+B?" and "does the pool spend this coin already?", and lists the writes+that put the transaction in. If the tip moves before the script runs,+the first answer differs: nothing is written, and the offer is decided+again.++**Why that is one step.** Redis runs the script alone (R1 of+[mempool-ingestion.md](mempool-ingestion.md)). So the answers are all+true at one moment, that of the script. The decision depends on its+answers and on nothing else. So the writes are what the decision would+have written, had it run inside Redis at that moment.++**Why it cannot fail half way.** The script compares every answer before+its first write, and then runs plain commands with nothing to decide+between them. A fault in a decision is an exception in Haskell, before+Redis is told anything.++**What it rests on**, and how each part is known:++| Part | How it is known |+| --- | --- |+| A decision does nothing but ask and write | By its type: it is run as `forall m. Monad m => Atomic m a`. |+| The script compares before it writes, and decides nothing | By reading it: a hundred lines, with no rule of the fleet in them. |+| A decision sees its own writes as the model of Redis says them (`replay`) | What a write does to one cell is written once, in `Haskoin.Store.Fleet.Atomic.Cells`, and both use it. **Proved** by Liquid Haskell (`proofs/`) for every cell function, key and list of writes: the cell of a key in the model after the writes is the answer that the decision works out from the cell before. The proof assumes four facts of `Data.Map`, and does not look into the arithmetic of `INCRBY`. Six bugs planted in it are each rejected. For all the fields of a hash and all the members of a set, the decision changes its answer by the function that changes the model. |+| The rest of what a decision sees of its own writes: the names of the fields of a hash, a range and a count of a sorted set, whether a key is there, and that a write goes to the map of its own kind | Not proved. **Sampled** on 5,000 random cases against the model of Redis, and **tested** on 300 against a Valkey. Where a decision cannot tell, it stops with an error and guesses nothing. |+| The model of Redis says what Redis says | Tested against a Valkey: any writes, then every question. |+| A decision whose answers changed writes nothing | Tested against a Valkey, with a set and a hash of 200 members in whatever order Redis lists them. |+| No change is lost when many decide at once | Tested: eight threads, four hundred additions to one number. |+| A decision has one clock, that of Redis when it was first asked, however long the decision takes | Tested in the model of Redis: Redis is asked three times, with a clock ten seconds later each time, and the decision reads the first. The test fails with a clock for each time. |+| A decision of any size is carried out | Tested against a Valkey: 280,000 writes, more words than Redis takes arguments in a command (1,048,576). Questions and writes go a thousand to an argument, packed, and the script unpacks one argument at a time. |+| The writes that are sent do what all the writes do | Writes that a later delete undoes are not sent (`tidy`): sampled on 5,000 random cases in the model of Redis. The rest become commands with many members: tested against a Valkey on 300 random lists of writes, and by the two comparisons with the old Lua scripts, below. |+| No write fails in Redis for the kind of its key | By type. A key has its kind in its type (`Haskoin.Store.Fleet.Atomic.Keys`), given once where the key is named, and each write takes keys of one kind. A hash written to a set, or an addition to what is no number, does not compile; three such writes were tried. The decisions of the pool and of the cache import that module, and not the writes without kinds. A key that both write is named once: the cache takes it from the record of the pool. |+| The decisions of the pool do what the old Lua script of the pool did | Sampled: the old script and the decisions side by side, under two prefixes of one Valkey. 300 random sequences of offers, withdrawals, expiries and moves of the tip of each kind, with all that Redis holds compared after every step (`Haskoin.Store.Fleet.DecideSpec`). |+| The decisions of the cache do what its old Lua script did | Sampled the same way: 300 random sequences of builds, of moves begun, written in pieces, given up, gone quiet and committed, and of entries dropped and evicted, with the pool changing under them (`Haskoin.Store.Fleet.XPubDecideSpec`). |++One row is proved. The rest is by type, by reading, sampled or tested.+What changed is where a fault can be: in a pure function, where it is an+exception before any write, and no longer in the middle of a script.++**What it costs.** Two calls to Redis where there was one:++| | Old Lua script | Decision |+| --- | --- | --- |+| An offer that is taken (Valkey's own count, 2,000 offers) | 1 call, 74 microseconds of Redis | 2 calls, about 137 |+| A build of an xpub with 20 addresses and 300 rows | 1 call, 1.0 milliseconds of Redis | 2 calls, about 1.5 |++A decision takes more than one pass, to learn what it asks. So Redis is+asked in a few calls, and not once for each question.++**One clock.** A decision judges time by one clock, read at its start.+With the clock read again at each call to Redis, a move that took ten+seconds to decide judged the ten-second lease of its own store ten+seconds late: it found no store live and gave up, at every turn+(item 17). An early clock is safe for what stays true: a lease that had+run out has run out, and one that had not is what a script that ran at+the start would have found.++**One change to the cache.** A move whose store wrote nothing for ten+seconds is ended by whichever decision comes across it. A read ended it+too, and no longer does: to a read, an entry that the pieces of such a+move wrote to is a miss, and the build that follows the miss ends the+move.++**Two fleets on one Redis.** The keys of stores that keep the pool in+this way start with `hs3:`, and those of stores that ran the old script+with `hs2:`. On one Redis they are two fleets.++### The floor: a long decision gets its turn++**The problem.** A decision is carried out only if nothing that it read+has changed. That makes it right, and does not make it happen. A short+decision is refused now and then, and is made again. A long one can be+refused every time.++The long one is a move that removes the transactions of a block from the+pool. It removes thousands of them, reads the answers to tens of+thousands of questions, and takes a second or more. Transactions are+offered several times a second, and each offer changes an answer or two.+So on a network with traffic the move was refused at every try.++That happened on a server on 22 November 2026, at the first block that a+store of this design met on Bitcoin. The store imported every block and+went on answering from the one before, while its health, which looks at+the database, said that all was well. Nothing had shown it: Redis ran+the old Lua script alone, and the tests moved the tip over a dozen+transactions with nothing else writing.++**The rule.** The mover has the floor, as it already had for the cache+(`Haskoin.Store.Fleet.XPub.Decide.begin`):++1. The mover writes its token to `fx:moving`, and the time beside it,+   to `fx:beat`.+2. It writes the time again every two seconds, for as long as it works+   at the move (`beat`, from `moveTip`).+3. Whatever else writes gives way while that time is less than ten+   seconds old (`Haskoin.Store.Fleet.Pool.Decide.floorHeld`).++| Decision | While another store has the floor |+| --- | --- |+| an offer | is late, and is made again by the path into the pool |+| a withdrawal, an expiry | removes nothing; the next turn does |+| a build of an entry of the cache | is busy, as before |+| a drop, an eviction | leaves the entries; whoever asked finds them there |+| another move of the tip | does not begin |++Each of those reads `fx:moving`. So one that was decided before the+floor was taken, and would be carried out after, is refused by the+script and decided again. From the moment the token is written, nothing+but the mover changes what the move reads.++Two things still write under a floor, and the move does not read them in+a way that they change. A store renews its lease at every turn: the+move asks which leases still run, and not when each runs out (`HAbove`),+so a renewal is the same answer. And a read of the cache notes that an+xpub was used, in a list that the move does not read.++**The floor lasts as long as the move**, and not ten seconds from when+it was taken. With the time written only at the beginning and at each+piece, a move that took more than ten seconds to decide lost the floor:+the offers that it had held back were taken, and it was refused+(item 17). So the beat is a key of its own, written from a thread of its+own:++- **The move reads the token and never the beat.** So a beat changes no+  answer of the move: the store cannot race itself.+- **The decisions of the mover** (`piece`, `abort`, `advance`) **ask+  only whether the token is theirs.** A move is its store's until+  another decision ends it, which takes the token away.+- **Everyone else reads both**, and ends a move whose store wrote no+  beat for ten seconds. A store that stops loses the floor ten seconds+  later.++**What a store says of its moves.** A move that is not over in ten+minutes has gone wrong, and its store stops the beat. A store whose move+is refused five turns in a row says so in its log, as a warning, with+how long the last took and which answer had changed. One whose move took+a second or more says how long, since transactions wait meanwhile. Both+say where the time went: the blocks read from the database, the cache+read and written, the decision with how much of it was calls to Redis,+the call that carries it out, and how long the garbage collector ran+meanwhile. What would shorten a move depends on which of those is long,+and that is measured on the server, not guessed.++**The cost grows with the block, not with its square.** A decision sees+its own writes. For a question about one cell it goes only through the+writes to that cell (`Haskoin.Store.Fleet.Atomic.Cells.skipOthers`,+proved). Going through every write to the key grew with the square of+the block.++**The block is gone through once, whatever its size.** A decision+starts again from its top each time Redis is asked, and what the move+asks comes in steps that each need the answers of the one before: which+transactions are in the pool, what each does at its addresses, which+cached xpubs have those addresses. Left to find those as it went, the+move went through the whole block five times, and on a server nine.+Three of those times were for a few hundred questions about the children+of its transactions: whether each could still be replaced by fee. The+pool no longer works that out: on Bitcoin every unconfirmed transaction+can be, and on Bitcoin Cash none.++So the move names what it will ask before it starts, in those steps+(`Haskoin.Store.Fleet.Pool.Decide.foreseen`), and leaves at once a pass+in which Redis has not answered all of it+(`Haskoin.Store.Fleet.Atomic.ahead`). A step then costs a call to Redis,+and not a pass over the block. Naming a question changes nothing of what+is decided: a decision depends on a question only by asking it. A+question of the move that is not named costs a pass over the block+again, which a test counts.++`haskoin-store-bench decide` (`bench/Decide.hs`) measures where the time+of deciding goes, without Redis. For a block of 4,000 transactions on a+desktop:++| | Passes | Through the block | Deciding | Collector |+| --- | --- | --- | --- | --- |+| Finding the questions as it went | 8 | 5 | 4.4 s | 1.8 s |+| Naming them ahead | 5 | 1 | 1.3 s | 0.4 s |+| And not working out which can be replaced by fee | 4 | 1 | 1.1 s | 0.3 s |+| The same block in conflict with 60 transactions of the pool, found as it went | 9 | 6 | 5.4 s | |+| And named ahead | 6 | 1 | 1.2 s | |++The last two rows are what a server showed once the rest was in place:+of four blocks, two moved in under five seconds, and two took nine and+fifteen, asking Redis seven times. A block of Bitcoin confirms+transactions that the pool never had, and that spend what transactions+of the pool spend. Those of the pool leave, with all that spends from+them, and each step of that was found by going through the block again.++The first two rows have the same answers and writes, 103,741 and+212,540, and the third 94,409 and 205,207. A pass costs about a+microsecond and a kilobyte allocated for each of them, and a server took+four times as long for each. Compiling the decisions specialised to the+monad that runs them was tried, and changed nothing: the cost was in how+many passes there were, and is now in what one pass does.++How this is known:++| Claim | How it is known |+| --- | --- |+| While its store keeps the beat, no other decision changes an answer that the move depends on, however long that lasts. Neither does the beat | Sampled in the model of Redis, 2,000 random cases: a pool, a move decided, then any mix of offers, withdrawals, expiries, trims, builds, drops, evictions, another move begun, written and given up, and a lease renewed. Each comes seven seconds after the one before, with a beat a second before it. Every answer of the move is the same after them. With the floor taken and no beat after, the same property fails, and it fails without the floor: both are sampled too. |+| A move that is carried out twelve seconds after it was decided is carried out, with leases of ten seconds | Tested against a Valkey: a move that removes 200 transactions from the pool, offers that spend from them every 5 ms, a beat every two seconds. With no beat the same move is refused, which is tested too. |+| The move goes through its block once, whatever the size | Tested against a Valkey. Redis is asked three times for 40 unrelated transactions and for 400. It is asked five times when a quarter have children in the pool, a cached xpub has one of their addresses, and the block is in conflict with ten transactions of the pool that have children; nine times without the conflicts named ahead. The test fails when one question of the move is not named ahead. That naming changes nothing of what is decided is by construction, and the two comparisons with the old Lua scripts hold it to that. |+| A move over a full block is carried out at its first try while others write | Tested against a Valkey: a move that removes 800 transactions from the pool, with offers that spend from them, another store's reports, and builds at their addresses, every 5 ms. It fails if nobody gives way, and if the move depends on when a lease runs out. |+| A store answers from each new block while its node never stops taking transactions | Tested against Bitcoin Core and Bitcoin Cash Node in Podman (`Haskoin.Store.MempoolSpec`): a block that confirms 2,400 transactions of the pool while about sixty a second keep coming. It fails without the floor. |++Not known:++- **That a move always wins within a bound** when the stores of a fleet+  report different blocks at once. That changes the agreed block, and+  so, rightly, has the move decided again.+- **That the member keeps the beat while it works** is tested only where+  a move takes about a second (`Haskoin.Store.MempoolSpec`). In the test+  of the long move, the test writes the beat.+- **How long a move takes on a server** is not measured here. The tests+  run without optimisation. There, a move over 5,400 transactions of+  three inputs and three outputs takes about eight seconds, and one over+  9,000 about thirteen, both carried out at the first try under offers.+  Transactions wait for that long at each block.++### What the fleet relies on++| | Invariant | Why it holds |+| --- | --- | --- |+| I1 | The tip, the pool and the cache's tip change only together | one decision, `advance`, carried out in one step |+| I2 | Each input of a transaction of the pool spends an output of the pool, or one unspent at the tip. An output has one spender. Every unconfirmed parent of a transaction of the pool is in the pool | the offer reads the tip that it was judged at, in the same step |+| I3 | The tip moves only to a block that every live store has a view of | `report.lua` takes a report only from a store with a view of the tip, or alone; `advance` reads the agreed block |+| I4 | The pool is emptied only when no live store could say the way | `advance` empties it for a way that the caller does not know only if the caller is the one live store (`mayEmptyAlone`), and only a store whose report was taken moves the tip |+| I5 | A store keeps a view of the tip while it is live | `prune` decides what to keep in the STM transaction that lets views go, and a block joins the recent ones before its view is taken |+| I6 | Whether a transaction that a node announces is fetched is whether the pool has it | the stores ask the pool alone (`fleetSettled`). A set of what the fleet had seen is no longer kept: a transaction that the pool let go and a node took again stayed out ([mempool-ingestion.md](mempool-ingestion.md), T7) |++### The member's own state++| State | Who changes it | Rule |+| --- | --- | --- |+| `views`, with `recent`, `reported`, `tip` | the member and the block store both prune | one STM transaction per change (`keepViews`) |+| `built`, announcements of builds | the listener and the requests that wait | one STM transaction per change; an xpub is in it only while a request waits |+| `healthy`, `owed`, `newBest`: what wakes the member | set by the web server's health check (`setHealthy`) and the block store (`noteBest`); cleared by the member | `memberLoop` reads them and clears what its turn sees to in one STM transaction, so a signal that comes during a turn wakes the next |++When the member takes a turn is a pure function,+`Haskoin.Store.Fleet.turn`: none while the store is unwell, one at a new+block, one every two seconds, and one as soon as the store is well+again. `FleetSpec` replays any sequence of blocks, health changes and+timers through it, and holds that a well store leaves nothing waiting. A+turn offers no transaction. The path into the pool does, each as it+comes (`memberOffer`).++### After the move: the pool lets go++A move over new blocks alone does not take out of the pool what the+blocks confirmed or made invalid. It marks those transactions, and they+are taken out afterwards, a few at a time. [tip-first.md](tip-first.md)+walks through it, and [fleet-mempool.md](fleet-mempool.md), "The tip+first", has the rest. This section says who owns what.++So the common move reads a fifth of what it read, and writes a+twentieth. The long decision that the floor is for is now the move that+undoes a block, which still removes everything in its own step.++**Who owns what**, between the move and the last transaction out:++- **The move writes the marks** (`pool:leaving`), in the step that moves+  the tip, and only when there are none. A move that finds the marks of+  the move before it waits (`Leaving`).+- **Only taking out removes a mark** (`takeOut`), in the step that takes+  its transaction out. Anyone may do it, for any marked transactions:+  the store that moved the tip, another store at its turn, a request+  that has to read one. It does nothing for a transaction that is not+  marked. So two stores that take the same transaction out take it out+  once: the second finds no mark.+- **No write gets by a mark.** Every key of the pool and of the cache+  is named with the key of the marks (`guarded`, in `poolKeys`), and+  every write to such a key asks first whether Redis has a mark+  (`guarding`). With a mark, the decision stops before it writes.+  Without one, it depends on there being none, as on any answer. Only+  the taking out and the emptying of the pool write among marks+  (`unguarded`). This is by construction: a decision has no other+  function to write with.+- **Every other writer gives way** (`leavingHeld`). Whatever else+  writes to the pool or to the cache asks whether there is a mark, and+  does nothing if there is: the offer, the withdrawal, the expiry, the+  build, the drop, the eviction, and the next move. The next move waits+  from its first step: the move of the cache that comes before it does+  not begin. Each is carried out only if that answer still holds, as+  with any answer of a decision.+- **A read goes by no marked transaction** (`read.lua`, `xpub.lua`). It+  names the marked transactions in its way, they are taken out, and it+  reads again.++**Why no order of events breaks it.**++1. Between the move and the last transaction out, the only writes to the+   pool and to the cache are takings out.+2. Each takes whole transactions out, exactly as the move removed them+   when it did so itself, and the order does not matter.+   `Haskoin.Store.Fleet.DecideSpec` holds this to the old Lua script,+   state by state, with the order and the batches changing.+3. A read sees the pool before a taking out or after it, never half of+   one. And what it reads is written only by transactions that it has+   had taken out (tip-first.md, "Why a reader only has to look at its+   own addresses").+4. A store that stops leaves marks, and the next turn of any store takes+   them out. Nothing waits for a store that is gone.++**How it is known.** That no write gets by a mark: by construction.+That any order of taking out leaves the same pool: proved, for the pool+as a pure value (`anyOrder` in `Haskoin.Store.Fleet.Pool.Order`). For+the pool in Redis: checked in small worlds, sampled and tested+(tip-first.md, "How it is known to be right", has the sizes and the+limits of each).+The checker (`scripts/check-pool.sh`) goes through every pool, every+block and every order of taking out of its worlds, with the decisions+themselves. In every state it checks that writers wait, that every read+is exact, and that any order ends as the move in one step. The+decisions also: random histories, sampled in the model of Redis and+tested against a Redis. In+the model, each of the other writers is tried between two takings out,+and the property fails when one of them is made not to wait. The reads+of the pool: random histories against a Redis, tested. The reads of the+cache: two cases, tested.++The order does matter to one thing that nobody reads: a count can end as+a zero in one order and as nothing in another+([fleet-mempool.md](fleet-mempool.md), "How it is tested").++## The web server++The web server answers each request in a thread of its own. What those+threads share:++| Protocol | Machine | Rule |+| --- | --- | --- |+| The xpub indexer: jobs, queue, waiters | `Haskoin.Store.XPub.Indexer`, one `queue` TVar | one STM transaction per change; a reservation is undone if its request is interrupted |+| Admission: slots and line | `Haskoin.Store.Web.Admission` | one STM transaction per change, masked |+| Events: the log and each client's place | `Haskoin.Store.Web.Events` | append-only log; a client's start is taken before its filters |+| Asking for published transactions | `Haskoin.Store.Web.Publish.due` and `asked` | each transaction's schedule moves on once it was asked for |+| Whether Redis answers (`cacheUp`) | `reach` | three slow answers in a row clear it, any quick one sets it |+| Background loops | `supervised` | a loop that fails is logged and started again |++## What the audit found, and what changed++Each item is a rule that the audit of November 2026 left, and the fault+that the rule prevents.++1. **A peer that still owes blocks is kept when the store comes in+   sync**, among the peers passed over (`Sync.finish`). Forgotten with+   what it owed, its late copy of a block looked unrequested, and a good+   peer was disconnected.+2. **The in-sync check goes through the block store's mailbox.** It ends+   the syncing peer's turn, and the refill ran it on the web server's+   thread.+3. **`request` looks at what a peer owes.** After `forgetRequests` a+   peer could owe a block twice, and be disconnected for the copy that+   it no longer owed.+4. **A block is imported only if it is on the node's main chain, and a+   revert publishes the new best block.** A block of an abandoned branch+   that arrived after the node moved to another chain was imported, and+   the fleet moved to it until the store reverted it.+5. **The lists that pruning goes by are read in the STM transaction that+   lets views go.** Two threads that pruned from lists read earlier+   could let go of the view of the newest block.+6. **Only the one live store may empty the pool, and only a store whose+   report was taken moves the tip.** The old Lua script counted the live+   stores, not which: a store that was not live could empty the pool+   while one other store was live.+7. **A store that cannot read the blocks of a reorganisation waits**+   (`Unreadable`), until the way is too long for every store. It emptied+   the pool, where the documentation said that it waits.+8. **Expiry chooses and withdraws in one step** (`poolExpire`). Chosen+   in a step before, a transaction that had just come back could be+   withdrawn.+9. **`ask` runs masked and undoes its reservation.** A request that was+   interrupted while it took the lock of an xpub left its job reserved+   for good, and every later request for that xpub waited in vain.+10. **The listener of announcements backs off while Redis is down,+    counts only xpubs that requests wait for, wakes nobody at a+    reconnection, and announces only builds that are in the cache**; a+    build that is not fails its job. It spun with no pause, its map grew+    without bound, and a reconnection or an abandoned build woke waiting+    requests as if a build were done, which made them answer 503.+11. **It takes three slow answers from Redis in a row for a store to+    answer 503.** One made every store answer 503 for up to five+    seconds.+12. **Every background loop of the web server is supervised, and the+    read of the newest transaction has a timeout.** Loops could die in+    silence, and the health check could hang on a connection to Redis+    that hung.+13. **The schedule of each published transaction moves on once it was+    asked for.** An error while asking for one skipped the others, and+    could drop one at its last delay.+14. **The member waits on all its signals in one STM transaction+    (`Fleet.turn`), and takes a whole turn when the store is well again.**+    A store that a block made well took no turn for up to two seconds: the+    member woke at the block, read a health that the check had not updated+    yet, and slept until its timer.+15. **The path of a transaction into the pool is one machine,+    `Haskoin.Store.Ingest`, with a statement of what it must do**+    ([mempool-ingestion.md](mempool-ingestion.md)). It replaced five+    separate stages, each of which lost transactions in its own way: the+    queue of announcements, the set of requests, the member's list of what+    waits, the offer at each turn, and the question to the peers at the+    start.+16. **The mover has the floor, and what else writes gives way** ("The+    floor", above). With transactions offered all the time, a move was+    refused for ever. A test moves the tip while others write, as no+    test did.+17. **A decision has one clock, the mover keeps the floor for as long as+    it works, questions and writes go a thousand to an argument, and a+    store whose move is refused says which answer had changed.** A move+    over a full block was still refused at every turn, for three faults+    of a move that takes ten seconds. Two are told above ("One clock",+    "The floor lasts as long as the move"). The third: the move went to+    Redis as one command of 1,008,352 arguments, four in a hundred under+    the most that Redis takes, and a block a little larger would have+    closed the connection. No test had seen them: the tests moved 800+    small transactions in under a second, with leases of a minute. Each+    now has a test at the time or the size that it failed at.++### Known limits, left as they are++- **Redis that fails over to a replica that lags**, or restarts from an+  old snapshot, keeps its epoch, the number by which stores notice that+  Redis lost its data. So the stores do not notice, and what was offered+  since is gone from the pool. The pool fills again from new+  announcements and from the next reading of the nodes' mempools. Run+  Redis without replicas that can be promoted behind, or flush it, which+  the stores notice.+- **The stream of events keeps 10,000 entries.** A listener further+  behind loses what was trimmed, without an error.+- **A store that stops for more than ten seconds in the middle of a+  move**, as a machine that swaps can, loses the floor. Its move can be+  ended by another store, or refused. That costs time, never the state:+  the last decision of the move reads the token and every answer.+- **Transactions wait after a block**, while its transactions are taken+  out of the pool: one to two seconds for a full block on a server. The+  move of the tip itself is under a second. A move that undoes a block+  still takes seconds, and transactions wait for all of it.+- **The tip follows its slowest healthy store**, whose own node may be+  hours behind the network.+- **`fleetMove` sets the tip without the pool.** It is for the tests.+  The stores move the tip with `fleetCommit` only.++## Checking a change++- **A change to a machine changes its spec.** Add the property that the+  change keeps.+- **A new piece of shared state** names its owner and its rule in the+  tables above.+- **A change to a Lua script** is tested against Redis (the+  `Haskoin.Store.Fleet.*` specs), and the model of the fleet changes+  with it.+- **A change to a decision of the pool** is tested against the model of+  the fleet (`RedisSpec`), and one to a decision of the cache against+  the stores that read it (`CacheSpec`). `DecideSpec` or+  `XPubDecideSpec` then fails, since the old Lua script that it compares+  with has not changed. Say there what differs and why, or drop the+  comparison once the old script is no longer what the stores should do.+- **A new question in the move** is named in `foreseen`, or the move of+  a full block goes through the block once more for it. `asks Redis no+  more times` in `DecideSpec` fails then, and+  `haskoin-store-bench decide` says what it costs.+- **A new key of the pool or of the cache** is named in its record of+  keys, with its kind. A decision imports+  `Haskoin.Store.Fleet.Atomic.Keys`, never the writes of+  `Haskoin.Store.Fleet.Atomic`.
haskoin-store.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack  name:           haskoin-store-version:        1.16.7+version:        2.0.0 synopsis:       Storage and index for Bitcoin and Bitcoin Cash description:    An indexer for Bitcoin and Bitcoin Cash. It downloads blocks and mempool                 transactions from the peer-to-peer network, indexes the chain in RocksDB and@@ -27,8 +27,8 @@     GHC == 9.12.4 extra-source-files:     cbits/haskoin_store_merge.h+    src/Haskoin/Store/Fleet/lua/atomic.lua     src/Haskoin/Store/Fleet/lua/move.lua-    src/Haskoin/Store/Fleet/lua/pool.lua     src/Haskoin/Store/Fleet/lua/read.lua     src/Haskoin/Store/Fleet/lua/report.lua     src/Haskoin/Store/Fleet/lua/xpub.lua@@ -41,6 +41,7 @@ extra-doc-files:     README.md     CHANGELOG.md+    docs/concurrency.md  source-repository head   type: git@@ -50,11 +51,11 @@   exposed-modules:       Haskoin.Store       Haskoin.Store.BlockStore-      Haskoin.Store.BlockStore.Pending       Haskoin.Store.BlockStore.Sync       Haskoin.Store.Common       Haskoin.Store.Database.Merge       Haskoin.Store.Database.Migrate+      Haskoin.Store.Database.Migrate.Tokens       Haskoin.Store.Database.Query       Haskoin.Store.Database.Query.Pooled       Haskoin.Store.Database.Reader@@ -66,12 +67,27 @@       Haskoin.Store.Database.Writer       Haskoin.Store.Exception       Haskoin.Store.Fleet+      Haskoin.Store.Fleet.Atomic+      Haskoin.Store.Fleet.Atomic.Cells+      Haskoin.Store.Fleet.Atomic.Keys+      Haskoin.Store.Fleet.Atomic.Redis       Haskoin.Store.Fleet.Member       Haskoin.Store.Fleet.Pool+      Haskoin.Store.Fleet.Pool.Decide+      Haskoin.Store.Fleet.Pool.Order+      Haskoin.Store.Fleet.Pool.Types       Haskoin.Store.Fleet.Redis+      Haskoin.Store.Fleet.Script       Haskoin.Store.Fleet.XPub+      Haskoin.Store.Fleet.XPub.Decide+      Haskoin.Store.Ingest+      Haskoin.Store.Ingest.Ledger+      Haskoin.Store.Ingest.Run       Haskoin.Store.Logic       Haskoin.Store.Manager+      Haskoin.Store.NodePeer+      Haskoin.Store.NodeRpc+      Haskoin.Store.NodeZmq       Haskoin.Store.Outage       Haskoin.Store.Runtime       Haskoin.Store.Startup@@ -123,10 +139,11 @@     , file-embed >=0.0.16.0 && <0.1     , hashable >=1.5.1.0 && <1.6     , hashtables >=1.4.2 && <1.5-    , haskoin-core >=2.0.1 && <2.1-    , haskoin-node >=2.6.1 && <2.7-    , haskoin-store-data >=3.0.1 && <3.1+    , haskoin-core >=3.0.0 && <3.1+    , haskoin-node >=2.7.0 && <2.8+    , haskoin-store-data >=4.0.0 && <4.1     , hedis >=0.16.4 && <0.17+    , http-client >=0.7.19 && <0.8     , http-types >=0.12.6 && <0.13     , lens >=5.3.6 && <5.4     , monad-control >=1.0.3.1 && <1.1@@ -159,7 +176,6 @@   exposed-modules:       Haskoin.Store.Integration.Image       Haskoin.Store.Integration.Node-      Haskoin.Store.Integration.Podman       Haskoin.Store.Integration.Temp       Haskoin.Store.Integration.Valkey   other-modules:@@ -191,17 +207,19 @@     , file-embed >=0.0.16.0 && <0.1     , hashable >=1.5.1.0 && <1.6     , hashtables >=1.4.2 && <1.5-    , haskoin-core >=2.0.1 && <2.1-    , haskoin-node >=2.6.1 && <2.7+    , haskoin-core >=3.0.0 && <3.1+    , haskoin-node >=2.7.0 && <2.8     , haskoin-store-    , haskoin-store-data >=3.0.1 && <3.1+    , haskoin-store-data >=4.0.0 && <4.1     , hedis >=0.16.4 && <0.17+    , http-client     , http-types >=0.12.6 && <0.13     , lens >=5.3.6 && <5.4     , monad-control >=1.0.3.1 && <1.1     , mtl >=2.3.2 && <2.4     , network >=3.2.12.0 && <3.3     , nqe >=0.7.0 && <0.8+    , podman-test >=0.1.0 && <0.2     , process >=1.6.26.1 && <1.7     , random >=1.3.1 && <1.4     , rocksdb-haskell-jprupp >=2.8.0 && <2.9@@ -258,11 +276,12 @@     , filepath >=1.5.5.0 && <1.6     , hashable >=1.5.1.0 && <1.6     , hashtables >=1.4.2 && <1.5-    , haskoin-core >=2.0.1 && <2.1-    , haskoin-node >=2.6.1 && <2.7+    , haskoin-core >=3.0.0 && <3.1+    , haskoin-node >=2.7.0 && <2.8     , haskoin-store-    , haskoin-store-data >=3.0.1 && <3.1+    , haskoin-store-data >=4.0.0 && <4.1     , hedis >=0.16.4 && <0.17+    , http-client >=0.7.19 && <0.8     , http-types >=0.12.6 && <0.13     , lens >=5.3.6 && <5.4     , monad-control >=1.0.3.1 && <1.1@@ -296,9 +315,7 @@   type: exitcode-stdio-1.0   main-is: Spec.hs   other-modules:-      Haskoin.Store.BlockStore.PendingSpec       Haskoin.Store.BlockStore.SyncSpec-      Haskoin.Store.BlockStoreSpec       Haskoin.Store.CommonSpec       Haskoin.Store.Database.MergeSpec       Haskoin.Store.Database.MigrateSpec@@ -306,16 +323,27 @@       Haskoin.Store.Database.StallsSpec       Haskoin.Store.Database.ViewsSpec       Haskoin.Store.Database.WriterSpec+      Haskoin.Store.DownloadSpec       Haskoin.Store.ExceptionSpec+      Haskoin.Store.Fleet.AtomicSpec       Haskoin.Store.Fleet.CacheSpec+      Haskoin.Store.Fleet.DecideSpec+      Haskoin.Store.Fleet.LeavingModel+      Haskoin.Store.Fleet.LeavingSpec+      Haskoin.Store.Fleet.Oracle       Haskoin.Store.Fleet.PoolSpec       Haskoin.Store.Fleet.RedisSpec+      Haskoin.Store.Fleet.XPubDecideSpec       Haskoin.Store.Fleet.XPubSpec       Haskoin.Store.FleetSpec       Haskoin.Store.Histories+      Haskoin.Store.Ingest.Model+      Haskoin.Store.IngestSpec       Haskoin.Store.Integration.TempSpec       Haskoin.Store.IntegrationSpec       Haskoin.Store.LogicSpec+      Haskoin.Store.MempoolSpec+      Haskoin.Store.NodeAxiomsSpec       Haskoin.Store.OutageSpec       Haskoin.Store.TestBlocks       Haskoin.Store.Web.AdmissionSpec@@ -326,7 +354,6 @@       Haskoin.Store.Web.RouterSpec       Haskoin.Store.WebSpec       Haskoin.Store.XPub.IndexerSpec-      Haskoin.StoreSpec       Paths_haskoin_store   autogen-modules:       Paths_haskoin_store@@ -354,17 +381,18 @@     , data-default >=0.8.0.2 && <0.9     , deepseq >=1.5.1.0 && <1.6     , directory >=1.3.10.1 && <1.4-    , fast-logger >=3.2.9 && <3.3+    , fast-logger >=3.2.9 && <3.4     , file-embed >=0.0.16.0 && <0.1     , filepath >=1.5.5.0 && <1.6     , hashable >=1.5.1.0 && <1.6     , hashtables >=1.4.2 && <1.5-    , haskoin-core >=2.0.1 && <2.1-    , haskoin-node >=2.6.1 && <2.7+    , haskoin-core >=3.0.0 && <3.1+    , haskoin-node >=2.7.0 && <2.8     , haskoin-store-    , haskoin-store-data >=3.0.1 && <3.1+    , haskoin-store-data >=4.0.0 && <4.1     , hedis >=0.16.4 && <0.17     , hspec >=2.11.18 && <2.12+    , http-client >=0.7.19 && <0.8     , http-types >=0.12.6 && <0.13     , integration     , lens >=5.3.6 && <5.4@@ -372,6 +400,7 @@     , mtl >=2.3.2 && <2.4     , network >=3.2.12.0 && <3.3     , nqe >=0.7.0 && <0.8+    , podman-test     , process >=1.6.26.1 && <1.7     , random >=1.3.1 && <1.4     , rocksdb-haskell-jprupp >=2.8.0 && <2.9@@ -401,6 +430,7 @@   main-is: Main.hs   other-modules:       Admission+      Decide       Import       Merge       Paths_haskoin_store@@ -432,11 +462,12 @@     , filepath >=1.5.5.0 && <1.6     , hashable >=1.5.1.0 && <1.6     , hashtables >=1.4.2 && <1.5-    , haskoin-core >=2.0.1 && <2.1-    , haskoin-node >=2.6.1 && <2.7+    , haskoin-core >=3.0.0 && <3.1+    , haskoin-node >=2.7.0 && <2.8     , haskoin-store-    , haskoin-store-data >=3.0.1 && <3.1+    , haskoin-store-data >=4.0.0 && <4.1     , hedis >=0.16.4 && <0.17+    , http-client >=0.7.19 && <0.8     , http-types >=0.12.6 && <0.13     , integration     , lens >=5.3.6 && <5.4
integration/Haskoin/Store/Integration/Image.hs view
@@ -32,7 +32,8 @@ -- -- To move to new releases, change the versions and hashes below after -- checking them the same way. The tag of the image is a hash of the whole--- recipe, so a change builds a new image and the old one is no longer used.+-- recipe ("Test.Podman.Image"), so a change builds a new image and the old+-- one is no longer used. module Haskoin.Store.Integration.Image   ( testImage,     coreBin,@@ -42,13 +43,7 @@ where  import Data.ByteString.Char8 qualified as C8-import Data.List (intercalate)-import Data.Serialize (encode)-import Data.Text qualified as T-import Haskoin (encodeHex, sha256)-import Haskoin.Store.Integration.Temp (withSystemTempDirectory)-import System.Exit (ExitCode (..))-import System.Process (readProcessWithExitCode)+import Test.Podman (Image (..), ImageSpec (..))  -- | Ubuntu 26.04, by the digest of its multi-architecture index. base :: String@@ -153,34 +148,17 @@         " rm /tmp/release.tar.gz"       ] --- | Tag of the image: a hash of its recipe.-tag :: String-tag =-  "localhost/haskoin-store-test:"-    <> take 16 (T.unpack (encodeHex (encode (sha256 (C8.pack containerfile)))))---- | Build the image unless it exists already, and return its tag. The first--- build downloads the base image, the packages and the two releases, and may--- take a few minutes; later builds of a changed recipe reuse the layers that--- did not change (see the recipe above). Images and layers are never removed by--- the tests. The build may use 1 GiB of memory.-testImage :: IO String-testImage = do-  (exists, _, _) <- readProcessWithExitCode "podman" ["image", "exists", tag] ""-  case exists of-    ExitSuccess -> return tag-    _ -> withSystemTempDirectory "haskoin-store-image" $ \ctx -> do-      (code, out, err) <--        readProcessWithExitCode-          "podman"-          ["build", "--layers", "--memory", "1g", "--tag", tag, "--file", "-", ctx]-          containerfile-      case code of-        ExitSuccess -> return tag-        _ ->-          fail $-            intercalate-              "\n"-              ["Could not build the test image " <> tag <> ":", lastLines out, lastLines err]-  where-    lastLines = unlines . reverse . take 30 . reverse . lines+-- | The image, built from the recipe by podman-test the first time a test+-- needs it, and tagged by a hash of the recipe. The first build downloads+-- the base image, the packages and the two releases, and may take a few+-- minutes; later builds of a changed recipe reuse the layers that did not+-- change (see the recipe above). Test processes that start together build+-- it once. Images and layers are never removed by the tests.+testImage :: Image+testImage =+  Built+    ImageSpec+      { name = "haskoin-store-test",+        containerfile = C8.pack containerfile,+        files = []+      }
integration/Haskoin/Store/Integration/Node.hs view
@@ -16,6 +16,12 @@ -- test connects to the node over the peer-to-peer protocol, as it would to -- the real networks. --+-- The node runs in a container of podman-test ("Test.Podman"), whose bridge+-- joins its RPC and peer-to-peer ports to Unix sockets of its pod: the+-- tests call the RPC through one ('Haskoin.Store.Web.unixSocketManager'),+-- and the store connects to the node as the peer @unix:PATH@. Neither node+-- listens on a socket itself.+-- -- Only RPC calls that both nodes have are used. Bitcoin Cash Node has no -- @generateblock@, so the reorganisation test is built on coinbase maturity -- instead (see "Haskoin.Store.IntegrationSpec").@@ -23,7 +29,12 @@   ( NodeKind (..),     Node (..),     nodeContainer,+    nodeContainerAt,     strangerContainer,+    nodeOf,+    nodeAt,+    freezeNode,+    thawNode,     nodeNetwork,     RpcError (..),     rpc,@@ -45,7 +56,7 @@  import Control.Concurrent (threadDelay) import Control.Exception (Exception, throwIO)-import Control.Lens ((&), (?~), (^.))+import Control.Lens ((&), (.~), (?~), (^.)) import Control.Monad (void) import Data.Aeson (Value (..), eitherDecode, object, (.=)) import Data.Aeson.Key qualified as Key@@ -56,9 +67,21 @@ import Data.Word (Word64) import Haskoin (Network, bchRegTest, btcRegTest) import Haskoin.Store.Exception (tryAny)-import Haskoin.Store.Integration.Image (bchnBin, coreBin)-import Haskoin.Store.Integration.Podman (ContainerSpec (..))+import Haskoin.Store.Integration.Image (bchnBin, coreBin, testImage)+import Haskoin.Store.Web (unixSocketManager)+import Network.HTTP.Client (Manager, newManager) import Network.Wreq qualified as Wreq+import Test.Podman+  ( Address (..),+    ContainerSpec (..),+    Endpoint (..),+    Pod,+    address,+    container,+    containerName,+    socketInside,+  )+import Test.Podman.Command (podman)  -- | Which node software. data NodeKind = BitcoinCore | BitcoinCashNode@@ -67,12 +90,68 @@ -- | A node and how to reach it. data Node = Node   { kind :: !NodeKind,-    -- | URL of the JSON-RPC interface+    -- | URL of the JSON-RPC interface, with its user and password; its+    -- host is not used, since every request goes through 'rpcSocket'     url :: !String,-    -- | port of the peer-to-peer interface on 127.0.0.1-    p2p :: !Int+    -- | the Unix socket of the JSON-RPC interface+    rpcSocket :: !FilePath,+    -- | an HTTP client whose connections go to 'rpcSocket'+    manager :: !Manager,+    -- | the peer of the store: the Unix socket of the peer-to-peer+    -- interface, as @unix:PATH@+    peer :: !String,+    -- | where the node publishes what it takes over ZeroMQ, as the+    -- address that a subscriber is given: @ipc:\/\/PATH@+    zmq :: !String   } +-- | The node of a pod that runs 'nodeContainer' or 'strangerContainer'.+nodeOf :: NodeKind -> Pod -> IO Node+nodeOf = nodeAt 0++-- | Node number @i@ of a pod that runs 'nodeContainerAt' for it.+nodeAt :: Int -> NodeKind -> Pod -> IO Node+nodeAt i kind p = do+  rpcSocket <- socketOf ("rpc" <> suffix i)+  p2pSocket <- socketOf ("p2p" <> suffix i)+  zmqSocket <- socketOf ("zmq" <> suffix i)+  manager <- newManager (unixSocketManager rpcSocket)+  return+    Node+      { kind,+        url = "http://test:test@localhost/",+        rpcSocket,+        manager,+        peer = "unix:" <> p2pSocket,+        zmq = "ipc://" <> zmqSocket+      }+  where+    socketOf e = case address p e of+      UnixSocket path -> return path+      a -> fail ("The endpoint " <> e <> " of the node is not a socket: " <> show a)++-- | Stop node number @i@ of a pod in its tracks, with @SIGSTOP@ sent from+-- outside its container: the node is the first process of the container,+-- which takes no signal sent from inside. Its connections stay open and it+-- answers nothing on them, as a peer that hangs does, and its RPC answers+-- nothing either until 'thawNode'.+freezeNode :: Pod -> Int -> NodeKind -> IO ()+freezeNode p i kind = signalNode p i kind "STOP"++-- | Let node number @i@ go on after 'freezeNode'.+thawNode :: Pod -> Int -> NodeKind -> IO ()+thawNode p i kind = signalNode p i kind "CONT"++signalNode :: Pod -> Int -> NodeKind -> String -> IO ()+signalNode p i kind sig =+  void $ podman ["kill", "--signal", sig, containerName p (nodeContainerAt i kind).name]++-- | What sets the names of node number @i@ apart: nothing for the first, so+-- that the names of a pod of one node stay as they were.+suffix :: Int -> String+suffix 0 = ""+suffix i = show i+ -- | Network constants of the regtest chain of a node. nodeNetwork :: NodeKind -> Network nodeNetwork BitcoinCore = btcRegTest@@ -81,26 +160,37 @@ -- | Container of a regtest node, from the test image -- ("Haskoin.Store.Integration.Image"): its chain is in a tmpfs of 512 MiB, -- it may use 1 GiB of memory, and its caches and mempool are kept small.+-- Its RPC and peer-to-peer ports are bridged to the sockets @rpc@ and+-- @p2p@ of its pod: neither node listens on a Unix socket for those. It+-- publishes over ZeroMQ on the socket @zmq@ of its pod, which it makes+-- itself. -- -- Every peer is whitelisted, so that the store may ask for the mempool and -- gets transactions relayed without delay.-nodeContainer :: NodeKind -> String -> ContainerSpec-nodeContainer kind image =-  ContainerSpec-    { name = case kind of-        BitcoinCore -> "bitcoin-core"-        BitcoinCashNode -> "bitcoin-cash-node",-      image = image,-      options =-        [ "--memory",-          "1g",-          "--tmpfs",-          "/chain:rw,size=512m,mode=1777",-          "--entrypoint",-          case kind of-            BitcoinCore -> coreBin-            BitcoinCashNode -> bchnBin-        ],+nodeContainer :: NodeKind -> ContainerSpec+nodeContainer = nodeContainerAt 0++-- | Node number @i@ of a pod of several nodes, as 'nodeContainer' is the+-- first: the containers of a pod share its network, so each listens on+-- ports of its own, ten above those of the one before, with endpoints+-- @rpcI@ and @p2pI@ (no number for the first). Add+-- @-addnode=127.0.0.1:18444@ to its command for the first as a peer.+nodeContainerAt :: Int -> NodeKind -> ContainerSpec+nodeContainerAt i kind =+  ( container+      ( ( case kind of+            BitcoinCore -> "bitcoin-core"+            BitcoinCashNode -> "bitcoin-cash-node"+        )+          <> (if i == 0 then "" else "-" <> show i)+      )+      testImage+  )+    { entrypoint = Just $ case kind of+        BitcoinCore -> coreBin+        BitcoinCashNode -> bchnBin,+      memory = Just "1g",+      tmpfs = [("/chain", "512m")],       command =         [ "-regtest",           "-datadir=/chain",@@ -111,30 +201,65 @@           "-rpcbind=0.0.0.0",           "-rpcallowip=0.0.0.0/0",           "-bind=0.0.0.0",+          "-port=" <> show p2pPort,+          "-rpcport=" <> show rpcPort,           "-listen=1",           "-whitelist=0.0.0.0/0",           "-txindex=1",           "-fallbackfee=0.0002",           "-dbcache=16",-          "-maxmempool=16"+          "-maxmempool=16",+          -- the ids of the transactions that it takes and the hashes of+          -- the blocks that become its tip, published over ZeroMQ on a+          -- Unix socket that the node makes itself+          "-zmqpubhashtx=" <> zmqAddress,+          "-zmqpubhashblock=" <> zmqAddress         ]           <> case kind of             -- releases of Bitcoin Cash Node stop serving RPC some months             -- after they come out unless told not to             BitcoinCashNode -> ["-expire=0"]             BitcoinCore -> [],-      ports = [18443, 18444]+      endpoints =+        [ Bridged ("rpc" <> suffix i) rpcPort,+          Bridged ("p2p" <> suffix i) p2pPort,+          Native ("zmq" <> suffix i)+        ]     }+  where+    rpcPort = 18443 + 10 * i+    p2pPort = 18444 + 10 * i+    -- The two nodes write a Unix socket differently. Bitcoin Core 32+    -- takes @ipc:\/\/@ for a port that it cannot read, and does not+    -- start: a node of a server did not, for 25 minutes, while these+    -- tests gave both nodes a TCP port and a bridge.+    zmqAddress = case kind of+      BitcoinCore -> "unix:" <> socketInside ("zmq" <> suffix i)+      BitcoinCashNode -> "ipc://" <> socketInside ("zmq" <> suffix i)  -- | The same node without the whitelist: it treats the store as it treats -- any peer that connected to it. It announces transactions on its timer--- and not at once, does not answer a request for its mempool, and may--- close the connections of a peer that sends it an invalid transaction.-strangerContainer :: NodeKind -> String -> ContainerSpec-strangerContainer kind image =-  spec {name = spec.name <> "-stranger", command = filter (/= "-whitelist=0.0.0.0/0") spec.command}+-- and not at once, and may close the connections of a peer that sends it an+-- invalid transaction.+--+-- Bitcoin Core gives the store its mempool and nothing more (the permission+-- @mempool@), which the tests tell the store (@peerPermissions@): once the+-- pool fills, the store asks the peers whose node allows it for their+-- mempools, and a node that does not allow it closes the connection, with+-- what it had in its mempool then never announced again. Bitcoin Cash Node+-- gets no permission: it serves Bloom filters, and answers the request of+-- any peer.+strangerContainer :: NodeKind -> ContainerSpec+strangerContainer kind =+  spec+    { name = spec.name <> "-stranger",+      command = filter (/= "-whitelist=0.0.0.0/0") spec.command <> mempoolOnly+    }   where-    spec = nodeContainer kind image+    spec = nodeContainer kind+    mempoolOnly = case kind of+      BitcoinCore -> ["-whitelist=mempool@0.0.0.0/0"]+      BitcoinCashNode -> []  -- | Error returned by a node. data RpcError = RpcError !Text !Value@@ -149,6 +274,7 @@         Wreq.defaults           & Wreq.auth ?~ Wreq.basicAuth "test" "test"           & Wreq.checkResponse ?~ (\_ _ -> return ())+          & Wreq.manager .~ Right node.manager       body =         object           [ "jsonrpc" .= ("1.0" :: Text),
− integration/Haskoin/Store/Integration/Podman.hs
@@ -1,191 +0,0 @@--- |--- Module      : Haskoin.Store.Integration.Podman--- Copyright   : (c) Haskoin Developers--- License     : MIT--- Maintainer  : jprupp@protonmail.ch--- Stability   : experimental--- Portability : POSIX------ Containers for the integration tests, run with Podman.------ The integration tests need real nodes and a real Redis, which are easiest--- to get, at pinned versions and without installing anything, as container--- images. Podman runs them without a daemon and without root, so a developer--- or a CI runner can use it as it is.------ Everything is kept off the disk and cleaned up:------ * containers run with @--rm@ and are removed with @podman rm --force@ when---   the test that started them ends, even if it fails;--- * the volumes that images declare are mounted as tmpfs---   (@--image-volume tmpfs@), and data directories are tmpfs mounts of---   limited size;--- * every container has a memory limit;--- * containers carry a label with the process ID of the test run, and---   containers left by a test run that was killed (whose process is gone) are---   removed before new ones start.------ Ports are published on random ports of the loopback interface, so several--- test runs can share a machine.-module Haskoin.Store.Integration.Podman-  ( podmanUsable,-    ContainerSpec (..),-    Container (..),-    withContainer,-    hostPort,-    withRamDir,-  )-where--import Control.Monad (forM_, unless, void)-import Data.Aeson qualified as A-import Data.Aeson.Key qualified as Key-import Data.Aeson.KeyMap qualified as KeyMap-import Data.ByteString.Char8 qualified as C8-import Data.ByteString.Lazy qualified as BL-import Data.Char (isDigit, isSpace)-import Data.List (dropWhileEnd)-import Data.Text qualified as T-import Haskoin.Store.Exception (bracket, onException, tryAny)-import Haskoin.Store.Integration.Temp (withTempDirectory)-import System.Directory (doesDirectoryExist, doesPathExist, getTemporaryDirectory)-import System.Environment (lookupEnv)-import System.Exit (ExitCode (..))-import System.IO (hPutStrLn, stderr)-import System.Process (getCurrentPid, readProcessWithExitCode)-import System.Timeout (timeout)---- | Whether Podman can run containers here, or why not. Set--- @HASKOIN_STORE_NO_PODMAN@ to a value other than @0@ to skip the tests that--- need it.-podmanUsable :: IO (Either String ())-podmanUsable = do-  skip <- lookupEnv "HASKOIN_STORE_NO_PODMAN"-  case skip of-    Just v | v `notElem` ["", "0"] -> return (Left "HASKOIN_STORE_NO_PODMAN is set")-    _ -> do-      r <--        tryAny . timeout (60 * 1000 * 1000) $-          readProcessWithExitCode "podman" ["info", "--format", "{{.Host.Arch}}"] ""-      -- containers left by a test run that was killed are removed before-      -- anything else, even if this run fails before starting any-      case r of-        Right (Just (ExitSuccess, _, _)) -> removeStale-        _ -> return ()-      return $ case r of-        Left e -> Left ("Podman is not available: " <> show e)-        Right Nothing -> Left "podman info did not answer within a minute"-        Right (Just (ExitSuccess, _, _)) -> Right ()-        Right (Just (_, _, err)) -> Left ("Podman cannot run containers: " <> trim err)---- | What to run.-data ContainerSpec = ContainerSpec-  { -- | short name, part of the container name-    name :: !String,-    -- | image, with a pinned tag-    image :: !String,-    -- | options of @podman run@, such as memory limits and tmpfs mounts-    options :: ![String],-    -- | command and arguments, after the image-    command :: ![String],-    -- | TCP ports to publish on random ports of 127.0.0.1-    ports :: ![Int]-  }---- | A running container.-data Container = Container-  { -- | container ID-    cid :: !String,-    -- | container name-    name :: !String-  }---- | Label on every container started by the tests. Its value is the process--- ID of the test run.-testLabel :: String-testLabel = "haskoin-store-test"---- | Run a container while an action runs, and remove it afterwards. If the--- action throws, the last lines of the log of the container are printed to--- help find out why.-withContainer :: ContainerSpec -> (Container -> IO a) -> IO a-withContainer spec act = do-  removeStale-  pid <- show <$> getCurrentPid-  let cname = testLabel <> "-" <> pid <> "-" <> spec.name-      args =-        ["run", "--detach", "--rm", "--name", cname]-          <> ["--label", testLabel <> "=" <> pid, "--image-volume", "tmpfs"]-          <> spec.options-          <> concatMap (\p -> ["--publish", "127.0.0.1::" <> show p]) spec.ports-          <> [spec.image]-          <> spec.command-  bracket (start cname args) stop $ \c -> act c `onException` logs c-  where-    start cname args = do-      (code, out, err) <- readProcessWithExitCode "podman" args ""-      case code of-        ExitSuccess -> return Container {cid = trim out, name = cname}-        _ -> do-          -- a container may exist even though the command failed-          void $ readProcessWithExitCode "podman" ["rm", "--force", cname] ""-          fail ("podman run " <> spec.image <> " failed: " <> trim err)-    stop :: Container -> IO ()-    stop c =-      void $ readProcessWithExitCode "podman" ["rm", "--force", "--time", "2", c.cid] ""-    logs :: Container -> IO ()-    logs c = do-      (_, out, err) <- readProcessWithExitCode "podman" ["logs", "--tail", "40", c.cid] ""-      hPutStrLn stderr $ "--- last lines of the log of " <> c.name <> " ---\n" <> out <> err---- | Remove the containers of test runs whose process is gone. The list--- comes as JSON: the Go templates of @podman ps@ cannot index the labels in--- every version of Podman.-removeStale :: IO ()-removeStale = do-  (code, out, _) <--    readProcessWithExitCode-      "podman"-      ["ps", "--all", "--filter", "label=" <> testLabel, "--format", "json"]-      ""-  case (code, A.decode (BL.fromStrict (C8.pack out))) of-    (ExitSuccess, Just cs) ->-      forM_ (cs :: [A.Value]) $ \c -> case staleOf c of-        Just (cid, pid) | all isDigit pid -> do-          alive <- doesPathExist ("/proc/" <> pid)-          unless alive . void $ readProcessWithExitCode "podman" ["rm", "--force", cid] ""-        _ -> return ()-    _ -> return ()-  where-    staleOf c = do-      A.Object o <- Just c-      A.String cid <- KeyMap.lookup "Id" o-      A.Object labels <- KeyMap.lookup "Labels" o-      A.String pid <- KeyMap.lookup (Key.fromString testLabel) labels-      return (T.unpack cid, T.unpack pid)---- | Port of the host where a port of a container is published.-hostPort :: Container -> Int -> IO Int-hostPort c p = do-  (code, out, err) <- readProcessWithExitCode "podman" ["port", c.cid, show p <> "/tcp"] ""-  case (code, lines out) of-    (ExitSuccess, l : _)-      | [(n, "")] <- reads (reverse (takeWhile (/= ':') (reverse (trim l)))) ->-          return n-    _ -> fail ("Cannot find the published port " <> show p <> " of " <> c.name <> ": " <> trim err)--trim :: String -> String-trim = dropWhileEnd isSpace . dropWhile isSpace---- | A temporary directory in memory: under @/dev/shm@ if there is one, else--- under @$XDG_RUNTIME_DIR@, else the usual temporary directory.-withRamDir :: (FilePath -> IO a) -> IO a-withRamDir f = do-  shm <- doesDirectoryExist "/dev/shm"-  xdg <- lookupEnv "XDG_RUNTIME_DIR"-  tmp <- getTemporaryDirectory-  let base-        | shm = "/dev/shm"-        | Just x <- xdg = x-        | otherwise = tmp-  withTempDirectory base "haskoin-store-test" f
integration/Haskoin/Store/Integration/Temp.hs view
@@ -15,17 +15,19 @@ -- is stopped from outside while it removes its database, by a timeout or by -- a second Ctrl-C, still removes all of it, where the others could leave -- half of it behind. A database of a test is tens of megabytes, often in--- memory ('Haskoin.Store.Integration.Podman.withRamDir'), so what is left+-- memory ('withRamDir'), so what is left -- behind matters. module Haskoin.Store.Integration.Temp   ( withSystemTempDirectory,     withTempDirectory,+    withRamDir,   ) where  import Control.Exception (IOException, handle) import Haskoin.Store.Exception (bracket)-import System.Directory (removeDirectoryRecursive)+import System.Directory (doesDirectoryExist, getTemporaryDirectory, removeDirectoryRecursive)+import System.Environment (lookupEnv) import System.IO.Temp (createTempDirectory, getCanonicalTemporaryDirectory)  -- | Run an action with a new directory under the temporary directory of@@ -43,3 +45,18 @@ withTempDirectory parent template = bracket (createTempDirectory parent template) remove   where     remove = handle (\(_ :: IOException) -> return ()) . removeDirectoryRecursive++-- | A temporary directory in memory: under @/dev/shm@ if there is one, else+-- under @$XDG_RUNTIME_DIR@, else the usual temporary directory. The+-- databases of the integration tests are there, so that their writes cost+-- no disk.+withRamDir :: (FilePath -> IO a) -> IO a+withRamDir f = do+  shm <- doesDirectoryExist "/dev/shm"+  xdg <- lookupEnv "XDG_RUNTIME_DIR"+  tmp <- getTemporaryDirectory+  let base+        | shm = "/dev/shm"+        | Just x <- xdg = x+        | otherwise = tmp+  withTempDirectory base "haskoin-store-test" f
integration/Haskoin/Store/Integration/Valkey.hs view
@@ -6,34 +6,37 @@ -- Stability   : experimental -- Portability : POSIX ----- A Redis server for the integration tests: Valkey, the--- Redis-compatible server that Ubuntu ships, from the test image.+-- A Redis server for the integration tests: Valkey, the Redis-compatible+-- server that Ubuntu ships, from the test image, in a container of+-- podman-test ("Test.Podman").+--+-- It listens on a Unix socket of its pod and on no port, so tests that run+-- at once each reach their own, and the store reaches it as @unix:PATH@+-- ('Haskoin.Store.Startup.redisConnectInfo'). module Haskoin.Store.Integration.Valkey   ( redisContainer,-    waitRedis,+    redisURL,   ) where -import Control.Concurrent (threadDelay)-import Database.Redis qualified as Redis-import Haskoin.Store.Exception (bracket, tryAny)-import Haskoin.Store.Integration.Image (valkeyBin)-import Haskoin.Store.Integration.Podman (ContainerSpec (..))+import Haskoin.Store.Integration.Image (testImage, valkeyBin)+import Test.Podman (Address (..), ContainerSpec (..), Endpoint (..), Pod, address, container, socketInside) --- | Valkey, the Redis-compatible server of Ubuntu, from the test image, listening on every interface of the container--- (only its published port is reachable, on 127.0.0.1), with nothing saved--- to disk and at most 128 MiB of data.-redisContainer :: String -> ContainerSpec-redisContainer image =-  ContainerSpec-    { name = "redis",-      image = image,-      options = ["--memory", "256m", "--entrypoint", valkeyBin],+-- | Valkey, from the test image, on the socket @redis@ of its pod, open to+-- every user so that the tests can reach it from outside the container,+-- with nothing saved to disk, at most 128 MiB of data and 256 MiB of+-- memory.+redisContainer :: ContainerSpec+redisContainer =+  (container "redis" testImage)+    { entrypoint = Just valkeyBin,       command =-        [ "--bind",-          "0.0.0.0",-          "--protected-mode",-          "no",+        [ "--port",+          "0",+          "--unixsocket",+          socketInside "redis",+          "--unixsocketperm",+          "777",           "--save",           "",           "--appendonly",@@ -41,17 +44,12 @@           "--maxmemory",           "128mb"         ],-      ports = [6379]+      memory = Just "256m",+      endpoints = [Native "redis"]     } --- | Wait until Redis answers, for up to 30 seconds.-waitRedis :: String -> IO ()-waitRedis url = go (120 :: Int)-  where-    info = either error id (Redis.parseConnectInfo url)-    go n =-      tryAny (bracket (Redis.checkedConnect info) Redis.disconnect (const (return ()))) >>= \case-        Right () -> return ()-        Left e-          | n <= 0 -> fail ("Redis did not start: " <> show e)-          | otherwise -> threadDelay 250000 >> go (n - 1)+-- | The URL of the Valkey of a pod, as the store reads it: @unix:PATH@.+redisURL :: Pod -> String+redisURL p = case address p "redis" of+  UnixSocket path -> "unix:" <> path+  TcpPort host port -> "redis://" <> host <> ":" <> show port
src/Haskoin/Store/BlockStore.hs view
@@ -32,18 +32,12 @@ -- -- = Transactions ----- Once the database is in sync, the block store requests every transaction--- that peers announce and that no store of the fleet has seen ('toFetch'):--- what the fleet saw is a set in Redis, the same for every store and kept--- across restarts, so a transaction is fetched about once for the fleet.--- It asks peers for their whole mempools only to fill the pool again--- after it was emptied ('blockStoreRefill'): the pool outlives--- the store, so a store that starts has nothing to ask for. A transaction--- that arrives goes to 'onTx': the member of the fleet offers it to the--- pool that the fleet shares in Redis, which is the mempool--- ("Haskoin.Store.Fleet.Member"). The database holds the chain alone. The--- transactions on their way in, requested, are the pure value of--- "Haskoin.Store.BlockStore.Pending".+-- The block store has nothing to do with the transactions that peers+-- announce and send: their way into the pool that the fleet shares is a+-- machine of its own, "Haskoin.Store.Ingest", run by+-- "Haskoin.Store.Ingest.Run". It was here once, as a queue, a set of+-- requests and a question to the peers at the start, each of which lost+-- transactions in its own way. The database holds the chain alone. -- -- = Feeding the block store --@@ -84,16 +78,7 @@     blockStoreAnnouncedSTM,     blockStorePong,     blockStorePongSTM,-    blockStoreTx,-    blockStoreTxSTM,-    blockStoreTxHash,-    blockStoreTxHashSTM,-    blockStorePendingTxs,-    blockStorePendingTxsSTM,     needsMoreBlocks,-    blockStoreRefill,-    asksMempool,-    toFetch,   ) where @@ -105,12 +90,10 @@     atomically,     modifyTVar',     newTVarIO,-    readTVar,     readTVarIO,     stateTVar,-    writeTVar,   )-import Control.Exception (Exception, SomeException, catch, throwIO, try)+import Control.Exception (Exception, throwIO, try) import Control.Monad   ( filterM,     forM,@@ -123,8 +106,6 @@ import Data.ByteString qualified as B import Data.HashMap.Strict (HashMap) import Data.HashMap.Strict qualified as HashMap-import Data.HashSet (HashSet)-import Data.HashSet qualified as HashSet import Data.Maybe   ( catMaybes,     isJust,@@ -142,7 +123,6 @@ import Data.Time.Clock.POSIX   ( getPOSIXTime,     posixSecondsToUTCTime,-    utcTimeToPOSIXSeconds,   ) import Data.Time.Format   ( defaultTimeLocale,@@ -161,13 +141,9 @@     Message (..),     Network (..),     Ping (..),-    Tx (..),-    TxHash (..),     Version (..),     blockHashToHex,     headerHash,-    txHash,-    txHashToHex,   ) import Haskoin.Node   ( Chain,@@ -190,10 +166,7 @@     releasePeer,     reservePeer,     sendMessage,-    toSockAddr,   )-import Haskoin.Store.BlockStore.Pending (Pending)-import Haskoin.Store.BlockStore.Pending qualified as Pending import Haskoin.Store.BlockStore.Sync   ( Accept (..),     Sync,@@ -230,7 +203,6 @@     send,     sendSTM,   )-import Network.Socket (SockAddr) import System.Metrics.StatsD import System.Random (randomIO, randomRIO) @@ -251,10 +223,6 @@     BlockAnnounced !Peer ![BlockHash]   | -- | a peer answered a ping with a nonce     BlockPong !Peer !Word64-  | -- | a peer sent a transaction-    TxRefReceived !Peer !Tx-  | -- | a peer announced transactions-    TxRefAvailable !Peer ![TxHash]   | -- | clock tick for housekeeping; reply when done     BlockPing !(Listen ()) @@ -278,14 +246,8 @@     config :: !BlockStoreConfig,     -- | state of the block download ("Haskoin.Store.BlockStore.Sync")     sync :: !(TVar (Sync Peer)),-    -- | transactions requested from peers-    -- ("Haskoin.Store.BlockStore.Pending")-    pending :: !(TVar Pending),     -- | StatsD metrics, if enabled     metrics :: !(Maybe StoreMetrics),-    -- | whether a refill of the pool waits to ask the peers for their-    -- mempools ('blockStoreRefill')-    refill :: !(TVar Bool),     -- | what each peer said that it has, by its label: a peer is asked     -- only for blocks that it announced     knows :: !(TVar (HashMap Text Known)),@@ -431,28 +393,11 @@     db :: !DatabaseReader,     -- | network constants     net :: !Network,-    -- | the peers given on the command line or in the environment, as-    -- @host:port@: on Bitcoin, only these are asked for their mempools,-    -- since a node whitelists the store there or disconnects it-    -- ('blockStoreRefill')-    explicitPeers :: ![String],     -- | what to do with the best block right after it changes, and when the     -- store starts, before anything else is written to the database: a     -- member of a fleet takes a view of the database for the block here     -- ('Haskoin.Store.Fleet.Member.noteBest')     onBest :: !(BlockHash -> IO ()),-    -- | what to do with a transaction that a peer sent: the member of the-    -- fleet offers it to the pool, the mempool, which is in Redis alone-    -- ('Haskoin.Store.Fleet.Member.memberReceived')-    onTx :: !(UnixTime -> Tx -> IO ()),-    -- | of these transactions, those that the store does not fetch when a-    -- peer announces them: those that it holds to offer to the pool, and-    -- those that the pool has decided on, taken, refused as a conflict or-    -- let go unconfirmed. The database keeps-    -- nothing of the mempool, so without this every store would fetch each-    -- transaction from every peer that announces it-    -- ('Haskoin.Store.Fleet.Member.memberSeen')-    seen :: !([TxHash] -> IO (HashSet TxHash)),     -- | blocks to request from the syncing peer in one batch     blockWindow :: !Int,     -- | disconnect syncing peer if inactive for this long@@ -529,10 +474,6 @@ getBlock :: BlockStore -> BlockHash -> IO (Maybe BlockData) getBlock self = Q.getBlock self.config.db --- | Data of a confirmed transaction in the database.-getTxData :: BlockStore -> TxHash -> IO (Maybe TxData)-getTxData self = Q.getTxData self.config.db- -- | Network of the block store. getNetwork :: BlockStore -> IO Network getNetwork self = return self.config.net@@ -544,8 +485,6 @@   IO a withBlockStore cfg action = do   pb <- newTVarIO . Sync.idle =<< getCurrentTime-  ts <- newTVarIO Pending.empty-  refill <- newTVarIO False   inbox <- newInbox   metrics <- newStoreMetrics cfg   owner <- (newOwner "block store")@@ -555,9 +494,7 @@           { mailbox = inboxToMailbox inbox,             config = cfg,             sync = pb,-            pending = ts,             metrics = metrics,-            refill = refill,             knows = knows,             owner = owner           }@@ -603,73 +540,6 @@         then clearSyncingState self >> return True         else return False --- | Run an action only if the database is in sync.-guardSync :: BlockStore -> IO () -> IO ()-guardSync self f = isInSync self >>= \s -> when s f---- | Ask the peers connected now for their mempools, if a refill waits for--- it ('blockStoreRefill') and the database is in sync; with no peer, the--- refill waits for the first one. Called again on each block imported in--- sync and each peer that connects.-syncMempool :: BlockStore -> IO ()-syncMempool self =-  guardSync self $ do-    peers <- getPeers self.config.peerMgr >>= mempoolPeers self-    asking <- atomically $ do-      waits <- readTVar self.refill-      when (waits && not (null peers)) $ writeTVar self.refill False-      return (waits && not (null peers))-    when asking $ do-      logInfo self $ "Asking " <> cs (show (length peers)) <> " peers for their mempools"-      forM_ peers $ \op -> MMempool `sendMessage` op.mailbox---- | Of the connected peers, those that answer a request for their mempool--- ('asksMempool'), with 'explicitPeers' resolved to their addresses. A name--- that does not resolve leaves its peer out.-mempoolPeers :: BlockStore -> [OnlinePeer] -> IO [OnlinePeer]-mempoolPeers self peers = do-  explicit <--    if isJust self.config.net.cashAddrPrefix-      then return []-      else concat <$> mapM resolve self.config.explicitPeers-  return [p | p <- peers, asksMempool self.config.net explicit p.address]-  where-    resolve s = toSockAddr self.config.net s `catch` \(_ :: SomeException) -> return []---- | Whether to ask a peer at an address for its mempool, given the--- addresses of the peers given explicitly. On Bitcoin Cash, always: Bitcoin--- Cash Node serves bloom filters by default, and so answers anyone. On--- Bitcoin, only a peer given explicitly: Bitcoin Core disconnects any peer--- that asks unless it whitelists it, which an operator does for the peers--- that the store is told to use, and not for seeds or discovered peers.-asksMempool :: Network -> [SockAddr] -> SockAddr -> Bool-asksMempool net explicit a = isJust net.cashAddrPrefix || a `elem` explicit---- | Ask the peers for their mempools, once, and fetch every transaction--- that they announce and the fleet has not seen: for when the pool was--- emptied, because Redis lost its data--- ('Haskoin.Store.Fleet.Member.noteEpoch') or the pool started again--- ('Haskoin.Store.Fleet.Member.noteRestarts'). What the fleet had seen--- went with it, so all of it is fetched. The transactions go to 'onTx',--- which offers them to the pool again.------ Only the peers connected at that time are asked, and only once, and of--- those only the ones that answer ('asksMempool'). Bitcoin Core closes the--- connection of a peer that asks for its mempool unless it serves bloom--- filters (@-peerbloomfilters@, off by default) or it whitelists that peer;--- Bitcoin Cash Node serves bloom filters by default and answers anyone. So--- on Bitcoin only the peers given with @--peer@ are asked, since an--- operator whitelists those: asking the others, seeds and discovered peers,--- only loses them, all at once, and with them the health of the store.--- Asking every peer that connects, as the store once did, lost its public--- Bitcoin Core peers one after the other for as long as it ran. A node--- that the store has over RPC (@--node-rpc@) answers in any case--- ('Haskoin.Store.Web.refillLoop').-blockStoreRefill :: BlockStore -> IO ()-blockStoreRefill self = do-  atomically $ writeTVar self.refill True-  syncMempool self- -- | Import a block from the syncing peer, then ask for more blocks or, if now in -- sync, sync the mempool. Disconnects the peer if it is not the syncing peer, if -- the block is unknown to the node, or if the block cannot be imported.@@ -689,18 +559,29 @@               <> " sent unknown block "               <> blockHashToHex blockhash           killPeer peer-        Just node -> do-          logDebug self $-            "Processing block "-              <> blockText node Nothing-              <> " from peer "-              <> peer.label-          ret <--            withBlockTiming self $-              runImportNotify self (Just blockhash) (\wr -> importBlock wr block node)-          case ret of-            Left e -> failure e-            Right _ -> success node+        Just node ->+          chainBlockMain self.config.chain blockhash >>= \case+            -- the node moved to another chain since the block was asked+            -- for: it is no fault of the peer's, and importing it would+            -- move the store, and the fleet with it, to a block that is+            -- reverted at once. The requests go, and the sync starts+            -- again from the chain of the node.+            False -> do+              logDebug self $ "Block " <> hexhash <> " is no longer on the chain of the node"+              transition self $ \st -> ((), Sync.forgetRequests st)+              syncMe self+            True -> do+              logDebug self $+                "Processing block "+                  <> blockText node Nothing+                  <> " from peer "+                  <> peer.label+              ret <-+                withBlockTiming self $+                  runImportNotify self (Just blockhash) (\wr -> importBlock wr block node)+              case ret of+                Left e -> failure e+                Right _ -> success node   where     header = block.header     blockhash = headerHash header@@ -720,7 +601,7 @@       transition self $ \st -> ((), Sync.imported now blockhash st)       isInSync self >>= \case         False -> syncMe self-        True -> syncMempool self+        True -> return ()     failure e = do       logError self $         "Error importing block "@@ -757,62 +638,6 @@         <> p.label   killPeer p --- | A transaction that a peer sent: no longer a request, and on to the fleet member to offer to the pool.-processTx :: BlockStore -> Peer -> Tx -> IO ()-processTx self p tx = do-  t <- getCurrentTime-  logDebug self $-    "Received tx "-      <> txHashToHex (txHash tx)-      <> " by peer: "-      <> p.label-  changePending self (Pending.answered (txHash tx))-  self.config.onTx (fromIntegral (floor (utcTimeToPOSIXSeconds t) :: Integer)) tx---- | Change the transactions on their way to the pool of the fleet.-changePending :: BlockStore -> (Pending -> Pending) -> IO ()-changePending self f = atomically $ modifyTVar' self.pending f---- | Whether a transaction was requested recently.-isPending :: BlockStore -> TxHash -> IO Bool-isPending self th = Pending.isPending th <$> readTVarIO self.pending---- | Of the transactions that a peer announced, those to fetch: given--- whether one is queued or was requested lately, which of them the fleet--- has seen ('seen' of t'BlockStoreConfig'), and whether one is in the--- database. The fleet is asked once for all of them, since an inventory can--- name thousands, and only for those that are not queued.-toFetch :: (TxHash -> IO Bool) -> ([TxHash] -> IO (HashSet TxHash)) -> (TxHash -> IO Bool) -> [TxHash] -> IO [TxHash]-toFetch pending seen stored hs = do-  fresh <- filterM (fmap not . pending) hs-  have <- if null fresh then return HashSet.empty else seen fresh-  filterM (fmap not . stored) (filter (not . (`HashSet.member` have)) fresh)---- | Request from a peer the announced transactions that are neither queued,--- recently requested, seen by the fleet nor in the database ('toFetch').--- Only while in sync.-processTxs :: BlockStore -> Peer -> [TxHash] -> IO ()-processTxs self p hs = guardSync self $ do-  xs <- toFetch (isPending self) self.config.seen stored hs-  logDebug self $-    "Requesting "-      <> cs (show (length xs))-      <> " of "-      <> cs (show (length hs))-      <> " transactions announced by peer: "-      <> p.label-  unless (null xs) $ go xs-  where-    stored h = isJust <$> getTxData self h-    go xs = do-      now <- getCurrentTime-      changePending self (Pending.requested now xs)-      let net = self.config.net-      let inv = if net.segWit then InvWitnessTx else InvTx-          vec = map (InvVector inv . (.get)) xs-          msg = MGetData (GetData vec)-      msg `sendMessage` p- -- | Deal with peers that do not deliver: disconnect the syncing peer if it -- has been silent for the timeout, else look for another peer to ask for its -- blocks if it has been silent for the stall; and disconnect the peers passed@@ -983,7 +808,8 @@             <> cs (show e)         throwIO e       Right () -> do-        getBestBlock self >>= mapM_ self.config.onBest+        -- as after an import: the member first, then whoever listens+        getBestBlock self >>= mapM_ (\b -> self.config.onBest b >> publish (StoreBestBlock b) self.config.pub)         transition self $ \st -> ((), Sync.forgetRequests st)     revertToMainChain self @@ -1054,8 +880,7 @@             -- it has delivered what it had, and has not announced what             -- comes next: let it go, for a peer that has to be found             logDebug self $ "Syncing peer has not announced the next block: " <> p.label-            released <- transition self (Sync.release p)-            when released (void (releasePeer self.owner p))+            finishPeer self p           else request p bns   where     request p bns = do@@ -1103,10 +928,22 @@           <> cs (show target.height)       throwIO $ AncestorNotInChain height h --- | Forget a peer: release it if it was the syncing peer.+-- | Forget a peer that disconnected ('Sync.forget'): release it if it was+-- the syncing peer.+forgetPeer :: BlockStore -> Peer -> IO ()+forgetPeer self p = do+  released <- transition self (Sync.forget p)+  when released $ do+    logDebug self $ "Releasing peer: " <> p.label+    void (releasePeer self.owner p)++-- | Stop syncing from a peer that is still connected ('Sync.finish'):+-- release it if it was the syncing peer. It stays owed what it was asked+-- for, so that a block it sends late is dropped, not taken for a fault. finishPeer :: BlockStore -> Peer -> IO () finishPeer self p = do-  released <- transition self (Sync.release p)+  now <- getCurrentTime+  released <- transition self (Sync.finish now p)   when released $ do     logDebug self $ "Releasing peer: " <> p.label     void (releasePeer self.owner p)@@ -1140,8 +977,7 @@         False -> revertToMainChain self >> search self []  -- | Note the height that a newly connected peer gave, then start syncing if--- needed, or, if in sync, ask the peers for their mempools if a refill--- waits for a peer ('syncMempool').+-- needed. trySyncingPeer :: BlockStore -> Peer -> IO () trySyncingPeer self p = do   online <- getOnlinePeer self.config.peerMgr p@@ -1149,7 +985,7 @@   atomically . modifyTVar' self.knows $     HashMap.insertWith (\_ k -> Known (max height k.height) k.tip) p.label (Known height Nothing)   isInSync self >>= \case-    True -> syncMempool self+    True -> return ()     False -> trySyncing self  -- | Release the syncing peer, if any.@@ -1175,7 +1011,7 @@   logDebug self $     "Peer disconnected: " <> p.label   atomically $ modifyTVar' self.knows $ HashMap.delete p.label-  finishPeer self p+  forgetPeer self p processBlockStoreMessage self (BlockReceived p b) = do   logDebug self $     "Received block: "@@ -1190,26 +1026,8 @@   processNoBlocks self p bs processBlockStoreMessage self (BlockAnnounced p bs) = processAnnounced self p bs processBlockStoreMessage self (BlockPong p n) = processPong self p n-processBlockStoreMessage self (TxRefReceived p tx) = do-  logDebug self $-    "Transaction received from peer "-      <> p.label-      <> ": "-      <> txHashToHex (txHash tx)-  processTx self p tx-processBlockStoreMessage self (TxRefAvailable p ts) = do-  logDebug self $-    "Transactions available from peer "-      <> p.label-      <> ": "-      <> T.unwords (map txHashToHex ts)-  processTxs self p ts processBlockStoreMessage self (BlockPing r) = do   logDebug self "Internal clock event"-  -- a request that no peer answered, as a node does not for a transaction-  -- that it has not announced to the store, may be made again-  now <- getCurrentTime-  changePending self (Pending.prune now)   setStoreHeight self   setHeadersHeight self   setPeersConnected self@@ -1270,18 +1088,6 @@ blockStorePongSTM :: Peer -> Word64 -> BlockStore -> STM () blockStorePongSTM peer nonce store = BlockPong peer nonce `sendSTM` store.mailbox --- | Give the block store a transaction received from a peer.-blockStoreTx ::-  Peer -> Tx -> BlockStore -> IO ()-blockStoreTx peer tx store =-  TxRefReceived peer tx `send` store.mailbox---- | Tell the block store that a peer announced transactions.-blockStoreTxHash ::-  Peer -> [TxHash] -> BlockStore -> IO ()-blockStoreTxHash peer txhashes store =-  TxRefAvailable peer txhashes `send` store.mailbox- -- | 'STM' version of 'blockStorePeerConnect'. blockStorePeerConnectSTM ::   Peer -> BlockStore -> STM ()@@ -1311,29 +1117,6 @@   Peer -> [BlockHash] -> BlockStore -> STM () blockStoreNotFoundSTM peer blocks store =   BlockNotFound peer blocks `sendSTM` store.mailbox---- | 'STM' version of 'blockStoreTx'.-blockStoreTxSTM ::-  Peer -> Tx -> BlockStore -> STM ()-blockStoreTxSTM peer tx store =-  TxRefReceived peer tx `sendSTM` store.mailbox---- | 'STM' version of 'blockStoreTxHash'.-blockStoreTxHashSTM ::-  Peer -> [TxHash] -> BlockStore -> STM ()-blockStoreTxHashSTM peer txhashes store =-  TxRefAvailable peer txhashes `sendSTM` store.mailbox---- | Number of transactions queued or requested by the block store.-blockStorePendingTxs ::-  BlockStore -> IO Int-blockStorePendingTxs =-  atomically . blockStorePendingTxsSTM---- | 'STM' version of 'blockStorePendingTxs'.-blockStorePendingTxsSTM ::-  BlockStore -> STM Int-blockStorePendingTxsSTM store = Pending.size <$> readTVar store.pending  -- | Describe a block for logs: height, time, hash and, if the block is given, size. blockText :: BlockNode -> Maybe Block -> Text
− src/Haskoin/Store/BlockStore/Pending.hs
@@ -1,84 +0,0 @@--- |--- Module      : Haskoin.Store.BlockStore.Pending--- Copyright   : (c) Haskoin Developers--- License     : MIT--- Maintainer  : jprupp@protonmail.ch--- Stability   : experimental--- Portability : POSIX------ The transactions that the block store asked its peers for and that have--- not arrived yet, as a pure value with transitions.------ A transaction that a peer announces is requested once, and not again--- while the request is fresh: another peer that announces it meanwhile is--- not asked. When it arrives it is no longer a request ('answered'), and--- goes on to the pool of the fleet. A request that no peer answers is--- forgotten after 'requestTimeout', so that the next announcement asks--- again.------ The block store holds no transaction here: what arrives is offered to--- the pool at once, and what waits for its parents waits in the fleet--- member ("Haskoin.Store.Fleet.Member").------ = Why a pure value------ The block store kept the recent requests in a variable changed by--- several functions, and forgot each request in a thread of its own that--- slept for twenty seconds: one thread per transaction requested. Here--- every change is a function, the clock is an argument, and requests are--- forgotten by 'prune' on the clock tick of the block store.-module Haskoin.Store.BlockStore.Pending-  ( -- * State-    Pending,-    empty,-    isPending,-    size,--    -- * Transitions-    requested,-    answered,-    prune,--    -- * Timeouts-    requestTimeout,-  )-where--import Data.HashMap.Strict (HashMap)-import Data.HashMap.Strict qualified as HashMap-import Data.Time.Clock (NominalDiffTime, UTCTime, diffUTCTime)-import Haskoin (TxHash)---- | Transactions requested from peers and not received yet, with when.-newtype Pending = Pending (HashMap TxHash UTCTime)-  deriving stock (Show, Eq)---- | How long a request keeps the transaction from being requested again.-requestTimeout :: NominalDiffTime-requestTimeout = 20---- | Nothing requested.-empty :: Pending-empty = Pending HashMap.empty---- | Whether a transaction was requested recently, so that it is not--- requested again.-isPending :: TxHash -> Pending -> Bool-isPending h (Pending asked) = HashMap.member h asked---- | How many transactions are requested and not received yet.-size :: Pending -> Int-size (Pending asked) = HashMap.size asked---- | Transactions were requested.-requested :: UTCTime -> [TxHash] -> Pending -> Pending-requested now hs (Pending asked) = Pending (HashMap.union (HashMap.fromList [(h, now) | h <- hs]) asked)---- | A transaction that was requested arrived, to be offered to the pool--- of the fleet: it is no longer a request.-answered :: TxHash -> Pending -> Pending-answered h (Pending asked) = Pending (HashMap.delete h asked)---- | Forget requests older than 'requestTimeout'.-prune :: UTCTime -> Pending -> Pending-prune now (Pending asked) = Pending (HashMap.filter (\t -> now `diffUTCTime` t <= requestTimeout) asked)
src/Haskoin/Store/BlockStore/Sync.hs view
@@ -25,6 +25,12 @@ -- sequence of events, and the rules are in one place: -- -- * There is at most one syncing peer, and only 'start' and 'pass' set one.+-- * A peer that was asked for a block, and has not disconnected, is never+--   taken for a peer that was not asked: it is the syncing peer or among+--   those passed over until it delivers, or until the timeout ('finish',+--   'forget').+-- * Only the block store's own thread changes the state, so that each+--   transition sees the one before it. -- * A block is accepted only from a peer that was asked for it ('accept'), --   so a block that nobody asked that peer for is a reason to disconnect it. -- * A block is wanted at most once ('request').@@ -100,7 +106,8 @@     -- * Transitions     start,     pass,-    release,+    forget,+    finish,     Accept (..),     accept,     imported,@@ -249,13 +256,43 @@ -- | Forget a peer, as when it disconnects. Says whether it was the syncing -- peer, for the caller to unlock it; the blocks wanted are then forgotten -- with it, for the next syncing peer to be asked from the best block on.-release :: (Eq p) => p -> Sync p -> (Bool, Sync p)-release p s = case s.current of+-- Nothing of the peer is left: a block that it sends after this is from a+-- peer that was not asked ('NotSyncingPeer'), which a peer that is gone+-- cannot do.+forget :: (Eq p) => p -> Sync p -> (Bool, Sync p)+forget p s = case s.current of   Just a | a.peer == p -> (True, others {current = Nothing, wanted = [], passes = 0})   _ -> (False, others)   where     others = skip p s {passed = filter ((/= p) . (.peer)) s.passed} +-- | Stop syncing from a peer that is still connected, as when the store is+-- in sync or the peer has nothing more to give. Says whether it was the+-- syncing peer, for the caller to unlock it. The blocks wanted are+-- forgotten, as with 'forget', but the peer still owes what it was asked+-- for: it joins the peers passed over, its silence starting now, so that a+-- block it sends later is dropped as 'Late', not taken for a fault. Only a+-- peer that still owes blocks when the timeout runs out is disconnected+-- ('expired'). A peer that is not the syncing peer is left as it is: it+-- may be owed blocks as one passed over, and those are not forgotten.+--+-- 'forget' was used for this once, and dropped what the peer owed: a peer+-- passed over during a stall that delivered after another had brought the+-- store in sync was disconnected for a block that it was asked for.+finish :: (Eq p) => UTCTime -> p -> Sync p -> (Bool, Sync p)+finish now p s = case s.current of+  Just a+    | a.peer == p ->+        ( True,+          s+            { current = Nothing,+              wanted = [],+              passes = 0,+              passed = [a {since = now} | not (null a.owes)] <> filter ((/= p) . (.peer)) s.passed+            }+        )+  _ -> (False, s)+ -- | What to do with a block that a peer sent. data Accept   = -- | this peer was asked for it and it is wanted: import it@@ -301,11 +338,14 @@     gap' = maybe sample (\g -> (3 * g + sample) / 4) s.gap  -- | Blocks were requested from the syncing peer. Those already wanted are--- not added again. Nothing changes without a syncing peer.+-- not added again, and the peer owes each block once: after+-- 'forgetRequests' it may be asked again for a block that it still owes,+-- and owing it twice would leave it owing one copy after it delivered,+-- to be disconnected for it later. Nothing changes without a syncing peer. request :: [BlockHash] -> Sync p -> Sync p request hs s = case s.current of   Nothing -> s-  Just a -> s {wanted = s.wanted <> new, current = Just a {owes = a.owes <> new}}+  Just a -> s {wanted = s.wanted <> new, current = Just a {owes = a.owes <> filter (`notElem` a.owes) new}}   where     new = foldl' (\bs h -> if h `elem` bs || h `elem` s.wanted then bs else bs <> [h]) [] hs 
src/Haskoin/Store/Common.hs view
@@ -104,6 +104,7 @@     BlockRef (..),     DeriveType (..),     Spender,+    TokenBalance (..),     Transaction (..),     TxData (..),     TxRef (..),@@ -238,6 +239,14 @@     -- | number of distinct transactions of a set of addresses, counted     -- without reading them     getAddressesTxCount :: [Address] -> IO Word32,+    -- | the token balances of an address, one per category (CashTokens)+    getAddressTokens :: Address -> IO [TokenBalance],+    -- | the holders of a category, one token balance per address+    getTokenHolders :: TxHash -> Limits -> IO [TokenBalance],+    -- | transactions that moved tokens of a category, newest first+    getTokenTxs :: TxHash -> Limits -> IO [TxRef],+    -- | unspent outputs that hold tokens of a category, newest first+    getTokenUnspents :: TxHash -> Limits -> IO [Unspent],     -- | what is kept of a transaction that a block of the main chain     -- replaced, if it did in the last 'replacedKept' blocks     getReplaced :: TxHash -> IO (Maybe Replaced)
src/Haskoin/Store/Database/Migrate.hs view
@@ -106,6 +106,7 @@     migrateRecords,     layeredVersion,     recordsVersion,+    mergesVersion,     Migration (..),     MigrationError (..),     MigrationOptions (..),@@ -154,6 +155,7 @@ import Haskoin   ( Address,     BlockHeader (..),+    Network (..),     OutPoint (..),     Tx (..),     TxHash,@@ -176,6 +178,7 @@     UnixTime,     confirmed,   )+import Haskoin.Store.Database.Migrate.Tokens (migrateTokens, tokenActivation) import Haskoin.Store.Database.Query qualified as Q import Haskoin.Store.Database.Reader   ( DatabaseReader (..),@@ -216,11 +219,16 @@ recordsVersion :: Word32 recordsVersion = 22 --- | Version that the store runs on: that of 'recordsVersion', in which the--- import of a block writes merge records for balances and spenders--- ("Haskoin.Store.Database.Merge").+-- | Version of 'recordsVersion' in which the import of a block writes merge+-- records for balances and spenders ("Haskoin.Store.Database.Merge").+mergesVersion :: Word32+mergesVersion = 23++-- | Version that the store runs on: that of 'mergesVersion', with the+-- outputs that hold tokens of Bitcoin Cash under their addresses, and the+-- token balances and categories indexed (@docs\/cashtokens.md@). currentVersion :: Word32-currentVersion = 23+currentVersion = 24  -- | Version that the migration starts from. mixedVersion :: Word32@@ -339,17 +347,21 @@       | v == currentVersion && marker == Nothing -> return nothing       -- no migration leaves its marker with this version       | v >= currentVersion -> throwIO (UnknownVersion version)-      | v == recordsVersion && marker == Nothing -> merges nothing+      | v == mergesVersion && marker == Nothing -> tokens nothing+      -- the tokens were being indexed when the store last stopped+      | v == mergesVersion && isJust r.net.cashAddrPrefix -> tokens nothing+      | v == mergesVersion -> throwIO (UnknownVersion version)+      | v == recordsVersion && marker == Nothing -> merges nothing >>= tokens       -- the times were being set when the store last stopped-      | v == recordsVersion && marker == Just layeredVersion -> times nothing >>= merges+      | v == recordsVersion && marker == Just layeredVersion -> times nothing >>= merges >>= tokens       | v == recordsVersion -> throwIO (UnknownVersion version)       -- versions 18 and 19 have the chain of version 20, and a mempool that       -- the migration to the layered layout reads where it is       | v == 18 || v == 19 -> do           report $ "Upgrading the database from version " <> cs (show v)           writeBatch r.db [insertOp VersionKey mixedVersion]-          layered >>= times >>= merges-    Just (_ :: Word32) -> layered >>= times >>= merges+          layered >>= times >>= merges >>= tokens+    Just (_ :: Word32) -> layered >>= times >>= merges >>= tokens   where     nothing = Migration {moved = 0, batches = 0, checked = 0, rewritten = 0}     layered = migrateLayeredWith defaultMigrationOptions {report = report} r@@ -362,10 +374,30 @@         "Upgrading the database from version "           <> cs (show recordsVersion)           <> " to "-          <> cs (show currentVersion)+          <> cs (show mergesVersion)           <> ": blocks will write merge records, which no older haskoin-store can read"-      writeBatch r.db [insertOp VersionKey currentVersion]+      writeBatch r.db [insertOp VersionKey mergesVersion]       return done+    -- from 'mergesVersion': a network without tokens has nothing to add;+    -- one of Bitcoin Cash indexes them, or carries that on+    -- ("Haskoin.Store.Database.Migrate.Tokens")+    tokens done+      | isJust r.net.cashAddrPrefix = do+          marker <- retrieve r.db MigrationKey :: IO (Maybe Word32)+          start <- maybe (tokenActivation r) return marker+          _ <- migrateTokens report start r+          writeBatch r.db [insertOp VersionKey currentVersion, deleteOp MigrationKey]+          report $ "The tokens are indexed: the database is now of version " <> cs (show currentVersion)+          return done+      | otherwise = do+          report $+            "Upgrading the database from version "+              <> cs (show mergesVersion)+              <> " to "+              <> cs (show currentVersion)+              <> ": this network has no tokens, so nothing else changes"+          writeBatch r.db [insertOp VersionKey currentVersion]+          return done  -- | Bring the records of the confirmed transactions of a database of -- version 21 to what version 22 writes, and make the database one of that
+ src/Haskoin/Store/Database/Migrate/Tokens.hs view
@@ -0,0 +1,271 @@+-- |+-- Module      : Haskoin.Store.Database.Migrate.Tokens+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- Migration of a database of Bitcoin Cash from version 23 to 24: what the+-- tokens of Bitcoin Cash (CashTokens) need indexed (@docs\/cashtokens.md@).+--+-- = The problem+--+-- Until version 24 the store read scripts with haskoin-core 2.0, which did+-- not know the token prefix: an output that holds tokens had no address,+-- and was in no address's history, balance or unspent outputs.+-- haskoin-core 2.1 gives such an output the address of its locking script.+-- A database of version 23 is wrong for it in two ways. What is missing is+-- missing: the history of the addresses that held tokens. And what is+-- there would go wrong: spending an old output that holds tokens takes its+-- coins out of a balance that never had them.+--+-- = What it does+--+-- It walks the blocks of the main chain from the activation of CashTokens+-- to the tip, and for every transaction with an output or a spent output+-- that holds tokens, writes what version 24 would have written when the+-- block was imported:+--+-- * the address of each such output and spent output gets the transaction+--   in its history, and one more in the count of its balance, unless an+--   output or a spent output without tokens gave it the transaction+--   already;+--+-- * each output with tokens and an address adds its coins to what the+--   address received, and, if it is still unspent, to its balance and its+--   unspent outputs;+--+-- * the token balances, the holders, the transactions and the unspent+--   outputs of the categories, as the import of a block writes them+--   ("Haskoin.Store.Logic").+--+-- It writes the result, not the history: an output spent since counts as+-- received and not as held, whatever came between. A balance it did not+-- touch is the balance of the chain at the tip, so the sum is too.+--+-- = Safe to interrupt+--+-- It works in batches of blocks. Each batch is one atomic write, with the+-- height of the next block to do under t'MigrationKey' in the same write+-- ('Haskoin.Store.Database.Writer.writeRaw'), so a batch is done once or+-- not at all: the balances are added to, without reading, and a batch done+-- twice would count its outputs twice. A store that stopped carries on+-- from that height. 'Haskoin.Store.Database.Migrate.upgradeDatabase' then+-- sets version 24 and removes the marker.+--+-- = Where it starts+--+-- The rules of CashTokens apply to the blocks after the first whose median+-- time past is the time of the upgrade, on every network of Bitcoin Cash.+-- 'tokenActivation' finds that block from the timestamps of the blocks in+-- the database. An output that started with the token byte before then is+-- left as it was: the prefix meant nothing yet, and consensus makes such+-- an output unspendable, so nothing reads it again.+module Haskoin.Store.Database.Migrate.Tokens+  ( migrateTokens,+    tokenActivation,+    tokenUpgradeTime,+  )+where++import Control.Monad (forM, forM_, when)+import Data.HashSet qualified as HashSet+import Data.IntMap.Strict qualified as IntMap+import Data.List (sort)+import Data.Maybe (catMaybes, isJust, mapMaybe)+import Data.String.Conversions (cs)+import Data.Text (Text)+import Data.Word (Word32, Word64)+import Database.RocksDB.Query (insertOp, retrieve)+import Haskoin+  ( BlockHeader (..),+    BlockHeight,+    OutPoint (..),+    TokenData (..),+    Tx (..),+    TxOut (..),+    eitherToMaybe,+    scriptToAddressBS,+    txHash,+  )+import Haskoin.Node (LogLevel (..), Logger (..))+import Haskoin.Store.Data+  ( BlockData (..),+    Prev (..),+    TxData (..),+    TxRef (..),+    Unspent (..),+    scriptTokens,+  )+import Haskoin.Store.Database.Query qualified as Q+import Haskoin.Store.Database.Reader (DatabaseReader (..))+import Haskoin.Store.Database.Types+  ( BalVal (..),+    MigrationKey (..),+    TokBalVal (..),+  )+import Haskoin.Store.Database.Writer+  ( Writer,+    insertAddrTx,+    insertAddrUnspent,+    insertCatTx,+    insertCatUnspent,+    mergeBalance,+    mergeTokBal,+    runWriter,+    writeRaw,+  )++-- | The time of the upgrade of Bitcoin Cash that brought CashTokens, 15 May+-- 2023 at noon UTC: the rules apply after the first block whose median time+-- past is at least this.+tokenUpgradeTime :: Word64+tokenUpgradeTime = 1684152000++-- | Blocks in each write of the migration: a few thousand transactions on+-- Bitcoin Cash.+batchBlocks :: BlockHeight+batchBlocks = 200++-- | The height of the first block of the main chain under the rules of+-- CashTokens: the one after the first block whose median time past is+-- 'tokenUpgradeTime' or later. The height after the best block if there is+-- none yet.+--+-- The median time past only goes up along a chain, so it is found by+-- halving the range of heights, from the timestamps of the blocks in the+-- database: no headers are needed.+tokenActivation :: DatabaseReader -> IO BlockHeight+tokenActivation r = do+  tip <- bestHeight r+  let search lo hi+        | lo >= hi = return lo+        | otherwise = do+            let mid = (lo + hi) `div` 2+            reached <- (>= tokenUpgradeTime) <$> medianTimePast r mid+            if reached then search lo mid else search (mid + 1) hi+  -- the first block whose median time past reached the upgrade, and the+  -- rules start at the one after it+  (+ 1) <$> search 0 (tip + 1)++-- | Add what version 24 indexes to a database of Bitcoin Cash of version+-- 23, from a height or from where an earlier run stopped, telling a+-- function how far it is. Says how many transactions it wrote for. The+-- version is left to the caller.+migrateTokens :: (Text -> IO ()) -> BlockHeight -> DatabaseReader -> IO Int+migrateTokens report start r = do+  marker <- retrieve r.db MigrationKey :: IO (Maybe Word32)+  tip <- bestHeight r+  let from = maybe start id marker+  report $+    "Indexing the tokens of Bitcoin Cash from block "+      <> cs (show from)+      <> " to "+      <> cs (show tip)+      <> ": this reads every transaction since the upgrade of May 2023"+  counts <- forM [from, from + batchBlocks .. tip] $ \h -> do+    let to = min tip (h + batchBlocks - 1)+    n <- runWriter r.net r quiet $ \w -> do+      ns <- forM [h .. to] (migrateBlock r w)+      writeRaw w (insertOp MigrationKey (to + 1))+      return (sum ns)+    when ((to + 1) `mod` 10000 < batchBlocks) $+      report $+        "Tokens indexed up to block " <> cs (show to)+    return n+  return (sum counts)+  where+    quiet = Logger {level = LevelError, source = "", push = \_ -> return ()}++-- | Write what version 24 adds for the transactions of the block of the+-- main chain at a height. Says how many it wrote for.+migrateBlock :: DatabaseReader -> Writer -> BlockHeight -> IO Int+migrateBlock r w h = do+  hashes <- Q.getBlocksAtHeight r h+  blocks <- catMaybes <$> mapM (Q.getBlock r) hashes+  case filter (.main) blocks of+    bd : _ -> do+      tds <- catMaybes <$> mapM (Q.getTxData r) bd.txs+      length . filter id <$> mapM (migrateTx r w) tds+    [] -> return 0++-- | Write what version 24 adds for one confirmed transaction, if it has an+-- output or a spent output that holds tokens. Says whether it had.+migrateTx :: DatabaseReader -> Writer -> TxData -> IO Bool+migrateTx r w td = do+  let held = not (null tokenOuts && null tokenPrevs)+  when held $ do+    -- the history and the count of the addresses that only tokens gave it+    forM_ (HashSet.toList (HashSet.difference tokenAddrs plainAddrs)) $ \a -> do+      insertAddrTx w a ref+      mergeBalance w a (bal 0 0 1 0)+    forM_ tokenOuts $ \(i, o, t) -> do+      let p = OutPoint h i+          address = addr o.script+          u = Unspent {block = td.block, outpoint = p, value = o.value, script = o.script, address}+      unspent <- isJust <$> Q.getUnspent r p+      forM_ address $ \a -> do+        mergeBalance w a (bal 0 0 0 o.value)+        mergeTokBal w a t.category (tok 0 0 0 0 t.amount)+      when unspent $ do+        insertCatUnspent w t.category u+        forM_ address $ \a -> do+          insertAddrUnspent w a u+          mergeBalance w a (bal o.value 1 0 0)+          mergeTokBal w a t.category (tokensIn t)+    forM_ categories $ \c -> insertCatTx w c ref+    forM_ holders $ \(a, c) -> mergeTokBal w a c (tok 0 0 0 1 0)+  return held+  where+    net = r.net+    h = txHash td.tx+    ref = TxRef {block = td.block, txid = h}+    addr = eitherToMaybe . scriptToAddressBS net+    tokens = scriptTokens net+    outs = zip [0 ..] td.tx.outputs+    tokenOuts = [(i, o, t) | (i, o) <- outs, Just t <- [tokens o.script]]+    tokenPrevs = [(pv, t) | pv <- IntMap.elems td.prevs, Just t <- [tokens pv.script]]+    plainAddrs =+      HashSet.fromList $+        mapMaybe (addr . (.script)) [o | (_, o) <- outs, not (isJust (tokens o.script))]+          <> mapMaybe (addr . (.script)) [pv | pv <- IntMap.elems td.prevs, not (isJust (tokens pv.script))]+    tokenAddrs =+      HashSet.fromList $+        mapMaybe (\(_, o, _) -> addr o.script) tokenOuts <> mapMaybe (addr . (.script) . fst) tokenPrevs+    owned = [(addr o.script, t) | (_, o, t) <- tokenOuts] <> [(addr pv.script, t) | (pv, t) <- tokenPrevs]+    categories = HashSet.toList (HashSet.fromList [t.category | (_, t) <- owned])+    holders = HashSet.toList (HashSet.fromList [(a, t.category) | (Just a, t) <- owned])++-- | What an output that holds tokens adds to the token balance of its+-- address while it is unspent, as the import of a block adds it.+tokensIn :: TokenData -> TokBalVal+tokensIn t = tok t.amount (maybe 0 (const 1) t.nft) 1 0 0++-- | Differences to a balance: coins held, unspent outputs, transactions,+-- coins received. Nothing is unconfirmed in the chain.+bal :: Word64 -> Word64 -> Word64 -> Word64 -> BalVal+bal confirmed utxo txs received = BalVal {confirmed, unconfirmed = 0, utxo, txs, received}++-- | Differences to a token balance: tokens held, non-fungible tokens,+-- unspent outputs, transactions, tokens received.+tok :: Word64 -> Word64 -> Word64 -> Word64 -> Word64 -> TokBalVal+tok amount nfts outputs count received = TokBalVal {amount, nfts, outputs, count, received}++-- | The height of the best block.+bestHeight :: DatabaseReader -> IO BlockHeight+bestHeight r =+  Q.getBestBlock r >>= \case+    Nothing -> return 0+    Just b -> maybe 0 (.height) <$> Q.getBlock r b++-- | The median time past of the block of the main chain at a height: the+-- median of its timestamp and those of the ten blocks before it.+medianTimePast :: DatabaseReader -> BlockHeight -> IO Word64+medianTimePast r h = do+  times <- forM [h - min h 10 .. h] $ \k -> do+    hashes <- Q.getBlocksAtHeight r k+    blocks <- catMaybes <$> mapM (Q.getBlock r) hashes+    return [fromIntegral b.header.timestamp | b <- blocks, b.main]+  let sorted = sort (concat times)+  return $ if null sorted then 0 else sorted !! (length sorted `div` 2)
src/Haskoin/Store/Database/Query.hs view
@@ -47,6 +47,11 @@      -- * Addresses     getBalance,+    getTokBal,+    getAddressTokens,+    getCategoryHolders,+    getCategoryTxs,+    getCategoryUnspents,     getBalances,     getUnspent,     getAddressTxs,@@ -80,6 +85,7 @@ import Conduit   ( ConduitT,     concatC,+    concatMapC,     dropWhileC,     lift,     liftIO,@@ -128,6 +134,8 @@     OutPoint (..),     Tx (..),     TxHash,+    eitherToMaybe,+    scriptToAddressBS,   ) import Haskoin.Store.Common   ( Limits (..),@@ -326,6 +334,11 @@ -- Addresses ------------------------------------------------------------------------------- +-- | The tokens of a category that an address holds in the chain, if it+-- ever held any (CashTokens).+getTokBal :: DatabaseReader -> Address -> TxHash -> IO (Maybe TokBalVal)+getTokBal r a c = retrieveCF r.db (tokBalCF r.db) (TokBalKey a c)+ -- | Balance of an address, if it was ever used. getBalance :: DatabaseReader -> Address -> IO (Maybe Balance) getBalance r a = do@@ -452,6 +465,62 @@              in scanFrom it (AddrOutKeyA a) (AddrOutKeyB a b)                   .| (dropWhileC before >> mapC id)           Nothing -> return ()++-------------------------------------------------------------------------------+-- Tokens of Bitcoin Cash+-------------------------------------------------------------------------------++-- | The token balances of an address in the chain, one per category, in+-- the order of the categories' bytes.+getAddressTokens :: DatabaseReader -> Address -> IO [(TxHash, TokBalVal)]+getAddressTokens r a =+  withIterCFStat r (tokBalCF r.db) (TokBalKeyA a) $ \it ->+    runConduit $ scan it (TokBalKeyA a) .| concatMapC (\case (TokBalKey _ c, v) -> [(c, v)]; _ -> []) .| sinkList++-- | The holders of a category in the chain, one token balance per address,+-- in the order of the addresses' bytes, with an offset and a limit.+getCategoryHolders :: DatabaseReader -> TxHash -> Limits -> IO [(Address, TokBalVal)]+getCategoryHolders r c limits =+  withIterCFStat r (holderCF r.db) (HolderKeyC c) $ \it ->+    runConduit $+      scan it (HolderKeyC c)+        .| concatMapC (\case (HolderKey _ a, v) -> [(a, v)]; _ -> [])+        .| applyLimitsC limits+        .| sinkList++-- | Transactions that moved tokens of a category, in the chain, newest+-- first, from a block or a transaction as for an address.+getCategoryTxs :: DatabaseReader -> TxHash -> Limits -> IO [TxRef]+getCategoryTxs r c limits =+  withIterCFStat r (catTxCF r.db) (CatTxKeyC c) $ \it ->+    runConduit $+      from it .| concatMapC (\case (CatTxKey _ t, ()) -> [t]; _ -> []) .| applyLimitsC limits .| sinkList+  where+    from it = case limits.start of+      Nothing -> scan it (CatTxKeyC c)+      Just (AtBlock bh) -> scanFrom it (CatTxKeyC c) (CatTxKeyB c (BlockRef bh maxBound))+      Just (AtTx txh) ->+        lift (getTxRecord r txh) >>= \case+          Just TxData {block = b@BlockRef {}} -> scanFrom it (CatTxKeyC c) (CatTxKeyB c b)+          _ -> return ()++-- | Unspent outputs that hold tokens of a category, in the chain, newest+-- first, from a block or a transaction as for an address.+getCategoryUnspents :: DatabaseReader -> TxHash -> Limits -> IO [Unspent]+getCategoryUnspents r c limits =+  withIterCFStat r (catOutCF r.db) (CatOutKeyC c) $ \it ->+    runConduit $+      from it .| concatMapC (\case (CatOutKey _ b p, v) -> [unspent b p v]; _ -> []) .| applyLimitsC limits .| sinkList+  where+    unspent block outpoint (OutVal value script) =+      Unspent {block, outpoint, value, script, address = eitherToMaybe (scriptToAddressBS r.net script)}+    from it = case limits.start of+      Nothing -> scan it (CatOutKeyC c)+      Just (AtBlock bh) -> scanFrom it (CatOutKeyC c) (CatOutKeyB c (BlockRef bh maxBound))+      Just (AtTx txh) ->+        lift (getTxRecord r txh) >>= \case+          Just TxData {block = b@BlockRef {}} -> scanFrom it (CatOutKeyC c) (CatOutKeyB c b)+          _ -> return ()  ------------------------------------------------------------------------------- -- Extended public keys
src/Haskoin/Store/Database/Query/Pooled.hs view
@@ -19,8 +19,8 @@ -- its database at that block ("Haskoin.Store.Database.Views"), and from the -- one pool that they share. The mempool's part comes through a -- t'PoolReads', a handful of functions that say what a pool has: its--- summaries, the entries of an address by the page, bodies, spenders and--- its list. A pool far away answers each in one round trip, and+-- summaries, the entries of an address by the page, bodies, spenders,+-- its list, and what it does to tokens (CashTokens). A pool far away answers each in one round trip, and -- 'emptyPool' answers for no pool at all, which is how the chain alone is -- read ('chainRead'). --@@ -63,6 +63,7 @@ import Data.ByteString qualified as BS import Data.Bytes.Put (runPutS) import Data.Bytes.Serial (serialize)+import Data.Default (def) import Data.Functor ((<&>)) import Data.HashMap.Strict (HashMap) import Data.HashMap.Strict qualified as HashMap@@ -71,7 +72,7 @@ import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map import Data.Maybe (catMaybes, fromMaybe, isJust)-import Data.Serialize (encode)+import Data.Serialize (Serialize, encode) import Data.Word (Word16, Word32, Word64) import Database.RocksDB (Iterator) import Database.RocksDB.Query (matchingAsListCF)@@ -101,6 +102,7 @@   ( Balance (..),     BlockRef (..),     Spender,+    TokenBalance (..),     TxData (..),     TxRef (..),     UnixTime,@@ -115,6 +117,8 @@     Derived (..),     addrOutCF,     addrTxCF,+    catOutCF,+    catTxCF,     derivedAddrs,     txCF,     withSnapshotReader,@@ -122,8 +126,13 @@ import Haskoin.Store.Database.Types   ( AddrOutKey (..),     AddrTxKey (..),+    CatOutKey (..),+    CatTxKey (..),+    CategorySummary (..),     MemSummary (..),-    OutVal,+    OutVal (..),+    PoolTokens (..),+    TokBalVal (..),     TxKey (..),     decodeTxKey,     toUnspent,@@ -163,7 +172,21 @@     startingWith :: (Word32, Word16) -> IO [TxHash],     -- | what the pool keeps of a transaction that a block replaced as the     -- tip moved past it ('Haskoin.Store.Fleet.Pool.advanceReplacing')-    replaced :: TxHash -> IO (Maybe Replaced)+    replaced :: TxHash -> IO (Maybe Replaced),+    -- | what the pool does to the tokens of each category at an address,+    -- in no order (CashTokens)+    addressTokens :: Address -> IO [(TxHash, PoolTokens)],+    -- | what the pool does to the tokens of a category at each address, in+    -- no order+    categoryHolders :: TxHash -> IO [(Address, PoolTokens)],+    -- | what the pool does to a category, or 'Nothing' if it does not move+    -- it+    categorySummary :: TxHash -> IO (Maybe CategorySummary),+    -- | transactions that move tokens of a category, as 'addressTxs'+    categoryTxs :: TxHash -> Maybe (UnixTime, TxHash) -> Int -> IO [(UnixTime, TxHash)],+    -- | outputs that the pool makes and that hold tokens of a category, as+    -- 'addressOuts', each with whether the pool also uses it up+    categoryOuts :: TxHash -> Maybe (UnixTime, OutPoint) -> Int -> IO [(Unspent, Bool)]   }  -- | The queries of a store that answers from the chain as a reader has it,@@ -201,7 +224,11 @@       -- from the pool, which keeps what the blocks replaced as the tip       -- moves past them, the same for every store: not from the store's       -- own database, which has what its own mempool lost-      getReplaced = pool.replaced+      getReplaced = pool.replaced,+      getAddressTokens = getAddressTokens r pool,+      getTokenHolders = getTokenHolders r pool,+      getTokenTxs = getTokenTxs r pool,+      getTokenUnspents = getTokenUnspents r pool     }   where     only = \case@@ -221,7 +248,12 @@       spenders = return . map (const Nothing),       page = \_ _ -> return [],       startingWith = \_ -> return [],-      replaced = \_ -> return Nothing+      replaced = \_ -> return Nothing,+      addressTokens = \_ -> return [],+      categoryHolders = \_ -> return [],+      categorySummary = \_ -> return Nothing,+      categoryTxs = \_ _ _ -> return [],+      categoryOuts = \_ _ _ -> return []     }  -- | The queries of the chain alone, each on a snapshot of the database of@@ -257,7 +289,11 @@       xPubTxs = \x bs l -> one (\q -> q.xPubTxs x bs l),       xPubTxCount = \x bs -> one (\q -> q.xPubTxCount x bs),       getAddressesTxCount = \as -> one (\q -> q.getAddressesTxCount as),-      getReplaced = \_ -> return Nothing+      getReplaced = \_ -> return Nothing,+      getAddressTokens = \a -> one (\q -> q.getAddressTokens a),+      getTokenHolders = \c l -> one (\q -> q.getTokenHolders c l),+      getTokenTxs = \c l -> one (\q -> q.getTokenTxs c l),+      getTokenUnspents = \c l -> one (\q -> q.getTokenUnspents c l)     }   where     one :: (StoreRead -> IO a) -> IO a@@ -519,11 +555,8 @@ -- | The stream of unspent outputs of each address, from where a page -- starts, given the iterators on the chain's index: the outputs that the -- pool pays and does not spend, then those of the chain that the pool does--- not spend. The pool is asked which outputs of the chain it spends--- several at a time, four at first and then four times as many each time,--- so that the first output of each of many addresses does not cost a batch--- of rows read ahead, and no more once as many were found as its summary--- counts.+-- not spend ('unspentStream'). One read of the pool gives the summaries of+-- all the addresses, which say which of them have anything in the pool. unspentStreams ::   DatabaseReader ->   PoolReads ->@@ -535,31 +568,62 @@   sums <- pool.summaries as   return $ \its -> zipWith3 stream as sums its   where-    stream a summary it = fresh a summary >> (chainUnspentsC r from a it .| hide a (maybe 0 hidden summary) 4)-    hidden s = s.spentCount - s.bothCount-    fresh a = \case-      Just s | s.paidCount > s.bothCount -> case from of-        Top -> outs a Nothing-        InMempool time h -> outs a (Just (time, OutPoint h 0))-        InChain _ -> return ()-      _ -> return ()-    -- some of what the pool pays it also spends, so more is asked for-    outs a start =-      pages (\(u, _) -> position u) (pool.addressOuts a) (2 * firstPage limits) start+    stream a summary it =+      unspentStream+        from+        limits+        (maybe False (\s -> s.paidCount > s.bothCount) summary)+        (pool.addressOuts a)+        (pool.spentOutputs a)+        (maybe 0 (\s -> s.spentCount - s.bothCount) summary)+        (chainUnspentsC r from a it)++-- | A stream of unspent outputs, newest first, from where a page starts:+-- the outputs that the pool makes and does not spend, if it has any, then+-- those of the chain without the ones that the pool spends, of which it+-- has so many. The pool is asked which outputs of the chain it spends+-- several at a time, four at first and then four times as many each time,+-- so that the first output of each of many lists does not cost a batch of+-- rows read ahead, and no more once as many were found as it spends.+unspentStream ::+  From ->+  Limits ->+  -- | whether the pool makes outputs of the list that it does not spend+  Bool ->+  -- | the outputs of the list that the pool makes, by the page+  (Maybe (UnixTime, OutPoint) -> Int -> IO [(Unspent, Bool)]) ->+  -- | whether the pool spends each of some outputs of the list+  ([OutPoint] -> IO [Bool]) ->+  -- | how many outputs of the chain in the list the pool spends+  Word64 ->+  -- | the list in the chain+  ConduitT () Unspent IO () ->+  ConduitT () Unspent IO ()+unspentStream from limits made outs spentBy hidden chain = fresh >> (chain .| hide hidden 4)+  where+    fresh+      | made = case from of+          Top -> stream Nothing+          InMempool time h -> stream (Just (time, OutPoint h 0))+          InChain _ -> return ()+      | otherwise = return ()+    -- some of what the pool makes it also spends, so more is asked for+    stream start =+      pages (\(u, _) -> position u) outs (2 * firstPage limits) start         .| awaitForever (\(u, spent) -> if spent then return () else yield u)     position u = case u.block of       MemRef t -> (t, u.outpoint)       BlockRef {} -> (0, u.outpoint)-    hide :: Address -> Word64 -> Int -> ConduitT Unspent Unspent IO ()-    hide _ 0 _ = awaitForever yield-    hide a n size = do+    hide :: Word64 -> Int -> ConduitT Unspent Unspent IO ()+    hide 0 _ = awaitForever yield+    hide n size = do       batch <- gather size       case batch of         [] -> return ()         _ -> do-          flags <- lift (pool.spentOutputs a (map (.outpoint) batch))+          flags <- lift (spentBy (map (.outpoint) batch))           yieldMany [u | (u, False) <- zip batch flags]-          hide a (n - min n (fromIntegral (length (filter id flags)))) (min 256 (size * 4))+          hide (n - min n (fromIntegral (length (filter id flags)))) (min 256 (size * 4))     gather :: Int -> ConduitT Unspent o IO [Unspent]     gather 0 = return []     gather k =@@ -611,3 +675,122 @@       txs <- forM several $ \(a, _) -> runConduit (poolTxsC pool Top 256 a True .| mapC (.txid) .| sinkList)       return (HashSet.size (HashSet.fromList (concat txs)))   return (inBlocks + fromIntegral inPool)++-------------------------------------------------------------------------------+-- Tokens+-------------------------------------------------------------------------------++-- | The token balances of an address, one per category, in the order of+-- the categories' bytes as the chain keeps them, with the pool applied:+-- the categories of the chain, and those that only the pool moves at the+-- address.+getAddressTokens :: DatabaseReader -> PoolReads -> Address -> IO [TokenBalance]+getAddressTokens r pool a = do+  chain <- Q.getAddressTokens r a+  pooled <- pool.addressTokens a+  return [tokenBalance a c v t | (c, v, t) <- overlay chain pooled]++-- | The holders of a category, one token balance per address, in the order+-- of the addresses' bytes as the chain keeps them, with an offset and a+-- limit, and the pool applied. The addresses that only the pool has can+-- fall anywhere in the list, so with any of them the chain's list is read+-- from its start to the end of the page, which the offset and the limit+-- are then applied to.+getTokenHolders :: DatabaseReader -> PoolReads -> TxHash -> Limits -> IO [TokenBalance]+getTokenHolders r pool c limits =+  pool.categoryHolders c >>= \case+    [] -> map (\(a, v) -> tokenBalance a c v Nothing) <$> Q.getCategoryHolders r c limits+    pooled -> do+      let upTo = case limits.limit of+            0 -> limits {offset = 0}+            n -> limits {offset = 0, limit = limits.offset + n}+      chain <- Q.getCategoryHolders r c upTo+      let listed = [tokenBalance a c v t | (a, v, t) <- overlay chain pooled]+          page = drop (fromIntegral limits.offset) listed+      return $ case limits.limit of+        0 -> page+        n -> take (fromIntegral n) page++-- | Token balances of the chain and what the pool does to tokens, by the+-- same key, a category or an address: one for each key that either has,+-- in the order of the keys' bytes, which is that of the chain's index.+overlay :: (Serialize k) => [(k, TokBalVal)] -> [(k, PoolTokens)] -> [(k, TokBalVal, Maybe PoolTokens)]+overlay chain pooled = Map.elems (Map.unionWith joined inChain inPool)+  where+    inChain = Map.fromList [(encode k, (k, v, Nothing)) | (k, v) <- chain]+    inPool = Map.fromList [(encode k, (k, def, Just t)) | (k, t) <- pooled]+    joined (k, v, _) (_, _, t) = (k, v, t)++-- | A token balance as the API answers it, from what the chain has, with+-- what the pool does applied, as 'applySummary' does for a balance.+tokenBalance :: Address -> TxHash -> TokBalVal -> Maybe PoolTokens -> TokenBalance+tokenBalance address category v pooled =+  TokenBalance+    { address,+      category,+      confirmedTokens = v.amount `minus` p.spent,+      unconfirmedTokens = p.free,+      nfts = (v.nfts `minus` p.spentNfts) + p.freeNfts,+      tokenUtxo = (v.outputs `minus` p.spentOutputs) + p.freeOutputs,+      tokenTxs = v.count + p.txs,+      receivedTokens = v.received + p.received+    }+  where+    p = fromMaybe (PoolTokens 0 0 0 0 0 0 0 0) pooled+    minus x y = if y > x then 0 else x - y++-- | Transactions that moved tokens of a category, newest first: those of+-- the pool, then those of the chain, paged as those of an address.+getTokenTxs :: DatabaseReader -> PoolReads -> TxHash -> Limits -> IO [TxRef]+getTokenTxs r pool c limits = paged r pool limits $ \from ->+  Q.withManyIters r (catTxCF r.db) [CatTxKeyC c] $ \its ->+    Q.joinConduits txRefKey [inPool from >> chainCatTxsC from c it | it <- its] limits+  where+    inPool from = case from of+      InChain _ -> return ()+      Top -> stream Nothing+      InMempool time h -> stream (Just (time, h))+    stream start =+      pages id (pool.categoryTxs c) (firstPage limits) start .| mapC (\(t, h) -> TxRef {block = MemRef t, txid = h})++-- | Transactions of a category in the chain, newest first, from where a+-- page starts.+chainCatTxsC :: From -> TxHash -> Iterator -> ConduitT i TxRef IO ()+chainCatTxsC from c it = chain .| concatMapC ref+  where+    chain = case from of+      InChain position -> Q.scanFrom it (CatTxKeyC c) (CatTxKeyB c position)+      _ -> Q.scan it (CatTxKeyC c)+    ref :: (CatTxKey, ()) -> Maybe TxRef+    ref (CatTxKey _ t, ()) = Just t+    ref _ = Nothing++-- | Unspent outputs that hold tokens of a category, newest first: those+-- that the pool makes and does not use up, then those of the chain that+-- the pool does not use up, as for an address ('unspentStream').+getTokenUnspents :: DatabaseReader -> PoolReads -> TxHash -> Limits -> IO [Unspent]+getTokenUnspents r pool c limits = paged r pool limits $ \from -> do+  summary <- pool.categorySummary c+  let stream it =+        unspentStream+          from+          limits+          (maybe False ((> 0) . (.free)) summary)+          (pool.categoryOuts c)+          (fmap (map isJust) . pool.spenders)+          (maybe 0 (.spent) summary)+          (chainCatUnspentsC r from c it)+  Q.withManyIters r (catOutCF r.db) [CatOutKeyC c] $ \its -> Q.joinConduits unspentKey (map stream its) limits++-- | Unspent outputs of a category in the chain, newest first, from where a+-- page starts. Those that the pool uses up are among them.+chainCatUnspentsC :: DatabaseReader -> From -> TxHash -> Iterator -> ConduitT i Unspent IO ()+chainCatUnspentsC r from c it = chain .| concatMapC output+  where+    chain = case from of+      InChain position -> Q.scanFrom it (CatOutKeyC c) (CatOutKeyB c position)+      _ -> Q.scan it (CatOutKeyC c)+    output :: (CatOutKey, OutVal) -> Maybe Unspent+    output (CatOutKey _ block outpoint, OutVal value script) =+      Just Unspent {block, outpoint, value, script, address = eitherToMaybe (scriptToAddressBS r.net script)}+    output _ = Nothing
src/Haskoin/Store/Database/Reader.hs view
@@ -57,6 +57,7 @@     withReader,     columnFamilyConfig,     layeredFamilyConfig,+    tokenFamilyConfig,     mergeGuardFamily,     memoryReport,     addrTxCF,@@ -68,6 +69,10 @@     heightCF,     balanceCF,     mempoolCF,+    tokBalCF,+    holderCF,+    catTxCF,+    catOutCF,      -- * Snapshots     snapshotReader,@@ -402,6 +407,7 @@ layeredFamilyConfig bloom cached =   map mempool (columnFamilyConfig bloom cached)     <> [("mempool-addr", c (Just 22)), (mergeGuardFamily, def)]+    <> tokenFamilyConfig bloom cached   where     c p =       def@@ -414,6 +420,32 @@       | name == "mempool" = (name, c Nothing)       | otherwise = (name, cfg) +-- | The column families of the tokens of Bitcoin Cash, since database+-- version 24 (@docs\/cashtokens.md@): token balances by address and by+-- category, with the merge operator of the balances, since their values are+-- five numbers too; and the transactions and the unspent outputs of each+-- category. Every network has them, empty where there are no tokens, so+-- that a database has one layout. Like 'mergeGuardFamily', they keep a+-- store that does not know them from opening a database that has them.+tokenFamilyConfig :: Bool -> Bool -> [(String, Config)]+tokenFamilyConfig bloom cached =+  [ ("tok-bal", (c (Just 22)) {mergeOperator = Just balanceOperator}),+    ("holder", (c (Just 33)) {mergeOperator = Just balanceOperator}),+    ("cat-tx", scanned (Just 33)),+    ("cat-out", scanned (Just 33))+  ]+  where+    -- the balances are read one key at a time too, when a block is taken+    -- out, as the balances of the addresses are+    c p =+      def+        { prefixLength = p,+          bloomFilter = bloom,+          cacheIndexAndFilterBlocks = cached,+          partitionIndexAndFilters = cached+        }+    scanned p = (c p) {bloomFilter = False}+ -- | The name of the column family that has nothing in it, and is there so -- that a store older than database version 23 cannot open the database: -- see 'layeredFamilyConfig'. The name is what the error of such a store@@ -458,6 +490,22 @@ -- 20 ('MemTxKey'), which only its migration reads. mempoolCF :: DB -> ColumnFamily mempoolCF db = columnFamilies db !! 8++-- | Column family of the token balances by address ('TokBalKey').+tokBalCF :: DB -> ColumnFamily+tokBalCF db = columnFamilies db !! 11++-- | Column family of the token balances by category ('HolderKey').+holderCF :: DB -> ColumnFamily+holderCF db = columnFamilies db !! 12++-- | Column family of the transactions of each category ('CatTxKey').+catTxCF :: DB -> ColumnFamily+catTxCF db = columnFamilies db !! 13++-- | Column family of the unspent outputs of each category ('CatOutKey').+catOutCF :: DB -> ColumnFamily+catOutCF db = columnFamilies db !! 14  -- | A reader of a snapshot of the database of another reader: the same -- in everything, but that it reads the snapshot.
src/Haskoin/Store/Database/Stalls.hs view
@@ -1,5 +1,6 @@ {-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}  -- | -- Module      : Haskoin.Store.Database.Stalls@@ -29,19 +30,23 @@ -- -- * 'watchStalls' reads RocksDB's properties every few seconds, logs when --   writes start to be delayed or stopped and when they recover, keeps the---   state for @\/health@, and sends it to StatsD.+--   state for @\/health@, and sends it to StatsD. The state is that of the+--   check of the database of haskoin-store-data+--   ('Haskoin.Store.Data.DatabaseHealth'): beside the writes, the+--   compactions and flushes running, the tables in memory waiting for a+--   flush, the size of the files and the errors in the background, which+--   say why writes are slow. -- -- The properties are polled rather than heard from an event listener of -- RocksDB, which the C API of the binding does not have: a stall lasts -- minutes to hours, so a few seconds late is soon enough, and each poll is--- three reads of counters that RocksDB keeps anyway.+-- a few reads, for each column family, of counters that RocksDB keeps+-- anyway. module Haskoin.Store.Database.Stalls   ( -- * Background jobs     defaultBackgroundJobs,      -- * Write stalls-    Writes (..),-    Stall (..),     noStall,     readStall,     stallNote,@@ -58,6 +63,7 @@ import Data.Text qualified as T import Database.RocksDB (DB, Property (..), columnFamilies, getProperty, getPropertyCF) import Haskoin.Node (LogLevel (..))+import Haskoin.Store.Data (DatabaseHealth (..), DatabaseWrites (..)) import System.Metrics.StatsD (Stats, newStatGauge, setGauge) import Text.Read (readMaybe) @@ -82,73 +88,81 @@ defaultBackgroundJobs :: Int -> Int defaultBackgroundJobs cores = max 2 (min 16 cores) --- | Whether RocksDB lets writes through.-data Writes-  = -- | at full speed-    Flowing-  | -- | slowed down to let compactions catch up-    Delayed-  | -- | stopped until compactions or flushes catch up-    Stopped-  deriving (Eq, Ord, Show, Enum, Bounded)---- | What RocksDB said at a poll.-data Stall = Stall-  { -- | whether writes go through-    writes :: !Writes,-    -- | bytes that RocksDB estimates it has to compact, summed over every-    -- column family (@rocksdb.estimate-pending-compaction-bytes@)-    pending :: !Integer,-    -- | bytes a second that writes are slowed to, 0 when they are not-    -- (@rocksdb.actual-delayed-write-rate@)-    rate :: !Integer-  }-  deriving (Eq, Show)---- | The state before the first poll: writes flowing, nothing pending.-noStall :: Stall-noStall = Stall {writes = Flowing, pending = 0, rate = 0}+-- | The state before the first poll: writes flowing, nothing pending or+-- running, an empty database.+noStall :: DatabaseHealth+noStall =+  DatabaseHealth+    { writes = WritesFlowing,+      pendingCompaction = 0,+      delayedWriteRate = 0,+      compactions = 0,+      flushes = 0,+      memtables = 0,+      size = 0,+      liveData = 0,+      errors = 0+    } --- | Read the state of writes from RocksDB.-readStall :: DB -> IO Stall+-- | Read the state of the database from RocksDB's properties. Those of a+-- column family are summed over all of them; the others are of the whole+-- database. A property that RocksDB does not give reads as 0.+readStall :: DB -> IO DatabaseHealth readStall db = do-  pendings <- forM (Nothing : map Just (columnFamilies db)) $ \cf ->-    number <$> maybe (getProperty db pendingP) (\c -> getPropertyCF db c pendingP) cf-  stopped <- number <$> getProperty db (PropertyName "rocksdb.is-write-stopped")-  rate <- number <$> getProperty db (PropertyName "rocksdb.actual-delayed-write-rate")+  pendingCompaction <- summed "rocksdb.estimate-pending-compaction-bytes"+  memtables <- summed "rocksdb.num-immutable-mem-table"+  size <- summed "rocksdb.total-sst-files-size"+  liveData <- summed "rocksdb.estimate-live-data-size"+  stopped <- whole "rocksdb.is-write-stopped" :: IO Integer+  delayedWriteRate <- whole "rocksdb.actual-delayed-write-rate"+  compactions <- whole "rocksdb.num-running-compactions"+  flushes <- whole "rocksdb.num-running-flushes"+  errors <- whole "rocksdb.background-errors"   let writes-        | stopped /= 0 = Stopped-        | rate /= 0 = Delayed-        | otherwise = Flowing-  return Stall {writes, pending = sum pendings, rate}+        | stopped /= 0 = WritesStopped+        | delayedWriteRate /= 0 = WritesDelayed+        | otherwise = WritesFlowing+  return DatabaseHealth {..}   where-    pendingP = PropertyName "rocksdb.estimate-pending-compaction-bytes"+    whole :: (Read a, Num a) => String -> IO a+    whole name = number <$> getProperty db (PropertyName name)+    summed :: (Read a, Num a) => String -> IO a+    -- the default column family, then the others+    summed name =+      let p = PropertyName name+       in fmap sum . forM (Nothing : map Just (columnFamilies db)) $ \cf ->+            number <$> maybe (getProperty db p) (\c -> getPropertyCF db c p) cf+    number :: (Read a, Num a) => Maybe BS8.ByteString -> a     number = fromMaybe 0 . (>>= readMaybe . BS8.unpack)  -- | What to log when the state of writes was the first and is now the -- second: nothing while it stays the same, a warning when it gets worse, -- and an info line when it gets better. A stall lasts long, and a line at -- every poll would bury the rest of the log.-stallNote :: Writes -> Stall -> Maybe (LogLevel, Text)+stallNote :: DatabaseWrites -> DatabaseHealth -> Maybe (LogLevel, Text) stallNote before now   | now.writes == before = Nothing   | now.writes > before = Just (LevelWarn, worse)   | otherwise = Just (LevelInfo, better)   where     worse = case now.writes of-      Stopped -> "RocksDB stopped writes" <> behind <> hint-      _ -> "RocksDB delays writes to " <> T.pack (show now.rate) <> " bytes/s" <> behind <> hint+      WritesStopped -> "RocksDB stopped writes" <> behind <> hint+      _ -> "RocksDB delays writes to " <> T.pack (show now.delayedWriteRate) <> " bytes/s" <> behind <> hint     better = case now.writes of-      Flowing -> "RocksDB writes at full speed again" <> behind-      _ -> "RocksDB no longer stops writes, but delays them to " <> T.pack (show now.rate) <> " bytes/s" <> behind-    behind = ": " <> T.pack (show now.pending) <> " bytes of compaction pending"+      WritesFlowing -> "RocksDB writes at full speed again" <> behind+      _ ->+        "RocksDB no longer stops writes, but delays them to "+          <> T.pack (show now.delayedWriteRate)+          <> " bytes/s"+          <> behind+    behind = ": " <> T.pack (show now.pendingCompaction) <> " bytes of compaction pending"     hint = "; more --background-jobs may help if the cores and disk have room"  -- | Poll RocksDB every five seconds, forever: run it in a thread of its own. -- It keeps the latest state in the variable, logs the changes -- ('stallNote'), and sends the gauges @db.pending_compaction_bytes@ and -- @db.write_delayed@ (0 flowing, 1 delayed, 2 stopped) to StatsD.-watchStalls :: (LogLevel -> Text -> IO ()) -> Maybe Stats -> DB -> TVar Stall -> IO ()+watchStalls :: (LogLevel -> Text -> IO ()) -> Maybe Stats -> DB -> TVar DatabaseHealth -> IO () watchStalls note stats db var = do   gauges <- forM stats $ \s ->     (,)@@ -160,6 +174,6 @@     atomically (writeTVar var now)     forM_ (stallNote before.writes now) (uncurry note)     forM_ gauges $ \(pendingG, writesG) -> do-      setGauge pendingG (fromIntegral now.pending)+      setGauge pendingG (fromIntegral now.pendingCompaction)       setGauge writesG (fromEnum now.writes)     threadDelay 5000000
src/Haskoin/Store/Database/Table.hs view
@@ -106,6 +106,18 @@ instance TableKey (Address, BlockRef, OutPoint) where   tableHash salt (a, _, p) = tableHash (tableHash salt a) p +-- | The address and the category of a token balance.+instance TableKey (Address, TxHash) where+  tableHash salt (a, c) = tableHash salt a `hashWithSalt` c++-- | The category and the hash of the transaction, as for an address.+instance TableKey (TxHash, TxRef) where+  tableHash salt (c, t) = salt `hashWithSalt` c `hashWithSalt` t.txid++-- | The category and the output, as for an address.+instance TableKey (TxHash, BlockRef, OutPoint) where+  tableHash salt (c, _, p) = tableHash (salt `hashWithSalt` c) p+ -- | An empty table. new :: IO (Table k v) new = Table <$> H.new
src/Haskoin/Store/Database/Types.hs view
@@ -70,19 +70,38 @@ -- | 0x10      | t'SpenderKey'    | t'SpenderVal': inputs of blocks that      | -- |           |                  | spend outputs of a transaction            | -- +-----------+------------------+-------------------------------------------++-- | 0x13      | t'TokBalKey'     | t'TokBalVal': tokens of a category at an  |+-- |           |                  | address                                   |+-- +-----------+------------------+-------------------------------------------++-- | 0x14      | t'HolderKey'     | t'TokBalVal': the same, category first    |+-- +-----------+------------------+-------------------------------------------++-- | 0x15      | t'CatTxKey'      | nothing: a transaction of a category      |+-- +-----------+------------------+-------------------------------------------++-- | 0x16      | t'CatOutKey'     | t'OutVal': an unspent output of a         |+-- |           |                  | category                                  |+-- +-----------+------------------+-------------------------------------------+ -- -- Since version 23 the values of 'BalKey' and of t'SpenderKey' can also -- be written as merge records, which RocksDB combines into the value:--- "Haskoin.Store.Database.Merge".+-- "Haskoin.Store.Database.Merge". Since version 24 those of t'TokBalKey'+-- and t'HolderKey' too, with the operator of the balances. module Haskoin.Store.Database.Types   ( AddrTxKey (..),     AddrOutKey (..),     BestKey (..),     BlockKey (..),     BalKey (..),+    TokBalKey (..),+    HolderKey (..),+    TokBalVal (..),+    addTokBalVal,+    CatTxKey (..),+    CatOutKey (..),     HeightKey (..),     MemTxKey (..),     MemSummary (..),+    PoolTokens (..),+    CategorySummary (..),     MigrationKey (..),     ReplacedKey (..),     ReplacedAtKey (..),@@ -380,6 +399,55 @@   }   deriving (Show, Read, Eq, Ord, Generic, Hashable, Serialize, NFData) +-- | What the mempool does to the tokens of one category at one address,+-- added up, as the pool of the fleet keeps it+-- ("Haskoin.Store.Fleet.Pool.Decide"): what a token+-- balance of the chain needs to become one with the mempool.+--+-- Unlike t'MemSummary', it does not add up what is paid and what is spent+-- and take off what is both. Every output that holds tokens is counted at+-- most once: as free, while the pool makes it and does not use it up, or+-- as spent, while the pool uses it up and the chain made it. So no sum is+-- ever more than the tokens that exist, which a supply of the largest+-- amount that moves twice in the pool would be otherwise. The amount paid+-- is the exception, as the chain's amount received is.+data PoolTokens = PoolTokens+  { -- | mempool transactions that move tokens of the category at the+    -- address+    txs :: !Word64,+    -- | fungible tokens of the outputs that the mempool makes and does not+    -- use up+    free :: !Word64,+    -- | non-fungible tokens of those outputs+    freeNfts :: !Word64,+    -- | number of those outputs+    freeOutputs :: !Word64,+    -- | fungible tokens of the outputs of the chain that the mempool uses+    -- up+    spent :: !Word64,+    -- | non-fungible tokens of those outputs+    spentNfts :: !Word64,+    -- | number of those outputs+    spentOutputs :: !Word64,+    -- | fungible tokens of all the outputs that the mempool makes, as the+    -- amount received of the chain counts them+    received :: !Word64+  }+  deriving (Show, Read, Eq, Ord, Generic, Hashable, Serialize, NFData)++-- | What the mempool does to the tokens of one category, as the pool of the+-- fleet keeps it: enough to know whether a list of the category needs to+-- read the pool.+data CategorySummary = CategorySummary+  { -- | mempool transactions that move tokens of the category+    txs :: !Word64,+    -- | outputs that the mempool makes and does not use up+    free :: !Word64,+    -- | outputs of the chain that the mempool uses up+    spent :: !Word64+  }+  deriving (Show, Read, Eq, Ord, Generic, Hashable, Serialize, NFData)+ -- | Key that is present while a migration of the database is under way, -- with the version that it started from. A migration that works in several -- batches sets it with the first and removes it with the last, so that a@@ -588,6 +656,146 @@ instance Key BalKey  instance KeyValue BalKey BalVal++-- | Key of the tokens of one category that an address holds, in the column+-- family @tok-bal@ (CashTokens, @docs\/cashtokens.md@). The same values are+-- kept under t'HolderKey' too, category first, to list the holders of a+-- category.+data TokBalKey+  = -- | the tokens of a category at an address+    TokBalKey !Address !TxHash+  | -- | short key that matches the token balances of an address+    TokBalKeyA !Address+  deriving (Show, Read, Eq, Ord, Generic, Hashable)++instance Serialize TokBalKey where+  -- 0x13 · Address · category+  put (TokBalKey a c) = put (TokBalKeyA a) >> put c+  -- 0x13 · Address+  put (TokBalKeyA a) = putWord8 0x13 >> put a+  get = do+    guard . (== 0x13) =<< getWord8+    TokBalKey <$> get <*> get++instance Key TokBalKey++instance KeyValue TokBalKey TokBalVal++-- | Key of the tokens of a category at an address, category first, in the+-- column family @holder@: the holders of a category are a scan of its+-- prefix. Written with the same values as t'TokBalKey'.+data HolderKey+  = -- | the tokens of a category at an address+    HolderKey !TxHash !Address+  | -- | short key that matches the holders of a category+    HolderKeyC !TxHash+  deriving (Show, Read, Eq, Ord, Generic, Hashable)++instance Serialize HolderKey where+  -- 0x14 · category · Address+  put (HolderKey c a) = put (HolderKeyC c) >> put a+  -- 0x14 · category+  put (HolderKeyC c) = putWord8 0x14 >> put c+  get = do+    guard . (== 0x14) =<< getWord8+    HolderKey <$> get <*> get++instance Key HolderKey++instance KeyValue HolderKey TokBalVal++-- | The tokens of a category that an address holds in the chain: five+-- numbers, as a t'BalVal' has, so that the merge operator of the balances+-- adds them ("Haskoin.Store.Database.Merge"). The tokens in the mempool are+-- in the pool that the fleet shares, not here.+data TokBalVal = TokBalVal+  { -- | fungible tokens in unspent outputs+    amount :: !Word64,+    -- | non-fungible tokens in unspent outputs+    nfts :: !Word64,+    -- | unspent outputs that hold tokens of the category+    outputs :: !Word64,+    -- | transactions that moved tokens of the category to or from the+    -- address+    count :: !Word64,+    -- | fungible tokens that the outputs of the address ever received+    received :: !Word64+  }+  deriving (Show, Read, Eq, Ord, Generic, Hashable, Serialize, NFData)++instance Default TokBalVal where+  def = TokBalVal {amount = 0, nfts = 0, outputs = 0, count = 0, received = 0}++-- | The sum of two token balances, each number modulo 2^64, as the merge+-- operator adds them.+addTokBalVal :: TokBalVal -> TokBalVal -> TokBalVal+addTokBalVal a b =+  TokBalVal+    { amount = a.amount + b.amount,+      nfts = a.nfts + b.nfts,+      outputs = a.outputs + b.outputs,+      count = a.count + b.count,+      received = a.received + b.received+    }++-- | Database key of a transaction that moved tokens of a category, in the+-- column family @cat-tx@: as t'AddrTxKey', with the category in place of+-- the address.+data CatTxKey+  = -- | a transaction of a category+    CatTxKey !TxHash !TxRef+  | -- | short key that matches the transactions of a category+    CatTxKeyC !TxHash+  | -- | short key that matches the transactions of a category at a position+    -- in the chain+    CatTxKeyB !TxHash !BlockRef+  deriving (Show, Eq, Ord, Generic, Hashable)++instance Serialize CatTxKey where+  -- 0x15 · category · BlockRef · TxHash+  put (CatTxKey c TxRef {block = b, txid = t}) = put (CatTxKeyB c b) >> put t+  -- 0x15 · category · BlockRef+  put (CatTxKeyB c b) = put (CatTxKeyC c) >> put b+  -- 0x15 · category+  put (CatTxKeyC c) = putWord8 0x15 >> put c+  get = do+    guard . (== 0x15) =<< getWord8+    c <- get+    b <- get+    t <- get+    return $ CatTxKey c TxRef {block = b, txid = t}++instance Key CatTxKey++instance KeyValue CatTxKey ()++-- | Database key of an unspent output that holds tokens of a category, in+-- the column family @cat-out@: as t'AddrOutKey', with the category in place+-- of the address.+data CatOutKey+  = -- | an unspent output of a category+    CatOutKey !TxHash !BlockRef !OutPoint+  | -- | short key that matches the unspent outputs of a category+    CatOutKeyC !TxHash+  | -- | short key that matches the unspent outputs of a category at a+    -- position in the chain+    CatOutKeyB !TxHash !BlockRef+  deriving (Show, Read, Eq, Ord, Generic, Hashable)++instance Serialize CatOutKey where+  -- 0x16 · category · BlockRef · OutPoint+  put (CatOutKey c b p) = put (CatOutKeyB c b) >> put p+  -- 0x16 · category · BlockRef+  put (CatOutKeyB c b) = put (CatOutKeyC c) >> put b+  -- 0x16 · category+  put (CatOutKeyC c) = putWord8 0x16 >> put c+  get = do+    guard . (== 0x16) =<< getWord8+    CatOutKey <$> get <*> get <*> get++instance Key CatOutKey++instance KeyValue CatOutKey OutVal  -- | Key for best block in database. data BestKey = BestKey
src/Haskoin/Store/Database/Views.hs view
@@ -42,7 +42,7 @@   ) where -import Control.Concurrent.STM (TVar, atomically, newTVarIO, readTVar, readTVarIO, stateTVar, writeTVar)+import Control.Concurrent.STM (STM, TVar, atomically, newTVarIO, readTVar, readTVarIO, stateTVar, writeTVar) import Control.Exception (mask_) import Control.Monad (forM_, when) import Data.Map.Strict (Map)@@ -87,15 +87,23 @@ heldViews :: Views b -> IO [b] heldViews views = Map.keys . Map.filter (not . (.doomed)) <$> readTVarIO views.held --- | Let go of every view but those of the given blocks. A view that is--- being read is released when its last reader is done, and counts as gone--- from now on.-keepViews :: (Ord b) => Views b -> [b] -> IO ()-keepViews views blocks = mask_ $ do-  free <- atomically . stateTVar views.held $ \m ->-    let (stay, go) = Map.partitionWithKey (\b _ -> b `elem` blocks) m-        (idle, busy) = Map.partition ((== 0) . (.readers)) go-     in (Map.elems idle, stay <> Map.map (\h -> h {doomed = True}) busy)+-- | Let go of every view but those of the blocks that a transaction gives.+-- A view that is being read is released when its last reader is done, and+-- counts as gone from now on.+--+-- The blocks to keep are read in the same transaction that lets the others+-- go, so that two threads that prune at once cannot let go of a view on+-- the strength of what one of them read before the other changed it. A+-- list read before the transaction, as this once took, could miss a block+-- whose view another thread took in between, and let it go.+keepViews :: (Ord b) => Views b -> STM [b] -> IO ()+keepViews views keep = mask_ $ do+  free <- atomically $ do+    blocks <- keep+    stateTVar views.held $ \m ->+      let (stay, go) = Map.partitionWithKey (\b _ -> b `elem` blocks) m+          (idle, busy) = Map.partition ((== 0) . (.readers)) go+       in (Map.elems idle, stay <> Map.map (\h -> h {doomed = True}) busy)   forM_ free (releaseSnapshot . (.snapshot))  -- | Run an action with the database as it was at a block, if there is a
src/Haskoin/Store/Database/Writer.hs view
@@ -132,6 +132,18 @@     deleteTxData,     deleteBalance, +    -- * Tokens of Bitcoin Cash+    insertCatTx,+    deleteCatTx,+    insertCatUnspent,+    deleteCatUnspent,+    mergeTokBal,+    getTokBal,+    setTokBal,++    -- * Other keys+    writeRaw,+     -- * Spenders of the chain     getChainSpender,     getChainSpenders,@@ -149,7 +161,7 @@ import Control.Concurrent.Async (wait, withAsyncOn) import Control.DeepSeq (NFData, force) import Control.Exception (evaluate)-import Control.Monad (filterM, forM, when)+import Control.Monad (filterM, forM, mfilter, when) import Data.ByteString qualified as B import Data.ByteString.Builder.Extra (Next (..), runBuilder) import Data.ByteString.Internal (ByteString (BS))@@ -274,6 +286,19 @@ -- | Changed address unspent outputs: 'Nothing' for a deletion. type AddrOutTable = Table (Address, BlockRef, OutPoint) (Maybe OutVal) +-- | Token balances that the batch has as whole values, by address and+-- category: 'Nothing' for one to delete.+type TokBalTable = Table (Address, TxHash) (Maybe TokBalVal)++-- | Differences to token balances that are not in a t'TokBalTable'.+type TokBalMergeTable = Table (Address, TxHash) TokBalVal++-- | Transactions of each category.+type CatTxTable = Table (TxHash, TxRef) (Maybe ())++-- | Unspent outputs of each category.+type CatOutTable = Table (TxHash, BlockRef, OutPoint) (Maybe OutVal)+ -- | Changed groups of spenders of outputs in the chain. type SpenderTable = Table (TxHash, Word32) (IntMap Spender) @@ -320,6 +345,14 @@     addressTable :: !AddrTxTable,     -- | address unspent outputs     outputTable :: !AddrOutTable,+    -- | token balances that the batch has as whole values+    tokBalTable :: !TokBalTable,+    -- | differences to the token balances that are not in 'tokBalTable'+    tokBalMerges :: !TokBalMergeTable,+    -- | transactions of each category of tokens+    catTxTable :: !CatTxTable,+    -- | unspent outputs of each category of tokens+    catOutTable :: !CatOutTable,     -- | inputs of blocks that spend outputs, by group of outputs     -- as t'SpenderKey' says, each group as the batch leaves it: empty for one     -- that has no spent output left@@ -329,6 +362,8 @@     spenderMerges :: !SpenderTable,     -- | what is kept of transactions that blocks replaced     replacedTable :: !ReplacedTable,+    -- | writes of keys that no table has, in the order given ('writeRaw')+    raw :: !(IORef [BatchOp]),     -- | values read from the database     cache :: !ReadCache,     -- | how long the stages of the imports of blocks took, if any block was@@ -409,6 +444,60 @@       pending <- T.lookup w.memory.balanceMerges a       T.insert w.memory.balanceMerges a (maybe d (`addBalVal` d) pending) +-- | Add a transaction to the index of a category of tokens.+insertCatTx :: Writer -> TxHash -> TxRef -> IO ()+insertCatTx w c t = T.insert w.memory.catTxTable (c, t) (Just ())++-- | Remove a transaction from the index of a category of tokens.+deleteCatTx :: Writer -> TxHash -> TxRef -> IO ()+deleteCatTx w c t = T.insert w.memory.catTxTable (c, t) Nothing++-- | Add an unspent output to the index of a category of tokens.+insertCatUnspent :: Writer -> TxHash -> Unspent -> IO ()+insertCatUnspent w c u =+  T.insert w.memory.catOutTable (c, u.block, u.outpoint) (Just (OutVal u.value u.script))++-- | Remove an unspent output from the index of a category of tokens.+deleteCatUnspent :: Writer -> TxHash -> Unspent -> IO ()+deleteCatUnspent w c u = T.insert w.memory.catOutTable (c, u.block, u.outpoint) Nothing++-- | Add differences to the tokens of a category at an address without+-- reading them, as 'mergeBalance' does for a balance: each of the five+-- numbers modulo 2^64. For the import of a block.+mergeTokBal :: Writer -> Address -> TxHash -> TokBalVal -> IO ()+mergeTokBal w a c d =+  T.lookup w.memory.tokBalTable (a, c) >>= \case+    Just whole -> T.insert w.memory.tokBalTable (a, c) (Just (addTokBalVal (fromMaybe def whole) d))+    Nothing -> do+      pending <- T.lookup w.memory.tokBalMerges (a, c)+      T.insert w.memory.tokBalMerges (a, c) (maybe d (`addTokBalVal` d) pending)++-- | The tokens of a category at an address, with the changes of the batch+-- applied, as 'getBalance' reads a balance.+getTokBal :: Writer -> Address -> TxHash -> IO (Maybe TokBalVal)+getTokBal w a c =+  T.lookup w.memory.tokBalTable (a, c) >>= \case+    Just whole -> return whole+    Nothing -> do+      stored <- Q.getTokBal w.reader a c+      T.lookup w.memory.tokBalMerges (a, c) <&> \case+        Nothing -> stored+        Just d -> Just (addTokBalVal (fromMaybe def stored) d)++-- | Set the tokens of a category at an address, as a whole value, or+-- delete them with 'Nothing' or a value of all zeroes: what takes a block+-- out writes, having read them with 'getTokBal'.+setTokBal :: Writer -> Address -> TxHash -> Maybe TokBalVal -> IO ()+setTokBal w a c v = do+  T.insert w.memory.tokBalTable (a, c) (mfilter (/= def) v)+  T.delete w.memory.tokBalMerges (a, c)++-- | Write a key that no table of the batch has, with the rest of the batch:+-- for a migration, which keeps its place in the database in the same+-- atomic write as what it did, so that a batch is never done twice.+writeRaw :: Writer -> BatchOp -> IO ()+writeRaw w o = modifyIORef' w.memory.raw (o :)+ -- | Add an unspent output. insertUnspent :: Writer -> Unspent -> IO () insertUnspent w u = T.insert w.memory.unspentTable (fst (unspentToVal u)) (Just u)@@ -984,10 +1073,15 @@         balMergeOps db balanceMerges,         addrTxOps db addressTable,         addrOutOps db outputTable,+        tokBalOps db tokBalTable,+        tokBalMergeOps db tokBalMerges,+        catTxOps db catTxTable,+        catOutOps db catOutTable,         unspentOps db unspentTable,         spenderOps db spenderTable,         spenderMergeOps db spenderMerges,-        replacedOps db replacedTable+        replacedOps db replacedTable,+        map Ready . reverse <$> readIORef raw       ]  -- | Operation for the change of the best block, if any.@@ -1047,6 +1141,35 @@ balMergeOps :: DB -> BalanceMergeTable -> IO [Change] balMergeOps db t = map (\(a, d) -> joinOpCF (balanceCF db) (BalKey a) d) <$> T.toList t +-- | Operations for changed token balances: each under its address and+-- under its category.+tokBalOps :: DB -> TokBalTable -> IO [Change]+tokBalOps db t = concatMap (uncurry f) <$> T.toList t+  where+    f (a, c) (Just v) = [setOpCF (tokBalCF db) (TokBalKey a c) v, setOpCF (holderCF db) (HolderKey c a) v]+    f (a, c) Nothing = [dropOpCF (tokBalCF db) (TokBalKey a c), dropOpCF (holderCF db) (HolderKey c a)]++-- | Merge records for the token balances that the batch changes without+-- having read them, under their address and under their category.+tokBalMergeOps :: DB -> TokBalMergeTable -> IO [Change]+tokBalMergeOps db t = concatMap f <$> T.toList t+  where+    f ((a, c), d) = [joinOpCF (tokBalCF db) (TokBalKey a c) d, joinOpCF (holderCF db) (HolderKey c a) d]++-- | Operations for changed transactions of categories.+catTxOps :: DB -> CatTxTable -> IO [Change]+catTxOps db t = map (uncurry f) <$> T.toList t+  where+    f (c, t') (Just ()) = setOpCF (catTxCF db) (CatTxKey c t') ()+    f (c, t') Nothing = dropOpCF (catTxCF db) (CatTxKey c t')++-- | Operations for changed unspent outputs of categories.+catOutOps :: DB -> CatOutTable -> IO [Change]+catOutOps db t = map (uncurry f) <$> T.toList t+  where+    f (c, b, p) (Just v) = setOpCF (catOutCF db) (CatOutKey c b p) v+    f (c, b, p) Nothing = dropOpCF (catOutCF db) (CatOutKey c b p)+ -- | Operations for changed address transactions. addrTxOps :: DB -> AddrTxTable -> IO [Change] addrTxOps db t = map (uncurry f) <$> (T.toList t)@@ -1238,9 +1361,14 @@   balanceMerges <- T.new   addressTable <- T.new   outputTable <- T.new+  tokBalTable <- T.new+  tokBalMerges <- T.new+  catTxTable <- T.new+  catOutTable <- T.new   spenderTable <- T.new   spenderMerges <- T.new   replacedTable <- T.new+  raw <- newIORef []   cache <- newReadCache   times <- newIORef Nothing   return Memory {..}
src/Haskoin/Store/Fleet.hs view
@@ -78,6 +78,7 @@     mayReport,     report,     live,+    mayEmptyAlone,      -- * Moving the tip     agreed,@@ -88,6 +89,10 @@     keep,     Answer (..),     answer,++    -- * When a store takes a turn+    Wake (..),+    turn,   ) where @@ -136,6 +141,20 @@ mayReport now store has fleet =   maybe True has fleet.tip || Map.null (Map.delete store (live now fleet)) +-- | Whether a store that cannot say what the blocks between the tip and+-- the block that the stores agree on did, because it does not have the+-- tip, may empty the pool to move there: only if it is the one store that+-- is live. Another that is live may know the way; and a store that is not+-- live, whose report was refused, is behind the others and knows least.+-- 'Haskoin.Store.Fleet.Pool.Decide.advance' checks the same in the step+-- that empties the pool.+--+-- One store live was the rule once, whichever store it was: a store that+-- came back behind the tip, with its report refused, emptied the pool of+-- the one other store, which knew the way.+mayEmptyAlone :: (Eq s) => Time -> s -> Fleet s b -> Bool+mayEmptyAlone now store fleet = Map.keys (live now fleet) == [store]+ -- | Note the recent blocks of a store, newest first, under a lease of some -- length. The store must have checked 'mayReport' against the same state: -- in Redis the two are one script.@@ -202,3 +221,30 @@   Just b     | has b -> At b     | otherwise -> Behind++-- | What a store's member knows when it decides whether to take a turn:+-- whether the store is well, and what happened since its last turn.+data Wake = Wake+  { -- | the store's own health checks pass+    well :: !Bool,+    -- | the store was found unwell since its last turn+    owed :: !Bool,+    -- | the store has a new best block+    block :: !Bool,+    -- | two seconds went by since the last turn+    due :: !Bool+  }+  deriving (Eq, Show)++-- | Whether a member takes a turn. A store that is unwell takes none, so+-- that its lease runs out. One that is well takes a turn when its best+-- block changed, when two seconds went by, and as soon as it is well+-- again after it was not: the block that made it well woke it while its+-- health was still the old one, and without a turn then it waited out the+-- two seconds with the fleet behind it.+--+-- A turn reports and moves the tip. It offers no transaction: the path of+-- a transaction into the pool is a machine of its own,+-- "Haskoin.Store.Ingest", which offers each as it comes.+turn :: Wake -> Bool+turn w = w.well && (w.owed || w.block || w.due)
+ src/Haskoin/Store/Fleet/Atomic.hs view
@@ -0,0 +1,1101 @@+-- |+-- Module      : Haskoin.Store.Fleet.Atomic+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- Decisions about the state that a fleet keeps in Redis, made in Haskell+-- and carried out in one step: transactional memory over Redis.+-- "Haskoin.Store.Fleet.Atomic.Redis" runs them against a Redis; this+-- module is the pure part, which needs none.+--+-- = The problem+--+-- The stores of a fleet change what they share in Redis with Lua scripts,+-- because Redis runs a script alone, start to end, and so a script is one+-- decision whatever the other stores do. But a script that fails half way+-- keeps what it wrote: Redis undoes nothing. The script of the shared+-- mempool is eight hundred lines that read and write in turn, so an error+-- in it after its first write, a field that is not there or a number that+-- Redis does not take, leaves the pool half changed, with its indexes out+-- of step. And the rules of the pool were written twice, in Lua to run and+-- in Haskell as a model ("Haskoin.Store.Fleet.Pool"), held together by+-- tests that draw sequences at random.+--+-- = What is done instead+--+-- A decision is a computation in t'Atomic'. It reads Redis only through+-- 'query', which keeps every question with its answer, and it changes+-- nothing: 'write' adds to a list. When it ends, one small script is given+-- the questions with their answers and the list. The script asks every+-- question again; if one answer differs it changes nothing and says so,+-- and the decision is made again from new answers. If all are the same it+-- carries out the list.+--+-- That is as good as running the decision inside Redis. Redis runs the+-- script alone, so the answers are all true at one moment, that of the+-- script. A decision is a function of its answers and of nothing else,+-- which its type says: it runs in any monad, so it can do nothing but ask+-- and write. So what the script carries out is what the decision would+-- have written had it run at that moment.+--+-- And it cannot fail half way: the script compares before it writes+-- anything, and then runs plain commands with nothing to decide between+-- them. An error in a decision is an exception in Haskell, before Redis is+-- told anything.+--+-- = What this does not give: a turn+--+-- A decision that loses the race is made again, and may lose again. One+-- that asks a few questions wins soon. One that asks tens of thousands,+-- over a second or more, while others write several times a second,+-- loses every time: it is right whenever it is carried out, and it never+-- is. Nothing here prevents that. A decision that reads much has to be+-- given the floor by the others, as the move of the tip is+-- ('Haskoin.Store.Fleet.Pool.Decide.floorHeld'), for as long as it takes+-- and not for a time that it is expected to take, and has to be tested+-- while others write and at the time that it takes on a slow machine.+--+-- = A decision sees what it wrote+--+-- A script reads back what it has written, and a decision here does too:+-- 'query' answers from what Redis said and from what the decision wrote+-- since ('replay'). What Redis is asked is always the state before the+-- decision, and that is what the script compares.+--+-- Where what was written leaves an answer unknown, such as how many+-- members a sorted set has after one was added that may have been there,+-- 'query' fails with t'Unanswerable' rather than guess. Nothing in the rules+-- of the fleet asks such a question; one that did would be found by its+-- first test.+--+-- = The model of Redis+--+-- 'Db' is the part of Redis that the fleet uses, as a pure value, with the+-- questions ('answer') and the writes ('perform') of this module. A+-- decision runs against it as it runs against Redis ('runPure'), so the+-- rules of the fleet are tested, and can be gone through exhaustively,+-- without a Redis. That it says what Redis says is tested against a real+-- one, question by question and write by write.+module Haskoin.Store.Fleet.Atomic+  ( -- * Questions and writes+    Key,+    Score,+    Bound (..),+    Query (..),+    Answer (..),+    Op (..),+    queryKey,+    opKey,++    -- * Decisions+    Atomic,+    Backend (..),+    Unanswerable (..),+    query,+    queries,+    prefetch,+    Ahead (..),+    ahead,+    write,+    guarding,+    unguarded,+    heldByMark,+    clock,+    Outcome (..),+    runAtomic,+    tidy,++    -- * Reading+    get,+    hget,+    hexists,+    hgetall,+    hkeys,+    habove,+    sismember,+    smembers,+    zscore,+    zcard,+    zrangeByScore,+    exists,++    -- * What a decision wrote, seen by its questions+    replay,++    -- * A model of Redis+    Db,+    Value (..),+    emptyDb,+    answer,+    perform,+    runPure,+  )+where++import Control.Monad.Trans.Class (lift)+import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE)+import Control.Monad.Trans.Reader (ReaderT, ask, runReaderT)+import Control.Monad.Trans.State.Strict (StateT, gets, modify', runStateT)+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.ByteString.Char8 qualified as C+import Data.Foldable (toList)+import Data.Functor.Identity (Identity (..))+import Data.List (sortOn)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe)+import Data.Sequence (Seq, (|>))+import Data.Sequence qualified as Seq+import Data.Set (Set)+import Data.Set qualified as Set+import Haskoin.Store.Fleet.Atomic.Cells+  ( CellOp (..),+    MapOp (..),+    RankOp (..),+    at,+    cellAfter,+    mapAfter,+    rankAfter,+    thereAt,+  )++-- | The name of a key of Redis.+type Key = ByteString++-- | The score of a member of a sorted set. The fleet only uses whole+-- numbers that a double holds exactly: times, heights and their negatives.+type Score = Double++-- | An end of a range of scores.+data Bound = MinusInf | PlusInf | At !Score+  deriving (Eq, Ord, Show)++-- | A question to Redis. Each is one command that changes nothing.+data Query+  = -- | @GET@+    Get !Key+  | -- | @HGET@+    HGet !Key !ByteString+  | -- | @HEXISTS@+    HExists !Key !ByteString+  | -- | @HGETALL@+    HGetAll !Key+  | -- | @HKEYS@+    HKeys !Key+  | -- | the fields of a hash whose value is a whole number above a bound.+    -- A decision that only needs to know which leases still run asks this,+    -- and so does not depend on when each runs out: a lease that is+    -- renewed is the same answer.+    HAbove !Key !Integer+  | -- | @SISMEMBER@+    SIsMember !Key !ByteString+  | -- | @SMEMBERS@+    SMembers !Key+  | -- | @ZSCORE@+    ZScore !Key !ByteString+  | -- | @ZCARD@+    ZCard !Key+  | -- | @ZRANGEBYSCORE@ with the scores, and with at most so many members+    -- if a number is given+    ZRangeByScore !Key !Bound !Bound !(Maybe Int)+  | -- | @EXISTS@+    Exists !Key+  deriving (Eq, Ord, Show)++-- | What Redis says to a question.+data Answer+  = -- | to 'Get' and 'HGet'+    Text !(Maybe ByteString)+  | -- | to 'HExists', 'SIsMember' and 'Exists'+    Flag !Bool+  | -- | to 'HGetAll'+    Fields !(Map ByteString ByteString)+  | -- | to 'SMembers' and 'HKeys'+    Members !(Set ByteString)+  | -- | to 'ZScore'+    Scored !(Maybe Score)+  | -- | to 'ZCard'+    Count !Integer+  | -- | to 'ZRangeByScore': the members in the order of Redis, by score and+    -- then by their bytes+    Ranked ![(ByteString, Score)]+  deriving (Eq, Ord, Show)++-- | A change to Redis. Each is one command that cannot fail on a key of+-- the kind that it is for, and the keys of the fleet each have one kind.+data Op+  = -- | @SET@+    Set !Key !ByteString+  | -- | @DEL@+    Del !Key+  | -- | @INCRBY@+    IncrBy !Key !Integer+  | -- | @HSET@+    HSet !Key !ByteString !ByteString+  | -- | @HDEL@+    HDel !Key !ByteString+  | -- | @HINCRBY@+    HIncrBy !Key !ByteString !Integer+  | -- | @SADD@+    SAdd !Key !ByteString+  | -- | @SREM@+    SRem !Key !ByteString+  | -- | @ZADD@+    ZAdd !Key !Score !ByteString+  | -- | @ZADD NX@: only if the member is not there+    ZAddNX !Key !Score !ByteString+  | -- | @ZREM@+    ZRem !Key !ByteString+  | -- | @ZREMRANGEBYRANK@+    ZRemRangeByRank !Key !Integer !Integer+  | -- | @XADD@ to a stream that keeps about so many entries, with these+    -- fields+    XAdd !Key !Int ![(ByteString, ByteString)]+  | -- | delete every key that starts with these bytes+    Wipe !ByteString+  deriving (Eq, Ord, Show)++-- | The key that a question is about.+queryKey :: Query -> Key+queryKey = \case+  Get k -> k+  HGet k _ -> k+  HExists k _ -> k+  HGetAll k -> k+  HKeys k -> k+  HAbove k _ -> k+  SIsMember k _ -> k+  SMembers k -> k+  ZScore k _ -> k+  ZCard k -> k+  ZRangeByScore k _ _ _ -> k+  Exists k -> k++-- | The key that a write changes, or the start of those that it deletes.+opKey :: Op -> Either ByteString Key+opKey = \case+  Set k _ -> Right k+  Del k -> Right k+  IncrBy k _ -> Right k+  HSet k _ _ -> Right k+  HDel k _ -> Right k+  HIncrBy k _ _ -> Right k+  SAdd k _ -> Right k+  SRem k _ -> Right k+  ZAdd k _ _ -> Right k+  ZAddNX k _ _ -> Right k+  ZRem k _ -> Right k+  ZRemRangeByRank k _ _ -> Right k+  XAdd k _ _ -> Right k+  Wipe p -> Left p++-------------------------------------------------------------------------------+-- What a decision wrote, seen by its questions+-------------------------------------------------------------------------------++-- | A question cannot be answered from what Redis said and what the+-- decision wrote since: the question, and why.+data Unanswerable = Unanswerable !Query !String+  deriving (Eq, Show)++-- | The answer to a question after writes, given the answer before them.+-- The writes are those to the key of the question, in their order, with a+-- 'Del' for each 'Wipe' that takes the key.+--+-- What a write does to one cell, a field of a hash, a member of a set or+-- the score of one, is not said here: it is the function of+-- "Haskoin.Store.Fleet.Atomic.Cells" that the model of Redis below uses+-- too ('perform'). So for a question about one cell, the answer here is+-- what the model says after the writes, which Liquid Haskell checks+-- ('Haskoin.Store.Fleet.Atomic.Cells.cellAfterAll',+-- 'Haskoin.Store.Fleet.Atomic.Cells.thereAtAllSame'). For all the fields+-- of a hash and all the members of a set, the writes are done to the+-- answer by the function that does them to the model. For the rest, the+-- fields of a hash by name, a range or a count of a sorted set, whether a+-- key is there, the specs check it against the model on drawn cases, and+-- against a Redis.+replay :: Query -> Answer -> [Op] -> Either Unanswerable Answer+replay q before ops = case (q, before) of+  (Get _, Text v) -> Text <$> foldM' text v+  (HGet _ f, Text v) -> Text <$> foldM' (field f) v+  (HExists _ f, Flag b) -> Flag <$> foldM' (\x op -> (\o -> thereAt unmarked f o x) <$> kind hashOp op) b+  (HGetAll _, Fields m) -> Fields <$> foldM' fields m+  (HKeys _, Members s) -> Members . Map.keysSet <$> foldM' (those nameOp) (Map.fromSet (const ()) s)+  (HAbove _ _, Members _)+    | null ops -> Right before+    | otherwise -> no "which numbers of a hash are above a bound, after the hash was written to"+  (SIsMember _ x, Flag b) -> Flag <$> foldM' (\y op -> (\o -> thereAt unmarked x o y) <$> kind groupOp op) b+  (SMembers _, Members s) -> Members . Map.keysSet <$> foldM' (those groupOp) (Map.fromSet (const ()) s)+  (ZScore _ x, Scored s) -> Scored <$> foldM' (score x) s+  (ZCard _, Count n) -> Count <$> foldM' count n+  (ZRangeByScore _ lo hi limit, Ranked ms)+    | null ops -> Right before+    | Just _ <- limit -> no "a range with a limit, of a sorted set that was written to"+    | otherwise -> Ranked . sortOn (\(x, s) -> (s, x)) . Map.toList <$> foldM' (ranked lo hi) (Map.fromList ms)+  (Exists _, Flag b) ->+    foldM' there (Just b) >>= \case+      Just b' -> Right (Flag b')+      Nothing -> no "whether a key is there after something was taken out of it"+  _ -> no "an answer of another kind than the question"+  where+    no :: String -> Either Unanswerable a+    no = Left . Unanswerable q+    wrong :: Op -> Either Unanswerable a+    wrong op = no ("a write of another kind than the key: " <> show op)+    foldM' :: (a -> Op -> Either Unanswerable a) -> a -> Either Unanswerable a+    foldM' f z = foldl' (\acc op -> acc >>= (`f` op)) (Right z) ops+    -- a write as one to a key of some kind, or it is to a key of another+    kind :: (Op -> Maybe o) -> Op -> Either Unanswerable o+    kind as op = maybe (wrong op) Right (as op)+    -- Redis adds to a number only: a decision that adds to anything else+    -- would have its writes refused half way, so it is stopped here+    adds :: Maybe ByteString -> Either Unanswerable ()+    adds v = if maybe True numeric v then Right () else no "a number, of a value that is none"+    text v op =+      kind textOp op >>= \c -> case c of+        Plus _ -> cellAfter addTo c v <$ adds v+        _ -> Right (cellAfter addTo c v)+    field f v op =+      kind hashOp op >>= \o -> case o of+        On g (Plus _) | g == f -> at unmarked (cellAfter addTo) f o v <$ adds v+        _ -> Right (at unmarked (cellAfter addTo) f o v)+    fields m op =+      kind hashOp op >>= \o -> case o of+        On g (Plus _) -> mapAfter unmarked (cellAfter addTo) o m <$ adds (Map.lookup g m)+        _ -> Right (mapAfter unmarked (cellAfter addTo) o m)+    -- the names of what a hash or a set holds, as a map of cells that+    -- hold nothing+    those :: (Op -> Maybe (Within (CellOp ()))) -> Map ByteString () -> Op -> Either Unanswerable (Map ByteString ())+    those as m op = (\o -> mapAfter unmarked (cellAfter nothingTo) o m) <$> kind as op+    score x s = \case+      ZRemRangeByRank {} -> no "a score, of a sorted set that lost members by their rank"+      op -> (\o -> at unmarked rankAfter x o s) <$> kind rankOp op+    count _ = \case+      Del _ -> Right 0+      op | sortedOp op -> no "how many members a sorted set has after it was written to"+      op -> wrong op+    ranked lo hi m = \case+      ZAdd _ v y+        | within lo hi v -> Right (Map.insert y v m)+        | otherwise -> Right (Map.delete y m)+      ZRem _ y -> Right (Map.delete y m)+      Del _ -> Right Map.empty+      op | sortedOp op -> no ("a range, of a sorted set after " <> show op)+      op -> wrong op+    -- whether the key is there: known, or not known any more+    there known = \case+      Del _ -> Right (Just False)+      op | makes op -> Right (Just True)+      _ -> Right (if known == Just False then Just False else Nothing)++-- | A write to a map inside what a key holds: to a field of a hash, a+-- member of a set or of a sorted set, or to all of them. Nothing marks+-- those, as the start of a key marks the keys that a wipe takes.+type Within c = MapOp () ByteString c++-- | No field or member is marked.+unmarked :: () -> ByteString -> Bool+unmarked _ _ = False++-- | Add to the number that bytes say, as @INCRBY@ does, or to 0 for none.+addTo :: Integer -> Maybe ByteString -> ByteString+addTo n v = C.pack (show (maybe 0 (maybe 0 fst . C.readInteger) v + n))++-- | What adding gives a cell that holds nothing: nothing.+nothingTo :: Integer -> Maybe () -> ()+nothingTo _ _ = ()++-- | Whether bytes are a whole number, all of them.+numeric :: ByteString -> Bool+numeric v = case C.readInteger v of+  Just (_, rest) -> B.null rest+  Nothing -> False++-- | A write to a key that holds bytes, as a write to one cell.+textOp :: Op -> Maybe (CellOp ByteString)+textOp = \case+  Set _ x -> Just (Put x)+  Del _ -> Just Clear+  IncrBy _ n -> Just (Plus n)+  _ -> Nothing++-- | A write to a hash, as a write to the map of its fields.+hashOp :: Op -> Maybe (Within (CellOp ByteString))+hashOp = \case+  HSet _ f x -> Just (On f (Put x))+  HDel _ f -> Just (On f Clear)+  HIncrBy _ f n -> Just (On f (Plus n))+  Del _ -> Just All+  _ -> Nothing++-- | A write to a hash, as a write to the names of its fields.+nameOp :: Op -> Maybe (Within (CellOp ()))+nameOp = \case+  HSet _ f _ -> Just (On f (Put ()))+  HDel _ f -> Just (On f Clear)+  HIncrBy _ f _ -> Just (On f (Put ()))+  Del _ -> Just All+  _ -> Nothing++-- | A write to a set, as a write to the map of its members.+groupOp :: Op -> Maybe (Within (CellOp ()))+groupOp = \case+  SAdd _ x -> Just (On x (Put ()))+  SRem _ x -> Just (On x Clear)+  Del _ -> Just All+  _ -> Nothing++-- | A write to a sorted set that changes the score of one member or takes+-- all of them, as a write to the map of its scores. One that takes+-- members by their rank is not one of those.+rankOp :: Op -> Maybe (Within (RankOp Score))+rankOp = \case+  ZAdd _ s x -> Just (On x (Rank s))+  ZAddNX _ s x -> Just (On x (RankNew s))+  ZRem _ x -> Just (On x Unrank)+  Del _ -> Just All+  _ -> Nothing++-- | Whether a score is between two bounds, both included.+within :: Bound -> Bound -> Score -> Bool+within lo hi v = above && below+  where+    above = case lo of+      MinusInf -> True+      PlusInf -> False+      At x -> v >= x+    below = case hi of+      PlusInf -> True+      MinusInf -> False+      At x -> v <= x++sortedOp, makes :: Op -> Bool+sortedOp = \case+  ZAdd {} -> True+  ZAddNX {} -> True+  ZRem {} -> True+  ZRemRangeByRank {} -> True+  _ -> False+makes = \case+  Set {} -> True+  IncrBy {} -> True+  HSet {} -> True+  HIncrBy {} -> True+  SAdd {} -> True+  ZAdd {} -> True+  ZAddNX {} -> True+  XAdd {} -> True+  _ -> False++-------------------------------------------------------------------------------+-- Decisions+-------------------------------------------------------------------------------++-- | What a decision asks of what runs it: the answers of Redis to+-- questions, all at once, and the clock of Redis in milliseconds.+data Backend m = Backend+  { fetch :: !([Query] -> m [Answer]),+    time :: !(m Integer)+  }++-- | What a decision has done so far, in one pass over it.+data Session = Session+  { -- | what Redis said, to every question that it was asked+    said :: !(Map Query Answer),+    -- | the questions that the decision asked, and so depends on+    used :: !(Set Query),+    -- | the questions that Redis was not asked yet: the pass goes on as if+    -- the answer to each were nothing, and is made again with the answers+    missed :: !(Set Query),+    -- | how many writes there are+    next :: !Int,+    -- | the writes to each key, each with its number among all+    byKey :: !(Map Key (Seq (Int, Op))),+    -- | of those, the writes to one cell of a key: a field of a hash, a+    -- member of a set or of a sorted set+    byCell :: !(Map (Key, ByteString) (Seq (Int, Op))),+    -- | and those to all the cells of a key at once+    byWhole :: !(Map Key (Seq (Int, Op))),+    -- | the wipes, each with its number+    wipes :: !(Seq (Int, ByteString)),+    -- | every write, in order+    ops :: !(Seq Op),+    -- | the clock, once it was read+    clockAt :: !(Maybe Integer),+    -- | the marks that Redis was found without, so that a key that they+    -- guard may be written to ('guarding')+    clear :: !(Set Key),+    -- | whether the decision writes to guarded keys whatever is marked+    -- ('unguarded')+    free :: !Bool+  }++-- | A decision about the state in Redis: a computation that asks ('query'),+-- writes ('write') and can do nothing else, whatever monad @m@ runs it.+-- 'runAtomic' gives what it decided: the questions that it depends on with+-- their answers, and its writes.+--+-- A decision is run more than once ('runAtomic'), so it must be the same+-- computation each time: it is, having nothing to differ by but its+-- answers.+newtype Atomic m a = Atomic (ReaderT (Backend m) (ExceptT Stop (StateT Session m)) a)+  deriving newtype (Functor, Applicative, Monad)++-- | The state of a decision.+session :: (Monad m) => StateT Session m a -> Atomic m a+session = Atomic . lift . lift++-- | Stop a decision.+stop :: (Monad m) => Stop -> Atomic m a+stop = Atomic . lift . throwE++-- | Something of what runs the decision.+backend :: (Monad m) => (Backend m -> m a) -> Atomic m a+backend f = Atomic (ask >>= lift . lift . lift . f)++-- | Why a decision stopped before its end: it asked what cannot be+-- answered, or it was to write to a key that a mark guards while Redis+-- had the mark.+data Stop+  = Cannot !Unanswerable+  | Held !Key++-- | Before a write to a key that a mark guards: stop the decision if+-- Redis has the mark, and make the decision depend on Redis not having+-- it otherwise, so that it is carried out only if that is still so.+--+-- = Why+--+-- A move of the tip marks the transactions that leave the pool, and they+-- are taken out after it (@docs\/tip-first.md@). Until they are out,+-- nothing else may change the pool or the cache: what a request reads+-- there is right only because of that. Each decision that writes there+-- asks whether anything is marked, and does nothing if so. That was a+-- line of code in each of them, and a decision written without it would+-- have compiled, passed its own tests, and written among the marked+-- transactions.+--+-- So the asking is here, under every write+-- ("Haskoin.Store.Fleet.Atomic.Keys" calls this before each write to a+-- key that was named with its mark). A decision cannot write to such a+-- key without it. One that still asks for itself, to answer something+-- better than a failure, asks the same question and is never stopped+-- here.+--+-- = What counts+--+-- What Redis said, and not what the decision wrote since: the move of the+-- tip writes the marks itself, and goes on writing. A decision that has+-- to write among marked transactions says so ('unguarded'): the taking+-- out, and the emptying of the pool.+guarding :: (Monad m) => Key -> Atomic m ()+guarding mark = do+  s <- session (gets id)+  let q = Exists mark+  if s.free || Set.member mark s.clear+    then return ()+    else case Map.lookup q s.said of+      Just (Flag True) -> stop (Held mark)+      Just _ -> session (modify' (\x -> x {used = Set.insert q x.used, clear = Set.insert mark x.clear}))+      -- Redis was not asked: this pass does not count, and goes on as if+      -- it had no mark+      Nothing -> session (modify' (\x -> x {missed = Set.insert q x.missed}))++-- | From here on the decision writes to guarded keys whatever is marked.+-- For the decisions that are made among marked transactions: the taking+-- out of those, and the emptying of the pool with its marks.+unguarded :: (Monad m) => Atomic m ()+unguarded = session (modify' (\s -> s {free = True}))++-- | The clock of Redis, in milliseconds: read once in a decision, and the+-- same every time after, however many times Redis is asked before the+-- decision is made. The script does not compare it, as it compares+-- answers, and it is earlier than the script: by a moment for most+-- decisions, and by ten seconds and more for a move of the tip over a+-- full block.+--+-- So a decision may use it for what it writes, and may judge by it only+-- what stays true as time goes on, or what the time since does not matter+-- to: that a lease has run out, or that a move went quiet for ten+-- seconds, is as true later; that a lease has not run out yet is what a+-- script that ran when the decision began would have found.+--+-- It was read again each time Redis was asked, once. A move of the tip+-- that Redis was asked about for ten seconds then judged the leases by a+-- clock ten seconds after its store renewed its own, found no store+-- live, and was refused, turn after turn.+clock :: (Monad m) => Atomic m Integer+clock =+  session (gets (.clockAt)) >>= \case+    Just t -> return t+    Nothing -> do+      t <- backend (.time)+      session (modify' (\s -> s {clockAt = Just t}))+      return t++-- | Name questions that the decision will probably ask, so that Redis is+-- asked them with the next that it has to be asked, in the same round+-- trip. The decision does not depend on them: an answer is compared by+-- the script only if the decision asks for it. It changes how many round+-- trips a decision takes, and nothing else.+prefetch :: (Monad m) => [Query] -> Atomic m ()+prefetch qs = session . modify' $ \s ->+  s {missed = foldl' (\m q -> if Map.member q s.said then m else Set.insert q m) s.missed qs}++-- | A question to name ahead, with those that its answer names: what a+-- decision will ask of the children of a transaction is known only once+-- Redis has said which they are.+data Ahead = Ahead !Query (Answer -> [Ahead])++-- | Name questions ahead in steps: these, and, of each that Redis has+-- answered, those that its answer names, and so on. It says whether Redis+-- has answered all of them.+--+-- = Why+--+-- A decision is gone through from its start each time Redis is asked+-- ('runAtomic'). 'prefetch' is for what a decision can name before it+-- asks anything. What it asks next, of what the first answers name, cost+-- a whole pass for each step of such a chain: the move of the tip over a+-- block of four thousand transactions was gone through five times, three+-- of them to ask a few hundred questions each about the children of its+-- transactions.+--+-- = What a decision may do with the answer+--+-- It may leave a pass in which this says no, with any result: Redis has+-- not answered a question that was named here, so the pass does not+-- count, and is gone through again once Redis has. So the steps of a+-- chain cost a question each to Redis and not a pass each over the whole+-- decision. In the pass that counts Redis has answered everything, and+-- this says yes.+--+-- The answers that the steps are worked out from are what Redis said and+-- go nowhere else: the decision depends on a question only by asking it+-- ('query'), and the script compares only those. Naming too little costs+-- a pass, and too much costs its answer.+ahead :: (Monad m) => [Ahead] -> Atomic m Bool+ahead hints = do+  s <- session (gets id)+  let go ready missing = \case+        [] -> (ready, missing)+        Ahead q next : rest -> case Map.lookup q s.said of+          Just a -> go ready missing (next a <> rest)+          Nothing -> go False (Set.insert q missing) rest+      (answered, missed) = go True s.missed hints+  session (modify' (\x -> x {missed}))+  return answered++-- | The answer of a Redis that has nothing: what a pass goes on with for a+-- question that Redis was not asked yet.+nothing :: Query -> Answer+nothing = \case+  Get _ -> Text Nothing+  HGet _ _ -> Text Nothing+  HExists _ _ -> Flag False+  HGetAll _ -> Fields Map.empty+  HKeys _ -> Members Set.empty+  HAbove _ _ -> Members Set.empty+  SIsMember _ _ -> Flag False+  SMembers _ -> Members Set.empty+  ZScore _ _ -> Scored Nothing+  ZCard _ -> Count 0+  ZRangeByScore {} -> Ranked []+  Exists _ -> Flag False++-- | Ask a question: what Redis says, as changed by what the decision wrote+-- since. The decision depends on what Redis said from here on.+query :: (Monad m) => Query -> Atomic m Answer+query q = do+  s <- session (gets id)+  let written = writesTo q s+  case Map.lookup q s.said of+    Just before -> do+      session (modify' (\x -> x {used = Set.insert q x.used}))+      either (stop . Cannot) return (replay q before written)+    -- Redis was not asked: this pass will not count, and goes on only to+    -- find what else there is to ask+    Nothing -> do+      session (modify' (\x -> x {missed = Set.insert q x.missed}))+      return (either (const (nothing q)) id (replay q (nothing q) written))++-- | 'query' several.+queries :: (Monad m) => [Query] -> Atomic m [Answer]+queries = mapM query++-- | The writes of a decision that a question has to go through, in+-- order, a wipe that takes the key being a 'Del' of it.+--+-- For a question about one cell, a field of a hash, a member of a set or+-- the score of a member, those are the writes to that cell and the writes+-- to all the cells of the key: the writes to its other cells change+-- nothing for it ('Haskoin.Store.Fleet.Atomic.Cells.skipOthers'). A+-- decision that takes thousands of transactions out of the pool writes to+-- thousands of fields of one hash, and asks about each: going through all+-- the writes to the key for each question took time that grew with the+-- square of the block. For any other question they are all the writes to+-- its key.+writesTo :: Query -> Session -> [Op]+writesTo q s = map snd (merge (toList own) wiped)+  where+    k = queryKey q+    own = case cellOf q of+      Just c -> mergeSeq (found (k, c) s.byCell) (found k s.byWhole)+      Nothing -> found k s.byKey+    found :: (Ord a) => a -> Map a (Seq (Int, Op)) -> Seq (Int, Op)+    found x = fromMaybe Seq.empty . Map.lookup x+    mergeSeq a b = Seq.fromList (merge (toList a) (toList b))+    wiped = [(n, Del k) | (n, p) <- toList s.wipes, p `B.isPrefixOf` k]+    merge xs [] = xs+    merge [] ys = ys+    merge (x : xs) (y : ys)+      | fst x <= fst y = x : merge xs (y : ys)+      | otherwise = y : merge (x : xs) ys++-- | The cell that a question is about, if it is about one.+cellOf :: Query -> Maybe ByteString+cellOf = \case+  HGet _ f -> Just f+  HExists _ f -> Just f+  SIsMember _ x -> Just x+  ZScore _ x -> Just x+  _ -> Nothing++-- | The cell that a write is to, if it is to one; nothing for a write to+-- all the cells of its key, or to a key that has none.+cellOfOp :: Op -> Maybe ByteString+cellOfOp = \case+  HSet _ f _ -> Just f+  HDel _ f -> Just f+  HIncrBy _ f _ -> Just f+  SAdd _ x -> Just x+  SRem _ x -> Just x+  ZAdd _ _ x -> Just x+  ZAddNX _ _ x -> Just x+  ZRem _ x -> Just x+  _ -> Nothing++-- | Add a write to those of the decision. Nothing is changed in Redis+-- until the decision ends and the script finds its answers still true.+write :: (Monad m) => Op -> Atomic m ()+write op = session . modify' $ \s ->+  let n = s.next+      s' = s {next = n + 1, ops = s.ops |> op}+   in case opKey op of+        Right k ->+          let one = Seq.singleton (n, op)+              s'' = s' {byKey = Map.insertWith (flip (<>)) k one s.byKey}+           in case cellOfOp op of+                Just c -> s'' {byCell = Map.insertWith (flip (<>)) (k, c) one s.byCell}+                Nothing -> s'' {byWhole = Map.insertWith (flip (<>)) k one s.byWhole}+        Left p -> s' {wipes = s.wipes |> (n, p)}++-- | How a decision ended.+data Outcome a+  = -- | with a result, the questions that it depends on with what Redis+    -- said to each, its writes in order, and how many times Redis was+    -- asked+    Decided a ![(Query, Answer)] ![Op] !Int+  | -- | it asked what cannot be answered: a fault of the decision+    Stuck !Unanswerable++-- | Run a decision. Nothing is changed: what it decided is for the caller+-- to carry out, if the answers that it depends on are still true.+--+-- The decision is gone through as many times as it takes to know what it+-- asks. A pass that comes to a question that Redis was not asked goes on+-- as if the answer were nothing, to find what else it would ask; then+-- Redis is asked all of those at once, and the decision is gone through+-- again from its start. The last pass is the one that counts: every+-- answer in it is one that Redis gave, and what a pass before it made of+-- an answer that it did not have is dropped whole. So a decision that+-- asks a hundred questions asks Redis a few times and not a hundred, and+-- which questions go together is found, not written down.+--+-- It ends because each time Redis is asked at least one question that it+-- was not asked before, and a decision that ends asks finitely many.+runAtomic :: (Monad m) => Backend m -> Atomic m a -> m (Outcome a)+runAtomic with (Atomic f) = go Map.empty (0 :: Int) Nothing+  where+    -- with the clock that an earlier pass read, if one did: the clock of+    -- a decision is read once, and not once in each pass+    go known rounds before = do+      (r, s) <- runStateT (runExceptT (runReaderT f with)) (start known before)+      if Set.null s.missed+        then return $ case r of+          Left (Cannot why) -> Stuck why+          Left (Held mark) -> Stuck (Unanswerable (Exists mark) held)+          Right a -> Decided a [(q, x) | q <- Set.toList s.used, Just x <- [Map.lookup q known]] (toList s.ops) rounds+        else do+          let new = Set.toList s.missed+          answers <- with.fetch new+          go (foldl' (\m (q, a) -> Map.insert q a m) known (zip new answers)) (rounds + 1) s.clockAt+    start known before =+      Session+        { said = known,+          used = Set.empty,+          missed = Set.empty,+          next = 0,+          byKey = Map.empty,+          byCell = Map.empty,+          byWhole = Map.empty,+          wipes = Seq.empty,+          ops = Seq.empty,+          clockAt = before,+          clear = Set.empty,+          free = False+        }++-- | What a decision that was stopped at a mark says ('guarding'). It is a+-- fault of the decision, as a question that cannot be answered is: one+-- that writes to the pool or to the cache asks first whether anything is+-- marked, and does nothing then.+held :: String+held = "a write to a key that this mark guards, while Redis has the mark: nothing is written"++-- | Whether a decision was stopped at a mark.+heldByMark :: Unanswerable -> Bool+heldByMark (Unanswerable _ why) = why == held++-- | The writes of a decision without those that a later one undoes: a+-- write to a key that is deleted afterwards, or wiped, changes nothing in+-- the end. Redis is the same after the writes that are left, in their+-- order, as after all of them.+--+-- A decision writes as the script before it did, one thing at a time: a+-- transaction that leaves the pool takes five counts off the summary of+-- an address, and then the summary is deleted, since nothing is left of+-- it. For a block that confirms thousands of transactions, most of what+-- was written was undone a few writes later, and all of it was sent to+-- Redis.+tidy :: [Op] -> [Op]+tidy written = snd (foldl' keep ((Set.empty, []), []) (reverse written))+  where+    -- from the last write to the first, with the keys that a later write+    -- deletes and the starts of those that one wipes; what is kept is put+    -- in front of what was kept after it, and so comes out in its order+    keep ((gone, wiped), kept) op = case opKey op of+      Left p -> ((gone, p : wiped), op : kept)+      Right k+        | Set.member k gone || any (`B.isPrefixOf` k) wiped -> ((gone, wiped), kept)+        | Del _ <- op -> ((Set.insert k gone, wiped), op : kept)+        | otherwise -> ((gone, wiped), op : kept)++-------------------------------------------------------------------------------+-- Reading+-------------------------------------------------------------------------------++-- | An answer of another kind than its question, which 'replay' and the+-- backends never give.+mismatch :: (Monad m) => Query -> Atomic m a+mismatch q = stop (Cannot (Unanswerable q "an answer of another kind than the question"))++-- | @GET@.+get :: (Monad m) => Key -> Atomic m (Maybe ByteString)+get k =+  query (Get k) >>= \case+    Text v -> return v+    _ -> mismatch (Get k)++-- | @HGET@.+hget :: (Monad m) => Key -> ByteString -> Atomic m (Maybe ByteString)+hget k f =+  query (HGet k f) >>= \case+    Text v -> return v+    _ -> mismatch (HGet k f)++-- | @HEXISTS@.+hexists :: (Monad m) => Key -> ByteString -> Atomic m Bool+hexists k f =+  query (HExists k f) >>= \case+    Flag v -> return v+    _ -> mismatch (HExists k f)++-- | @HGETALL@.+hgetall :: (Monad m) => Key -> Atomic m (Map ByteString ByteString)+hgetall k =+  query (HGetAll k) >>= \case+    Fields v -> return v+    _ -> mismatch (HGetAll k)++-- | @HKEYS@.+hkeys :: (Monad m) => Key -> Atomic m (Set ByteString)+hkeys k =+  query (HKeys k) >>= \case+    Members v -> return v+    _ -> mismatch (HKeys k)++-- | The fields of a hash whose value is a whole number above a bound.+habove :: (Monad m) => Key -> Integer -> Atomic m (Set ByteString)+habove k n =+  query (HAbove k n) >>= \case+    Members v -> return v+    _ -> mismatch (HAbove k n)++-- | @SISMEMBER@.+sismember :: (Monad m) => Key -> ByteString -> Atomic m Bool+sismember k x =+  query (SIsMember k x) >>= \case+    Flag v -> return v+    _ -> mismatch (SIsMember k x)++-- | @SMEMBERS@.+smembers :: (Monad m) => Key -> Atomic m (Set ByteString)+smembers k =+  query (SMembers k) >>= \case+    Members v -> return v+    _ -> mismatch (SMembers k)++-- | @ZSCORE@.+zscore :: (Monad m) => Key -> ByteString -> Atomic m (Maybe Score)+zscore k x =+  query (ZScore k x) >>= \case+    Scored v -> return v+    _ -> mismatch (ZScore k x)++-- | @ZCARD@.+zcard :: (Monad m) => Key -> Atomic m Integer+zcard k =+  query (ZCard k) >>= \case+    Count v -> return v+    _ -> mismatch (ZCard k)++-- | @ZRANGEBYSCORE@, with the scores.+zrangeByScore :: (Monad m) => Key -> Bound -> Bound -> Maybe Int -> Atomic m [(ByteString, Score)]+zrangeByScore k lo hi limit =+  query (ZRangeByScore k lo hi limit) >>= \case+    Ranked v -> return v+    _ -> mismatch (ZRangeByScore k lo hi limit)++-- | @EXISTS@.+exists :: (Monad m) => Key -> Atomic m Bool+exists k =+  query (Exists k) >>= \case+    Flag v -> return v+    _ -> mismatch (Exists k)++-------------------------------------------------------------------------------+-- A model of Redis+-------------------------------------------------------------------------------++-- | What a key of Redis holds.+data Value+  = Bytes !ByteString+  | Hash !(Map ByteString ByteString)+  | -- | a set: its members+    Group !(Map ByteString ())+  | Sorted !(Map ByteString Score)+  | -- | a stream: the fields of its entries, oldest first+    Stream !(Seq [(ByteString, ByteString)])+  deriving (Eq, Show)++-- | The keys of a Redis and what each holds. A key that holds nothing is+-- not there, as in Redis.+type Db = Map Key Value++-- | A Redis with nothing in it.+emptyDb :: Db+emptyDb = Map.empty++-- | What a Redis in this state says to a question. A question about a key+-- of another kind is answered as if the key were not there; the fleet asks+-- none.+answer :: Db -> Query -> Answer+answer db = \case+  Get k -> Text (case Map.lookup k db of Just (Bytes v) -> Just v; _ -> Nothing)+  HGet k f -> Text (Map.lookup f (hash (Map.lookup k db)))+  HExists k f -> Flag (Map.member f (hash (Map.lookup k db)))+  HGetAll k -> Fields (hash (Map.lookup k db))+  HKeys k -> Members (Map.keysSet (hash (Map.lookup k db)))+  HAbove k n -> Members (Map.keysSet (Map.filter (maybe False ((> n) . fst) . C.readInteger) (hash (Map.lookup k db))))+  SIsMember k x -> Flag (Map.member x (group (Map.lookup k db)))+  SMembers k -> Members (Map.keysSet (group (Map.lookup k db)))+  ZScore k x -> Scored (Map.lookup x (sorted (Map.lookup k db)))+  ZCard k -> Count (fromIntegral (Map.size (sorted (Map.lookup k db))))+  ZRangeByScore k lo hi limit ->+    Ranked . maybe id take limit . sortOn (\(x, s) -> (s, x)) $+      [(x, s) | (x, s) <- Map.toList (sorted (Map.lookup k db)), within lo hi s]+  Exists k -> Flag (Map.member k db)++-- | The fields of what a key holds, if it is a hash, the members if it is+-- a set, and the scores if it is a sorted set: none for a key that is not+-- there or holds something else.+hash :: Maybe Value -> Map ByteString ByteString+hash = \case+  Just (Hash m) -> m+  _ -> Map.empty++group :: Maybe Value -> Map ByteString ()+group = \case+  Just (Group m) -> m+  _ -> Map.empty++sorted :: Maybe Value -> Map ByteString Score+sorted = \case+  Just (Sorted m) -> m+  _ -> Map.empty++-- | A Redis after a write: the map of its keys after a write to the cell+-- of one key, or to the cells of the keys that start with some bytes+-- ('Haskoin.Store.Fleet.Atomic.Cells.mapAfter').+perform :: Op -> Db -> Db+perform op = mapAfter B.isPrefixOf holds route+  where+    route = case opKey op of+      Right k -> On k op+      Left p -> Under p++-- | What a key holds after a write to it, from what it held: the cell of+-- the key. A hash, a set and a sorted set are maps of cells in turn, and+-- change by the same function, each with the function of its cells; one+-- that is left with nothing is no key any more, as in Redis.+--+-- A write to a key that holds something of another kind changes nothing+-- here, where Redis would refuse it; the fleet makes none.+holds :: Op -> Maybe Value -> Maybe Value+holds op v = case (op, v) of+  (Del _, _) -> Nothing+  (Wipe _, _) -> Nothing+  (_, Just (Bytes x)) | Just c <- textOp op -> Bytes <$> cellAfter addTo c (Just x)+  (_, Nothing) | Just c <- textOp op -> Bytes <$> cellAfter addTo c Nothing+  (_, Just (Hash m)) | Just o <- hashOp op -> kept Hash (mapAfter unmarked (cellAfter addTo) o m)+  (_, Nothing) | Just o <- hashOp op -> kept Hash (mapAfter unmarked (cellAfter addTo) o Map.empty)+  (_, Just (Group m)) | Just o <- groupOp op -> kept Group (mapAfter unmarked (cellAfter nothingTo) o m)+  (_, Nothing) | Just o <- groupOp op -> kept Group (mapAfter unmarked (cellAfter nothingTo) o Map.empty)+  (_, Just (Sorted m)) | Just o <- rankOp op -> kept Sorted (mapAfter unmarked rankAfter o m)+  (_, Nothing) | Just o <- rankOp op -> kept Sorted (mapAfter unmarked rankAfter o Map.empty)+  (ZRemRangeByRank _ from to, Just (Sorted m)) -> kept Sorted (dropRanks from to m)+  (XAdd _ keep fields, Just (Stream es)) -> Just (Stream (trim keep (es |> fields)))+  (XAdd _ keep fields, Nothing) -> Just (Stream (trim keep (Seq.singleton fields)))+  _ -> v+  where+    kept con m = if Map.null m then Nothing else Just (con m)+    -- a stream keeps about so many: here, no more than that+    trim keep es = Seq.drop (Seq.length es - keep) es+    -- the members from one rank to another, both included, counted from 0+    -- and, below zero, from the end+    dropRanks from to m =+      let ranked = sortOn (\(x, s) -> (s, x)) (Map.toList m)+          n = fromIntegral (length ranked) :: Integer+          -- as Redis counts: a start before the first member is the+          -- first, and an end before it is no member at all+          a = if from < 0 then max 0 (n + from) else from+          b = min (n - 1) (if to < 0 then n + to else to)+          gone = [x | (i, (x, _)) <- zip [0 ..] ranked, i >= a, i <= b]+       in foldl' (flip Map.delete) m gone++-- | Run a decision against the model, and carry out what it decided: the+-- result and the model after it. Nothing else changes the model+-- meanwhile, so the answers are always still true. The clock is given.+runPure :: Integer -> (forall m. (Monad m) => Atomic m a) -> Db -> Either Unanswerable (a, Db)+runPure now decision db =+  case runIdentity (runAtomic model decision) of+    Decided a _ written _ -> Right (a, foldl' (flip perform) db written)+    Stuck why -> Left why+  where+    model :: Backend Identity+    model = Backend {fetch = return . map (answer db), time = return now}
+ src/Haskoin/Store/Fleet/Atomic/Cells.hs view
@@ -0,0 +1,418 @@+{-@ LIQUID "--reflection" @-}+{-@ LIQUID "--ple" @-}+-- 'onKey', 'onCell' and 'underWhat' say which key, which write and which+-- mark a write has, for the kind of write that has one: the types that+-- Liquid Haskell checks let them be asked of that kind only.+{-# OPTIONS_GHC -Wno-incomplete-patterns #-}++-- |+-- Module      : Haskoin.Store.Fleet.Atomic.Cells+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- What a write does, said once: the part of "Haskoin.Store.Fleet.Atomic"+-- that Liquid Haskell checks (@proofs\/@ of the repository).+--+-- = The problem+--+-- A decision reads back what it has written. So what each write does was+-- written twice: in the model of Redis, which says what Redis holds after+-- a write, and in the function that changes an answer of Redis by the+-- writes that came after it. If the two differed, a decision would see+-- something else than Redis would have said, and decide wrongly without+-- anything failing. That they agreed was tested on drawn cases.+--+-- = What is done instead+--+-- Redis is a map from keys to what they hold, and a hash, a set and a+-- sorted set are maps too: from fields to values, from members to nothing,+-- from members to scores. Each is a __map of cells__, and a write is to+-- the cell of one key ('On'), to every cell ('All'), or to the cells of+-- the keys that something marks ('Under'), as a wipe is to the keys that+-- start with some bytes.+--+-- What a write does to one cell is a function, such as 'cellAfter'. Both+-- sides use the same one: the model changes the cell of the key that the+-- write names with it ('mapAfter'), and a decision takes the answer that+-- it has for a cell through it ('at'). So there is one statement of what+-- @HSET@ or @ZADD NX@ does.+--+-- = What is proved+--+-- What is left to get wrong is the map around the cells: that the write+-- reaches the cell of its key and no other. That is the theorem here,+-- 'cellAfterAll': for any function of a cell, any key, and any writes one+-- after the other, the cell of the key in the map after them is what the+-- cell was, taken through 'at' for each write. Liquid Haskell checks it+-- for every case, by 'step' for one write and by induction for a list.+--+-- 'thereAtAllSame' is the same for a question that only asks whether a+-- cell holds something, as @HEXISTS@ and @SISMEMBER@ do: that is known+-- after any writes from whether it did before, without what it held.+--+-- = What it assumes+--+-- Four facts of "Data.Map", written as @assume@ lines: that a lookup after+-- a cell was put gives that cell at its key ('selSame') and what was there+-- at any other ('selOther'), that an empty map has no cell ('selNone'),+-- and that a map filtered by its keys has the cells of the keys that stay+-- ('selLess'). And the arithmetic of @INCRBY@ is not looked into: it is a+-- function given from outside, the same for both sides.+--+-- The bytes are a type of any kind here, with nothing asked of it but+-- that two can be compared: the theorems hold for whatever they are.+module Haskoin.Store.Fleet.Atomic.Cells+  ( -- * Cells+    CellOp (..),+    Add,+    cellAfter,+    thereAfter,+    RankOp (..),+    rankAfter,++    -- * A map of cells+    MapOp (..),+    at,+    atAll,+    mapAfter,+    thereAt,+    thereAtAll,++    -- * What is assumed of "Data.Map"+    selSame,+    selOther,+    selNone,+    selLess,++    -- * What a write is, for the types that are checked+    isOn,+    isAll,+    isUnder,+    onKey,+    onCell,+    underWhat,++    -- * What is proved+    step,+    cellAfterAll,+    thereStep,+    thereAtStep,+    thereAtAllSame,++    -- * Only the writes that reach a cell+    reaches,+    onlyAt,+    skipOthers,+    skipOthersThere,+  )+where++import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (isJust)++-------------------------------------------------------------------------------+-- cells+-------------------------------------------------------------------------------++-- | A write to one cell that holds bytes: put bytes in it, take out what+-- it holds, or add to the number that it holds.+data CellOp b = Put b | Clear | Plus Integer++-- | What adding a number to what a cell holds, or to nothing, gives: the+-- arithmetic of @INCRBY@, given from outside and not looked into here.+type Add b = Integer -> Maybe b -> b++-- | What a cell holds after a write, from what it held.++{-@ reflect cellAfter @-}+cellAfter :: Add b -> CellOp b -> Maybe b -> Maybe b+cellAfter _ (Put x) _ = Just x+cellAfter _ Clear _ = Nothing+cellAfter add (Plus n) v = Just (add n v)++-- | Whether there is something in a cell after a write, from whether there was.++{-@ reflect thereAfter @-}+thereAfter :: CellOp b -> Bool -> Bool+thereAfter (Put _) _ = True+thereAfter Clear _ = False+thereAfter (Plus _) _ = True++-- | Whether a cell holds something after a write is what 'thereAfter'+-- says, from whether it did.++{-@ thereStep :: add:Add b -> c:CellOp b -> v:Maybe b -> {isJust (cellAfter add c v) == thereAfter c (isJust v)} @-}+thereStep :: Add b -> CellOp b -> Maybe b -> ()+thereStep _ (Put _) _ = ()+thereStep _ Clear _ = ()+thereStep _ (Plus _) _ = ()++-- | A write to the score of one member of a sorted set: give it a score,+-- give it one only if it has none, as @ZADD NX@ does, or take the member+-- out.+data RankOp s = Rank s | RankNew s | Unrank++-- | The score of a member after a write, from the score that it had.++{-@ reflect rankAfter @-}+rankAfter :: RankOp s -> Maybe s -> Maybe s+rankAfter (Rank s) _ = Just s+rankAfter (RankNew s) v = if isJust v then v else Just s+rankAfter Unrank _ = Nothing++-------------------------------------------------------------------------------+-- a map of cells+-------------------------------------------------------------------------------++-- | A write to a map of cells: to the cell of one key, to every cell, or to+-- the cells of the keys that something marks.+data MapOp p k c = On k c | All | Under p++-- | The cell of a key after a write to the map, from what the cell was:+-- what a decision takes its answer through. Given are what marks a key+-- and what a write does to a cell.++{-@ reflect at @-}+at :: (Eq k) => (p -> k -> Bool) -> (c -> Maybe v -> Maybe v) -> k -> MapOp p k c -> Maybe v -> Maybe v+at _ cell x (On y c) v = if y == x then cell c v else v+at _ _ _ All _ = Nothing+at marks _ x (Under p) v = if marks p x then Nothing else v++-- | 'at' for writes one after the other.++{-@ reflect atAll @-}+atAll :: (Eq k) => (p -> k -> Bool) -> (c -> Maybe v -> Maybe v) -> k -> [MapOp p k c] -> Maybe v -> Maybe v+atAll _ _ _ [] v = v+atAll marks cell x (op : ops) v = atAll marks cell x ops (at marks cell x op v)++-- "Data.Map", as far as this goes: a lookup, a cell put at a key or taken+-- from it, the empty map, and a map without the keys that something+-- marks. Each has a name in the types that are checked ('sel', 'put',+-- 'none', 'less'), and the functions below are what the rest of the+-- module calls, so that what is assumed of "Data.Map" is in these lines+-- and nowhere else.+{-@ measure sel :: Map k v -> k -> Maybe v @-}+{-@ measure put :: Map k v -> k -> Maybe v -> Map k v @-}+{-@ measure none :: Map k v -> Bool @-}+{-@ measure less :: Map k v -> p -> Map k v @-}++{-@ assume mLookup :: (Ord k) => x:k -> m:Map k v -> {r:Maybe v | r == sel m x} @-}+mLookup :: (Ord k) => k -> Map k v -> Maybe v+mLookup = Map.lookup++{-@ assume mPut :: (Ord k) => x:k -> c:Maybe v -> m:Map k v -> {n:Map k v | n == put m x c} @-}+mPut :: (Ord k) => k -> Maybe v -> Map k v -> Map k v+mPut x c = Map.alter (const c) x++{-@ assume mNone :: {m:Map k v | none m} @-}+mNone :: Map k v+mNone = Map.empty++{-@ assume mLess :: marks:(p -> k -> Bool) -> q:p -> m:Map k v -> {n:Map k v | n == less m q} @-}+mLess :: (p -> k -> Bool) -> p -> Map k v -> Map k v+mLess marks q = Map.filterWithKey (\k _ -> not (marks q k))++-- | Assumed: a lookup after a cell was put at a key gives that cell.++{-@ assume selSame :: m:Map k v -> x:k -> c:Maybe v -> {sel (put m x c) x == c} @-}+selSame :: Map k v -> k -> Maybe v -> ()+selSame _ _ _ = ()++-- | Assumed: a lookup at another key gives what was there before.++{-@ assume selOther :: m:Map k v -> x:k -> c:Maybe v -> y:{k | y /= x} -> {sel (put m x c) y == sel m y} @-}+selOther :: Map k v -> k -> Maybe v -> k -> ()+selOther _ _ _ _ = ()++-- | Assumed: the empty map has no cell.++{-@ assume selNone :: m:{Map k v | none m} -> x:k -> {sel m x == Nothing} @-}+selNone :: Map k v -> k -> ()+selNone _ _ = ()++-- | Assumed: a map without the keys that something marks has no cell at+-- such a key, and at any other the cell that it had.++{-@ assume selLess :: marks:(p -> k -> Bool) -> m:Map k v -> q:p -> x:k+      -> {sel (less m q) x == (if marks q x then Nothing else sel m x)} @-}+selLess :: (p -> k -> Bool) -> Map k v -> p -> k -> ()+selLess _ _ _ _ = ()++-- | Whether a write is to the cell of one key.++{-@ measure isOn @-}+isOn :: MapOp p k c -> Bool+isOn (On _ _) = True+isOn All = False+isOn (Under _) = False++-- | Whether a write is to every cell.++{-@ measure isAll @-}+isAll :: MapOp p k c -> Bool+isAll (On _ _) = False+isAll All = True+isAll (Under _) = False++-- | Whether a write is to the cells of the keys that something marks.++{-@ measure isUnder @-}+isUnder :: MapOp p k c -> Bool+isUnder (On _ _) = False+isUnder All = False+isUnder (Under _) = True++-- | The key of a write to one cell.++{-@ measure onKey @-}+{-@ onKey :: {op:MapOp p k c | isOn op} -> k @-}+onKey :: MapOp p k c -> k+onKey (On y _) = y++-- | What a write to one cell does to it.++{-@ measure onCell @-}+{-@ onCell :: {op:MapOp p k c | isOn op} -> c @-}+onCell :: MapOp p k c -> c+onCell (On _ c) = c++-- | What marks the keys of a write to marked cells.++{-@ measure underWhat @-}+{-@ underWhat :: {op:MapOp p k c | isUnder op} -> p @-}+underWhat :: MapOp p k c -> p+underWhat (Under q) = q++-- | The map after a write: what the model of Redis is changed by, for the+-- keys of Redis and for the fields, members and scores inside a key. Its+-- type says which map that is for each kind of write, in the names of+-- "Data.Map" above.++{-@ mapAfter :: (Ord k) => marks:(p -> k -> Bool) -> cell:(c -> Maybe v -> Maybe v) -> op:MapOp p k c -> m:Map k v+      -> {n:Map k v | (isAll op => none n)+                      && (isOn op => n == put m (onKey op) (cell (onCell op) (sel m (onKey op))))+                      && (isUnder op => n == less m (underWhat op))} @-}+mapAfter :: (Ord k) => (p -> k -> Bool) -> (c -> Maybe v -> Maybe v) -> MapOp p k c -> Map k v -> Map k v+mapAfter _ cell (On y c) m = mPut y (cell c (mLookup y m)) m+mapAfter _ _ All _ = mNone+mapAfter marks _ (Under q) m = mLess marks q m++-- | One write: the cell of a key, in any map that is what 'mapAfter' gives,+-- is what 'at' says, from what the cell was.++{-@ step :: (Ord k) => marks:(p -> k -> Bool) -> cell:(c -> Maybe v -> Maybe v) -> x:k -> op:MapOp p k c -> m:Map k v+      -> n:{Map k v | (isAll op => none n)+                      && (isOn op => n == put m (onKey op) (cell (onCell op) (sel m (onKey op))))+                      && (isUnder op => n == less m (underWhat op))}+      -> {sel n x == at marks cell x op (sel m x)} @-}+step :: (Ord k) => (p -> k -> Bool) -> (c -> Maybe v -> Maybe v) -> k -> MapOp p k c -> Map k v -> Map k v -> ()+step _ cell x (On y c) m _+  | y == x = selSame m y (cell c (mLookup y m))+  | otherwise = selOther m y (cell c (mLookup y m)) x+step _ _ x All _ n = selNone n x+step marks _ x (Under q) m _ = selLess marks m q x++-- | Any writes, one after the other: the cell of a key in the map after+-- them is what the cell was, taken through 'at' for each write.++{-@ cellAfterAll :: (Ord k) => marks:(p -> k -> Bool) -> cell:(c -> Maybe v -> Maybe v) -> x:k -> ops:[MapOp p k c]+      -> m:Map k v -> {r:Maybe v | r == atAll marks cell x ops (sel m x)} @-}+cellAfterAll :: (Ord k) => (p -> k -> Bool) -> (c -> Maybe v -> Maybe v) -> k -> [MapOp p k c] -> Map k v -> Maybe v+cellAfterAll _ _ x [] m = mLookup x m+cellAfterAll marks cell x (op : ops) m =+  let n = mapAfter marks cell op m+   in step marks cell x op m n `seq` cellAfterAll marks cell x ops n++-------------------------------------------------------------------------------+-- whether a cell holds something+-------------------------------------------------------------------------------++-- | Whether the cell of a key holds something after a write to the map,+-- from whether it did: 'at' for a question that asks no more.++{-@ reflect thereAt @-}+thereAt :: (Eq k) => (p -> k -> Bool) -> k -> MapOp p k (CellOp b) -> Bool -> Bool+thereAt _ x (On y c) b = if y == x then thereAfter c b else b+thereAt _ _ All _ = False+thereAt marks x (Under p) b = if marks p x then False else b++-- | 'thereAt' for writes one after the other.++{-@ reflect thereAtAll @-}+thereAtAll :: (Eq k) => (p -> k -> Bool) -> k -> [MapOp p k (CellOp b)] -> Bool -> Bool+thereAtAll _ _ [] b = b+thereAtAll marks x (op : ops) b = thereAtAll marks x ops (thereAt marks x op b)++-- | One write: whether the cell holds something after it, by 'at', is what+-- 'thereAt' says.++{-@ thereAtStep :: (Eq k) => marks:(p -> k -> Bool) -> add:Add b -> x:k -> op:MapOp p k (CellOp b) -> v:Maybe b+      -> {isJust (at marks (cellAfter add) x op v) == thereAt marks x op (isJust v)} @-}+thereAtStep :: (Eq k) => (p -> k -> Bool) -> Add b -> k -> MapOp p k (CellOp b) -> Maybe b -> ()+thereAtStep _ add x (On y c) v+  | y == x = thereStep add c v+  | otherwise = ()+thereAtStep _ _ _ All _ = ()+thereAtStep marks _ x (Under p) _+  | marks p x = ()+  | otherwise = ()++-- | Whether a cell holds something after any writes is known from whether+-- it did before them, without what it held.++{-@ thereAtAllSame :: (Eq k) => marks:(p -> k -> Bool) -> add:Add b -> x:k -> ops:[MapOp p k (CellOp b)] -> v:Maybe b+      -> {isJust (atAll marks (cellAfter add) x ops v) == thereAtAll marks x ops (isJust v)} @-}+thereAtAllSame :: (Eq k) => (p -> k -> Bool) -> Add b -> k -> [MapOp p k (CellOp b)] -> Maybe b -> ()+thereAtAllSame _ _ _ [] _ = ()+thereAtAllSame marks add x (op : ops) v =+  thereAtStep marks add x op v `seq` thereAtAllSame marks add x ops (at marks (cellAfter add) x op v)++-------------------------------------------------------------------------------+-- only the writes that reach a cell+-------------------------------------------------------------------------------++-- | Whether a write can change the cell of a key: one to that cell, to+-- every cell, or to marked cells. A write to the cell of another key+-- cannot.++{-@ reflect reaches @-}+reaches :: (Eq k) => k -> MapOp p k c -> Bool+reaches x (On y _) = y == x+reaches _ All = True+reaches _ (Under _) = True++-- | Of writes, those that can change the cell of a key, in their order.++{-@ reflect onlyAt @-}+onlyAt :: (Eq k) => k -> [MapOp p k c] -> [MapOp p k c]+onlyAt _ [] = []+onlyAt x (op : ops) = if reaches x op then op : onlyAt x ops else onlyAt x ops++-- | A decision that has written to ten thousand cells of one key need not+-- go through all of those writes for a question about one cell: the+-- writes to the other cells change nothing for it. So what a decision+-- sees of its own writes costs what the cell was written, not what the key+-- was.++{-@ skipOthers :: (Eq k) => marks:(p -> k -> Bool) -> cell:(c -> Maybe v -> Maybe v) -> x:k -> ops:[MapOp p k c]+      -> v:Maybe v -> {atAll marks cell x (onlyAt x ops) v == atAll marks cell x ops v} @-}+skipOthers :: (Eq k) => (p -> k -> Bool) -> (c -> Maybe v -> Maybe v) -> k -> [MapOp p k c] -> Maybe v -> ()+skipOthers _ _ _ [] _ = ()+skipOthers marks cell x (op : ops) v+  | reaches x op = skipOthers marks cell x ops (at marks cell x op v)+  | otherwise = skipOthers marks cell x ops v++-- | 'skipOthers' for a question that only asks whether a cell holds+-- something.++{-@ skipOthersThere :: (Eq k) => marks:(p -> k -> Bool) -> x:k -> ops:[MapOp p k (CellOp b)] -> b:Bool+      -> {thereAtAll marks x (onlyAt x ops) b == thereAtAll marks x ops b} @-}+skipOthersThere :: (Eq k) => (p -> k -> Bool) -> k -> [MapOp p k (CellOp b)] -> Bool -> ()+skipOthersThere _ _ [] _ = ()+skipOthersThere marks x (op : ops) b+  | reaches x op = skipOthersThere marks x ops (thereAt marks x op b)+  | otherwise = skipOthersThere marks x ops b
+ src/Haskoin/Store/Fleet/Atomic/Keys.hs view
@@ -0,0 +1,418 @@+-- |+-- Module      : Haskoin.Store.Fleet.Atomic.Keys+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- The questions and writes of "Haskoin.Store.Fleet.Atomic" with the kind+-- of each key in its type: what the decisions of the fleet are written+-- with.+--+-- = The problem+--+-- The script that carries out a decision compares every answer before it+-- writes, and then runs plain commands, so it cannot fail half way: unless+-- Redis refuses one of the commands. Redis refuses a command to a key of+-- another kind, an @HSET@ to a set, and an addition to what is no number.+-- That no decision makes such a write was a convention, kept by reading+-- eight hundred lines.+--+-- = What is done instead+--+-- A key has its kind in its type, t'K', given once, where the key is+-- named: in the record of the keys of the pool or of the cache. Each+-- question and each write here takes keys of one kind, so that a write of+-- another kind to a key does not compile. A key that holds a number, or a+-- hash that holds numbers, is a kind of its own ('Number', 'Counts'): it+-- can be added to, and it is only ever given a number.+--+-- A decision that imports this module, and not the writes of+-- "Haskoin.Store.Fleet.Atomic" itself, cannot write a command that Redis+-- refuses for the kind of its key. The two modules of decisions do.+--+-- = What it does not do+--+-- It does not know what a key holds in Redis: two records that name the+-- same key with two kinds would compile. So a key is named once. The pool+-- and the cache write some of the same keys, the version of the entries+-- and the lists of an entry among them, and the cache takes those from+-- the record of the pool.+module Haskoin.Store.Fleet.Atomic.Keys+  ( -- * Keys+    Kind (..),+    K,+    Family,+    named,+    guarded,+    family,+    guardedFamily,+    under,+    keyName,++    -- * Decisions+    Atomic,+    clock,+    prefetch,+    unguarded,++    -- * Questions named ahead, in steps+    Ahead,+    ahead,+    only,+    thenText,+    thenField,+    thenMember,+    thenMembers,+    thenAbove,+    askingCount,+    askingScore,+    askingRange,+    askingWhether,+    Query,+    Score,+    Bound (..),++    -- * Any key+    del,+    exists,+    wipe,++    -- * Bytes+    get,+    set,+    asking,++    -- * A number+    getNumber,+    setNumber,+    incrBy,+    askingNumber,++    -- * A hash+    hget,+    hexists,+    hgetall,+    hkeys,+    hset,+    hdel,+    askingField,+    askingWhetherField,++    -- * A hash of numbers+    hgetNumber,+    hsetNumber,+    hincrBy,+    hfieldsAbove,++    -- * A set+    sismember,+    smembers,+    sadd,+    srem,+    askingMember,+    askingMembers,++    -- * A sorted set+    zscore,+    zcard,+    zrangeByScore,+    zadd,+    zaddNew,+    zrem,+    zremRangeByRank,++    -- * A stream+    xadd,+  )+where++import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.ByteString.Char8 qualified as C+import Data.Map.Strict (Map)+import Data.Set (Set)+import Haskoin.Store.Fleet.Atomic+  ( Ahead (..),+    Atomic,+    Bound (..),+    Op (..),+    Query (..),+    Score,+    ahead,+    clock,+    prefetch,+    unguarded,+    write,+  )+import Haskoin.Store.Fleet.Atomic qualified as A++-- | What a key of Redis holds, as far as the fleet tells them apart.+data Kind+  = -- | bytes+    Text+  | -- | a whole number, which can be added to+    Number+  | -- | fields with bytes+    Hash+  | -- | fields with whole numbers, which can be added to+    Counts+  | -- | members+    Group+  | -- | members with scores+    Sorted+  | -- | entries, oldest first+    Stream++-- | A key that holds something of one kind, and the mark that guards it,+-- if one does ('guarded').+data K (kind :: Kind) = K !ByteString !(Maybe ByteString)+  deriving (Eq, Show)++-- | The start of the keys of one kind that there are for each of+-- something: for each address, each transaction, each entry. With the+-- mark that guards them all, if one does.+data Family (kind :: Kind) = Family !ByteString !(Maybe ByteString)++-- | A key by its name. Its kind is that of the place that it is put in:+-- the field of a record of keys.+named :: ByteString -> K kind+named k = K k Nothing++-- | A key that a mark guards: given the name of the mark, a key of its+-- own, and the name of the key. No decision can write to the key while+-- Redis has the mark, and a decision that writes to it is carried out+-- only if Redis still has no mark then+-- ('Haskoin.Store.Fleet.Atomic.guarding'). Every write of this module to+-- such a key asks first, so a decision has no way to write without it,+-- short of saying so ('unguarded').+--+-- The keys of the pool and of the cache of extended public keys are+-- guarded by the mark of the transactions that a move of the tip left to+-- be taken out (@docs\/tip-first.md@).+guarded :: ByteString -> ByteString -> K kind+guarded mark k = K k (Just mark)++-- | A family of keys by what they all start with.+family :: ByteString -> Family kind+family p = Family p Nothing++-- | A family of keys that a mark guards ('guarded').+guardedFamily :: ByteString -> ByteString -> Family kind+guardedFamily mark p = Family p (Just mark)++-- | The key of a family for one thing.+under :: Family kind -> ByteString -> K kind+under (Family p mark) x = K (p <> x) mark++-- | The name of a key.+keyName :: K kind -> ByteString+keyName (K k _) = k++num :: Integer -> ByteString+num = C.pack . show++-- | The whole number that bytes say, all of them.+whole :: ByteString -> Maybe Integer+whole v = case C.readInteger v of+  Just (n, rest) | B.null rest -> Just n+  _ -> Nothing++-- | A question to name ahead, and nothing after it ('ahead').+only :: Query -> Ahead+only q = Ahead q (const [])++-- | The question that 'get' asks, and what to name from its answer.+thenText :: K 'Text -> (Maybe ByteString -> [Ahead]) -> Ahead+thenText (K k _) next = Ahead (Get k) $ \case+  A.Text v -> next v+  _ -> []++-- | The question that 'hget' asks, and what to name from its answer.+thenField :: K 'Hash -> ByteString -> (Maybe ByteString -> [Ahead]) -> Ahead+thenField (K k _) f next = Ahead (HGet k f) $ \case+  A.Text v -> next v+  _ -> []++-- | The question that 'sismember' asks, and what to name from its answer.+thenMember :: K 'Group -> ByteString -> (Bool -> [Ahead]) -> Ahead+thenMember (K k _) x next = Ahead (SIsMember k x) $ \case+  A.Flag v -> next v+  _ -> []++-- | The question that 'smembers' asks, and what to name from its answer.+thenMembers :: K 'Group -> (Set ByteString -> [Ahead]) -> Ahead+thenMembers (K k _) next = Ahead (SMembers k) $ \case+  A.Members v -> next v+  _ -> []++-- | The question that 'hfieldsAbove' asks, and what to name from its+-- answer.+thenAbove :: K 'Counts -> Integer -> (Set ByteString -> [Ahead]) -> Ahead+thenAbove (K k _) n next = Ahead (HAbove k n) $ \case+  A.Members v -> next v+  _ -> []++-- | The question that 'hgetNumber' asks.+askingCount :: K 'Counts -> ByteString -> Query+askingCount (K k _) = HGet k++-- | The question that 'zscore' asks.+askingScore :: K 'Sorted -> ByteString -> Query+askingScore (K k _) = ZScore k++-- | The question that 'zrangeByScore' asks.+askingRange :: K 'Sorted -> Bound -> Bound -> Maybe Int -> Query+askingRange (K k _) = ZRangeByScore k++-- | The question that 'exists' asks.+askingWhether :: K kind -> Query+askingWhether (K k _) = Exists k++-- | @DEL@.+del :: (Monad m) => K kind -> Atomic m ()+del (K k mark) = mapM_ A.guarding mark >> write (Del k)++-- | @EXISTS@.+exists :: (Monad m) => K kind -> Atomic m Bool+exists (K k _) = A.exists k++-- | Delete every key that starts with some bytes, of whatever kind.+wipe :: (Monad m) => ByteString -> Atomic m ()+wipe = write . Wipe++-- | @GET@.+get :: (Monad m) => K 'Text -> Atomic m (Maybe ByteString)+get (K k _) = A.get k++-- | @SET@.+set :: (Monad m) => K 'Text -> ByteString -> Atomic m ()+set (K k mark) v = mapM_ A.guarding mark >> write (Set k v)++-- | The question that 'get' asks, to name it before it is asked+-- ('prefetch').+asking :: K 'Text -> Query+asking (K k _) = Get k++-- | The number that a key holds, or 0 for a key that is not there.+getNumber :: (Monad m) => K 'Number -> Atomic m Integer+getNumber (K k _) = maybe 0 (maybe 0 id . whole) <$> A.get k++-- | Give a key a number.+setNumber :: (Monad m) => K 'Number -> Integer -> Atomic m ()+setNumber (K k mark) n = mapM_ A.guarding mark >> write (Set k (num n))++-- | @INCRBY@.+incrBy :: (Monad m) => K 'Number -> Integer -> Atomic m ()+incrBy (K k mark) n = mapM_ A.guarding mark >> write (IncrBy k n)++-- | The question that 'getNumber' asks.+askingNumber :: K 'Number -> Query+askingNumber (K k _) = Get k++-- | @HGET@.+hget :: (Monad m) => K 'Hash -> ByteString -> Atomic m (Maybe ByteString)+hget (K k _) = A.hget k++-- | @HEXISTS@.+hexists :: (Monad m) => K 'Hash -> ByteString -> Atomic m Bool+hexists (K k _) = A.hexists k++-- | @HGETALL@.+hgetall :: (Monad m) => K 'Hash -> Atomic m (Map ByteString ByteString)+hgetall (K k _) = A.hgetall k++-- | @HKEYS@.+hkeys :: (Monad m) => K 'Hash -> Atomic m (Set ByteString)+hkeys (K k _) = A.hkeys k++-- | @HSET@.+hset :: (Monad m) => K 'Hash -> ByteString -> ByteString -> Atomic m ()+hset (K k mark) f v = mapM_ A.guarding mark >> write (HSet k f v)++-- | @HDEL@.+hdel :: (Monad m) => K 'Hash -> ByteString -> Atomic m ()+hdel (K k mark) f = mapM_ A.guarding mark >> write (HDel k f)++-- | The question that 'hget' asks.+askingField :: K 'Hash -> ByteString -> Query+askingField (K k _) = HGet k++-- | The question that 'hexists' asks.+askingWhetherField :: K 'Hash -> ByteString -> Query+askingWhetherField (K k _) = HExists k++-- | The number of a field, or nothing for a field that is not there.+hgetNumber :: (Monad m) => K 'Counts -> ByteString -> Atomic m (Maybe Integer)+hgetNumber (K k _) f = (>>= whole) <$> A.hget k f++-- | Give a field a number.+hsetNumber :: (Monad m) => K 'Counts -> ByteString -> Integer -> Atomic m ()+hsetNumber (K k mark) f n = mapM_ A.guarding mark >> write (HSet k f (num n))++-- | @HINCRBY@.+hincrBy :: (Monad m) => K 'Counts -> ByteString -> Integer -> Atomic m ()+hincrBy (K k mark) f n = mapM_ A.guarding mark >> write (HIncrBy k f n)++-- | The fields whose number is above a bound: for a decision that needs+-- to know which leases still run and not when each runs out, so that a+-- lease that is renewed meanwhile changes nothing for it.+hfieldsAbove :: (Monad m) => K 'Counts -> Integer -> Atomic m (Set ByteString)+hfieldsAbove (K k _) = A.habove k++-- | @SISMEMBER@.+sismember :: (Monad m) => K 'Group -> ByteString -> Atomic m Bool+sismember (K k _) = A.sismember k++-- | @SMEMBERS@.+smembers :: (Monad m) => K 'Group -> Atomic m (Set ByteString)+smembers (K k _) = A.smembers k++-- | @SADD@.+sadd :: (Monad m) => K 'Group -> ByteString -> Atomic m ()+sadd (K k mark) x = mapM_ A.guarding mark >> write (SAdd k x)++-- | @SREM@.+srem :: (Monad m) => K 'Group -> ByteString -> Atomic m ()+srem (K k mark) x = mapM_ A.guarding mark >> write (SRem k x)++-- | The question that 'sismember' asks.+askingMember :: K 'Group -> ByteString -> Query+askingMember (K k _) = SIsMember k++-- | The question that 'smembers' asks.+askingMembers :: K 'Group -> Query+askingMembers (K k _) = SMembers k++-- | @ZSCORE@.+zscore :: (Monad m) => K 'Sorted -> ByteString -> Atomic m (Maybe Score)+zscore (K k _) = A.zscore k++-- | @ZCARD@.+zcard :: (Monad m) => K 'Sorted -> Atomic m Integer+zcard (K k _) = A.zcard k++-- | @ZRANGEBYSCORE@, with the scores.+zrangeByScore :: (Monad m) => K 'Sorted -> Bound -> Bound -> Maybe Int -> Atomic m [(ByteString, Score)]+zrangeByScore (K k _) = A.zrangeByScore k++-- | @ZADD@.+zadd :: (Monad m) => K 'Sorted -> Score -> ByteString -> Atomic m ()+zadd (K k mark) s x = mapM_ A.guarding mark >> write (ZAdd k s x)++-- | @ZADD NX@: only if the member is not there.+zaddNew :: (Monad m) => K 'Sorted -> Score -> ByteString -> Atomic m ()+zaddNew (K k mark) s x = mapM_ A.guarding mark >> write (ZAddNX k s x)++-- | @ZREM@.+zrem :: (Monad m) => K 'Sorted -> ByteString -> Atomic m ()+zrem (K k mark) x = mapM_ A.guarding mark >> write (ZRem k x)++-- | @ZREMRANGEBYRANK@.+zremRangeByRank :: (Monad m) => K 'Sorted -> Integer -> Integer -> Atomic m ()+zremRangeByRank (K k mark) from to = mapM_ A.guarding mark >> write (ZRemRangeByRank k from to)++-- | @XADD@ to a stream that keeps about so many entries.+xadd :: (Monad m) => K 'Stream -> Int -> [(ByteString, ByteString)] -> Atomic m ()+xadd (K k mark) keep fields = mapM_ A.guarding mark >> write (XAdd k keep fields)
+ src/Haskoin/Store/Fleet/Atomic/Redis.hs view
@@ -0,0 +1,486 @@+{-# LANGUAGE TemplateHaskell #-}++-- |+-- Module      : Haskoin.Store.Fleet.Atomic.Redis+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- Decisions of "Haskoin.Store.Fleet.Atomic", run against a Redis:+-- 'transact' asks Redis what a decision asks, and gives the script+-- (@lua\/atomic.lua@) what it decided, to carry out if the answers are+-- still true.+--+-- What a decision is compared against is what Redis said, byte for byte,+-- in the script's own words: the script writes each answer as one string,+-- when it is asked and again when it compares, and this module keeps the+-- string and gives it back. So nothing here has to write an answer as the+-- script would, and the two cannot differ on how.+--+-- A decision that asks nothing more than once, and writes nothing, is not+-- given to the script: all that it knows, Redis said in one call, and so+-- at one moment.+--+-- = A decision of any size+--+-- A move of the tip over a full block asks tens of thousands of questions+-- and writes hundreds of thousands of words. Redis takes 1,048,576+-- arguments in a command and closes the connection of one with more, so+-- questions and writes go a thousand to an argument, each argument a+-- list in MessagePack that the script unpacks when it comes to it+-- (@packed@). The writes are sent without those that a later delete+-- undoes ('tidy'), and those to one key that follow each other as one+-- command with all their members (@commands@): what Redis has after them+-- is the same.+module Haskoin.Store.Fleet.Atomic.Redis+  ( transact,+    transactTelling,+    Attempt (..),+    insist,+    Failure (..),+    atomicScript,++    -- * In two steps+    Planned (..),+    plan,+    commit,+    carry,++    -- * How questions, answers and writes are put+    asked,+    command,+    readAnswer,+    Told (..),+    told,+  )+where++import Control.Applicative ((<|>))+import Control.Exception (Exception, evaluate, throwIO)+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.ByteString.Builder qualified as BB+import Data.ByteString.Char8 qualified as C+import Data.ByteString.Lazy qualified as BL+import Data.FileEmbed (embedFile, makeRelativeToProject)+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.Map.Strict qualified as Map+import Data.Set qualified as Set+import Data.Word (Word64)+import Database.Redis (Connection, Redis, Reply, runRedis)+import GHC.Clock (getMonotonicTimeNSec)+import Haskoin.Store.Fleet.Atomic+import Haskoin.Store.Fleet.Script (Script, evalScript, script)+import Numeric (showFFloat)+import Text.Read (readMaybe)++-- | Why a decision was not carried out.+data Failure+  = -- | Redis answered with an error, or with what cannot be read+    Unheard !String+  | -- | the decision asked what cannot be answered: a fault of the decision+    Faulty !Unanswerable+  deriving (Show)++instance Exception Failure++-- | The script that asks and that compares and writes.+atomicScript :: Script+atomicScript = script $(makeRelativeToProject "src/Haskoin/Store/Fleet/lua/atomic.lua" >>= embedFile)+{-# NOINLINE atomicScript #-}++-- | Make a decision and carry it out, as one step: the result of the+-- decision, or 'Nothing' if other stores changed what it asked about+-- every time, as many times as it may be made. Throws a t'Failure' if+-- Redis does not answer or the decision is at fault; nothing was written+-- then.+--+-- The decision is made again from new answers each time: what it decided+-- from answers that are no longer true is dropped whole.+transact :: Connection -> Int -> (forall m. (Monad m) => Atomic m a) -> IO (Maybe a)+transact conn tries = transactTelling conn tries (\_ -> return ())++-- | 'transact', telling of each try what it cost and how it ended, as+-- an t'Attempt'.+--+-- A decision that is refused says nothing of why, and one that is refused+-- time after time has a cause: a move of the tip was refused for hours on+-- a server, and which of its sixty thousand answers had changed had to be+-- guessed. And a decision that is slow says nothing of where its time+-- goes: the same move took ten seconds on that server, of which Redis had+-- less than one.+transactTelling ::+  Connection ->+  Int ->+  (Attempt -> IO ()) ->+  (forall m. (Monad m) => Atomic m a) ->+  IO (Maybe a)+transactTelling conn tries tell decision+  | tries <= 0 = return Nothing+  | otherwise = do+      began <- getMonotonicTimeNSec+      planned <- plan conn decision+      answers <- evaluate (length planned.guards)+      written <- evaluate (length planned.writes)+      decided <- getMonotonicTimeNSec+      outcome <- carry conn planned+      ended <- getMonotonicTimeNSec+      tell+        Attempt+          { passes = planned.rounds,+            answers,+            written,+            planning = decided - began,+            waiting = planned.waited,+            carrying = ended - decided,+            changed = either Just (const Nothing) outcome+          }+      case outcome of+        Right () -> return (Just planned.result)+        Left _ -> transactTelling conn (tries - 1) tell decision++-- | What one try of a decision cost, and how it ended. The times are in+-- nanoseconds, on the clock of the store.+data Attempt = Attempt+  { -- | how many times Redis was asked+    passes :: !Int,+    -- | how many answers the decision depends on+    answers :: !Int,+    -- | how many writes it decided on+    written :: !Int,+    -- | the time to decide, from the first question to the last write+    planning :: !Word64,+    -- | how much of that went by in calls to Redis: sending the+    -- questions, Redis answering, and reading the answers. The rest is+    -- the decision itself, gone through once for each time that Redis+    -- was asked.+    waiting :: !Word64,+    -- | the time to carry it out: putting the answers and the writes as+    -- the script takes them, and the one call+    carrying :: !Word64,+    -- | the first question that had another answer, if it was refused+    changed :: !(Maybe Query)+  }+  deriving (Show)++-- | Carry out a decision that has to be: one that other stores keep+-- changing the ground of is decided again, a hundred times before this+-- gives up with an exception. Nothing was written then.+insist :: Connection -> (forall m. (Monad m) => Atomic m a) -> IO a+insist conn decision =+  transact conn 100 decision+    >>= maybe (throwIO (Unheard "The fleet changed under a decision a hundred times")) return++-- | What a decision decided, from what Redis said: nothing is changed yet.+data Planned a = Planned+  { result :: a,+    -- | the questions that the decision depends on, each with what the+    -- script wrote for its answer+    guards :: ![(Query, ByteString)],+    writes :: ![Op],+    -- | how many times Redis was asked: with one, all that the decision+    -- knows Redis said at one moment+    rounds :: !Int,+    -- | how long the calls to Redis took between them, in nanoseconds+    waited :: !Word64+  }++-- | Make a decision, and change nothing. Throws a t'Failure' if Redis does+-- not answer or the decision is at fault.+plan :: Connection -> (forall m. (Monad m) => Atomic m a) -> IO (Planned a)+plan conn decision = do+  heard <- newIORef Map.empty+  now <- newIORef Nothing+  spent <- newIORef (0 :: Word64)+  -- The clock of a decision is that of Redis when the decision first+  -- asked it anything, whenever the decision first reads the clock+  -- ('clock').+  let timed call = do+        from <- getMonotonicTimeNSec+        got <- call+        to <- getMonotonicTimeNSec+        got <$ modifyIORef' spent (+ (to - from))+      fetch qs = do+        (t, raws) <- timed (reading conn qs)+        modifyIORef' now (<|> Just t)+        modifyIORef' heard (\m -> foldr (uncurry Map.insert) m (zip qs raws))+        either (throwIO . Unheard) return (mapM (uncurry readAnswer) (zip qs raws))+      time =+        readIORef now >>= \case+          Just t -> return t+          Nothing -> do+            t <- fst <$> timed (reading conn [])+            modifyIORef' now (<|> Just t)+            return t+  runAtomic Backend {fetch, time} decision >>= \case+    Stuck why -> throwIO (Faulty why)+    Decided result depends writes rounds -> do+      raws <- readIORef heard+      let guards = [(q, raw) | (q, _) <- depends, Just raw <- [Map.lookup q raws]]+      waited <- readIORef spent+      return Planned {result, guards, writes, rounds, waited}++-- | Carry out what a decision decided, if the answers that it depends on+-- are still true: whether it was carried out. If not, nothing changed.+commit :: Connection -> Planned a -> IO Bool+commit conn planned = either (const False) (const True) <$> carry conn planned++-- | 'commit', saying which question has another answer now if it was not+-- carried out: the first of them.+carry :: Connection -> Planned a -> IO (Either Query ())+carry conn planned+  | null planned.writes && planned.rounds <= 1 = return (Right ())+  | otherwise =+      applying conn planned.guards planned.writes >>= \case+        Nothing -> return (Right ())+        Just n -> case drop (n - 1) planned.guards of+          (q, _) : _ | n >= 1 -> return (Left q)+          _ -> throwIO (Unheard ("The script said that answer " <> show n <> " changed, of " <> counted))+  where+    counted = show (length planned.guards)++-- | Ask the script questions: the clock of Redis and the answers, each as+-- the script writes it.+--+-- The questions go as a few arguments, a thousand to each ('packed'). As+-- an argument each, with their words, the move of the tip over one block+-- of Bitcoin came to 1,008,352 arguments, and Redis closes the connection+-- of a command with more than 1,048,576.+reading :: Connection -> [Query] -> IO (Integer, [ByteString])+reading conn qs =+  run conn (evalScript atomicScript [] ("read" : map packed (pieces 1000 asking))) >>= \case+    t : raws+      | length raws == length qs, Just (ms, rest) <- C.readInteger t, B.null rest -> return (ms, raws)+    other -> throwIO (Unheard ("The script answered " <> show (length other) <> " words to " <> show (length qs)))+  where+    asking = map (several . map word . asked) qs++-- | Give the script the answers that a decision depends on and its writes:+-- nothing if it carried them out, and otherwise the number, from 1, of+-- the first answer that is another now.+--+-- They go a thousand to an argument, the answers first, and the script+-- unpacks one argument at a time: unpacked all at once, the two million+-- words of a large block were more than a Redis of the tests had memory+-- for. The writes are those that are not undone by a later one ('tidy'),+-- as few commands as say them ('commands').+applying :: Connection -> [(Query, ByteString)] -> [Op] -> IO (Maybe Int)+applying conn guards writes =+  run conn (evalScript atomicScript [] args) >>= \case+    ["done"] -> return Nothing+    ["raced", n] | Just (i, rest) <- C.readInt n, B.null rest -> return (Just i)+    other -> throwIO (Unheard ("The script answered " <> show (other :: [ByteString])))+  where+    guarded = pieces 1000 [several (word raw : map word (asked q)) | (q, raw) <- guards]+    written = pieces 1000 (map (several . map word) (commands (tidy writes)))+    args = "apply" : num (length guarded) : map packed (guarded <> written)++-- | So many at a time.+pieces :: Int -> [a] -> [[a]]+pieces _ [] = []+pieces n xs = let (a, b) = splitAt n xs in a : pieces n b++-- | Writes as commands of Redis, as few as say them: the writes to one key+-- that are of one kind and follow each other are one command with all+-- their members, five hundred at most, where Redis has such a command.+--+-- The writes to a key stay in their order. Those to different keys change+-- places, which changes nothing: each is to its own key. A wipe is to many+-- keys, so nothing changes places across one.+commands :: [Op] -> [[ByteString]]+commands = concatMap stretch . splitOn+  where+    -- the writes between two wipes, and each wipe by itself+    splitOn ops = case break wipe ops of+      (before, w : after) -> before : [w] : splitOn after+      (before, []) -> [before]+    wipe = \case+      Wipe _ -> True+      _ -> False+    stretch ops = concatMap merged (Map.elems (byKey ops))+    -- the writes to each key, in their order, the keys in the order in+    -- which they are first written to+    byKey ops =+      let add (order, m) op = case opKey op of+            Right k -> case Map.lookup k order of+              Just n -> (order, Map.adjust (op :) n m)+              Nothing -> let n = Map.size order in (Map.insert k n order, Map.insert n [op] m)+            Left _ -> let n = Map.size order in (Map.insert (C.pack ('!' : show n)) n order, Map.insert n [op] m)+       in Map.map reverse (snd (foldl add (Map.empty, Map.empty :: Map.Map Int [Op]) ops))+    merged [] = []+    merged (op : ops) = case op of+      HSet k f v -> run' (\case HSet _ g x -> Just [g, x]; _ -> Nothing) ["HSET", k] [f, v] ops+      HDel k f -> run' (\case HDel _ g -> Just [g]; _ -> Nothing) ["HDEL", k] [f] ops+      SAdd k x -> run' (\case SAdd _ y -> Just [y]; _ -> Nothing) ["SADD", k] [x] ops+      SRem k x -> run' (\case SRem _ y -> Just [y]; _ -> Nothing) ["SREM", k] [x] ops+      ZRem k x -> run' (\case ZRem _ y -> Just [y]; _ -> Nothing) ["ZREM", k] [x] ops+      ZAdd k sc x -> run' (\case ZAdd _ t y -> Just [scoreText t, y]; _ -> Nothing) ["ZADD", k] [scoreText sc, x] ops+      _ -> command op : merged ops+    -- a command with the members of the writes of its kind that follow+    run' same start first ops =+      let more = takeWhile' same ops+          rest = drop (length more) ops+       in [start <> concat some | some <- pieces 500 (first : more)] <> merged rest+    takeWhile' same = \case+      op : ops | Just x <- same op -> x : takeWhile' same ops+      _ -> []++-- | A list or bytes, to send as one argument.+data Packed = Listed' [Packed] | Bytes'' !ByteString++several :: [Packed] -> Packed+several = Listed'++word :: ByteString -> Packed+word = Bytes''++-- | Lists of lists of bytes as one string, in MessagePack, which the+-- script unpacks with the library that Redis gives its scripts: a list+-- as an array, and bytes as a raw string of the first version of the+-- format, which every version of that library reads.+packed :: [Packed] -> ByteString+packed = BL.toStrict . BB.toLazyByteString . one . Listed'+  where+    one = \case+      Listed' xs -> array (length xs) <> foldMap one xs+      Bytes'' b -> raw (B.length b) <> BB.byteString b+    array n+      | n < 16 = BB.word8 (0x90 + fromIntegral n)+      | n < 65536 = BB.word8 0xdc <> BB.word16BE (fromIntegral n)+      | otherwise = BB.word8 0xdd <> BB.word32BE (fromIntegral n)+    raw n+      | n < 32 = BB.word8 (0xa0 + fromIntegral n)+      | n < 65536 = BB.word8 0xda <> BB.word16BE (fromIntegral n)+      | otherwise = BB.word8 0xdb <> BB.word32BE (fromIntegral n)++run :: Connection -> Redis (Either Reply a) -> IO a+run conn f = runRedis conn f >>= either (throwIO . Unheard . show) return++num :: Int -> ByteString+num = C.pack . show++-- | A question as the script takes it: the shape of its answer, and the+-- words of its command.+asked :: Query -> [ByteString]+asked q = shape : ws+  where+    (shape, ws) = case q of+      Get k -> ("p", ["GET", k])+      HGet k f -> ("p", ["HGET", k, f])+      HExists k f -> ("p", ["HEXISTS", k, f])+      HGetAll k -> ("h", ["HGETALL", k])+      HKeys k -> ("u", ["HKEYS", k])+      HAbove k n -> ("k", [C.pack (show n), "HGETALL", k])+      SIsMember k x -> ("p", ["SISMEMBER", k, x])+      SMembers k -> ("u", ["SMEMBERS", k])+      ZScore k x -> ("p", ["ZSCORE", k, x])+      ZCard k -> ("p", ["ZCARD", k])+      ZRangeByScore k lo hi limit ->+        ( "p",+          ["ZRANGEBYSCORE", k, bound lo, bound hi, "WITHSCORES"]+            <> maybe [] (\n -> ["LIMIT", "0", num n]) limit+        )+      Exists k -> ("p", ["EXISTS", k])+    bound = \case+      MinusInf -> "-inf"+      PlusInf -> "+inf"+      At s -> scoreText s++-- | A write as the script takes it: the words of one command of Redis, or+-- @!WIPE@ and the start of the keys to delete.+command :: Op -> [ByteString]+command = \case+  Set k v -> ["SET", k, v]+  Del k -> ["DEL", k]+  IncrBy k n -> ["INCRBY", k, C.pack (show n)]+  HSet k f v -> ["HSET", k, f, v]+  HDel k f -> ["HDEL", k, f]+  HIncrBy k f n -> ["HINCRBY", k, f, C.pack (show n)]+  SAdd k x -> ["SADD", k, x]+  SRem k x -> ["SREM", k, x]+  ZAdd k s x -> ["ZADD", k, scoreText s, x]+  ZAddNX k s x -> ["ZADD", k, "NX", scoreText s, x]+  ZRem k x -> ["ZREM", k, x]+  ZRemRangeByRank k from to -> ["ZREMRANGEBYRANK", k, C.pack (show from), C.pack (show to)]+  XAdd k keep fields -> ["XADD", k, "MAXLEN", "~", num keep, "*"] <> concat [[f, v] | (f, v) <- fields]+  Wipe p -> ["!WIPE", p]++-- | A score as Redis takes it. The scores of the fleet are whole numbers,+-- written without a fraction or an exponent.+scoreText :: Score -> ByteString+scoreText s+  | s == fromIntegral whole && abs s < 1e17 = C.pack (show whole)+  | otherwise = C.pack (showFFloat Nothing s "")+  where+    whole = round s :: Integer++-- | What the script says: nothing, a number, bytes, or a list.+data Told = None | Number !Integer | Bytes' !ByteString | Listed ![Told]+  deriving (Eq, Show)++-- | Read what the script wrote for an answer, all of it.+told :: ByteString -> Either String Told+told raw = case one raw of+  Right (t, rest) | B.null rest -> Right t+  Right _ -> Left "more than an answer"+  Left e -> Left e+  where+    one s = case C.uncons s of+      Just ('n', rest) -> Right (None, rest)+      Just ('i', rest)+        | Just (n, more) <- C.readInteger rest,+          Just (';', after) <- C.uncons more ->+            Right (Number n, after)+      Just ('s', rest)+        | Just (n, more) <- C.readInt rest,+          Just (':', after) <- C.uncons more,+          B.length after >= n ->+            Right (Bytes' (B.take n after), B.drop n after)+      Just ('a', rest) | Just (n, more) <- C.readInt rest, Just (';', after) <- C.uncons more -> many n after []+      _ -> Left ("an answer that cannot be read: " <> show (B.take 40 s))+    many :: Int -> ByteString -> [Told] -> Either String (Told, ByteString)+    many 0 s acc = Right (Listed (reverse acc), s)+    many n s acc = one s >>= \(t, rest) -> many (n - 1) rest (t : acc)++-- | The answer to a question, from what the script wrote for it.+readAnswer :: Query -> ByteString -> Either String Answer+readAnswer q raw = do+  t <- told raw+  let wrong = Left ("Not an answer to " <> show q <> ": " <> show t)+  case (q, t) of+    (Get _, None) -> Right (Text Nothing)+    (Get _, Bytes' v) -> Right (Text (Just v))+    (HGet _ _, None) -> Right (Text Nothing)+    (HGet _ _, Bytes' v) -> Right (Text (Just v))+    (HExists _ _, Number n) -> Right (Flag (n /= 0))+    (SIsMember _ _, Number n) -> Right (Flag (n /= 0))+    (Exists _, Number n) -> Right (Flag (n /= 0))+    (HGetAll _, Listed ps) -> maybe wrong (Right . Fields . Map.fromList) (mapM pair ps)+    (SMembers _, Listed xs) -> maybe wrong (Right . Members . Set.fromList) (mapM bytes xs)+    (HKeys _, Listed xs) -> maybe wrong (Right . Members . Set.fromList) (mapM bytes xs)+    (HAbove _ _, Listed xs) -> maybe wrong (Right . Members . Set.fromList) (mapM bytes xs)+    (ZScore _ _, None) -> Right (Scored Nothing)+    (ZScore _ _, Bytes' v) -> maybe wrong (Right . Scored . Just) (score v)+    (ZCard _, Number n) -> Right (Count n)+    (ZRangeByScore {}, Listed xs) -> maybe wrong (Right . Ranked) (ranked xs)+    _ -> wrong+  where+    bytes = \case+      Bytes' v -> Just v+      _ -> Nothing+    pair = \case+      Listed [Bytes' f, Bytes' v] -> Just (f, v)+      _ -> Nothing+    ranked = \case+      [] -> Just []+      Bytes' x : Bytes' s : rest -> (:) . (x,) <$> score s <*> ranked rest+      _ -> Nothing+    -- a score as Redis writes it: a whole number, or a number with a+    -- fraction or an exponent, which Haskell reads without the plus sign+    score :: ByteString -> Maybe Score+    score v = case C.unpack v of+      "inf" -> Just (1 / 0)+      "-inf" -> Just (-1 / 0)+      s -> readMaybe (filter (/= '+') s)
src/Haskoin/Store/Fleet/Member.hs view
@@ -30,12 +30,12 @@ --   starts the pool again ('wayBetween'), which every store then fills --   again ('noteRestarts'). ----- * __It offers to the shared pool what its peers send it__ ('memberReceived',---   'offerMempool'), each---   transaction with whether its inputs are unspent in the store's view at---   the fleet tip, so that the pool only takes what is valid there. What---   the pool decided on is seen by the fleet, in Redis, and no store---   fetches it again when a peer announces it ('memberSeen').+-- * __It offers a transaction to the shared pool__ ('memberOffer') when+--   the path into the pool says ("Haskoin.Store.Ingest.Run"), with whether+--   its inputs are unspent in the store's view at the fleet tip, so that+--   the pool only takes what is valid there. What the pool decided on is+--   settled for the fleet, in Redis, and no store fetches it when a peer+--   names it ('memberSettled'). -- -- * __It answers from the view at the fleet tip with the pool on top__ --   ('answering', 'redisPool'), or says that it is behind when it has no@@ -64,6 +64,7 @@     MemberConfig (..),     newMember,     noteBest,+    setHealthy,     memberTick,     memberLoop,     memberAlive,@@ -88,16 +89,17 @@     -- * The parts of a tick     report,     moveTip,+    clearLeaving,     Between (..),     blocksBetween,     wayBetween,     Way (..),     farthest,     changeBetween,-    offerMempool,-    memberReceived,-    memberSeen,-    mostSeen,+    memberSettled,+    memberOffer,+    memberOfferTimed,+    OfferCost (..),     memberPoolBody,     memberNewest,     expirePool,@@ -108,7 +110,8 @@ import Control.Concurrent (threadDelay) import Control.Concurrent.Async (link, withAsync) import Control.Concurrent.STM-  ( TVar,+  ( STM,+    TVar,     atomically,     check,     modifyTVar',@@ -118,22 +121,21 @@     readTVarIO,     registerDelay,     retry,+    stateTVar,     writeTVar,   )-import Control.Exception (Exception, handle, throwIO)-import Control.Monad (filterM, forM, forM_, unless, void, when)+import Control.Exception (Exception, evaluate, handle, throwIO)+import Control.Monad (filterM, forM, forM_, join, unless, void, when) import Data.ByteString (ByteString) import Data.ByteString qualified as B import Data.ByteString.Char8 qualified as C-import Data.Either (rights)+import Data.Either (lefts, rights) import Data.Functor ((<&>)) import Data.HashMap.Strict (HashMap) import Data.HashMap.Strict qualified as HashMap-import Data.HashSet (HashSet)-import Data.HashSet qualified as HashSet import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef) import Data.IntMap.Strict qualified as IntMap-import Data.List (nub, partition, sortOn)+import Data.List (nub) import Data.Map.Strict qualified as Map import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, mapMaybe) import Data.Serialize (Serialize, decode, encode, get, getWord32be, putWord32be, runGet, runPut)@@ -144,11 +146,13 @@ import Data.Word (Word64) import Database.Redis qualified as R import GHC.Clock (getMonotonicTimeNSec)+import GHC.Stats (RTSStats (..), getRTSStats, getRTSStatsEnabled) import Haskoin   ( BlockHash,     BlockHeader (..),     Network (..),     OutPoint (..),+    TokenData (..),     Tx (..),     TxHash,     TxIn (..),@@ -171,16 +175,18 @@     UnixTime,     Unspent (..),     XPubSpec,+    scriptTokens,   ) import Haskoin.Store.Database.Query qualified as Q import Haskoin.Store.Database.Query.Pooled (From, PoolReads (..), pageStart, pooledRead) import Haskoin.Store.Database.Reader (DatabaseReader (..), txCF, withSnapshotReader)-import Haskoin.Store.Database.Types (MemSummary (..), TxKey (..))+import Haskoin.Store.Database.Types (CategorySummary (..), MemSummary (..), PoolTokens (..), TxKey (..)) import Haskoin.Store.Database.Views (Views, heldViews, keepViews, newViews, takeView, withViewAt)-import Haskoin.Store.Exception (handleAny, tryAny)+import Haskoin.Store.Exception (bracket, handleAny, tryAny) import Haskoin.Store.Fleet qualified as F import Haskoin.Store.Fleet.Redis import Haskoin.Store.Fleet.XPub+import Haskoin.Store.Ingest qualified as I import Haskoin.Store.Outage (Outage, attempt, newOutage) import Haskoin.Store.XPub (EntryMoved (..), XPubReads (..)) import Haskoin.Store.XPub.Indexer@@ -195,6 +201,7 @@   ) import Haskoin.Store.XPub.Lock (Lock (..), defaultLockConfig, redisLock) import Haskoin.Store.XPub.Service (Backend (..), Session (..), XPubs (..))+import Haskoin.Transaction.Judge (judgeRelayed) import System.IO (fixIO) import System.Metrics.StatsD   ( StatCounter,@@ -308,22 +315,25 @@     reported :: !(TVar [BlockHash]),     -- | the fleet tip, read after that report     tip :: !(TVar (Maybe BlockHash)),-    -- | the transactions that peers sent and that are still to offer: new,-    -- refused as orphans, or with no time to offer them yet, with the times-    -- at which the store heard of them; they are offered at the next turn.-    -- What the pool has decided on is in the fleet's seen set instead-    -- ('memberSeen'), which Redis keeps for every store.-    waiting :: !(TVar (HashMap TxHash (UnixTime, Tx))),     -- | whether the store's own health checks pass. While they do not, the     -- member does nothing, so that its lease runs out and a store that is     -- stuck does not hold the fleet back.     healthy :: !(TVar Bool),+    -- | whether the store was found unwell since the member's last whole+    -- turn, which it then takes as soon as the store is well ('setHealthy')+    owed :: !(TVar Bool),+    -- | whether the store has a new best block since the last whole turn+    -- ('noteBest')+    newBest :: !(TVar Bool),     -- | the indexer that builds the entries of the xpubs that requests     -- miss, one store of the fleet for each, holding its dibs in Redis     indexer :: !(Indexer XPubSpec ()),     lock :: !(Lock XPubSpec),-    -- | how many builds Redis announced, by xpub, for those that wait-    built :: !(TVar (HashMap ByteString Int)),+    -- | for each xpub that requests wait for, how many builds Redis+    -- announced while they waited and how many wait (@awaitBuilt@). A key+    -- is there only while a request waits for it, so the map holds no more+    -- keys than there are waiting requests+    built :: !(TVar (HashMap ByteString (Int, Int))),     -- | the door to the cache, for the web server     door :: !XPubs,     -- | the metrics of the cache, if the configuration has a StatsD client@@ -339,6 +349,9 @@     -- lost its data or the pool started again: the web server fills the     -- pool again each time ('Haskoin.Store.Web')     refills :: !(TVar Int),+    -- | how many moves of the tip in a row this store tried and did not+    -- make: what it warns of ('moveTip')+    refused :: !(TVar Int),     -- | the last tip that Redis was seen to have, and when, by the clock of     -- 'getMonotonicTimeNSec': a request that read nothing of the pool     -- takes it for the tip for 'seenFor', instead of asking Redis@@ -361,14 +374,16 @@   recent <- newTVarIO []   reported <- newTVarIO []   tip <- newTVarIO Nothing-  waiting <- newTVarIO HashMap.empty   healthy <- newTVarIO True+  owed <- newTVarIO False+  newBest <- newTVarIO False   metrics <- mapM newCacheMetrics config.stats   outage <- newOutage   built <- newTVarIO HashMap.empty   epoch <- newTVarIO Nothing   restarts <- newTVarIO Nothing   refills <- newTVarIO 0+  refused <- newTVarIO 0   seen <- newIORef ("", 0)   lock <- redisLock (defaultLockConfig (config.prefix <> "fleet:") config.name) redis xpubId   fixIO $ \m -> do@@ -391,20 +406,38 @@ -- this right after it imports or reverts a block, and when it starts, -- before it writes anything else: the view is then of that block and of -- nothing more.+--+-- The block joins the recent ones before its view is taken: @prune@ runs on+-- the member's thread too, and one that ran between the two would let go+-- of a view whose block it did not yet count as recent. noteBest :: Member -> BlockHash -> IO () noteBest m block = do-  takeView m.views block   atomically . modifyTVar' m.recent $ \blocks -> take m.config.depth (block : filter (/= block) blocks)+  takeView m.views block   prune m+  -- last, so that the turn that this wakes finds the view+  atomically (writeTVar m.newBest True) +-- | Say whether the store's own health checks pass. A store found unwell+-- owes a whole turn, which its member takes as soon as it is well again+-- ('Haskoin.Store.Fleet.turn'), instead of waiting up to two seconds for+-- its timer.+setHealthy :: Member -> Bool -> STM ()+setHealthy m well = do+  writeTVar m.healthy well+  unless well (writeTVar m.owed True)+ -- | Let go of the views that the rules do not ask for: all but those of--- the recent blocks, of the last report, and of the tip read after it.+-- the recent blocks, of the last report, and of the tip read after it. The+-- three are read in the transaction that lets the views go ('keepViews'),+-- so that the block store's thread and the member's, which both prune,+-- each decide on what is there at that moment. prune :: Member -> IO ()-prune m = do-  recent <- readTVarIO m.recent-  reported <- readTVarIO m.reported-  tip <- readTVarIO m.tip-  keepViews m.views (nub (F.keep (recent <> reported) tip))+prune m = keepViews m.views $ do+  recent <- readTVar m.recent+  reported <- readTVar m.reported+  tip <- readTVar m.tip+  return (nub (F.keep (recent <> reported) tip))  -- | Whether Redis answers a ping within two seconds. memberAlive :: Member -> IO Bool@@ -415,25 +448,30 @@       _ -> False  -- | One round of what a member does: report, move the tip if the stores--- agree on another block, offer what peers sent that it has not offered--- yet, let go of old views, and trim what the fleet has seen--- ('fleetTrimSeen'). Call it every second or two, and when--- the best block changes. A store whose own health checks fail must not+-- agree on another block, and let go of old views. Call it every second+-- or two, and when the best block changes. A store whose own health checks fail must not -- call it: its lease then runs out, and the fleet goes on without it. memberTick :: Member -> IO () memberTick m = do   noteEpoch m   noteRestarts m-  report m-  moved <- moveTip m+  -- only a store whose report was taken, which is live, moves the tip: one+  -- whose report was refused has no view of the tip, and moving from a tip+  -- that it does not know would empty the pool that another store knows+  taken <- report m+  -- what a move left in the pool for after it, if its store stopped+  -- before taking it out: nothing enters the pool until it is out+  when taken (clearLeaving m)+  moved <- if taken then moveTip m else return False+  -- the tip is at the block: what the block took out of the pool was+  -- only marked, and leaves now+  when moved (clearLeaving m)   -- the tip is read after the report, as the rule of 'F.keep' asks   tip <- fmap decoded <$> fleetTip m.redis m.keys   atomically (writeTVar m.tip (fromMaybe Nothing tip))   prune m   cacheGauges m   unless moved (expirePool m)-  offerMempool m-  void (fleetTrimSeen m.redis m.keys mostSeen)   where     decoded = either (const Nothing) Just . decode @@ -442,9 +480,9 @@ -- missing sets. A store that finds it missing or changed forgets its view -- of the fleet tip, so that it is -- unhealthy until a tip is set again, which its next turn does, since--- every live store reports. It counts the loss in 'refills', and the web--- server then asks the peers, and the node over RPC if it has one, for--- their mempools, which fill the pool again through 'memberReceived'.+-- every live store reports. It counts the loss in 'refills': the path+-- into the pool then reads the mempools of its sources again, and the web+-- server that of the node over RPC if it has one. -- Entries of the cache of extended public keys are built again on demand. -- -- Without an epoch, a loss would show only in the count of restarts of@@ -472,9 +510,9 @@  -- | Find out whether the pool was emptied since this store's last turn -- ('fleetRestarts'), and if so count a refill, as 'noteEpoch' does for a--- loss of Redis. The pool forgot with it what the fleet had seen, so what--- the peers announce from then on is fetched again; the refill brings--- back what they announced before. The first turn only notes the count.+-- loss of Redis. The pool is empty then, so what the peers announce from+-- then on is fetched again; the refill brings back what they announced+-- before. The first turn only notes the count. noteRestarts :: Member -> IO () noteRestarts m = do   now <- fleetRestarts m.redis m.keys@@ -487,18 +525,37 @@   when restarted . m.config.note LevelInfo $     "The pool started again: it fills again from the node and the peers" --- | Take a turn as a member every two seconds, and at once when an action--- that waits for the next best block returns, for as long as the store's--- health checks pass. A turn that fails, as when Redis is away, is tried--- again at the next, and logged as an outage is ('attempt').-memberLoop :: Member -> IO () -> IO a-memberLoop m nextBlock = go+-- | Take the member's turns ('memberTick'), for as long as the store runs,+-- when the rule of 'Haskoin.Store.Fleet.turn' says: every two seconds, at+-- each new best block and when the store is well again, only while the+-- store's health checks pass. A turn that fails, as when Redis is away, is+-- tried again at the next, and logged as an outage is ('attempt').+--+-- The member waits in one transaction for what wakes it, and clears in+-- the same transaction what the turn will see to: a block or a health+-- that comes during the turn wakes it again after it, and none is lost+-- between the read and the clearing. Before, the member waited for a+-- block with a timer around it, and read the health after: a store that+-- the block made well took no turn for up to two seconds.+--+-- Transactions are not offered here: "Haskoin.Store.Ingest.Run" offers+-- each as it comes ('memberOffer').+memberLoop :: Member -> IO a+memberLoop m = registerDelay 2000000 >>= go   where-    go = do-      void (timeout 2000000 nextBlock)-      well <- readTVarIO m.healthy-      when well (void (attempt m.outage m.config.note "take a turn in the fleet" (memberTick m)))-      go+    go timer = do+      atomically $ do+        wake <-+          F.Wake+            <$> readTVar m.healthy+            <*> readTVar m.owed+            <*> readTVar m.newBest+            <*> readTVar timer+        unless (F.turn wake) retry+        writeTVar m.owed False+        writeTVar m.newBest False+      void (attempt m.outage m.config.note "take a turn in the fleet" (memberTick m))+      registerDelay 2000000 >>= go  -- | Hear what happens to the fleet, for as long as the store runs: each -- move of the tip and each transaction that enters or leaves the pool is@@ -529,7 +586,7 @@  -- | Report the blocks of the main chain that the store has views of, newest -- first.-report :: Member -> IO ()+report :: Member -> IO Bool report m = do   held <- heldViews m.views   recent <- readTVarIO m.recent@@ -538,6 +595,7 @@   atomically (writeTVar m.reported (if taken then blocks else []))   unless taken . m.config.note LevelDebug $     "Report not taken: this store has no view of the fleet tip, and another store is live"+  return taken   where     main h = maybe False (.main) <$> Q.getBlock m.db h @@ -550,7 +608,20 @@ -- undone address by address, is written in pieces ('tipMoves', -- 'cachePieces'); then 'fleetCommit' moves the pool, the tip and the cache -- together. A move that is refused is aborted, and the entries that it--- wrote are dropped ('cacheAbort'). When this store cannot say what the+-- wrote are dropped ('cacheAbort').+--+-- From the beginning of a move to its end the store says every two+-- seconds that it is at it ('cacheBeat'), which keeps the floor: whatever+-- else writes to the pool or to the cache gives way meanwhile+-- ('Haskoin.Store.Fleet.Pool.Decide.floorHeld'). The move of a full block+-- takes seconds to decide, and more than ten on a slow machine. When the+-- floor lasted ten seconds from the last piece, such a move lost it before+-- it was carried out, and the tip of a server stayed where it was while+-- its database went on. A move that is not over in ten minutes has gone+-- wrong: the store stops saying so then, and the floor is free ten+-- seconds later, as it is ten seconds after a store that stopped.+--+-- When this store cannot say what the -- blocks did, the pool is emptied, and the cache with it: Redis allows that -- to a store that is alone, and to any store when the way is too long for -- all of them (v'TooFar').@@ -582,19 +653,30 @@           m.config.note LevelDebug "Fleet tip not moved: another store is moving it"           return False         BeginRaced -> return False-        Begun -> moveWith seen token target+        Begun -> withAsync (beats token (300 :: Int)) (\_ -> moveWith seen token target)     agreed -> do       when (isNothing agreed) . m.config.note LevelDebug $         "The live stores have no block in common: " <> shown (Map.size reports) <> " reports"       return False   where+    -- the store says that it is at its move, so many times at most, and+    -- stops when the move is no longer its own+    beats token n = when (n > 0) $ do+      threadDelay 2000000+      still <- cacheBeat m.redis m.keys token+      when still (beats token (n - 1))     -- the move under a token of the cache: what the blocks did at the     -- addresses of the entries is written in pieces, and the commit moves     -- the pool, the tip and the cache together     moveWith seen token target = do+      began <- getMonotonicTimeNSec+      collected <- collector+      tried <- newIORef []+      cacheAt <- newIORef Nothing       way <- case (traverse decode seen, decode target) of         (Right from, Right to) -> wayBetween m.views m.db from to         _ -> return NoWay+      found <- getMonotonicTimeNSec       let between = case way of             Way b -> Just b             _ -> Nothing@@ -604,12 +686,17 @@       written <- case (way, decode target) of         (Way b, Right to) ->           withViewAt m.views to (\r -> tipMoves m.redis m.keys r b.abandoned b.added) >>= \case-            Just moves -> cachePieces m.redis m.keys token (fromMaybe "" seen) moves+            Just moves -> do+              getMonotonicTimeNSec >>= writeIORef cacheAt . Just+              cachePieces m.redis m.keys token (fromMaybe "" seen) moves             Nothing -> return False         (Way _, _) -> return False         -- the store's chain moved since its report: not this turn         (Unsettled, _) -> return False+        -- what the abandoned blocks held cannot be read: not this turn+        (Unreadable, _) -> return False         _ -> return True+      pieced <- getMonotonicTimeNSec       moved <-         if not written           then return Raced@@ -622,7 +709,75 @@                   <> blockName target                   <> ": starting the shared mempool again there"               fleetRestart m.redis m.keys 32 Nothing seen target-            _ -> fleetCommit m.redis m.keys 32 Nothing seen target ((.pool) <$> between) path token+            _ ->+              fleetCommitTelling+                (\a -> modifyIORef' tried (a :))+                m.redis+                m.keys+                32+                Nothing+                m.config.name+                seen+                target+                ((.pool) <$> between)+                path+                token+      ended <- getMonotonicTimeNSec+      attempts <- reverse <$> readIORef tried+      collecting <- collector+      readAt <- fromMaybe pieced <$> readIORef cacheAt+      let ms a b = shown ((b - a) `div` 1000000)+          millis n = shown (n `div` 1000000)+          took = ms began ended <> " ms"+          -- what Redis answered otherwise when the move was to be carried+          -- out, if it was decided and then refused+          refusal = case mapMaybe (.changed) attempts of+            [] -> ""+            qs -> ", refused for the answer to " <> T.pack (show (last qs))+          -- Where the time went. Transactions wait for as long as a move+          -- takes, and what would shorten it depends on which part is+          -- long: reading the blocks from the database, the cache, the+          -- decision, which is gone through once for each time that Redis+          -- is asked, or Redis.+          parts =+            T.intercalate ", " $+              [ "over " <> shown (maybe 0 (length . (.pool.confirmed)) between) <> " transactions",+                "the blocks read in " <> ms began found <> " ms",+                "the cache read in " <> ms found readAt <> " and written in " <> ms readAt pieced <> " ms"+              ]+                <> [ mconcat+                       [ "decided in ",+                         millis a.planning,+                         " ms, ",+                         millis a.waiting,+                         " of them in ",+                         shown a.passes,+                         " calls to Redis, with ",+                         shown a.answers,+                         " answers and ",+                         shown a.written,+                         " writes, and ",+                         maybe "carried out" (const "refused") a.changed,+                         " in ",+                         millis a.carrying,+                         " ms"+                       ]+                   | a <- attempts+                   ]+                -- every thread waits while the collector runs, this one+                -- too: a store with a large heap may spend most of a move+                -- there, whatever the move does+                <> [ mconcat+                       [ "the collector ran for ",+                         shown ((after.gc_elapsed_ns - before.gc_elapsed_ns) `div` 1000000),+                         " ms meanwhile, in ",+                         shown (after.gcs - before.gcs),+                         " collections, ",+                         shown (after.major_gcs - before.major_gcs),+                         " of the whole heap"+                       ]+                   | (Just before, Just after) <- [(collected, collecting)]+                   ]       m.config.note LevelDebug . mconcat $         [ "Fleet tip from ",           maybe "none" blockName seen,@@ -631,11 +786,19 @@           case moved of             MovedTo _ -> ": moved"             Stays -> ": stays"-            Raced -> ": not moved, another store did it first or has to",+            Raced -> ": not moved, another store did it first or has to"+            Leaving -> ": not moved, the pool has not let go of the last blocks yet",+          " in ",+          took,+          " (",+          parts,+          ")",+          refusal,           case way of             Way _ -> ""             NoWay -> " (this store does not know the way)"             Unsettled -> " (the chain of this store moved since its report)"+            Unreadable -> " (this store cannot read what the abandoned blocks held)"             TooFar -> " (the way is too long)"         ]       case moved of@@ -644,14 +807,83 @@                 Way _ -> False                 _ -> True           when restarted $ wasEmptied m target "the shared mempool started again"+          -- transactions wait for as long as a move takes, so one that+          -- they notice is said, with where its time went. It was said+          -- from five seconds: the move over a full block then came+          -- under that, and nothing said what the two seconds or so+          -- that were left of it were made of+          when (ended - began >= 1000000000) . m.config.note LevelInfo $+            "The fleet tip moved to " <> blockName target <> " in " <> took <> ": " <> parts+          atomically (writeTVar m.refused 0)           return True-        _ -> False <$ cacheAbort m.redis m.keys token+        _ -> do+          -- A move that is refused once is nothing: another store made+          -- it, or the store was not ready. Refused turn after turn, the+          -- store answers from an old block while its database goes on,+          -- and its health, which looks at the database, says that all+          -- is well. That happened, in silence, so it is said.+          n <- atomically (stateTVar m.refused (\x -> (x + 1, x + 1)))+          when (n == 5 || n `mod` 150 == 0) . m.config.note LevelWarn . mconcat $+            [ "The fleet tip has not moved in ",+              shown n,+              " turns of this store, from ",+              maybe "none" blockName seen,+              " to ",+              blockName target,+              ": the store answers from the block that it is at. The last took ",+              took,+              " (",+              parts,+              ")",+              refusal+            ]+          False <$ cacheAbort m.redis m.keys token+    -- what the collector has done so far, if the store keeps count+    -- (@+RTS -T@)+    collector =+      getRTSStatsEnabled >>= \case+        True -> Just <$> getRTSStats+        False -> return Nothing     redis' :: R.Redis (Either R.Reply a) -> IO a     redis' f = R.runRedis m.redis f >>= either (fail . ("Redis error: " <>) . show) return     chunks bytes       | B.null bytes = []       | otherwise = B.take 32 bytes : chunks (B.drop 32 bytes) +-- | Take out of the shared mempool what the moves of the tip marked as+-- leaving, two hundred transactions to a decision, until none is left.+--+-- A move over a block marks what the block confirmed or replaced, and the+-- tip is at the block at once ('Haskoin.Store.Fleet.Pool.Decide.takeOut').+-- The store that moved it takes them out, and so does any store at its+-- next turn, for a store that stops in between: no transaction enters+-- the pool while one is marked. Two stores at it take nothing out twice.+-- It says how long it took when that is a second or more, since+-- transactions wait meanwhile.+clearLeaving :: Member -> IO ()+clearLeaving m = do+  began <- getMonotonicTimeNSec+  taken <- go (0 :: Int)+  ended <- getMonotonicTimeNSec+  when (ended - began >= 1000000000) . m.config.note LevelInfo . mconcat $+    [ "Took ",+      shown taken,+      " transactions that the blocks confirmed or replaced out of the shared mempool in ",+      shown ((ended - began) `div` 1000000),+      " ms"+    ]+  where+    go n = do+      marked <- poolLeaving m.redis m.keys+      if null marked+        then return n+        else do+          counts <- mapM (poolTakeOut m.redis m.keys 32) (pieces marked)+          go (n + sum counts)+    pieces xs = case splitAt 200 xs of+      (a, []) -> [a]+      (a, rest) -> a : pieces rest+ -- | The most blocks that 'changeBetween' goes through on either side of a -- fork. Beyond that, a store that is alone starts the pool again, which -- costs the stores an offer of their mempools; going through a thousand@@ -703,9 +935,17 @@ data Way   = -- | what the blocks between them did     Way !Between-  | -- | nothing: it does not have the first tip, or no view of the-    -- database at it. Another store may know.+  | -- | nothing: it does not have the first tip, or the blocks between+    -- do not connect in its database. Another store may know; a store that+    -- is the one live store empties the pool.     NoWay+  | -- | not now: it has the first tip, and a reorganisation abandoned+    -- blocks whose transactions it cannot read, having no view of the+    -- database at that tip. The tip waits: another store may read them,+    -- and once the way is longer than 'farthest' it is v'TooFar' for every+    -- store. Taken for v'NoWay' once, it emptied the pool of a store that+    -- was alone, where the documentation said that it waits.+    Unreadable   | -- | not yet: the second tip is not on its main chain as the database     -- has it now. The store reported the tip, and its chain has moved     -- since, as when it reverts blocks in a reorganisation; its next report@@ -724,8 +964,8 @@ -- longer in the database: reverting a block takes them out -- ("Haskoin.Store.Logic"). They are read from the store's view of the -- database at the first tip, which it keeps ('noteBest'). Without that--- view the store cannot say what they held, and the way is v'NoWay': it--- does not move the tip, which keeps the cache of extended public keys+-- view the store cannot say what they held, and the way is v'Unreadable':+-- it does not move the tip, which keeps the cache of extended public keys -- whole, since a reorganisation never empties it. Another store may know. wayBetween :: Views BlockHash -> DatabaseReader -> Maybe BlockHash -> BlockHash -> IO Way wayBetween views db from to = withSnapshotReader db $ \r -> do@@ -759,7 +999,8 @@       | bd.main ->           down 0 fork bd >>= \case             Left none -> return none-            Right added -> maybe (return NoWay) (wayWith r bd abandoned added) =<< abandonedBodies (reverse abandoned)+            Right added ->+              maybe (return Unreadable) (wayWith r bd abandoned added) =<< abandonedBodies (reverse abandoned)     -- the store reported the second tip, and has moved on since     _ -> return Unsettled   where@@ -818,7 +1059,6 @@       time,       inputs = [encode op | op <- spent],       body = encode (td :: TxData) {block = MemRef time, deleted = False, spenders = IntMap.empty},-      signals = net.replaceByFee && any ((< 0xffffffff - 1) . (.sequence)) td.tx.inputs,       entries =         [PoolTouches (encode a) | a <- touched]           <> [ PoolSpends (encode a) (encode i.outpoint) p.value@@ -831,6 +1071,17 @@              | (i, o) <- zip [0 ..] td.tx.outputs,                Just a <- [address o.script]              ]+          -- the outputs that hold tokens, made and used up (CashTokens)+          <> [ PoolMakes (tokenOut (OutPoint h i) o.script t) {coins = Just (o.value, o.script)}+             | (i, o) <- zip [0 ..] td.tx.outputs,+               Just t <- [scriptTokens net o.script]+             ]+          <> [ PoolUses (tokenOut i.outpoint p.script t)+             | (k, i) <- zip [0 :: Int ..] td.tx.inputs,+               i.outpoint /= nullOutPoint,+               Just p <- [IntMap.lookup k td.prevs],+               Just t <- [scriptTokens net p.script]+             ]     }   where     h = txHash td.tx@@ -842,172 +1093,254 @@       BlockRef {} -> max 1 td.timestamp     spent = [i.outpoint | i <- td.tx.inputs, i.outpoint /= nullOutPoint]     address = eitherToMaybe . scriptToAddressBS net+    tokenOut op s t =+      PoolTokenOut+        { address = encode <$> address s,+          output = encode op,+          category = encode t.category,+          amount = t.amount,+          nft = isJust t.nft,+          coins = Nothing+        }     touched =       nub $         mapMaybe (address . (.script)) (IntMap.elems td.prevs)           <> mapMaybe (address . (.script)) td.tx.outputs --- | Offer to the pool the transactions that peers sent this store and that--- it has not offered yet ('memberReceived'), oldest first, so that each--- comes after those that it spends from. A store without a view of the--- fleet tip offers nothing: it cannot say what is unspent there.+-- | Of these transactions, which are settled: the pool has them+-- ('fleetSettled'). 'Nothing' if Redis does not answer in five seconds. ----- A transaction whose inputs neither the tip nor the pool has, an orphan--- for now, waits for the next round, as does everything after an offer--- that the pool turned away because the tip had moved. An orphan is let go--- 'orphanLife' after the store heard of it: its parent is not coming. One that conflicts--- with transactions of the pool takes their place: a peer relayed it, so--- its node took it in place of them.+-- It is what "Haskoin.Store.Ingest" asks before it gives a place to what a+-- peer names ('Haskoin.Store.Ingest.Check'): a node names its whole+-- mempool when asked, and nearly all of it is in the pool already. The+-- ids go to Redis a thousand at a time, so that no call is long enough to+-- hold up the others. ----- A round offers 'mostOffers' transactions at most and leaves the rest--- waiting, so that a store with many to offer still reports in time to--- keep its lease.-offerMempool :: Member -> IO ()-offerMempool m =-  readTVarIO m.tip >>= \case-    Nothing -> return ()-    Just tip -> void . withViewAt m.views tip $ \at -> do-      now <- round <$> getPOSIXTime-      held <- readTVarIO m.waiting-      let todo = take mostOffers (sortOn (fst . snd) (HashMap.toList held))-          pool = redisPool m.redis m.keys (encode tip) (return ())-      go now at pool tip todo+-- A block of the store may confirm a transaction that the pool never had.+-- That is not looked up here, one read of the database for each of tens+-- of thousands of ids: 'memberOffer' finds it for the few that are+-- fetched.+memberSettled :: Member -> [TxHash] -> IO (Maybe [Bool])+memberSettled _ [] = return (Just [])+memberSettled m hs =+  handleAny (\_ -> return Nothing) . timeout 5000000 $+    concat <$> mapM (fleetSettled m.redis m.keys . map encode) (thousands hs)   where-    go _ _ _ _ [] = return ()-    go now at pool tip ((h, (time, tx)) : rest) =-      txDataAt at pool time tx >>= \case-        -- an input that neither the tip nor the pool has: an orphan for now-        Nothing -> orphan now h time >> go now at pool tip rest-        Just td -> do-          unspent <- forM [i.outpoint | i <- tx.inputs, i.outpoint /= nullOutPoint] $ \p ->-            isJust <$> Q.getUnspent at p-          let offer = poolOffer m.redis m.keys 32 (Just (encode tip)) (poolTx m.db.net td) unspent-              done = atomically (modifyTVar' m.waiting (HashMap.delete h))-          offer [] >>= \case-            Taken -> done >> go now at pool tip rest-            Known -> done >> go now at pool tip rest-            Orphan _ -> orphan now h time >> go now at pool tip rest-            Late -> return ()-            -- a peer relayed it, so its node took it in place of what it-            -- conflicts with: it replaces them in the pool too-            Conflict rivals -> offer rivals >> done >> go now at pool tip rest-    orphan now h time =-      when (now > time + orphanLife) $-        atomically (modifyTVar' m.waiting (HashMap.delete h))+    thousands [] = []+    thousands xs = let (a, b) = splitAt 1000 xs in a : thousands b --- | A transaction that the store heard from a peer, to offer to the pool at--- the next turn, with the time at which it was heard. There is no mempool--- of the store's own: the pool in Redis is the mempool.-memberReceived :: Member -> UnixTime -> Tx -> IO ()-memberReceived m time tx =-  atomically $ modifyTVar' m.waiting (HashMap.insertWith (\_ old -> old) (txHash tx) (time, tx))+-- | Offer a transaction to the pool, with the time at which the store has+-- it, and say what became of it, as "Haskoin.Store.Ingest" needs to know+-- ('Haskoin.Store.Ingest.Offer'):+--+-- * 'Haskoin.Store.Ingest.Settled': the pool took it or had it, or a block of the store's view+--   at the fleet tip confirms it;+--+-- * 'Haskoin.Store.Ingest.Orphan' with the transactions that it spends from and that neither+--   the tip nor the pool has;+--+-- * 'Haskoin.Store.Ingest.Again': there is no answer now. The store has no view of the fleet+--   tip, the tip moved between the reading and the offer, or the+--   transaction conflicts with the pool twice in a row.+--+-- The store says of each output that the transaction spends whether it is+-- unspent in its view at the fleet tip, so that the pool only takes what+-- is valid there. A transaction that conflicts with transactions of the+-- pool takes their place: a peer relayed it, so its node took it in place+-- of them.+--+-- One transaction to a call, and no list of those that wait: which to+-- offer and when is for the machine to say. The member held them once and+-- offered them oldest first by the second, so that a chain that a node+-- took in one second was offered child first and took as many rounds as+-- it had transactions.+memberOffer :: Member -> UnixTime -> Tx -> IO (I.Verdict TxHash)+memberOffer m time tx = fst <$> memberOfferTimed m True time tx --- | Of these transactions, those that the block store need not fetch when--- a peer announces them: those that this store holds to offer, and those--- that the fleet has seen ('fleetTrimSeen'), asked of Redis in one round--- trip. The fleet sees a transaction only once the pool has decided on it,--- so what this store received and has not offered yet is known here alone.--- Without an answer from Redis within a second, only what the store holds;--- the store then fetches the rest, and finds out at the offer what the pool--- has.-memberSeen :: Member -> [TxHash] -> IO (HashSet TxHash)-memberSeen m hs = do-  held <- readTVarIO m.waiting-  let (mine, others) = partition (`HashMap.member` held) hs-  fleet <--    if null others-      then return HashSet.empty-      else-        handleAny (\_ -> return HashSet.empty) $-          timeout 1000000 (fleetSeen m.redis m.keys (map encode others)) <&> \case-            Just flags -> HashSet.fromList [h | (h, True) <- zip others flags]-            Nothing -> HashSet.empty-  return (HashSet.union (HashSet.fromList mine) fleet)+-- | Where the time of offers went, in nanoseconds: what the path into the+-- pool says in its log when it is busy+-- ("Haskoin.Store.Ingest.Run"). An offer reads the database and the pool+-- before the pool decides, and which of them a slow offer waits for+-- cannot be told from outside.+data OfferCost = OfferCost+  { -- | asking the database whether a block has the transaction+    askedBlock :: !Word64,+    -- | reading from the database the outputs that it spends+    readDb :: !Word64,+    -- | reading from the pool those that the database has not+    readPool :: !Word64,+    -- | asking the database which of them are unspent+    readUnspent :: !Word64,+    -- | the decision of the pool+    decided :: !Word64,+    -- | looking at a transaction that no node of the operator vouches+    -- for: its signatures, mostly+    judged :: !Word64+  }+  deriving (Eq, Show) --- | How many transactions the fleet remembers having seen, the newest--- ('fleetTrimSeen'), trimmed at each turn of a member. A peer announces a transaction within seconds of having--- it, so a hundred thousand covers far more than the time in which the--- peers of the fleet announce one, at any rate that Bitcoin carries.-mostSeen :: Int-mostSeen = 100000+instance Semigroup OfferCost where+  OfferCost a b c d e f <> OfferCost a' b' c' d' e' f' =+    OfferCost (a + a') (b + b') (c + c') (d + d') (e + e') (f + f') +instance Monoid OfferCost where+  mempty = OfferCost 0 0 0 0 0 0++-- | 'memberOffer', with where its time went, of a transaction that a node+-- of the operator vouches for or not+-- ('Haskoin.Store.Ingest.vouchedFor').+--+-- A transaction that is vouched for is offered as it is: a node of the+-- operator took it, and the store takes what its node takes. One that+-- only strangers named is looked at first+-- ('Haskoin.Transaction.Judge.judgeRelayed'), once the outputs that it+-- spends are all there:+--+-- * 'Haskoin.Store.Ingest.Forged', if no node could have taken it: a+--   signature of a coin locked to one key does not verify, it spends more+--   than it has, or its tokens come from nowhere. A stranger could+--   otherwise show a wallet a payment that is not there, or a spend of+--   its coins.+--+-- * 'Haskoin.Store.Ingest.Unverified', if it spends a coin locked by a+--   script: only a full node can say whether it is good, and the store+--   runs no scripts. It is not offered on the word of a stranger.+--+-- Unless the pool has it already: another store of the fleet, whose node+-- vouched for it, was first.+--+-- A coinbase that is not in the chain of the store is+-- 'Haskoin.Store.Ingest.Forged' whoever named it. Only a block has a+-- coinbase, and no mempool. A node of the operator names one all the same:+-- when a block stops being part of its chain it publishes the ids of the+-- transactions of that block over ZeroMQ, the coinbase too, and it gives+-- the coinbase when asked, since it keeps the block. A store took it on+-- the word of its node, and showed an unconfirmed transaction that could+-- never confirm.+memberOfferTimed :: Member -> Bool -> UnixTime -> Tx -> IO (I.Verdict TxHash, OfferCost)+memberOfferTimed m vouched time tx = do+  cost <- newIORef mempty+  let timed :: (Word64 -> OfferCost) -> IO a -> IO a+      timed part act = do+        t0 <- getMonotonicTimeNSec+        r <- act+        t1 <- getMonotonicTimeNSec+        modifyIORef' cost (<> part (t1 - t0))+        return r+  verdict <- memberOffer' timed m vouched time tx+  (,) verdict <$> readIORef cost++-- | The offer itself, given what times each of its parts.+memberOffer' ::+  (forall a. (Word64 -> OfferCost) -> IO a -> IO a) ->+  Member ->+  Bool ->+  UnixTime ->+  Tx ->+  IO (I.Verdict TxHash)+memberOffer' timed m vouched time tx =+  readTVarIO m.tip >>= \case+    Nothing -> return I.Again+    Just tip -> fmap (fromMaybe I.Again) . withViewAt m.views tip $ \at ->+      timed (\d -> mempty {askedBlock = d}) (Q.getTxData at h) >>= \case+        Just td | not td.deleted -> return I.Settled+        -- only a block has a coinbase: no mempool does, whoever named it+        _ | any ((== nullOutPoint) . (.outpoint)) tx.inputs -> return I.Forged+        _ -> do+          let pool = redisPool m.db.net m.redis m.keys (encode tip) (return ())+          found <- forM (zip [0 :: Int ..] tx.inputs) (spent at pool)+          case lefts found of+            [] -> do+              doubt <-+                if vouched+                  then return Nothing+                  else timed (\d -> mempty {judged = d}) (evaluate (stranger (rights found)))+              case doubt of+                -- what the pool has is not doubted: a node of the operator+                -- of another store of the fleet vouched for it+                Just verdict -> do+                  has <- memberSettled m [h]+                  return (if has == Just [True] then I.Settled else verdict)+                Nothing -> do+                  unspent <- timed (\d -> mempty {readUnspent = d}) $+                    forM [i.outpoint | i <- tx.inputs, i.outpoint /= nullOutPoint] $ \p ->+                      isJust <$> Q.getUnspent at p+                  let td =+                        TxData+                          { block = MemRef time,+                            tx,+                            prevs = IntMap.fromList (catMaybes (rights found)),+                            deleted = False,+                            rbf = False,+                            timestamp = time,+                            spenders = IntMap.empty+                          }+                      offer = poolOffer m.redis m.keys 32 (Just (encode tip)) (poolTx m.db.net td) unspent+                      answered second = \case+                        Taken -> return I.Settled+                        Known -> return I.Settled+                        Orphan outs -> return (I.Orphan (nub [(op :: OutPoint).hash | Right op <- map decode outs]))+                        Late -> return I.Again+                        Conflict rivals+                          | not second -> offer rivals >>= answered True+                          | otherwise -> return I.Again+                  timed (\d -> mempty {decided = d}) (offer [] >>= answered False)+            missing -> return (I.Orphan (nub missing))+  where+    h = txHash tx+    -- what is wrong with a transaction that only strangers named, given+    -- the outputs that it spends, if anything is+    stranger prevs = case judgeRelayed m.db.net tx [TxOut value script | Just (_, Prev script value) <- prevs] of+      Left _ -> Just I.Forged+      Right (Just _) -> Just I.Unverified+      Right Nothing -> Nothing+    -- the output that an input spends, from the view at the tip or from+    -- the pool, or the transaction that should have it+    spent at pool (n, i)+      | i.outpoint == nullOutPoint = return (Right Nothing)+      | otherwise =+          timed (\d -> mempty {readDb = d}) (Q.getUnspent at i.outpoint) >>= \case+            Just u -> return (Right (Just (n, Prev u.script u.value)))+            Nothing ->+              timed (\d -> mempty {readPool = d}) (pool.bodies [i.outpoint.hash]) >>= \case+                [(Just parent, _)]+                  | fromIntegral i.outpoint.index < length parent.tx.outputs ->+                      let o = parent.tx.outputs !! fromIntegral i.outpoint.index+                       in return (Right (Just (n, Prev o.script o.value)))+                _ -> return (Left i.outpoint.hash)+ -- | The body of a transaction of the pool, for the filters of @/events@. memberPoolBody :: Member -> TxHash -> IO (Maybe TxData) memberPoolBody m h =   readTVarIO m.tip >>= \case     Nothing -> return Nothing     Just tip ->-      (redisPool m.redis m.keys (encode tip) (return ())).bodies [h] <&> \case+      (redisPool m.db.net m.redis m.keys (encode tip) (return ())).bodies [h] <&> \case         [(td, _)] -> td         _ -> Nothing  -- | The time at which the newest transaction of the pool entered it, if the -- pool has any and the member can read it at the tip that it knows: what--- tells the health check that transactions still come in.+-- tells the health check that transactions still come in. 'Nothing' too if+-- Redis does not answer within two seconds: the health check, which asks+-- this, must not hang with a connection that does. memberNewest :: Member -> IO (Maybe UnixTime) memberNewest m =   readTVarIO m.tip >>= \case     Nothing -> return Nothing     Just tip ->-      handleAny (\_ -> return Nothing) $-        (redisPool m.redis m.keys (encode tip) (return ())).page 0 1 <&> \case+      handleAny (\_ -> return Nothing) . fmap join . timeout 2000000 $+        (redisPool m.db.net m.redis m.keys (encode tip) (return ())).page 0 1 <&> \case           (t, _) : _ -> Just t           [] -> Nothing --- | A transaction with the outputs that it spends, from the view at the tip--- or from the pool; 'Nothing' if one of them is in neither.-txDataAt :: DatabaseReader -> PoolReads -> UnixTime -> Tx -> IO (Maybe TxData)-txDataAt at pool time tx = do-  prevs <- forM (zip [0 :: Int ..] tx.inputs) $ \(n, i) ->-    if i.outpoint == nullOutPoint-      then return (Just Nothing)-      else-        Q.getUnspent at i.outpoint >>= \case-          Just u -> return (Just (Just (n, Prev u.script u.value)))-          Nothing ->-            pool.bodies [i.outpoint.hash] >>= \case-              [(Just parent, _)]-                | fromIntegral i.outpoint.index < length parent.tx.outputs ->-                    let o = parent.tx.outputs !! fromIntegral i.outpoint.index-                     in return (Just (Just (n, Prev o.script o.value)))-              _ -> return Nothing-  return $ do-    ps <- sequence prevs-    return-      TxData-        { block = MemRef time,-          tx,-          prevs = IntMap.fromList (catMaybes ps),-          deleted = False,-          rbf = False,-          timestamp = time,-          spenders = IntMap.empty-        }---- | How long, in seconds, a transaction waits for its parent before it is--- let go: twenty minutes, as Bitcoin Core keeps its orphans. A parent comes--- within seconds when it comes at all, in a block or from a peer; one that--- has not come by then was replaced or never reached the network. Kept for--- ever, such orphans would pile up, and once they were 'mostOffers', the--- oldest first, a round would offer nothing else.-orphanLife :: UnixTime-orphanLife = 1200---- | The most transactions that one round offers. An offer takes a tenth of--- a millisecond or two, so this is well under the two seconds of a round.-mostOffers :: Int-mostOffers = 2000- -- | Take out of the pool the transactions that entered a mempool longer -- ago than the configuration allows, with what spends them. expirePool :: Member -> IO () expirePool m = when (m.config.expiry > 0) $ do   (now, _) <- R.runRedis m.redis R.time >>= either (fail . show) return-  let before = fromIntegral now - fromIntegral m.config.expiry :: Double-  old <--    R.runRedis m.redis (R.zrangebyscoreLimit (m.keys.prefix <> "pool:time") 0 before 0 1000)-      >>= either (fail . show) return-  unless (null old) (void (poolWithdraw m.redis m.keys 32 old))+  -- chosen and withdrawn in one call ('poolExpire')+  void (poolExpire m.redis m.keys 32 (fromIntegral now - fromIntegral m.config.expiry) 1000)  -- | Where a store stands when a request comes. data Standing a@@ -1027,6 +1360,14 @@  instance Exception TipMoved +-- | What a build that did not put its entry in the cache throws, with why:+-- the job of the indexer fails, and the requests that wait for it are told+-- so ('buildFor').+newtype NotBuilt = NotBuilt String+  deriving (Show)++instance Exception NotBuilt+ -- | Answer a request as a member of a fleet: read the fleet tip, and run -- an action with the database as it was at that block and the pool as it is -- at that tip. The action must do all its reading before it returns.@@ -1077,7 +1418,7 @@                   now <- memberTip m                   if now == Just tip then saw >> writeIORef checked True else throwIO TipMoved         found = saw >> writeIORef checked True-    action r (redisPool m.redis m.keys tip found) found confirm+    action r (redisPool m.db.net m.redis m.keys tip found) found confirm  -- | 'answeringAt' with the queries ready: those of -- "Haskoin.Store.Database.Query.Pooled" for the view and the pool, and@@ -1162,21 +1503,45 @@ memberCacheLoop :: Member -> IO a memberCacheLoop m = withAsync hear $ \a -> link a >> runIndexer m.indexer >> loopForever (return ())   where-    hear = loopForever $ do-      ctl <- R.newPubSubController [(m.config.prefix <> "fleet:built", heard)] []-      _ <- tryAny (R.pubSubForever m.redis ctl (return ()))-      atomically (modifyTVar' m.built (HashMap.map (+ 1)))-    heard i = atomically (modifyTVar' m.built (HashMap.insertWith (+) i 1))+    -- a connection that ends is made again, a second later after the first+    -- failure and up to five seconds after many: Redis that is down once+    -- made this a loop that never slept. A build announced while the+    -- connection was down is lost; the requests that wait for it find out+    -- when their wait runs out, and look again, as for any build that+    -- another store did not announce. Waking them all at each reconnection,+    -- as this once did, told them of builds that never happened+    hear = go (0 :: Int)+      where+        go failures = do+          ctl <- R.newPubSubController [(m.config.prefix <> "fleet:built", heard)] []+          r <- tryAny (R.pubSubForever m.redis ctl (return ()))+          let failures' = either (const (failures + 1)) (const 0) r+          threadDelay (1000000 * min 5 (max 1 failures'))+          go failures'+    -- only a key that a request waits for is counted+    heard i = atomically (modifyTVar' m.built (HashMap.adjust (\(n, w) -> (n + 1, w)) i))  -- | Wait at most so many microseconds for Redis to announce a build of the--- entry of a key; whether it did.+-- entry of a key; whether it did. The request counts itself among those+-- that wait for the key while it waits, and the last to go takes the key+-- out of the map ('built'), so that the map never grows past the requests+-- that wait. awaitBuilt :: Member -> XPubSpec -> Int -> IO Bool-awaitBuilt m x us = do-  n0 <- HashMap.lookupDefault 0 (xpubId x) <$> readTVarIO m.built+awaitBuilt m x us = bracket enter leave $ \n0 -> do   timer <- registerDelay (max 1 us)   atomically $-    (HashMap.lookupDefault 0 (xpubId x) <$> readTVar m.built >>= check . (> n0) >> return True)+    (count >>= check . (> n0) >> return True)       `orElse` (readTVar timer >>= check >> return False)+  where+    k = xpubId x+    count = maybe 0 fst . HashMap.lookup k <$> readTVar m.built+    enter = atomically $ do+      n0 <- count+      modifyTVar' m.built (HashMap.insertWith (\_ (n, w) -> (n, w + 1)) k (n0, 1))+      return n0+    leave _ =+      atomically . modifyTVar' m.built $+        HashMap.update (\(n, w) -> if w <= 1 then Nothing else Just (n, w - 1)) k  -- | Build the entry of a key at the fleet tip, the job of the indexer, and -- announce it; then evict past the size of the cache.@@ -1191,18 +1556,26 @@     Nothing -> return ()     Just built -> do       let name = decodeUtf8 (xpubId spec)+          -- announced only once it is in the cache: a request woken by the+          -- announcement reads the entry, and one woken for a build that was+          -- abandoned found nothing and answered 503+          announce = void (R.runRedis m.redis (R.publish (m.config.prefix <> "fleet:built") (xpubId spec)))       took <- subtract now <$> milliseconds-      _ <- R.runRedis m.redis (R.publish (m.config.prefix <> "fleet:built") (xpubId spec))       case built of-        Just (Built n) | n > 0 -> do-          tally m (.builds) 1-          forM_ m.metrics (\x -> addTiming x.buildTime (fromIntegral took))-          m.config.note LevelDebug $-            "Cached xpub " <> name <> ": " <> shown n <> " addresses added in " <> shown took <> " ms"-          gone <- cacheEvict m.redis m.keys m.config.cacheMax-          when (gone > 0) $ tally m (.evictions) gone-        Just Abandoned -> tally m (.abandoned) 1-        _ -> return ()+        Just (Built n) -> do+          announce+          when (n > 0) $ do+            tally m (.builds) 1+            forM_ m.metrics (\x -> addTiming x.buildTime (fromIntegral took))+            m.config.note LevelDebug $+              "Cached xpub " <> name <> ": " <> shown n <> " addresses added in " <> shown took <> " ms"+            gone <- cacheEvict m.redis m.keys m.config.cacheMax+            when (gone > 0) $ tally m (.evictions) gone+        -- not built: the job fails, and the requests that wait for it are+        -- told so, where they were told that it was done+        Just Abandoned -> tally m (.abandoned) 1 >> throwIO (NotBuilt "abandoned at a move of the tip")+        Just other -> throwIO (NotBuilt (show other))+        Nothing -> return ()   where     building tries =       memberTip m >>= \case@@ -1248,8 +1621,8 @@ -- "Haskoin.Store.Database.Query.Pooled". Every read throws v'TipMoved' if -- the tip is another one by then, and runs an action if it is not, by which -- a caller knows that the tip was checked.-redisPool :: R.Connection -> FleetKeys -> ByteString -> IO () -> PoolReads-redisPool conn keys tip checked =+redisPool :: Network -> R.Connection -> FleetKeys -> ByteString -> IO () -> PoolReads+redisPool net conn keys tip checked =   PoolReads     { summaries = \as -> case as of         [] -> return []@@ -1284,7 +1657,36 @@       replaced = \h ->         ask "replaced" [encode h] >>= \case           [value] | Right (by, height) <- runGet ((,) <$> get <*> getWord32be) value -> return (Just Replaced {..})-          _ -> return Nothing+          _ -> return Nothing,+      addressTokens = \a -> do+        rows <- ask "tokens" [encode a]+        return [(c, t) | [m, row] <- groups 2 rows, Right c <- [decode m], Just t <- [tokens row]],+      categoryHolders = \c -> do+        rows <- ask "holders" [encode c]+        return [(a, t) | [m, row] <- groups 2 rows, Right a <- [decode m], Just t <- [tokens row]],+      categorySummary = \c ->+        ask "csum" [encode c] <&> \case+          [row] | [txs, free, spent] <- map number (C.words row) -> Just CategorySummary {..}+          _ -> Nothing,+      categoryTxs = \c start n -> do+        rows <- ask "ctxs" (encode c : from start <> [num n])+        return [(number time, h) | [member, time] <- groups 2 rows, Right h <- [decode member]],+      categoryOuts = \c start n -> do+        rows <- ask "couts" (encode c : from start <> [num n])+        let made time p v s =+              Unspent+                { block = MemRef time,+                  outpoint = p,+                  value = v,+                  script = s,+                  address = eitherToMaybe (scriptToAddressBS net s)+                }+        return+          [ (made (number time) p (number v) s, f == "1")+          | [member, time, kept, f] <- groups 4 rows,+            Right p <- [decode member],+            let (v, s) = B.drop 1 <$> C.break (== ' ') kept+          ]     }   where     ask what args = poolRead conn keys 32 (Just tip) what args >>= maybe (throwIO TipMoved) (<$ checked)@@ -1297,10 +1699,9 @@     groups n rows       | null rows = []       | otherwise = take n rows : groups n (drop n rows)-    -- for each transaction: its body, whether it can be replaced by fee,-    -- how many of its outputs the pool spends, and those with what spends-    -- them-    transactions (bytes : flag : count : rest) =+    -- for each transaction: its body, how many of its outputs the pool+    -- spends, and those with what spends them+    transactions (bytes : count : rest) =       let (spent, more) = splitAt (3 * number count) rest           inputs =             IntMap.fromList@@ -1309,18 +1710,52 @@                 Right p <- [outpoint o],                 Just s <- [spender t i]               ]-       in (body bytes (flag == "1"), inputs) : transactions more+       in (body bytes, inputs) : transactions more     transactions _ = []     outpoint :: ByteString -> Either String OutPoint     outpoint = decode+    -- the sums of the tokens of a category at an address, each amount+    -- in two parts, the digits above the last nine and the last nine,+    -- joined again modulo 2^64 as the chain's sums are+    tokens row = case map number (C.words row) :: [Integer] of+      [ txs,+        freeHi,+        freeLo,+        freeNfts,+        freeOutputs,+        spentHi,+        spentLo,+        spentNfts,+        spentOutputs,+        receivedHi,+        receivedLo+        ] ->+          Just+            PoolTokens+              { 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+              }+      _ -> Nothing+    joined hi lo = fromInteger (hi * 1000000000 + lo)     summary row = case map number (C.words row) of       [txs, paid, paidCount, spent, spentCount, both, bothCount] -> Just MemSummary {..}       _ -> Nothing-    -- whether a transaction can be replaced by fee is what the pool says-    -- now, not what the store that offered it found then-    body bytes can+    -- Whether a transaction of the pool can be replaced by fee is a fact+    -- of its network: every one can on Bitcoin, whose nodes take a+    -- replacement of any unconfirmed transaction since Bitcoin Core 28,+    -- whatever the transaction says of itself, and none can on Bitcoin+    -- Cash, which has no such rule. The pool worked it out once, from+    -- what each transaction signalled and what it spent from (BIP 125),+    -- and kept that right as parents were confirmed and came back.+    body bytes       | B.null bytes = Nothing-      | otherwise = either (const Nothing) (\td -> Just (td :: TxData) {rbf = can}) (decode bytes)+      | otherwise = either (const Nothing) (\td -> Just (td :: TxData) {rbf = net.replaceByFee}) (decode bytes)     spender t i       | B.null t = Nothing       | otherwise = either (const Nothing) (\h -> Just Spender {txid = h, index = number i}) (decode t)
src/Haskoin/Store/Fleet/Pool.hs view
@@ -82,8 +82,14 @@     addresses,     totals, +    -- * What the pool holds for tokens+    TokenOut (..),+    TokenTotals (..),+    CategoryPool (..),+    tokenTotals,+    categories,+     -- * Replacing by fee-    replaceable,   ) where @@ -94,6 +100,7 @@ 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@@ -180,15 +187,16 @@ 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 =-  Pool-    { spends = Map.delete t pool.spends,-      spender = foldl' (flip Map.delete) pool.spender inputs,-      children = Map.filter (not . Set.null) (Map.map (Set.delete t) pool.children)-    }-  where-    inputs = Map.findWithDefault [] t pool.spends+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@@ -273,18 +281,36 @@         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@, 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+-- | 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@@ -318,14 +344,15 @@ -- 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])] -> Map a (AddressPool t o)+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) = map (one t time) entries+    single (t, time, entries) = mapMaybe (one t time) entries     one t time = \case-      Touches a -> (a, AddressPool [(time, t)] [] Map.empty)-      Spends a o v -> (a, AddressPool [] [] (Map.singleton o v))-      Pays a o v -> (a, AddressPool [] [(time, o, v)] Map.empty)+      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@@ -348,19 +375,104 @@   where     inside = [v | (_, o, v) <- p.paid, Map.member o p.spent] --- | The transactions of a pool that can be replaced by fee, given those--- that say so themselves: those, and whatever spends from one that can be.--- A transaction inherits this from its unconfirmed parents only, so it--- changes when a parent is confirmed and when one comes back from an--- abandoned block. This is the specification of what Redis keeps right as--- transactions come and go.-replaceable :: (Ord t) => (t -> Bool) -> (o -> t) -> Pool t o -> Set t-replaceable signals maker pool = go (Set.filter signals members)+-- | 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-    members = Map.keysSet pool.spends-    inherits found t = any ((`Set.member` found) . maker) (Map.findWithDefault [] t pool.spends)-    go found-      | grown == found = found-      | otherwise = go grown-      where-        grown = Set.union found (Set.filter (inherits found) members)+    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
+ src/Haskoin/Store/Fleet/Pool/Decide.hs view
@@ -0,0 +1,1084 @@+-- |+-- Module      : Haskoin.Store.Fleet.Pool.Decide+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- The shared mempool of a fleet as it is kept in Redis, and every change+-- to it, as decisions of "Haskoin.Store.Fleet.Atomic": what a store reads+-- and writes when it offers a transaction, withdraws some, lets the old+-- ones go, or moves the tip.+--+-- "Haskoin.Store.Fleet.Pool" says what the pool is, as a pure value. This+-- module says how that value lies in Redis, with all that the stores read+-- beside it: what the pool does at each address and to each category of+-- tokens, what the blocks replaced, what a move of the tip marked as+-- leaving, the events, and the pool's layer of the cache of extended+-- public keys.+--+-- = Why it is here and not in a script+--+-- These rules were a Lua script of eight hundred lines, which Redis ran+-- alone. That made each change one step, and it had two faults. A script+-- that fails after its first write leaves the pool half changed, since+-- Redis undoes nothing; and the rules were kept twice, in Lua to run and+-- in Haskell to test against. Here they are written once, in Haskell, and+-- "Haskoin.Store.Fleet.Atomic" makes each of them one step: the decision+-- is made from what Redis says, and carried out only if Redis still says+-- the same, by a script that decides nothing.+--+-- = How it is written+--+-- As the script was, on purpose: a function for each function of the+-- script, in its order of reading and writing, so that the two can be+-- compared line by line and, in the tests, state by state against a Redis+-- that runs the script. A decision sees what it has written, as a script+-- does, so the order means the same in both.+module Haskoin.Store.Fleet.Pool.Decide+  ( Keys (..),+    poolKeys,+    entryTxs,+    entryOuts,+    entryKey,+    entryOval,+    entryMeta,+    floorHeld,+    leavingHeld,+    takeOut,+    offer,+    withdraw,+    expire,+    How (..),+    advance,+  )+where++import Control.Monad (foldM_, forM, forM_, unless, when)+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.ByteString.Char8 qualified as C+import Data.List (nub)+import Data.Maybe (fromMaybe, isJust, isNothing)+import Data.Serialize+  ( Get,+    Put,+    getByteString,+    getWord64be,+    getWord8,+    putByteString,+    putWord64be,+    putWord8,+    runGet,+    runPut,+  )+import Data.Set qualified as Set+import Data.Word (Word32, Word64)+import Haskoin.Store.Fleet.Atomic.Keys+import Haskoin.Store.Fleet.Pool.Types++-- | The keys of the pool and of what goes with it, under the prefix of a+-- fleet, each with the kind of what it holds, and the size of a+-- transaction id in bytes. A family is the start of a key for each+-- address, category or transaction.+data Keys = Keys+  { prefix :: !ByteString,+    -- | bytes in a transaction id; an output is that and four more+    tsize :: !Int,+    tip :: !(K 'Text),+    -- | how many times the tip moved+    moves :: !(K 'Number),+    -- | how many times the pool was emptied+    restarts :: !(K 'Number),+    -- | until when each store is live+    lease :: !(K 'Counts),+    -- | the recent blocks of each store, newest first+    recent :: !(K 'Hash),+    events :: !(K 'Stream),+    xver :: !(K 'Number),+    -- | the outputs that each transaction spends, one after the other+    spends :: !(K 'Hash),+    -- | the transaction that spends each output+    spender :: !(K 'Hash),+    body :: !(K 'Hash),+    -- | the transactions of the pool that spend from each transaction+    kids :: !(Family 'Group),+    -- | what each transaction does at addresses and to tokens, as it was+    -- put in, to take it out the same+    entries :: !(K 'Hash),+    -- | every transaction by the time it entered a mempool+    time :: !(K 'Sorted),+    ids :: !(K 'Sorted),+    atx :: !(Family 'Sorted),+    aout :: !(Family 'Sorted),+    aval :: !(Family 'Hash),+    aspent :: !(Family 'Hash),+    asum :: !(Family 'Counts),+    tsum :: !(Family 'Counts),+    acat :: !(Family 'Group),+    chold :: !(Family 'Group),+    ctx :: !(Family 'Sorted),+    cout :: !(Family 'Sorted),+    cval :: !(Family 'Hash),+    csum :: !(Family 'Counts),+    -- | what a block replaced: the transaction that replaced it and the+    -- height of the block, with those by the transaction that replaced+    -- them and all by height+    rep :: !(K 'Hash),+    repby :: !(Family 'Group),+    repat :: !(K 'Sorted),+    -- | the same for what waits for the transaction that replaced it to+    -- be confirmed+    lost :: !(K 'Hash),+    lostby :: !(Family 'Group),+    lostat :: !(K 'Sorted),+    -- | the transactions that a move of the tip marked as leaving, and+    -- that are still in the pool ('takeOut'): nothing for one that a+    -- block confirmed, and for one that a block is in conflict with the+    -- transaction that replaced it and the height of the block+    leaving :: !(K 'Hash),+    -- | the place of the tip that the cache of extended public keys is at+    xtip :: !(K 'Text),+    -- | the move of the cache that is under way: its token+    moving :: !(K 'Text),+    -- | when the store that makes that move last said that it is at it+    beat :: !(K 'Number),+    -- | the entries of the cache that the move changed+    marked :: !(K 'Group),+    -- | the cached keys that have each address+    watchers :: !(Family 'Group),+    -- | the start of the entries of the cache of extended public keys+    entry :: !ByteString+  }++-- | The keys under a prefix.+poolKeys :: ByteString -> Int -> Keys+poolKeys p tsize =+  Keys+    { prefix = p,+      tsize,+      tip = named (p <> "fleet:tip"),+      moves = named (p <> "fleet:moves"),+      restarts = named (p <> "fleet:restarts"),+      lease = named (p <> "fleet:lease"),+      recent = named (p <> "fleet:recent"),+      events = named (p <> "fleet:events"),+      xver = named (p <> "fleet:xver"),+      spends = ours (p <> "pool:spends"),+      spender = ours (p <> "pool:spender"),+      body = ours (p <> "pool:body"),+      kids = oursFamily (p <> "pool:kids:"),+      entries = ours (p <> "pool:entries"),+      time = ours (p <> "pool:time"),+      ids = ours (p <> "pool:ids"),+      atx = oursFamily (p <> "pool:atx:"),+      aout = oursFamily (p <> "pool:aout:"),+      aval = oursFamily (p <> "pool:aval:"),+      aspent = oursFamily (p <> "pool:aspent:"),+      asum = oursFamily (p <> "pool:asum:"),+      tsum = oursFamily (p <> "pool:tsum:"),+      acat = oursFamily (p <> "pool:acat:"),+      chold = oursFamily (p <> "pool:chold:"),+      ctx = oursFamily (p <> "pool:ctx:"),+      cout = oursFamily (p <> "pool:cout:"),+      cval = oursFamily (p <> "pool:cval:"),+      csum = oursFamily (p <> "pool:csum:"),+      rep = ours (p <> "pool:rep"),+      repby = oursFamily (p <> "pool:repby:"),+      repat = ours (p <> "pool:repat"),+      lost = ours (p <> "pool:lost"),+      lostby = oursFamily (p <> "pool:lostby:"),+      lostat = ours (p <> "pool:lostat"),+      leaving = named mark,+      xtip = ours (p <> "fx:tip"),+      moving = ours (p <> "fx:moving"),+      beat = ours (p <> "fx:beat"),+      marked = ours (p <> "fx:marked"),+      watchers = oursFamily (p <> "fx:of:"),+      entry = p <> "fx:e:"+    }+  where+    -- Every key of the pool, and of the cache where it has what the pool+    -- gives it, is guarded by the mark of the transactions that a move+    -- left to be taken out: a decision that writes to one while Redis+    -- has a mark is stopped ('guarded'). The keys of the fleet are not:+    -- the tip, the leases and reports of the stores, the events.+    mark = p <> "pool:leaving"+    ours :: ByteString -> K kind+    ours = guarded mark+    oursFamily :: ByteString -> Family kind+    oursFamily = guardedFamily mark++-- | The lists of the entry of a cached key, what it keeps for each output,+-- and its numbers, of which the pool gives it a version.+entryTxs, entryOuts :: Keys -> ByteString -> K 'Sorted+entryTxs k i = entryKey k (i <> ":txs")+entryOuts k i = entryKey k (i <> ":outs")++entryOval :: Keys -> ByteString -> K 'Hash+entryOval k i = entryKey k (i <> ":oval")++entryMeta :: Keys -> ByteString -> K 'Counts+entryMeta k i = entryKey k (i <> ":meta")++-- | A key of an entry of the cache, by what follows the start of the+-- entries in its name: guarded as the keys of the pool are ('poolKeys').+entryKey :: Keys -> ByteString -> K kind+entryKey k rest = guarded (keyName k.leaving) (k.entry <> rest)++num :: (Show a) => a -> ByteString+num = C.pack . show++-- | The transaction that made an output.+maker :: Keys -> ByteString -> ByteString+maker k = B.take k.tsize++-- | Tell every store of the fleet that something happened: @t@ and a+-- transaction that entered the pool, @d@ and one that left it+-- unconfirmed. The events go in a stream, with the change, so that every+-- store serves the same events in the same order.+emit :: (Monad m) => Keys -> ByteString -> ByteString -> Atomic m ()+emit k kind what = xadd k.events 10000 [("k", kind), ("h", what)]++-- | Whether a transaction is in the pool.+member :: (Monad m) => Keys -> ByteString -> Atomic m Bool+member k = hexists k.spends++-- | The transactions of the pool among these, and all that spend them,+-- each once and none before one that it spends from among them.+descendants :: (Monad m) => Keys -> [ByteString] -> Atomic m [ByteString]+descendants k = descendantsBut k Set.empty++-- | 'descendants' without some transactions, nor what spends from the+-- rest only through them: a transaction that a block confirms leaves+-- what spends from it in the pool.+descendantsBut :: (Monad m) => Keys -> Set.Set ByteString -> [ByteString] -> Atomic m [ByteString]+descendantsBut k but from = do+  roots <- filterM' (member k) from+  go Set.empty [] (reverse roots)+  where+    go _ order [] = return (reverse order)+    go done order (t : todo)+      | Set.member t done || Set.member t but = go done order todo+      | otherwise = do+          children <- smembers (under k.kids t)+          go (Set.insert t done) (t : order) (Set.toDescList children <> todo)+    filterM' p = fmap concat . mapM (\x -> (\ok -> [x | ok]) <$> p x)++-- | Whether a member of a list of an entry of the cache is in the pool's+-- layer, with a score below zero: what the pool puts in or takes out of an+-- entry is never what the chain's layer has, which a move of the tip+-- writes ahead of the pool.+pooled :: (Monad m) => K 'Sorted -> ByteString -> Atomic m Bool+pooled z x = maybe False (< 0) <$> zscore z x++-- | Add to a field of a summary.+addTo :: (Monad m) => K 'Counts -> ByteString -> Integer -> Atomic m ()+addTo = hincrBy++-- | What the pool does to the tokens of an output, by category and by+-- address. An output is @free@ while the pool makes it and nothing in the+-- pool uses it up, and @spent@ while the pool uses it up and the chain+-- made it. An amount is kept in two parts, the digits above the last nine+-- and the last nine, as the stores read it.+tokens :: (Monad m) => Keys -> PoolTokenOut -> ByteString -> Integer -> Atomic m ()+tokens k o which sign = do+  addTo (under k.csum o.category) which sign+  forM_ o.address $ \a -> do+    let key = under k.tsum (o.category <> a)+        (hi, lo) = toInteger o.amount `divMod` 1000000000+    addTo key (which <> "Hi") (sign * hi)+    addTo key (which <> "Lo") (sign * lo)+    addTo key (which <> "Nfts") (sign * (if o.nft then 1 else 0))+    addTo key (which <> "Outputs") sign++-- | Put what a transaction does at addresses and to tokens in, with sign+-- 1, or take it out, with sign -1: the lists and the summary of each+-- address, the lists and counts of each category, and the pool's layer of+-- every cached key that has one of the addresses.+account :: (Monad m) => Keys -> ByteString -> Word64 -> [PoolEntry] -> Integer -> Atomic m ()+account k t at es sign = do+  forM_ es $ \case+    PoolMakes o -> do+      let c = o.category+      if entering+        then do+          zadd (under k.cout c) newest o.output+          hset (under k.cval c) o.output (maybe "" (\(v, s) -> num v <> " " <> s) o.coins)+        else do+          zrem (under k.cout c) o.output+          hdel (under k.cval c) o.output+      -- an output that the pool uses up was spent from the chain until+      -- the pool made it, and is spent from the chain again once the pool+      -- no longer makes it+      used <- hexists k.spender o.output+      if used then tokens k o "spent" (negate sign) else tokens k o "free" sign+      forM_ o.address $ \a -> do+        let (hi, lo) = toInteger o.amount `divMod` 1000000000+        addTo (under k.tsum (c <> a)) "receivedHi" (sign * hi)+        addTo (under k.tsum (c <> a)) "receivedLo" (sign * lo)+    PoolUses o -> do+      ours <- member k (maker k o.output)+      if ours then tokens k o "free" (negate sign) else tokens k o "spent" sign+    PoolTouches a -> do+      watching <- Set.toList <$> smembers (under k.watchers a)+      if entering then zadd (under k.atx a) newest t else zrem (under k.atx a) t+      forM_ watching $ \i ->+        if entering+          then zaddNew (entryTxs k i) newest t+          else do+            mine <- pooled (entryTxs k i) t+            when mine (zrem (entryTxs k i) t)+      addTo (under k.asum a) "txs" sign+    PoolSpends a o v -> do+      if entering then hset (under k.aspent a) o (num v) else hdel (under k.aspent a) o+      addTo (under k.asum a) "spent" (sign * toInteger v)+      addTo (under k.asum a) "spentCount" sign+      paid <- hexists (under k.aval a) o+      when paid $ do+        addTo (under k.asum a) "both" (sign * toInteger v)+        addTo (under k.asum a) "bothCount" sign+    PoolPays a o v s -> do+      watching <- Set.toList <$> smembers (under k.watchers a)+      if entering+        then do+          zadd (under k.aout a) newest o+          hset (under k.aval a) o (num v <> " " <> s)+        else do+          zrem (under k.aout a) o+          hdel (under k.aval a) o+      forM_ watching $ \i -> do+        let outs = entryOuts k i+        if entering+          then do+            there <- isJust <$> zscore outs o+            unless there $ do+              zadd outs newest o+              hset (entryOval k i) o (num v <> " " <> num (B.length a) <> " " <> a <> s)+          else do+            mine <- pooled outs o+            when mine $ do+              zrem outs o+              hdel (entryOval k i) o+      addTo (under k.asum a) "paid" (sign * toInteger v)+      addTo (under k.asum a) "paidCount" sign+      gone <- hexists (under k.aspent a) o+      when gone $ do+        addTo (under k.asum a) "both" (sign * toInteger v)+        addTo (under k.asum a) "bothCount" sign+  -- every entry with an address that the transaction touches has a new+  -- version, so that a request that read it before reads it again+  watched <- nub . concat <$> forM touched (\a -> Set.toList <$> smembers (under k.watchers a))+  unless (null watched) $ do+    before <- getNumber k.xver+    incrBy k.xver 1+    forM_ watched $ \i -> hsetNumber (entryMeta k i) "ver" (before + 1)+  -- the transaction in the lists of the categories that it moves, and in+  -- the count of each address that it moves tokens of+  forM_ cats $ \c -> do+    if entering then zadd (under k.ctx c) newest t else zrem (under k.ctx c) t+    addTo (under k.csum c) "txs" sign+  forM_ held $ \(c, a) -> do+    addTo (under k.tsum (c <> a)) "txs" sign+    when entering $ do+      sadd (under k.acat a) c+      sadd (under k.chold c) a+  -- an address that no transaction touches has no summary, nor has a+  -- category or an address of one that no transaction moves+  unless entering $ do+    forM_ touched $ \a -> do+      left <- hgetNumber (under k.asum a) "txs"+      when (left == Just 0) (del (under k.asum a))+    forM_ cats $ \c -> do+      left <- hgetNumber (under k.csum c) "txs"+      when (left == Just 0) (del (under k.csum c))+    forM_ held $ \(c, a) -> do+      left <- hgetNumber (under k.tsum (c <> a)) "txs"+      when (left == Just 0) $ do+        del (under k.tsum (c <> a))+        srem (under k.acat a) c+        srem (under k.chold c) a+  where+    entering = sign > 0+    newest = negate (fromIntegral at) :: Score+    touched = touchedBy es+    cats = categoriesOf es+    held = heldBy es++-- | The addresses that a transaction touches, each once.+touchedBy :: [PoolEntry] -> [ByteString]+touchedBy = nub . concatMap addressOf+  where+    addressOf = \case+      PoolTouches a -> [a]+      PoolSpends a _ _ -> [a]+      PoolPays a _ _ _ -> [a]+      _ -> []++-- | The outputs with tokens that a transaction makes or uses up.+tokenOuts :: [PoolEntry] -> [PoolTokenOut]+tokenOuts = concatMap (\case PoolMakes o -> [o]; PoolUses o -> [o]; _ -> [])++-- | The categories of the tokens that a transaction moves, each once.+categoriesOf :: [PoolEntry] -> [ByteString]+categoriesOf = nub . map (.category) . tokenOuts++-- | The categories that a transaction moves at each address, each once.+heldBy :: [PoolEntry] -> [(ByteString, ByteString)]+heldBy es = nub [(o.category, a) | o <- tokenOuts es, Just a <- [o.address]]++-- | What taking a transaction out asks about its addresses and tokens+-- ('account', with sign -1), given what it does there: for 'foreseen'.+-- What is asked of the cached keys at an address is named once Redis has+-- said which they are.+departing :: Keys -> ByteString -> [PoolEntry] -> [Ahead]+departing k t es =+  concatMap entry es+    <> [only (askingCount (under k.asum a) "txs") | a <- touchedBy es]+    <> [only (askingCount (under k.csum c) "txs") | c <- categoriesOf es]+    <> [only (askingCount (under k.tsum (c <> a)) "txs") | (c, a) <- heldBy es]+  where+    entry = \case+      PoolMakes o -> [only (askingWhetherField k.spender o.output)]+      PoolUses o -> [only (askingWhetherField k.spends (maker k o.output))]+      PoolTouches a -> [watching a (\i -> askingScore (entryTxs k i) t)]+      PoolSpends a o _ -> [only (askingWhetherField (under k.aval a) o)]+      PoolPays a o _ _ ->+        [ watching a (\i -> askingScore (entryOuts k i) o),+          only (askingWhetherField (under k.aspent a) o)+        ]+    watching a asks =+      thenMembers (under k.watchers a) $ \ids ->+        [only (askingNumber k.xver) | not (Set.null ids)] <> map (only . asks) (Set.toList ids)++-- | What a move of the tip over blocks asks, in the steps in which it can+-- be named: the tip; then what is asked of each transaction that the+-- blocks confirm and of each output that they spend, and which stores+-- are live; then, of each transaction, what taking it out asks about its+-- addresses ('departing'), and of each cached key at one of them.+--+-- And of each transaction of the pool that spends what a block spends:+-- what taking it out asks, and of all that spends from it.+--+-- These are the questions of a move with no block to undo, which is+-- nearly all of them. One that brings transactions back asks more, and+-- is gone through again for it. Nothing depends on this being right:+-- @asks Redis no more times@ in "Haskoin.Store.Fleet.DecideSpec" fails+-- when a question is missing here.+foreseen :: Keys -> Maybe ByteString -> ByteString -> Integer -> Bool -> PoolChange -> [Ahead]+foreseen k saw target now light change =+  [ thenText k.tip $ \tip ->+      let at = fromMaybe "" tip+       in if at /= fromMaybe "" saw || at == target then [] else rest+  ]+  where+    rest =+      [ thenAbove k.lease now (map (only . askingField k.recent) . Set.toList),+        only (askingNumber k.moves),+        only (asking k.moving),+        only (askingWhether k.leaving),+        only (asking k.xtip),+        thenMembers k.marked $ \ids ->+          [only (askingNumber k.xver) | not (Set.null ids)]+            <> [only (askingWhether (entryMeta k i)) | i <- Set.toList ids]+      ]+        <> [ only (askingRange z MinusInf (At (fromIntegral (h - 2016))) Nothing)+           | h <- maybe [] pure change.height,+             h >= 2016,+             z <- [k.repat, k.lostat]+           ]+        <> [ thenField k.spender (B.take (k.tsize + 4) item) (maybe [] rival)+           | item <- concatMap (pieces (2 * k.tsize + 8)) change.spent+           ]+        <> concatMap confirmed change.confirmed+    confirming = Set.fromList change.confirmed+    -- A transaction of the pool that spends what a block spends, and+    -- that the blocks do not confirm, leaves with all that spends it,+    -- and is kept as replaced. A block of Bitcoin has some of those, and+    -- finding them as it went had the move gone through five more times+    -- for sixty of them.+    rival t+      | Set.member t confirming = []+      | light = only (askingWhetherField k.spends t) : kin t+      | otherwise = leaver t+    -- all that spends from a transaction, to mark it: not what the+    -- blocks confirm, which leaves what spends from it+    kin t+      | Set.member t confirming = []+      | otherwise = [thenMembers (under k.kids t) (concatMap kin . Set.toList)]+    leaver t =+      [ only (askingWhetherField k.spends t),+        only (askingField k.spends t),+        only (askingField k.rep t),+        thenField k.entries t (maybe [] (departing k t . snd . kept)),+        thenMembers (under k.kids t) (concatMap leaver . Set.toList)+      ]+    confirmed t+      | light =+          [ only (askingWhetherField k.spends t),+            only (askingMembers (under k.lostby t))+          ]+      | otherwise =+          [ only (askingField k.spends t),+            only (askingMembers (under k.lostby t)),+            thenField k.entries t (maybe [] (departing k t . snd . kept))+          ]++-- | The outputs that are written one after the other.+outputs :: Keys -> ByteString -> [ByteString]+outputs k s+  | B.null s = []+  | otherwise = let (o, rest) = B.splitAt (k.tsize + 4) s in o : outputs k rest++-- | Take one transaction out, leaving what spends it: quietly if a block+-- confirmed it, which is no event of the mempool.+remove :: (Monad m) => Keys -> Bool -> ByteString -> Atomic m ()+remove k quiet t =+  hget k.spends t >>= \case+    Nothing -> return ()+    Just inputs -> do+      unless quiet (emit k "d" t)+      (at, es) <- maybe (0, []) kept <$> hget k.entries t+      account k t at es (-1)+      hdel k.entries t+      zrem k.time t+      zrem k.ids t+      forM_ (outputs k inputs) $ \o -> do+        hdel k.spender o+        srem (under k.kids (maker k o)) t+      hdel k.spends t+      hdel k.body t++-- | Put a transaction in.+insert :: (Monad m) => Keys -> PoolTx -> Atomic m ()+insert k tx = do+  let t = tx.txid+  hset k.spends t (B.concat tx.inputs)+  hset k.body t tx.body+  forM_ tx.inputs $ \o -> do+    hset k.spender o t+    sadd (under k.kids (maker k o)) t+  hset k.entries t (keep tx.time tx.entries)+  zadd k.time (fromIntegral tx.time) t+  zadd k.ids 0 t+  account k t tx.time tx.entries 1+  emit k "t" t++-- | Whether a store has the floor: it began a move of the tip+-- ('Haskoin.Store.Fleet.XPub.Decide.begin'), and said in the last ten+-- seconds that it is at it ('Haskoin.Store.Fleet.XPub.Decide.beat').+--+-- A move of the tip is one decision that reads what tens of thousands of+-- questions say, over seconds, and is carried out only if every answer+-- still holds. Transactions are offered several times a second, and each+-- offer changes some of those answers: left to themselves, offers would+-- have every move refused, and the tip would never move. So whatever else+-- writes to the pool or to the cache gives way while a store has the+-- floor, as everything gave way to the script that moved the tip, which+-- Redis ran alone. An offer is 'Late' then, and is made again.+--+-- The floor is the store's for as long as it says so, and not for ten+-- seconds from when it took it: the move over a block of Bitcoin was+-- decided in more than ten seconds on a server, lost the floor before it+-- was carried out, and was refused at every turn. What the store says is+-- written to a key of its own, which the move does not read, so that+-- saying it changes no answer of the move.+--+-- Giving way for no reason costs a moment, and the clock can only do+-- that: a move that looks under way and has just gone quiet. A move that+-- has gone quiet at the clock of this decision has still gone quiet when+-- the decision is carried out, if its store said nothing since, which the+-- script checks.+floorHeld :: (Monad m) => Keys -> Atomic m Bool+floorHeld k =+  get k.moving >>= \case+    Nothing -> return False+    Just _ -> do+      now <- clock+      said <- getNumber k.beat+      return (now - said <= 10000)++-- | Whether the pool still has transactions that a move of the tip marked+-- as leaving. Nothing else is put in or taken out of the pool until they+-- are out ('takeOut'): an offer is 'Late', a withdrawal takes nothing,+-- and the next move waits, as all of them do while a store has the floor.+leavingHeld :: (Monad m) => Keys -> Atomic m Bool+leavingHeld k = exists k.leaving++-- | Take out of the pool some of the transactions that a move of the tip+-- marked as leaving, and say how many of these were: one that a block+-- confirmed leaves quietly, and one that a block is in conflict with+-- leaves as withdrawn, and is kept as replaced. One that is not marked,+-- or no longer, is left alone, so that two stores may take the same ones+-- out.+--+-- A move of the tip over a full block took what the block confirmed out+-- of the pool in the same step: tens of thousands of questions and a+-- hundred thousand writes, for which the tip waited, seconds of them in+-- Redis, which answers nobody else meanwhile. The move now marks them,+-- which is one write for each, and the tip is at the new block. They+-- leave here, a few at a time, in the same way and to the same end, and+-- a request that would read one of them takes it out first.+takeOut :: (Monad m) => Keys -> [ByteString] -> Atomic m Int+takeOut k ts = do+  -- the one decision that is made among marked transactions+  unguarded+  ready <- ahead [thenField k.leaving t (maybe [] (going t)) | t <- ts]+  if ready then length . filter id <$> mapM one ts else return 0+  where+    going t by =+      [ only (askingField k.spends t),+        thenField k.entries t (maybe [] (departing k t . snd . kept))+      ]+        <> [only (askingField k.rep t) | not (B.null by)]+    one t =+      hget k.leaving t >>= \case+        Nothing -> return False+        Just by -> do+          if B.null by+            then remove k True t+            else remove k False t >> replaced k t by+          hdel k.leaving t+          return True++-- | Withdraw transactions and all that spends them: those that left. None+-- while a store is moving the tip.+withdraw :: (Monad m) => Keys -> [ByteString] -> Atomic m [ByteString]+withdraw k from = do+  held <- floorHeld k+  busy <- leavingHeld k+  if held || busy then return [] else withdrawn k from++-- | 'withdraw' whoever has the floor: for the move of the tip itself.+withdrawn :: (Monad m) => Keys -> [ByteString] -> Atomic m [ByteString]+withdrawn k from = do+  order <- descendants k from+  forM_ order (remove k False)+  return order++-- | Withdraw what has been in the pool since before a time, so many at+-- most, chosen here and withdrawn in the same step. Chosen by the caller+-- in a step before, a transaction could leave and come back in between+-- with a new time, and be withdrawn for the time that it had.+expire :: (Monad m) => Keys -> Integer -> Int -> Atomic m [ByteString]+expire k before most = do+  old <- zrangeByScore k.time (At 0) (At (fromIntegral before)) (Just most)+  withdraw k (map fst old)++-- | Offer a transaction, which the store checked against a tip: the tip+-- that it saw or nothing, whether each output that the transaction spends+-- is unspent at that tip, the transactions that it replaces, and the+-- transaction.+--+-- It is taken if no other of the pool spends what it spends, and each+-- output that it spends is made by a transaction of the pool or unspent+-- at the tip. What it replaces leaves first, with all that spends it, but+-- only if it is taken.+--+-- It is 'Late' while a store is moving the tip ('floorHeld'), as it is+-- when the tip is no longer the one that the store saw: the store offers+-- it again.+offer :: (Monad m) => Keys -> Maybe ByteString -> [Bool] -> [ByteString] -> PoolTx -> Atomic m Offered+offer k saw unspent replaces tx = do+  prefetch (likely k tx <> map (askingWhetherField k.spends) replaces)+  at <- get k.tip+  held <- floorHeld k+  busy <- leavingHeld k+  if held || busy || fromMaybe "" at /= fromMaybe "" saw+    then return Late+    else do+      known <- member k tx.txid+      if known+        then return Known+        else do+          leaving <- descendants k replaces+          let left = Set.fromList leaving+          spenders <- forM tx.inputs (hget k.spender)+          let rivals = nub [s | Just s <- spenders, Set.notMember s left]+          if not (null rivals)+            then return (Conflict rivals)+            else do+              made <- forM tx.inputs $ \o -> (&& Set.notMember (maker k o) left) <$> member k (maker k o)+              let orphans = [o | (o, ours, free) <- zip3 tx.inputs made (unspent <> repeat False), not ours, not free]+              if not (null orphans)+                then return (Orphan orphans)+                else do+                  forM_ leaving (remove k False)+                  insert k tx+                  return Taken++-- | What the offer of a transaction asks when the transaction is taken+-- and replaces nothing, which is what most offers are: named before the+-- first question, so that Redis is asked all of it at once. Nothing+-- depends on this list being right. A question that is missing costs a+-- round trip, and one too many costs its answer.+likely :: Keys -> PoolTx -> [Query]+likely k tx =+  [ asking k.tip,+    asking k.moving,+    askingWhether k.leaving,+    askingWhetherField k.spends t,+    askingField k.spends t+  ]+    <> concat+      [ [askingField k.spender o, askingWhetherField k.spends (maker k o)]+      | o <- tx.inputs+      ]+    <> concatMap entry tx.entries+    <> [askingNumber k.xver]+  where+    t = tx.txid+    entry = \case+      PoolMakes o -> [askingWhetherField k.spender o.output]+      PoolUses o -> [askingWhetherField k.spends (maker k o.output)]+      PoolTouches a -> [askingMembers (under k.watchers a)]+      PoolSpends a o _ -> [askingMembers (under k.watchers a), askingWhetherField (under k.aval a) o]+      PoolPays a o _ _ -> [askingMembers (under k.watchers a), askingWhetherField (under k.aspent a) o]++-------------------------------------------------------------------------------+-- The tip moves+-------------------------------------------------------------------------------++-- | What a store that moves the tip knows of the way.+data How+  = -- | what the blocks between the two tips did to the pool. With no+    -- block to undo, what leaves the pool is marked and taken out+    -- afterwards ('takeOut'); otherwise as 'AtOnce'.+    Changing !PoolChange+  | -- | the same, with everything that leaves the pool taken out in the+    -- move itself+    AtOnce !PoolChange+  | -- | nothing, for it does not have the old tip: the pool is emptied,+    -- and only if this store, by its name, is the one that is live, since+    -- another may know the way+    AloneNotKnowing !ByteString+  | -- | that the way is longer than a store goes through, which is so for+    -- every store: the pool is emptied, or the tip would never move again+    TooLong++-- | Four bytes, big-endian, as a number: the height at the end of what is+-- kept of a replaced transaction.+heightOf :: Keys -> ByteString -> Score+heightOf k value = fromIntegral (B.foldl' (\n b -> n * 256 + toInteger b) 0 (B.take 4 (B.drop k.tsize value)))++-- | Forget that these transactions were replaced.+unreplaced :: (Monad m) => Keys -> [ByteString] -> Atomic m ()+unreplaced k ts =+  forM_ ts $ \t ->+    hget k.rep t >>= \case+      Nothing -> return ()+      Just value -> do+        srem (under k.repby (B.take k.tsize value)) t+        hdel k.rep t+        zrem k.repat t++-- | Keep that a transaction was replaced: by a transaction, which comes+-- first in the value, at a height, which follows in four bytes. What was+-- kept of it before goes, with its place among what its winner replaced.+replaced :: (Monad m) => Keys -> ByteString -> ByteString -> Atomic m ()+replaced k t value = do+  unreplaced k [t]+  hset k.rep t value+  sadd (under k.repby (B.take k.tsize value)) t+  zadd k.repat (heightOf k value) t++-- | Pieces of so many bytes.+pieces :: Int -> ByteString -> [ByteString]+pieces n s+  | B.null s || n <= 0 = []+  | otherwise = let (a, rest) = B.splitAt n s in a : pieces n rest++-- | Move the tip, and the pool and the cache of extended public keys with+-- it, in one step: the commit of a move.+--+-- Given are the tip that the store saw or nothing, the block to move to,+-- the time in milliseconds or nothing for the clock of Redis, the size of+-- a block in bytes, what the store knows of the way, the blocks that the+-- tip moves through, oldest first, and the token of the move of the cache+-- that the store began, or none.+--+-- The tip moves only to the block that the live stores agree on: the+-- newest block of the first of them, by name, that every other has among+-- its recent ones. It says 'Raced' when the tip is not the one that the+-- store saw, when no store is live, when the block is not the one agreed+-- on, when a store that does not know the way is not alone, and when the+-- move of the cache is not the one that the store began; and it has+-- changed nothing then.+--+-- With the way known: the transactions of the abandoned blocks come back,+-- and what spends the same in the pool gives way; what spends from the+-- rest of them leaves; what the new blocks confirm leaves quietly; what+-- spends what they spend leaves with all that spends it, and is kept as+-- replaced, by which transaction and at which height. What is kept of+-- replaced transactions is forgotten 2016 blocks later.+advance ::+  (Monad m) =>+  Keys ->+  Maybe ByteString ->+  ByteString ->+  Maybe Integer ->+  Int ->+  How ->+  [ByteString] ->+  ByteString ->+  Atomic m Moved+advance k saw target given bsize how path token = do+  -- What a move over blocks will ask, named before it is gone through+  -- ('foreseen'). A pass in which Redis has not answered all of that+  -- does not count, and is left at once, with a result that nobody sees.+  ready <- case how of+    Changing change -> do+      now <- maybe clock return given+      ahead (foreseen k saw target now (plain change) change)+    AtOnce change -> do+      now <- maybe clock return given+      ahead (foreseen k saw target now False change)+    _ -> return True+  if ready then moving else return Raced+  where+    moving = do+      at <- fromMaybe "" <$> get k.tip+      if at /= fromMaybe "" saw+        then return Raced+        else+          if target == at+            then return Stays+            else do+              now <- maybe clock return given+              -- which stores are live, and not until when: a store that+              -- renews its lease while this is decided changes nothing for it+              live <- Set.toAscList <$> hfieldsAbove k.lease now+              reports <- forM live (fmap (pieces bsize . fromMaybe "") . hget k.recent)+              let agreed = case reports of+                    first : others -> take 1 [b | b <- first, all (elem b) others]+                    [] -> []+              if null live || agreed /= [target]+                then return Raced+                else do+                  count <- getNumber k.moves+                  let before = num count <> "@" <> at+                      after = num (count + 1) <> "@" <> target+                  case how of+                    AloneNotKnowing caller+                      | live /= [caller] -> return Raced+                      | otherwise -> emptied at after+                    TooLong -> emptied at after+                    Changing change+                      | plain change -> floored (marked change before after)+                      | otherwise -> floored (changed change before after)+                    AtOnce change -> floored (changed change before after)+    -- A move over blocks is for the store that began the move of the+    -- cache, and waits for what the move before it left in the pool.+    floored go = do+      busy <- leavingHeld k+      current <- get k.moving+      let other = maybe False (/= token) current+      if busy+        then return Leaving+        else+          if other || (isNothing current && not (B.null token))+            then return Raced+            else go+    -- no block is undone: nothing comes back, and nothing that was+    -- replaced is to be kept+    plain change = null change.returned && null change.gone && null change.lost+    -- the cache of extended public keys at the new place of the tip: its+    -- entries gone if the pool is, or if it was not at the place before;+    -- and otherwise every entry that the move marked with a new version+    settle emptying before after = do+      place <- get k.xtip+      if emptying || maybe False (/= before) place+        then wipe (k.prefix <> "fx:")+        else do+          ids <- Set.toList <$> smembers k.marked+          unless (null ids) $ do+            version <- getNumber k.xver+            incrBy k.xver 1+            forM_ ids $ \i -> do+              there <- exists (entryMeta k i)+              when there (hsetNumber (entryMeta k i) "ver" (version + 1))+          del k.marked+          del k.moving+          del k.beat+      set k.xtip after+    -- the pool starts again, and a counter tells the stores to fill it+    -- again; the first tip of a fleet empties nothing.+    emptied at after = do+      -- with its marks: nothing of the pool is left for them to guard+      unguarded+      wipe (k.prefix <> "pool:")+      unless (B.null at) (incrBy k.restarts 1)+      settle True "" after+      set k.tip target+      incrBy k.moves 1+      emit k "b" target+      return (MovedTo target)+    -- The move over new blocks alone, with what leaves the pool only+    -- marked: 'takeOut' takes it out, a few transactions at a time.+    marked change before after = do+      let confirming = Set.fromList change.confirmed+      forM_ change.confirmed $ \t -> do+        ours <- member k t+        when ours (hset k.leaving t "")+      -- what waited for a transaction that they confirm was replaced+      forM_ change.confirmed $ \t -> do+        waiting <- smembers (under k.lostby t)+        unless (Set.null waiting) $ do+          forM_ (Set.toList waiting) $ \w -> do+            value <- hget k.lost w+            forM_ value (replaced k w)+            hdel k.lost w+            zrem k.lostat w+          del (under k.lostby t)+      -- what spends what they spend leaves with all that spends it: each+      -- is marked with the first transaction that replaces it+      foldM_+        ( \seen item -> do+            let (o, by) = B.splitAt (k.tsize + 4) item+            s <- hget k.spender o+            case s of+              Just rival | Set.notMember rival confirming -> do+                order <- descendantsBut k confirming [rival]+                let new = filter (`Set.notMember` seen) order+                forM_ new (\t -> hset k.leaving t by)+                return (foldr Set.insert seen new)+              _ -> return seen+        )+        Set.empty+        (concatMap (pieces (2 * k.tsize + 8)) change.spent)+      forM_ change.height $ \h -> when (h >= 2016) $ do+        let limit = At (fromIntegral (h - 2016 :: Word32))+        old <- zrangeByScore k.repat MinusInf limit Nothing+        unreplaced k (map fst old)+        stale <- zrangeByScore k.lostat MinusInf limit Nothing+        forM_ stale $ \(t, _) -> do+          value <- hget k.lost t+          forM_ value $ \v -> srem (under k.lostby (B.take k.tsize v)) t+          hdel k.lost t+          zrem k.lostat t+      settle False before after+      set k.tip target+      incrBy k.moves 1+      forM_ (if null path then [target] else path) (emit k "b")+      return (MovedTo target)+    changed change before after = do+      -- the abandoned blocks: what can come back does, and what spends the+      -- same in the pool gives way. What a transaction that comes back+      -- replaced is not replaced any more.+      forM_ change.returned $ \tx -> do+        won <- smembers (under k.repby tx.txid)+        unreplaced k (Set.toList won)+        ours <- member k tx.txid+        unless ours $ do+          rivals <- forM tx.inputs (hget k.spender)+          _ <- withdrawn k [s | Just s <- rivals]+          insert k tx+      -- what the store has as replaced of the abandoned blocks waits for+      -- the transaction that replaced it+      forM_ (concatMap (pieces (2 * k.tsize + 4)) change.lost) $ \item -> do+        let (t, value) = B.splitAt k.tsize item+        old <- hget k.lost t+        forM_ old $ \v -> srem (under k.lostby (B.take k.tsize v)) t+        hset k.lost t value+        sadd (under k.lostby (B.take k.tsize value)) t+        zadd k.lostat (heightOf k value) t+      -- what spends from those that are gone for good leaves+      orphaned <- concat <$> forM change.gone (fmap Set.toList . smembers . under k.kids)+      _ <- withdrawn k orphaned+      -- the new blocks: what they confirm leaves alone+      forM_ change.confirmed (remove k True)+      -- what waited for a transaction that they confirm was replaced+      forM_ change.confirmed $ \t -> do+        waiting <- smembers (under k.lostby t)+        forM_ (Set.toList waiting) $ \w -> do+          value <- hget k.lost w+          forM_ value (replaced k w)+          hdel k.lost w+          zrem k.lostat w+        del (under k.lostby t)+      -- what spends what they spend leaves with all that spends it, and is+      -- kept as replaced+      forM_ (concatMap (pieces (2 * k.tsize + 8)) change.spent) $ \item -> do+        let (o, by) = B.splitAt (k.tsize + 4) item+        s <- hget k.spender o+        forM_ s $ \rival -> do+          left <- withdrawn k [rival]+          forM_ left (\t -> replaced k t by)+      -- forget what was replaced, or waits, 2016 blocks before the block+      -- of the tip+      forM_ change.height $ \h -> when (h >= 2016) $ do+        let limit = At (fromIntegral (h - 2016 :: Word32))+        old <- zrangeByScore k.repat MinusInf limit Nothing+        unreplaced k (map fst old)+        stale <- zrangeByScore k.lostat MinusInf limit Nothing+        forM_ stale $ \(t, _) -> do+          value <- hget k.lost t+          forM_ value $ \v -> srem (under k.lostby (B.take k.tsize v)) t+          hdel k.lost t+          zrem k.lostat t+      settle False before after+      set k.tip target+      incrBy k.moves 1+      -- the blocks that the tip moved through, oldest first, if the store+      -- that moves it gave them, and the block that it is at now otherwise+      forM_ (if null path then [target] else path) (emit k "b")+      return (MovedTo target)++-------------------------------------------------------------------------------+-- What is kept of a transaction, to take it out as it was put in+-------------------------------------------------------------------------------++-- | The time and the entries of a transaction, as the pool keeps them.+keep :: Word64 -> [PoolEntry] -> ByteString+keep at es = runPut $ do+  putWord64be at+  putWord64be (fromIntegral (length es))+  mapM_ putEntry es++-- | What 'keep' wrote, or nothing for what it did not write.+kept :: ByteString -> (Word64, [PoolEntry])+kept = either (const (0, [])) id . runGet ((,) <$> getWord64be <*> listed)+  where+    listed = getWord64be >>= \n -> mapM (const getEntry) [1 .. n]++putBytes :: ByteString -> Put+putBytes s = putWord64be (fromIntegral (B.length s)) >> putByteString s++getBytes :: Get ByteString+getBytes = getWord64be >>= getByteString . fromIntegral++putEntry :: PoolEntry -> Put+putEntry = \case+  PoolTouches a -> putWord8 0 >> putBytes a+  PoolSpends a o v -> putWord8 1 >> putBytes a >> putBytes o >> putWord64be v+  PoolPays a o v s -> putWord8 2 >> putBytes a >> putBytes o >> putWord64be v >> putBytes s+  PoolMakes o -> putWord8 3 >> putToken o+  PoolUses o -> putWord8 4 >> putToken o+  where+    putToken o = do+      maybe (putWord8 0) (\a -> putWord8 1 >> putBytes a) o.address+      putBytes o.output+      putBytes o.category+      putWord64be o.amount+      putWord8 (if o.nft then 1 else 0)+      maybe (putWord8 0) (\(v, s) -> putWord8 1 >> putWord64be v >> putBytes s) o.coins++getEntry :: Get PoolEntry+getEntry =+  getWord8 >>= \case+    0 -> PoolTouches <$> getBytes+    1 -> PoolSpends <$> getBytes <*> getBytes <*> getWord64be+    2 -> PoolPays <$> getBytes <*> getBytes <*> getWord64be <*> getBytes+    3 -> PoolMakes <$> getToken+    4 -> PoolUses <$> getToken+    _ -> fail "Not an entry of the pool"+  where+    getToken = do+      address <- getWord8 >>= \case 0 -> return Nothing; _ -> Just <$> getBytes+      output <- getBytes+      category <- getBytes+      amount <- getWord64be+      nft <- (/= 0) <$> getWord8+      coins <- getWord8 >>= \case 0 -> return Nothing; _ -> Just <$> ((,) <$> getWord64be <*> getBytes)+      return PoolTokenOut {address, output, category, amount, nft, coins}
+ src/Haskoin/Store/Fleet/Pool/Order.hs view
@@ -0,0 +1,287 @@+{-@ LIQUID "--reflection" @-}+{-@ LIQUID "--ple" @-}++-- | Taking transactions out of the pool, proved to be the same in any+-- order: the heart of the pool as a pure value ("Haskoin.Store.Fleet.Pool"),+-- in a module that Liquid Haskell checks (@proofs\/@).+--+-- = Why+--+-- A move of the tip marks the transactions that leave the pool, and they+-- are taken out afterwards, a few at a time, by whoever gets to them: the+-- store that moved the tip, another store, a request that has to read one+-- (@docs\/tip-first.md@). That is right only if the order does not+-- matter. For the pool in Redis, small worlds are gone through and random+-- histories are tried (@scripts\/check-pool.sh@,+-- @Haskoin.Store.Fleet.DecideSpec@). Here it is proved, for every pool+-- and every two transactions, of the pool as a pure value, which is what+-- the pool in Redis is held to.+--+-- = What is proved+--+-- The pool is three maps: what each transaction spends, which+-- transaction spends each output, and which transactions spend from each+-- transaction. 'removeCore' takes one transaction out of the three.+-- 'anyOrder' says that taking out one and then another leaves the same+-- three maps as taking them out the other way round. Any order of any+-- number of transactions is a series of such swaps, so all orders leave+-- the same.+--+-- = What is assumed+--+-- What "Data.Map" does, as far as this goes, in five laws (@lookGone@,+-- @lookLess@, @lookWout@, @lookFull@, @same@): what a lookup gives after+-- a key is deleted, after a set of keys is taken out, after a member is+-- taken out of every set, and after the empty sets are dropped; and that+-- two maps with the same lookups are the same map. Each is one line, in+-- one place. Everything else follows from them, and Liquid Haskell checks+-- that it does.+--+-- = What is not proved here+--+-- That the pool in Redis does what this value does: that is sampled+-- (@Haskoin.Store.Fleet.RedisSpec@) and checked in small worlds. And+-- nothing of what the pool keeps for addresses and tokens: in the pure+-- pool those are worked out from the transactions that it has+-- (@addresses@, @totals@), so they follow the three maps.+module Haskoin.Store.Fleet.Pool.Order+  ( Core (..),+    removeCore,+    anyOrder,+  )+where++import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Set (Set)+import Data.Set qualified as Set++-- | The three maps of the pool: what each transaction spends, the+-- transaction that spends each output, and the transactions that spend+-- from each transaction.+data Core t o = Core (Map t [o]) (Map o t) (Map t (Set t))++{-@ data Core t o = Core+      { cSpends :: Map t [o],+        cSpender :: Map o t,+        cKids :: Map t (Set t)+      } @-}++-------------------------------------------------------------------------------+-- "Data.Map", as far as this goes+-------------------------------------------------------------------------------++-- A lookup, a map without a key, without a set of keys, with a member+-- taken out of every set, and without its empty sets. Each has a name in+-- the types that are checked, and the functions below are what the rest+-- of the module calls.+{-@ measure look :: Map k v -> k -> Maybe v @-}+{-@ measure gone :: Map k v -> k -> Map k v @-}+{-@ measure less :: Map k v -> Set k -> Map k v @-}+{-@ measure wout :: Map k (Set t) -> t -> Map k (Set t) @-}+{-@ measure full :: Map k (Set t) -> Map k (Set t) @-}+{-@ measure ins :: Maybe [o] -> Set o @-}++{-@ assume mLookup :: (Ord k) => x:k -> m:Map k v -> {r:Maybe v | r == look m x} @-}+mLookup :: (Ord k) => k -> Map k v -> Maybe v+mLookup = Map.lookup++{-@ assume mDelete :: (Ord k) => x:k -> m:Map k v -> {n:Map k v | n == gone m x} @-}+mDelete :: (Ord k) => k -> Map k v -> Map k v+mDelete = Map.delete++{-@ assume mLess :: (Ord k) => s:Set k -> m:Map k v -> {n:Map k v | n == less m s} @-}+mLess :: (Ord k) => Set k -> Map k v -> Map k v+mLess s m = Map.withoutKeys m s++{-@ assume mWithout :: (Ord t) => x:t -> m:Map k (Set t) -> {n:Map k (Set t) | n == wout m x} @-}+mWithout :: (Ord t) => t -> Map k (Set t) -> Map k (Set t)+mWithout x = Map.map (\s -> Set.difference s (Set.singleton x))++{-@ assume mFull :: (Ord t) => m:Map k (Set t) -> {n:Map k (Set t) | n == full m} @-}+mFull :: (Ord t) => Map k (Set t) -> Map k (Set t)+mFull = Map.filter (/= Set.empty)++-- | What a key has once a member is taken out of every set: the set that+-- it had without that member, and no set if it had none.++{-@ reflect minus @-}+minus :: (Ord t) => t -> Maybe (Set t) -> Maybe (Set t)+minus _ Nothing = Nothing+minus x (Just s) = Just (Set.difference s (Set.singleton x))++-- | What a key has once the empty sets are dropped: the set that it had+-- if that was not empty, and nothing otherwise.++{-@ reflect kept @-}+kept :: (Ord t) => Maybe (Set t) -> Maybe (Set t)+kept Nothing = Nothing+kept (Just s) = if s == Set.empty then Nothing else Just s++-- | The outputs that a transaction spends, as a set: none for a+-- transaction that the pool does not have.++{-@ assume spentBy :: (Ord o) => r:Maybe [o] -> {s:Set o | s == ins r} @-}+spentBy :: (Ord o) => Maybe [o] -> Set o+spentBy = maybe Set.empty Set.fromList++-- | Assumed: a map without a key has nothing at that key, and at any+-- other what it had.++{-@ assume lookGone :: m:Map k v -> x:k -> y:k+      -> {look (gone m x) y == (if y == x then Nothing else look m y)} @-}+lookGone :: Map k v -> k -> k -> ()+lookGone _ _ _ = ()++-- | Assumed: a map without a set of keys has nothing at a key of the set,+-- and at any other what it had.++{-@ assume lookLess :: m:Map k v -> s:Set k -> y:k+      -> {look (less m s) y == (if Set_mem y s then Nothing else look m y)} @-}+lookLess :: Map k v -> Set k -> k -> ()+lookLess _ _ _ = ()++-- | Assumed: with a member taken out of every set, a key has the set that+-- it had without that member, and no set if it had none.++{-@ assume lookWout :: m:Map k (Set t) -> x:t -> y:k -> {look (wout m x) y == minus x (look m y)} @-}+lookWout :: Map k (Set t) -> t -> k -> ()+lookWout _ _ _ = ()++-- | Assumed: without its empty sets, a map has at a key the set that it+-- had if that was not empty, and nothing otherwise.++{-@ assume lookFull :: m:Map k (Set t) -> y:k -> {look (full m) y == kept (look m y)} @-}+lookFull :: Map k (Set t) -> k -> ()+lookFull _ _ = ()++-- | Assumed: two maps that give the same at every key are the same map.++{-@ assume same :: m:Map k v -> n:Map k v -> (y:k -> {look m y == look n y}) -> {m == n} @-}+same :: Map k v -> Map k v -> (k -> ()) -> ()+same _ _ _ = ()++-------------------------------------------------------------------------------+-- Taking one transaction out+-------------------------------------------------------------------------------++-- | Take one transaction out of the three maps, leaving what spends it:+-- it spends nothing any more, nothing is spent by it, and it spends from+-- no transaction. A transaction from which nothing spends any more has no+-- set left.++{-@ removeCore :: (Ord t, Ord o) => x:t -> c:Core t o+      -> {d:Core t o | cSpends d == gone (cSpends c) x+                    && cSpender d == less (cSpender c) (ins (look (cSpends c) x))+                    && cKids d == full (wout (cKids c) x)} @-}+removeCore :: (Ord t, Ord o) => t -> Core t o -> Core t o+removeCore x (Core spends spender kids) =+  Core (mDelete x spends) (mLess (spentBy (mLookup x spends)) spender) (mFull (mWithout x kids))++-------------------------------------------------------------------------------+-- Any order+-------------------------------------------------------------------------------++-- | Two facts, both known where this is used.+both :: () -> () -> ()+both _ _ = ()++-- | Proved: at any key, deleting two keys in one order gives what+-- deleting them in the other gives.++{-@ goneAt :: (Ord k) => m:Map k v -> a:k -> b:k -> y:k+      -> {look (gone (gone m b) a) y == look (gone (gone m a) b) y} @-}+goneAt :: (Ord k) => Map k v -> k -> k -> k -> ()+goneAt m a b y =+  both+    (both (lookGone (mDelete b m) a y) (lookGone m b y))+    (both (lookGone (mDelete a m) b y) (lookGone m a y))++-- | Proved: at any key, taking two sets of keys out in one order gives+-- what taking them out in the other gives.++{-@ lessAt :: (Ord k) => m:Map k v -> s:Set k -> u:Set k -> y:k+      -> {look (less (less m u) s) y == look (less (less m s) u) y} @-}+lessAt :: (Ord k) => Map k v -> Set k -> Set k -> k -> ()+lessAt m s u y =+  both+    (both (lookLess (mLess u m) s y) (lookLess m u y))+    (both (lookLess (mLess s m) u y) (lookLess m s y))++-- | Proved: for what one key has, taking two members out, dropping the+-- set each time that it is empty, gives the same in either order. A set+-- that the first leaves empty is dropped at once, and the second then+-- finds none; taken the other way round, the second leaves a set that the+-- first empties, and it is dropped then.++{-@ swap :: (Ord t) => a:t -> b:t -> v:Maybe (Set t)+      -> {kept (minus a (kept (minus b v))) == kept (minus b (kept (minus a v)))} @-}+swap :: (Ord t) => t -> t -> Maybe (Set t) -> ()+swap _ _ Nothing = ()+swap a b (Just s)+  | withoutB == Set.empty && withoutA == Set.empty = ()+  | withoutB == Set.empty = ()+  | withoutA == Set.empty = ()+  | otherwise = ()+  where+    withoutA = Set.difference s (Set.singleton a)+    withoutB = Set.difference s (Set.singleton b)++-- | Proved: at any key, taking two transactions out of the sets of those+-- that spend from each transaction, and dropping the empty sets each+-- time, gives the same in either order.++{-@ kidsAt :: (Ord k, Ord t) => m:Map k (Set t) -> a:t -> b:t -> y:k+      -> {look (full (wout (full (wout m b)) a)) y == look (full (wout (full (wout m a)) b)) y} @-}+kidsAt :: (Ord k, Ord t) => Map k (Set t) -> t -> t -> k -> ()+kidsAt m a b y =+  both (swap a b (mLookup y m)) $+    both+      ( both+          (both (lookFull (mWithout a (mFull (mWithout b m))) y) (lookWout (mFull (mWithout b m)) a y))+          (both (lookFull (mWithout b m) y) (lookWout m b y))+      )+      ( both+          (both (lookFull (mWithout b (mFull (mWithout a m))) y) (lookWout (mFull (mWithout a m)) b y))+          (both (lookFull (mWithout a m) y) (lookWout m a y))+      )++-- | Proved: taking one transaction out and then another leaves the same+-- three maps as taking them out the other way round.+--+-- The one thing that could differ is what the second is found to spend,+-- since the first is gone by then: it does not, because a transaction+-- that is not the first one spends what it spent before+-- (@lookGone@).++{-@ anyOrder :: (Ord t, Ord o) => a:t -> b:t -> c:Core t o+      -> {r:(Core t o, Core t o) | cSpends (fst r) == cSpends (snd r)+                                && cSpender (fst r) == cSpender (snd r)+                                && cKids (fst r) == cKids (snd r)} @-}+anyOrder :: (Ord t, Ord o) => t -> t -> Core t o -> (Core t o, Core t o)+anyOrder a b c@(Core spends spender kids)+  | a == b = (removeCore a (removeCore b c), removeCore b (removeCore a c))+  | otherwise =+      const+        (removeCore a (removeCore b c), removeCore b (removeCore a c))+        ( both+            ( both+                (same (mDelete a (mDelete b spends)) (mDelete b (mDelete a spends)) (goneAt spends a b))+                (both (lookGone spends b a) (lookGone spends a b))+            )+            ( both+                ( same+                    (mLess sa (mLess sb spender))+                    (mLess sb (mLess sa spender))+                    (lessAt spender sa sb)+                )+                ( same+                    (mFull (mWithout a (mFull (mWithout b kids))))+                    (mFull (mWithout b (mFull (mWithout a kids))))+                    (kidsAt kids a b)+                )+            )+        )+  where+    sa = spentBy (mLookup a spends)+    sb = spentBy (mLookup b spends)
+ src/Haskoin/Store/Fleet/Pool/Types.hs view
@@ -0,0 +1,129 @@+-- |+-- Module      : Haskoin.Store.Fleet.Pool.Types+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- What goes to the shared mempool in Redis and comes back from it, as the+-- stores of a fleet agree on it: transactions with what they do at+-- addresses and to tokens, what blocks did to the pool, and what became of+-- an offer or of a move of the tip. In a module of its own so that the+-- decisions ("Haskoin.Store.Fleet.Pool.Decide") and what carries them out+-- ("Haskoin.Store.Fleet.Redis") share it.+module Haskoin.Store.Fleet.Pool.Types+  ( Moved (..),+    Offered (..),+    PoolEntry (..),+    PoolTokenOut (..),+    PoolTx (..),+    PoolChange (..),+  )+where++import Data.ByteString (ByteString)+import Data.Word (Word32, Word64)++-- | What became of an attempt to move the tip; see+-- t'Haskoin.Store.Fleet.Move'.+data Moved+  = -- | the tip is now this block+    MovedTo !ByteString+  | -- | the tip is where the live stores agree, or they agree on nothing+    Stays+  | -- | another store moved the tip first+    Raced+  | -- | the pool still has transactions that the last move marked as+    -- leaving: they are taken out first+    Leaving+  deriving (Eq, Show)++-- | What became of an offer; see t'Haskoin.Store.Fleet.Pool.Offer'.+data Offered+  = -- | it is in the pool now+    Taken+  | -- | it was there already+    Known+  | -- | these transactions of the pool spend what it spends+    Conflict ![ByteString]+  | -- | these outputs are neither made by the pool nor unspent at the tip+    Orphan ![ByteString]+  | -- | the tip is not the one that the store checked the transaction+    -- against: check again and offer again+    Late+  deriving (Eq, Show)++-- | What a transaction does at an address; see+-- t'Haskoin.Store.Fleet.Pool.Entry'. Addresses, outputs and scripts are+-- whatever bytes the stores of a fleet agree on.+data PoolEntry+  = -- | it spends from the address or pays to it+    PoolTouches !ByteString+  | -- | it spends this output of the address, of this amount+    PoolSpends !ByteString !ByteString !Word64+  | -- | it pays this output to the address, with this amount and script+    PoolPays !ByteString !ByteString !Word64 !ByteString+  | -- | it makes an output that holds tokens (CashTokens)+    PoolMakes !PoolTokenOut+  | -- | it uses up an output that holds tokens+    PoolUses !PoolTokenOut+  deriving (Eq, Show)++-- | An output that holds tokens, as an entry of the pool gives it, so that+-- the scripts in Redis never read the token prefix of a script.+data PoolTokenOut = PoolTokenOut+  { -- | the address of the output, if it has one+    address :: !(Maybe ByteString),+    output :: !ByteString,+    category :: !ByteString,+    -- | fungible tokens+    amount :: !Word64,+    -- | whether it also holds a non-fungible token+    nft :: !Bool,+    -- | the value of the output and its script: what the pool keeps of an+    -- output that it makes, to list it with the category. Not given for+    -- an output that it uses up.+    coins :: !(Maybe (Word64, ByteString))+  }+  deriving (Eq, Show)++-- | A transaction as the pool keeps it.+data PoolTx = PoolTx+  { txid :: !ByteString,+    -- | when it entered the mempool of the store that offers it. The pool+    -- keeps the time of the first offer, so that every store lists the+    -- transaction in the same place.+    time :: !Word64,+    -- | the outputs that it spends, in the order of its inputs+    inputs :: ![ByteString],+    -- | what a store needs to answer about it+    body :: !ByteString,+    -- | what it does at each address+    entries :: ![PoolEntry]+  }+  deriving (Eq, Show)++-- | What the blocks between two tips did; see+-- 'Haskoin.Store.Fleet.Pool.Change'.+data PoolChange = PoolChange+  { -- | transactions that come back+    returned :: ![PoolTx],+    -- | transactions of abandoned blocks that cannot come back+    gone :: ![ByteString],+    -- | transactions that the new blocks confirm+    confirmed :: ![ByteString],+    -- | outputs that the new blocks spend, each followed by the transaction+    -- of the block that spends it and the height of that block in four+    -- bytes, big-endian: what replaces a transaction of the pool that+    -- spends it ('Haskoin.Store.Fleet.Pool.advanceReplacing')+    spent :: ![ByteString],+    -- | the height of the block that the tip moves to, by which what was+    -- replaced 2016 blocks before is forgotten, if it is known+    height :: !(Maybe Word32),+    -- | transactions of the abandoned blocks that the store has as+    -- replaced, each followed like an output of 'spent' by what replaced+    -- it: kept as replaced once the tip reaches it+    lost :: ![ByteString]+  }+  deriving (Eq, Show)
src/Haskoin/Store/Fleet/Redis.hs view
@@ -9,19 +9,27 @@ -- Portability : POSIX -- -- The rules of "Haskoin.Store.Fleet" carried out against Redis: the state--- of a fleet in three keys, and a Lua script for each step that has to be--- one step.+-- of a fleet in three keys, and each change that has to be one step made+-- one. ----- = Why scripts+-- = Why one step -- -- Whether a store may report depends on the tip and on the leases of the -- others, and the block that the tip moves to depends on every report. Read -- and written in separate commands, each could change in between: two -- stores would both find themselves alone, or the tip would move to a block -- that a store had just stopped reporting. Redis runs a script without--- letting anything else in, so each rule sees one state and changes it at--- once.+-- letting anything else in, so a rule that is a script sees one state and+-- changes it at once. --+-- The reports and the move of the tip alone are short Lua scripts. The+-- changes to the shared mempool, and the move of the tip with the pool,+-- are decisions made in Haskell ("Haskoin.Store.Fleet.Pool.Decide") and+-- carried out by one script that decides nothing+-- ("Haskoin.Store.Fleet.Atomic"): a script of eight hundred lines that+-- failed half way left the pool half changed, and its rules had to be kept+-- twice.+-- -- = Whose clock -- -- Leases are measured on the clock of Redis, read inside the scripts. The@@ -36,8 +44,9 @@ -- -- = The shared mempool ----- The rules of "Haskoin.Store.Fleet.Pool" are one more script, with the--- pool in keys next to those of the tip. A transaction is its id, of one+-- The rules of "Haskoin.Store.Fleet.Pool" are the decisions of+-- "Haskoin.Store.Fleet.Pool.Decide", with the pool in keys next to those+-- of the tip. A transaction is its id, of one -- fixed size, and an output is the id of the transaction that made it and -- four more bytes. An offer says which tip the store checked the -- transaction against, and is turned away if the tip has moved since: what@@ -45,8 +54,8 @@ -- changing the pool for the blocks in between is one step ('fleetAdvance'), -- so that no request finds a block without what it did to the pool. ----- A transaction comes with what it does at each address (t'PoolEntry'),--- and the script keeps what the pool holds for each address in step: its+-- A transaction comes with what it does at each address, a t'PoolEntry'+-- for each, and the pool keeps what it holds for each address in step: its -- transactions and the outputs paid to it, each in a sorted set ordered as -- queries list them, the outputs of it that are spent, and the sums that a -- balance needs. 'Haskoin.Store.Fleet.Pool.addresses' says what those@@ -55,6 +64,13 @@ -- every entry of the address, which is what the store's own mempool area -- did at first and was measured to be thousands of times too slow for a -- busy address.+--+-- The tokens of Bitcoin Cash come the same way: each output that holds+-- some and that a transaction makes or uses up is an entry, a+-- t'PoolTokenOut' with its category and amounts read by the store, and+-- the script keeps for each category its transactions and outputs, and for+-- each address and category the sums that a token balance needs.+-- 'Haskoin.Store.Fleet.Pool.tokenTotals' says what those should be. module Haskoin.Store.Fleet.Redis   ( FleetKeys (..),     fleetKeys,@@ -69,10 +85,16 @@     PoolChange (..),     PoolTx (..),     PoolEntry (..),+    PoolTokenOut (..),     poolOffer,     poolWithdraw,+    poolExpire,+    poolLeaving,+    poolTakeOut,     fleetAdvance,     fleetCommit,+    fleetCommitTelling,+    Attempt (..),     fleetRestart,     fleetRestarts,     FleetEvent (..),@@ -82,9 +104,8 @@     poolBody,     poolRead, -    -- * What the fleet has seen-    fleetTrimSeen,-    fleetSeen,+    -- * What is settled+    fleetSettled,      -- * Scripts     Script,@@ -93,18 +114,19 @@   ) where -import Control.Monad.IO.Class (liftIO) import Data.ByteString (ByteString) import Data.ByteString qualified as B import Data.ByteString.Char8 qualified as C import Data.FileEmbed (embedFile, makeRelativeToProject)-import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.Maybe (fromMaybe, isJust)-import Data.Word (Word32, Word64)-import Database.Redis (Connection, Redis, RedisResult, Reply (..))+import Database.Redis (Connection, Redis, Reply (..)) import Database.Redis qualified as R import Haskoin.Store.Fleet (Time)-import System.IO.Unsafe (unsafePerformIO)+import Haskoin.Store.Fleet.Atomic (Atomic)+import Haskoin.Store.Fleet.Atomic.Redis (Attempt (..), insist, transact, transactTelling)+import Haskoin.Store.Fleet.Pool.Decide qualified as D+import Haskoin.Store.Fleet.Pool.Types+import Haskoin.Store.Fleet.Script (Script, evalScript, script)  -- | The keys of a fleet in Redis, and the size of its blocks in bytes. data FleetKeys = FleetKeys@@ -134,16 +156,6 @@       size     } --- | What became of an attempt to move the tip; see 'Haskoin.Store.Fleet.Move'.-data Moved-  = -- | the tip is now this block-    MovedTo !ByteString-  | -- | the tip is where the live stores agree, or they agree on nothing-    Stays-  | -- | another store moved the tip first-    Raced-  deriving (Eq, Show)- -- | Report the recent blocks of a store, newest first, under a lease of so -- many milliseconds, given the blocks that the store has views of. Says -- whether the report was taken: it is not when the store has no view of the@@ -175,77 +187,6 @@ fleetLive :: Connection -> FleetKeys -> IO [(ByteString, Time)] fleetLive conn keys = map (fmap (maybe 0 (fromIntegral . fst) . C.readInteger)) <$> run conn (R.hgetall keys.lease) --- | What became of an offer; see 'Haskoin.Store.Fleet.Pool.Offer'.-data Offered-  = -- | it is in the pool now-    Taken-  | -- | it was there already-    Known-  | -- | these transactions of the pool spend what it spends-    Conflict ![ByteString]-  | -- | these outputs are neither made by the pool nor unspent at the tip-    Orphan ![ByteString]-  | -- | the tip is not the one that the store checked the transaction-    -- against: check again and offer again-    Late-  deriving (Eq, Show)---- | What a transaction does at an address; see--- 'Haskoin.Store.Fleet.Pool.Entry'. Addresses, outputs and scripts are--- whatever bytes the stores of a fleet agree on.-data PoolEntry-  = -- | it spends from the address or pays to it-    PoolTouches !ByteString-  | -- | it spends this output of the address, of this amount-    PoolSpends !ByteString !ByteString !Word64-  | -- | it pays this output to the address, with this amount and script-    PoolPays !ByteString !ByteString !Word64 !ByteString-  deriving (Eq, Show)---- | A transaction as the pool keeps it.-data PoolTx = PoolTx-  { txid :: !ByteString,-    -- | when it entered the mempool of the store that offers it. The pool-    -- keeps the time of the first offer, so that every store lists the-    -- transaction in the same place.-    time :: !Word64,-    -- | the outputs that it spends, in the order of its inputs-    inputs :: ![ByteString],-    -- | what a store needs to answer about it-    body :: !ByteString,-    -- | whether it says itself that it can be replaced by fee. Whether it-    -- can also depends on the transactions of the pool that it spends-    -- from, which the pool works out and keeps right as those come and go.-    signals :: !Bool,-    -- | what it does at each address-    entries :: ![PoolEntry]-  }-  deriving (Eq, Show)---- | What the blocks between two tips did; see--- 'Haskoin.Store.Fleet.Pool.Change'.-data PoolChange = PoolChange-  { -- | transactions that come back-    returned :: ![PoolTx],-    -- | transactions of abandoned blocks that cannot come back-    gone :: ![ByteString],-    -- | transactions that the new blocks confirm-    confirmed :: ![ByteString],-    -- | outputs that the new blocks spend, each followed by the transaction-    -- of the block that spends it and the height of that block in four-    -- bytes, big-endian: what replaces a transaction of the pool that-    -- spends it ('Haskoin.Store.Fleet.Pool.advanceReplacing')-    spent :: ![ByteString],-    -- | the height of the block that the tip moves to, by which what was-    -- replaced 2016 blocks before is forgotten, if it is known-    height :: !(Maybe Word32),-    -- | transactions of the abandoned blocks that the store has as-    -- replaced, each followed like an output of 'spent' by what replaced-    -- it: kept as replaced once the tip reaches it-    lost :: ![ByteString]-  }-  deriving (Eq, Show)- -- | Offer a transaction to the pool: given the size of a transaction id, -- the tip that the store checked against, the transaction, whether the -- store finds each output that it spends unspent at that tip, in the order@@ -260,51 +201,50 @@   [ByteString] ->   IO Offered poolOffer conn keys tsize seen tx unspents replaced =-  run conn (evalScript poolScript [] args) >>= \case-    ["taken"] -> return Taken-    ["known"] -> return Known-    "conflict" : rivals -> return (Conflict rivals)-    "orphan" : outputs -> return (Orphan outputs)-    ["raced"] -> return Late-    other -> fail ("Unexpected answer of the pool script: " <> show (other :: [ByteString]))-  where-    flags = C.pack [if unspent then '1' else '0' | unspent <- unspents]-    args = ["offer", keys.prefix, num tsize, maybe "" id seen, flags, B.concat replaced] <> txArgs tx+  fromMaybe Late <$> transact conn 5 (D.offer (D.poolKeys keys.prefix tsize) seen unspents replaced tx)  -- | Take transactions out of the pool, with all that spends them. Gives -- those that left. poolWithdraw :: Connection -> FleetKeys -> Int -> [ByteString] -> IO [ByteString]-poolWithdraw conn keys tsize ts =-  run conn (evalScript poolScript [] ["withdraw", keys.prefix, num tsize, B.concat ts])+poolWithdraw conn keys tsize ts = insist conn (D.withdraw (D.poolKeys keys.prefix tsize) ts) --- | Keep the newest of the transactions that the fleet has seen, so--- many. Gives how many are kept.------ The fleet keeps, in one sorted set, each transaction that the pool has--- decided on: each that entered it, that an offer found in it or in--- conflict with it, and that left it unconfirmed, by the time at which it--- was first seen. No store fetches one of them when a peer announces it--- ('fleetSeen'). The pool's script adds them, with @ZADD NX@, in the step--- that decides, so a transaction that a store received and has not offered--- is not in the set: if the store stops first, another fetches it. In--- Redis, the set is the same for every store and outlives a store that--- restarts; in the memory of each store, as it was before, every store--- fetched each transaction once, and again after a restart. The set is--- trimmed here, when it has grown a hundredth past its bound, and not on--- every addition.-fleetTrimSeen :: Connection -> FleetKeys -> Int -> IO Integer-fleetTrimSeen conn keys most =-  run conn (evalScript poolScript [] ["trim", keys.prefix, "0", num most])+-- | Take out of the pool what has been in it since before a time, in+-- seconds of the clock of Redis, so many at most, with all that spends+-- them, choosing and withdrawing them in one call. Gives those that left.+poolExpire :: Connection -> FleetKeys -> Int -> Integer -> Int -> IO [ByteString]+poolExpire conn keys tsize before most = insist conn (D.expire (D.poolKeys keys.prefix tsize) before most) --- | Of these transactions, which the fleet has seen ('fleetTrimSeen'), in one--- round trip.-fleetSeen :: Connection -> FleetKeys -> [ByteString] -> IO [Bool]-fleetSeen _ _ [] = return []-fleetSeen conn keys ts =-  map isJust <$> run conn scores+-- | The transactions that a move of the tip marked as leaving and that+-- the pool still has ('Haskoin.Store.Fleet.Pool.Decide.takeOut').+poolLeaving :: Connection -> FleetKeys -> IO [ByteString]+poolLeaving conn keys = run conn (R.hkeys (keys.prefix <> "pool:leaving"))++-- | Take some of them out of the pool: how many of these were marked.+-- One that another store took out first counts for nothing.+poolTakeOut :: Connection -> FleetKeys -> Int -> [ByteString] -> IO Int+poolTakeOut conn keys tsize ts = insist conn (D.takeOut (D.poolKeys keys.prefix tsize) ts)++-- | Of these transactions, which are settled: those that the pool has.+--+-- A node names a transaction because it has it, and the pool is to have+-- what the nodes of its stores have. So a transaction that a node names+-- and that the pool has not is fetched and offered, whatever became of it+-- before: the pool, with the chain as the store has it, then says what it+-- is ('Haskoin.Store.Fleet.Member.memberOffer').+--+-- The fleet kept a set of what its pool had decided on, once, the newest+-- hundred thousand (@fleet:seen@), and what was in it counted as settled+-- too, so that no store fetched it again. A transaction that was+-- remembered and that the pool did not have was then never fetched,+-- whichever way it had come to that: a server did not take a transaction+-- that its own node held for hours, and read the whole mempool of the+-- node again without taking it. The set is no longer kept.+fleetSettled :: Connection -> FleetKeys -> [ByteString] -> IO [Bool]+fleetSettled _ _ [] = return []+fleetSettled conn keys ts = map isJust <$> run conn held   where-    scores :: Redis (Either Reply [Maybe ByteString])-    scores = R.sendRequest ("ZMSCORE" : keys.prefix <> "fleet:seen" : ts)+    held :: Redis (Either Reply [Maybe ByteString])+    held = R.sendRequest ("ZMSCORE" : keys.prefix <> "pool:time" : ts)  -- | Move the tip to a block and bring the pool there, in one step: given -- the tip that the caller saw, the block, which must be the one that the@@ -325,13 +265,15 @@   FleetKeys ->   Int ->   Maybe Time ->+  -- | the name of the store that moves the tip+  ByteString ->   Maybe ByteString ->   ByteString ->   Maybe PoolChange ->   [ByteString] ->   IO Moved-fleetAdvance conn keys tsize clock seen target known path =-  fleetCommit conn keys tsize clock seen target known path ""+fleetAdvance conn keys tsize clock store seen target known path =+  fleetCommit conn keys tsize clock store seen target known path ""  -- | 'fleetAdvance' as the commit of a move of the tip with the cache of -- extended public keys: given also the token of the move of the cache that@@ -347,18 +289,37 @@   FleetKeys ->   Int ->   Maybe Time ->+  -- | the name of the store that moves the tip: without a change of the+  -- pool, it empties the pool only if it is the one store that is live+  ByteString ->   Maybe ByteString ->   ByteString ->   Maybe PoolChange ->   [ByteString] ->   ByteString ->   IO Moved-fleetCommit conn keys tsize clock seen target known path token =-  advance conn keys tsize clock seen target how (fromMaybe unchanged known) (path, token)-  where-    how = maybe "1" (const "0") known-    unchanged = PoolChange [] [] [] [] Nothing []+fleetCommit = fleetCommitTelling (\_ -> return ()) +-- | 'fleetCommit', telling of each time that the move was decided what+-- that cost and, if it was not carried out, which question had another+-- answer by then ('transactTelling'): what a store says of a tip that+-- does not move, or moves slowly.+fleetCommitTelling ::+  (Attempt -> IO ()) ->+  Connection ->+  FleetKeys ->+  Int ->+  Maybe Time ->+  ByteString ->+  Maybe ByteString ->+  ByteString ->+  Maybe PoolChange ->+  [ByteString] ->+  ByteString ->+  IO Moved+fleetCommitTelling tell conn keys tsize clock store seen target known path token =+  advance tell conn keys tsize clock seen target (maybe (D.AloneNotKnowing store) D.Changing known) (path, token)+ -- | Move the tip to a block and empty the pool, for a store that has both -- the tip and the block and finds the way between them longer than it -- goes through.@@ -368,13 +329,12 @@ -- none would ever say what the blocks did, and the tip would stay where it -- is for good: a fleet whose stores came back together after half a day -- away answered nothing from then on. Emptying the pool costs the--- transactions that were in it until the stores fill it again: what the--- fleet has seen is forgotten with it, and the count of 'fleetRestarts'--- goes up, so that each store reads the mempool of its node and asks its+-- transactions that were in it until the stores fill it again: the+-- count of 'fleetRestarts' goes up, so that each store reads the mempool of its node and asks its -- peers for theirs. fleetRestart :: Connection -> FleetKeys -> Int -> Maybe Time -> Maybe ByteString -> ByteString -> IO Moved fleetRestart conn keys tsize clock seen target =-  advance conn keys tsize clock seen target "2" (PoolChange [] [] [] [] Nothing []) ([], "")+  advance (\_ -> return ()) conn keys tsize clock seen target D.TooLong ([], "")  -- | How many times the pool was emptied, by 'fleetRestart' or by a store -- alone that did not have the old tip. A store that sees another number@@ -385,43 +345,45 @@ fleetRestarts conn keys =   maybe 0 (maybe 0 fst . C.readInteger) <$> run conn (R.get (keys.prefix <> "fleet:restarts")) --- | The advance of the pool script, with its way of treating the pool: "0"--- to change it, "1" and "2" to empty it ('fleetAdvance', 'fleetRestart').+-- | A move of the tip with the pool and the cache, as one decision+-- ('Haskoin.Store.Fleet.Pool.Decide.advance'). Another store that changes+-- what the decision asked about makes it be decided again, three times at+-- most: then the move is 'Raced', and the store tries at its next turn. advance ::+  (Attempt -> IO ()) ->   Connection ->   FleetKeys ->   Int ->   Maybe Time ->   Maybe ByteString ->   ByteString ->-  ByteString ->-  PoolChange ->+  D.How ->   ([ByteString], ByteString) ->   IO Moved-advance conn keys tsize clock seen target how change (path, token) =-  run conn (evalScript poolScript [] args) >>= \case-    ["moved"] -> return (MovedTo target)-    ["stays"] -> return Stays-    ["raced"] -> return Raced-    other -> fail ("Unexpected answer of the pool script: " <> show (other :: [ByteString]))+advance tell conn keys tsize clock seen target how (path, token) =+  fromMaybe Raced <$> transactTelling conn 3 tell decision   where-    args =-      ["advance", keys.prefix, num tsize, maybe "" id seen, target, maybe "" num clock, num keys.size, how]-        <> [maybe "" num change.height]-        <> [B.concat change.gone, B.concat change.confirmed, B.concat change.spent, B.concat change.lost]-        <> [num (length change.returned)]-        <> concatMap txArgs change.returned-        <> [B.concat path, token]+    decision :: (Monad m) => Atomic m Moved+    decision = D.advance (D.poolKeys keys.prefix tsize) seen target (fromIntegral <$> clock) keys.size how path token  -- | Read from the pool as it is at a tip: given the size of a transaction -- id, the tip that the caller answers from, what to read and its arguments, -- as @read.lua@ takes them. 'Nothing' if the tip is another one by now. poolRead :: Connection -> FleetKeys -> Int -> Maybe ByteString -> ByteString -> [ByteString] -> IO (Maybe [ByteString])-poolRead conn keys tsize tip what args =-  run conn (evalScript readScript [] (what : keys.prefix : num tsize : maybe "" id tip : args)) >>= \case-    "ok" : rows -> return (Just rows)-    ["raced"] -> return Nothing-    other -> fail ("Unexpected answer of the read script: " <> show (take 1 other))+--+-- A read that would go by transactions that a move of the tip marked as+-- leaving takes those out first ('poolTakeOut'), and reads again: the+-- chain has them at that tip, and the pool is read as it is without them.+poolRead conn keys tsize tip what args = go (1000 :: Int)+  where+    go tries =+      run conn (evalScript readScript [] (what : keys.prefix : num tsize : maybe "" id tip : args)) >>= \case+        "ok" : rows -> return (Just rows)+        ["raced"] -> return Nothing+        "leaving" : ts+          | tries > 0 -> poolTakeOut conn keys tsize ts >> go (tries - 1)+          | otherwise -> fail "The shared mempool does not let go of what a block took out of it"+        other -> fail ("Unexpected answer of the read script: " <> show (take 1 other))  -- | Something that happened to the fleet, as every store of it tells its -- clients.@@ -469,17 +431,6 @@     pairs (R.Bulk (Just k) : R.Bulk (Just v) : more) = (k, v) : pairs more     pairs _ = [] --- | A transaction as the arguments of the pool script.-txArgs :: PoolTx -> [ByteString]-txArgs tx =-  [tx.txid, num tx.time, B.concat tx.inputs, tx.body, if tx.signals then "1" else "0", num (length tx.entries)]-    <> concatMap entry tx.entries-  where-    entry = \case-      PoolTouches a -> ["t", a, "", "", ""]-      PoolSpends a o v -> ["s", a, o, num v, ""]-      PoolPays a o v s -> ["o", a, o, num v, s]- -- | The transactions of the pool, each with the outputs that it spends one -- after the other. poolSpends :: Connection -> FleetKeys -> IO [(ByteString, ByteString)]@@ -502,44 +453,6 @@     Right x -> return x     Left e -> fail ("Redis error: " <> show e) --- | A Lua script that Redis keeps compiled under its digest.------ @EVAL@ sends the whole script with every call, and Redis hashes it every--- time to find it compiled: for the scripts of the pool, several kilobytes--- for a read of a few bytes. That was most of what Redis did for a simple--- request, and Redis has one thread for the whole fleet. So a script is--- loaded once, its digest kept here, and called by it with @EVALSHA@. A--- Redis that lost its scripts, as one that restarted, says @NOSCRIPT@, and--- the script is loaded again. The digest is the same on every Redis, so--- one is kept for the program, not for each connection.-data Script = Script-  { source :: !ByteString,-    digest :: !(IORef (Maybe ByteString))-  }---- | A script of this source. Only for a top-level binding marked NOINLINE,--- so that there is one of each script.-script :: ByteString -> Script-script s = unsafePerformIO (Script s <$> newIORef Nothing)-{-# NOINLINE script #-}---- | Run a script, as 'R.eval' does, by its digest.-evalScript :: (RedisResult a) => Script -> [ByteString] -> [ByteString] -> Redis (Either Reply a)-evalScript sc keys args =-  liftIO (readIORef sc.digest) >>= \case-    Nothing -> load-    Just sha ->-      R.evalsha sha keys args >>= \case-        Left (Error e) | "NOSCRIPT" `B.isPrefixOf` e -> load-        r -> return r-  where-    load =-      R.scriptLoad sc.source >>= \case-        Left e -> return (Left e)-        Right sha -> do-          liftIO (writeIORef sc.digest (Just sha))-          R.evalsha sha keys args- -- | 'Haskoin.Store.Fleet.mayReport' and 'Haskoin.Store.Fleet.report' in one -- step. reportScript :: Script@@ -556,9 +469,3 @@ readScript :: Script readScript = script $(makeRelativeToProject "src/Haskoin/Store/Fleet/lua/read.lua" >>= embedFile) {-# NOINLINE readScript #-}---- | 'Haskoin.Store.Fleet.Pool.offer', 'Haskoin.Store.Fleet.Pool.withdraw',--- and 'Haskoin.Store.Fleet.Pool.advance' with the move of the tip.-poolScript :: Script-poolScript = script $(makeRelativeToProject "src/Haskoin/Store/Fleet/lua/pool.lua" >>= embedFile)-{-# NOINLINE poolScript #-}
+ src/Haskoin/Store/Fleet/Script.hs view
@@ -0,0 +1,62 @@+-- |+-- Module      : Haskoin.Store.Fleet.Script+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- Lua scripts that Redis keeps compiled, called by their digest: what+-- every module that runs a script of the fleet shares.+module Haskoin.Store.Fleet.Script+  ( Script,+    script,+    evalScript,+  )+where++import Control.Monad.IO.Class (liftIO)+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Database.Redis (Redis, RedisResult, Reply (..))+import Database.Redis qualified as R+import System.IO.Unsafe (unsafePerformIO)++-- | A Lua script that Redis keeps compiled under its digest.+--+-- @EVAL@ sends the whole script with every call, and Redis hashes it every+-- time to find it compiled: for the scripts of the pool, several kilobytes+-- for a read of a few bytes. That was most of what Redis did for a simple+-- request, and Redis has one thread for the whole fleet. So a script is+-- loaded once, its digest kept here, and called by it with @EVALSHA@. A+-- Redis that lost its scripts, as one that restarted, says @NOSCRIPT@, and+-- the script is loaded again. The digest is the same on every Redis, so+-- one is kept for the program, not for each connection.+data Script = Script+  { source :: !ByteString,+    digest :: !(IORef (Maybe ByteString))+  }++-- | A script of this source. Only for a top-level binding marked NOINLINE,+-- so that there is one of each script.+script :: ByteString -> Script+script s = unsafePerformIO (Script s <$> newIORef Nothing)+{-# NOINLINE script #-}++-- | Run a script by its digest, as @EVAL@ runs one by its source.+evalScript :: (RedisResult a) => Script -> [ByteString] -> [ByteString] -> Redis (Either Reply a)+evalScript sc keys args =+  liftIO (readIORef sc.digest) >>= \case+    Nothing -> load+    Just sha ->+      R.evalsha sha keys args >>= \case+        Left (Error e) | "NOSCRIPT" `B.isPrefixOf` e -> load+        r -> return r+  where+    load =+      R.scriptLoad sc.source >>= \case+        Left e -> return (Left e)+        Right sha -> do+          liftIO (writeIORef sc.digest (Just sha))+          R.evalsha sha keys args
src/Haskoin/Store/Fleet/XPub.hs view
@@ -27,9 +27,9 @@ --   them; -- -- * __the pool's layer__: the transactions of the shared pool that touch---   those addresses and the outputs that it pays to them. The script of the---   pool puts them in and takes them out in the step in which it changes---   the pool, so this layer is the pool, always.+--   those addresses and the outputs that it pays to them. The pool puts+--   them in and takes them out in the step in which it changes, so this+--   layer is the pool, always. -- -- Transactions and outputs of both layers are in one list each, ordered as -- the API orders them, so a page is a range of a sorted set. A balance is@@ -54,7 +54,7 @@ -- * __The tip and the cache move in one commit.__ The store that moves the --   tip first writes what the blocks in between did at the addresses that --   entries have ('tipMoves'), in pieces that mark the entries they touch---   ('cachePieces'); readers wait for a marked entry. Then one script moves+--   ('cachePieces'); readers wait for a marked entry. Then one step moves --   the pool, the fleet tip and the cache together, gives each marked entry --   a new version and clears the marks ('Haskoin.Store.Fleet.Redis.fleetCommit'). --   No request finds the tip without its cache, or an entry half moved.@@ -116,6 +116,7 @@     cacheTracked,     Begun (..),     cacheBegin,+    cacheBeat,     AddressMove (..),     tipMoves,     cachePieces,@@ -182,7 +183,11 @@ import Haskoin.Store.Database.Query.Pooled (From (..), PoolReads (..), applySummary, emptyPool, pooledRead) import Haskoin.Store.Database.Reader (DatabaseReader (..), Derived (..), derivedAddrs) import Haskoin.Store.Database.Types (MemSummary (..))+import Haskoin.Store.Fleet.Atomic (Atomic)+import Haskoin.Store.Fleet.Atomic.Redis (insist, transact)+import Haskoin.Store.Fleet.Pool.Decide qualified as P import Haskoin.Store.Fleet.Redis (FleetKeys (..), Script, evalScript, script)+import Haskoin.Store.Fleet.XPub.Decide qualified as X import Haskoin.Store.XPub (greedyLua, indexCost)  -------------------------------------------------------------------------------@@ -431,6 +436,11 @@         ["marked"]           | tries > 0 -> threadDelay 5000 >> go (tries - 1)           | otherwise -> return Moved+        -- the entry has transactions that a move of the tip marked as+        -- leaving the pool: they are taken out, and it is read again+        "leaving" : ts+          | tries > 0 -> insist conn (P.takeOut (P.poolKeys keys.prefix 32) ts) >> go (tries - 1)+          | otherwise -> return Moved         other -> fail ("Unexpected answer of the xpub script: " <> show (take 1 other))  -------------------------------------------------------------------------------@@ -460,9 +470,7 @@  -- | Delete the entry of a key. cacheDrop :: Connection -> FleetKeys -> XPubSpec -> IO ()-cacheDrop conn keys spec = do-  _ <- run conn (evalScript xpubScript [] ["drop", keys.prefix, "32", xpubId spec]) :: IO [ByteString]-  return ()+cacheDrop conn keys spec = insist conn (X.drop (X.cacheKeys keys.prefix) (xpubId spec))  -- | Build the entry of a key, or add to it the addresses that the key has -- gained: given the tip that the fleet is at, the database as it was at@@ -516,21 +524,31 @@               (sum [length txs | (_, _, txs, _) <- now'])               (sum [length outs | (_, _, _, outs) <- now'])               0-          args =-            [tip, xpubId spec, num n0, num n1, num cost, num (length now')]-              <> concatMap address now'+          additions = map address now'           count m = length [() | (XPubBal {path = m' : _}, _, _, _) <- now', m' == m]-      run conn (evalScript xpubScript [] ("build" : keys.prefix : "32" : args)) >>= \case-        ["ok"] -> go (n0 + count 0, n1 + count 1) (added + length now') later-        ["busy"] -> return Busy-        [why] | why `elem` ["raced", "behind", "changed"] -> return Abandoned-        other -> fail ("Unexpected answer of the xpub script: " <> show (take 1 (other :: [ByteString])))+          step :: (Monad m) => Atomic m X.Step+          step =+            X.build+              (X.cacheKeys keys.prefix)+              tip+              (xpubId spec)+              (toInteger n0, toInteger n1)+              (toInteger cost)+              additions+      -- one that other stores change the ground of five times is given up,+      -- as one that found the entry changed+      transact conn 5 step >>= \case+        Just X.StepAdded -> go (n0 + count 0, n1 + count 1) (added + length now') later+        Just X.StepBusy -> return Busy+        _ -> return Abandoned     address (b, bal, txs, outs) =-      [encode b.balance.address, path b.path, maybe "" encode (bal >>= real)]-        <> [num (length txs)]-        <> concat [[encode t.txid, num (score t.block)] | t <- txs]-        <> [num (length outs)]-        <> concat [[encode u.outpoint, num (score u.block), num u.value, u.script] | u <- outs]+      X.Addition+        { address = encode b.balance.address,+          path = path b.path,+          balance = maybe "" encode (bal >>= real),+          txs = [(encode t.txid, fromIntegral (score t.block)) | t <- txs],+          outs = [(encode u.outpoint, fromIntegral (score u.block), num u.value, u.script) | u <- outs]+        }     real b = if nullBalance b then Nothing else Just b     path = \case       [m, n] -> runPut (putWord8 (fromIntegral m) >> putWord32be n)@@ -620,22 +638,29 @@ -- that the store saw: from here until the commit ('fleetCommit' in -- "Haskoin.Store.Fleet.Redis") or 'cacheAbort', builds wait, so that every -- entry is either one that the move brings along or one built after it. A--- move whose store wrote nothing for ten seconds is aborted by whoever--- comes across it.+-- move whose store said nothing for ten seconds ('cacheBeat') is aborted+-- by whoever comes across it. cacheBegin :: Connection -> FleetKeys -> ByteString -> ByteString -> IO Begun cacheBegin conn keys token seen =-  run conn (evalScript xpubScript [] ["begin", keys.prefix, "32", token, seen]) >>= \case-    ["ok"] -> return Begun-    ["busy"] -> return Moving-    ["raced"] -> return BeginRaced-    other -> fail ("Unexpected answer of the xpub script: " <> show (other :: [ByteString]))+  transact conn 5 (X.begin (X.cacheKeys keys.prefix) token seen) <&> \case+    Just X.BeganMove -> Begun+    Just X.TipElsewhere -> BeginRaced+    -- another store moves the tip, or others kept changing what this+    -- asked about: the store tries at its next turn+    _ -> Moving +-- | Say that the store is still at the move of a token: whether the move+-- is still its own. A store says so every two seconds while it works at a+-- move, and has the floor for ten seconds from each time+-- ('Haskoin.Store.Fleet.Pool.Decide.floorHeld'): for as long as the move+-- takes, and no longer than ten seconds after the store stops.+cacheBeat :: Connection -> FleetKeys -> ByteString -> IO Bool+cacheBeat conn keys token = fromMaybe False <$> transact conn 3 (X.beat (X.cacheKeys keys.prefix) token)+ -- | End a move of the cache that will not be committed, dropping the -- entries that its pieces wrote, to be built again. cacheAbort :: Connection -> FleetKeys -> ByteString -> IO ()-cacheAbort conn keys token = do-  _ <- run conn (evalScript xpubScript [] ["abort", keys.prefix, "32", token]) :: IO [ByteString]-  return ()+cacheAbort conn keys token = insist conn (X.abort (X.cacheKeys keys.prefix) token)  -- | What a move of the tip does to the chain's layer of an address that -- entries have: its balance in the chain at the new tip, the transactions@@ -699,36 +724,37 @@     go [] = return True     go moves = do       let (now', later) = batch chunk moves-          args = ["piece", keys.prefix, "32", token, seen, num (length now')] <> concatMap one now'-      run conn (evalScript xpubScript [] args) >>= \case-        ["ok"] -> go later-        ["raced"] -> return False-        other -> fail ("Unexpected answer of the xpub script: " <> show (other :: [ByteString]))+          pieces = map one now'+          written :: (Monad m) => Atomic m Bool+          written = X.piece (X.cacheKeys keys.prefix) token seen pieces+      -- a piece that other stores change the ground of five times is not+      -- written, and the caller aborts the move+      transact conn 5 written >>= \case+        Just True -> go later+        _ -> return False     weight x = 1 + length x.abandoned + length x.added + length x.gone + length x.unspent     batch _ [] = ([], [])     batch room (x : xs)       | room <= 0 = ([], x : xs)       | otherwise = let (now', later) = batch (room - weight x) xs in (x : now', later)     one x =-      [encode x.address, maybe "" encode (x.balance >>= real), num (length x.abandoned)]-        <> map encode x.abandoned-        <> [num (length x.added)]-        <> concat [[encode h, num (score ref)] | (h, ref) <- x.added]-        <> [num (length x.gone)]-        <> map encode x.gone-        <> [num (length x.unspent)]-        <> concat [[encode o.outpoint, num (score o.block), num o.value, o.script] | o <- x.unspent]+      X.Piece+        { address = encode x.address,+          balance = maybe "" encode (x.balance >>= real),+          abandoned = map encode x.abandoned,+          added = [(encode h, fromIntegral (score ref)) | (h, ref) <- x.added],+          gone = map encode x.gone,+          unspent = [(encode o.outpoint, fromIntegral (score o.block), num o.value, o.script) | o <- x.unspent]+        }     real b = if nullBalance b then Nothing else Just b  -- | Delete entries past so many by GreedyDual, those of the lowest priority--- first, raising the level to each ('Haskoin.Store.XPub.greedyLua'). A use--- of an entry gave it the level plus its cost, so a large key outlives--- small ones used as recently, and any key goes once it is not used for--- long enough. Entries of a version that ordered them by last use are given--- the level first, so they go first. Says how many it deleted.+-- first, raising the level to each ('Haskoin.Store.Fleet.XPub.Decide.evict').+-- A use of an entry gave it the level plus its cost, so a large key+-- outlives small ones used as recently, and any key goes once it is not+-- used for long enough. Says how many it deleted. cacheEvict :: Connection -> FleetKeys -> Int -> IO Int-cacheEvict conn keys most =-  fromInteger <$> run conn (evalScript xpubScript [] ["evict", keys.prefix, "32", num most])+cacheEvict conn keys most = fromInteger <$> insist conn (X.evict (X.cacheKeys keys.prefix) most)  -- | How large the cache is: the number of its entries, one for each -- extended public key, and the number of addresses that they have between@@ -774,7 +800,9 @@     Right x -> return x     Left e -> fail ("Redis error: " <> show e) --- | The script of the cache; see its header for what it takes and gives.+-- | The script of the reads of the cache; see its header for what it+-- takes and gives. What writes the cache is+-- "Haskoin.Store.Fleet.XPub.Decide". xpubScript :: Script xpubScript = script (greedyLua <> $(makeRelativeToProject "src/Haskoin/Store/Fleet/lua/xpub.lua" >>= embedFile)) {-# NOINLINE xpubScript #-}
+ src/Haskoin/Store/Fleet/XPub/Decide.hs view
@@ -0,0 +1,457 @@+-- |+-- Module      : Haskoin.Store.Fleet.XPub.Decide+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- Every change to the cache of extended public keys of a fleet, as+-- decisions of "Haskoin.Store.Fleet.Atomic": building an entry, moving+-- the chain's layer of the entries with the tip, in pieces, and dropping+-- and evicting entries. "Haskoin.Store.Fleet.XPub" says what an entry is+-- and why, and calls these.+--+-- = Why it is here and not in a script+--+-- These were commands of a Lua script, beside the reads of the cache. A+-- build writes thousands of rows for a large key, and a piece of a move+-- as many: a script that failed among them left an entry half written,+-- with addresses that its numbers did not count or rows of a block that+-- the tip had left, and Redis undoes nothing. As decisions, each is+-- carried out whole or not at all ("Haskoin.Store.Fleet.Atomic" says how),+-- and a fault in one is an exception in Haskell before Redis is told+-- anything.+--+-- The reads stay a script (@lua\/xpub.lua@). They change nothing, but for+-- noting that a key was used, and they are what every request for a key+-- costs: one call.+--+-- = A move that went quiet+--+-- A store that begins a move of the tip and then writes nothing for ten+-- seconds has its move ended by whoever comes across it here: the entries+-- that its pieces wrote are dropped, to be built again (@moving@). The+-- reads do not do that, as they once did: an entry that such a move marked+-- is a miss to them, and the build that follows a miss ends the move.+--+-- = How it is written+--+-- As the script was, a function for each of its functions, in its order+-- of reading and writing, so that the two can be compared line by line+-- and, in the tests, state by state against a Redis that runs the script.+module Haskoin.Store.Fleet.XPub.Decide+  ( Keys (..),+    cacheKeys,+    Addition (..),+    Piece (..),+    Row,+    Began (..),+    Step (..),+    build,+    begin,+    beat,+    piece,+    abort,+    drop,+    evict,+  )+where++import Control.Monad (foldM, forM_, unless, when)+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.ByteString.Char8 qualified as C+import Data.Maybe (fromMaybe, isJust, isNothing)+import Data.Set qualified as Set+import Haskoin.Store.Fleet.Atomic.Keys+import Haskoin.Store.Fleet.Pool.Decide qualified as P+import Prelude hiding (drop)++-- | The keys of the cache and of what it reads beside itself, under the+-- prefix of a fleet, each with the kind of what it holds.+data Keys = Keys+  { -- | the fleet tip+    fleet :: !(K 'Text),+    -- | how many times the tip moved+    moves :: !(K 'Number),+    -- | the version that the last change of an entry got+    xver :: !(K 'Number),+    -- | the place of the tip that the cache is at: a move and its block+    place :: !(K 'Text),+    -- | the entries by their priority, lowest first to go+    prio :: !(K 'Sorted),+    -- | the priority of the last entry that was evicted+    level :: !(K 'Number),+    -- | how many addresses the entries have between them+    addrs :: !(K 'Number),+    -- | the entries that have each address+    watchers :: !(Family 'Group),+    -- | the keys of the pool, for those of each entry (@entryOf@)+    pool :: !P.Keys,+    -- | the move of the tip under way: its token+    moving :: !(K 'Text),+    -- | when the store that makes that move last said that it is at it+    beat :: !(K 'Number),+    -- | the entries that the move under way wrote+    marked :: !(K 'Group),+    -- | the transactions of the pool at each address, the outputs that it+    -- pays to each, and what it keeps for each output+    atx :: !(Family 'Sorted),+    aout :: !(Family 'Sorted),+    aval :: !(Family 'Hash)+  }++-- | The keys under a prefix. Those that the pool has too, the tip, the+-- count of its moves, the version of the entries, the move under way, the+-- entries that have each address and what the pool holds at each, are+-- taken from the keys of the pool: each has one name and one kind.+cacheKeys :: ByteString -> Keys+cacheKeys p =+  Keys+    { fleet = pool.tip,+      moves = pool.moves,+      xver = pool.xver,+      place = pool.xtip,+      prio = named (p <> "fx:prio"),+      level = named (p <> "fx:level"),+      addrs = named (p <> "fx:addrs"),+      watchers = pool.watchers,+      pool,+      moving = pool.moving,+      beat = pool.beat,+      marked = pool.marked,+      atx = pool.atx,+      aout = pool.aout,+      aval = pool.aval+    }+  where+    -- the size of a transaction id is not asked of these keys+    pool = P.poolKeys p 0++-- | The keys of one entry: its addresses, each with its path and its+-- balance in the chain; its numbers, which are how many addresses it has+-- in each chain of the key, its version and what it cost; its+-- transactions and its outputs, in the order of the lists; and what it+-- keeps for each output.+data Entry = Entry+  { addrs :: !(K 'Hash),+    meta :: !(K 'Counts),+    txs :: !(K 'Sorted),+    outs :: !(K 'Sorted),+    oval :: !(K 'Hash)+  }++-- | The keys of the entry of a key. The pool writes four of them too, and+-- they are its keys.+entryOf :: Keys -> ByteString -> Entry+entryOf k i =+  Entry+    { addrs = P.entryKey k.pool (i <> ":addrs"),+      meta = P.entryMeta k.pool i,+      txs = P.entryTxs k.pool i,+      outs = P.entryOuts k.pool i,+      oval = P.entryOval k.pool i+    }++-- | An output in a list of an entry: the output, its place in the list,+-- its amount in digits and its script.+type Row = (ByteString, Score, ByteString, ByteString)++-- | An address to add to an entry, with what the chain has for it.+data Addition = Addition+  { address :: !ByteString,+    -- | five bytes: the chain of the key that the address is in, and its+    -- number there+    path :: !ByteString,+    -- | its balance in the chain, or nothing+    balance :: !ByteString,+    -- | its transactions in the chain, each with its place in the list+    txs :: ![(ByteString, Score)],+    -- | its unspent outputs in the chain+    outs :: ![Row]+  }++-- | What a move of the tip does to the chain's layer of an address.+data Piece = Piece+  { address :: !ByteString,+    -- | its balance in the chain at the new block, or nothing+    balance :: !ByteString,+    -- | the transactions of the abandoned blocks+    abandoned :: ![ByteString],+    -- | those of the new blocks, each with its place in the list+    added :: ![(ByteString, Score)],+    -- | the outputs that are no longer unspent in the chain+    gone :: ![ByteString],+    -- | those that are unspent in the chain at the new block+    unspent :: ![Row]+  }++-- | What became of an attempt to begin a move.+data Began+  = -- | the move is under way+    BeganMove+  | -- | another store is moving the tip+    OtherMoving+  | -- | the fleet tip is not the one that the store saw+    TipElsewhere+  deriving (Eq, Show)++-- | What became of one write of a build.+data Step+  = -- | the addresses are in the entry+    StepAdded+  | -- | the fleet tip is another block+    StepRaced+  | -- | the cache is at another place of the tip+    StepBehind+  | -- | the entry does not have the numbers of addresses that the store+    -- found+    StepChanged+  | -- | a move of the tip is under way+    StepBusy+  deriving (Eq, Show)++num :: (Show a) => a -> ByteString+num = C.pack . show++-- | What an entry keeps for an output: its amount, the length of its+-- address, the address and the script.+keptFor :: ByteString -> ByteString -> ByteString -> ByteString+keptFor a amount script = amount <> " " <> num (B.length a) <> " " <> a <> script++-- | Delete the entry of a key, unless a store is moving the tip: the+-- entry stays then, and whoever wanted it gone finds it there and asks+-- again ('Haskoin.Store.Fleet.Pool.Decide.floorHeld').+drop :: (Monad m) => Keys -> ByteString -> Atomic m ()+drop k i = do+  held <- P.floorHeld k.pool+  busy <- P.leavingHeld k.pool+  unless (held || busy) (dropped k i)++-- | Delete the entry of a key, whoever has the floor.+dropped :: (Monad m) => Keys -> ByteString -> Atomic m ()+dropped k i = do+  let e = entryOf k i+  had <- Set.toList <$> hkeys e.addrs+  forM_ had $ \a -> srem (k.watchers `under` a) i+  unless (null had) (incrBy k.addrs (negate (toInteger (length had))))+  del e.addrs+  del e.meta+  del e.txs+  del e.outs+  del e.oval+  zrem k.prio i++-- | End a move of the tip that did not finish: what its pieces wrote is+-- dropped, entry by entry.+ended :: (Monad m) => Keys -> Atomic m ()+ended k = do+  ids <- smembers k.marked+  forM_ (Set.toList ids) (dropped k)+  del k.marked+  del k.moving+  del k.beat++-- | The token of the move of the tip under way, if there is one. A move+-- whose store said nothing for ten seconds is ended here, and there is+-- none then: the store stopped, or lost its way to Redis.+moving :: (Monad m) => Keys -> Atomic m (Maybe ByteString)+moving k =+  get k.moving >>= \case+    Nothing -> return Nothing+    Just token -> do+      now <- clock+      said <- getNumber k.beat+      if now - said > 10000+        then ended k >> return Nothing+        else return (Just token)++-- | Whether the move under way is that of a token: what the store that+-- makes the move asks. It does not ask when it last said that it is at+-- it, as @moving@ does: its move is its own until another decision ends+-- it, which takes the token away. So what it says (@beat@) changes no+-- answer of its own decisions.+mine :: (Monad m) => Keys -> ByteString -> Atomic m Bool+mine k token = (== Just token) <$> get k.moving++-- | Say that the store of a token is still at its move: whether the move+-- is still its own. It keeps the floor for ten seconds from here+-- ('Haskoin.Store.Fleet.Pool.Decide.floorHeld').+--+-- A store says it every two seconds for as long as it works at a move+-- (@moveTip@ in "Haskoin.Store.Fleet.Member"). Without it the floor was+-- the store's for ten seconds from its last piece, and a move that took+-- longer to decide was first raced by the offers that it had held back,+-- and then ended by the first request for a key.+beat :: (Monad m) => Keys -> ByteString -> Atomic m Bool+beat k token = do+  ours <- mine k token+  when ours (clock >>= setNumber k.beat)+  return ours++-- | A use of an entry: its priority is the level plus what it cost+-- (GreedyDual).+used :: (Monad m) => Keys -> ByteString -> Integer -> Atomic m ()+used k i cost = do+  lowest <- getNumber k.level+  zadd k.prio (fromIntegral (lowest + cost)) i++-- | Delete the entries of the lowest priority past so many, raising the+-- level to that of each: how many were deleted. None while a store is+-- moving the tip.+evict :: (Monad m) => Keys -> Int -> Atomic m Integer+evict k most = do+  held <- P.floorHeld k.pool+  busy <- P.leavingHeld k.pool+  n <- zcard k.prio+  if held || busy || n <= toInteger most+    then return 0+    else do+      lowest <- zrangeByScore k.prio MinusInf PlusInf (Just (fromInteger n - most))+      start <- fromIntegral <$> getNumber k.level+      let go bar (i, p) = do+            when (p > bar) (setNumber k.level (round p))+            dropped k i+            return (max bar p)+      _ <- foldM go (start :: Score) lowest+      return (toInteger (length lowest))++-- | End the move of a token, if it is the one under way: for a store+-- whose commit was refused.+abort :: (Monad m) => Keys -> ByteString -> Atomic m ()+abort k token = do+  ours <- mine k token+  when ours (ended k)++-- | Begin a move of the tip under a token, from the tip that the store+-- saw. Builds wait until it is done, so that every entry is one that the+-- move brings along or one built after it.+--+-- It does not begin while the pool has what the move before it marked as+-- leaving ('Haskoin.Store.Fleet.Pool.Decide.leavingHeld'), and says that another store is moving the+-- tip, which is what the store has to do then: wait a turn. The pieces+-- of a move write to the entries, and nothing but the taking out writes+-- to the pool or to the cache until everything is out. The move would be+-- refused at its end anyway, and its pieces dropped.+begin :: (Monad m) => Keys -> ByteString -> ByteString -> Atomic m Began+begin k token saw = do+  at <- fromMaybe "" <$> get k.fleet+  if at /= saw+    then return TipElsewhere+    else do+      under' <- moving k+      busy <- P.leavingHeld k.pool+      if busy || (isJust under' && under' /= Just token)+        then return OtherMoving+        else do+          set k.moving token+          clock >>= setNumber k.beat+          return BeganMove++-- | Write what a move of the tip does at addresses into every entry that+-- has one of them, and mark those entries: whether it was written, which+-- it is not if the tip is another block or the move another.+--+-- What is taken out of an entry is only what has a score of the chain, at+-- or above zero, so that the pool's layer stays as it is.+piece :: (Monad m) => Keys -> ByteString -> ByteString -> [Piece] -> Atomic m Bool+piece k token saw pieces = do+  at <- fromMaybe "" <$> get k.fleet+  own <- if at /= saw then return False else mine k token+  if not own+    then return False+    else do+      clock >>= setNumber k.beat+      version <- (+ 1) <$> getNumber k.xver+      incrBy k.xver 1+      forM_ pieces $ \p -> do+        ids <- smembers (k.watchers `under` p.address)+        forM_ (Set.toList ids) $ \i -> do+          let e = entryOf k i+          sadd k.marked i+          hsetNumber e.meta "ver" version+          row <- hget e.addrs p.address+          forM_ row $ \r -> hset e.addrs p.address (B.take 5 r <> p.balance)+          forM_ p.abandoned $ \t -> do+            ours <- chained e.txs t+            when ours (zrem e.txs t)+          forM_ p.added $ \(t, s) -> zadd e.txs s t+          forM_ p.gone $ \o -> do+            ours <- chained e.outs o+            when ours $ do+              zrem e.outs o+              hdel e.oval o+          forM_ p.unspent $ \(o, s, amount, script) -> do+            zadd e.outs s o+            hset e.oval o (keptFor p.address amount script)+      return True+  where+    chained z x = maybe False (>= 0) <$> zscore z x++-- | Add addresses to the entry of a key, with what the chain has for each+-- and what the pool has for it now, which the pool keeps up from here on.+--+-- Given are the tip that the store answers from, the key, the numbers of+-- addresses that the entry is to have before, in each of the two chains+-- of the key, what the addresses cost to read, and the addresses. It is+-- for a request that missed, and so a use of the key, at the cost so far.+--+-- A cache with nothing in it starts at the place of the tip, here.+build :: (Monad m) => Keys -> ByteString -> ByteString -> (Integer, Integer) -> Integer -> [Addition] -> Atomic m Step+build k tip i expected cost additions = do+  at <- fromMaybe "" <$> get k.fleet+  if at /= tip+    then return StepRaced+    else do+      under' <- moving k+      -- nor while the pool has what the last move marked as leaving:+      -- nothing but the taking out writes to the pool or to the cache+      -- until it is out ('P.leavingHeld')+      busy <- P.leavingHeld k.pool+      if isJust under' || busy+        then return StepBusy+        else do+          count <- getNumber k.moves+          let here = num count <> "@" <> at+          place <- get k.place+          when (isNothing place) (set k.place here)+          if maybe False (/= here) place+            then return StepBehind+            else do+              n0 <- fromMaybe 0 <$> hgetNumber e.meta "n0"+              n1 <- fromMaybe 0 <$> hgetNumber e.meta "n1"+              if (n0, n1) /= expected+                then return StepChanged+                else do+                  spent <- (+ cost) . fromMaybe 0 <$> hgetNumber e.meta "cost"+                  hincrBy e.meta "cost" cost+                  used k i spent+                  (m0, m1) <- foldM add (n0, n1) additions+                  version <- (+ 1) <$> getNumber k.xver+                  incrBy k.xver 1+                  hsetNumber e.meta "n0" m0+                  hsetNumber e.meta "n1" m1+                  hsetNumber e.meta "ver" version+                  incrBy k.addrs (toInteger (length additions))+                  return StepAdded+  where+    e = entryOf k i+    add (n0, n1) a = do+      hset e.addrs a.address (a.path <> a.balance)+      sadd (k.watchers `under` a.address) i+      forM_ a.txs $ \(t, s) -> zadd e.txs s t+      forM_ a.outs $ \(o, s, amount, script) -> do+        zadd e.outs s o+        hset e.oval o (keptFor a.address amount script)+      -- what the pool has for the address+      theirs <- zrangeByScore (k.atx `under` a.address) MinusInf PlusInf Nothing+      forM_ theirs $ \(t, s) -> zadd e.txs s t+      paid <- zrangeByScore (k.aout `under` a.address) MinusInf PlusInf Nothing+      forM_ paid $ \(o, s) -> do+        value <- hget (k.aval `under` a.address) o+        forM_ value $ \v -> do+          let (amount, script) = B.breakSubstring " " v+          zadd e.outs s o+          hset e.oval o (keptFor a.address amount (B.drop 1 script))+      return (if B.take 1 a.path == "\0" then (n0 + 1, n1) else (n0, n1 + 1))
+ src/Haskoin/Store/Fleet/lua/atomic.lua view
@@ -0,0 +1,151 @@+-- Decisions made in Haskell, carried out in one step: atomicScript in+-- Haskoin.Store.Fleet.Atomic.Redis, for Haskoin.Store.Fleet.Atomic, which+-- says why. This script decides nothing. It asks Redis questions, and it+-- carries out a list of writes if the answers to questions are what the+-- caller was told before.+--+-- ARGV[1] is what to do. Everything else comes as lists, a thousand+-- items to an argument, each argument one string in MessagePack: Redis+-- closes the connection of a command with more than 1,048,576 arguments,+-- and the move of the tip over one block has that many words. An argument+-- is unpacked when its turn comes and let go after it, so that the script+-- never holds more than a thousand items unpacked.+--+-- 'read': lists of questions. Returns the clock of Redis in milliseconds,+-- as a string, and then the answer to each question.+--+-- 'apply': the number of lists of questions, those lists, and lists of+-- writes. A question comes after the answer that the caller has for it.+-- Returns {'raced', n} if the answer to question n, from 1, is another+-- now, and has changed nothing then; {'done'} once it has carried out+-- every write.+--+-- A question is a letter for the shape of its answer, and the words of its+-- command: 'p' for an answer to take as it is, 'u' for a list in no order,+-- as the members of a set, 'h' for the fields of a hash with their values,+-- and 'k' for the fields of a hash whose value is a number above a bound,+-- which is then the first of the words, before the command.+--+-- An answer is given as a string that says all of it, so that two answers+-- are the same when their strings are: 'n' for none, 'i' a number and ';',+-- 's' a length, ':' and so many bytes, 'a' a count, ';' and so many+-- answers. A list in no order is given in the order of the SHA-1 of its+-- members, and a hash as pairs in the order of the SHA-1 of its fields:+-- that order is the same every time, which the order of the bytes is not+-- where Redis compares strings as some language does.+--+-- A write is the words of one command, or two words, '!WIPE' and the+-- start of the keys to delete.+--+-- No write comes before the last answer is compared, and nothing is+-- decided between two writes: each is a plain command to a key of the kind+-- that the command is for. So a call changes everything it was given or+-- nothing, which a script that reads and writes in turn cannot promise:+-- Redis keeps what a script wrote before it failed.+local mode = ARGV[1]++local function enc(r)+  local t = type(r)+  if t == 'string' then+    return 's' .. #r .. ':' .. r+  elseif t == 'number' then+    return 'i' .. string.format('%.0f', r) .. ';'+  elseif t == 'table' then+    if r.ok then+      return 's' .. #r.ok .. ':' .. r.ok+    end+    local parts = {'a' .. #r .. ';'}+    for i = 1, #r do+      parts[#parts + 1] = enc(r[i])+    end+    return table.concat(parts)+  end+  return 'n'+end++-- pairs of a key to order by and an item, as the items in the order of+-- the SHA-1 of their keys+local function ordered(keyed)+  for _, pair in ipairs(keyed) do+    pair[1] = redis.sha1hex(pair[1])+  end+  table.sort(keyed, function(a, b) return a[1] < b[1] end)+  local out = {}+  for i, pair in ipairs(keyed) do+    out[i] = pair[2]+  end+  return out+end++-- the answer to a question: its words, from a place in a list+local function ask(q, from)+  local shape = q[from]+  local words = {}+  for i = from + 1, #q do+    words[#words + 1] = q[i]+  end+  local above+  if shape == 'k' then+    above = tonumber(table.remove(words, 1))+  end+  local r = redis.call(unpack(words))+  if shape == 'k' then+    -- of a hash, the fields whose value is a number above the bound+    local keyed = {}+    for i = 1, #r, 2 do+      local n = tonumber(r[i + 1])+      if n and n > above then+        keyed[#keyed + 1] = {r[i], r[i]}+      end+    end+    r = ordered(keyed)+  elseif shape == 'u' then+    local keyed = {}+    for i, member in ipairs(r) do+      keyed[i] = {member, member}+    end+    r = ordered(keyed)+  elseif shape == 'h' then+    local keyed = {}+    for i = 1, #r, 2 do+      keyed[#keyed + 1] = {r[i], {r[i], r[i + 1]}}+    end+    r = ordered(keyed)+  end+  return enc(r)+end++if mode == 'read' then+  local time = redis.call('TIME')+  local answers = {string.format('%.0f', time[1] * 1000 + math.floor(time[2] / 1000))}+  for a = 2, #ARGV do+    for _, q in ipairs(cmsgpack.unpack(ARGV[a])) do+      answers[#answers + 1] = ask(q, 1)+    end+  end+  return answers+end++-- apply: compare every answer, and only then write+local asked = tonumber(ARGV[2])+local n = 0+for a = 3, 2 + asked do+  for _, q in ipairs(cmsgpack.unpack(ARGV[a])) do+    n = n + 1+    if ask(q, 2) ~= q[1] then+      return {'raced', tostring(n)}+    end+  end+end+for a = 3 + asked, #ARGV do+  for _, words in ipairs(cmsgpack.unpack(ARGV[a])) do+    if words[1] == '!WIPE' then+      for _, k in ipairs(redis.call('KEYS', words[2] .. '*')) do+        redis.call('DEL', k)+      end+    else+      redis.call(unpack(words))+    end+  end+end+return {'done'}
src/Haskoin/Store/Fleet/lua/move.lua view
@@ -64,9 +64,10 @@       return {'stays'}     end     redis.call('SET', KEYS[1], block)-    -- the moves of the tip are counted, next to it: see pool.lua+    -- the moves of the tip are counted, next to it, as the advance of the+    -- pool counts them (Haskoin.Store.Fleet.Pool.Decide)     redis.call('INCR', string.sub(KEYS[1], 1, -4) .. 'moves')-    -- and told to the stores, as pool.lua tells it+    -- and told to the stores, as the advance tells it     redis.call('XADD', string.sub(KEYS[1], 1, -4) .. 'events', 'MAXLEN', '~', '10000', '*', 'k', 'b', 'h', block)     return {'moved', block}   end
− src/Haskoin/Store/Fleet/lua/pool.lua
@@ -1,688 +0,0 @@--- The shared mempool of a fleet: poolScript in Haskoin.Store.Fleet.Redis,--- and offer, withdraw and advance in Haskoin.Store.Fleet.Pool. The three are--- one script because they share how a transaction is put in and taken out.------ ARGV[1] is what to do, ARGV[2] the prefix of the keys, and ARGV[3] the--- size of a transaction id in bytes. An output is the id of the transaction--- that made it and four more bytes. Lists are their items one after the--- other.------ A transaction is given as its id, the time it entered a mempool, the--- outputs that it spends, its body, '1' if it says itself that it can be--- replaced by fee or '0', the number of its entries by address, and then--- five arguments for each entry: its kind, the address, an output--- or '', an amount or '', and a script or ''. The kinds are 't', the--- transaction touches the address; 's', it spends that output of the--- address, of that amount; and 'o', it pays that output to the address,--- with that amount and script.------ 'offer': the tip that the store saw or '', a string with '1' for each--- output that the transaction spends and that the store finds unspent at--- the tip and '0' for the others, the transactions that it replaces, and--- the transaction. Returns {'taken'}, {'known'}, {'conflict', ...},--- {'orphan', ...} or {'raced'}.------ 'withdraw': the transactions. Returns those that left.------ 'trim': how many of the transactions seen to keep. Returns how many are--- kept.------ 'advance': the tip that the store saw or '', the block to move to, the--- time in milliseconds or '' for the clock of Redis, the size of a block in--- bytes, '1' to empty the pool instead of changing it or '0', the height of--- the block to move to or '', the transactions that are gone, those that--- are confirmed, the outputs that are spent, each followed by the--- transaction of the block that spends it and the height of that block in--- four bytes, big-endian, the transactions of the abandoned blocks that the--- store has as replaced, each followed in the same way, the number of--- transactions that come back, those transactions, and the blocks that the--- tip moves through, oldest first, or '', the token of the move of the--- cache that the store began (xpub.lua) or ''. Returns {'moved'}, {'stays'} or {'raced'}, also when the token is--- not that of the move of the cache under way.------ The advance is the commit of a move of the tip: the pool, the tip and the--- cache of extended public keys change in it together. The pieces of the--- move (xpub.lua) wrote the chain's layer of the entries and marked them;--- here the pool's layer changes with the pool, every marked entry gets a--- new version, the marks go, and the cache is put at the new place of the--- tip. The cache is emptied only when the pool is, when the store cannot--- say what the abandoned blocks held, or when it was not at the tip.------ What the new blocks replaced is kept: each transaction of the pool that--- leaves because it, or an ancestor, spent an output that a transaction of--- the blocks spends, with that transaction and the height of its block.--- A transaction of the abandoned blocks that the store names as replaced--- waits until a move confirms the transaction that replaced it, and is--- kept then. What is kept is forgotten when the transaction that replaced--- it comes back from an abandoned block; it, and what waits, are forgotten--- 2016 blocks after their height, by the height of the block that the tip--- moves to. Haskoin.Store.Fleet.Pool.advanceReplacing says the same.------ The pool is emptied instead of changed in two cases. With '1' the store--- cannot say what the blocks between the two tips did, because it does--- not have the old tip: only when no other store is live, and {'raced'}--- otherwise, since another store may know. With '2' the store has both--- tips and the way between them is longer than a store goes through: that--- is so for every store, so any of them may, or the tip would never move--- again. Each time the pool is emptied, what the fleet has seen is--- forgotten, since what it decided on is gone, and a counter goes up,--- next to the tip, which tells the stores to fill the pool again.------ What the pool holds for each address, kept in step with its transactions:--- its transactions and the outputs paid to it, both ordered newest first,--- the outputs of it that are spent, and the sums of all that, which are the--- summary of Haskoin.Store.Database.Types.MemSummary. It also holds every--- transaction by the time it entered a mempool, which is the list of the--- mempool, and by its id alone, to find those whose id starts with some--- bytes.------ A transaction can be replaced by fee if it says so itself or if it spends--- from a transaction of the pool that can be. The second changes when a--- parent is confirmed or comes back from an abandoned block, so the pool--- keeps the answer apart from the body, and corrects it for what spends a--- transaction whenever that one comes or goes. An output counts in--- 'both' while the pool has both the entry that pays it and the entry that--- spends it, so it is added by the second to come and taken off by the--- first to go.------ Every move of the tip is counted, in 'fleet:moves'. The cache of extended--- public keys answers at one move of the tip and not at one block, since--- the tip can leave a block and come back to it, and what the pool did to--- the entries on the way is not undone by coming back.------ The cache of extended public keys (xpub.lua) has, for each key that it--- holds, the transactions of its addresses and the outputs paid to them,--- those of the pool among them. So what the pool puts in or takes out at an--- address goes in or out of the entry of every key that has the address,--- here, in the same step.-local what, prefix, tsize = ARGV[1], ARGV[2], tonumber(ARGV[3])-local osize = tsize + 4-local key = {-  tip = prefix .. 'fleet:tip',-  moves = prefix .. 'fleet:moves',-  events = prefix .. 'fleet:events',-  lease = prefix .. 'fleet:lease',-  recent = prefix .. 'fleet:recent',-  spends = prefix .. 'pool:spends',-  spender = prefix .. 'pool:spender',-  body = prefix .. 'pool:body',-  kids = prefix .. 'pool:kids:',-  entries = prefix .. 'pool:entries',-  time = prefix .. 'pool:time',-  ids = prefix .. 'pool:ids',-  own = prefix .. 'pool:own',-  rbf = prefix .. 'pool:rbf',-  atx = prefix .. 'pool:atx:',-  aout = prefix .. 'pool:aout:',-  aval = prefix .. 'pool:aval:',-  aspent = prefix .. 'pool:aspent:',-  asum = prefix .. 'pool:asum:',-  rep = prefix .. 'pool:rep',-  repby = prefix .. 'pool:repby:',-  repat = prefix .. 'pool:repat',-  lostval = prefix .. 'pool:lost',-  lostby = prefix .. 'pool:lostby:',-  lostat = prefix .. 'pool:lostat',-  seen = prefix .. 'fleet:seen',-  restarts = prefix .. 'fleet:restarts',-  of = prefix .. 'fx:of:',-  entry = prefix .. 'fx:e:',-  xtip = prefix .. 'fx:tip',-  moving = prefix .. 'fx:moving',-  marked = prefix .. 'fx:marked'-}--local function split(s, n)-  local items = {}-  for i = 1, #s, n do-    items[#items + 1] = string.sub(s, i, i + n - 1)-  end-  return items-end---- Tell every store of the fleet that something happened: 'b' and a block--- that the tip moved to or through, 't' and a transaction that entered the--- pool, 'd' and one that left it unconfirmed. The events go in a stream, in--- the step that makes the change, so that every store serves the same--- events in the same order, whatever its own node saw and when. The stream--- keeps about the last ten thousand.-local function emit(kind, what)-  redis.call('XADD', key.events, 'MAXLEN', '~', '10000', '*', 'k', kind, 'h', what)-end---- The transactions that the fleet has seen, by the time in milliseconds at--- which they were first seen: each that entered the pool, that an offer--- found in the pool or in conflict with it, and that left the pool--- unconfirmed. No store fetches one of them when a peer announces it. Only--- what the pool has decided on is seen: a transaction that a store--- received and has not offered yet is not, so that if the store stops--- before the offer, another fetches it. Not under 'pool:', so that it--- outlives a pool that is started again, as the transactions do: peers do--- not announce them again. 'trim' keeps the newest of them.-local seenAt-local function seen(t)-  if not seenAt then-    local time = redis.call('TIME')-    seenAt = time[1] * 1000 + math.floor(time[2] / 1000)-  end-  redis.call('ZADD', key.seen, 'NX', seenAt, t)-end--local function member(t)-  return redis.call('HEXISTS', key.spends, t) == 1-end---- the transactions of the pool among these, and all that spend them-local function descendants(from)-  local seen, order, todo = {}, {}, {}-  for _, t in ipairs(from) do-    if member(t) then-      todo[#todo + 1] = t-    end-  end-  while #todo > 0 do-    local t = table.remove(todo)-    if not seen[t] then-      seen[t] = true-      order[#order + 1] = t-      for _, kid in ipairs(redis.call('SMEMBERS', key.kids .. t)) do-        todo[#todo + 1] = kid-      end-    end-  end-  return order, seen-end---- a transaction of the arguments, from a position, and the position after--- it-local function read(at)-  local tx = {id = ARGV[at], time = tonumber(ARGV[at + 1]), inputs = ARGV[at + 2], body = ARGV[at + 3]}-  tx.own = ARGV[at + 4] == '1'-  local entries = {}-  local n = tonumber(ARGV[at + 5])-  at = at + 6-  for i = 1, n do-    entries[i] = {ARGV[at], ARGV[at + 1], ARGV[at + 2], ARGV[at + 3], ARGV[at + 4]}-    at = at + 5-  end-  tx.entries = entries-  return tx, at-end---- whether a member of a list of an entry is in the pool's layer, with a--- score below zero: what the pool puts in or takes out of an entry is never--- what the chain's layer has, which a move of the tip writes ahead of the--- pool (xpub.lua)-local function pooled(z, m)-  local s = redis.call('ZSCORE', z, m)-  return s and tonumber(s) < 0-end---- add to a field of the summary of an address; the + 0 turns -0, which taking--- out an output of value 0 gives, into 0: Redis reads '-0' as no integer, and--- the error would stop the whole script half way-local function add(a, field, by)-  redis.call('HINCRBY', key.asum .. a, field, string.format('%.0f', by + 0))-end---- put the entries of a transaction in, with sign 1, or take them out, with--- sign -1-local function account(t, time, entries, sign)-  local touched = {}-  for _, e in ipairs(entries) do-    local kind, a, o, v = e[1], e[2], e[3], tonumber(e[4])-    touched[a] = true-    -- the cached keys that have the address-    local watching = {}-    if kind ~= 's' then-      watching = redis.call('SMEMBERS', key.of .. a)-    end-    if kind == 't' then-      if sign > 0 then-        redis.call('ZADD', key.atx .. a, -time, t)-      else-        redis.call('ZREM', key.atx .. a, t)-      end-      for _, id in ipairs(watching) do-        if sign > 0 then-          redis.call('ZADD', key.entry .. id .. ':txs', 'NX', -time, t)-        elseif pooled(key.entry .. id .. ':txs', t) then-          redis.call('ZREM', key.entry .. id .. ':txs', t)-        end-      end-      add(a, 'txs', sign)-    elseif kind == 's' then-      if sign > 0 then-        redis.call('HSET', key.aspent .. a, o, e[4])-      else-        redis.call('HDEL', key.aspent .. a, o)-      end-      add(a, 'spent', sign * v)-      add(a, 'spentCount', sign)-      if redis.call('HEXISTS', key.aval .. a, o) == 1 then-        add(a, 'both', sign * v)-        add(a, 'bothCount', sign)-      end-    else-      if sign > 0 then-        redis.call('ZADD', key.aout .. a, -time, o)-        redis.call('HSET', key.aval .. a, o, e[4] .. ' ' .. e[5])-      else-        redis.call('ZREM', key.aout .. a, o)-        redis.call('HDEL', key.aval .. a, o)-      end-      for _, id in ipairs(watching) do-        if sign > 0 then-          if redis.call('ZADD', key.entry .. id .. ':outs', 'NX', -time, o) == 1 then-            redis.call('HSET', key.entry .. id .. ':oval', o, e[4] .. ' ' .. #a .. ' ' .. a .. e[5])-          end-        elseif pooled(key.entry .. id .. ':outs', o) then-          redis.call('ZREM', key.entry .. id .. ':outs', o)-          redis.call('HDEL', key.entry .. id .. ':oval', o)-        end-      end-      add(a, 'paid', sign * v)-      add(a, 'paidCount', sign)-      if redis.call('HEXISTS', key.aspent .. a, o) == 1 then-        add(a, 'both', sign * v)-        add(a, 'bothCount', sign)-      end-    end-  end-  -- every entry with an address that the transaction touches has a new-  -- version, so that a request that read it before reads it again-  local ver = nil-  for a, _ in pairs(touched) do-    for _, id in ipairs(redis.call('SMEMBERS', key.of .. a)) do-      ver = ver or redis.call('INCR', prefix .. 'fleet:xver')-      redis.call('HSET', key.entry .. id .. ':meta', 'ver', ver)-    end-  end-  -- an address that no transaction touches has no summary-  if sign < 0 then-    for a, _ in pairs(touched) do-      if tonumber(redis.call('HGET', key.asum .. a, 'txs')) == 0 then-        redis.call('DEL', key.asum .. a)-      end-    end-  end-end---- work out again whether a transaction of the pool can be replaced by--- fee, and if that changed, the same for what spends it-local function replaceable(t)-  local inputs = redis.call('HGET', key.spends, t)-  if not inputs then-    return-  end-  local can = redis.call('SISMEMBER', key.own, t) == 1-  if not can then-    for _, o in ipairs(split(inputs, osize)) do-      if redis.call('SISMEMBER', key.rbf, string.sub(o, 1, tsize)) == 1 then-        can = true-        break-      end-    end-  end-  if can ~= (redis.call('SISMEMBER', key.rbf, t) == 1) then-    if can then-      redis.call('SADD', key.rbf, t)-    else-      redis.call('SREM', key.rbf, t)-    end-    for _, kid in ipairs(redis.call('SMEMBERS', key.kids .. t)) do-      replaceable(kid)-    end-  end-end---- take one transaction out, leaving what spends it: quietly if a block--- confirmed it, which is no event of the mempool-local function remove(t, quiet)-  local inputs = redis.call('HGET', key.spends, t)-  if not inputs then-    return-  end-  if not quiet then-    emit('d', t)-    seen(t)-  end-  local kept = cmsgpack.unpack(redis.call('HGET', key.entries, t))-  account(t, kept[1], kept[2], -1)-  redis.call('HDEL', key.entries, t)-  redis.call('ZREM', key.time, t)-  redis.call('ZREM', key.ids, t)-  for _, o in ipairs(split(inputs, osize)) do-    redis.call('HDEL', key.spender, o)-    redis.call('SREM', key.kids .. string.sub(o, 1, tsize), t)-  end-  redis.call('HDEL', key.spends, t)-  redis.call('HDEL', key.body, t)-  redis.call('SREM', key.own, t)-  if redis.call('SREM', key.rbf, t) == 1 then-    for _, kid in ipairs(redis.call('SMEMBERS', key.kids .. t)) do-      replaceable(kid)-    end-  end-end--local function insert(tx)-  local t = tx.id-  redis.call('HSET', key.spends, t, tx.inputs)-  redis.call('HSET', key.body, t, tx.body)-  for _, o in ipairs(split(tx.inputs, osize)) do-    redis.call('HSET', key.spender, o, t)-    redis.call('SADD', key.kids .. string.sub(o, 1, tsize), t)-  end-  redis.call('HSET', key.entries, t, cmsgpack.pack({tx.time, tx.entries}))-  redis.call('ZADD', key.time, tx.time, t)-  redis.call('ZADD', key.ids, 0, t)-  account(t, tx.time, tx.entries, 1)-  if tx.own then-    redis.call('SADD', key.own, t)-  end-  replaceable(t)-  emit('t', t)-  seen(t)-end--local function withdraw(from)-  local order = descendants(from)-  for _, t in ipairs(order) do-    remove(t)-  end-  return order-end--if what == 'withdraw' then-  return withdraw(split(ARGV[4], tsize))-end---- trimmed only when the set has grown a hundredth past its bound, so that--- most calls cost a ZCARD-if what == 'trim' then-  local most, n = tonumber(ARGV[4]), redis.call('ZCARD', key.seen)-  if n > most + math.max(1, math.floor(most / 100)) then-    redis.call('ZREMRANGEBYRANK', key.seen, 0, n - most - 1)-    n = most-  end-  return n-end---- forget that these transactions were replaced-local function unreplaced(ts)-  for _, t in ipairs(ts) do-    local value = redis.call('HGET', key.rep, t)-    if value then-      redis.call('SREM', key.repby .. string.sub(value, 1, tsize), t)-      redis.call('HDEL', key.rep, t)-      redis.call('ZREM', key.repat, t)-    end-  end-end---- keep that a transaction was replaced: by a transaction, which comes--- first in the value, at a height, which follows in four bytes. What was--- kept of it before goes, with its place among what its winner replaced.-local function replaced(t, value)-  local by, h = string.sub(value, 1, tsize), string.sub(value, tsize + 1, tsize + 4)-  local b1, b2, b3, b4 = string.byte(h, 1, 4)-  unreplaced({t})-  redis.call('HSET', key.rep, t, value)-  redis.call('SADD', key.repby .. by, t)-  redis.call('ZADD', key.repat, ((b1 * 256 + b2) * 256 + b3) * 256 + b4, t)-end--local tip = redis.call('GET', key.tip) or ''-if tip ~= ARGV[4] then-  return {'raced'}-end--if what == 'offer' then-  local flags = ARGV[5]-  local tx = read(7)-  local t, inputs = tx.id, split(tx.inputs, osize)-  if member(t) then-    seen(t)-    return {'known'}-  end-  -- what it replaces leaves first, but only if it is taken-  local leaving, left = descendants(split(ARGV[6], tsize))-  local rivals, counted = {}, {}-  for _, o in ipairs(inputs) do-    local s = redis.call('HGET', key.spender, o)-    if s and not left[s] and not counted[s] then-      counted[s] = true-      rivals[#rivals + 1] = s-    end-  end-  if #rivals > 0 then-    seen(t)-    table.insert(rivals, 1, 'conflict')-    return rivals-  end-  local orphans = {'orphan'}-  for i, o in ipairs(inputs) do-    local maker = string.sub(o, 1, tsize)-    local made = member(maker) and not left[maker]-    if not made and string.sub(flags, i, i) ~= '1' then-      orphans[#orphans + 1] = o-    end-  end-  if #orphans > 1 then-    return orphans-  end-  for _, gone in ipairs(leaving) do-    remove(gone)-  end-  insert(tx)-  return {'taken'}-end---- advance: the block must be the one that the live stores agree on-local target, clock, bsize = ARGV[5], ARGV[6], tonumber(ARGV[7])-if target == tip then-  return {'stays'}-end-local now-if clock == '' then-  local time = redis.call('TIME')-  now = time[1] * 1000 + math.floor(time[2] / 1000)-else-  now = tonumber(clock)-end-local live = {}-local leases = redis.call('HGETALL', key.lease)-for i = 1, #leases, 2 do-  if tonumber(leases[i + 1]) > now then-    live[#live + 1] = leases[i]-  end-end-if #live == 0 then-  return {'raced'}-end-table.sort(live)-local reports = {}-for i, store in ipairs(live) do-  reports[i] = redis.call('HGET', key.recent, store) or ''-end-local agreed = ''-for _, block in ipairs(split(reports[1], bsize)) do-  local everywhere = true-  for j = 2, #reports do-    local found = false-    for _, other in ipairs(split(reports[j], bsize)) do-      if other == block then-        found = true-        break-      end-    end-    if not found then-      everywhere = false-      break-    end-  end-  if everywhere then-    agreed = block-    break-  end-end-if agreed ~= target then-  return {'raced'}-end---- the cache: the place of the tip before this move and after it, as--- xpub.lua has them, and the move of the cache that the store began-local moves = tonumber(redis.call('GET', key.moves) or '0')-local before, after = moves .. '@' .. tip, (moves + 1) .. '@' .. target-local function token(at)-  return ARGV[at + 1] or ''-end-local function settle(wipe)-  local at = redis.call('GET', key.xtip)-  if wipe or (at and at ~= before) then-    for _, k in ipairs(redis.call('KEYS', prefix .. 'fx:*')) do-      redis.call('DEL', k)-    end-  else-    local ids = redis.call('SMEMBERS', key.marked)-    if #ids > 0 then-      local ver = redis.call('INCR', prefix .. 'fleet:xver')-      for _, id in ipairs(ids) do-        if redis.call('EXISTS', key.entry .. id .. ':meta') == 1 then-          redis.call('HSET', key.entry .. id .. ':meta', 'ver', ver)-        end-      end-    end-    redis.call('DEL', key.marked, key.moving)-  end-  redis.call('SET', key.xtip, after)-end---- a store that does not know the way from the old tip starts the pool--- again: if it is alone, or if the way is too long for any store-if ARGV[8] == '1' or ARGV[8] == '2' then-  if ARGV[8] == '1' and #live ~= 1 then-    return {'raced'}-  end-  for _, k in ipairs(redis.call('KEYS', prefix .. 'pool:*')) do-    redis.call('DEL', k)-  end-  -- what the pool decided on is gone: the stores fetch it again when it-  -- is announced, and fill the pool again when the counter goes up. The-  -- first tip of a fleet, or the first after Redis lost its data, empties-  -- nothing, and the loss is a refill of its own (noteEpoch).-  redis.call('DEL', key.seen)-  if tip ~= '' then-    redis.call('INCR', key.restarts)-  end-  -- the entries have the pool's layer of the pool that is gone-  settle(true)-  redis.call('SET', key.tip, target)-  redis.call('INCR', key.moves)-  emit('b', target)-  return {'moved'}-end---- the move of the cache must be the one that the store began, and nobody--- aborted it; with none begun, none may be under way-local at = 15-for _ = 1, tonumber(ARGV[14]) do-  local _, next = read(at)-  at = next-end-local mine = token(at)-local current = redis.call('GET', key.moving)-if (current and string.sub(current, 1, #mine + 1) ~= mine .. ' ') or (not current and mine ~= '') then-  return {'raced'}-end---- the abandoned blocks: what can come back does, and what spends the rest--- leaves. What a transaction that comes back replaced is not replaced any--- more.-at = 15-for _ = 1, tonumber(ARGV[14]) do-  local tx-  tx, at = read(at)-  unreplaced(redis.call('SMEMBERS', key.repby .. tx.id))-  if not member(tx.id) then-    -- it was confirmed: what spends the same in the pool gives way-    local rivals = {}-    for _, o in ipairs(split(tx.inputs, osize)) do-      local s = redis.call('HGET', key.spender, o)-      if s then-        rivals[#rivals + 1] = s-      end-    end-    withdraw(rivals)-    insert(tx)-  end-end--- what the store has as replaced of the abandoned blocks waits for the--- transaction that replaced it-for _, item in ipairs(split(ARGV[13], 2 * tsize + 4)) do-  local t, value = string.sub(item, 1, tsize), string.sub(item, tsize + 1)-  local old = redis.call('HGET', key.lostval, t)-  if old then-    redis.call('SREM', key.lostby .. string.sub(old, 1, tsize), t)-  end-  local b1, b2, b3, b4 = string.byte(string.sub(value, tsize + 1, tsize + 4), 1, 4)-  redis.call('HSET', key.lostval, t, value)-  redis.call('SADD', key.lostby .. string.sub(value, 1, tsize), t)-  redis.call('ZADD', key.lostat, ((b1 * 256 + b2) * 256 + b3) * 256 + b4, t)-end-local orphaned = {}-for _, t in ipairs(split(ARGV[10], tsize)) do-  for _, kid in ipairs(redis.call('SMEMBERS', key.kids .. t)) do-    orphaned[#orphaned + 1] = kid-  end-end-withdraw(orphaned)---- the new blocks: what they confirm leaves alone, and what spends what they--- spend leaves with all that spends it, and is kept as replaced-for _, t in ipairs(split(ARGV[11], tsize)) do-  remove(t, true)-end--- what waited for a transaction that they confirm was replaced-for _, t in ipairs(split(ARGV[11], tsize)) do-  for _, waiting in ipairs(redis.call('SMEMBERS', key.lostby .. t)) do-    replaced(waiting, redis.call('HGET', key.lostval, waiting))-    redis.call('HDEL', key.lostval, waiting)-    redis.call('ZREM', key.lostat, waiting)-  end-  redis.call('DEL', key.lostby .. t)-end-for _, item in ipairs(split(ARGV[12], osize + tsize + 4)) do-  local s = redis.call('HGET', key.spender, string.sub(item, 1, osize))-  if s then-    for _, t in ipairs(withdraw({s})) do-      replaced(t, string.sub(item, osize + 1))-    end-  end-end--- forget what was replaced, or waits, 2016 blocks before the block of the--- tip-if ARGV[9] ~= '' and tonumber(ARGV[9]) >= 2016 then-  local limit = tonumber(ARGV[9]) - 2016-  unreplaced(redis.call('ZRANGEBYSCORE', key.repat, '-inf', limit))-  for _, t in ipairs(redis.call('ZRANGEBYSCORE', key.lostat, '-inf', limit)) do-    redis.call('SREM', key.lostby .. string.sub(redis.call('HGET', key.lostval, t), 1, tsize), t)-    redis.call('HDEL', key.lostval, t)-    redis.call('ZREM', key.lostat, t)-  end-end--settle(false)-redis.call('SET', key.tip, target)-redis.call('INCR', key.moves)--- the blocks that the tip moved through, oldest first, if the store that--- moves it gave them, and the block that it is at now otherwise-local path = split(ARGV[at] or '', bsize)-if #path == 0 then-  path = {target}-end-for _, block in ipairs(path) do-  emit('b', block)-end-return {'moved'}
src/Haskoin/Store/Fleet/lua/read.lua view
@@ -1,5 +1,6 @@ -- What a store reads from the shared mempool of its fleet: readScript in--- Haskoin.Store.Fleet.Redis. pool.lua writes what this reads.+-- Haskoin.Store.Fleet.Redis. Haskoin.Store.Fleet.Pool.Decide writes what+-- this reads. -- -- ARGV[1] is what to read, ARGV[2] the prefix of the keys, ARGV[3] the size -- of a transaction id in bytes, and ARGV[4] the fleet tip that the store@@ -7,6 +8,19 @@ -- the pool goes with the tip, and laid over the chain of another block it -- would give a transaction twice or not at all. Otherwise it is {'ok', ...}. --+-- A move of the tip marks what its blocks took out of the pool, and the+-- transactions leave after it, a few at a time (pool:leaving, and takeOut+-- in Haskoin.Store.Fleet.Pool.Decide). The chain has them already, at the+-- tip that the store answers from, and the pool still does. So a read that+-- would go by one of them answers {'leaving', ...} with those+-- transactions, and reads nothing: the store takes them out and reads+-- again. Which those are, for each read: what the pool keeps for an+-- address is written by the transactions at that address and by no+-- other, and the same for a category of tokens; a transaction and an+-- output are read with what spends them. A read that goes by none of+-- them reads the pool as it will be when they are all out. The list of+-- the pool alone is read without them.+-- -- 'sums': addresses. For each, its seven sums separated by spaces, in the -- order of the summary, or '' if the pool has nothing for it. --@@ -23,9 +37,9 @@ -- address that the pool spends and '0' for the others. -- -- 'bodies': transactions, of the pool or not. For each: its body or '',--- '1' if it can be replaced by fee or '0', the number of its outputs that--- the pool spends, and for each of those the output, the transaction that--- spends it and the number of its input that does.+-- the number of its outputs that the pool spends, and for each of those+-- the output, the transaction that spends it and the number of its input+-- that does. -- -- 'spenders': outputs. For each, the transaction that spends it and the -- number of its input that does, or two ''.@@ -35,6 +49,23 @@ -- -- 'ids': some bytes. The transactions whose id starts with them. --+-- 'tokens': an address. For each category of tokens that the pool moves at+-- the address: the category, and its eleven sums separated by spaces: the+-- transactions; the amount in two parts, the digits above the last nine+-- and the last nine, the non-fungible tokens and the outputs, that are+-- free; the same that are spent; and the amount paid in two parts.+--+-- 'holders': a category. For each address at which the pool moves tokens+-- of it: the address and its sums, as 'tokens' gives them.+--+-- 'csum': a category. Its transactions, free outputs and spent outputs+-- separated by spaces, or '' if the pool does not move it.+--+-- 'ctxs': as 'txs', for a category of tokens.+--+-- 'couts': as 'outs', for the outputs that hold a category of tokens; the+-- flag says whether the pool uses the output up.+-- -- 'replaced': transactions. For each, the transaction of a block that -- replaced it and the height of the block in four bytes, or ''. local what, prefix, tsize = ARGV[1], ARGV[2], tonumber(ARGV[3])@@ -52,6 +83,69 @@   return items end +local leaving = prefix .. 'pool:leaving'+local some = redis.call('EXISTS', leaving) == 1+if some then+  local found, seen = {'leaving'}, {}+  local function note(t)+    if not seen[t] and redis.call('HEXISTS', leaving, t) == 1 then+      seen[t] = true+      found[#found + 1] = t+    end+  end+  -- the marked among the members of a sorted set, going through the+  -- smaller of the two+  local function among(zkey)+    if redis.call('ZCARD', zkey) <= redis.call('HLEN', leaving) then+      for _, t in ipairs(redis.call('ZRANGE', zkey, 0, -1)) do+        note(t)+      end+    else+      for _, t in ipairs(redis.call('HKEYS', leaving)) do+        if not seen[t] and redis.call('ZSCORE', zkey, t) then+          seen[t] = true+          found[#found + 1] = t+        end+      end+    end+  end+  if what == 'sums' then+    for i = 5, #ARGV do+      among(prefix .. 'pool:atx:' .. ARGV[i])+    end+  elseif what == 'txs' or what == 'outs' or what == 'spent' or what == 'tokens' then+    among(prefix .. 'pool:atx:' .. ARGV[5])+  elseif what == 'holders' or what == 'csum' or what == 'ctxs' or what == 'couts' then+    among(prefix .. 'pool:ctx:' .. ARGV[5])+  elseif what == 'bodies' then+    for _, t in ipairs(split(ARGV[5], tsize)) do+      note(t)+      for _, kid in ipairs(redis.call('SMEMBERS', prefix .. 'pool:kids:' .. t)) do+        note(kid)+      end+    end+  elseif what == 'spenders' then+    for _, o in ipairs(split(ARGV[5], osize)) do+      local s = redis.call('HGET', prefix .. 'pool:spender', o)+      if s then+        note(s)+      end+    end+  elseif what == 'ids' then+    for _, t in ipairs(redis.call('ZRANGEBYLEX', prefix .. 'pool:ids',+      '[' .. ARGV[5], '(' .. ARGV[5] .. string.rep(string.char(255), tsize))) do+      note(t)+    end+  elseif what == 'replaced' then+    for i = 5, #ARGV do+      note(ARGV[i])+    end+  end+  if #found > 1 then+    return found+  end+end+ -- whether one string of bytes sorts before another, as Redis sorts the -- members of a sorted set; the comparison of Lua goes by the locale local function before(a, b)@@ -122,7 +216,6 @@ elseif what == 'bodies' then   for _, t in ipairs(split(ARGV[5], tsize)) do     answer[#answer + 1] = redis.call('HGET', prefix .. 'pool:body', t) or ''-    answer[#answer + 1] = tostring(redis.call('SISMEMBER', prefix .. 'pool:rbf', t))     -- what spends its outputs: the inputs of the transactions of the pool     -- that spend from it     local spent = {}@@ -160,6 +253,21 @@   if many > 0 then     last = offset + many - 1   end+  if some then+    -- without what is leaving: the place of a transaction in the list+    -- is its place among those that stay+    local rows, at = redis.call('ZREVRANGE', prefix .. 'pool:time', 0, -1, 'WITHSCORES'), 0+    for i = 1, #rows, 2 do+      if redis.call('HEXISTS', leaving, rows[i]) == 0 then+        if at >= offset and (many == 0 or at < offset + many) then+          answer[#answer + 1] = rows[i]+          answer[#answer + 1] = string.format('%.0f', tonumber(rows[i + 1]))+        end+        at = at + 1+      end+    end+    return answer+  end   local rows = redis.call('ZREVRANGE', prefix .. 'pool:time', offset, last, 'WITHSCORES')   for i = 1, #rows, 2 do     answer[#answer + 1] = rows[i]@@ -170,6 +278,50 @@     '[' .. ARGV[5], '(' .. ARGV[5] .. string.rep(string.char(255), tsize))   for _, t in ipairs(found) do     answer[#answer + 1] = t+  end+elseif what == 'tokens' or what == 'holders' then+  local sets, lead = prefix .. 'pool:acat:', true+  if what == 'holders' then+    sets, lead = prefix .. 'pool:chold:', false+  end+  for _, m in ipairs(redis.call('SMEMBERS', sets .. ARGV[5])) do+    local c, a = m, ARGV[5]+    if not lead then+      c, a = ARGV[5], m+    end+    local s = redis.call('HMGET', prefix .. 'pool:tsum:' .. c .. a, 'txs', 'freeHi', 'freeLo', 'freeNfts',+      'freeOutputs', 'spentHi', 'spentLo', 'spentNfts', 'spentOutputs', 'receivedHi', 'receivedLo')+    for j = 1, 11 do+      s[j] = s[j] or '0'+    end+    answer[#answer + 1] = m+    answer[#answer + 1] = table.concat(s, ' ')+  end+elseif what == 'csum' then+  local s = redis.call('HMGET', prefix .. 'pool:csum:' .. ARGV[5], 'txs', 'free', 'spent')+  if s[1] then+    answer[2] = (s[1] or '0') .. ' ' .. (s[2] or '0') .. ' ' .. (s[3] or '0')+  else+    answer[2] = ''+  end+elseif what == 'ctxs' then+  local zkey = prefix .. 'pool:ctx:' .. ARGV[5]+  local at = position(zkey, ARGV[6], ARGV[7])+  local rows = redis.call('ZRANGE', zkey, at, at + tonumber(ARGV[8]) - 1, 'WITHSCORES')+  for i = 1, #rows, 2 do+    answer[#answer + 1] = rows[i]+    answer[#answer + 1] = string.format('%.0f', -tonumber(rows[i + 1]))+  end+elseif what == 'couts' then+  local c = ARGV[5]+  local zkey = prefix .. 'pool:cout:' .. c+  local at = position(zkey, ARGV[6], ARGV[7])+  local rows = redis.call('ZRANGE', zkey, at, at + tonumber(ARGV[8]) - 1, 'WITHSCORES')+  for i = 1, #rows, 2 do+    answer[#answer + 1] = rows[i]+    answer[#answer + 1] = string.format('%.0f', -tonumber(rows[i + 1]))+    answer[#answer + 1] = redis.call('HGET', prefix .. 'pool:cval:' .. c, rows[i])+    answer[#answer + 1] = tostring(redis.call('HEXISTS', prefix .. 'pool:spender', rows[i]))   end elseif what == 'replaced' then   for i = 5, #ARGV do
src/Haskoin/Store/Fleet/lua/xpub.lua view
@@ -1,7 +1,12 @@--- The cache of extended public keys of a fleet: xpubScript in--- Haskoin.Store.Fleet.XPub, which says what an entry is and why, after--- greedy.lua. pool.lua keeps the part of each entry that comes from the--- shared mempool.+-- The reads of the cache of extended public keys of a fleet: xpubScript+-- in Haskoin.Store.Fleet.XPub, which says what an entry is and why, after+-- greedy.lua. Nothing here writes an entry: building, moving with the tip,+-- dropping and evicting are decisions made in Haskell+-- (Haskoin.Store.Fleet.XPub.Decide), and the pool keeps the part of each+-- entry that comes from the shared mempool+-- (Haskoin.Store.Fleet.Pool.Decide). A script that failed among the+-- thousands of rows of a build left an entry half written. The one write+-- here is the note that a key was used, a single command. -- -- ARGV[1] is what to do, ARGV[2] the prefix of the keys, and ARGV[3] the -- size of a transaction id in bytes. An output is the id of the transaction@@ -16,7 +21,7 @@ -- caller has them. They answer {'raced'} if the fleet tip is another block, -- {'miss'} if the cache is not where the tip is, if it does not have the key, -- or if it has it with other addresses, {'marked'} while a move of the tip--- is writing the entry in pieces ('piece'), and {'ok', version, ...}+-- is writing the entry in pieces, and {'ok', version, ...} -- otherwise. A reader that gets 'marked' waits a moment and asks again: it -- never sees an entry half moved. --@@ -41,73 +46,28 @@ -- 'have': the id. The two numbers of the entry, whatever block the cache is -- at: {n0, n1}. ----- 'build': the tip, the id, the two numbers that the entry is to have--- before, what the addresses added cost to read, in tokens, the number of--- addresses to add, and for--- each: the address, its path, its balance in the chain or '', the number--- of its transactions in the chain, a transaction and a score for each, the--- number of its unspent outputs in the chain, and an output, a score, an--- amount and a script for each. What the pool has for the address is added--- from the pool. Returns {'ok'}; {'raced'} if the fleet tip is another--- block; {'behind'} if the cache is at another block; {'changed'} if the--- entry does not have those two numbers of addresses; {'busy'} while a--- move of the tip is under way.------ 'drop': the id. Deletes the entry.--- -- 'tracked': addresses. A string with '1' for each address that an entry -- has and '0' for the others. ----- = Moving the tip with the cache------ A move of the fleet tip changes the chain's layer of the entries in the--- same commit as the pool and the tip: the last step is the advance of--- pool.lua, which takes the pool to the new block, stamps a new version on--- every entry that the move wrote, and puts the cache at the new place of--- the tip. What comes before it is written in pieces, each a short script,--- so that a large block does not hold Redis for long:------ 'begin': a token of the move and the tip that the mover saw. Marks that--- a move is under way: builds wait until it is done, so that every entry--- is either among those that the move brings along or built after it.--- Returns {'ok'}, {'raced'} if the fleet tip is another block, or {'busy'}--- if another store is moving it.------ 'piece': the token, the tip that the mover saw, the number of addresses,--- and for each: the address, its balance in the chain at the new block or--- '', the number of transactions of the abandoned blocks, those--- transactions, the number of transactions of the new blocks, a--- transaction and a score for each, the number of outputs that are no--- longer unspent in the chain, those outputs, the number of outputs that--- are unspent in the chain at the new block, and an output, a score, an--- amount and a script for each. Every entry that has the address is marked--- and changed: what is taken out is only what has a score of the chain, at--- or above zero, so that the pool's layer stays as it is. Returns {'ok'} or--- {'raced'}.------ 'abort': the token. Drops the entries that the pieces of that move--- marked, and ends the move: for a mover whose advance was refused.------ A move whose mover went quiet for ten seconds is aborted by whoever finds--- it: its marked entries are dropped, one at a time, to be built again.+-- An entry that a move of the tip is writing in pieces is marked, and a+-- read of it answers {'marked'} until the move is committed. A move whose+-- store wrote nothing for ten seconds is no move any more: a read of an+-- entry that it marked is a miss, and the build that follows a miss ends+-- the move and drops what it wrote. -- -- 'size': nothing. The number of entries, and the number of addresses that -- they have between them: {entries, addresses}.------ 'evict': how many entries to keep. Deletes those of the lowest priority--- past that many, by GreedyDual, and says how many it deleted. local what, prefix, tsize = ARGV[1], ARGV[2], tonumber(ARGV[3]) local key = {   fleet = prefix .. 'fleet:tip',   tip = prefix .. 'fx:tip',-  -- times of last use, of versions before GreedyDual-  lru = prefix .. 'fx:lru',   prio = prefix .. 'fx:prio',   level = prefix .. 'fx:level',   addrs = prefix .. 'fx:addrs',   of = prefix .. 'fx:of:',   entry = prefix .. 'fx:e:',   moving = prefix .. 'fx:moving',+  beat = prefix .. 'fx:beat',   marked = prefix .. 'fx:marked',   spender = prefix .. 'pool:spender',   atx = prefix .. 'pool:atx:',@@ -129,27 +89,9 @@   return #a < #b end -local function kept(a, amount, script)-  return amount .. ' ' .. #a .. ' ' .. a .. script-end--local function drop(id)-  local e = key.entry .. id .. ':'-  local had = redis.call('HKEYS', e .. 'addrs')-  for _, a in ipairs(had) do-    redis.call('SREM', key.of .. a, id)-  end-  if #had > 0 then-    redis.call('DECRBY', key.addrs, #had)-  end-  redis.call('DEL', e .. 'addrs', e .. 'meta', e .. 'txs', e .. 'outs', e .. 'oval')-  redis.call('ZREM', key.prio, id)-  redis.call('ZREM', key.lru, id)-end- -- the number of entries local function entries()-  return redis.call('ZCARD', key.prio) + redis.call('ZCARD', key.lru)+  return redis.call('ZCARD', key.prio) end  local function now()@@ -157,28 +99,17 @@   return t[1] * 1000 + math.floor(t[2] / 1000) end --- end a move of the tip that did not finish: what its pieces wrote is--- dropped, entry by entry-local function abort()-  for _, id in ipairs(redis.call('SMEMBERS', key.marked)) do-    drop(id)-  end-  redis.call('DEL', key.marked, key.moving)-end---- the token of the move of the tip under way, if there is one; a move that--- wrote nothing for ten seconds is aborted+-- the token of the move of the tip under way, if there is one; a move+-- whose store said nothing for ten seconds is none local function moving()-  local v = redis.call('GET', key.moving)-  if not v then+  local token = redis.call('GET', key.moving)+  if not token then     return nil   end-  local space = string.find(v, ' ', 1, true)-  if now() - tonumber(string.sub(v, space + 1)) > 10000 then-    abort()+  if now() - tonumber(redis.call('GET', key.beat) or '0') > 10000 then     return nil   end-  return string.sub(v, 1, space - 1)+  return token end  local function numbers(e)@@ -189,9 +120,6 @@ if what == 'have' then   local n0, n1 = numbers(key.entry .. ARGV[4] .. ':')   return {n0, n1}-elseif what == 'drop' then-  drop(ARGV[4])-  return {'ok'} elseif what == 'tracked' then   local flags = {}   for i = 4, #ARGV do@@ -200,9 +128,6 @@   return table.concat(flags) elseif what == 'size' then   return {entries(), tonumber(redis.call('GET', key.addrs) or '0')}-elseif what == 'evict' then-  greedy_migrate(key.lru, key.prio, key.level)-  return greedy_evict(key.prio, key.level, tonumber(ARGV[4]), drop) end  local fleet = redis.call('GET', key.fleet) or ''@@ -218,91 +143,6 @@ end local here = place(moves, fleet) -if what == 'abort' then-  if moving() == ARGV[4] then-    abort()-  end-  return {'ok'}-elseif what == 'begin' then-  if fleet ~= ARGV[5] then-    return {'raced'}-  end-  local other = moving()-  if other and other ~= ARGV[4] then-    return {'busy'}-  end-  redis.call('SET', key.moving, ARGV[4] .. ' ' .. now())-  return {'ok'}-elseif what == 'piece' then-  if fleet ~= ARGV[5] or moving() ~= ARGV[4] then-    return {'raced'}-  end-  redis.call('SET', key.moving, ARGV[4] .. ' ' .. now())-  local ver = redis.call('INCR', prefix .. 'fleet:xver')-  -- take out what has a score of the chain, and leave the pool's layer-  local function chained(z, m)-    local s = redis.call('ZSCORE', z, m)-    return s and tonumber(s) >= 0-  end-  local i = 7-  for _ = 1, tonumber(ARGV[6]) do-    local a, bal = ARGV[i], ARGV[i + 1]-    local old, new, gone, unspent = {}, {}, {}, {}-    local n = tonumber(ARGV[i + 2])-    i = i + 3-    for _ = 1, n do-      old[#old + 1] = ARGV[i]-      i = i + 1-    end-    n = tonumber(ARGV[i])-    i = i + 1-    for _ = 1, n do-      new[#new + 1] = {ARGV[i], ARGV[i + 1]}-      i = i + 2-    end-    n = tonumber(ARGV[i])-    i = i + 1-    for _ = 1, n do-      gone[#gone + 1] = ARGV[i]-      i = i + 1-    end-    n = tonumber(ARGV[i])-    i = i + 1-    for _ = 1, n do-      unspent[#unspent + 1] = {ARGV[i], ARGV[i + 1], kept(a, ARGV[i + 2], ARGV[i + 3])}-      i = i + 4-    end-    for _, id in ipairs(redis.call('SMEMBERS', key.of .. a)) do-      local e = key.entry .. id .. ':'-      redis.call('SADD', key.marked, id)-      redis.call('HSET', e .. 'meta', 'ver', ver)-      local row = redis.call('HGET', e .. 'addrs', a)-      if row then-        redis.call('HSET', e .. 'addrs', a, string.sub(row, 1, 5) .. bal)-      end-      for _, t in ipairs(old) do-        if chained(e .. 'txs', t) then-          redis.call('ZREM', e .. 'txs', t)-        end-      end-      for _, t in ipairs(new) do-        redis.call('ZADD', e .. 'txs', t[2], t[1])-      end-      for _, o in ipairs(gone) do-        if chained(e .. 'outs', o) then-          redis.call('ZREM', e .. 'outs', o)-          redis.call('HDEL', e .. 'oval', o)-        end-      end-      for _, o in ipairs(unspent) do-        redis.call('ZADD', e .. 'outs', o[2], o[1])-        redis.call('HSET', e .. 'oval', o[1], o[3])-      end-    end-  end-  return {'ok'}-end- -- everything else is for a store that answers from the fleet tip local tip, id = ARGV[4], ARGV[5] local e = key.entry .. id .. ':'@@ -310,65 +150,6 @@   return {'raced'} end -if what == 'build' then-  if moving() then-    return {'busy'}-  end-  local at = redis.call('GET', key.tip)-  if not at then-    -- nothing is cached yet: the cache starts here-    redis.call('SET', key.tip, here)-  elseif at ~= here then-    return {'behind'}-  end-  local n0, n1 = numbers(e)-  if n0 ~= tonumber(ARGV[6]) or n1 ~= tonumber(ARGV[7]) then-    return {'changed'}-  end-  -- a build is for a request that missed: a use, at the cost so far-  greedy_use(key.prio, key.level, id, redis.call('HINCRBY', e .. 'meta', 'cost', ARGV[8]), false)-  local i = 10-  for _ = 1, tonumber(ARGV[9]) do-    local a, path, bal = ARGV[i], ARGV[i + 1], ARGV[i + 2]-    redis.call('HSET', e .. 'addrs', a, path .. bal)-    redis.call('SADD', key.of .. a, id)-    if string.byte(path, 1) == 0 then-      n0 = n0 + 1-    else-      n1 = n1 + 1-    end-    local n = tonumber(ARGV[i + 3])-    i = i + 4-    for _ = 1, n do-      redis.call('ZADD', e .. 'txs', ARGV[i + 1], ARGV[i])-      i = i + 2-    end-    n = tonumber(ARGV[i])-    i = i + 1-    for _ = 1, n do-      redis.call('ZADD', e .. 'outs', ARGV[i + 1], ARGV[i])-      redis.call('HSET', e .. 'oval', ARGV[i], kept(a, ARGV[i + 2], ARGV[i + 3]))-      i = i + 4-    end-    -- what the pool has for the address, which pool.lua keeps up from now-    local rows = redis.call('ZRANGE', key.atx .. a, 0, -1, 'WITHSCORES')-    for j = 1, #rows, 2 do-      redis.call('ZADD', e .. 'txs', rows[j + 1], rows[j])-    end-    rows = redis.call('ZRANGE', key.aout .. a, 0, -1, 'WITHSCORES')-    for j = 1, #rows, 2 do-      local o = rows[j]-      local value = redis.call('HGET', key.aval .. a, o)-      local space = string.find(value, ' ', 1, true)-      redis.call('ZADD', e .. 'outs', rows[j + 1], o)-      redis.call('HSET', e .. 'oval', o, kept(a, string.sub(value, 1, space - 1), string.sub(value, space + 1)))-    end-  end-  redis.call('HSET', e .. 'meta', 'n0', n0, 'n1', n1, 'ver', redis.call('INCR', prefix .. 'fleet:xver'))-  redis.call('INCRBY', key.addrs, tonumber(ARGV[9]))-  return {'ok'}-end- if (redis.call('GET', key.tip) or '') ~= here then   return {'miss'} end@@ -378,6 +159,34 @@     return {'marked'}   end   return {'miss'}+end+-- A move of the tip marks what its blocks took out of the pool, and the+-- transactions leave after it (pool:leaving, and takeOut in+-- Haskoin.Store.Fleet.Pool.Decide). The entry has the chain at the tip+-- already, and what the pool keeps for its addresses still counts them.+-- So a read of an entry that has one of them answers {'leaving', ...}+-- with those, and reads nothing: the store takes them out and reads+-- again. Every transaction at an address of the entry is in its list,+-- whichever of the chain or the pool it is from.+local leaving = prefix .. 'pool:leaving'+if redis.call('EXISTS', leaving) == 1 then+  local found = {'leaving'}+  if redis.call('ZCARD', e .. 'txs') <= redis.call('HLEN', leaving) then+    for _, t in ipairs(redis.call('ZRANGE', e .. 'txs', 0, -1)) do+      if redis.call('HEXISTS', leaving, t) == 1 then+        found[#found + 1] = t+      end+    end+  else+    for _, t in ipairs(redis.call('HKEYS', leaving)) do+      if redis.call('ZSCORE', e .. 'txs', t) then+        found[#found + 1] = t+      end+    end+  end+  if #found > 1 then+    return found+  end end -- every read gives the version of the entry, which each change stamps local answer = {'ok', redis.call('HGET', e .. 'meta', 'ver') or '0'}
+ src/Haskoin/Store/Ingest.hs view
@@ -0,0 +1,1210 @@+-- |+-- Module      : Haskoin.Store.Ingest+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- How transactions get from the nodes that a store is a peer of to the+-- mempool that its fleet shares: one pure machine, 'step', that decides+-- everything between an announcement and the pool's verdict.+-- @docs\/mempool-ingestion.md@ has what it must guarantee (T1 to T7) and+-- what it may assume of a node (A1 to A8); this module is written to be+-- checked against that, and @Haskoin.Store.IngestSpec@ does the checking.+--+-- = Why one machine+--+-- The path was five stages joined by IO code, each free to lose a+-- transaction on terms of its own: a full queue, a request forgotten after+-- twenty seconds, a store out of sync for a moment. Each loss was excused+-- by "a peer announces again", and a node announces a transaction to a+-- peer once. Every stage passed its tests, and stores fell thousands of+-- transactions behind their nodes. What was wrong was in how the stages+-- compose, where nothing was stated and so nothing could be checked.+--+-- = The shape of it+--+-- * __Every id has one place__ ('Place'): wanted, asked of a peer, or+--   held with its body. The places are the values of one map, so an id is+--   never in two, and it leaves the map through one function, which says+--   why in an output ('Gone'). Nothing leaves in silence. The map is in+--   "Haskoin.Store.Ingest.Ledger", which this module cannot reach into:+--   that is what lets Liquid Haskell prove it of every state.+--+-- * __An id gets a place once the pool says that it has not decided on+--   it__ ('Check', 'Checked'). What a peer names is first asked of the+--   pool, and what is settled never takes room. A machine that gave the+--   named ids a place while it asked went round for ever on a mempool+--   larger than its room: each reading named the settled ones first, and+--   they took the room of those that it lacked.+--+-- * __A peer that connects owes what its node took before__, which the+--   node will not announce. A source is asked for its mempool when it+--   connects; when a peer that is none connects, the sources are read+--   again.+--+-- * __Giving up is allowed, and remembered.__ When there is no room, when+--   a peer goes, when a request gets no answer, the id is given up with a+--   reason and the machine is /dirty/. A dirty machine reads the whole+--   mempool of its sources again ('Sweep'), which names every transaction+--   that was given up and that a node still has. That is what makes every+--   loss temporary.+--+-- * __A window for each peer__, the most requests out to it: it grows+--   with every answer and halves when a request gets none, between the+--   bounds of the configuration.+--+-- * __A transaction that spends from one the machine is still fetching+--   waits for it__, and is offered when that one settles. A chain of+--   transactions that arrives in any order is offered root first, one+--   offer each.+--+-- * __What the pool lacks of what a held transaction spends from is asked+--   for__ (@seek@), of every peer, at once. It is not waited for: nothing+--   says that it will come by itself.+--+-- * __A stranger is not taken at its word.__ A peer is a node of the+--   operator ('Own'), or a stranger. What a node of the operator names or+--   sends is /vouched for/, and the pool takes it as the node did. What+--   only strangers named is looked at by the runner before it is offered:+--   forged, it is given up ('Forged'); if the store cannot tell, it is+--   held until a node of the operator names it, or given up+--   ('Unverified', 'Doubted').+--+-- = What the runner does+--+-- 'step' takes an 'Input' and gives 'Output's. The runner turns messages+-- of peers, answers of Redis and the clock into inputs, and carries out+-- the outputs: it sends, asks Redis, offers to the pool, and counts. It+-- decides nothing. A 'Check' and an 'Offer' are answered later by+-- 'Checked' and 'Offered', so that what may happen in between is a matter+-- of the order of inputs, which the specs go through exhaustively.+--+-- The peers, the ids and the bodies can be of any type that can be+-- compared, so that the specs run the machine on small numbers.+module Haskoin.Store.Ingest+  ( -- * The machine+    Ingest,+    Config (..),+    defaultConfig,+    start,+    step,+    Input (..),+    Output (..),+    Verdict (..),+    End (..),+    Reason (..),+    Tick,++    -- * Reading it+    Place (..),+    Hold (..),+    placeOf,+    ids,+    idCount,+    pending,+    holding,+    isDirty,+    Standing (..),+    standing,+    vouchedFor,+    hasSource,+    sourceCount,+    windowOf,++    -- * For the specs+    wellFormed,+    rebase,+  )+where++-- Liquid Haskell is given no type to check the functions of this module+-- against: it finds one for each, and checks that each handles every case,+-- ends, and calls the ledger as the ledger asks. To find them it puts an+-- unknown for what is true of each function, and by default writes each+-- unknown out wherever it is used before it solves for them. In a module+-- of small functions that call each other the formulas grow with that: it+-- took 6.5 GiB for this module, more than 12 once three functions on plain+-- numbers were added, and all that a machine had for a function that+-- never ends, where it gave no verdict at all. Without that step it has+-- three times as many things to check, each small, and takes 1 GiB and+-- less time, with the same verdicts. The option is for this module only:+-- the ledger and the cells have their types written, and are checked as+-- Liquid Haskell checks by default.+{-@ LIQUID "--eliminate=none" @-}++import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Set (Set)+import Data.Set qualified as Set+import Haskoin.Store.Ingest.Ledger+  ( End (..),+    Hold (..),+    Ledger,+    Output (..),+    Place (..),+    Reason (..),+    Tick,+    heldOf,+    newLedger,+    placesOf,+    rehold,+    retarget,+    retime,+  )+import Haskoin.Store.Ingest.Ledger qualified as L++-- | The bounds and the waits of a machine.+data Config = Config+  { -- | the most ids that the machine keeps a place for+    room :: !Int,+    -- | the most transactions that it holds the body of+    heldRoom :: !Int,+    -- | the fewest and the most requests out to one peer+    minWindow :: !Int,+    maxWindow :: !Int,+    -- | how long a request waits for its answer+    patience :: !Tick,+    -- | how long a transaction is held for transactions that it spends+    -- from and that do not come+    orphanLife :: !Tick,+    -- | the least time before a transaction that waits for others is+    -- offered again whether they came or not; it doubles from there+    retry :: !Tick,+    -- | the least time between two readings of the sources+    sweepGap :: !Tick,+    -- | a reading of the sources this often even when nothing was given+    -- up, or 0 for none+    sweepEvery :: !Tick,+    -- | and this often while peers name transactions that the pool+    -- lacks: not more than 'sweepEvery', and never sooner than 'sweepGap'+    sweepFast :: !Tick+  }+  deriving (Eq, Ord, Show)++-- | The bounds of a store: room for the ids of two full mempools of+-- Bitcoin Core, a hundred thousand bodies, windows from 16 to 4,096, a+-- request given twenty seconds and an orphan twenty minutes, offered again+-- after two seconds and then twice as long each time, and a reading of the+-- sources at most every ten seconds, every thirty while transactions+-- come, and at least every minute.+defaultConfig :: Config+defaultConfig =+  Config+    { room = 1000000,+      heldRoom = 100000,+      minWindow = 16,+      maxWindow = 4096,+      patience = 20000,+      orphanLife = 1200000,+      retry = 2000,+      sweepGap = 10000,+      sweepEvery = 60000,+      sweepFast = 30000+    }++-- | What the machine knows of a peer.+data Link h = Link+  { -- | whether it gives its whole mempool when asked+    source :: !Bool,+    -- | the most requests out to it+    window :: !Int,+    -- | the requests out to it+    out :: !Int,+    -- | the ids that it named and that are wanted, with the time since+    -- which each is wanted of it: the oldest is asked for first+    queue :: !(Set (Tick, h)),+    -- | the requests out to it, with the time of each: the oldest times+    -- out first+    asks :: !(Set (Tick, h)),+    -- | when its mempool was last asked for+    swept :: !(Maybe Tick),+    -- | whether something was given up since, that it may still have+    owed :: !Bool,+    -- | how long after its mempool was asked for it is asked for again,+    -- when nothing else has it asked for+    every :: !Tick,+    -- | whether a peer named a transaction that the pool lacked, since+    -- its mempool was asked for+    lively :: !Bool,+    -- | whether it is a node of the operator, which is taken at its word+    own :: !Bool,+    -- | when its mempool was first asked for since the store last may+    -- have missed something of it ('missed'): a reading from which+    -- nothing is known to be missing, and which is whole once the peer+    -- had the time to answer ('standing')+    since :: !(Maybe Tick)+  }+  deriving (Eq, Ord, Show)++-- | The machine.+data Ingest p h b = Ingest+  { config :: !Config,+    now :: !Tick,+    -- | whether the store has the blocks of its nodes+    synced :: !Bool,+    -- | whether it ever had them, since it started: until then nothing+    -- that a peer names or sends is taken in ('react')+    begun :: !Bool,+    -- | where each id is, and how many transactions are held: what+    -- only "Haskoin.Store.Ingest.Ledger" can change+    ledger :: !(Ledger p h b),+    links :: !(Map p (Link h)),+    -- | for a transaction, those held that wait for it+    waiters :: !(Map h (Set h)),+    -- | those held that wait, by the time to offer them again+    tries :: !(Set (Tick, h)),+    -- | those held that are ready to offer+    ready :: !(Set h),+    -- | those held whose offer could not be judged+    later :: !(Set h),+    -- | the ids with a place that a node of the operator named or sent,+    -- or that such a transaction spends from+    vouched :: !(Set h),+    -- | those held that wait for a node of the operator to name them, by+    -- the time to give them up+    doubts :: !(Set (Tick, h)),+    -- | whether something was given up that a node may still have+    dirty :: !Bool,+    -- | whether the machine has, since it started or since the pool lost+    -- what it had, read the nodes of the operator and seen the pool+    -- decide on all that they named ('standing')+    caughtUp :: !Bool,+    -- | how many questions to the pool about what a peer named have no+    -- answer yet: ids that have no place, and may get one+    checking :: !Int+  }+  deriving (Eq, Ord, Show)++-- | What happens to the machine.+data Input p h b+  = -- | the time+    Tick !Tick+  | -- | a peer connected; whether it is a source+    PeerUp !p !Bool+  | -- | a peer that is there is a node of the operator+    Own !p+  | -- | a peer is gone+    PeerDown !p+  | -- | whether the store has the blocks of its nodes+    Synced !Bool+  | -- | a peer named transactions (@inv@)+    Named !p ![h]+  | -- | a transaction came: from a peer, or from a client of the store+    Body !(Maybe p) !h !b+  | -- | a peer does not have what it was asked for (@notfound@)+    Missing !p ![h]+  | -- | the answer to a 'Check' of what a peer named: those that are+    -- settled, and those that are not+    Checked !p ![h] ![h]+  | -- | a 'Check' that got no answer+    Unchecked !p ![h]+  | -- | the pool's verdict on an 'Offer'+    Offered !h !(Verdict h)+  | -- | the pool lost what it had+    Emptied+  deriving (Eq, Ord, Show)++-- | What the pool says of an offer.+data Verdict h+  = -- | it has the transaction now, or a block does+    Settled+  | -- | it lacks these transactions that this one spends from+    Orphan ![h]+  | -- | it could not say: ask again+    Again+  | -- | not offered: no node takes it. A signature of it does not verify,+    -- or it spends more than it has. Only of what is not vouched for.+    Forged+  | -- | not offered: the store cannot verify it, and no node of the+    -- operator named it+    Unverified+  deriving (Eq, Ord, Show)++-- | A machine with nothing in it and no peer, at a time.+start :: Config -> Tick -> Ingest p h b+start config now =+  Ingest+    { config,+      now,+      synced = False,+      begun = False,+      ledger = newLedger (max 0 config.room) (max 0 config.heldRoom),+      links = Map.empty,+      waiters = Map.empty,+      tries = Set.empty,+      ready = Set.empty,+      later = Set.empty,+      vouched = Set.empty,+      doubts = Set.empty,+      dirty = False,+      caughtUp = False,+      checking = 0+    }++-- | The places of the ids.+places :: Ingest p h b -> Map h (Place p h b)+places s = placesOf s.ledger++-- | Change the ledger of a machine with one of the functions that keep+-- every id in its place.+edit :: (Ledger p h b -> Ledger p h b) -> Ingest p h b -> Ingest p h b+edit f s = s {ledger = f s.ledger}++-- | Where an id is, if the machine has it.+placeOf :: (Ord h) => h -> Ingest p h b -> Maybe (Place p h b)+placeOf h s = Map.lookup h (places s)++-- | The ids that the machine has a place for.+ids :: Ingest p h b -> Set h+ids s = Map.keysSet (places s)++-- | How many ids the machine has a place for. It is said after every+-- event, and @Set.size (ids s)@ makes a set of them all to count it: 0.8+-- milliseconds for 65,000 ids on a desktop, after each transaction that+-- comes. That was what a store of Bitcoin spent its time on while it took+-- a whole mempool: it took in 380 transactions a second with a core+-- busy, and 2,300 a second without it.+idCount :: Ingest p h b -> Int+idCount s = Map.size (places s)++-- | How many requests are out: what the health check of a store counts.+pending :: Ingest p h b -> Int+pending s = sum (map (.out) (Map.elems s.links))++-- | How many bodies are held.+holding :: Ingest p h b -> Int+holding s = heldOf s.ledger++-- | Whether something was given up that a node may still have, and a+-- source has not been read since, or there is none to read.+isDirty :: Ingest p h b -> Bool+isDirty s = s.dirty || any (\l -> l.source && l.owed) (Map.elems s.links)++-- | How the pool stands with the mempools of the nodes of the operator.+data Standing+  = -- | no node of the operator gives its mempool: the machine cannot+    -- tell. What strangers name says nothing of what the pool should+    -- have: a stranger may name what no honest node took, and keep quiet+    -- about what every node has.+    PoolUnknown+  | -- | the machine has not yet read the nodes of the operator and seen+    -- the pool decide on all that they named, since it started or since+    -- the pool lost what it had: the store shows fewer transactions than+    -- its node+    PoolSyncing+  | -- | it has+    PoolSynced+  deriving (Eq, Ord, Show)++-- | How the pool stands with the mempools of the nodes of the operator,+-- a t'Standing'. It is what a store says in its health, and nothing in+-- the machine depends on it.+standing :: Ingest p h b -> Standing+standing s+  | null (trusted s) = PoolUnknown+  | s.caughtUp = PoolSynced+  | otherwise = PoolSyncing++-- | The peers that are nodes of the operator and give their mempools:+-- those whose mempool the pool is measured against.+trusted :: Ingest p h b -> [Link h]+trusted s = filter (\l -> l.source && l.own) (Map.elems s.links)++-- | Note that the machine caught up, when it did: it is in sync, a node+-- of the operator gives its mempool, each such node was asked for it and+-- had the time to answer, none owes a reading, nothing was given up that+-- a node may still have, no question to the pool is on its way, and+-- nothing that a node of the operator vouched for has a place.+--+-- Nothing in the protocol says that the answer of a source is all there.+-- A node names its mempool in as many messages as it takes, and in none+-- when it has nothing; and what it names while it is asked may be a+-- transaction that it just took, and no part of the answer. So a source+-- has answered when as long passed as a request is given: a node that+-- named nothing by then is taken to have nothing. The ids that it named+-- are then on their way, and the machine has caught up when none is+-- left. A store therefore says that it is syncing for that long at+-- least, twenty seconds, after it starts.+--+-- The time is counted from the first reading since the store last may+-- have missed something of the node ('since', 'missed'), and not from+-- the last reading: a node that is read more often than a request is+-- given would otherwise never have answered. A reading that is owed for+-- a node of the operator to vouch for what a stranger named ('oweOwn')+-- does not start the count again: nothing of the node was missed, and a+-- store that strangers kept naming such transactions to would never+-- have caught up.+--+-- Only what a node of the operator vouched for counts. A transaction+-- that only strangers named, and that the store cannot verify, keeps+-- its place for twenty minutes, and is no part of what the pool should+-- have: a store among strangers said that it was filling for as long+-- as one was held, which was always.+--+-- A machine that loses its last node of the operator has not caught up+-- when one is back: what that node took meanwhile is not known.+settleUp :: Ingest p h b -> Ingest p h b+settleUp s+  | null nodes = if s.caughtUp then s {caughtUp = False} else s+  | s.caughtUp = s+  | s.synced && all heard nodes && not s.dirty && s.checking == 0 && Set.null s.vouched = s {caughtUp = True}+  | otherwise = s+  where+    nodes = trusted s+    heard l = case l.since of+      Just at -> s.now - at >= s.config.patience+      Nothing -> False++-- | The store may have missed something that a source has: it owes a+-- reading, and what it read before is no longer all that the source has.+missed :: Link h -> Link h+missed l = l {owed = True, since = Nothing}++-- | Whether a peer gives its whole mempool when asked. Without one, what+-- the store misses stays missed.+hasSource :: Ingest p h b -> Bool+hasSource s = any (.source) (Map.elems s.links)++-- | How many peers give their whole mempool when asked.+sourceCount :: Ingest p h b -> Int+sourceCount s = length (filter (.source) (Map.elems s.links))++-- | The window of a peer.+windowOf :: (Ord p) => p -> Ingest p h b -> Maybe Int+windowOf p s = (.window) <$> Map.lookup p s.links++-- | A step of the machine, given the transactions that a body spends+-- from: what it becomes, and what the runner is to do, in order.+step ::+  (Ord p, Ord h) =>+  (b -> [h]) ->+  Input p h b ->+  Ingest p h b ->+  (Ingest p h b, [Output p h b])+step parents input s0 =+  let (s1, o1) = react parents input s0+      (s2, o2) = pump s1+   in (settleUp s2, o1 <> o2)++-- | A machine and what it has said so far, newest first.+type Acc p h b = (Ingest p h b, [Output p h b])++-- | What an input does, before the machine looks for what it can do next.+react :: (Ord p, Ord h) => (b -> [h]) -> Input p h b -> Ingest p h b -> (Ingest p h b, [Output p h b])+react parents input s = case input of+  Tick t -> done (onTick (max s.now t) (s {now = max s.now t}, []))+  PeerUp p src+    | Map.member p s.links -> (s, [])+    | otherwise ->+        let link =+              Link+                { source = src,+                  window = s.config.minWindow,+                  out = 0,+                  queue = Set.empty,+                  asks = Set.empty,+                  swept = Nothing,+                  owed = False,+                  every = max s.config.sweepGap s.config.sweepFast,+                  lively = False,+                  own = False,+                  since = Nothing+                }+            -- A node names to a peer nothing that it took before the peer+            -- connected (A1). A peer that is a source is asked for its+            -- mempool, which has it. One that is none is not, so what its+            -- node took until now is owed by the sources: one of them may+            -- be that node, as its RPC is, and was read before.+            --+            -- Without this, a store that had the RPC of a node and was+            -- its peer read the RPC, connected a moment later, and never+            -- had what the node took in between: one test in many ended+            -- with four transactions lost, one for each of four that were+            -- sent at once, and all that spent from them waiting.+            others+              | src = s.links+              | otherwise = Map.map (\l -> if l.source then missed l else l) s.links+         in (s {links = Map.insert p link others}, [])+  Own p -> (s {links = Map.adjust (\l -> l {own = True}) p s.links}, [])+  PeerDown p -> done (peerDown p (s, []))+  Synced b -> (s {synced = b, begun = s.begun || b}, [])+  -- Until the store first has the blocks of its nodes, nothing that a+  -- peer names or sends is taken in. The store could not place it: the+  -- pool decides on a transaction from the outputs that it spends, and+  -- those are in blocks that the store has not yet. And by the time that+  -- it has them, most of what was named is in a block. A store that took+  -- 160,000 blocks in half an hour fetched what its node named+  -- meanwhile, held thousands of transactions that it could not place,+  -- and gave them up for seven minutes after it had its blocks.+  --+  -- Nothing is lost by it: a source has not been asked for its mempool+  -- yet, and is asked when the store has its blocks ('sweep'), which+  -- names all that its node has then.+  --+  -- A store that had its blocks and is a block behind for a moment goes+  -- on as before: it keeps what is named, and asks for nothing until it+  -- has the block ('pump').+  Named _ _ | not s.begun -> (s, [])+  Body (Just _) _ _ | not s.begun -> (s, [])+  Named p hs+    | Map.member p s.links ->+        -- what has a place is named by one more peer; the rest is asked+        -- of the pool before it gets one+        let one (st, new) h+              | Map.member h (places st) = (again h (vouchBy p h (also p h st)), new)+              | otherwise = (st, h : new)+            -- a stranger names again what is held for a node of the+            -- operator to name: a node still has it, and theirs may+            again h st = if doubted st h then oweOwn st else st+            (s', fresh) = foldl' one (s, []) hs+         in if null fresh then (s', []) else (s' {checking = s'.checking + 1}, [Check p (reverse fresh)])+    -- a peer that the machine does not know: it cannot be asked+    | otherwise -> (s, [])+  Body from h b -> done (body parents from h b (s, []))+  Missing p hs -> done (foldl' (unanswered NodeHasNot False p) (s, []) hs)+  Checked p settled unsettled ->+    done (foldl' (unsettled' p) (foldl' settle (answeredCheck s, []) settled) unsettled)+  Unchecked _ hs ->+    done (foldl' (\acc h -> if known h acc then acc else forget Unjudged h acc) (answeredCheck s, []) hs)+  Offered h v -> done (offered h v (s, []))+  Emptied -> (s {dirty = True, caughtUp = False}, [])+  where+    done (s', outs) = (s', reverse outs)+    known h (s', _) = Map.member h (places s')+    -- one question to the pool fewer is on its way+    answeredCheck st = st {checking = max 0 (st.checking - 1)}++-- | One more peer named an id that has a place.+also :: (Ord p, Ord h) => p -> h -> Ingest p h b -> Ingest p h b+also p h s = case Map.lookup h (places s) of+  Just (Wanted ms) | Map.notMember p ms -> queued p h (put (Wanted (Map.insert p s.now ms)))+  Just (Asked q t ps) | p /= q -> put (Asked q t (Set.insert p ps))+  _ -> s+  where+    put place = edit (retarget h place) s++-- | Put an id, wanted of a peer since now, among those to ask it for.+queued :: (Ord p, Ord h) => p -> h -> Ingest p h b -> Ingest p h b+queued p h s = s {links = Map.adjust (\l -> l {queue = Set.insert (s.now, h) l.queue}) p s.links}++-- | An id that has a place and is not held is wanted of these peers, since+-- now.+want :: (Ord p, Ord h) => h -> Set p -> Ingest p h b -> Ingest p h b+want h ps s = foldl' (\st p -> queued p h st) placed ps+  where+    placed = edit (retarget h (Wanted (Map.fromSet (const s.now) ps))) s++-- | An id is no longer wanted of the peers that it was wanted of: it is+-- out of their queues. Its place is for the caller to change.+unwant :: (Ord p, Ord h) => h -> Map p Tick -> Ingest p h b -> Ingest p h b+unwant h ms s = s {links = Map.foldlWithKey' out s.links ms}+  where+    out ls p t = Map.adjust (\l -> l {queue = Set.delete (t, h) l.queue}) p ls++-- | An id is given up, for a reason, wherever it is. It is something that+-- a node may still have, unless the node said that it has not.+forget :: (Ord p, Ord h) => Reason -> h -> Acc p h b -> Acc p h b+forget why h acc =+  let (s, said) = leave h (GaveUp why) acc+   in (s {dirty = s.dirty || mayHave why}, said)+  where+    -- A node may have what was given up for any reason but these. It+    -- said itself that it has it not; no node takes what is forged; and+    -- what was not vouched for is named again by a node of the operator+    -- that has it, at its next reading, with no need to ask for one.+    mayHave = \case+      NodeHasNot -> False+      IsForged -> False+      NotVouched -> False+      _ -> True++-- | The one way out of the machine: the id loses its place, the indexes+-- that mention it are put right, and an output says how it left. An id+-- that has no place leaves too, with the same word: it was learned and+-- let go in the same step.+leave :: (Ord p, Ord h) => h -> End -> Acc p h b -> Acc p h b+leave h end (s, said) =+  let s' = unplace h s+      (ledger, said') = L.leave h end s'.ledger said+   in (s' {ledger, vouched = Set.delete h s'.vouched}, said')++-- | Take an id out of every index that its place puts it in. Its place+-- is for the caller to change or to delete.+unplace :: (Ord p, Ord h) => h -> Ingest p h b -> Ingest p h b+unplace h s = case Map.lookup h (places s) of+  Just (Wanted ms) -> unwant h ms s+  Just (Asked p t _) -> answered p t h s+  Just (Held _ _ hold) -> unhold h hold s+  _ -> s++-- | A request to a peer is no longer out.+answered :: (Ord p, Ord h) => p -> Tick -> h -> Ingest p h b -> Ingest p h b+answered p t h s = s {links = Map.adjust (\l -> l {out = l.out - 1, asks = Set.delete (t, h) l.asks}) p s.links}++-- | Take a held transaction out of the indexes of what it waits for.+unhold :: (Ord h) => h -> Hold h -> Ingest p h b -> Ingest p h b+unhold h hold s = case hold of+  Ready -> s {ready = Set.delete h s.ready}+  Offering -> s+  Waiting ps t ->+    s+      { tries = Set.delete (t, h) s.tries,+        waiters = foldl' (\w p -> Map.update (nonEmpty . Set.delete h) p w) s.waiters ps+      }+  Later -> s {later = Set.delete h s.later}+  Doubted t -> s {doubts = Set.delete (t, h) s.doubts}+  where+    nonEmpty x = if Set.null x then Nothing else Just x++-- | Whether a node of the operator named or sent a transaction, or one+-- that spends from it: the runner offers such a transaction as the node+-- took it, and looks first at any other.+vouchedFor :: (Ord h) => h -> Ingest p h b -> Bool+vouchedFor h s = Set.member h s.vouched++-- | A peer named or sent a transaction that has a place: if the peer is+-- a node of the operator, the transaction is vouched for.+vouchBy :: (Ord p, Ord h) => p -> h -> Ingest p h b -> Ingest p h b+vouchBy p h s = case Map.lookup p s.links of+  Just l | isOwn l -> vouch h s+  _ -> s++-- | Whether a peer is a node of the operator.+isOwn :: Link h -> Bool+isOwn l = l.own++-- | A transaction that has a place is vouched for, and with it every+-- transaction that it waits for, and that those wait for: a node that+-- took a transaction took what it spends from, or a block has it. One+-- that was held to be vouched for is ready to offer.+vouch :: (Ord h) => h -> Ingest p h b -> Ingest p h b+vouch h s = foldl' one s (awaited h s)+  where+    one st x = case Map.lookup x (places st) of+      Just (Held _ _ hold@(Doubted _)) -> makeReady x (unhold x hold st) {vouched = Set.insert x st.vouched}+      Just _ -> st {vouched = Set.insert x st.vouched}+      Nothing -> st++-- | A transaction, those that it waits for, and those that they wait+-- for, to the end.+awaited :: (Ord h) => h -> Ingest p h b -> [h]+awaited h s = closure (\x -> case Map.lookup x (places s) of Just (Held _ _ (Waiting ps _)) -> ps; _ -> Set.empty) h++-- | A transaction, those that wait for it, and those that wait for+-- them, to the end.+family :: (Ord h) => h -> Ingest p h b -> [h]+family h s = closure (\x -> Map.findWithDefault Set.empty x s.waiters) h++-- | All that is reached from one by a relation. It ends: each round+-- takes what the last one found and was not found before, of a set that+-- only grows, among the ids of the machine.+closure :: (Ord h) => (h -> Set h) -> h -> [h]+closure next h = Set.toList (fst (until (Set.null . snd) grow (Set.singleton h, Set.singleton h)))+  where+    grow (seen, frontier) =+      let found = Set.unions (map next (Set.toList frontier)) `Set.difference` seen+       in (Set.union seen found, found)++-- | An id got a place: it is vouched for if a transaction that waits for+-- it is.+inherit :: (Ord h) => h -> Ingest p h b -> Ingest p h b+inherit h s+  | any (\c -> Set.member c s.vouched) (Set.toList (Map.findWithDefault Set.empty h s.waiters)) = vouch h s+  | otherwise = s++-- | Give up a transaction and all that waits for it, for one reason:+-- what spends from a transaction that no node takes, or that nobody+-- vouches for, is no better than it.+disown :: (Ord p, Ord h) => Reason -> h -> Acc p h b -> Acc p h b+disown why h acc@(s, _) = foldl' (\a c -> forget why c a) acc (family h s)++-- | The pool has decided on an id: it leaves, whether it had a place or+-- was only being checked, and what waited for it is ready.+settle :: (Ord p, Ord h) => Acc p h b -> h -> Acc p h b+settle acc h = wake h (leave h Done acc)++-- | The transactions that waited for one are let go of it, and those that+-- wait for nothing else are ready.+wake :: (Ord h) => h -> Acc p h b -> Acc p h b+wake h (s, said) = (foldl' free s {waiters = Map.delete h s.waiters} children, said)+  where+    children = maybe [] Set.toList (Map.lookup h s.waiters)+    free st c = case Map.lookup c (places st) of+      Just (Held _ _ (Waiting ps t)) ->+        let rest = Set.delete h ps+         in if Set.null rest+              then (edit (rehold c Ready) st) {tries = Set.delete (t, c) st.tries, ready = Set.insert c st.ready}+              else edit (rehold c (Waiting rest t)) st+      _ -> st++-- | The pool has not decided on an id that a peer named: it is wanted of+-- that peer, if the peer is still there and there is room.+unsettled' :: (Ord p, Ord h) => p -> Acc p h b -> h -> Acc p h b+unsettled' p acc@(s, said) h+  -- the peer left while the pool was asked: it cannot be asked for it+  | Map.notMember p s.links = if Map.member h (places s) then acc else forget PeerGone h acc+  | Map.member h (places s) = (vouchBy p h (also p h s), said)+  | otherwise = case L.put h (Wanted (Map.singleton p s.now)) s.ledger of+      Just ledger -> (vouchBy p h (inherit h (told (queued p h s {ledger}))), said)+      Nothing -> forget NoRoom h acc++-- | A peer named a transaction that the pool lacks: transactions are+-- coming, and the sources are read again after the shortest wait.+--+-- A node names transactions to a peer no faster than it chooses to.+-- Bitcoin Core names about five hundred at once and then seventy every+-- five seconds, to a peer that it whitelists too, and a node that takes+-- more than fourteen a second for a few minutes has thousands that it+-- has not named to anyone yet. Its mempool, when asked for, has them+-- all. So a store that reads it only every ten minutes is minutes behind+-- its node whenever transactions come fast, and one that reads it while+-- they come is half a minute behind at most.+--+-- Whether they come fast, the machine cannot tell: it sees what the node+-- names, at the node's pace. So it reads while they come at all, and+-- waits twice as long each time that a reading comes after none came+-- ('sweep').+told :: Ingest p h b -> Ingest p h b+told s+  | s.config.sweepEvery > 0 = s {links = Map.map soon s.links}+  | otherwise = s+  where+    soon l+      | l.source = l {lively = True, every = max s.config.sweepGap s.config.sweepFast}+      | otherwise = l++-- | A request of a peer got no answer, or the answer that the peer does+-- not have it: the id is wanted of the others that named it, or given up.+-- Says whether to give the peer a smaller window.+unanswered :: (Ord p, Ord h) => Reason -> Bool -> p -> Acc p h b -> h -> Acc p h b+unanswered why shrink p acc@(s, said) h = case Map.lookup h (places s) of+  Just (Asked q t ps)+    | q == p ->+        let s1 = narrowed (answered p t h s)+         in if Set.null ps+              then forget why h (edit (retarget h (Wanted Map.empty)) s1, said)+              else (want h ps s1, said)+  _ -> acc+  where+    narrowed st+      | shrink = st {links = Map.adjust (\l -> l {window = max st.config.minWindow (l.window `div` 2)}) p st.links}+      | otherwise = grown p st++-- | A peer answered: its window grows by one, up to the most.+grown :: (Ord p) => p -> Ingest p h b -> Ingest p h b+grown p s = s {links = Map.adjust (\l -> l {window = min s.config.maxWindow (l.window + 1)}) p s.links}++-- | A transaction came. It is held: to offer, or to wait for those that it+-- spends from and that the machine is still getting.+body :: (Ord p, Ord h) => (b -> [h]) -> Maybe p -> h -> b -> Acc p h b -> Acc p h b+body parents from h b acc@(s, said) = case Map.lookup h (places s) of+  -- held already: a node of the operator that sends it vouches for it+  Just (Held {}) -> (sent s, said)+  Just (Asked q _ _) -> hold (credit q (unplace h s))+  Just _ -> hold (unplace h s)+  Nothing -> hold s+  where+    -- vouched for before it came: so is what it now waits for+    again st = if Set.member h st.vouched then vouch h st else st+    -- the transaction has a place: its sender vouches for it, if it is a+    -- node of the operator+    sent st = case from of+      Just p -> vouchBy p h st+      Nothing -> st+    -- the peer that was asked answered, if it is the one that sent this+    credit q st = if from == Just q then grown q st else st+    -- the body is held if the ledger has room: for one more id if this+    -- one is new, and for one more body+    hold st = case holdAs st of+      Just (how, indexed)+        | Just ledger <- L.put h (Held b st.now how) st.ledger -> (sent (inherit h (again indexed {ledger})), said)+      _ -> gone st+    -- what the body waits for, with the indexes that say so+    holdAs st+      | Set.null waits = Just (Ready, st {ready = Set.insert h st.ready})+      | mayWait st = let (t, st') = waiting h st.now waits st in Just (Waiting waits t, st')+      | otherwise = Nothing+      where+        waits = Set.fromList [p | p <- parents b, p /= h, Map.member p (places st)]+    -- no room for the body: the id goes, from wherever it was+    gone st = forget NoRoom h (edit (retarget h (Wanted Map.empty)) st, said)++-- | Whether one more transaction may be held to wait for others: never+-- the last of the room for bodies, which is kept for those that can be+-- offered as they come. With every body waiting for another that had no+-- room, nothing would ever be offered.+mayWait :: Ingest p h b -> Bool+mayWait s = Set.size s.tries + Set.size s.doubts < s.config.heldRoom - 1++-- | A held transaction is ready to offer.+makeReady :: (Ord h) => h -> Ingest p h b -> Ingest p h b+makeReady h s = (edit (rehold h Ready) s) {ready = Set.insert h s.ready}++-- | Note that a held transaction waits for others, and when to offer it+-- again in any case: after a time that grows with how long it has been+-- held. Gives that time; its place is for the caller to set.+waiting :: (Ord h) => h -> Tick -> Set h -> Ingest p h b -> (Tick, Ingest p h b)+waiting h since ps s =+  let t = s.now + max s.config.retry (s.now - since)+   in ( t,+        s+          { tries = Set.insert (t, h) s.tries,+            waiters = foldl' (\w p -> Map.insertWith Set.union p (Set.singleton h) w) s.waiters ps+          }+      )++-- | The pool's verdict on an offer.+offered :: (Ord p, Ord h) => h -> Verdict h -> Acc p h b -> Acc p h b+offered h v acc@(s, said) = case Map.lookup h (places s) of+  Just (Held _ since Offering) -> case v of+    Settled -> settle acc h+    Orphan ps+      | s.now - since > s.config.orphanLife -> forget WaitedTooLong h acc+      | otherwise -> case Set.delete h (Set.fromList ps) of+          waits+            | Set.null waits -> again+            | mayWait s ->+                let (t, s') = waiting h since waits (foldl' (sought h) s waits)+                 in (edit (rehold h (Waiting waits t)) s', said)+            | otherwise -> forget NoRoom h acc+    Again -> again+    Forged -> disown IsForged h acc+    Unverified+      -- a node of the operator named it since it was offered: offered+      -- again, as vouched for+      | Set.member h s.vouched -> again+      | mayDoubt s ->+          let t = since + s.config.orphanLife+           in (oweOwn (edit (rehold h (Doubted t)) s) {doubts = Set.insert (t, h) s.doubts}, said)+      | otherwise -> disown NotVouched h acc+  _ -> acc+  where+    again = ((edit (rehold h Later) s) {later = Set.insert h s.later}, said)++-- | Whether one more transaction may be held for a node of the operator+-- to name it: as 'mayWait', never the last of the room for bodies, with+-- those that wait for others counted too.+mayDoubt :: Ingest p h b -> Bool+mayDoubt = mayWait++-- | The pool lacks a transaction that a held one spends from. If the+-- machine has no place for it, it is wanted of every peer, since now, as+-- if each had named it: a node that has a transaction has what it spends+-- from, or a block has confirmed that.+--+-- The machine waited for it to come by itself once, trying the held+-- transaction again after two seconds, then four, then eight, and giving+-- it up after twenty minutes, to read the sources again. A transaction+-- that the store had lost without knowing it, which happened, then kept+-- all that spent from it out of the pool for as long: 84 transactions+-- behind four, in one test. Asking costs a request, and a node that has+-- it not says so.+--+-- The pool has just said that it lacks the transaction, so it is not+-- asked again whether it has it, as it is for what a peer names+-- ('Check').+--+-- With no peer to ask, or no room, nothing is done here, and the held+-- transaction waits as it did.+seek :: (Ord p, Ord h) => Ingest p h b -> h -> Ingest p h b+seek s p+  | Map.member p (places s) || Set.null peers = s+  | otherwise = case L.put p (Wanted (Map.fromSet (const s.now) peers)) s.ledger of+      Just ledger -> inherit p (foldl' (\st q -> queued q p st) s {ledger} peers)+      Nothing -> s+  where+    peers = Map.keysSet s.links++-- | 'seek' what a held transaction spends from, and vouch for it if the+-- held one is vouched for: a node that took a transaction took what it+-- spends from, or a block has it.+sought :: (Ord p, Ord h) => h -> Ingest p h b -> h -> Ingest p h b+sought child s p =+  let s' = seek s p+   in if Set.member child s'.vouched then vouch p s' else s'++-- | A peer is gone: what was asked of it is wanted of the others, and+-- what only it named is given up.+peerDown :: (Ord p, Ord h) => p -> Acc p h b -> Acc p h b+peerDown p (s, said)+  | Map.notMember p s.links = (s, said)+  | otherwise = foldl' one (s {links = Map.delete p s.links}, said) (Map.toList (places s))+  where+    one acc@(st, o) (h, place) = case place of+      Wanted ms+        | Map.member p ms ->+            let rest = Map.delete p ms+             in if Map.null rest then gone acc h else (edit (retarget h (Wanted rest)) st, o)+      Asked q t ps+        | q == p ->+            if Set.null ps+              then gone (edit (retarget h (Wanted Map.empty)) st, o) h+              else (want h ps st, o)+        | Set.member p ps -> (edit (retarget h (Asked q t (Set.delete p ps))) st, o)+      _ -> acc+    gone acc h = forget PeerGone h acc++-- | What the time brings: requests that waited too long, and held+-- transactions to offer again or to give up.+onTick :: (Ord p, Ord h) => Tick -> Acc p h b -> Acc p h b+onTick t acc0 = undoubted (retried (laterOnes (foldl' overdue acc0 (Map.keys (fst acc0).links))))+  where+    -- held transactions that no node of the operator named in time:+    -- those whose time it is now, each once+    undoubted acc@(s0, _) = foldl' doubt1 acc (takeWhile ((<= t) . fst) (Set.toAscList s0.doubts))+    doubt1 acc@(s, said) (at, h) = case Map.lookup h (places s) of+      Just (Held _ _ (Doubted _)) -> disown NotVouched h acc+      _ -> (s {doubts = Set.delete (at, h) s.doubts}, said)+    -- the requests of a peer that are out for longer than the patience:+    -- those that are so now, each once, so that this ends whatever the+    -- indexes say+    overdue acc@(s, _) p = case Map.lookup p s.links of+      Just l ->+        let late = [h | (at, h) <- Set.toAscList l.asks, t - at > s.config.patience]+         in foldl' (unanswered Unanswered True p) acc late+      Nothing -> acc+    -- offers that could not be judged are ready again+    laterOnes (s, said) =+      let again st h = case Map.lookup h (places st) of+            Just (Held _ _ Later) -> makeReady h st+            _ -> st+       in (foldl' again s {later = Set.empty} s.later, said)+    -- held transactions whose time to be offered again has come: those+    -- whose time it is now, each once+    retried acc@(s0, _) = foldl' retry1 acc (takeWhile ((<= t) . fst) (Set.toAscList s0.tries))+    retry1 acc@(s, said) (at, h) = case Map.lookup h (places s) of+      Just (Held _ since hold@(Waiting ps _))+        | t - since > s.config.orphanLife ->+            -- what it waited for is itself held for a node of the+            -- operator to name it: no reading of a source brings that+            if any (doubted s) (Set.toList ps) then disown NotVouched h acc else forget WaitedTooLong h acc+        | onTheirWay ps s -> (putOff h at since ps s, said)+        | otherwise -> (makeReady h (unhold h hold s), said)+      _ -> (s {tries = Set.delete (at, h) s.tries}, said)++-- | Whether every transaction that a held one waits for has a place: each+-- is wanted, asked for or held, and the held one is made ready when the+-- last of them settles ('wake').+--+-- Such a transaction is not offered when its time comes. The pool lacks+-- what it spends from, and would only say so. A machine that offered it+-- all the same, after two seconds, then four, then eight, spent most of+-- its offers on that when a whole mempool came at once, one offer at a+-- time: given 65,000 transactions in chains of 24, it made 103,862 offers+-- that the pool refused beside the 65,000 that it took, and a store+-- filling an empty pool from Bitcoin Core made 44,000 beside 24,000.+--+-- One that it waits for and that has no place was given up, and nothing+-- will wake the held one: that is what its time is for.+onTheirWay :: (Ord h) => Set h -> Ingest p h b -> Bool+onTheirWay ps s = all (\p -> Map.member p (places s)) (Set.toList ps)++-- | A held transaction whose time came keeps waiting for the same+-- transactions, until a later time: as much later as 'waiting' says of+-- one held since then.+putOff :: (Ord h) => h -> Tick -> Tick -> Set h -> Ingest p h b -> Ingest p h b+putOff h at since ps s =+  let (t, s') = waiting h since ps s {tries = Set.delete (at, h) s.tries}+   in edit (rehold h (Waiting ps t)) s'++-- | The sources that are nodes of the operator owe a reading. A node+-- that has a transaction names it when its mempool is read, and one whose+-- RPC is all that the store has of it names nothing by itself: a+-- transaction that waits for such a node to name it would wait for the+-- clock.+oweOwn :: Ingest p h b -> Ingest p h b+oweOwn s = s {links = Map.map (\l -> if l.own && l.source then l {owed = True} else l) s.links}++-- | Whether a transaction is held for a node of the operator to name it.+doubted :: (Ord h) => Ingest p h b -> h -> Bool+doubted s h = case Map.lookup h (places s) of+  Just (Held _ _ (Doubted _)) -> True+  _ -> False++-- | What the machine can do as it is: read its sources if something is+-- owed or it is time, request what is wanted within the windows, and+-- offer what is ready. Only a store that has the blocks of its nodes does+-- any of it.+pump :: (Ord p, Ord h) => Ingest p h b -> (Ingest p h b, [Output p h b])+pump s0+  | not s0.synced = (s0, [])+  | otherwise =+      let (s1, sweeps) = sweep s0+          (s2, gets) = foldl' request (s1, []) (Map.keys s1.links)+          (s3, offers) = offer s2+       in (s3, sweeps <> reverse gets <> offers)+  where+    request (s, said) p =+      let (s', got) = requests p s+       in (s', [Get p (reverse got) | not (null got)] <> said)++-- | Request of a peer the ids that are wanted of it, oldest first, as+-- many as its window has room for: those at the front of its queue now,+-- each once. Gives them newest first.+requests :: (Ord p, Ord h) => p -> Ingest p h b -> (Ingest p h b, [h])+requests p s = case Map.lookup p s.links of+  Just l -> foldl' ask (s, []) (take (l.window - l.out) (map snd (Set.toAscList l.queue)))+  Nothing -> (s, [])+  where+    ask (st, got) h = case Map.lookup h (places st) of+      Just (Wanted ms) ->+        let s1 = unwant h ms st+            out l = l {out = l.out + 1, asks = Set.insert (st.now, h) l.asks}+            asked = Asked p st.now (Set.delete p (Map.keysSet ms))+         in ((edit (retarget h asked) s1) {links = Map.adjust out p s1.links}, h : got)+      _ -> (st, got)++-- | Ask the sources for their mempools: each one when it connects, when+-- something was given up since it was last asked, and when it is time,+-- and none sooner than the gap after its last time. What was given up is+-- owed by every source, since any of their nodes may have it, and a+-- source owes it until it is asked: reading one does not clear another.+--+-- When it is time depends on whether transactions come ('told'): after+-- the shortest wait if a peer named one that the pool lacked since the+-- last reading, and after twice the last wait if none did, up to the+-- longest. A store of a network where nothing happens reads a mempool+-- that does not change every minute, and one of a network that+-- never rests every thirty seconds.+sweep :: (Ord p) => Ingest p h b -> (Ingest p h b, [Output p h b])+sweep s0+  | null due = (s, [])+  | otherwise =+      ( s {links = foldl' (\ls p -> Map.adjust asked p ls) s.links due},+        map Sweep due+      )+  where+    asked l = l {swept = Just s.now, owed = False, lively = False, every = after l, since = first l}+    -- the first reading since something may have been missed+    first l = case l.since of+      Nothing -> Just s.now+      at -> at+    -- the wait until the next reading that nothing else asks for+    after l+      | l.lively = max s.config.sweepGap s.config.sweepFast+      | otherwise =+          let was = max (max s.config.sweepGap s.config.sweepFast) l.every+           in min (max was s.config.sweepEvery) (was + was)+    -- with a source to read, what was given up becomes what each owes+    s+      | s0.dirty && any (.source) (Map.elems s0.links) =+          s0 {dirty = False, links = Map.map (\l -> if l.source then missed l else l) s0.links}+      | otherwise = s0+    due = [p | (p, l) <- Map.toList s.links, l.source, wants l]+    wants l = case l.swept of+      -- a node does not announce what it took before the peer connected+      Nothing -> True+      Just at ->+        (l.owed && s.now - at >= s.config.sweepGap)+          || (s.config.sweepEvery > 0 && s.now - at >= l.every)++-- | Offer what is ready.+offer :: (Ord h) => Ingest p h b -> (Ingest p h b, [Output p h b])+offer s = (foldl' mark s {ready = Set.empty} offers, [Offer h b | (h, b) <- offers])+  where+    offers = [(h, b) | h <- Set.toList s.ready, Just (Held b _ Ready) <- [Map.lookup h (places s)]]+    mark st (h, _) = edit (rehold h Offering) st++-- | What is wrong with a machine, if anything: the invariant that every+-- step keeps (@Haskoin.Store.IngestSpec@). Each line is something that+-- another part of the machine relies on.+wellFormed :: (Ord p, Ord h) => Ingest p h b -> [String]+wellFormed s =+  concat+    [ ["more ids than there is room for" | length placed > s.config.room],+      ["more bodies than there is room for" | heldOf s.ledger > s.config.heldRoom],+      ["the count of bodies is wrong" | heldOf s.ledger /= length [() | Held {} <- map snd placed]],+      ["the count of requests out to a peer is wrong" | l <- Map.elems s.links, l.out /= Set.size l.asks],+      [ "a window out of its bounds"+      | l <- Map.elems s.links,+        l.window < s.config.minWindow || l.window > s.config.maxWindow+      ],+      ["more requests out than the most a window allows" | l <- Map.elems s.links, l.out > s.config.maxWindow],+      [ "a wait between two readings of a source longer than the longest"+      | s.config.sweepEvery > 0,+        l <- Map.elems s.links,+        l.every > max (max s.config.sweepGap s.config.sweepFast) s.config.sweepEvery+      ],+      ["a peer that is gone is still named" | ps <- namers, not (ps `Set.isSubsetOf` Map.keysSet s.links)],+      ["an id that nobody named is waiting to be asked for" | Wanted ms <- map snd placed, Map.null ms],+      [ "every body held waits for another, or to be vouched for"+      | s.config.heldRoom > 0,+        Set.size s.tries + Set.size s.doubts >= s.config.heldRoom+      ],+      [ "the ids to ask a peer for are not those wanted of it"+      | (p, l) <- Map.toList s.links,+        l.queue /= Set.fromList [(t, h) | (h, Wanted ms) <- placed, Just t <- [Map.lookup p ms]]+      ],+      [ "the requests out to a peer are not those asked of it"+      | (p, l) <- Map.toList s.links,+        l.asks /= Set.fromList [(t, h) | (h, Asked q t _) <- placed, q == p]+      ],+      [ "the transactions to offer are not those ready"+      | s.ready /= Set.fromList [h | (h, Held _ _ Ready) <- placed]+      ],+      [ "the transactions to offer later are not those"+      | s.later /= Set.fromList [h | (h, Held _ _ Later) <- placed]+      ],+      [ "the times to offer again are not those of what waits"+      | s.tries /= Set.fromList [(t, h) | (h, Held _ _ (Waiting _ t)) <- placed]+      ],+      [ "the times to give up what is doubted are not those of what is doubted"+      | s.doubts /= Set.fromList [(t, h) | (h, Held _ _ (Doubted t)) <- placed]+      ],+      ["an id without a place is vouched for" | not (s.vouched `Set.isSubsetOf` placedIds)],+      ["a transaction that is vouched for is doubted" | (h, Held _ _ (Doubted _)) <- placed, Set.member h s.vouched],+      [ "a transaction that is vouched for waits for one that has a place and is not"+      | (h, Held _ _ (Waiting ps _)) <- placed,+        Set.member h s.vouched,+        p <- Set.toList ps,+        Set.member p placedIds,+        Set.notMember p s.vouched+      ],+      ["a transaction waits for nothing" | Held _ _ (Waiting ps _) <- map snd placed, Set.null ps],+      [ "the index of what waits for a transaction is wrong"+      | s.waiters+          /= Map.fromListWith+            Set.union+            [(p, Set.singleton h) | (h, Held _ _ (Waiting ps _)) <- placed, p <- Set.toList ps]+      ]+    ]+  where+    -- the places, read once+    placed = Map.toList (places s)+    placedIds = Set.fromList (map fst placed)+    namers =+      concat+        [ case place of+            Wanted ms -> [Map.keysSet ms]+            Asked p _ ps -> [Set.insert p ps]+            Held {} -> []+        | place <- map snd placed+        ]++-- | The same machine with its clock at 0 and every time counted from+-- there, none further back than a bound. Two machines that differ only in+-- when they are, and in how long ago things happened that happened longer+-- ago than matters, become equal: what lets a spec go through every state+-- of a machine whose clock never stops.+rebase :: (Ord h) => Tick -> Ingest p h b -> Ingest p h b+rebase bound s =+  s+    { now = 0,+      ledger = retime rel s.ledger,+      links = Map.map link s.links,+      tries = Set.map (\(t, h) -> (rel t, h)) s.tries,+      doubts = Set.map (\(t, h) -> (rel t, h)) s.doubts+    }+  where+    rel t = max (negate bound) (t - s.now)+    link l = l {queue = times l.queue, asks = times l.asks, swept = rel <$> l.swept, since = first <$> l.since}+    -- 'since' is only asked whether it is as long ago as a request is+    -- given, and not at all by a machine that caught up, which forgets it+    -- before it asks again ('missed'): longer ago is all the same+    first t+      | s.caughtUp = long+      | otherwise = max long (t - s.now)+    long = negate s.config.patience+    times = Set.map (\(t, h) -> (rel t, h))
+ src/Haskoin/Store/Ingest/Ledger.hs view
@@ -0,0 +1,315 @@+-- |+-- Module      : Haskoin.Store.Ingest.Ledger+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- Where each transaction id is on its way to the pool, and the only+-- functions that can put one there or take it away. It is the part of+-- "Haskoin.Store.Ingest" that two of its guarantees rest on+-- (@docs\/mempool-ingestion.md@), kept apart and small so that they can be+-- __proved for every state__, by Liquid Haskell, and not only checked in+-- small worlds:+--+-- * __T1, nothing leaves in silence.__ A t'Ledger' is abstract: the machine+--   cannot build one or reach into one. An id loses its place through+--   'leave' alone, and 'leave' says so, with an output, in the same call.+--   Every other function here keeps every id. So whatever the machine+--   does, an id that it had and no longer has was said to be 'Gone'.+--+-- * __T2, the bounds.__ A ledger never has more ids than its room, nor+--   more transactions held than its room for those. 'put' is the one+--   function that adds, and it refuses when there is no room.+--+-- The refinement types in the comments that start with @{-\@@ state this,+-- and @cabal build@ in @proofs\/@ checks them. Liquid Haskell does not see+-- through the dot of a record field, so this module reads its records by+-- matching on them, unlike the rest of the store.+--+-- What is assumed, not proved, is what "Data.Map" does: that an insert+-- adds its key and at most one to the size, that a delete takes its key+-- away, that a lookup finds a key exactly when it is there. Those+-- assumptions are the @assume@ lines below.+module Haskoin.Store.Ingest.Ledger+  ( -- * The types of the machine+    Tick,+    Place (..),+    Hold (..),+    Output (..),+    End (..),+    Reason (..),+    goneOf,++    -- * The ledger+    Ledger,+    newLedger,+    placesOf,+    heldOf,+    hasPlace,++    -- * Changing it+    put,+    retarget,+    rehold,+    retime,+    leave,+  )+where++import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (isJust)+import Data.Set (Set)+import Data.Set qualified as Set++-- | A moment, in milliseconds of a clock that does not go back.+type Tick = Int++-- | Where an id is.+data Place p h b+  = -- | not settled, and to request from one of these peers, each with+    -- the time since which it is wanted of that peer+    Wanted !(Map p Tick)+  | -- | requested of a peer at a time; the others named it too+    Asked !p !Tick !(Set p)+  | -- | its body is here, since a time+    Held !b !Tick !(Hold h)+  deriving (Eq, Ord, Show)++-- | What a transaction that is held waits for.+data Hold h+  = -- | to be offered at the next occasion+    Ready+  | -- | the pool's verdict on an offer+    Offering+  | -- | these transactions that it spends from, and a time to offer it+    -- again whether they came or not+    Waiting !(Set h) !Tick+  | -- | the next tick, after an offer that could not be judged+    Later+  | -- | a node of the operator to name it, until this time: the store+    -- could not verify it, and only strangers named it+    Doubted !Tick+  deriving (Eq, Ord, Show)++-- | What the runner is to do.+data Output p h b+  = -- | request these transactions of a peer (@getdata@)+    Get !p ![h]+  | -- | ask a peer for its mempool (@mempool@)+    Sweep !p+  | -- | find out which of these, that a peer named, the pool has decided+    -- on+    Check !p ![h]+  | -- | offer a transaction to the pool+    Offer !h !b+  | -- | an id left the machine, and how+    Gone !h !End+  deriving (Eq, Ord, Show)++-- | How an id left.+data End+  = -- | the pool decided on it+    Done+  | -- | given up+    GaveUp !Reason+  deriving (Eq, Ord, Show)++-- | Why an id was given up.+data Reason+  = -- | every peer that named it says it does not have it+    NodeHasNot+  | -- | a request for it got no answer, and no other peer named it+    Unanswered+  | -- | there was no room for it+    NoRoom+  | -- | the peers that named it are gone+    PeerGone+  | -- | what it spends from did not come+    WaitedTooLong+  | -- | the pool could not say whether it had decided on it+    Unjudged+  | -- | it is no transaction that a node takes: a signature of it does+    -- not verify, or it spends more than it has+    IsForged+  | -- | the store could not verify it, and no node of the operator named+    -- it+    NotVouched+  deriving (Eq, Ord, Show, Enum, Bounded)++-- What Liquid Haskell is told of maps: their keys and their size, and+-- what the functions used here do to them. The assumptions are on+-- functions of this module that only name those of "Data.Map": on the+-- functions of "Data.Map" themselves they would hold for every map of+-- every module that imports this one, and Liquid Haskell would carry+-- them through all of the machine.++{-@ measure mkeys :: Map k v -> Set k @-}++{-@ measure msize :: Map k v -> Int @-}++{-@ assume mEmpty :: {m:Map k v | Set_emp (mkeys m) && msize m = 0} @-}+mEmpty :: Map k v+mEmpty = Map.empty++{-@ assume mSize :: m:Map k v -> {n:Nat | n = msize m} @-}+mSize :: Map k v -> Int+mSize = Map.size++{-@ assume mLookup :: (Ord k) => x:k -> m:Map k v -> {r:Maybe v | isJust r <=> Set_mem x (mkeys m)} @-}+mLookup :: (Ord k) => k -> Map k v -> Maybe v+mLookup = Map.lookup++{-@ assume mInsert :: (Ord k) => x:k -> v -> m:Map k v+      -> {n:Map k v | mkeys n = Set_cup (mkeys m) (Set_sng x)+                      && msize n = (if (Set_mem x (mkeys m)) then (msize m) else (msize m + 1))} @-}+mInsert :: (Ord k) => k -> v -> Map k v -> Map k v+mInsert = Map.insert++{-@ assume mDelete :: (Ord k) => x:k -> m:Map k v+      -> {n:Map k v | mkeys n = Set_dif (mkeys m) (Set_sng x) && msize n <= msize m && 0 <= msize n} @-}+mDelete :: (Ord k) => k -> Map k v -> Map k v+mDelete = Map.delete++{-@ assume mAdjust :: (Ord k) => (v -> v) -> k -> m:Map k v+      -> {n:Map k v | mkeys n = mkeys m && msize n = msize m} @-}+mAdjust :: (Ord k) => (v -> v) -> k -> Map k v -> Map k v+mAdjust = Map.adjust++{-@ assume mMap :: (v -> w) -> m:Map k v -> {n:Map k w | mkeys n = mkeys m && msize n = msize m} @-}+mMap :: (v -> w) -> Map k v -> Map k w+mMap = Map.map++-- | The places of the ids, with how many of them are transactions held,+-- within the room for each. The fields are not strict: Liquid Haskell+-- cannot refine a constructor whose numbers GHC unpacks. Every function+-- here builds a ledger from values that it has already looked at.+data Ledger p h b = Ledger Int Int (Map h (Place p h b)) Int+  deriving (Eq, Ord, Show)++{-@ data Ledger p h b = Ledger+      { lRoom :: Nat,+        lHeldRoom :: Nat,+        lPlaces :: {m:Map h (Place p h b) | msize m <= lRoom},+        lHeld :: {n:Nat | n <= lHeldRoom}+      } @-}++-- | The id that an output says is gone, if it says so of one: what the+-- proof of 'leave' is stated with.++{-@ measure goneOf @-}+goneOf :: Output p h b -> Set h+goneOf (Gone h _) = Set.singleton h+goneOf (Get _ _) = Set.empty+goneOf (Sweep _) = Set.empty+goneOf (Check _ _) = Set.empty+goneOf (Offer _ _) = Set.empty++-- | A ledger with nothing in it, with room for so many ids, and for so+-- many transactions held.++{-@ newLedger :: Nat -> Nat -> Ledger p h b @-}+newLedger :: Int -> Int -> Ledger p h b+newLedger room heldRoom = Ledger room heldRoom mEmpty 0++-- | The places of the ids.++{-@ placesOf :: Ledger p h b -> Map h (Place p h b) @-}+placesOf :: Ledger p h b -> Map h (Place p h b)+placesOf (Ledger _ _ places _) = places++-- | How many transactions are held.++{-@ heldOf :: l:Ledger p h b -> {n:Nat | n <= lHeldRoom l} @-}+heldOf :: Ledger p h b -> Int+heldOf (Ledger _ _ _ held) = held++-- | Whether an id has a place.++{-@ hasPlace :: (Ord h) => h -> Ledger p h b -> Bool @-}+hasPlace :: (Ord h) => h -> Ledger p h b -> Bool+hasPlace h (Ledger _ _ places _) = isJust (mLookup h places)++isHeld :: Place p h b -> Bool+isHeld (Held {}) = True+isHeld _ = False++-- | Give an id a place, or another place: 'Nothing' when there is no room+-- for one more id, or for one more transaction held. No id loses its+-- place.++{-@ put :: (Ord h) => x:h -> Place p h b -> l:Ledger p h b+      -> Maybe ({n:Ledger p h b | mkeys (lPlaces n) = Set_cup (mkeys (lPlaces l)) (Set_sng x)}) @-}+put :: (Ord h) => h -> Place p h b -> Ledger p h b -> Maybe (Ledger p h b)+put h new (Ledger room heldRoom places held) =+  case mLookup h places of+    Nothing+      | mSize places >= room -> Nothing+      | isHeld new ->+          if held >= heldRoom+            then Nothing+            else Just (Ledger room heldRoom (mInsert h new places) (held + 1))+      | otherwise -> Just (Ledger room heldRoom (mInsert h new places) held)+    Just old+      | isHeld new && not (isHeld old) ->+          if held >= heldRoom+            then Nothing+            else Just (Ledger room heldRoom (mInsert h new places) (held + 1))+      | isHeld old && not (isHeld new) ->+          Just (Ledger room heldRoom (mInsert h new places) (if held > 0 then held - 1 else 0))+      | otherwise -> Just (Ledger room heldRoom (mInsert h new places) held)++-- | Another place for an id that has one and is not a transaction held,+-- when the new place is not one of those either: wanted, or asked of a+-- peer. Anything else is left as it is. Every id keeps a place.++{-@ retarget :: (Ord h) => h -> Place p h b -> l:Ledger p h b+      -> {n:Ledger p h b | mkeys (lPlaces n) = mkeys (lPlaces l)} @-}+retarget :: (Ord h) => h -> Place p h b -> Ledger p h b -> Ledger p h b+retarget h new (Ledger room heldRoom places held)+  | isHeld new = Ledger room heldRoom places held+  | otherwise = Ledger room heldRoom (mAdjust (\old -> if isHeld old then old else new) h places) held++-- | What a transaction that is held waits for. An id that is not held is+-- left as it is. Every id keeps a place.++{-@ rehold :: (Ord h) => h -> Hold h -> l:Ledger p h b+      -> {n:Ledger p h b | mkeys (lPlaces n) = mkeys (lPlaces l)} @-}+rehold :: (Ord h) => h -> Hold h -> Ledger p h b -> Ledger p h b+rehold h hold (Ledger room heldRoom places held) =+  Ledger room heldRoom (mAdjust held' h places) held+  where+    held' (Held b since _) = Held b since hold+    held' other = other++-- | Every time in the ledger, changed by a function. Every id keeps its+-- place.++{-@ retime :: (Tick -> Tick) -> l:Ledger p h b+      -> {n:Ledger p h b | mkeys (lPlaces n) = mkeys (lPlaces l)} @-}+retime :: (Tick -> Tick) -> Ledger p h b -> Ledger p h b+retime f (Ledger room heldRoom places held) = Ledger room heldRoom (mMap place places) held+  where+    place (Wanted ms) = Wanted (Map.map f ms)+    place (Asked p t ps) = Asked p (f t) ps+    place (Held b since hold) = Held b (f since) (waits hold)+    waits (Waiting ps t) = Waiting ps (f t)+    waits (Doubted t) = Doubted (f t)+    waits other = other++-- | The one way out: an id loses its place, and an output says so and how,+-- at the head of those said so far. An id that had no place is said to be+-- gone too: it was learned and let go in one step.++{-@ leave :: (Ord h) => x:h -> End -> l:Ledger p h b -> os:[Output p h b]+      -> ( {n:Ledger p h b | mkeys (lPlaces n) = Set_dif (mkeys (lPlaces l)) (Set_sng x)},+           {ns:[Output p h b] | goneOf (head ns) == Set_sng x && tail ns == os} ) @-}+leave :: (Ord h) => h -> End -> Ledger p h b -> [Output p h b] -> (Ledger p h b, [Output p h b])+leave h end (Ledger room heldRoom places held) said =+  (Ledger room heldRoom (mDelete h places) held', Gone h end : said)+  where+    held' = case mLookup h places of+      Just old | isHeld old, held > 0 -> held - 1+      _ -> held
+ src/Haskoin/Store/Ingest/Run.hs view
@@ -0,0 +1,689 @@+-- |+-- Module      : Haskoin.Store.Ingest.Run+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- The runner of "Haskoin.Store.Ingest": the thread that gives the machine+-- its inputs and carries out its outputs. Every decision about a+-- transaction on its way to the pool is the machine's+-- (@docs\/mempool-ingestion.md@); this module decides nothing, and is the+-- part of the path that no proof covers, so it is kept to what a reader+-- can check by eye.+--+-- = What it does+--+-- * __It takes what happens__ from the thread that reads the events of the+--   node (the functions ending in @STM@), and from the clock, once a+--   second, in one queue and so in their order.+--+-- * __It names each connection__ with a number of its own, never used+--   again: what the pool answers about what a peer named is for that+--   connection, never for a later one to the same node (U1).+--+-- * __It carries out each output__: a request or a question to a peer, a+--   question to the pool ('memberSettled'), an offer ('memberOfferTimed'), a+--   count of what left and why. An answer of the pool is an input, given+--   to the machine before the next thing that happened.+--+-- = What it does when it is behind+--+-- Its queue takes any number of the events that are few and must not be+-- lost: a peer that comes or goes, a pool that was emptied. Of the others,+-- what peers name and send, it takes 20,000 and drops the rest, and tells+-- the machine that something was lost, which makes it read its sources+-- again. Waiting instead would hold up the thread that reads the node's+-- events, and its blocks with it.+--+-- While Redis does not answer, an offer fails, and the machine asks for it+-- again at each tick. The runner makes one such attempt a tick, not one+-- for each transaction that is held.+--+-- = A source that is no peer+--+-- A node announces a transaction to a peer once, so what the store misses+-- comes back only from a /source/: something that gives a node's whole+-- mempool when asked. A peer is one when its node allows it, which Bitcoin+-- Core does only for a peer that it whitelists. The RPC of a node always+-- answers, so a store that has it has a source whatever its peers are: it+-- is given to the runner as a t'Feed', with 'ingestFeed'.+--+-- To the machine a feed is one more peer that is a source: it is told that+-- the feed came, asks it for its mempool and for transactions with the+-- same outputs, within the same window, and gets the same inputs back. So+-- nothing of the machine, of its proofs or of its model is particular to a+-- feed. A feed that fails is a peer that went, and one that answers again+-- is a new peer, with a new number (U1).+module Haskoin.Store.Ingest.Run+  ( Ingester,+    IngestConfig (..),+    IngestState (..),+    withIngest,+    ingestState,++    -- * A source that is no peer+    Feed (..),+    ingestFeed,++    -- * What happens+    ingestPeerUpSTM,+    ingestPeerDownSTM,+    ingestNamedSTM,+    ingestTxSTM,+    ingestMissingSTM,+    ingestLookSTM,+    ingestEmptiedSTM,+  )+where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (link, withAsync)+import Control.Concurrent.STM+  ( STM,+    TQueue,+    TVar,+    atomically,+    check,+    modifyTVar',+    newTQueue,+    newTQueueIO,+    newTVarIO,+    orElse,+    readTQueue,+    readTVar,+    registerDelay,+    swapTVar,+    writeTQueue,+    writeTVar,+  )+import Control.Exception (evaluate)+import Control.Monad (forM_, unless, when)+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.List (find, nub)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.String.Conversions (cs)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time.Clock.POSIX (getPOSIXTime)+import Data.Word (Word64)+import GHC.Clock (getMonotonicTimeNSec)+import Haskoin+  ( GetData (..),+    InvType (..),+    InvVector (..),+    Message (..),+    Network (..),+    OutPoint (..),+    Tx (..),+    TxHash (..),+    TxIn (..),+    nullOutPoint,+    txHash,+  )+import Haskoin.Node (LogLevel (..), Logger, Peer, logAt, sendMessage)+import Haskoin.Store.Exception (catchAny, onException, tryAny)+import Haskoin.Store.Fleet.Member (Member, OfferCost (..), memberOfferTimed, memberSettled)+import Haskoin.Store.Ingest+import System.Metrics.StatsD (StatCounter, StatGauge, Stats, incrementCounter, newStatCounter, newStatGauge, setGauge)++-- | What the runner needs of the store.+data IngestConfig = IngestConfig+  { net :: !Network,+    -- | the bounds and the waits of the machine+    config :: !Config,+    -- | the store as a member of its fleet, which asks the pool and offers+    -- to it; without one, in tests, nothing is ever settled+    member :: !(Maybe Member),+    -- | whether the store has the blocks of its nodes now+    inSync :: !(IO Bool),+    -- | whether a peer gives its whole mempool when asked, and so is a+    -- source: what the model of its node says+    -- ('Haskoin.Node.judgeMessage')+    source :: !(Peer -> IO Bool),+    -- | whether a peer is a node of the operator, which is taken at its+    -- word ("Haskoin.Store.Ingest"). A feed always is: the operator gave+    -- the store the RPC of that node.+    own :: !(Peer -> IO Bool),+    stats :: !(Maybe Stats),+    logger :: !Logger+  }++-- | A way to read the whole mempool of a node that is no peer of the+-- store, such as its RPC. Both actions throw when the node does not+-- answer, and only then: what they return is the node's word.+data Feed = Feed+  { -- | what it is, for the log, as in "Reading the mempool of …"+    label :: !Text,+    -- | the id of every transaction of the node's mempool; none for an+    -- empty mempool+    names :: !(IO [TxHash]),+    -- | the transactions asked for, in the order asked, with 'Nothing'+    -- for one that the node says it has not+    bodies :: !([TxHash] -> IO [Maybe Tx])+  }++-- | What the runner asks of a feed.+data Job+  = -- | every id of the mempool+    ReadAll+  | Fetch ![TxHash]++-- | What the machine knows as a peer: a connection to a node, or a feed+-- from when it is reached to when it fails, with its number among the+-- feeds, its label and the queue of what is asked of it.+data Link+  = Wire !Peer+  | Fed !Int !Text !(TQueue Job)+  deriving (Eq)++-- | Something that happened, for the runner.+data Event+  = PeerCame !Link+  | PeerLeft !Link+  | Names !Link ![TxHash]+  | Came !Link !Tx+  | Lacks !Link ![TxHash]+  | -- | the store may be in sync now, or no longer+    Look+  | PoolLost++-- | The way to tell the runner what happens, and to read what it knows.+data Ingester = Ingester+  { events :: !(TQueue Event),+    -- | how many of the events that may be dropped are in the queue+    waiting :: !(TVar Int),+    -- | how many were dropped since the machine was last told+    dropped :: !(TVar Int),+    state :: !(TVar IngestState),+    -- | the number of the next feed+    feeds :: !(TVar Int),+    logger :: !Logger+  }++-- | What the path into the pool is at, for the health check of a store+-- and for whoever looks at it.+data IngestState = IngestState+  { -- | ids that the machine has a place for+    known :: !Int,+    -- | requests out to peers and not answered: what the health check+    -- counts as pending+    pending :: !Int,+    -- | transactions held, to offer or waiting for others+    held :: !Int,+    -- | whether something was given up that no source has been read for+    dirty :: !Bool,+    -- | how many peers give their whole mempool when asked. With none,+    -- what the store misses stays missed until a block has it.+    sources :: !Int,+    -- | how the pool stands with the mempools of the nodes of the+    -- operator ('Haskoin.Store.Ingest.standing')+    standing :: !Standing+  }+  deriving (Eq, Show)++-- | How many events of peers wait at most. Each is the ids that a peer+-- named in a message, or a transaction.+room :: Int+room = 20000++-- | What the path into the pool is at.+ingestState :: Ingester -> STM IngestState+ingestState ing = readTVar ing.state++always :: Event -> Ingester -> STM ()+always e ing = writeTQueue ing.events e++-- | An event that is dropped when @room@ of them wait already.+bulk :: Event -> Ingester -> STM ()+bulk e ing = do+  n <- readTVar ing.waiting+  if n >= room+    then modifyTVar' ing.dropped (+ 1)+    else writeTQueue ing.events e >> writeTVar ing.waiting (n + 1)++-- | An event that waits until there is room for it: for a thread that+-- may wait, as that of a feed, which the reader of the node's events may+-- not.+patient :: Event -> Ingester -> STM ()+patient e ing = do+  n <- readTVar ing.waiting+  check (n < room)+  writeTQueue ing.events e+  writeTVar ing.waiting (n + 1)++-- | A peer finished its handshake.+ingestPeerUpSTM :: Peer -> Ingester -> STM ()+ingestPeerUpSTM = always . PeerCame . Wire++-- | A peer is gone.+ingestPeerDownSTM :: Peer -> Ingester -> STM ()+ingestPeerDownSTM = always . PeerLeft . Wire++-- | A peer named transactions (@inv@).+ingestNamedSTM :: Peer -> [TxHash] -> Ingester -> STM ()+ingestNamedSTM p hs = bulk (Names (Wire p) hs)++-- | A peer sent a transaction.+ingestTxSTM :: Peer -> Tx -> Ingester -> STM ()+ingestTxSTM p tx = bulk (Came (Wire p) tx)++-- | A peer does not have transactions that it was asked for (@notfound@).+ingestMissingSTM :: Peer -> [TxHash] -> Ingester -> STM ()+ingestMissingSTM p hs = bulk (Lacks (Wire p) hs)++-- | The store has a new best header or a new best block: it may be in+-- sync now, or no longer.+ingestLookSTM :: Ingester -> STM ()+ingestLookSTM = always Look++-- | The pool lost what it had: Redis lost its data, or the pool was+-- started again. The machine is told the same when the runner dropped+-- events of peers: in both cases something may be missing that only a+-- reading of the sources brings back.+ingestEmptiedSTM :: Ingester -> STM ()+ingestEmptiedSTM = always PoolLost++-- | Give the path into the pool a source that is no peer, for as long as+-- this runs: it does not return.+--+-- The feed is told to the machine as a peer that gives its mempool. What+-- the machine then asks of that peer is asked of the feed, one thing at a+-- time, and what the feed answers goes to the machine as what a peer names+-- and sends. The machine asks within the window that it keeps for every+-- peer, which follows what the feed delivers, so nothing here says how+-- much a node is asked at once or how often.+--+-- When the feed throws, the machine is told that the peer went, which+-- makes it give up what it had asked of it, with a reason, and remember+-- that it has something to read again. The feed is tried again after a+-- second, then two, up to a minute, as a new peer each time (U1).+--+-- Its events wait for room in the queue of the runner and are never+-- dropped: this thread reads nothing else, so making it wait holds up+-- nothing.+ingestFeed :: Ingester -> Feed -> IO a+ingestFeed ing feed = connect 1 False+  where+    -- with the seconds to wait if it fails at once, and whether it failed+    -- the last time+    connect wait down = do+      (me, jobs) <- atomically $ do+        n <- readTVar ing.feeds+        writeTVar ing.feeds (n + 1)+        jobs <- newTQueue+        let me = Fed n feed.label jobs+        always (PeerCame me) ing+        return (me, jobs)+      let gone = atomically (always (PeerLeft me) ing)+      (why, still) <- serve me jobs down `onException` gone+      gone+      let pause = if still then wait else 1+      unless still . say LevelWarn $+        "Could not read " <> feed.label <> ", and will try again: " <> cs (show why)+      threadDelay (pause * 1000000)+      connect (min 60 (pause * 2)) True+    -- carry out what is asked until something fails: the failure, and+    -- whether nothing worked since the last one+    serve me jobs down = do+      job <- atomically (readTQueue jobs)+      tryAny (carry me job) >>= \case+        Left e -> return (e, down)+        Right () -> do+          when down (say LevelInfo ("Reading " <> feed.label <> " works again"))+          serve me jobs False+    carry me = \case+      ReadAll -> do+        hs <- feed.names+        forM_ (pieces hs) $ \some -> atomically (patient (Names me some) ing)+      Fetch hs -> do+        found <- feed.bodies hs+        forM_ found . mapM_ $ \tx -> atomically (patient (Came me tx) ing)+        let lacking = [h | (h, Nothing) <- zip hs found]+        unless (null lacking) (atomically (patient (Lacks me lacking) ing))+    -- as many ids to an event as a node names in a message+    pieces hs+      | null hs = []+      | otherwise = take 50000 hs : pieces (drop 50000 hs)+    say level = logAt level ing.logger++-- | What the runner keeps beside the machine.+data Run = Run+  { machine :: !(Ingest Int TxHash Tx),+    -- | the connections and the feeds, by the numbers that name them+    peers :: !(Map Int Link),+    -- | the number of the next connection+    next :: !Int+  }++-- | StatsD metrics of the path, under @ingest@.+data Metrics = Metrics+  { settled :: !StatCounter,+    gaveUp :: !(Map Reason StatCounter),+    droppedEvents :: !StatCounter,+    knownG :: !StatGauge,+    pendingG :: !StatGauge,+    heldG :: !StatGauge+  }++newMetrics :: Stats -> IO Metrics+newMetrics s = do+  settled <- newStatCounter s "ingest.settled" 10+  gaveUp <- Map.fromList <$> mapM reason [minBound ..]+  droppedEvents <- newStatCounter s "ingest.dropped" 10+  knownG <- newStatGauge s "ingest.ids" 0+  pendingG <- newStatGauge s "ingest.pending" 0+  heldG <- newStatGauge s "ingest.held" 0+  return Metrics {settled, gaveUp, droppedEvents, knownG, pendingG, heldG}+  where+    reason r = (r,) <$> newStatCounter s ("ingest.given_up." <> reasonName r) 10++-- | The name of a reason in a metric and in the log.+reasonName :: Reason -> String+reasonName = \case+  NodeHasNot -> "node_has_not"+  Unanswered -> "unanswered"+  NoRoom -> "no_room"+  PeerGone -> "peer_gone"+  WaitedTooLong -> "waited_too_long"+  Unjudged -> "unjudged"+  IsForged -> "forged"+  NotVouched -> "not_vouched"++-- | Run the path into the pool while an action runs, and give the action+-- the way to tell it what happens.+withIngest :: IngestConfig -> (Ingester -> IO a) -> IO a+withIngest cfg action = do+  events <- newTQueueIO+  waiting <- newTVarIO 0+  dropped <- newTVarIO 0+  state <- newTVarIO (IngestState 0 0 0 False 0 PoolUnknown)+  metrics <- mapM newMetrics cfg.stats+  feeds <- newTVarIO 0+  now <- milliseconds+  let ing = Ingester {events, waiting, dropped, state, feeds, logger = cfg.logger}+      run0 = Run {machine = start cfg.config now, peers = Map.empty, next = 0}+  withAsync (loop cfg ing metrics run0) $ \a -> link a >> action ing++-- | The clock of the machine.+milliseconds :: IO Tick+milliseconds = fromIntegral . (`div` 1000000) <$> getMonotonicTimeNSec++-- | The transactions that one spends from.+parentsOf :: Tx -> [TxHash]+parentsOf tx = nub [i.outpoint.hash | i <- tx.inputs, i.outpoint /= nullOutPoint]++-- | Where the time of the runner went since it last said, in nanoseconds,+-- and what it did meanwhile.+data Costs = Costs+  { -- | events taken in+    passes :: !Int,+    offersMade :: !Int,+    checksMade :: !Int,+    -- | waiting for an event+    idle :: !Word64,+    -- | in the steps of the machine+    inMachine :: !Word64,+    inOffers :: !Word64,+    -- | asking the pool which of the ids that a peer named it has+    inChecks :: !Word64,+    -- | sending requests to peers+    inSends :: !Word64,+    -- | saying the state of the machine, for @\/health@ and the metrics+    inPublish :: !Word64,+    offerParts :: !OfferCost+  }++noCosts :: Costs+noCosts = Costs 0 0 0 0 0 0 0 0 0 mempty++loop :: IngestConfig -> Ingester -> Maybe Metrics -> Run -> IO a+loop cfg ing metrics run0 = do+  t <- milliseconds+  costs <- newIORef noCosts+  saidAt <- newIORef t+  loopWith costs saidAt cfg ing metrics run0 t++loopWith :: IORef Costs -> IORef Tick -> IngestConfig -> Ingester -> Maybe Metrics -> Run -> Tick -> IO a+loopWith costs saidAt cfg ing metrics run0 t0 = go False t0 run0+  where+    -- the time that an action takes, added to what the runner spent+    timed :: (Costs -> Word64 -> Costs) -> IO x -> IO x+    timed add act = do+      a <- getMonotonicTimeNSec+      r <- act+      b <- getMonotonicTimeNSec+      modifyIORef' costs (`add` (b - a))+      return r+    -- Say where the time went, every ten seconds in which the runner was+    -- busy for five or more: a store that is slow to fill its pool then+    -- says why, which nothing outside it can tell.+    account now m = do+      since <- readIORef saidAt+      when (now - since >= 10000) $ do+        c <- readIORef costs+        writeIORef costs noCosts+        writeIORef saidAt now+        let ms :: Word64 -> Text+            ms ns = shown (ns `div` 1000000)+            busy = c.inMachine + c.inOffers + c.inChecks + c.inSends + c.inPublish+            o = c.offerParts+        when (busy >= 5000000000) . say LevelInfo . T.unwords $+          [ "The path into the pool was busy for",+            ms busy,+            "of the last",+            shown (now - since) <> " ms:",+            shown c.passes,+            "events,",+            shown c.offersMade,+            "offers,",+            shown c.checksMade,+            "questions to the pool. In milliseconds: machine",+            ms c.inMachine <> ", offers",+            ms c.inOffers,+            "(whether a block has it",+            ms o.askedBlock <> ", outputs from the database",+            ms o.readDb <> ", outputs from the pool",+            ms o.readPool <> ", which are unspent",+            ms o.readUnspent <> ", the pool's decision",+            ms o.decided <> ", looking at what strangers sent",+            ms o.judged <> "), questions",+            ms c.inChecks <> ", sending",+            ms c.inSends <> ", saying its state",+            ms c.inPublish <> ", waiting",+            ms c.idle <> ". It knows",+            shown (idCount m),+            "ids and holds",+            shown (holding m) <> "."+          ]+    -- with whether the machine was last told that the store is in sync,+    -- and when it was last told the time+    go wasSynced lastTick run = do+      before <- milliseconds+      timer <- registerDelay (1000 * max 0 (lastTick + 1000 - before))+      event <-+        timed (\c d -> c {idle = c.idle + d, passes = c.passes + 1}) . atomically $+          (Just <$> readTQueue ing.events) `orElse` (readTVar timer >>= check >> return Nothing)+      lost <- atomically (swapTVar ing.dropped 0)+      when (lost > 0) $ do+        forM_ metrics $ \m -> incrementCounter m.droppedEvents lost+        say LevelWarn $+          "Dropped " <> shown lost <> " messages of peers that waited for the pool: the sources are read again"+      (run', inputs) <- inputsOf run event+      now <- milliseconds+      -- the time is told once a second, however many events come+      let tick = now - lastTick >= 1000+          looks = case event of+            Just Look -> True+            _ -> tick+      -- whether the store is in sync is looked at when it may have changed,+      -- and at every tick+      synced <- if looks then cfg.inSync else return wasSynced+      -- one attempt at the pool a pass while it fails+      failing <- newIORef False+      -- what the machine gives up in this pass, by reason+      lostNow <- newIORef Map.empty+      let all' =+            [Emptied | lost > 0]+              <> [Synced synced | synced /= wasSynced]+              <> inputs+              <> [Tick now | tick]+      machine <- drive run'.peers failing lostNow run'.machine all'+      timed (\c d -> c {inPublish = c.inPublish + d}) (publish machine)+      -- A source is read every thirty seconds while transactions come+      -- (@told@ in "Haskoin.Store.Ingest"), and a reading goes through+      -- every transaction of a mempool. What that costs is said when it+      -- is a second or more, so that a store for which it is too much+      -- shows it.+      done <- milliseconds+      case event of+        Just (Names _ hs)+          | done - now >= 1000,+            length hs >= 1000 ->+              say LevelInfo . T.unwords $+                [ "Went through",+                  shown (length hs),+                  "transactions that a node named at once in",+                  shown (done - now),+                  "ms"+                ]+        _ -> return ()+      -- what was given up and that a node may still have is said, once a+      -- pass: it makes the store read its sources again, and without the+      -- reason nobody can tell why it did+      gaveUp <- Map.toList . Map.delete NodeHasNot <$> readIORef lostNow+      unless (null gaveUp) . say LevelInfo $+        "Gave up transactions on their way to the pool, and will read the sources again: "+          <> T.intercalate ", " [shown n <> " " <> cs (reasonName why) | (why, n) <- gaveUp]+      account done machine+      go synced (if tick then now else lastTick) run' {machine}+    -- what an event is to the machine, with the peers named+    inputsOf run = \case+      Nothing -> return (run, [])+      Just e -> do+        when (droppable e) (atomically (modifyTVar' ing.waiting (subtract 1)))+        case e of+          PeerCame p -> do+            (src, ours) <- case p of+              Wire peer -> do+                src <- cfg.source peer+                unless src . say LevelInfo . T.unwords $+                  [ "Peer " <> shown peer <> " does not give its mempool when asked:",+                    "what the store misses of it stays missed"+                  ]+                ours <- cfg.own peer+                -- said for each peer, so that an operator sees that the+                -- store knows its node: a node taken for a stranger+                -- shows late what the store cannot verify+                say LevelInfo $+                  if ours+                    then "Peer " <> shown peer <> " is a node of the operator: what it names is taken at its word"+                    else "Peer " <> shown peer <> " is a stranger: what only strangers name is verified first"+                return (src, ours)+              -- a feed is nothing but a source, of a node of the operator+              Fed {} -> return (True, True)+            return+              ( run {peers = Map.insert run.next p run.peers, next = run.next + 1},+                PeerUp run.next src : [Own run.next | ours]+              )+          PeerLeft p -> case keyOf run p of+            Just k -> return (run {peers = Map.delete k run.peers}, [PeerDown k])+            Nothing -> return (run, [])+          Names p hs -> return (run, [Named k hs | Just k <- [keyOf run p]])+          Came from tx+            -- Only a block has a coinbase, and no mempool: one is not+            -- taken in, whoever sent it. A node gives the coinbase of a+            -- block that is no longer in its chain, and publishes its id+            -- when it takes the block back ("Haskoin.Store.NodePeer"). To+            -- the machine the peer does not have it, as if it had said so.+            | coinbase tx -> return (run, [Missing k [txHash tx] | Just k <- [keyOf run from]])+            | otherwise -> return (run, [Body (keyOf run from) (txHash tx) tx])+          Lacks p hs -> return (run, [Missing k hs | Just k <- [keyOf run p]])+          Look -> return (run, [])+          PoolLost -> return (run, [Emptied])+    coinbase tx = any ((== nullOutPoint) . (.outpoint)) tx.inputs+    droppable = \case+      Names {} -> True+      Came {} -> True+      Lacks {} -> True+      _ -> False+    keyOf run p = fst <$> find ((== p) . snd) (Map.toList run.peers)+    -- give the machine inputs, and carry out what it says; what the pool+    -- answers goes in after the inputs that are there already+    drive _ _ _ m [] = return m+    drive peers failing lostNow m (i : is) = do+      -- the step is made here, and what it says counted, so that its+      -- time is not taken for that of what is done with it+      (m', outs) <- timed (\c d -> c {inMachine = c.inMachine + d}) $ do+        let (next, said) = step parentsOf i m+        _ <- evaluate (length said)+        next' <- evaluate next+        return (next', said)+      answers <- concat <$> mapM (perform m' peers failing lostNow) outs+      drive peers failing lostNow m' (is <> answers)+    perform m peers failing lostNow = \case+      Get k hs -> timed (\c d -> c {inSends = c.inSends + d}) $ do+        forM_ (Map.lookup k peers) $ \case+          Wire p -> MGetData (GetData [InvVector kind h.get | h <- hs]) `sendMessage` p+          Fed _ _ jobs -> atomically (writeTQueue jobs (Fetch hs))+        return []+      Sweep k -> do+        forM_ (Map.lookup k peers) $ \case+          Wire p -> do+            say LevelInfo ("Asking peer " <> shown p <> " for its mempool")+            MMempool `sendMessage` p+          Fed _ label jobs -> do+            say LevelInfo ("Reading " <> label)+            atomically (writeTQueue jobs ReadAll)+        return []+      Check k hs -> case cfg.member of+        Nothing -> return [Unchecked k hs]+        Just member ->+          timed asked (memberSettled member hs) >>= \case+            Nothing -> return [Unchecked k hs]+            Just flags ->+              return [Checked k [h | (h, True) <- zip hs flags] [h | (h, False) <- zip hs flags]]+      Offer h tx -> do+        down <- readIORef failing+        case cfg.member of+          Just member | not down -> do+            time <- round <$> getPOSIXTime+            (verdict, parts) <-+              timed (\c d -> c {inOffers = c.inOffers + d, offersMade = c.offersMade + 1}) $+                memberOfferTimed member (vouchedFor h m) time tx `catchAny` \e -> do+                  writeIORef failing True+                  say LevelDebug ("Could not offer " <> shown h <> " to the pool: " <> shown e)+                  return (Again, mempty)+            modifyIORef' costs (\c -> c {offerParts = c.offerParts <> parts})+            return [Offered h verdict]+          _ -> return [Offered h Again]+      Gone h end -> do+        case end of+          Done -> forM_ metrics $ \m -> incrementCounter m.settled 1+          GaveUp why -> do+            modifyIORef' lostNow (Map.insertWith (+) why (1 :: Int))+            forM_ metrics $ \m -> forM_ (Map.lookup why m.gaveUp) (`incrementCounter` 1)+            say LevelDebug ("Gave up " <> shown h <> ": " <> cs (reasonName why))+        return []+    asked c d = c {inChecks = c.inChecks + d, checksMade = c.checksMade + 1}+    kind = if cfg.net.segWit then InvWitnessTx else InvTx+    publish m = do+      let st =+            IngestState+              { known = idCount m,+                pending = Haskoin.Store.Ingest.pending m,+                held = holding m,+                dirty = isDirty m,+                sources = sourceCount m,+                standing = Haskoin.Store.Ingest.standing m+              }+      atomically (writeTVar ing.state st)+      forM_ metrics $ \x -> do+        setGauge x.knownG st.known+        setGauge x.pendingG st.pending+        setGauge x.heldG st.held+    say level = logAt level cfg.logger+    shown :: (Show x) => x -> Text+    shown = cs . show
src/Haskoin/Store/Logic.hs view
@@ -109,7 +109,7 @@ import Data.Functor ((<&>)) import Data.HashSet qualified as H import Data.IntMap.Strict qualified as I-import Data.List (nub)+import Data.List (nub, zip4) import Data.Maybe (catMaybes, fromMaybe, isNothing, mapMaybe) import Data.Serialize (encode) import Data.Set qualified as S@@ -124,6 +124,7 @@     BlockNode (..),     Network (..),     OutPoint (..),+    TokenData (..),     Tx (..),     TxHash (..),     TxIn (..),@@ -145,7 +146,7 @@ import Haskoin.Node (LogLevel (..), logAt) import Haskoin.Store.Common (nub', replacedKept, sortTxs, sortTxsWith) import Haskoin.Store.Data-import Haskoin.Store.Database.Types (BalVal (..))+import Haskoin.Store.Database.Types (BalVal (..), TokBalVal (..), addTokBalVal) import Haskoin.Store.Database.Writer  -- | Reasons why an import can fail.@@ -275,6 +276,9 @@     spends :: ![OutPoint],     -- | the address of each of its outputs, for those that have one     paid :: ![Maybe Address],+    -- | the tokens of each of its outputs, for those that hold any+    -- (CashTokens, on Bitcoin Cash only)+    tokens :: ![Maybe TokenData],     -- | bytes that it takes in a block, with its witness     size :: !Int,     -- | the same without its witness@@ -325,6 +329,7 @@       txid = TxHash (doubleSHA256 stripped),       spends = prevOuts tx,       paid = map (eitherToMaybe . scriptToAddressBS net . (.script)) tx.outputs,+      tokens = map (scriptTokens net . (.script)) tx.outputs,       size = if null tx.witness then B.length stripped else B.length (encode tx),       base = B.length stripped     }@@ -431,7 +436,7 @@       Nothing -> do         logError wr $ "Attempted to import a tx missing UTXO: " <> txHashToHex p.txid         throwIO Orphan-  let td = prepareTxData False br time p.tx us+  let td = prepareTxData br time p.tx us   addChainTx wr p td us   return td @@ -445,6 +450,11 @@   forM_ (txDataAddresses wr t) $ \a -> do     deleteAddrTx wr a TxRef {block = t.block, txid = h}     insertAddrTx wr a TxRef {block = new, txid = h}+  let spent = [(Nothing, k) | pv <- I.elems t.prevs, Just k <- [scriptTokens' wr pv.script]]+      made = [(Nothing, k) | o <- t.tx.outputs, Just k <- [scriptTokens' wr o.script]]+  forM_ (tokenCategories spent made) $ \c -> do+    deleteCatTx wr c TxRef {block = t.block, txid = h}+    insertCatTx wr c TxRef {block = new, txid = h}   forM_ (zip [0 ..] t.tx.outputs) $ \(i, _) ->     getUnspent wr (OutPoint h i) >>= mapM_ move   let td = (t :: TxData) {block = new, timestamp = time}@@ -456,6 +466,7 @@       let u' = (u :: Unspent) {block = new}       insertUnspent wr u'       forM_ u.address $ \a -> deleteAddrUnspent wr a u >> insertAddrUnspent wr a u'+      forM_ (unspentTokens wr u) $ \k -> deleteCatUnspent wr k.category u >> insertCatUnspent wr k.category u'  -- | Revert the best block: make its parent the best block, mark it as not in -- the main chain, and take its transactions out of the chain, each after@@ -500,16 +511,16 @@ -- The chain's column families ------------------------------------------------------------------------------- --- | Data of a new transaction, from its replace-by-fee flag, position, time and--- the outputs it spends.-prepareTxData :: Bool -> BlockRef -> Word64 -> Tx -> [Unspent] -> TxData-prepareTxData rbf br tt tx us =+-- | Data of a new transaction of a block, from its position, time and the+-- outputs it spends. It cannot be replaced by fee: a block confirms it.+prepareTxData :: BlockRef -> Word64 -> Tx -> [Unspent] -> TxData+prepareTxData br tt tx us =   TxData     { block = br,       tx = tx,       prevs = ps,       deleted = False,-      rbf = rbf,+      rbf = False,       timestamp = tt,       spenders = I.empty     }@@ -528,6 +539,61 @@   b <- f . fromMaybe (zeroBalance a) <$> getBalance wr a   if nullBalance b then deleteBalance wr a else setBalance wr b +-- | Change the tokens of a category at an address in the chain, by reading+-- them and writing them whole, as 'modifyBalance' does a balance.+modifyTokBal :: Writer -> Address -> TxHash -> (TokBalVal -> TokBalVal) -> IO ()+modifyTokBal wr a c f = do+  v <- f . fromMaybe def <$> getTokBal wr a c+  setTokBal wr a c (Just v)++-- | The tokens of the script field of an output, on Bitcoin Cash.+scriptTokens' :: Writer -> B.ByteString -> Maybe TokenData+scriptTokens' wr = scriptTokens (writerNet wr)++-- | The tokens of an unspent output.+unspentTokens :: Writer -> Unspent -> Maybe TokenData+unspentTokens wr u = scriptTokens' wr u.script++-- | What an output that holds some tokens adds to the token balance of its+-- address: its fungible amount, its non-fungible token if any, and one+-- output. The amount received and the count of transactions are counted+-- apart.+tokensIn :: TokenData -> TokBalVal+tokensIn t = (def :: TokBalVal) {amount = t.amount, nfts = maybe 0 (const 1) t.nft, outputs = 1}++-- | Each number of a token balance taken off, by its two's complement: what+-- a merge adds to take a balance away.+negateTokBalVal :: TokBalVal -> TokBalVal+negateTokBalVal v =+  TokBalVal+    { amount = negate v.amount,+      nfts = negate v.nfts,+      outputs = negate v.outputs,+      count = negate v.count,+      received = negate v.received+    }++-- | Take the tokens of an output out of a token balance, or stop if any+-- number would go below zero.+takeTokens :: TokenData -> TokBalVal -> TokBalVal+takeTokens t v =+  v+    { amount = less "token amount" v.amount d.amount,+      nfts = less "count of non-fungible tokens" v.nfts d.nfts,+      outputs = less "count of token outputs" v.outputs d.outputs+    }+  where+    d = tokensIn t++-- | The categories of the tokens that a transaction spends and makes.+tokenCategories :: [(Maybe Address, TokenData)] -> [(Maybe Address, TokenData)] -> [TxHash]+tokenCategories spent made = S.toList (S.fromList [t.category | (_, t) <- spent <> made])++-- | The addresses and categories of the tokens that a transaction spends+-- and makes, each pair once: their counts of transactions go up by one.+tokenHolders :: [(Maybe Address, TokenData)] -> [(Maybe Address, TokenData)] -> [(Address, TxHash)]+tokenHolders spent made = S.toList (S.fromList [(a, t.category) | (Just a, t) <- spent <> made])+ -- | Subtract, or stop: no count or amount of the chain goes below zero. less :: String -> Word64 -> Word64 -> Word64 less what x y@@ -569,16 +635,23 @@   forM_ (S.toList (S.fromList (mapMaybe (.address) us <> catMaybes p.paid))) $ \a -> do     insertAddrTx wr a TxRef {block = td.block, txid = h}     mergeBalance wr a (def :: BalVal) {txs = 1}-  forM_ (zip3 [0 ..] td.tx.outputs p.paid) $ \(i, o, address) -> do+  forM_ (tokenCategories spent made) $ \c -> insertCatTx wr c TxRef {block = td.block, txid = h}+  forM_ (tokenHolders spent made) $ \(a, c) -> mergeTokBal wr a c (def :: TokBalVal) {count = 1}+  forM_ (zip4 [0 ..] td.tx.outputs p.paid p.tokens) $ \(i, o, address, tokens) -> do     let u = Unspent {block = td.block, outpoint = OutPoint h i, value = o.value, script = o.script, address}     insertUnspent wr u     forM_ address $ \a -> do       insertAddrUnspent wr a u       mergeBalance wr a (def :: BalVal) {confirmed = o.value, utxo = 1, received = o.value}+    forM_ tokens $ \t -> do+      insertCatUnspent wr t.category u+      forM_ address $ \a -> mergeTokBal wr a t.category (tokensIn t) {received = t.amount}   zipWithM_ spend [0 ..] p.spends   insertTxOf wr h td   where     h = p.txid+    spent = [(u.address, t) | u <- us, Just t <- [unspentTokens wr u]]+    made = [(a, t) | (a, Just t) <- zip p.paid p.tokens]     spend ix o = do       u <-         getUnspent wr o >>= \case@@ -593,6 +666,9 @@         deleteAddrUnspent wr a u         -- taken off by adding the two's complement         mergeBalance wr a (def :: BalVal) {confirmed = negate u.value, utxo = negate 1}+      forM_ (unspentTokens wr u) $ \t -> do+        deleteCatUnspent wr t.category u+        forM_ u.address $ \a -> mergeTokBal wr a t.category (negateTokBalVal (tokensIn t))  -- | Take a confirmed transaction that nothing in the chain spends out of -- every index of the chain, and make the outputs that it spent unspent@@ -602,6 +678,11 @@   forM_ (txDataAddresses wr td) $ \a -> do     deleteAddrTx wr a TxRef {block = td.block, txid = h}     modifyBalance wr a $ \b -> (b :: Balance) {txs = less "count of transactions" b.txs 1}+  let spent = [(scriptAddress wr pv.script, t) | pv <- I.elems td.prevs, Just t <- [scriptTokens' wr pv.script]]+      made = [(scriptAddress wr o.script, t) | o <- td.tx.outputs, Just t <- [scriptTokens' wr o.script]]+  forM_ (tokenCategories spent made) $ \c -> deleteCatTx wr c TxRef {block = td.block, txid = h}+  forM_ (tokenHolders spent made) $ \(a, c) ->+    modifyTokBal wr a c $ \v -> v {count = less "count of token transactions" v.count 1}   forM_ (zip [0 ..] td.tx.outputs) $ \(i, o) -> do     let p = OutPoint h i         u = unspentOutput wr td.block p o@@ -614,6 +695,11 @@             utxo = less "count of unspent outputs" b.utxo 1,             received = less "amount received" b.received o.value           }+    forM_ (unspentTokens wr u) $ \t -> do+      deleteCatUnspent wr t.category u+      forM_ u.address $ \a ->+        modifyTokBal wr a t.category $ \v ->+          (takeTokens t v) {received = less "token amount received" v.received t.amount}   forM_ (prevOuts td.tx) $ \p -> do     parent <-       chainTx wr p.hash >>= \case@@ -626,6 +712,9 @@     forM_ u.address $ \a -> do       insertAddrUnspent wr a u       modifyBalance wr a $ \b -> (b :: Balance) {confirmed = b.confirmed + o.value, utxo = b.utxo + 1}+    forM_ (unspentTokens wr u) $ \t -> do+      insertCatUnspent wr t.category u+      forM_ u.address $ \a -> modifyTokBal wr a t.category (addTokBalVal (tokensIn t))   deleteTxData wr h   where     h = txHash td.tx
src/Haskoin/Store/Manager.hs view
@@ -25,10 +25,13 @@ where  import Control.Concurrent.Async (link, withAsync)-import Control.Concurrent.STM (STM, TVar, atomically, newTVarIO)-import Control.Monad (forM_, unless, when)+import Control.Concurrent.STM (STM, TVar, atomically, newTVarIO, readTVar, retry)+import Control.Exception (throwIO)+import Control.Monad (forM, forM_, join, unless, when) import Data.ByteString (ByteString) import Data.ByteString.Char8 qualified as C+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Maybe (isJust, isNothing) import Data.Serialize (Serialize, decode) import Data.String.Conversions (cs) import Data.Time.Clock (NominalDiffTime)@@ -36,6 +39,7 @@ import Database.Redis qualified as Redis import Haskoin   ( BlockHash (..),+    BlockNode (..),     Headers (..),     Inv (..),     InvType (..),@@ -55,18 +59,27 @@ import Haskoin.Node   ( Chain,     ChainEvent (..),+    Judgement (..),     LogLevel (..),     Logger,     Node (..),     NodeConfig (..),     NodeEvent (..),+    OnlinePeer (..),+    Peer,     PeerEvent (..),     PeerMgr,+    Permissions,     WithConnection,+    chainGetBest,+    chainHasHeaders,+    getPeers,+    judgeMessage,     logAt,     withNode,     withSource,   )+import Haskoin.Node.Address (toSockAddr) import Haskoin.Store.BlockStore   ( BlockStore,     BlockStoreConfig (..),@@ -77,33 +90,47 @@     blockStorePeerConnectSTM,     blockStorePeerDisconnectSTM,     blockStorePongSTM,-    blockStoreTxHashSTM,-    blockStoreTxSTM,     withBlockStore,   ) import Haskoin.Store.Common   ( StoreEvent (..),     loopForever,   )+import Haskoin.Store.Data (DatabaseHealth) import Haskoin.Store.Database.Migrate (Migration (..), upgradeDatabase)+import Haskoin.Store.Database.Query qualified as Q import Haskoin.Store.Database.Reader   ( DatabaseReader (..),     createDataMetrics,     withLayeredReader,   )-import Haskoin.Store.Database.Stalls (Stall, noStall, watchStalls)+import Haskoin.Store.Database.Stalls (noStall, watchStalls) import Haskoin.Store.Fleet.Member   ( Member (..),     MemberConfig (..),     memberCacheLoop,     memberEvents,     memberLoop,-    memberReceived,-    memberSeen,     newMember,     noteBest,   ) import Haskoin.Store.Fleet.Redis (FleetEvent (..))+import Haskoin.Store.Ingest (defaultConfig)+import Haskoin.Store.Ingest.Run+  ( IngestConfig (..),+    Ingester,+    ingestEmptiedSTM,+    ingestLookSTM,+    ingestMissingSTM,+    ingestNamedSTM,+    ingestPeerDownSTM,+    ingestPeerUpSTM,+    ingestTxSTM,+    withIngest,+  )+import Haskoin.Store.NodePeer (NodePeer (..), lacksZmq, nodePeerAddress, nodePeerConnect, nodePeerName)+import Haskoin.Store.NodeRpc (nodeSession)+import Haskoin.Store.NodeZmq (parseZmqAddress) import Haskoin.Store.Startup (connectRedis, explainDatabase) import Haskoin.Store.XPub.Service (XPubConfig (..)) import NQE@@ -126,8 +153,11 @@     peerMgr :: !PeerMgr,     -- | block header chain of the node     chain :: !Chain,-    -- | process that imports blocks and transactions+    -- | process that imports blocks     block :: !BlockStore,+    -- | the path of transactions from the peers to the pool of the fleet+    -- ("Haskoin.Store.Ingest.Run")+    ingest :: !Ingester,     -- | database reader     db :: !DatabaseReader,     -- | the store as a member of its fleet, with the door to the fleet's@@ -148,9 +178,10 @@     -- besides the ones of the peer manager     -- ("Haskoin.Store.Web.Publish")     connect :: !(SockAddr -> WithConnection),-    -- | whether RocksDB lets writes through, polled every five seconds+    -- | the state of the database: whether RocksDB lets writes through,+    -- and its work in the background, polled every five seconds     -- ("Haskoin.Store.Database.Stalls"); @\/health@ reports it-    writes :: !(TVar Stall)+    writes :: !(TVar DatabaseHealth)   }  -- | Configuration for a 'Store'.@@ -159,6 +190,16 @@     maxPeers :: !Int,     -- | static set of peers to connect to     initPeers :: ![String],+    -- | the permissions that the nodes of 'initPeers' grant the store with+    -- @-whitelist@ or @-whitebind@, such as 'Haskoin.Node.PermMempool', which lets the+    -- store ask them for their mempools ('Haskoin.Node.NodeConfig')+    peerPermissions :: !Permissions,+    -- | whether the nodes of 'initPeers' are nodes of somebody else. They+    -- are taken for nodes of the operator otherwise, and the store takes+    -- what such a node took: a transaction that only strangers named is+    -- looked at first, and not taken if the store cannot verify it+    -- ("Haskoin.Store.Ingest").+    foreignPeers :: !Bool,     -- | discover new peers     discover :: !Bool,     -- | RocksDB database path@@ -197,6 +238,17 @@     maxPeerLife :: !NominalDiffTime,     -- | connect to peers using the function 'Haskoin.Node.withConnection'     connect :: !(SockAddr -> WithConnection),+    -- | the RPC of a full node of the operator, its Unix socket if it has+    -- one, and where that node publishes over ZeroMQ. With the RPC, the+    -- node is one more peer of the store, which needs no peer-to-peer+    -- connection ("Haskoin.Store.NodePeer"). The ZeroMQ socket is+    -- expected with it: without it the node is asked every five seconds+    -- for what the socket would announce, and the store warns of it.+    -- The web server has the RPC too, to publish through+    -- ('Haskoin.Store.Web.WebConfig').+    nodePeerRpc :: !(Maybe String),+    nodePeerRpcSocket :: !(Maybe FilePath),+    nodePeerZmq :: !(Maybe String),     -- | StatsD     stats :: !(Maybe Stats),     -- | Bloom filters on the column families that are read by key@@ -237,7 +289,11 @@   StoreConfig ->   (Store -> IO a) ->   IO a-withStore cfg action = do+withStore cfg0 action = do+  -- whether the node peer is the only node of the operator that is a+  -- peer: asked of the peer manager, which is not there yet+  alone <- newIORef (return True)+  cfg <- withNodePeer (join (readIORef alone)) cfg0   -- Redis first: a store cannot run without it, and finding out after the   -- database opened and the node started only takes longer   redis <- mapM connectRedis cfg.redis@@ -247,38 +303,105 @@         withPublisher $ \node_pub ->           withSubscription node_pub $ \node_sub ->             withNode (nodeCfg cfg db node_pub) $ \node -> do+              writeIORef alone (onlyNodePeer cfg node)               member <- storeMember cfg redis db-              withBlockStore (blockStoreCfg cfg node pub db member) $ \block_store ->-                withAsync (nodeForwarder block_store pub node_sub) $ \fwd -> do-                  link fwd-                  withStoreFleet cfg pub member $-                    withFleetEvents cfg pub member $ \events ->-                      action $-                        Store-                          { peerMgr = node.peerMgr,-                            chain = node.chain,-                            block = block_store,-                            db = db,-                            fleet = member,-                            events = events,-                            pub = pub,-                            net = cfg.net,-                            connect = cfg.connect,-                            writes = writes-                          }+              -- whether the store ever had the blocks of its nodes+              begun <- newIORef False+              withIngest (ingestCfg begun cfg node db member) $ \ingest ->+                withBlockStore (blockStoreCfg cfg node pub db member ingest) $ \block_store ->+                  withAsync (nodeForwarder block_store ingest pub node_sub) $ \fwd -> do+                    link fwd+                    withStoreFleet member ingest $+                      withFleetEvents cfg pub member $ \events ->+                        action $+                          Store+                            { peerMgr = node.peerMgr,+                              chain = node.chain,+                              block = block_store,+                              ingest = ingest,+                              db = db,+                              fleet = member,+                              events = events,+                              pub = pub,+                              net = cfg.net,+                              connect = cfg.connect,+                              writes = writes+                            } +-- | The configuration of a store that has the RPC of a node, with that+-- node as one more of its peers ("Haskoin.Store.NodePeer"): it is named+-- among the peers that the store was given, and a connection to its+-- address is a pipe in memory. Any other store is left as it is. With+-- whether no other node of the operator is a peer of the store.+--+-- The address of its ZeroMQ socket is expected with it. A store without+-- it has the peer all the same, which then asks the node every five+-- seconds, and says so with a warning here and in its health.+--+-- An address of ZeroMQ that cannot be read stops the store, as any+-- option that makes no sense does.+withNodePeer :: IO Bool -> StoreConfig -> IO StoreConfig+withNodePeer alone cfg = case cfg.nodePeerRpc of+  Just url -> do+    zmq <- forM cfg.nodePeerZmq (either (throwIO . userError) return . parseZmqAddress)+    session <- nodeSession cfg.nodePeerRpcSocket+    let logger = withSource "Node RPC" cfg.logger+        peer = NodePeer {net = cfg.net, session, url, zmq, alone, logger}+        connect sa+          | sa == nodePeerAddress = nodePeerConnect peer+          | otherwise = cfg.connect sa+    when (isNothing zmq) (logAt LevelWarn logger lacksZmq)+    return (cfg {initPeers = cfg.initPeers <> [nodePeerName], connect} :: StoreConfig)+  Nothing -> return cfg++-- | Whether a peer is a node of the operator: the node that the store has+-- through its RPC, always, and those that the store was given+-- ('initPeers'), unless it was told that they are not ('foreignPeers').+--+-- A peer is known by its address, as haskoin-node names a peer, and the+-- names of 'initPeers' are resolved here as haskoin-node resolves them+-- ('toSockAddr'), each time that it is asked. A name that resolves to+-- another address by then makes a node of the operator a stranger: what+-- the store cannot verify of it comes late, and nothing is taken that+-- should not be.+ownPeer :: StoreConfig -> Peer -> IO Bool+ownPeer cfg p+  | isNodePeer p = return (isJust cfg.nodePeerRpc)+  | cfg.foreignPeers = return False+  | otherwise = do+      given <- concat <$> mapM (toSockAddr cfg.net) cfg.initPeers+      return (show p `elem` map show given)++-- | Whether a peer is the node that the store has through its RPC.+isNodePeer :: Peer -> Bool+isNodePeer p = show p == show nodePeerAddress++-- | Whether no node of the operator is a peer of the store now but the+-- one that it has through its RPC: every other peer is a stranger, or+-- there is none.+onlyNodePeer :: StoreConfig -> Node -> IO Bool+onlyNodePeer cfg node = do+  peers <- getPeers node.peerMgr+  not . or <$> mapM (ownPeer cfg . (.mailbox)) (filter (not . isNodePeer . (.mailbox)) peers)+ -- | Watch RocksDB for write stalls while an action runs -- ("Haskoin.Store.Database.Stalls"), and give the action the latest state.-withStalls :: StoreConfig -> DatabaseReader -> (TVar Stall -> IO a) -> IO a+withStalls :: StoreConfig -> DatabaseReader -> (TVar DatabaseHealth -> IO a) -> IO a withStalls cfg db action = do   writes <- newTVarIO noStall   withAsync (watchStalls note cfg.stats db.db writes) $ \a -> link a >> action writes   where     note level = logAt level (withSource "Database" cfg.logger) --- | What every key of the fleet in Redis starts with.+-- | What every key of the fleet in Redis starts with. The number is that of+-- the way the fleet keeps its state: stores that keep it in another way+-- have another, and so are a fleet of their own on the same Redis, where+-- sharing keys would have each misread what the other wrote. It is 3 since+-- the rules of the shared mempool are decided in Haskell+-- ("Haskoin.Store.Fleet.Pool.Decide"), which keeps what a transaction does+-- at addresses in a form that the script before it does not read. cachePrefix :: Network -> ByteString-cachePrefix net = "hs2:" <> C.pack net.name <> ":"+cachePrefix net = "hs3:" <> C.pack net.name <> ":"  -- | The store as a member of its fleet, on the Redis that 'connectRedis' -- connected and checked ('Nothing' only without one, in tests): under a@@ -308,21 +431,26 @@   Nothing -> return Nothing  -- | Take the store's turns as a member of its fleet while an action runs,--- if it is one: every two seconds, and whenever the best block changes.--- Beside them, in a thread of its own, the member builds the entries of--- the fleet's cache of extended public keys that requests asked for.-withStoreFleet :: StoreConfig -> Publisher StoreEvent -> Maybe Member -> IO a -> IO a-withStoreFleet _ _ Nothing action = action-withStoreFleet _ pub (Just member) action =-  withSubscription pub $ \sub ->-    withAsync (memberLoop member (nextBlock sub)) $ \a ->-      withAsync (memberCacheLoop member) $ \b -> link a >> link b >> action+-- if it is one: every two seconds, whenever the best block changes, and+-- an offer as soon as a transaction comes ('memberLoop'). Beside them, in+-- a thread of its own, the member builds the entries of the fleet's cache+-- of extended public keys that requests asked for.+withStoreFleet :: Maybe Member -> Ingester -> IO a -> IO a+withStoreFleet Nothing _ action = action+withStoreFleet (Just member) ingest action =+  withAsync (memberLoop member) $ \a ->+    withAsync (memberCacheLoop member) $ \b ->+      withAsync (emptied 0) $ \c -> link a >> link b >> link c >> action   where-    -- until the next block-    nextBlock sub =-      receive sub >>= \case-        StoreBestBlock _ -> return ()-        _ -> nextBlock sub+    -- each time the member finds that the pool lost what it had, the path+    -- into the pool is told, and reads its sources again+    emptied seen = do+      n <- atomically $ do+        n <- readTVar member.refills+        when (n == seen) retry+        return n+      atomically (ingestEmptiedSTM ingest)+      emptied n  -- | Run an action with the events that the store tells its clients: those -- of the fleet, which a thread reads from Redis for as long as the action@@ -388,18 +516,18 @@   Publisher StoreEvent ->   DatabaseReader ->   Maybe Member ->+  Ingester ->   BlockStoreConfig-blockStoreCfg cfg node pub db member =+blockStoreCfg cfg node pub db member ingest =   BlockStoreConfig     { chain = node.chain,       peerMgr = node.peerMgr,       pub = pub,       db = db,       net = cfg.net,-      explicitPeers = cfg.initPeers,-      onBest = maybe (\_ -> return ()) noteBest member,-      onTx = maybe (\_ _ -> return ()) memberReceived member,-      seen = maybe (\_ -> return mempty) memberSeen member,+      -- the member takes its view of the block, and the path into the+      -- pool looks at whether the store is in sync now+      onBest = \h -> mapM_ (`noteBest` h) member >> atomically (ingestLookSTM ingest),       blockWindow = cfg.blockWindow,       peerTimeout = cfg.peerTimeout,       blockStall = cfg.blockStall,@@ -408,6 +536,44 @@       logger = withSource "BlockStore" cfg.logger     } +-- | What the path into the pool needs of the store ("Haskoin.Store.Ingest.Run"):+-- the member of the fleet, whether the best block of the database is the+-- best header of the node, and the first time whether the node has the+-- headers of its peers too, which peers give their mempools when asked,+-- as the model of each peer's node says ('judgeMessage'), and which are+-- nodes of the operator ('ownPeer').+ingestCfg :: IORef Bool -> StoreConfig -> Node -> DatabaseReader -> Maybe Member -> IngestConfig+ingestCfg begun cfg node db member =+  IngestConfig+    { net = cfg.net,+      config = defaultConfig,+      member,+      -- The first time, the headers too: while the node still takes+      -- them, two thousand at a time, the database catches up with the+      -- last of those that it has again and again, and is at no tip. Not+      -- whether the chain is in sync, which also asks for a block of+      -- the last two hours: a network where none was found has a tip.+      --+      -- Only the first time. A store that had its blocks and has no+      -- peer for a moment, or a peer that owes it headers, is in sync+      -- when its database is at its best header, as it always was.+      inSync = do+        best <- Q.getBestBlock db+        top <- chainGetBest node.chain+        let level = best == Just (headerHash top.header)+        had <- readIORef begun+        if had || not level+          then return level+          else do+            headers <- chainHasHeaders node.chain+            when headers (writeIORef begun True)+            return headers,+      source = \p -> (== Allowed) <$> judgeMessage p MMempool,+      own = ownPeer cfg,+      stats = cfg.stats,+      logger = withSource "Ingest" cfg.logger+    }+ -- | Configuration of the node, from the store configuration. The node keeps its -- headers in the default column family of the store database. nodeCfg ::@@ -431,17 +597,19 @@       timeout = cfg.peerTimeout,       maxPeerLife = cfg.maxPeerLife,       connect = cfg.connect,-      logger = cfg.logger+      logger = cfg.logger,+      permissions = cfg.peerPermissions     }  -- | Forward every node event to the block store and the store publisher, forever. nodeForwarder ::   BlockStore ->+  Ingester ->   Publisher StoreEvent ->   Inbox NodeEvent ->   IO ()-nodeForwarder b pub sub =-  loopForever $ receive sub >>= atomically . storeDispatch b pub+nodeForwarder b ing pub sub =+  loopForever $ receive sub >>= atomically . storeDispatch b ing pub  -- | Dispatcher of node events. Peer connections, blocks, transactions, -- inventories and not-found messages go to the block store; peer events,@@ -449,17 +617,20 @@ -- events; new best headers go to the block store. storeDispatch ::   BlockStore ->+  Ingester ->   Publisher StoreEvent ->   NodeEvent ->   STM ()-storeDispatch b pub (PeerEvent pe) =+storeDispatch b ing pub (PeerEvent pe) =   case pe of     PeerConnected p -> do       publishSTM (StorePeerConnected p) pub       blockStorePeerConnectSTM p b+      ingestPeerUpSTM p ing     PeerDisconnected p -> do       publishSTM (StorePeerDisconnected p) pub       blockStorePeerDisconnectSTM p b+      ingestPeerDownSTM p ing     PeerMessage p msg ->       case msg of         MPong (Pong n) -> do@@ -472,14 +643,20 @@         MBlock block ->           blockStoreBlockSTM p block b         MTx tx ->-          blockStoreTxSTM p tx b+          ingestTxSTM p tx ing         MNotFound (NotFound is) -> do           let blocks =                 [ BlockHash h                 | InvVector t h <- is,                   t == InvBlock || t == InvWitnessBlock                 ]+              txs =+                [ TxHash h+                | InvVector t h <- is,+                  t == InvTx || t == InvWitnessTx+                ]           unless (null blocks) $ blockStoreNotFoundSTM p blocks b+          unless (null txs) $ ingestMissingSTM p txs ing         MInv (Inv is) -> do           let txs =                 [ TxHash h@@ -493,12 +670,14 @@                 ]           publishSTM (StoreTxAnnounce p txs) pub           unless (null blocks) $ blockStoreAnnouncedSTM p blocks b-          unless (null txs) $ blockStoreTxHashSTM p txs b+          unless (null txs) $ ingestNamedSTM p txs ing         -- A reject that names no transaction hash cannot be attributed to a         -- transaction and falls through to the catch-all below.         MReject Reject {message = MCTx, extra = Just h, code, reason} ->           publishSTM (StoreTxReject p (TxHash h) code reason.get) pub         _ -> return ()-storeDispatch b _ (ChainEvent (ChainBestBlock bn)) =+storeDispatch b ing _ (ChainEvent (ChainBestBlock bn)) = do   blockStoreHeadSTM bn b-storeDispatch _ _ (ChainEvent _) = return ()+  -- a new best header: the store may be out of sync now+  ingestLookSTM ing+storeDispatch _ _ _ (ChainEvent _) = return ()
+ src/Haskoin/Store/NodePeer.hs view
@@ -0,0 +1,458 @@+-- |+-- Module      : Haskoin.Store.NodePeer+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- A full node as a peer of the store, reached through its RPC and its+-- ZeroMQ socket and not through the peer-to-peer protocol (@--node-rpc@,+-- with @--node-zmq@).+--+-- = The problem+--+-- A store takes its blocks and its transactions from peers, over the+-- peer-to-peer protocol. That protocol is made for strangers: a node+-- tells a peer what it chooses to, at the pace that it chooses, and+-- closes the connection of a peer that asks for more than it grants. An+-- operator who runs the node has two better ways to it. Its RPC answers+-- anything, at once, to whoever has its password. Its ZeroMQ socket+-- publishes every transaction and every block as the node takes them.+-- Together they give all that a peer gives.+--+-- = What this is+--+-- A peer that is no connection to the network: the store is handed the two+-- ends of a pipe in memory, and at the other end a thread answers the+-- messages of the peer-to-peer protocol from the RPC of the node, and+-- announces what the node publishes.+--+-- > the store asks, as it asks any peer      answered from+-- > version                                  getblockcount+-- > getheaders                               getblockheader, getblockhash+-- > getdata of a block                       getblock+-- > getdata of a transaction                 getrawtransaction+-- > mempool                                  getrawmempool+-- > a transaction to relay                   sendrawtransaction+-- > (a new block, a new transaction)         ZeroMQ: hashblock, hashtx+--+-- So nothing else of the store knows the difference. The node counts as+-- a peer in the health of the store, it is a node of the operator, whose+-- word is taken ("Haskoin.Store.Ingest"), and it is a source: it says+-- that it serves Bloom filters, which is what tells the store that a peer+-- gives its mempool. A store can run on it alone, with no peer-to-peer+-- connection at all.+--+-- = Why a peer, and not another way to get blocks+--+-- The store could have learned to take headers and blocks from an RPC,+-- beside the way that it takes them from peers. That is a second path for+-- blocks, with its own windows, its own stalls and its own order, to get+-- right and to keep right. A peer costs a translation of some ten+-- messages, and everything that the store does with a peer, and every test+-- of it, applies as it is.+--+-- = When it is there+--+-- Both connections are the peer. If the RPC fails, or the ZeroMQ socket+-- closes, the peer is gone, and the store sees a peer that disconnected:+-- it connects again, as to any peer. A store whose node is down is a+-- store with no peer, and says so.+--+-- A ZeroMQ socket can also go quiet without closing, and a node drops what+-- a slow subscriber does not read. So the thread asks the node for its+-- best block every thirty seconds, and announces it if nothing did. When+-- messages may have been lost, it names the whole mempool of the node, as+-- an answer to @mempool@ does.+--+-- = Without the ZeroMQ socket+--+-- A node is meant to be given with both, and a store that has only the+-- RPC says so, in its log and in its health. It is a peer all the same,+-- and since the RPC announces nothing, the thread asks instead, every+-- five seconds ('pollEvery'):+--+-- * for the best block of the node, which it announces if it is new;+-- * for the ids of the mempool of the node, of which it names those that+--   were not there the last time, as a node names what it just took.+--+-- It asks for the mempool only while no other node of the operator is a+-- peer of the store ('alone'). Such a peer announces what the node takes,+-- and reading the mempool beside it would say the same twice. While every+-- other peer is a stranger, this reading is the only word of a node of+-- the operator that the store gets, and a transaction that only strangers+-- named waits for it ("Haskoin.Store.Ingest"): so it is asked for often.+--+-- A store without the socket is up to five seconds behind its node, and+-- asks it for the ids of its whole mempool each time: some four megabytes+-- of JSON for a mempool of sixty thousand transactions. That is the price+-- of not giving the socket.+--+-- = What it does not do+--+-- It serves no addresses of other nodes, no filters and no compact+-- blocks: the store asks a peer for none of them. Blocks come one RPC+-- call each, as hexadecimal in JSON, which is slower than the+-- peer-to-peer protocol for the first sync of a chain.+module Haskoin.Store.NodePeer+  ( NodePeer (..),+    nodePeerName,+    nodePeerAddress,+    nodePeerConnect,+    lacksZmq,+    pollEvery,+    fresh,+  )+where++import Conduit (awaitForever, liftIO, yield)+import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (race_)+import Control.Concurrent.STM+  ( TBQueue,+    atomically,+    newTBQueueIO,+    newTVarIO,+    readTBQueue,+    readTVarIO,+    writeTBQueue,+    writeTVar,+  )+import Control.Exception (finally, throwIO)+import Control.Monad (forM, forM_, forever, unless, void, when)+import Data.Aeson qualified as A+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Bits ((.|.))+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.Foldable (toList)+import Data.IORef (newIORef, readIORef, writeIORef)+import Data.Maybe (catMaybes, isNothing, listToMaybe)+import Data.Serialize (decode, encode, putByteString, putWord32be, putWord32le, runGet, runPut)+import Data.Set (Set)+import Data.Set qualified as Set+import Data.Text (Text)+import Data.Time.Clock.POSIX (getPOSIXTime)+import Haskoin+  ( BlockHash (..),+    BlockHeader,+    GetData (..),+    GetHeaders (..),+    Headers (..),+    Inv (..),+    InvType (..),+    InvVector (..),+    Message (..),+    Network (..),+    NetworkAddress (..),+    NotFound (..),+    Ping (..),+    Pong (..),+    TxHash (..),+    VarInt (..),+    VarString (..),+    Version (..),+    blockHashToHex,+    decodeHex,+    doubleSHA256,+    encodeHex,+    getMessage,+    hexToBlockHash,+    hexToTxHash,+    nodeBloom,+    nodeNetwork,+    nodeWitness,+    putMessage,+    sockToHostAddress,+    txHashToHex,+  )+import Haskoin.Node (Conduits (..), LogLevel (..), Logger, WithConnection, logAt)+import Haskoin.Store.NodeRpc (RpcFailure (..), nodeAnswers)+import Haskoin.Store.NodeZmq (Heard (..), ZmqAddress, hearNode)+import Network.Socket (SockAddr (..))+import Network.Wreq.Session (Session)+import System.Random (randomIO)++-- | What the peer needs: the network, the RPC of the node and its+-- ZeroMQ socket, if it was given.+data NodePeer = NodePeer+  { net :: !Network,+    -- | the HTTP client of the RPC ('Haskoin.Store.NodeRpc.nodeSession')+    session :: !Session,+    -- | the URL of the RPC, with its user and password+    url :: !String,+    -- | where the node publishes, or 'Nothing' for a node whose RPC is+    -- all that the store has: it is then asked every 'pollEvery'+    zmq :: !(Maybe ZmqAddress),+    -- | whether no other node of the operator is a peer of the store now:+    -- the mempool of a node without a ZeroMQ socket is read only then+    alone :: !(IO Bool),+    logger :: !Logger+  }++-- | The name of the peer among the peers of a store, as @--peer@ would+-- have it: a Unix socket whose path no socket has.+nodePeerName :: String+nodePeerName = "unix:@node-rpc"++-- | The address that 'nodePeerName' is: a store that is asked to connect+-- to it is given 'nodePeerConnect' in place of a connection.+nodePeerAddress :: SockAddr+nodePeerAddress = SockAddrUnix "@node-rpc"++-- | What happens at the other end of the pipe.+data Event+  = -- | bytes of the store, or the end of them+    Bytes !(Maybe ByteString)+  | Said !Heard+  | -- | time to ask the node for its best block and, without a ZeroMQ+    -- socket, for its mempool+    Poll++-- | How often a node without a ZeroMQ socket is asked for its best block+-- and for its mempool, in microseconds: five seconds. It is how far such+-- a store is behind its node.+pollEvery :: Int+pollEvery = 5000000++-- | Of the ids of a mempool, those that were not there the last time, in+-- the order that the node gave them: what a node that announces would+-- have named since.+fresh :: (Ord h) => Set h -> [h] -> [h]+fresh before = filter (`Set.notMember` before)++-- | A connection to the peer: a pipe in memory, served until the store+-- closes it or the node fails.+nodePeerConnect :: NodePeer -> WithConnection+nodePeerConnect cfg act = do+  toStore <- newTBQueueIO 256+  events <- newTBQueueIO 1024+  let conduits =+        Conduits+          { inboundConduit = source toStore,+            outboundConduit =+              awaitForever (liftIO . atomically . writeTBQueue events . Bytes . Just)+                >> liftIO (atomically (writeTBQueue events (Bytes Nothing)))+          }+      source q = liftIO (atomically (readTBQueue q)) >>= maybe (return ()) (\b -> yield b >> source q)+      -- whatever ends the serving, the store reads the end of the pipe+      served = serve cfg toStore events `finally` atomically (writeTBQueue toStore Nothing)+      -- without a socket there is nothing to hear, and no end of it+      hearing = case cfg.zmq of+        Just zmq -> hearNode zmq (atomically . writeTBQueue events . Said)+        Nothing -> forever (threadDelay maxBound)+      wait = if isNothing cfg.zmq then pollEvery else 30000000+      polling = forever (threadDelay wait >> atomically (writeTBQueue events Poll))+  race_ (act conduits) (race_ served (race_ hearing polling))++-- | Answer the store until it closes the pipe. Any failure of the RPC ends+-- it, and with it the peer.+serve :: NodePeer -> TBQueue (Maybe ByteString) -> TBQueue Event -> IO ()+serve cfg toStore events = do+  buffer <- newIORef B.empty+  announced <- newTVarIO Nothing+  -- the mempool of the node as it was last read+  named <- newIORef Set.empty+  let send m = atomically (writeTBQueue toStore (Just (runPut (putMessage cfg.net m))))+      -- a message whose payload is here already, as the node gave it+      sendRaw name payload = atomically (writeTBQueue toStore (Just (framed cfg.net name payload)))+      announce b = do+        before <- readTVarIO announced+        unless (before == Just b) $ do+          atomically (writeTVar announced (Just b))+          send (MInv (Inv [InvVector InvBlock b.get]))+      loop = do+        event <- atomically (readTBQueue events)+        case event of+          Bytes Nothing -> return ()+          Bytes (Just bytes) -> do+            before <- readIORef buffer+            let (messages, rest) = split cfg.net (before <> bytes)+            writeIORef buffer rest+            mapM_ (answer cfg send sendRaw whole) messages+            loop+          Said (HeardTxs hs) -> send (MInv (Inv [InvVector InvTx h.get | h <- hs])) >> loop+          Said (HeardBlock b) -> announce b >> loop+          -- something was not heard: all that the node has is named+          Said Missed -> whole >> best >>= announce >> loop+          Poll -> do+            best >>= announce+            quiet <- if isNothing cfg.zmq then cfg.alone else return False+            when quiet news+            loop+      -- every transaction of the mempool of the node+      whole = do+        hs <- mempool cfg+        writeIORef named (Set.fromList hs)+        naming hs+      -- those that the node took since its mempool was last read+      news = do+        hs <- mempool cfg+        before <- readIORef named+        writeIORef named (Set.fromList hs)+        naming (fresh before hs)+      -- as many to a message as a node names+      naming hs = forM_ (pieces hs) $ \some -> send (MInv (Inv [InvVector InvTx h.get | h <- some]))+      pieces hs+        | null hs = []+        | otherwise = take 50000 hs : pieces (drop 50000 hs)+      best =+        call cfg "getbestblockhash" [] >>= \case+          A.String t | Just b <- hexToBlockHash t -> return b+          other -> unexpected "getbestblockhash" other+  loop++-- | What the node answers to a message of the store.+answer :: NodePeer -> (Message -> IO ()) -> (ByteString -> ByteString -> IO ()) -> IO () -> Message -> IO ()+answer cfg send sendRaw whole = \case+  MVersion _ -> do+    height <-+      call cfg "getblockcount" [] >>= \case+        A.Number n -> return (round n)+        other -> unexpected "getblockcount" other+    now <- round <$> getPOSIXTime+    nonce <- randomIO+    -- a node that has the whole chain, with witnesses where there are+    -- any, and that gives its mempool when asked: what a node says when it+    -- serves Bloom filters+    let services = nodeNetwork .|. nodeBloom .|. (if cfg.net.segWit then nodeWitness else 0)+        here = NetworkAddress services (sockToHostAddress (SockAddrInet 0 0))+    send . MVersion $+      Version+        { version = 70016,+          services,+          timestamp = now,+          addrRecv = here,+          addrSend = here,+          nonce,+          userAgent = VarString peerLabel,+          startHeight = height,+          relay = True+        }+    send MVerAck+    case cfg.zmq of+      Just _ -> logAt LevelInfo cfg.logger "The node is a peer of the store through its RPC and its ZeroMQ socket"+      Nothing -> logAt LevelWarn cfg.logger lacksZmq+  -- A ping is answered once the node has answered a call: the store+  -- tells a peer that is there from one that is not by its pongs, and+  -- this thread would answer for a node that is gone.+  MPing (Ping n) -> call cfg "getblockcount" [] >> send (MPong (Pong n))+  MGetHeaders gh -> headersAfter cfg gh.locator >>= \hs -> send (MHeaders (Headers [(h, VarInt 0) | h <- hs]))+  MGetData (GetData ivs) -> do+    forM_ [BlockHash h | InvVector t h <- ivs, t `elem` [InvBlock, InvWitnessBlock]] $ \b ->+      call' cfg "getblock" [A.String (blockHashToHex b), A.Number 0] >>= \case+        Right (A.String hex) | Just bytes <- decodeHex hex -> sendRaw "block" bytes+        Left _ -> send (MNotFound (NotFound [InvVector InvBlock b.get]))+        Right other -> unexpected "getblock" other+    let wanted = [TxHash h | InvVector t h <- ivs, t `elem` [InvTx, InvWitnessTx]]+    answers <- nodeAnswers cfg.session cfg.url [("getrawtransaction", [A.String (txHashToHex h)]) | h <- wanted]+    lacking <- forM (zip wanted answers) $ \case+      (_, Right (A.String hex)) | Just bytes <- decodeHex hex -> sendRaw "tx" bytes >> return Nothing+      -- the node says that it has it not+      (h, Left _) -> return (Just h)+      (_, Right other) -> unexpected "getrawtransaction" other+    unless (null (catMaybes lacking)) $+      send (MNotFound (NotFound [InvVector InvTx h.get | h <- catMaybes lacking]))+  MMempool -> whole+  -- a transaction that the store relays for a client: the node judges it+  MTx tx -> void (call' cfg "sendrawtransaction" [A.String (encodeHex (encode tx))])+  -- the rest asks for nothing that the store waits for+  _ -> return ()++-- | What the peer calls itself in its version message, which never+-- leaves the store.+peerLabel :: ByteString+peerLabel = "/node-rpc/"++-- | What a store says, in its log and in its health, when it has the RPC+-- of its node and not its ZeroMQ socket.+lacksZmq :: Text+lacksZmq =+  "The store has the RPC of its node and not its ZeroMQ socket (--node-zmq): \+  \it asks the node every five seconds for what the socket would announce at once"++-- | The ids of the mempool of the node.+mempool :: NodePeer -> IO [TxHash]+mempool cfg =+  call cfg "getrawmempool" [] >>= \case+    A.Array a | Just hs <- mapM hash (toList a) -> return hs+    other -> unexpected "getrawmempool" other+  where+    hash = \case+      A.String t -> hexToTxHash t+      _ -> Nothing++-- | The headers of the chain of the node after the first block of a+-- locator that is in it, two thousand at most, as a node answers+-- @getheaders@. A locator ends with the first block of the chain, which+-- every node has.+headersAfter :: NodePeer -> [BlockHash] -> IO [BlockHeader]+headersAfter cfg locator = do+  known <- many [("getblockheader", [A.String (blockHashToHex b), A.Bool True]) | b <- locator]+  -- a block that is not in the best chain has no confirmations, or less+  -- than none+  let heights =+        [ round h :: Int+        | Right (A.Object o) <- known,+          Just (A.Number c) <- [KeyMap.lookup "confirmations" o],+          c > 0,+          Just (A.Number h) <- [KeyMap.lookup "height" o]+        ]+  top <-+    call cfg "getblockcount" [] >>= \case+      A.Number n -> return (round n :: Int)+      other -> unexpected "getblockcount" other+  case listToMaybe heights of+    Nothing -> return []+    Just from -> do+      hashes <- many [("getblockhash", [A.Number (fromIntegral h)]) | h <- [from + 1 .. min top (from + 2000)]]+      found <- many [("getblockheader", [h, A.Bool False]) | Right h <- hashes]+      -- the chain of the node may change between the calls: the headers+      -- that are there, up to the first that is not+      return (catMaybes (takeWhile (/= Nothing) (map header found)))+  where+    many = nodeAnswers cfg.session cfg.url+    header = \case+      Right (A.String hex) | Just bytes <- decodeHex hex, Right h <- decode bytes -> Just h+      _ -> Nothing++-- | One call of the RPC, and its result: an error of the node is a+-- failure.+call :: NodePeer -> Text -> [A.Value] -> IO A.Value+call cfg method params = call' cfg method params >>= either (unexpected method) return++-- | One call of the RPC: the error of the node, or its result.+call' :: NodePeer -> Text -> [A.Value] -> IO (Either A.Value A.Value)+call' cfg method params =+  nodeAnswers cfg.session cfg.url [(method, params)] >>= \case+    [r] -> return r+    _ -> throwIO (RpcFailure ("No answer to " <> show method))++unexpected :: (Show v) => Text -> v -> IO a+unexpected method v = throwIO (RpcFailure ("Unexpected answer to " <> show method <> ": " <> take 200 (show v)))++-- | The messages at the front of some bytes, and the bytes after them. A+-- message is 24 bytes of header, with the length of the rest in the+-- seventeenth to the twentieth. One that cannot be read is left out.+split :: Network -> ByteString -> ([Message], ByteString)+split net bytes+  | B.length bytes < 24 = ([], bytes)+  | B.length bytes < 24 + size = ([], bytes)+  | otherwise =+      let (one, rest) = B.splitAt (24 + size) bytes+          (more, left) = split net rest+       in (either (const more) (: more) (runGet (getMessage net) one), left)+  where+    size = B.foldr (\w acc -> acc * 256 + fromIntegral w) 0 (B.take 4 (B.drop 16 bytes))++-- | A message of the peer-to-peer protocol with a payload that is given+-- as bytes: the magic of the network, the name in twelve bytes, the+-- length, and the first four bytes of the double hash of the payload.+framed :: Network -> ByteString -> ByteString -> ByteString+framed net name payload = runPut $ do+  putWord32be net.magic+  putByteString (name <> B.replicate (12 - B.length name) 0)+  putWord32le (fromIntegral (B.length payload))+  putByteString (B.take 4 (encode (doubleSHA256 payload)))+  putByteString payload
+ src/Haskoin/Store/NodeRpc.hs view
@@ -0,0 +1,175 @@+-- |+-- Module      : Haskoin.Store.NodeRpc+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- The JSON-RPC of the store's node (@--node-rpc@), as far as the store+-- uses it: the HTTP client that reaches it, and the mempool of the node+-- read through it, as a source of the path into the shared mempool+-- ('nodeFeed').+--+-- A store needs nothing of a node but to be its peer, and the RPC is an+-- option. What it adds to the path into the pool is a source that does not+-- depend on what the node allows its peers: a node announces a transaction+-- to a peer once, so what a store misses comes back only by reading a+-- whole mempool again, and Bitcoin Core lets only a peer that it+-- whitelists do that. The RPC always answers its account.+--+-- The rule that this module keeps is to tell a node that __says__+-- something from a node that __does not answer__. A node that says that it+-- has not a transaction is believed, and the transaction is given up as+-- gone from its mempool. A node that does not answer, or whose answer+-- cannot be read, says nothing about any transaction: that is an+-- exception here, t'RpcFailure', never an empty mempool or a transaction+-- that is gone. The code before this one read a failed call as an empty+-- mempool.+module Haskoin.Store.NodeRpc+  ( nodeSession,+    unixSocketManager,+    nodeOptions,+    RpcFailure (..),+    nodeAnswers,+    nodeFeed,+  )+where++import Control.Exception (Exception, throwIO)+import Control.Lens ((&), (.~), (?~), (^.))+import Control.Monad (forM)+import Data.Aeson ((.=))+import Data.Aeson qualified as A+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Foldable (toList)+import Data.HashMap.Strict qualified as HashMap+import Data.Serialize (decode)+import Data.Text (Text)+import Data.Text qualified as T+import Haskoin (decodeHex, hexToTxHash, txHashToHex)+import Haskoin.Store.Exception (onException)+import Haskoin.Store.Ingest.Run (Feed (..))+import Network.HTTP.Client (ManagerSettings (..), defaultManagerSettings)+import Network.HTTP.Client.Internal (socketConnection)+import Network.Socket (Family (AF_UNIX), SockAddr (SockAddrUnix), SocketType (Stream))+import Network.Socket qualified as Socket+import Network.Wreq qualified as Wreq+import Network.Wreq.Session (Session)+import Network.Wreq.Session qualified as Wreq.Session++-- | An HTTP client for the RPC of the node: one whose every connection+-- goes to a Unix socket if one is given (@--node-rpc-socket@), or one that+-- goes where the URL says.+nodeSession :: Maybe FilePath -> IO Session+nodeSession = \case+  Nothing -> Wreq.Session.newAPISession+  Just path -> Wreq.Session.newSessionControl Nothing (unixSocketManager path)++-- | Settings of an HTTP client whose every connection goes to a Unix+-- socket, whatever host and port the URL names: for the RPC of a node that+-- is reached through a socket (@--node-rpc-socket@). Neither Bitcoin Core+-- nor Bitcoin Cash Node listens on one, so the socket is something that+-- joins it to the node, such as socat, or the bridge of a test in a+-- container. The URL still carries the user and the password of the RPC.+unixSocketManager :: FilePath -> ManagerSettings+unixSocketManager path =+  defaultManagerSettings+    { managerRawConnection = return $ \_ _ _ -> do+        s <- Socket.socket AF_UNIX Stream Socket.defaultProtocol+        Socket.connect s (SockAddrUnix path) `onException` Socket.close s+        socketConnection s 8192+    }++-- | The options of every request to the node's JSON-RPC: an answer of any+-- status is read, since the node says what went wrong in its body, and the+-- connection is closed after each answer. A connection kept open made+-- Bitcoin Cash Node wait, when it stopped, until the connection had been+-- idle for its @-rpcservertimeout@, 30 seconds by default. A new+-- connection for each request costs nothing that shows: the store calls+-- the RPC to publish a transaction, and to read the mempool in requests of+-- thousands of transactions each.+nodeOptions :: Wreq.Options+nodeOptions =+  Wreq.defaults+    & Wreq.checkResponse ?~ (\_ _ -> return ())+    & Wreq.header "Connection" .~ ["close"]++-- | The node did not answer a call of its RPC, or answered what cannot be+-- read, with what happened. It says nothing of what the node has.+newtype RpcFailure = RpcFailure String+  deriving (Show)++instance Exception RpcFailure++-- | What a node answers to calls of its JSON-RPC, made in one batch, in+-- the order of the calls: for each the result, or the error that the node+-- gave in its place. Throws when the node gives no answer that can be read+-- to any one of the calls, t'RpcFailure' or the exception of the HTTP+-- client: the answers are all there or none is.+nodeAnswers :: Session -> String -> [(Text, [A.Value])] -> IO [Either A.Value A.Value]+nodeAnswers _ _ [] = return []+nodeAnswers session url calls = do+  r <- Wreq.Session.postWith nodeOptions session url (A.toJSON (zipWith call [0 :: Int ..] calls))+  let status = r ^. Wreq.responseStatus . Wreq.statusCode+  answers <- case A.decode (r ^. Wreq.responseBody) of+    Just (A.Array a) ->+      return . HashMap.fromList $+        [ (i, answer o)+        | A.Object o <- toList a,+          Just (A.String i) <- [KeyMap.lookup "id" o]+        ]+    _ -> throwIO (RpcFailure ("The node answered HTTP " <> show status <> " and nothing that can be read"))+  forM [0 .. length calls - 1] $ \i ->+    case HashMap.lookup (T.pack (show i)) answers of+      Just (Just x) -> return x+      _ -> throwIO (RpcFailure ("The node gave no answer to call " <> show i <> " of " <> show (length calls)))+  where+    call i (method, params) =+      A.object+        [ "jsonrpc" .= ("1.0" :: Text),+          "id" .= T.pack (show i),+          "method" .= method,+          "params" .= params+        ]+    -- an error that is not null, or else a result, which may be null+    answer o = case (KeyMap.lookup "error" o, KeyMap.lookup "result" o) of+      (Just e, _) | e /= A.Null -> Just (Left e)+      (_, Just v) -> Just (Right v)+      _ -> Nothing++-- | The mempool of a node, read over its RPC, as a source of the path+-- into the shared mempool ('Haskoin.Store.Ingest.Run.ingestFeed'):+-- @getrawmempool@ for the ids, and @getrawtransaction@ in one batch for+-- the transactions that the path asks for.+--+-- A transaction is said to be gone only when the node says so, with the+-- error that both Bitcoin Core and Bitcoin Cash Node give for a+-- transaction that they have not (@RPC_INVALID_ADDRESS_OR_KEY@, -5).+-- Anything else that is not the transaction is an t'RpcFailure'.+--+-- How many transactions a batch has is not decided here: the path asks+-- for as many as the window that it keeps for this source, which follows+-- what the node delivers in time.+nodeFeed :: Session -> String -> Feed+nodeFeed session url = Feed {label = "the mempool of the node over its RPC", names, bodies}+  where+    names =+      nodeAnswers session url [("getrawmempool", [])] >>= \case+        [Right (A.Array a)] | Just hs <- mapM hash (toList a) -> return hs+        other -> throwIO (RpcFailure ("Unexpected answer to getrawmempool: " <> brief other))+    hash = \case+      A.String t -> hexToTxHash t+      _ -> Nothing+    bodies hs = do+      answers <- nodeAnswers session url [("getrawtransaction", [A.String (txHashToHex h)]) | h <- hs]+      forM answers $ \case+        Right (A.String hex)+          | Just bytes <- decodeHex hex, Right tx <- decode bytes -> return (Just tx)+        Left e | lacks e -> return Nothing+        other -> throwIO (RpcFailure ("Unexpected answer to getrawtransaction: " <> brief other))+    lacks = \case+      A.Object o -> KeyMap.lookup "code" o == Just (A.Number (-5))+      _ -> False+    brief :: (Show x) => x -> String+    brief = take 200 . show
+ src/Haskoin/Store/NodeZmq.hs view
@@ -0,0 +1,348 @@+-- |+-- Module      : Haskoin.Store.NodeZmq+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- What a full node publishes over ZeroMQ, as a subscriber hears it+-- (@--node-zmq@).+--+-- = The problem+--+-- A store hears of a transaction when its node names it to a peer, and a+-- node names transactions to a peer at its own pace: Bitcoin Core about+-- fourteen a second after a first batch, to a peer that it whitelists too.+-- A store that has the RPC of its node reads the whole mempool every+-- thirty seconds while transactions come, and is up to that far behind in+-- a burst. The RPC itself announces nothing.+--+-- Both Bitcoin Core and Bitcoin Cash Node can publish what they take as+-- they take it (@-zmqpubhashtx@, @-zmqpubhashblock@): the id of every+-- transaction that enters the mempool, at once, and the hash of every+-- block that becomes the tip. With that and the RPC, a store hears of a+-- transaction and fetches it within the same second.+--+-- = What a node publishes+--+-- Each message has three parts: a topic, a body and a counter of the+-- messages of that topic, four bytes, least significant first.+--+-- > topic      body                              on+-- > hashtx     the id of a transaction           Bitcoin Core, Bitcoin Cash Node+-- > hashblock  the hash of a block               Bitcoin Core, Bitcoin Cash Node+-- > rawtx      a transaction                     both+-- > rawblock   a block                           both+-- > sequence   every change of mempool and tip   Bitcoin Core only+-- > hashds     a double-spend proof              Bitcoin Cash Node only+--+-- The ids and hashes are in the order in which people write them, the+-- reverse of their bytes in a transaction. A transaction is published+-- when it enters the mempool, and again when a block that has it becomes+-- the tip.+--+-- = What it does not give+--+-- The socket only publishes. Nothing can be asked of it, a subscriber+-- that connects late hears nothing of what came before, and a node drops+-- what a slow subscriber does not read, a thousand messages behind by+-- default. The counter says that messages were lost, and not which. So+-- this is never the only way that a store hears of transactions: when a+-- message was lost, or the connection made again, the store reads the+-- mempool of its node ('Heard', 'Missed').+--+-- Nothing is authenticated: whoever reaches the socket hears it, and+-- whoever answers on it is believed. It is for a node of the operator,+-- on the same machine or a network that the operator trusts.+--+-- = Why no library+--+-- ZeroMQ has a library in C, and a Haskell package that binds it. A+-- subscriber needs little of it: a greeting, one command, a subscription+-- for each topic, and frames to read (ZMTP 3.0,+-- <https://rfc.zeromq.org/spec/23/>). That is written here, on the+-- sockets that the store already uses, so that the store gains no library+-- of the system, and reaches a node through a Unix socket as it does+-- everywhere else.+module Haskoin.Store.NodeZmq+  ( -- * Where a node publishes+    ZmqAddress (..),+    parseZmqAddress,++    -- * Subscribing+    ZmqMessage (..),+    zmqSubscribe,++    -- * What the store hears+    Heard (..),+    hearNode,+  )+where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (race_)+import Control.Concurrent.STM (atomically, flushTQueue, newTQueueIO, readTQueue, writeTQueue)+import Control.Exception (Exception, bracket, throwIO)+import Control.Monad (forM_, forever, unless, when)+import Data.Bits (shiftL, shiftR, testBit, (.&.), (.|.))+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.ByteString.Char8 qualified as C+import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)+import Data.Map.Strict qualified as Map+import Data.Serialize (decode)+import Data.Word (Word32, Word64)+import Haskoin (BlockHash, TxHash)+import Network.Socket+  ( AddrInfo (..),+    Family (AF_UNIX),+    SockAddr (SockAddrUnix),+    Socket,+    SocketType (Stream),+    close,+    connect,+    defaultHints,+    defaultProtocol,+    getAddrInfo,+    socket,+  )+import Network.Socket.ByteString (recv, sendAll)+import Text.Read (readMaybe)++-- | Where a node publishes: the address given to its @-zmqpub…@ options.+data ZmqAddress+  = -- | a host and a port (@tcp:\/\/127.0.0.1:28332@)+    ZmqTcp !String !Int+  | -- | a Unix socket (@ipc:\/\/\/run\/bitcoind\/zmq.sock@, or+    -- @unix:\/run\/bitcoind\/zmq.sock@ as Bitcoin Core also writes it)+    ZmqUnix !FilePath+  deriving (Eq, Show)++-- | Read an address as the nodes write it.+parseZmqAddress :: String -> Either String ZmqAddress+parseZmqAddress s+  | Just rest <- after "tcp://" = tcp rest+  | Just path <- after "ipc://", not (null path) = Right (ZmqUnix path)+  | Just path <- after "unix:", not (null path) = Right (ZmqUnix path)+  | otherwise = Left ("Not an address of ZeroMQ, such as tcp://127.0.0.1:28332 or ipc:///run/node/zmq.sock: " <> s)+  where+    after prefix+      | take (length prefix) s == prefix = Just (drop (length prefix) s)+      | otherwise = Nothing+    -- the port is after the last colon: an IPv6 host has colons, and is+    -- written in brackets+    tcp rest = case break (== ':') (reverse rest) of+      (port, ':' : host)+        | Just n <- readMaybe (reverse port),+          n > 0,+          n < (65536 :: Int),+          not (null host) ->+            Right (ZmqTcp (unbracket (reverse host)) n)+      _ -> Left ("No host and port in the address of ZeroMQ: " <> s)+    unbracket h = case h of+      '[' : more | not (null more), last more == ']' -> init more+      _ -> h++-- | A message of a node: its topic, its body, and how many messages of+-- that topic the node published before it.+data ZmqMessage = ZmqMessage+  { topic :: !ByteString,+    body :: !ByteString,+    number :: !Word32+  }+  deriving (Eq, Show)++-- | What went wrong with a connection to the socket of a node.+data ZmqError+  = -- | the other end closed the connection+    ZmqClosed+  | -- | what answered does not speak ZMTP 3 without encryption, or sent+    -- something that a publisher does not send+    ZmqProtocol !String+  deriving (Show)++instance Exception ZmqError++-- | Subscribe to topics of a node and give each message to an action,+-- after an action that is run once the subscription is made. It does not+-- return: it ends with an exception when the connection does.+--+-- What is spoken is ZMTP 3.0 with no security mechanism (@NULL@), which is+-- what a node speaks: a greeting of 64 bytes each way, the command+-- @READY@ each way, a subscription for each topic, and then frames. A+-- subscription is a prefix: a topic is given whole.+zmqSubscribe :: ZmqAddress -> [ByteString] -> IO () -> (ZmqMessage -> IO ()) -> IO a+zmqSubscribe address topics ready deliver = bracket (dial address) close $ \sock -> do+  sendAll sock greeting+  theirs <- exactly sock 64+  unless (B.take 1 theirs == "\xff" && B.index theirs 9 == 0x7f) $+    throwIO (ZmqProtocol "the greeting is not one of ZMTP")+  when (B.index theirs 10 < 3) $+    throwIO (ZmqProtocol ("ZMTP " <> show (B.index theirs 10) <> ", older than 3"))+  unless (B.takeWhile (/= 0) (B.take 20 (B.drop 12 theirs)) == "NULL") $+    throwIO (ZmqProtocol "the socket asks for a security mechanism")+  sendAll sock (frame True False (command "READY" [("Socket-Type", "SUB")]))+  answer <- readFrame sock+  case answer of+    (True, _, name) | B.take 6 name == "\x05READY" -> return ()+    (True, _, name) -> throwIO (ZmqProtocol ("the socket answered " <> C.unpack (B.take 40 name)))+    _ -> throwIO (ZmqProtocol "no READY from the socket")+  -- in ZMTP 3.0 a subscription is a message that starts with a byte 1+  forM_ topics $ \t -> sendAll sock (frame False False (B.cons 1 t))+  ready+  forever $ do+    parts <- readMessage sock+    case parts of+      [t, b, n] | B.length n == 4 -> deliver (ZmqMessage t b (littleEndian n))+      -- a publisher of another kind: no counter+      [t, b] -> deliver (ZmqMessage t b 0)+      _ -> return ()+  where+    -- the signature, version 3.0, the mechanism in twenty bytes, not a+    -- server, and thirty-one bytes of nothing+    greeting =+      B.concat+        [ "\xff\0\0\0\0\0\0\0\x01\x7f",+          "\x03\x00",+          "NULL" <> B.replicate 16 0,+          "\0",+          B.replicate 31 0+        ]+    littleEndian = B.foldr (\w acc -> acc `shiftL` 8 .|. fromIntegral w) 0++-- | A command: its name with its length before it, then properties, each+-- a name with its length in one byte and a value with its length in four.+command :: ByteString -> [(ByteString, ByteString)] -> ByteString+command name properties =+  B.concat (B.singleton (fromIntegral (B.length name)) : name : concatMap property properties)+  where+    property (k, v) = [B.singleton (fromIntegral (B.length k)), k, word32 (B.length v), v]+    word32 n = B.pack [fromIntegral (n `shiftR` s) | s <- [24, 16, 8, 0]]++-- | A frame: whether it is a command, whether more frames of the message+-- follow, and its body. The flags are one byte: 1 for more, 2 for a long+-- size, 4 for a command; the size is one byte, or eight when long.+frame :: Bool -> Bool -> ByteString -> ByteString+frame isCommand more payload+  | n < 256 = B.concat [B.singleton flags, B.singleton (fromIntegral n), payload]+  | otherwise = B.concat [B.singleton (flags .|. 2), word64 (fromIntegral n), payload]+  where+    n = B.length payload+    flags = (if isCommand then 4 else 0) .|. (if more then 1 else 0)+    word64 :: Word64 -> ByteString+    word64 w = B.pack [fromIntegral (w `shiftR` s) | s <- [56, 48, 40, 32, 24, 16, 8, 0]]++-- | The next frame: whether it is a command, whether more follow, and its+-- body.+readFrame :: Socket -> IO (Bool, Bool, ByteString)+readFrame sock = do+  flags <- B.head <$> exactly sock 1+  size <-+    if testBit flags 1+      then B.foldl' (\acc w -> acc `shiftL` 8 .|. fromIntegral w) (0 :: Word64) <$> exactly sock 8+      else fromIntegral . B.head <$> exactly sock 1+  when (size > maxFrame) $ throwIO (ZmqProtocol ("a frame of " <> show size <> " bytes"))+  payload <- exactly sock (fromIntegral size)+  return (testBit flags 2, flags .&. 1 == 1, payload)++-- | The largest frame taken: a block of Bitcoin, with room to spare. A+-- size past it is a connection that is not what it seems.+maxFrame :: Word64+maxFrame = 64000000++-- | The next message: its frames, with the commands between them left+-- out, such as a ping of a newer peer.+readMessage :: Socket -> IO [ByteString]+readMessage sock = go []+  where+    go parts = do+      (isCommand, more, payload) <- readFrame sock+      if isCommand+        then go parts+        else+          if more+            then go (payload : parts)+            else return (reverse (payload : parts))++-- | So many bytes of a socket, or 'ZmqClosed'.+exactly :: Socket -> Int -> IO ByteString+exactly sock = go []+  where+    go got 0 = return (B.concat (reverse got))+    go got n = do+      chunk <- recv sock (min n 65536)+      when (B.null chunk) (throwIO ZmqClosed)+      go (chunk : got) (n - B.length chunk)++-- | A connection to an address.+dial :: ZmqAddress -> IO Socket+dial = \case+  ZmqUnix path -> do+    sock <- socket AF_UNIX Stream defaultProtocol+    connect sock (SockAddrUnix path)+    return sock+  ZmqTcp host port -> do+    found <- getAddrInfo (Just defaultHints {addrSocketType = Stream}) (Just host) (Just (show port))+    case found of+      info : _ -> do+        sock <- socket info.addrFamily info.addrSocketType info.addrProtocol+        connect sock info.addrAddress+        return sock+      [] -> throwIO (ZmqProtocol ("no address for " <> host))++-- | What the store hears of its node.+data Heard+  = -- | the node took these transactions, or a block that became the tip+    -- has them+    HeardTxs ![TxHash]+  | -- | a block became the tip of the node+    HeardBlock !BlockHash+  | -- | something may not have been heard: the subscription was just+    -- made, or the counter of a topic skipped. Only a reading of the+    -- mempool of the node brings back what was lost.+    Missed+  deriving (Eq, Show)++-- | Subscribe to the transactions and blocks of a node (@hashtx@,+-- @hashblock@) and say what is heard. It does not return, and ends with an+-- exception when the connection does: the caller makes it again.+--+-- The ids of transactions are given together when they come together, at+-- most a thousand at once: a block that becomes the tip publishes every+-- transaction that it has, thousands in one go, and the path into the pool+-- asks the pool about a thousand ids in one question, or about one.+--+-- 'Missed' is said first, since what the node took before the+-- subscription was made was not heard, and again whenever the counter of a+-- topic is not the one after the last.+hearNode :: ZmqAddress -> (Heard -> IO ()) -> IO a+hearNode address tell = do+  queue <- newTQueueIO+  counters <- newIORef Map.empty+  let deliver m = do+        seen <- Map.lookup m.topic <$> readIORef counters+        modifyIORef' counters (Map.insert m.topic m.number)+        forM_ seen $ \before -> when (m.number /= before + 1) (atomically (writeTQueue queue Nothing))+        when (B.length m.body == 32) (atomically (writeTQueue queue (Just (m.topic, B.reverse m.body))))+      -- what waits, in the order in which it came: runs of transactions+      -- together, a block or a loss by itself+      batches = forever $ do+        first <- atomically (readTQueue queue)+        -- what comes within a moment comes with it+        threadDelay 20000+        rest <- atomically (flushTQueue queue)+        go [] (first : rest)+      go txs [] = flush txs+      go txs (item : items) = case item of+        Just ("hashtx", h)+          | Right t <- decode h ->+              if length txs >= 999 then flush (t : txs) >> go [] items else go (t : txs) items+        Just ("hashblock", h)+          | Right b <- decode h -> flush txs >> tell (HeardBlock b) >> go [] items+        Nothing -> flush txs >> tell Missed >> go [] items+        _ -> go txs items+      flush txs = unless (null txs) (tell (HeardTxs (reverse txs)))+      started = writeIORef counters Map.empty >> atomically (writeTQueue queue Nothing)+  race_ batches (zmqSubscribe address ["hashtx", "hashblock"] started deliver)+  throwIO ZmqClosed
src/Haskoin/Store/Startup.hs view
@@ -53,6 +53,7 @@      -- * Redis     connectRedis,+    redisConnectInfo,     redisProblem,      -- * Files and directories@@ -107,8 +108,26 @@       "at a running one with --redis-url or REDIS_URL (redis://[:password@]host:port[/db])."     ] +-- | How to connect to the Redis of a URL: the default Redis,+-- @redis:\/\/localhost:6379@, for an empty one; the Unix socket at PATH for+-- @unix:PATH@, as haskoin-node writes a peer on a socket; and what hedis+-- reads of a @redis:\/\/@ URL otherwise, or why it cannot.+--+-- A socket takes no password and no database in the URL: a Redis that+-- listens on a socket is one of the machine, which its permissions guard.+-- The tests reach theirs that way, so that tests that run at once each have+-- their own without a port of the machine.+redisConnectInfo :: String -> Either String R.ConnectInfo+redisConnectInfo = \case+  "" -> Right R.defaultConnectInfo+  'u' : 'n' : 'i' : 'x' : ':' : path+    | null path -> Left "a Unix socket needs a path"+    | otherwise -> Right R.defaultConnectInfo {R.connectAddr = R.ConnectAddrUnixSocket path}+  url -> R.parseConnectInfo url+ -- | Connect to the Redis of the fleet at this URL (empty for the default,--- @redis:\/\/localhost:6379@), and make sure that it answers: a ping must+-- @redis:\/\/localhost:6379@, and @unix:PATH@ for a Unix socket, as+-- 'redisConnectInfo' reads it), and make sure that it answers: a ping must -- come back as @PONG@. Throws a 'StartupError' that says what went wrong: -- the URL is not one of Redis, nothing listens there, the name of the host -- is unknown, Redis wants a password or another one, or it does not answer@@ -121,10 +140,7 @@ -- \"Redis does not answer\". connectRedis :: String -> IO R.Connection connectRedis url = do-  info <--    if null url-      then return R.defaultConnectInfo-      else either badURL return (R.parseConnectInfo url)+  info <- either badURL return (redisConnectInfo url)   -- hedis waits for ever by default for a host that drops the packets   let info' = info {R.connectTimeout = Just (fromMaybe 5 info.connectTimeout)}   conn <- R.connect info' `catch` \(e :: IOException) -> unreachable (show e)@@ -148,7 +164,8 @@           T.pack (show url),           "is not a Redis URL:",           T.pack why <> ".",-          "It should look like redis://localhost:6379, or redis://:password@host:port/db."+          "It should look like redis://localhost:6379, redis://:password@host:port/db,",+          "or unix:/path/to/redis.sock."         ]     unreachable :: String -> IO b     unreachable why
src/Haskoin/Store/Web.hs view
@@ -77,6 +77,7 @@     WebLimits (..),     runWeb,     runWebSocket,+    unixSocketManager,      -- * Request parsing     decodeTxBody,@@ -86,7 +87,6 @@     ailments,      -- * Health-    withDatabase,      -- * Xpubs     Unindexed (..),@@ -117,7 +117,8 @@ import Control.Concurrent (getNumCapabilities, threadDelay) import Control.Concurrent.Async (link, mapConcurrently, race_, withAsync) import Control.Concurrent.STM-  ( TVar,+  ( STM,+    TVar,     atomically,     check,     newTQueueIO,@@ -126,13 +127,12 @@     readTVar,     readTVarIO,     registerDelay,-    retry,     stateTVar,     writeTQueue,     writeTVar,   ) import Control.Exception (Exception, catch, evaluate, fromException, throwIO, try)-import Control.Lens ((&), (.~), (<&>), (?~), (^.))+import Control.Lens ((&), (.~), (^.)) import Control.Monad   ( filterM,     forM,@@ -169,7 +169,6 @@ import Data.Bytes.Serial import Data.Char (isSpace) import Data.Default (Default (..))-import Data.Foldable qualified as Foldable import Data.HashMap.Strict (HashMap) import Data.HashMap.Strict qualified as HashMap import Data.HashSet (HashSet)@@ -198,7 +197,7 @@ import Data.Text.Lazy qualified as TL import Data.Text.Lazy.Encoding qualified as TL import Data.Time.Clock (getCurrentTime)-import Data.Time.Clock.POSIX (POSIXTime, getPOSIXTime)+import Data.Time.Clock.POSIX (getPOSIXTime) import Data.Time.Format (defaultTimeLocale, formatTime) import Data.Word (Word32, Word64) import Database.RocksDB@@ -226,7 +225,6 @@     withSource,   ) import Haskoin.Script-import Haskoin.Store.BlockStore import Haskoin.Store.Common hiding   ( blockAtOrAfter,     blockAtOrAfterMTP,@@ -243,7 +241,6 @@ import Haskoin.Store.Database.Query qualified as Q import Haskoin.Store.Database.Query.Pooled (chainRead) import Haskoin.Store.Database.Reader-import Haskoin.Store.Database.Stalls (Stall (..), Writes (..)) import Haskoin.Store.Exception (bracket, bracket_, catchAny, finally, handleAny, onException, tryAny) import Haskoin.Store.Fleet.Member   ( Member (..),@@ -253,11 +250,16 @@     memberEvents,     memberNewest,     memberPoolBody,-    memberReceived,     memberTip,+    setHealthy,   ) import Haskoin.Store.Fleet.Redis (FleetEvent (..))+import Haskoin.Store.Ingest (Standing (..))+import Haskoin.Store.Ingest.Run (IngestState (..), ingestNamedSTM, ingestState) import Haskoin.Store.Manager+import Haskoin.Store.NodePeer (lacksZmq)+import Haskoin.Store.NodeRpc (nodeOptions, unixSocketManager)+import Haskoin.Store.NodeRpc qualified as NodeRpc import Haskoin.Store.Startup (explainListen, redisProblem) import Haskoin.Store.Web.Admission   ( Admission,@@ -479,8 +481,18 @@     accessLog :: !Bool,     -- | URL of the JSON-RPC interface of a full node, with its user and     -- password, to publish transactions through ('sendNode'); 'Nothing'-    -- to publish through peers only+    -- to publish through peers only. The store has it too, and has the+    -- node as a peer through it ('Haskoin.Store.StoreConfig').     nodeRpc :: !(Maybe String),+    -- | a Unix socket to send the requests of 'nodeRpc' through, in place of+    -- the host and port of its URL, which are not used then+    nodeRpcSocket :: !(Maybe FilePath),+    -- | where the node of 'nodeRpc' publishes over ZeroMQ+    -- (@-zmqpubhashtx@, @-zmqpubhashblock@), as the store was told+    -- ('Haskoin.Store.StoreConfig'). It is expected with 'nodeRpc': a+    -- web server that has the RPC and not this says so in the warnings+    -- of @\/health@ ("Haskoin.Store.NodePeer").+    nodeZmq :: !(Maybe String),     -- | a certificate and its private key, in files in PEM format, to     -- serve HTTPS instead of HTTP; 'Nothing' for HTTP, which is the     -- default@@ -499,6 +511,9 @@     metrics :: !(Maybe WebMetrics),     -- | HTTP session for price requests     session :: !Wreq.Session,+    -- | HTTP session for the RPC of the node: 'session', or one that goes+    -- through 'nodeRpcSocket'+    nodeSession :: !Wreq.Session,     -- | result of the latest health check     health :: !(TVar HealthCheck),     -- | the queries to answer with, the cache included ('xpubQuery'): those@@ -783,6 +798,7 @@   ticker <- newTVarIO HashMap.empty   metrics <- mapM createMetrics config.stats   session <- Wreq.Session.newAPISession+  nodeSession <- maybe (return session) (NodeRpc.nodeSession . Just) config.nodeRpcSocket   first <- runHealthCheck   health <- newTVarIO first   -- A member of a fleet takes no turn before its store is known to be@@ -790,8 +806,10 @@   -- web server has nothing else to say when; with one, a store that had   -- just started took a turn before its first check, reported the blocks   -- that it had then, and with nobody else there moved the fleet to them.-  forM_ config.store.fleet $ \member -> atomically (writeTVar member.healthy (isOK first.blocks && isOK first.peers))+  forM_ config.store.fleet $ \member -> atomically (setHealthy member (isOK first.blocks && isOK first.peers))   cacheUp <- cacheCheck >>= newTVarIO+  -- requests in a row that found Redis too slow to say the tip; see 'reach'+  cacheMisses <- newTVarIO (0 :: Int)   eventLog <- newEventLog   asking <- Publish.newAsking   admission <-@@ -840,9 +858,12 @@         known <- if fresh then return Nothing else fmap encode <$> readTVarIO member.tip         asked <- case known of           Just tip -> return (Just (Just tip))-          Nothing -> timeout 2000000 (memberTip member) `catchAny` \_ -> return Nothing+          Nothing -> do+            r <- timeout 2000000 (memberTip member) `catchAny` \_ -> return Nothing+            atomically (reach cacheMisses cacheUp (isJust r))+            return r         case asked of-          Nothing -> atomically (writeTVar cacheUp False) >> behind answer+          Nothing -> behind answer           -- no store has reported yet           Just Nothing -> behind answer           Just (Just tip) -> do@@ -925,14 +946,18 @@   -- at once   newBlock <- newTVarIO False   date <- httpDate >>= newIORef-  withAsync (forever (snooze 500_000 >> httpDate >>= writeIORef date)) $ \_a0 ->-    withAsync (priceUpdater session ticker) $ \_a1 ->-      withAsync (healthCheckLoop health cacheUp saidWell saidRedis pinged newBlock) $ \_a2 ->-        withAsync (admissionLoop metrics capStats admission) $ \_a5 ->-          withAsync (regulate admission (reportControl metrics)) $ \_a6 ->-            withAsync (feedEvents st) $ \a3 ->-              withAsync (askingLoop st) $ \_a4 ->-                withAsync (refillLoop st) $ \_a7 ->+  -- every loop runs under 'supervised', which logs a failure and starts the+  -- loop again: one that died once did so in silence, and the store went on+  -- without its health checks, its prices or its line of requests+  let supervise = supervised config.logger+  withAsync (supervise "Date" (forever (snooze 500_000 >> httpDate >>= writeIORef date))) $ \_a0 ->+    withAsync (supervise "Prices" (priceUpdater session ticker)) $ \_a1 ->+      withAsync (supervise "Health" (healthCheckLoop health cacheUp cacheMisses saidWell saidRedis pinged newBlock)) $+        \_a2 ->+          withAsync (supervise "Admission" (admissionLoop metrics capStats admission)) $ \_a5 ->+            withAsync (supervise "Regulate" (regulate admission (reportControl metrics))) $ \_a6 ->+              withAsync (feedEvents st) $ \a3 ->+                withAsync (supervise "Publish" (askingLoop st)) $ \_a4 ->                   link a3 >> do                     let logged = logIt config.logger config.accessLog config.limits.slowRequest                         outer =@@ -959,7 +984,7 @@     -- costs little to run often; but a store that is catching up imports     -- thousands of small blocks a second, and a check for each would be     -- work for nothing, so there is a tenth of a second between two.-    healthCheckLoop v up saidWell saidRedis pinged newBlock =+    healthCheckLoop v up misses saidWell saidRedis pinged newBlock =       bracket (subscribe config.store.pub (heard newBlock)) (unsubscribe config.store.pub) $ \_ ->         loopForever $ do           threadDelay 100000@@ -974,7 +999,7 @@           tellHealth saidWell h           -- a store whose checks fail stops taking its turns as a member           -- of its fleet, so that it does not hold the others back-          forM_ config.store.fleet $ \member -> atomically (writeTVar member.healthy (isOK h.blocks && isOK h.peers))+          forM_ config.store.fleet $ \member -> atomically (setHealthy member (isOK h.blocks && isOK h.peers))           -- Redis is asked less often, every five seconds: it is the one           -- part of the check that leaves the program, and waits up to           -- two seconds for a Redis that is away. Requests find out by@@ -985,7 +1010,7 @@           when (now - last' >= 5) $ do             writeIORef pinged now             problem <- redisCheck-            atomically (writeTVar up (isNothing problem))+            atomically (writeTVar misses 0 >> writeTVar up (isNothing problem))             tellRedis saidRedis problem     heard newBlock = \case       StoreBestBlock _ -> writeTVar newBlock True@@ -1389,6 +1414,10 @@     plainList limits (\r -> GetAddrTxs <$> cap r <*> lim r) (handleAddrTxs st),     marshalled [] (\r -> GetAddrBalance <$> cap r) (handleAddrBalance st),     marshalledList limits (\r -> GetAddrUnspent <$> cap r <*> lim r) (handleAddrUnspent st),+    marshalledList [] (\r -> GetAddrTokens <$> cap r) (handleAddrTokens st),+    marshalledList ["limit", "offset"] (\r -> GetTokenHolders <$> cap r <*> opt r <*> off r) (handleTokenHolders st),+    marshalledList limits (\r -> GetTokenUnspent <$> cap r <*> lim r) (handleTokenUnspent st),+    plainList limits (\r -> GetTokenTxs <$> cap r <*> lim r) (handleTokenTxs st),     lightly (plainList [] (\_ -> return GetPeers) (handlePeers st)),     lightly (pathHealth st),     plainList ["limit", "offset"] (\r -> GetMempool <$> opt r <*> off r) (handleMempool st),@@ -2010,7 +2039,7 @@ -- transaction that the node has already was sent. sendNode :: WebState -> String -> Tx -> IO Publish.Direct sendNode st url tx =-  tryAny (Wreq.Session.postWith opts st.session url body) >>= \case+  tryAny (Wreq.Session.postWith nodeOptions st.nodeSession url body) >>= \case     Left e -> unheard (cs (show e))     Right r -> case A.decode (r ^. Wreq.responseBody) >>= answer of       Nothing -> unheard ("HTTP " <> cs (show (r ^. Wreq.responseStatus . Wreq.statusCode)))@@ -2019,7 +2048,6 @@         | "already" `T.isInfixOf` why -> return Publish.Sent         | otherwise -> return (Publish.Declined why)   where-    opts = Wreq.defaults & Wreq.checkResponse ?~ (\_ _ -> return ())     body =       A.object         [ "jsonrpc" .= ("1.0" :: Text),@@ -2041,6 +2069,35 @@         ("The node did not take a transaction over RPC, which goes to a peer if it is verified: " <> why)       return Publish.Unavailable +-- | Run a loop of the web server for as long as the server runs: an+-- exception that it throws is logged as an error, and the loop starts again+-- a second later. A loop that ends by itself, as one with nothing to do,+-- stays ended.+supervised :: Logger -> Text -> IO a -> IO b+supervised logger name loop =+  tryAny loop >>= \case+    Right _ -> forever (threadDelay maxBound)+    Left e -> do+      logError (withSource name logger) ("The loop stopped, and starts again: " <> cs (show e))+      threadDelay 1000000+      supervised logger name loop++-- | Note whether a request found Redis quick enough to say the fleet tip,+-- in the count of requests in a row that did not and the flag that says+-- that Redis answers ('cacheUp'). A request that found it quick sets the+-- flag and clears the count; it takes three in a row that did not to+-- clear the flag. One slow answer, such as one behind a long script of+-- another store, once cleared the flag of every store at once, and the+-- fleet answered 503 until their next checks, up to five seconds later.+-- The health check sets the flag too, and clears the count.+reach :: TVar Int -> TVar Bool -> Bool -> STM ()+reach misses up quick+  | quick = writeTVar misses 0 >> writeTVar up True+  | otherwise = do+      n <- (+ 1) <$> readTVar misses+      writeTVar misses n+      when (n >= 3) (writeTVar up False)+ -- | What "Haskoin.Store.Web.Publish" needs, for a request. -- -- The peers are those of the store that take transactions. A transaction@@ -2091,86 +2148,7 @@       (chainRead own.db).getTxData h >>= \case         Just _ -> return True         Nothing -> maybe (return False) (\m -> isJust <$> memberPoolBody m h) own.fleet-    ask h = getPeers own.peerMgr >>= mapM_ (\op -> blockStoreTxHash op.mailbox [h] own.block)---- | Fill the pool again each time the member finds it emptied, because--- Redis lost its data ('Haskoin.Store.Fleet.Member.noteEpoch') or the pool--- started again ('Haskoin.Store.Fleet.Member.noteRestarts'): ask the peers--- for their mempools, once ('blockStoreRefill'), and with the RPC of the--- store's node (@--node-rpc@), read the node's whole mempool,--- 'refillBatch' transactions every two seconds, a turn of the member, each--- given to the member as if a peer had sent it ('memberReceived'). The--- peers alone may not answer: Bitcoin Core answers only a peer that it--- whitelists or when it serves bloom filters, which it does not by--- default. The RPC answers in any case, and its transactions are offered--- whether the fleet has seen them or not.-refillLoop :: WebState -> IO ()-refillLoop st = forM_ own.fleet $ \m -> go m 0-  where-    own = st.config.store-    say = withSource "Fleet" st.config.logger-    go m seen = do-      n <- atomically $ do-        n <- readTVar m.refills-        when (n == seen) retry-        return n-      blockStoreRefill own.block-      forM_ st.config.nodeRpc $ \url ->-        tryAny (refillFromNode st m url) >>= \case-          Left e -> logWarn say ("Could not read the mempool of the node over RPC: " <> cs (show e))-          Right k -> logInfo say ("Gave the pool " <> cs (show k) <> " transactions of the node's mempool")-      go m n---- | How many transactions 'refillLoop' reads from the node at a time.-refillBatch :: Int-refillBatch = 2000---- | Give a member every transaction of the mempool of a node, read over its--- RPC (@getrawmempool@, then @getrawtransaction@ in batches of--- 'refillBatch'). Says how many it gave.-refillFromNode :: WebState -> Member -> String -> IO Int-refillFromNode st m url = do-  ids <--    nodeCalls st url [("getrawmempool", [])] <&> \case-      [Just (A.Array a)] -> [h | A.String h <- Foldable.toList a]-      _ -> []-  fmap sum . forM (batches ids) $ \hs -> do-    now <- fromIntegral . (floor :: POSIXTime -> Integer) <$> getPOSIXTime-    found <- nodeCalls st url [("getrawtransaction", [A.String h]) | h <- hs]-    let txs = [tx | Just (A.String hex) <- found, Just bytes <- [decodeHex hex], Right tx <- [decode bytes]]-    mapM_ (memberReceived m now) txs-    threadDelay 2000000-    return (length txs)-  where-    batches xs-      | null xs = []-      | otherwise = take refillBatch xs : batches (drop refillBatch xs)---- | The results of calls to the JSON-RPC of a node, made in one batch, in--- their order: 'Nothing' for one that failed.-nodeCalls :: WebState -> String -> [(Text, [A.Value])] -> IO [Maybe A.Value]-nodeCalls st url calls = do-  r <- Wreq.Session.postWith opts st.session url (A.toJSON (zipWith call [0 :: Int ..] calls))-  let answers = case A.decode (r ^. Wreq.responseBody) of-        Just (A.Array a) ->-          HashMap.fromList-            [ (i, v)-            | A.Object o <- Foldable.toList a,-              Just (A.String i) <- [KeyMap.lookup "id" o],-              Just v <- [KeyMap.lookup "result" o],-              v /= A.Null-            ]-        _ -> HashMap.empty-  return [HashMap.lookup (T.pack (show i)) answers | i <- [0 .. length calls - 1]]-  where-    opts = Wreq.defaults & Wreq.checkResponse ?~ (\_ _ -> return ())-    call i (method, params) =-      A.object-        [ "jsonrpc" .= ("1.0" :: Text),-          "id" .= T.pack (show i),-          "method" .= method,-          "params" .= params-        ]+    ask h = getPeers own.peerMgr >>= mapM_ (\op -> atomically (ingestNamedSTM op.mailbox [h] own.ingest))  -- GET Mempool / Events -- @@ -2510,6 +2488,36 @@   withMetrics st (.addressUnspent) $     st.query.getAddressesUnspents addrs =<< paramToLimits st False pLimits +-- GET Tokens --++-- | Handler for @GET \/address\/:address\/tokens@: the token balances of an+-- address, one per category (CashTokens). Empty on Bitcoin.+handleAddrTokens :: WebState -> GetAddrTokens -> IO [TokenBalance]+handleAddrTokens st (GetAddrTokens addr) =+  withMetrics st (.addressBalance) $ st.query.getAddressTokens addr++-- | Handler for @GET \/token\/:category\/holders@: the token balances of a+-- category, one per address, in the order of the addresses' bytes.+handleTokenHolders :: WebState -> GetTokenHolders -> IO [TokenBalance]+handleTokenHolders st (GetTokenHolders category limit offset) =+  withMetrics st (.addressBalance) $ do+    limits <- paramToLimits st False (LimitsParam limit offset Nothing)+    st.query.getTokenHolders category limits++-- | Handler for @GET \/token\/:category\/unspent@: unspent outputs that+-- hold tokens of a category, newest first.+handleTokenUnspent :: WebState -> GetTokenUnspent -> IO [Unspent]+handleTokenUnspent st (GetTokenUnspent category pLimits) =+  withMetrics st (.addressUnspent) $+    st.query.getTokenUnspents category =<< paramToLimits st False pLimits++-- | Handler for @GET \/token\/:category\/transactions@: transactions that+-- moved tokens of a category, newest first.+handleTokenTxs :: WebState -> GetTokenTxs -> IO [TxRef]+handleTokenTxs st (GetTokenTxs category pLimits) =+  withMetrics st (.addressTx) $+    st.query.getTokenTxs category =<< paramToLimits st False pLimits+ -- GET XPubs --  -- | Handler for @GET \/xpub\/:xpub@: summary of an extended public key.@@ -3458,8 +3466,9 @@             if               | cashaddr -> net               | net == bch -> btc-              | net == bchTest -> btcTest-              | net == bchTest4 -> btcTest+              -- both test networks of Bitcoin Cash; the legacy prefixes+              -- of every Bitcoin test network are the same+              | net.cashAddrPrefix == Just "bchtest" -> btcTest4               | otherwise -> net        in case addrToText net' a of             Nothing -> return Nothing@@ -3875,49 +3884,15 @@ pathHealth st =   route (renderStdMethod (resourceMethod proxy)) (capturePath proxy) [] $ \_ -> do     h <- handleHealth st GetHealth-    stall <- readTVarIO st.config.store.writes-    let stopped = stall.writes == Stopped-        (status, extra)-          | not (isOK h) || stopped = (status503, [("Retry-After", "5")])+    let (status, extra)+          | not (isOK h) = (status503, [("Retry-After", "5")])           | h.redis == Just False = (status503, [("Retry-After", "5"), ("Haskoin-Degraded", "redis")])           | otherwise = (status200, [])     return $-      responseLBS status ((hContentType, "application/json") : extra) (A.encode (withDatabase stall h))+      responseLBS status ((hContentType, "application/json") : extra) (A.encode h)   where     proxy = Proxy :: Proxy GetHealth --- | The JSON of a health check with the state of RocksDB's writes added--- ("Haskoin.Store.Database.Stalls"), under @\"database\"@:------ > "database": {"ok": true, "writes": "delayed",--- >              "pending-compaction-bytes": 70000000000, "delayed-write-rate": 16777216}------ Writes that RocksDB stopped make the store unhealthy: it imports nothing--- until they flow again. Delayed writes do not. RocksDB slows writes for--- seconds at a time while a store syncs, and a store that serves requests--- answers them at full speed meanwhile; if the delay makes it fall behind,--- the check of the blocks says so.------ The field is added here and not to 'HealthCheck', which is in--- haskoin-store-data: clients that read it ignore the field, and see--- @\"ok\": false@ when writes stop.-withDatabase :: Stall -> HealthCheck -> A.Value-withDatabase stall h = case toJSON h of-  A.Object o ->-    A.Object $-      KeyMap.insert "ok" (A.Bool (isOK h && not stopped)) $-        KeyMap.insert "database" database o-  v -> v-  where-    stopped = stall.writes == Stopped-    database =-      A.object-        [ "ok" .= not stopped,-          "writes" .= T.toLower (T.pack (show stall.writes)),-          "pending-compaction-bytes" .= stall.pending,-          "delayed-write-rate" .= stall.rate-        ]- -- | Handler for @GET \/health@: health of the store. handleHealth ::   WebState ->@@ -3927,9 +3902,26 @@   withMetrics st (.health) $ do     h <- readTVarIO st.health     up <- readTVarIO st.cacheUp-    -- Redis is mandatory: the answer always says whether it answers-    let HealthCheck {blocks, lastBlock, lastTx, pendingTxs, peers, network, version, time} = h-    return HealthCheck {redis = Just up, ..}+    database <- readTVarIO st.config.store.writes+    path <- atomically (ingestState st.config.store.ingest)+    -- Redis is mandatory: the answer always says whether it answers. The+    -- database is read every five seconds by a thread of its own+    -- ("Haskoin.Store.Database.Stalls"), and is the last state it read.+    -- How the store stands with the mempool of its nodes is what the path+    -- into the pool last said ("Haskoin.Store.Ingest.Run").+    let HealthCheck {blocks, lastBlock, lastTx, pendingTxs, peers, network, version, time, warnings} = h+        mempool =+          MempoolHealth+            { sources = fromIntegral path.sources,+              dirty = path.dirty,+              known = fromIntegral path.known,+              held = fromIntegral path.held,+              sync = case path.standing of+                PoolUnknown -> MempoolUnknown+                PoolSyncing -> MempoolSyncing+                PoolSynced -> MempoolSynced+            }+    return HealthCheck {redis = Just up, database = Just database, mempool = Just mempool, ..}  -- | Heights of the best header and best block, and the maximum lag allowed. blockHealthCheck :: WebConfig -> IO BlockHealth@@ -3979,7 +3971,7 @@ -- | Transactions requested from peers and not received yet, and the maximum allowed. pendingTxsHealthCheck :: WebConfig -> IO MaxHealth pendingTxsHealthCheck cfg = do-  n <- blockStorePendingTxs cfg.store.block+  n <- (.pending) <$> atomically (ingestState cfg.store.ingest)   return     MaxHealth       { max = fromIntegral cfg.maxPendingTxs,@@ -4006,8 +3998,13 @@       { network = cfg.store.net.name,         version = cfg.version,         -- filled in when the check is served, from what the last request-        -- or ping found+        -- or ping found, and from the last poll of the database         redis = Nothing,+        database = Nothing,+        mempool = Nothing,+        -- what the operator should put right, which decides nothing: a+        -- node is expected with its RPC and its ZeroMQ socket both+        warnings = [lacksZmq | isJust cfg.nodeRpc, isNothing cfg.nodeZmq],         ..       } @@ -4368,8 +4365,6 @@   T.intercalate ", " . concat $     [ [shown (h.blocks.headers - h.blocks.blocks) <> " blocks behind the headers" | not (isOK h.blocks)],       [shown h.lastBlock.age <> " seconds since the last block" | not (isOK h.lastBlock)],-      [shown h.lastTx.age <> " seconds since the last transaction" | not (isOK h.lastTx)],-      [shown h.pendingTxs.count <> " transactions requested from peers and not received" | not (isOK h.pendingTxs)],       [shown h.peers.count <> " peers" | not (isOK h.peers)]     ]   where
src/Haskoin/Store/Web/Publish.hs view
@@ -99,8 +99,13 @@     askLoop,     askAgain,     due,+    asked,      -- * What the store can check++    -- | The checks themselves are in haskoin-core+    -- ("Haskoin.Transaction.Judge"), which other programs use too: they+    -- say nothing of a store. They are exported from here as they were.     Coin (..),     Refusal (..),     Rules (..),@@ -115,9 +120,8 @@  import Control.Concurrent (threadDelay) import Control.Concurrent.Async (mapConcurrently, race, waitCatch, withAsync)-import Control.Concurrent.STM (TVar, atomically, modifyTVar', newTVarIO, readTVarIO, stateTVar, writeTVar)+import Control.Concurrent.STM (TVar, atomically, modifyTVar', newTVarIO, readTVarIO, writeTVar) import Control.Monad (forM_, forever, unless, when)-import Data.Bits (shiftL, (.&.), (.|.)) import Data.ByteString (ByteString) import Data.ByteString qualified as B import Data.HashMap.Strict (HashMap)@@ -137,6 +141,7 @@     InputVerdict (..),     Message (..),     MessageCommand (..),+    NFToken (..),     Network (..),     NetworkAddress (..),     OutPoint (..),@@ -144,16 +149,18 @@     Pong (..),     Reject (..),     Script (..),+    TokenData (..),     Tx (..),     TxHash,     TxIn (..),     TxOut (..),     VarString (..),+    genesisNode,     isMinimalPush,     isPushOp,     nullOutPoint,     sockToHostAddress,-    splitTokenPrefix,+    splitTokenData,     txHash,     txHashToHex,   )@@ -164,14 +171,26 @@     PeerEvent (..),     WithConnection,     buildVersion,+    expectsReject,+    newPeer,     peer,     peerMessageDone,     sendMessage,-    wrapPeer,   )-import Haskoin.Node.Peer.Lock (Lock (..))+import Haskoin.Node.Address (peerHostAddress, seenAs)+import Haskoin.Node.Peer.Remote (newRemote) import Haskoin.Store.Common (StoreRead (..)) import Haskoin.Store.Data (BlockRef (..), Spender (..), TxData (..), isCoinbaseTx)+import Haskoin.Transaction.Judge+  ( Coin (..),+    Refusal (..),+    Rules (..),+    isDust,+    judge,+    maxStandardSize,+    maxTxSize,+    tokenRules,+  ) import NQE (newMailbox, receive, withPublisher, withSubscription) import Network.Socket (SockAddr (..)) import System.Random (randomIO)@@ -218,239 +237,6 @@     NoPeers   deriving (Eq, Show) --- | An output that a transaction spends, as the store knows it.-data Coin-  = -- | it is there to spend, or only an unconfirmed transaction spends-    -- it-    Coin-      { -- | the output, as it is in the transaction that made it-        output :: !TxOut,-        -- | the height of the block that confirmed it, if one did-        mined :: !(Maybe BlockHeight),-        -- | whether a coinbase made it-        coinbase :: !Bool-      }-  | -- | a confirmed transaction has spent it-    Spent !TxHash-  | -- | the store does not know it-    Missing-  deriving (Eq, Show)---- | Why the store refuses a transaction without sending it.-data Refusal-  = TooLarge !Int-  | NoInputs-  | NoOutputs-  | IsCoinbase-  | DuplicateInput !OutPoint-  | UnknownOutput !OutPoint-  | SpentOutput !OutPoint !TxHash-  | Overspent-  | Immature !OutPoint-  | NotFinal !Word32-  | TooHeavy !Int-  | Dust !Int-  | Forged !Int-  | BadVersion !Word32-  | NotPushOnly !Int-  | NotMinimal !Int-  | BadTokens !Int-  | TokensUnbacked !String-  deriving (Eq)--instance Show Refusal where-  show (TooLarge n) = "The transaction is too large: " <> show n <> " bytes"-  show NoInputs = "The transaction has no inputs"-  show NoOutputs = "The transaction has no outputs"-  show IsCoinbase = "A coinbase transaction cannot be published"-  show (DuplicateInput o) = "The transaction spends the same output twice: " <> showOutPoint o-  show (UnknownOutput o) = "The transaction spends an output that this server does not know: " <> showOutPoint o-  show (SpentOutput o by) =-    "The transaction spends an output that a confirmed transaction has spent: "-      <> showOutPoint o-      <> " by "-      <> cs (txHashToHex by)-  show Overspent = "The outputs of the transaction are worth more than its inputs"-  show (Immature o) = "The transaction spends a coinbase that is not a hundred blocks old: " <> showOutPoint o-  show (NotFinal lock) = "The lock time of the transaction has not passed: " <> show lock-  show (TooHeavy n) = "The transaction is larger than nodes relay: " <> show n-  show (Dust i) = "Output " <> show i <> " is worth less than it costs to spend, and nodes do not relay it"-  show (Forged i) = "The signature of input " <> show i <> " does not verify"-  show (BadVersion v) = "Nodes do not take a transaction of version " <> show v-  show (NotPushOnly i) = "The script of input " <> show i <> " does more than push data"-  show (NotMinimal i) = "The script of input " <> show i <> " pushes data in a longer form than it needs"-  show (BadTokens i) = "The tokens of output " <> show i <> " are not written as tokens are"-  show (TokensUnbacked c) = "The transaction gives tokens of category " <> c <> " that its inputs do not hold"--showOutPoint :: OutPoint -> String-showOutPoint o = cs (txHashToHex o.hash) <> ":" <> show o.index---- | The largest transaction that a block of the network can hold, in--- bytes. With SegWit a block weighs four million units at most, and a byte--- of witness weighs one, so a transaction that is nearly all witness comes--- close to four million bytes. Without it, the rule of Bitcoin Cash is a--- million bytes for a transaction.------ Nodes relay far smaller ones only, a hundred thousand bytes or so. The--- store does not hold their rule, which is theirs to change: this is the--- size past which no node can take the transaction.-maxTxSize :: Network -> Int-maxTxSize net-  | net.segWit = 4000000-  | otherwise = 1000000---- | What the store knows of the chain and the network when it looks at a--- transaction.-data Rules = Rules-  { net :: !Network,-    -- | what can be said of the signature of each input, given the-    -- outputs they spend: 'judgeInputs' of haskoin-core-    inputs :: !(Tx -> [TxOut] -> [InputVerdict]),-    -- | height of the best block-    height :: !BlockHeight,-    -- | median of the times of the last eleven blocks, which is the time-    -- that lock times are held to (BIP 113)-    medianTime :: !Word64-  }---- | What the store can say of a transaction from its own index, given the--- coin of each input in order ('coinOf').------ Every check here is one whose answer a node would give too, and that--- does not depend on what else is in a mempool:------ * __What makes it no transaction__: no inputs or outputs, an input---   twice, a coinbase, longer than a block can hold ('maxTxSize').--- * __The coins__: each input spends an output that the store knows, that---   no confirmed transaction has spent, and a coinbase only after a---   hundred blocks. The outputs are not worth more than the inputs.--- * __The lock time__ has passed, by height or by the median time, unless---   every input waives it.--- * __What nodes do not relay__: more than 'maxStandardSize', and an---   output so small that spending it costs more than it holds ('isDust').---   These are rules of relay and not of the chain; they are the ones that---   have not changed in years.--- * __Input scripts__ only push data, each push in its shortest form. On---   Bitcoin Cash that is a rule of the chain, and a node drops every---   connection of a peer that sends a transaction that breaks it.--- * __The version__: 1 or 2 on Bitcoin Cash, a rule of the chain there; 1---   to 3 on Bitcoin, which nodes relay.--- * __Tokens__ of Bitcoin Cash ('tokenRules'): written as tokens are, and---   given only as the inputs hold them. A node drops every connection of a---   peer that sends a transaction that breaks them.--- * __Signatures__, where there is no script to run: an input that spends---   a coin locked to one key with a signature that does not verify---   ('judgeInputs' of haskoin-core). An input that is a script, or that---   the store cannot read, is left to the node.------ A conflict with an unconfirmed transaction is not a reason to refuse:--- whether one may replace the other is for the node to say, and the--- mempool of the store may hold what the network has dropped. The fee is--- not checked either: what a node asks for changes with its mempool.------ The answer for a transaction that passes says whether every signature--- was verified, or names the first input that the store could not judge:--- a script, a hash type other than all. Such a transaction may be good,--- and only a full node can say. See 'publish' for what becomes of it.-judge :: Rules -> Tx -> [Coin] -> Either Refusal (Maybe Int)-judge rules tx coins = do-  when (size > maxTxSize rules.net) $ Left (TooLarge size)-  when (null tx.inputs) $ Left NoInputs-  when (null tx.outputs) $ Left NoOutputs-  when (any ((== nullOutPoint) . (.outpoint)) tx.inputs) $ Left IsCoinbase-  mapM_ (Left . DuplicateInput) (firstDuplicate (map (.outpoint) tx.inputs))-  unless (tx.version `elem` versions) $ Left (BadVersion tx.version)-  mapM_ pushes (zip [0 ..] tx.inputs)-  spent <- mapM known (zip (map (.outpoint) tx.inputs) coins)-  when cash $ tokenRules tx spent-  -- sums of 64-bit values: compared as integers, which do not wrap-  unless (sum (map (toInteger . (.value)) spent) >= sum (map (toInteger . (.value)) tx.outputs)) $ Left Overspent-  mapM_ mature (zip (map (.outpoint) tx.inputs) coins)-  unless final $ Left (NotFinal tx.locktime)-  when (heavy > maxStandardSize rules.net) $ Left (TooHeavy heavy)-  mapM_ (Left . Dust) (take 1 [i | (i, o) <- zip [0 ..] tx.outputs, isDust rules.net o])-  let verdicts = zip [0 ..] (rules.inputs tx spent)-  mapM_ (Left . Forged) (take 1 [i | (i, InputForged) <- verdicts])-  return (listToMaybe [i | (i, InputUndecided) <- verdicts])-  where-    cash = isJust rules.net.sigHashForkId-    -- Bitcoin Cash takes versions 1 and 2 only, by its rules since May-    -- 2023; Bitcoin Core relays those and version 3-    versions-      | cash = [1, 2]-      | otherwise = [1, 2, 3]-    -- an input script that only pushes data, each push in its shortest-    -- form: rules of Bitcoin Cash, relay rules of Bitcoin Core-    pushes (i, input) = case decode input.script of-      Right (Script ops)-        | not (all isPushOp ops) -> Left (NotPushOnly i)-        | not (all isMinimalPush ops) -> Left (NotMinimal i)-        | otherwise -> Right ()-      Left _ -> Left (NotPushOnly i)-    size = B.length (encode tx)-    -- what the limit of relay counts: weight with SegWit, bytes without-    heavy-      | rules.net.segWit = 3 * B.length (encode (tx {witness = []} :: Tx)) + size-      | otherwise = size-    known (_, Coin {output}) = Right output-    known (o, Spent by) = Left (SpentOutput o by)-    known (o, Missing) = Left (UnknownOutput o)-    -- a coinbase can be spent in the hundredth block after its own-    mature (o, Coin {coinbase = True, mined = Just h})-      | rules.height + 1 < h + 100 = Left (Immature o)-    mature _ = Right ()-    -- IsFinalTx of Bitcoin Core, for the block after the best one-    final-      | tx.locktime == 0 = True-      | tx.locktime < 500000000 = tx.locktime < rules.height + 1 || waived-      | otherwise = fromIntegral tx.locktime < rules.medianTime || waived-    waived = all ((== maxBound) . (.sequence)) tx.inputs-    firstDuplicate = go HashMap.empty-      where-        go _ [] = Nothing-        go seen (o : os)-          | HashMap.member o seen = Just o-          | otherwise = go (HashMap.insert o () seen) os---- | The most that nodes relay: 400,000 units of weight with SegWit, which--- is 100,000 bytes of a transaction without witness, and 100,000 bytes on--- Bitcoin Cash.-maxStandardSize :: Network -> Int-maxStandardSize net-  | net.segWit = 400000-  | otherwise = 100000---- | Whether an output is dust: worth less than three times what it costs,--- at the lowest fee nodes relay, to make it and to spend it. Nodes do not--- relay a transaction with one. This is @IsDust@ of Bitcoin Core at its--- default of 3,000 satoshi a kilobyte, and of Bitcoin Cash Node: 546--- satoshi for an output to a key hash, 294 to a witness key hash.------ An output that cannot be spent, which starts with @OP_RETURN@, holds--- data and may hold no value.-isDust :: Network -> TxOut -> Bool-isDust net o-  | unspendable = False-  | otherwise = toInteger o.value < 3 * toInteger (made + spent)-  where-    s = o.script-    unspendable = (not (B.null s) && B.head s == 0x6a) || B.length s > 10000-    made = 8 + lengthOfLength + B.length s-    lengthOfLength-      | B.length s < 0xfd = 1-      | B.length s <= 0xffff = 3-      | otherwise = 5-    -- what an input that spends it adds: less when its signature is in-    -- the witness-    spent-      | net.segWit && witnessProgram = 67-      | otherwise = 148-    witnessProgram =-      B.length s >= 4-        && B.length s <= 42-        && (B.head s == 0 || (B.head s >= 0x51 && B.head s <= 0x60))-        && fromIntegral (B.index s 1) == B.length s - 2- -- | The coin of an output, from the queries of a request. coinOf :: StoreRead -> OutPoint -> IO Coin coinOf q o =@@ -518,7 +304,7 @@               Nothing -> do                 addresses <- p.peers                 delivered <- mapConcurrently (\a -> p.courier a tx) addresses-                let handed = length [() | d <- delivered, d `elem` [Took, NoAnswer]]+                let handed = length [() | d <- delivered, d `elem` [Took, Kept, NoAnswer]]                     reasons = [why | Rejected why <- delivered]                 if                   | handed > 0 -> do@@ -584,17 +370,37 @@           d : rest -> Just (addUTCTime d now, rest)           [] -> Nothing +-- | The schedule after a transaction whose time had come was asked for:+-- at its next delay, or no more after its last ('due').+asked ::+  UTCTime ->+  TxHash ->+  HashMap TxHash (UTCTime, [NominalDiffTime]) ->+  HashMap TxHash (UTCTime, [NominalDiffTime])+asked now h = HashMap.update next h+  where+    next (t, ds)+      | t > now = Just (t, ds)+      | otherwise = case ds of+          d : rest -> Just (addUTCTime d now, rest)+          [] -> Nothing+ -- | Every second, ask for each transaction whose time has come, unless the -- store has it now. Runs until it is cancelled.+--+-- The schedule of a transaction moves on only once it was asked for, one+-- at a time ('asked'). Moved on for all of them first, as it once was, an+-- error in the middle lost the turn of the others, and a transaction at its+-- last delay was never asked for at all. askLoop :: Asking -> (TxHash -> IO Bool) -> (TxHash -> IO ()) -> IO () askLoop (Asking var) present ask = forever $ do   threadDelay 1000000   now <- getCurrentTime-  ready <- atomically (stateTVar var (due now))+  ready <- fst . due now <$> readTVarIO var   forM_ ready $ \h ->     present h >>= \case       True -> atomically (modifyTVar' var (HashMap.delete h))-      False -> ask h+      False -> ask h >> atomically (modifyTVar' var (asked now h))  -- | When to ask for a transaction that was handed over: soon, for Bitcoin -- Cash Node, and then every 25 seconds for two minutes and a half. The@@ -603,105 +409,15 @@ askAgain :: [NominalDiffTime] askAgain = [2, 25, 25, 25, 25, 25, 25] --- | The tokens that an output holds: their category, a non-fungible token--- with its capability and commitment, and an amount of fungible ones.-data Tokens = Tokens-  { category :: !ByteString,-    nft :: !(Maybe (Word8, ByteString)),-    amount :: !Word64-  }---- | The tokens at the front of the script of an output, if it has any, or--- 'Left' if they are not written as tokens are ('splitTokenPrefix').-readTokens :: ByteString -> Either () (Maybe Tokens)-readTokens script = case splitTokenPrefix script of-  Nothing -> Left ()-  Just (prefix, _)-    | B.null prefix -> Right Nothing-    | otherwise -> Right (Just (parse prefix))-  where-    -- the prefix is well formed: 'splitTokenPrefix' said so-    parse prefix =-      let flags = B.index prefix 33-          rest0 = B.drop 34 prefix-          (commitment, rest1)-            | flags .&. 0x40 /= 0 = let (n, r) = compact rest0 in B.splitAt (fromIntegral n) r-            | otherwise = (B.empty, rest0)-          held-            | flags .&. 0x10 /= 0 = fst (compact rest1)-            | otherwise = 0-       in Tokens-            { category = B.take 32 (B.drop 1 prefix),-              nft = if flags .&. 0x20 /= 0 then Just (flags .&. 0x0f, commitment) else Nothing,-              amount = held-            }-    compact :: ByteString -> (Word64, ByteString)-    compact b = case B.uncons b of-      Just (w, r)-        | w < 0xfd -> (fromIntegral w, r)-        | w == 0xfd -> sized 2 r-        | w == 0xfe -> sized 4 r-        | otherwise -> sized 8 r-      Nothing -> (0, B.empty)-    sized :: Int -> ByteString -> (Word64, ByteString)-    sized k r = (B.foldr (\w acc -> acc `shiftL` 8 .|. fromIntegral w) 0 (B.take k r), B.drop k r)---- | The rules of the tokens of Bitcoin Cash (CashTokens, since May 2023),--- given the outputs that the inputs spend, in order. A node drops every--- connection of a peer that sends it a transaction that breaks them, so--- the store checks them before it sends anything.------ * The tokens of every output are written as tokens are.--- * A category is new when it is the id of a transaction whose first---   output an input spends: its tokens may be made at will.--- * Of any other category, the outputs hold no more fungible tokens than---   the inputs, and no more than the largest amount, in all.--- * And its non-fungible tokens come from the inputs: any, when an input---   holds one that can mint; else each output's equals one of an input---   that cannot be changed, or takes the place of one that can be changed,---   and none can mint.-tokenRules :: Tx -> [TxOut] -> Either Refusal ()-tokenRules tx spent = do-  outs <- mapM readOut (zip [0 ..] tx.outputs)-  let ins = [t | Right (Just t) <- map (readTokens . (.script)) spent]-      made = [t | Just t <- outs]-      new = [encode i.outpoint.hash | i <- tx.inputs, i.outpoint.index == 0]-      categories = HashMap.keys (HashMap.fromList [(t.category, ()) | t <- made])-  forM_ categories $ \c -> do-    let given = [t | t <- made, t.category == c]-        held = [t | t <- ins, t.category == c]-        total = sum (map (toInteger . (.amount)) given)-    when (total > 0x7fffffffffffffff) $ Left (TokensUnbacked (named c))-    unless (c `elem` new) $ do-      when (total > sum (map (toInteger . (.amount)) held)) $ Left (TokensUnbacked (named c))-      unless (nftsBacked [n | Just n <- map (.nft) given] [n | Just n <- map (.nft) held]) $-        Left (TokensUnbacked (named c))-  where-    readOut (i, o) = either (const (Left (BadTokens i))) Right (readTokens o.script)-    -- the id of a category as people write it: the bytes reversed-    named = concatMap hex . B.unpack . B.reverse-    hex w = [digits !! fromIntegral (w `div` 16), digits !! fromIntegral (w `mod` 16)]-    digits = "0123456789abcdef"-    -- capabilities: 0 none, 1 mutable, 2 minting-    nftsBacked given held-      | any ((== 2) . fst) held = True-      | any ((== 2) . fst) given = False-      | otherwise =-          let (fixed, changing) = partition ((== 0) . fst) given-              left = foldl matched ([n | n <- held, fst n == 0], []) fixed-              mutable = length (filter ((== 1) . fst) held)-           in length (snd left) + length changing <= mutable-    -- an immutable token given takes an equal one held, or waits for a-    -- mutable one-    matched (pool, unmatched) n = case break (== n) pool of-      (before, _ : after) -> (before <> after, unmatched)-      _ -> (pool, n : unmatched)- -- | What a node did with a transaction handed to it. data Delivery   = -- | it answered the ping that followed: it is done with the-    -- transaction, and said nothing against it+    -- transaction, and said nothing against it, as Bitcoin Core never does     Took+  | -- | it answered the ping that followed without a @reject@, and it is a+    -- node that answers a transaction it refuses with one, as Bitcoin Cash+    -- Node does: it did not refuse it+    Kept   | -- | it sent a @reject@ message for the transaction, with this reason     Rejected !Text   | -- | it closed the connection after getting the transaction and@@ -727,32 +443,43 @@ -- node answers until its @pong@. -- -- The connection is a peer of "Haskoin.Node.Peer" with a publisher of its--- own, so nothing of it reaches the peer manager or the block store.+-- own, so nothing of it reaches the peer manager or the block store. It has+-- a model of the node, as every peer does ("Haskoin.Node.Peer.Remote"),+-- which judges each message before it goes. The model also says whether the+-- node answers a refusal with a @reject@ ('expectsReject'): if it does, a+-- @pong@ with no @reject@ before it means that the node kept the+-- transaction ('Kept'); if it never does, only that the node is done with+-- it ('Took'). deliver :: Courier -> SockAddr -> Tx -> IO Delivery deliver c sa tx =   withPublisher $ \pub -> withSubscription pub $ \sub -> do     (inbox, mailbox) <- newMailbox-    busy <- newTVarIO Free-    pending <- newTVarIO 0     sent <- newTVarIO False     refused <- newTVarIO Nothing     nonce <- randomIO     token <- randomIO+    seed <- randomIO     now <- getCurrentTime-    let config =+    let (addrNet, local) = seenAs sa+        opened = floor (utcTimeToPOSIXSeconds now * 1000000)+        config =           PeerConfig             { pub = pub,               net = c.net,               label = "courier " <> cs (show sa),               connect = c.connect sa,               logger = c.logger,-              lookupBlock = const (return Nothing)+              lookupBlock = const (return Nothing),+              bestBlock = return (genesisNode c.net),+              remote = newRemote c.net mempty addrNet local opened seed             }-        node = wrapPeer config busy pending mailbox         nowhere = NetworkAddress 0 (sockToHostAddress (SockAddrInet 0 0))-        there = NetworkAddress 0 (sockToHostAddress sa)+        -- the zero address for a peer on a Unix socket, which has none+        there = NetworkAddress 0 (peerHostAddress sa)         version = buildVersion c.net nonce 0 nowhere there (floor (utcTimeToPOSIXSeconds now))-        next =+        took = if expectsReject c.net version then Kept else Took+    node <- newPeer config mailbox+    let next =           receive sub >>= \case             PeerMessage _ m -> peerMessageDone node >> return m             _ -> next@@ -786,7 +513,7 @@       why <- readTVarIO refused       return $ case (why, r) of         (Just reason, _) -> Rejected reason-        (Nothing, Just (Right ())) -> Took+        (Nothing, Just (Right ())) -> took         (Nothing, Just (Left ())) -> if was then Closed else NoConnection         (Nothing, Nothing) -> if was then NoAnswer else NoConnection 
src/Haskoin/Store/XPub/Indexer.hs view
@@ -131,7 +131,7 @@     retry,     writeTVar,   )-import Control.Exception (SomeException)+import Control.Exception (SomeException, mask) import Control.Monad (forM_, replicateM_, unless, void, when) import Data.HashMap.Strict (HashMap) import Data.HashMap.Strict qualified as HashMap@@ -145,7 +145,7 @@ import Foreign.C.Types (CInt (..), CUInt (..)) import GHC.Clock (getMonotonicTimeNSec) import Haskoin.Store.Common (loopForever)-import Haskoin.Store.Exception (catchAny, finally, tryAny)+import Haskoin.Store.Exception (catchAny, finally, onException, tryAny) import Haskoin.Store.XPub (Budget (..), noBudget) import Haskoin.Store.XPub.Lock (Lock (..), Taken (..)) @@ -343,8 +343,7 @@     RefuseNothing !Refusal !Int   deriving (Eq, Show) --- | The decision of @docs\/xpub-indexing.md@ (What a request for an xpub--- does):+-- | The decision of @docs\/xpub-indexing.md@ (The door): -- -- +------------------------+---------------------------+------------------------------------+ -- | Holder                 | Estimate                  | Decision                           |@@ -561,11 +560,20 @@  -- | Ask for a key, waiting so many microseconds at most. It counts nothing: -- 'request' and 'prefetch' count what they were told.+--+-- The reservation of a new job ('Pending') and the attempt to take its lock+-- run masked, and an exception that comes while the lock is being taken+-- undoes the reservation ('abandonReserved'): it answers the requests that+-- joined the job, and lets go of the lock if it was taken. Only waiting and+-- the call to Redis can be interrupted. A request killed between the two,+-- by its client going away or by a sibling of @mapConcurrently@ that+-- failed, once left the job 'Pending' for good, and every later request+-- for the key waited on it in vain. ask :: (Hashable k, Semigroup p) => Bool -> Indexer k p -> Int -> k -> p -> IO Answer ask decided i wait k p =   i.runner.ready >>= \case     False -> return (Refused NotInSync i.settings.horizon)-    True -> do+    True -> mask $ \restore -> do       now <- i.clock       step <- atomically $ do         q <- readTVar i.queue@@ -596,14 +604,14 @@                 return (Take d w est)       case step of         Done a -> return a-        Await key v -> await i key v+        Await key v -> restore (await i key v)         Take d w est ->-          acquireFor i k est >>= \case+          (restore (acquireFor i k est) `onException` abandonReserved i k) >>= \case             Just a -> do               forM_ w (unwait i . fst)               return a             Nothing -> case (d, w) of-              (Wait, Just (key, v)) -> await i key v+              (Wait, Just (key, v)) -> restore (await i key v)               (RefuseKeep e, _) -> return (Refused TooLong e)               _ -> return Failed   where@@ -660,22 +668,34 @@       let a = case decide (Situation 0 0 0 False (AnotherStore t)) of             RefuseNothing why e -> Refused why e             _ -> Refused OtherStore (max 0 t)-      gone <- atomically (unreserve a)+      gone <- atomically (unreserve i k a)       forM_ gone $ \j -> i.runner.blocked k j.payload t `catchAny` \_ -> return ()       return (Just a)     Left e -> do-      gone <- atomically (unreserve Failed)+      gone <- atomically (unreserve i k Failed)       forM_ gone $ \j -> i.runner.failed k j.payload e `catchAny` \_ -> return ()       return (Just Failed)-  where-    unreserve a = do-      q <- readTVar i.queue-      case HashMap.lookup k q.jobs of-        Just job@Job {stage = Pending} -> do-          writeTVar i.queue q {jobs = HashMap.delete k q.jobs}-          mapM_ (answer a) job.waiters-          return (Just job)-        _ -> return Nothing++-- | Drop the reservation of a key, if its job is still 'Pending', and+-- answer the requests that joined it.+unreserve :: (Hashable k) => Indexer k p -> k -> Answer -> STM (Maybe (Job p))+unreserve i k a = do+  q <- readTVar i.queue+  case HashMap.lookup k q.jobs of+    Just job@Job {stage = Pending} -> do+      writeTVar i.queue q {jobs = HashMap.delete k q.jobs}+      mapM_ (answer a) job.waiters+      return (Just job)+    _ -> return Nothing++-- | Undo the reservation of a key after an exception: drop the job if it is+-- still 'Pending', answering its requests 'Failed', and let go of the lock,+-- which the store may hold if the exception came after it was taken. A job+-- already queued is left: a worker runs it.+abandonReserved :: (Hashable k) => Indexer k p -> k -> IO ()+abandonReserved i k = do+  gone <- atomically (unreserve i k Failed)+  forM_ gone $ \_ -> i.lock.release k `catchAny` \_ -> return ()  -- | A request joins the job of a key: a queued job of upkeep moves to the -- end of the first part, and takes the payload of the request; a running
src/Haskoin/Store/XPub/Lock.hs view
@@ -11,7 +11,7 @@ -- One store of a fleet indexes an xpub at a time: a lock per xpub in the -- Redis that the stores share, taken by the indexer -- ("Haskoin.Store.XPub.Indexer") when it queues the xpub and let go when--- the job has written the entry (@docs\/xpub-indexing.md@, In a fleet).+-- the job has written the entry (@docs\/xpub-indexing.md@, The indexer). -- -- = Why --
swagger.yaml view
@@ -11,7 +11,7 @@   - url: './'  info:-  version: &version 1.16.7+  version: &version 2.0.0   title: Haskoin   contact:     name: JP Rupp@@ -332,6 +332,11 @@     description: |       The state of the server and the network: health, peers, and a live stream of       new blocks and transactions.+  - name: Tokens+    description: |+      The tokens of Bitcoin Cash (CashTokens): what an address holds, and the+      holders, transactions and unspent outputs of a category. On Bitcoin there+      are no tokens, and these answer with nothing.   - name: Blockchain     description: |       Endpoints that answer like those of Blockchain.info, for software written@@ -346,11 +351,16 @@       description: |         Whether this server is ready to answer, for load balancers and monitoring. -        The status is **200** when every check passes and **503** when one fails;-        the body is the same either way and says which check failed. A server that is-        still catching up with the network answers 503, so a load balancer stops-        sending it traffic until its answers are current.+        The status is **200** when the server has the blocks of the network+        and **503** when it has not; the body is the same either way and says+        which check failed. A server that is still catching up with the blocks+        of the network answers 503, so a load balancer stops sending it traffic+        until its answers are current. +        The state of the mempool does not decide it: a server at the head of+        the chain is healthy. How its mempool stands, as after a start, is+        said in one word in `mempool.sync`.+         A server that cannot reach its Redis answers **503** too, with the         header `Haskoin-Degraded: redis` and `"redis": {"ok": false}` in the         body: Redis holds the mempool and the cache of extended public keys@@ -369,6 +379,9 @@                 $ref: '#/components/schemas/HealthCheck'               example:                 ok: true+                text: >-+                  The store is healthy: it has every block up to height 688,794,+                  with 20 peers connected, and its Redis answers.                 net: bch                 blocks:                   ok: true@@ -376,30 +389,54 @@                   blocks: 688794                   diff: 0                   headers: 688794+                  text: The database has every block up to the best header, at height 688,794.                 pending-txs:                   ok: true                   max: 100                   count: 0+                  text: 0 transactions asked of peers are still to come, within the 100 allowed.                 version: *version                 last-tx:                   ok: true                   max: 300                   age: 0+                  text: A transaction or block came just now, within the 5 minutes allowed.                 last-block:                   ok: true                   max: 7200                   age: 3279+                  text: The best header is 54 minutes old, within the 2 hours allowed.                 peers:                   ok: true                   count: 20                   min: 1+                  text: 20 peers connected, and at least 1 needed.                 redis:                   ok: true+                  text: Redis answers.                 database:                   ok: true                   writes: flowing                   pending-compaction-bytes: 0                   delayed-write-rate: 0+                  running-compactions: 1+                  running-flushes: 0+                  immutable-memtables: 0+                  size-bytes: 412000000000+                  live-data-bytes: 405300000000+                  background-errors: 0+                  text: >-+                    RocksDB writes at full speed. Its files hold 412.0 GB, 405.3 GB of+                    them live data. 1 compaction running.+                mempool:+                  sources: 1+                  dirty: false+                  known: 0+                  held: 0+                  sync: synced+                  text: >-+                    The store has 1 source to read a whole mempool from again, which it+                    does when it may have missed a transaction.                 time: '2021-06-14 10:21:43 UTC'         '503':           description: unavailable@@ -409,6 +446,11 @@                 $ref: '#/components/schemas/HealthCheck'               example:                 ok: false+                text: >-+                  The store is not healthy. The database is 4 blocks behind the best+                  header, at height 688,798, more than the 2 allowed: the store is+                  syncing, or cannot import blocks fast enough. 0 peers connected,+                  fewer than the 1 needed: the store hears too little of the network.                 net: bch                 blocks:                   ok: false@@ -416,30 +458,59 @@                   blocks: 688794                   diff: 4                   headers: 688798+                  text: >-+                    The database is 4 blocks behind the best header, at height 688,798,+                    more than the 2 allowed: the store is syncing, or cannot import+                    blocks fast enough.                 pending-txs:                   ok: true                   max: 100                   count: 0+                  text: 0 transactions asked of peers are still to come, within the 100 allowed.                 version: *version                 last-tx:                   ok: true                   max: 300                   age: 0+                  text: A transaction or block came just now, within the 5 minutes allowed.                 last-block:                   ok: true                   max: 7200                   age: 3279+                  text: The best header is 54 minutes old, within the 2 hours allowed.                 peers:                   ok: false                   count: 0                   min: 1+                  text: >-+                    0 peers connected, fewer than the 1 needed: the store hears too+                    little of the network.                 redis:                   ok: true+                  text: Redis answers.                 database:                   ok: true                   writes: flowing                   pending-compaction-bytes: 0                   delayed-write-rate: 0+                  running-compactions: 0+                  running-flushes: 0+                  immutable-memtables: 0+                  size-bytes: 412000000000+                  live-data-bytes: 405300000000+                  background-errors: 0+                  text: >-+                    RocksDB writes at full speed. Its files hold 412.0 GB, 405.3 GB of+                    them live data. Nothing waits to be compacted or flushed.+                mempool:+                  sources: 1+                  dirty: false+                  known: 0+                  held: 0+                  sync: synced+                  text: >-+                    The store has 1 source to read a whole mempool from again, which it+                    does when it may have missed a transaction.                 time: '2021-06-14 10:21:43 UTC'    '/address/{address}/transactions':@@ -2652,6 +2723,156 @@                   services: "0000000000000425"                   relay: true +  '/address/{address}/tokens':+    get:+      tags:+        - Tokens+      operationId: getAddressTokens+      summary: Address Tokens+      description: |+        The tokens that an address holds, one balance per category. An address that+        never held tokens has none: the list is empty.++        The balances count the mempool, as the balance of an address does.++        Token amounts are strings, since a category can have up to 2^63 - 1 tokens,+        more than a JSON number holds exactly in many languages. The coins of the+        same outputs are in the address's balance, as those of any output.+      parameters:+        - $ref: '#/components/parameters/addressParam'+      responses:+        '200':+          description: Token balances of the address.+          content:+            application/json:+              schema:+                type: array+                items:+                  $ref: '#/components/schemas/TokenBalance'+              example:+                # from a regtest chain of Bitcoin Cash Node+                - address: bchreg:qzpdpp48htve8dsl5w2009xts33gvz44ts853ucllm+                  category: 084c120da82f5235b0f9b5ba5851e62d0dcad3febaf0620fdae8bd3aeeb893ae+                  confirmed: '1000'+                  unconfirmed: '0'+                  nfts: 0+                  utxo: 1+                  txs: 2+                  received: '2000'+        '404':+          description: Invalid address.+          content:+            application/json:+              schema:+                $ref: '#/components/schemas/Error'++  '/token/{category}/holders':+    get:+      tags:+        - Tokens+      operationId: getTokenHolders+      summary: Token Holders+      description: |+        The addresses that hold tokens of a category, one balance each, in the order+        of their bytes, a page at a time. Tokens in outputs without an address are+        in no one's balance.+      parameters:+        - $ref: '#/components/parameters/categoryParam'+        - $ref: '#/components/parameters/offsetParam'+        - $ref: '#/components/parameters/limitParam'+      responses:+        '200':+          description: Token balances of the holders.+          content:+            application/json:+              schema:+                type: array+                items:+                  $ref: '#/components/schemas/TokenBalance'+              example:+                # from a regtest chain of Bitcoin Cash Node+                - address: bchreg:qzpdpp48htve8dsl5w2009xts33gvz44ts853ucllm+                  category: 084c120da82f5235b0f9b5ba5851e62d0dcad3febaf0620fdae8bd3aeeb893ae+                  confirmed: '1000'+                  unconfirmed: '0'+                  nfts: 0+                  utxo: 1+                  txs: 2+                  received: '2000'++  '/token/{category}/unspent':+    get:+      tags:+        - Tokens+      operationId: getTokenUnspent+      summary: Token Unspent Outputs+      description: |+        The unspent outputs that hold tokens of a category, newest first: those of the+        mempool first, then those of blocks that the mempool does not spend. Each has+        its tokens in its `token` field.+      parameters:+        - $ref: '#/components/parameters/categoryParam'+        - $ref: '#/components/parameters/heightParam'+        - $ref: '#/components/parameters/offsetParam'+        - $ref: '#/components/parameters/limitParam'+      responses:+        '200':+          description: Unspent outputs, newest first.+          content:+            application/json:+              schema:+                type: array+                items:+                  $ref: '#/components/schemas/Unspent'+              example:+                # from a regtest chain of Bitcoin Cash Node+                - address: bchreg:qzpdpp48htve8dsl5w2009xts33gvz44ts853ucllm+                  block:+                    height: 151+                    position: 2+                  txid: d74025d2a71dd0de1e721bf3323d2d5b86aae867713c18cb0971fce46e2f6b7f+                  index: 0+                  pkscript: "efae93b8ee3abde8da0f62f0bafed3ca0d2de65158bab5f9b035522fa80d124c\+                    0810fde80376a91482d086a7bad993b61fa394f794cb8462860ab55c88ac"+                  value: 4999800000+                  token:+                    category: 084c120da82f5235b0f9b5ba5851e62d0dcad3febaf0620fdae8bd3aeeb893ae+                    amount: '1000'++  '/token/{category}/transactions':+    get:+      tags:+        - Tokens+      operationId: getTokenTransactions+      summary: Token Transactions+      description: |+        The transactions that created, moved or burned tokens of a category, newest+        first, those of the mempool first, as the transactions of an address.+      parameters:+        - $ref: '#/components/parameters/categoryParam'+        - $ref: '#/components/parameters/heightParam'+        - $ref: '#/components/parameters/offsetParam'+        - $ref: '#/components/parameters/limitParam'+      responses:+        '200':+          description: Transactions, newest first.+          content:+            application/json:+              schema:+                type: array+                items:+                  $ref: '#/components/schemas/TxRef'+              example:+                # from a regtest chain of Bitcoin Cash Node+                - txid: d74025d2a71dd0de1e721bf3323d2d5b86aae867713c18cb0971fce46e2f6b7f+                  block:+                    height: 151+                    position: 2+                - txid: 178e6d219b4d96166fdf243ad74341b89da84eaa5f970a4eeea9860aea3c37ff+                  block:+                    height: 151+                    position: 1+   '/xpub/{xpub}':     get:       tags:@@ -6006,6 +6227,85 @@             Number of transactions that pay to or spend from the address.           format: int64 +    Token:+      type: object+      description: |+        The tokens that one output holds (CashTokens): all of one category, a+        fungible amount, a non-fungible token, or both. As in the CashTokens test+        vectors and the RPC of Bitcoin Cash Node.+      required:+        - category+        - amount+      properties:+        category:+          type: string+          description: |+            The category: the id of the transaction whose output 0 the transaction+            that created the tokens spent.+        amount:+          type: string+          description: |+            Fungible tokens, as a string: "0" for none.+        nft:+          type: object+          description: |+            The non-fungible token, if the output holds one.+          properties:+            capability:+              type: string+              enum: [none, mutable, minting]+              description: |+                What the holder can do: nothing more, change the commitment, or make+                new tokens of the category.+            commitment:+              type: string+              description: |+                The data that the token commits to, in hexadecimal; empty for none.++    TokenBalance:+      type: object+      description: |+        The tokens of one category that an address holds. `confirmed` plus+        `unconfirmed` is the fungible amount it holds now. Amounts are strings.+      required:+        - address+        - category+        - confirmed+        - unconfirmed+        - nfts+        - utxo+        - txs+        - received+      properties:+        address:+          type: string+        category:+          type: string+        confirmed:+          type: string+          description: |+            Fungible tokens in outputs in blocks that the mempool does not spend.+        unconfirmed:+          type: string+          description: |+            Fungible tokens in outputs of the mempool that the mempool does not spend.+        nfts:+          type: integer+          description: |+            Non-fungible tokens held.+        utxo:+          type: integer+          description: |+            Unspent outputs that hold tokens of the category.+        txs:+          type: integer+          description: |+            Transactions that moved tokens of the category to or from the address.+        received:+          type: string+          description: |+            Fungible tokens that the address ever received, spent ones included.+     Unspent:       type: object       description: |@@ -6043,6 +6343,15 @@           description: |             Value in satoshis.           format: int64+        token:+          description: |+            The tokens that the output holds, on Bitcoin Cash (CashTokens): null for+            an output without tokens. The field is there on the Bitcoin Cash networks+            only. The tokens are written at the front of the script field, so+            `pkscript` has them too.+          nullable: true+          allOf:+            - $ref: '#/components/schemas/Token'      BlockData:       type: object@@ -6200,6 +6509,15 @@             Witness stack, each item in hexadecimal; empty without SegWit.           items:             type: string+        token:+          description: |+            The tokens that the output spent holds, on Bitcoin Cash (CashTokens): null for+            an output without tokens. The field is there on the Bitcoin Cash networks+            only. The tokens are written at the front of the script field, so+            `pkscript` has them too.+          nullable: true+          allOf:+            - $ref: '#/components/schemas/Token'      Spender:       type: object@@ -6251,6 +6569,15 @@             The input that spends it, if any.           allOf:             - $ref: '#/components/schemas/Spender'+        token:+          description: |+            The tokens that the output holds, on Bitcoin Cash (CashTokens): null for+            an output without tokens. The field is there on the Bitcoin Cash networks+            only. The tokens are written at the front of the script field, so+            `pkscript` has them too.+          nullable: true+          allOf:+            - $ref: '#/components/schemas/Token'      Transaction:       type: object@@ -6327,8 +6654,12 @@           type: boolean           description: |             Whether the transaction can still be replaced by one paying a higher fee:-            it signals replace-by-fee (BIP 125), or spends an unconfirmed transaction-            that does. Only meaningful while unconfirmed, and on BTC.+            true for every unconfirmed transaction on BTC, whose nodes take a+            replacement of any unconfirmed transaction whatever it signals (full+            replace-by-fee, the rule of Bitcoin Core since version 28), and false for+            every confirmed transaction and on BCH, which has no such rule. Until+            version 2.0 it said whether the transaction signalled replace-by-fee+            (BIP 125) or spent an unconfirmed transaction that did.         weight:           type: integer           description: |@@ -6397,6 +6728,7 @@         - diff         - max         - ok+        - text       properties:         headers:           type: integer@@ -6418,6 +6750,12 @@           type: boolean           description: |             Whether `diff` is at most `max`.+        text:+          type: string+          description: |+            What the check found, in a sentence or two for people, and if it+            fails, what that may mean. Programs should read `ok` and the+            numbers: the wording may change.      TimeHealth:       type: object@@ -6427,6 +6765,7 @@         - age         - max         - ok+        - text       properties:         age:           type: integer@@ -6440,6 +6779,12 @@           type: boolean           description: |             Whether `age` is at most `max`.+        text:+          type: string+          description: |+            What the check found, in a sentence or two for people, and if it+            fails, what that may mean. Programs should read `ok` and the+            numbers: the wording may change.      CountHealth:       type: object@@ -6449,6 +6794,7 @@         - count         - min         - ok+        - text       properties:         count:           type: integer@@ -6462,6 +6808,12 @@           type: boolean           description: |             Whether `count` is at least `min`.+        text:+          type: string+          description: |+            What the check found, in a sentence or two for people, and if it+            fails, what that may mean. Programs should read `ok` and the+            numbers: the wording may change.      MaxHealth:       type: object@@ -6471,6 +6823,7 @@         - count         - max         - ok+        - text       properties:         count:           type: integer@@ -6484,12 +6837,29 @@           type: boolean           description: |             Whether `count` is at most `max`.+        text:+          type: string+          description: |+            What the check found, in a sentence or two for people, and if it+            fails, what that may mean. Programs should read `ok` and the+            numbers: the wording may change.      HealthCheck:       type: object       description: |-        The result of the latest health check. `ok` is true when every check passes.-        The limits are set by the operator of the server.+        The result of the latest health check. `ok` is true when the server+        has the blocks of the network: `blocks`, `last-block`, `peers` and+        `database` pass. The limits are set by the operator of the server.++        Nothing of the mempool decides it. A server that is at the head of the+        chain answers every request rightly from what it has, whatever the+        state of its mempool. The checks `last-tx` and `pending-txs` are made+        and say whether they pass, each with its own `ok`, and `ok` here does+        not depend on them. What to know of the mempool is in `mempool`:+        `sync` says in one word how it stands.++        `warnings`, when there are any, are not checks either: `ok` and the+        status do not depend on them.       required:         - blocks         - last-block@@ -6498,9 +6868,11 @@         - peers         - redis         - database+        - mempool         - net         - version         - ok+        - text       properties:         blocks:           description: |@@ -6516,12 +6888,14 @@         last-tx:           description: |             Age of the newest unconfirmed transaction (or block, if newer). A busy-            network sends transactions all the time, so silence means trouble.+            network sends transactions all the time, so silence may mean+            trouble. It does not decide `ok` of the server.           allOf:             - $ref: '#/components/schemas/TimeHealth'         pending-txs:           description: |-            Transactions requested from peers and not received yet.+            Transactions requested from peers and not received yet. It does+            not decide `ok` of the server.           allOf:             - $ref: '#/components/schemas/MaxHealth'         peers:@@ -6538,21 +6912,36 @@             extended public keys to answer from.           required:             - ok+            - text           properties:             ok:               type: boolean+            text:+              type: string+              description: |+                Whether Redis answers, in words.         database:           type: object           description: |-            Whether RocksDB lets writes through. RocksDB delays writes, and then stops-            them, when its compactions fall behind. Stopped writes make `ok` false and-            the status 503; delayed writes do not, as the server still answers at full-            speed, and `blocks` says so if it falls behind. Read every five seconds.+            The state of the database, as RocksDB reports it, read every five+            seconds. RocksDB writes to memory, flushes that to files, and merges+            the files in the background (compaction); when compaction falls behind+            it delays writes, and then stops them. Stopped writes make `ok` false+            and the status 503; delayed writes do not, as the server still answers+            at full speed, and `blocks` says so if it falls behind. The other+            numbers say why writes are slow, and are not judged.           required:             - ok+            - text             - writes             - pending-compaction-bytes             - delayed-write-rate+            - running-compactions+            - running-flushes+            - immutable-memtables+            - size-bytes+            - live-data-bytes+            - background-errors           properties:             ok:               type: boolean@@ -6569,6 +6958,124 @@               type: integer               description: |                 Bytes a second that writes are slowed to; 0 when they are not.+            running-compactions:+              type: integer+              description: |+                Compactions running.+            running-flushes:+              type: integer+              description: |+                Flushes of memory to files running.+            immutable-memtables:+              type: integer+              description: |+                Tables in memory that are full and wait to be flushed, over every+                column family.+            size-bytes:+              type: integer+              description: |+                Bytes of the files of the database, over every column family.+            live-data-bytes:+              type: integer+              description: |+                Bytes of those files that hold live data, as RocksDB estimates.+            background-errors:+              type: integer+              description: |+                Errors of the work in the background since the database opened.+                After one, RocksDB may refuse writes; the log of the server says+                more.+            text:+              type: string+              description: |+                What RocksDB reports, in words: the state of writes, the size of+                the files, and the work in hand.+        mempool:+          type: object+          description: |+            How the server stands with the mempool of its nodes. It is not a+            check: it has no `ok`, and does not change the status.++            A node announces a transaction to a peer once. A server that misses+            one gets it back only by reading the whole mempool of a node again,+            from a source: the RPC of a node, if the server was given one, or a+            peer whose node allows it. Bitcoin Core allows it to a peer that it+            whitelists with the permission `mempool`, or when it serves Bloom+            filters; Bitcoin Cash Node serves them by default. A server with no+            source may show fewer unconfirmed transactions than a node until the+            next block, and the `text` at the top says so.+          required:+            - sources+            - dirty+            - known+            - held+            - sync+            - text+          properties:+            sources:+              type: integer+              description: |+                What the server can read a whole mempool from: connected peers+                that give theirs when asked, and the RPC of a node while it+                answers.+            dirty:+              type: boolean+              description: |+                Whether the server may have missed transactions that a node has,+                and has not read a source since: it gave some up, it dropped+                messages of its peers, or the shared mempool lost what it had. It+                reads its sources again within seconds; with no source it stays+                true.+            known:+              type: integer+              description: |+                Transaction ids on their way to the shared mempool: wanted,+                asked of a peer, or held.+            held:+              type: integer+              description: |+                Transactions held: being offered, or waiting for one that they+                spend from.+            sync:+              type: string+              enum:+                - syncing+                - synced+                - unknown+              description: |+                How the shared mempool stands with the mempools of the nodes+                of the operator of the server, in one word.++                `syncing`: the server has such a node to read a whole mempool+                from, and has not yet read it and taken in all that it named,+                since it started or since the shared mempool lost what it had.+                It then shows fewer unconfirmed transactions than its node+                has. It says so for twenty seconds at least after a start, the+                time that a node is given to name its mempool.++                `synced`: it has.++                `unknown`: the server has no node of its operator to read a+                whole mempool from, only peers that it does not trust or+                nobody, and cannot tell.++                The server is healthy in all three: wait for `synced` before+                giving a new server traffic, if unconfirmed transactions+                matter to you.+            text:+              type: string+              description: |+                The same in words.+        warnings:+          type: array+          description: |+            What the operator of the server should put right in how it is set+            up, a sentence each, for people. Left out when there is none. A+            warning decides nothing of `ok`. There is one so far: the server+            has the RPC of its node and not its ZeroMQ socket, and asks the+            node every five seconds for what the socket would announce.+          items:+            type: string         net:           type: string           description: |@@ -6581,6 +7088,13 @@           type: boolean           description: |             Whether every check passed, writes to the database included.+        text:+          type: string+          description: |+            The state of the whole server in a sentence or two, for people: that+            it is healthy, with its height and peers, or what is wrong, from the+            checks that fail and Redis. Programs should read `ok` and the+            numbers: the wording may change.         time:           type: string           description: |@@ -7468,6 +7982,16 @@       schema:         type: string         example: 03c16602a41ae7cbc2a25b0d2801fdc3295e2e8ebfb26774030b2f7d538f5568++    categoryParam:+      name: category+      in: path+      description: |+        A category of tokens of Bitcoin Cash: the id of the transaction whose output+        0 created it, in hexadecimal.+      required: true+      schema:+        type: string      timeParam:       name: time
− test/Haskoin/Store/BlockStore/PendingSpec.hs
@@ -1,41 +0,0 @@--- | The transactions that the block store requested from peers.-module Haskoin.Store.BlockStore.PendingSpec (spec) where--import Data.ByteString.Char8 qualified as C8-import Data.Time.Calendar (fromGregorian)-import Data.Time.Clock (UTCTime (..), addUTCTime)-import Haskoin-import Haskoin.Store.BlockStore.Pending-import Test.Hspec-import Test.Hspec.QuickCheck (prop)-import Test.QuickCheck--t0 :: UTCTime-t0 = UTCTime (fromGregorian 2026 11 9) 0---- | Distinct transaction ids.-hashes :: Gen [TxHash]-hashes = do-  n <- choose (1, 12 :: Int)-  return [TxHash (sha256 (C8.pack (show i))) | i <- [1 .. n]]--spec :: Spec-spec = describe "Pending requests" $ do-  prop "does not request again what is requested" $-    forAll hashes $ \hs ->-      let p = requested t0 hs empty-       in all (`isPending` p) hs .&&. size p === length hs--  prop "forgets a request once its transaction arrives" $-    forAll hashes $ \hs ->-      let (got, still) = splitAt (length hs `div` 2) hs-          p = foldr answered (requested t0 hs empty) got-       in not (any (`isPending` p) got) .&&. all (`isPending` p) still .&&. size p === length still--  prop "forgets requests after twenty seconds" $-    forAll hashes $ \hs ->-      let asked = requested t0 hs empty-       in conjoin-            [ property (all (`isPending` prune (addUTCTime 20 t0) asked) hs),-              property (not (any (`isPending` prune (addUTCTime 21 t0) asked) hs))-            ]
test/Haskoin/Store/BlockStore/SyncSpec.hs view
@@ -20,7 +20,10 @@ data Event   = Start Int   | Pass Int-  | Release Int+  | -- | a peer disconnects+    Disconnect Int+  | -- | the store stops syncing from a peer that is still connected+    Finish Int   | Request [Int]   | -- | a peer sends a block, which is imported if it is accepted     Deliver Int Int@@ -33,7 +36,8 @@     frequency       [ (2, Start <$> peer),         (2, Pass <$> peer),-        (1, Release <$> peer),+        (1, Disconnect <$> peer),+        (1, Finish <$> peer),         (3, Request <$> listOf block),         (4, Deliver <$> peer <*> block),         (1, pure Forget),@@ -61,7 +65,8 @@ step (now, s) = \case   Start p -> (now, fromMaybe s (start now p s))   Pass p -> (now, snd (pass now p s))-  Release p -> (now, snd (release p s))+  Disconnect p -> (now, snd (forget p s))+  Finish p -> (now, snd (finish now p s))   Request bs -> (now, request (map hash bs) s)   Deliver p b -> case accept p (hash b) s of     (Requested, s') -> (now, imported now (hash b) s')@@ -104,11 +109,32 @@       [ case e of           Start p -> syncingPeer s' == if isNothing (syncingPeer s) then Just p else syncingPeer s           Pass p -> syncingPeer s' == (p <$ syncingPeer s)-          Release p | syncingPeer s == Just p -> isNothing (syncingPeer s')+          Disconnect p | syncingPeer s == Just p -> isNothing (syncingPeer s')+          Finish p | syncingPeer s == Just p -> isNothing (syncingPeer s')           _ -> syncingPeer s' == syncingPeer s       | ((_, s), e, (_, s')) <- steps es       ] +  prop "never takes a peer that owes a block for one that was not asked" $ \es ->+    and+      [ fst (accept p (hash b) s) /= NotSyncingPeer+      | ((_, s), Deliver p b, _) <- steps es,+        maybe False (hash b `elem`) (owed p s)+      ]++  prop "keeps every peer owed its blocks when the store stops syncing from one" $ \es ->+    and+      [ all (\q -> fromMaybe [] (owed q s') == fromMaybe [] (owed q s)) [0 .. 3]+      | ((_, s), Finish _, (_, s')) <- steps es+      ]++  prop "has a peer owe each block once" $ \es ->+    and+      [ nub a.owes == a.owes+      | (_, s) <- run es,+        a <- maybe [] pure s.current <> s.passed+      ]+   prop "keeps a peer that is passed over owed its blocks" $ \es ->     and       [ owed old s' == owed old s@@ -252,13 +278,26 @@       expired timeout (at 61) s `shouldBe` [0]     it "is forgotten when it disconnects" $ do       let (_, s) = pass (at 11) 1 asked-          (wasSyncing, s') = release 0 s+          (wasSyncing, s') = forget 0 s       wasSyncing `shouldBe` False       passedPeers s' `shouldBe` []       fst (accept 0 (hash 1) s') `shouldBe` NotSyncingPeer+    it "drops, and does not disconnect, a peer that delivers after another brought the store in sync" $ do+      -- peer 0 stalls, peer 1 is asked in its place, peer 0 delivers, and+      -- the store, in sync, stops syncing from peer 1, which still owes it+      let (_, s1) = pass (at 11) 1 asked+          s2 = case accept 0 (hash 1) s1 of+            (Requested, s') -> imported (at 12) (hash 1) s'+            (v, _) -> error ("not taken: " <> show v)+          (wasSyncing, s3) = finish (at 12) 1 s2+      wasSyncing `shouldBe` True+      passedPeers s3 `shouldBe` [1]+      fst (accept 1 (hash 1) s3) `shouldBe` Late+      expired timeout (at 72) s3 `shouldBe` []+      expired timeout (at 73) s3 `shouldBe` [1]     it "still owes its blocks if it becomes the syncing peer again" $ do       let (_, s1) = pass (at 11) 1 asked-          (_, s2) = release 1 s1+          (_, s2) = forget 1 s1           s3 = fromMaybe s2 (start (at 20) 0 s2)       passedPeers s3 `shouldBe` []       -- the block is not wanted any more: the request went with peer 1@@ -352,7 +391,7 @@       let (_, s) = pong wait (at 7) 1 7 searching       overdue wait (at 7) s `shouldBe` [1, 0]     it "ends when the last peer pinged is gone" $ do-      let (_, s1) = release 0 searching+      let (_, s1) = forget 0 searching       probing s1 `shouldBe` True       probing (skip 1 s1) `shouldBe` False       probing (settle searching) `shouldBe` False
− test/Haskoin/Store/BlockStoreSpec.hs
@@ -1,17 +0,0 @@--- | Which peers the block store asks for their mempools.-module Haskoin.Store.BlockStoreSpec (spec) where--import Haskoin (bch, btc)-import Haskoin.Store.BlockStore (asksMempool)-import Network.Socket (SockAddr (..), tupleToHostAddress)-import Test.Hspec--spec :: Spec-spec = describe "Asking for a mempool" $ do-  let local = SockAddrInet 8335 (tupleToHostAddress (127, 0, 0, 1))-      seed = SockAddrInet 8333 (tupleToHostAddress (192, 0, 2, 7))-  it "asks every peer on Bitcoin Cash, whose nodes answer anyone" $-    map (asksMempool bch []) [local, seed] `shouldBe` [True, True]-  it "asks only the peers given explicitly on Bitcoin, whose nodes disconnect the others" $ do-    map (asksMempool btc [local]) [local, seed] `shouldBe` [True, False]-    asksMempool btc [] local `shouldBe` False
test/Haskoin/Store/Database/MergeSpec.hs view
@@ -196,9 +196,9 @@           agree           compactRange db.db (Just cf) Nothing Nothing           agree-      it "has the two operators on their column families, and the one that keeps older stores out" $+      it "has the operators on their column families, the one that keeps older stores out, and those of the tokens" $         withDB $-          \db -> length (columnFamilies db.db) `shouldBe` 11+          \db -> length (columnFamilies db.db) `shouldBe` 15  ------------------------------------------------------------------------------- -- Calling the operators as RocksDB does
test/Haskoin/Store/Database/MigrateSpec.hs view
@@ -4,13 +4,30 @@ import Control.Monad (forM, forM_, replicateM_, void, when) import Data.ByteString qualified as B import Data.List (isInfixOf)+import Data.Maybe (fromJust) import Data.Serialize (encode) import Data.Word (Word32) import Database.RocksDB (columnFamilies, put) import Database.RocksDB.Query (insert, insertOp, retrieve, writeBatch)-import Haskoin (TxHash, btcRegTest)-import Haskoin.Store.Data (UnixTime)+import Haskoin+  ( NFToken (..),+    Network (..),+    OutPoint (..),+    TokenCapability (..),+    TokenData (..),+    Tx (..),+    TxHash,+    TxIn (..),+    TxOut (..),+    bchRegTest,+    btcRegTest,+    encodeTokenPrefix,+    txHash,+  )+import Haskoin.Store.Data (BlockData (..), UnixTime) import Haskoin.Store.Database.Migrate+import Haskoin.Store.Database.Migrate.Tokens (migrateTokens)+import Haskoin.Store.Database.Query qualified as Q import Haskoin.Store.Database.Reader (DatabaseReader (..)) import Haskoin.Store.Database.Types (MigrationKey (..), VersionKey (..)) import Haskoin.Store.Histories@@ -40,11 +57,12 @@     withSystemTempDirectory "haskoin-store-merges-" $ \dir ->       openLayered net dir $ \db -> do         void (upgradeDatabase (\_ -> return ()) db)-        retrieve db.db VersionKey `shouldReturn` Just (23 :: Word32)-        insert db.db VersionKey (24 :: Word32)-        upgradeDatabase (\_ -> return ()) db `shouldThrow` (== UnknownVersion (Just 24))-        retrieve db.db VersionKey `shouldReturn` Just (24 :: Word32)-        displayException (UnknownVersion (Just 24)) `shouldSatisfy` ("newer haskoin-store" `isInfixOf`)+        retrieve db.db VersionKey `shouldReturn` Just currentVersion+        insert db.db VersionKey (currentVersion + 1)+        upgradeDatabase (\_ -> return ()) db `shouldThrow` (== UnknownVersion (Just (currentVersion + 1)))+        retrieve db.db VersionKey `shouldReturn` Just (currentVersion + 1)+        displayException (UnknownVersion (Just (currentVersion + 1)))+          `shouldSatisfy` ("newer haskoin-store" `isInfixOf`)         -- no migration leaves a marker with the current version         writeBatch db.db [insertOp VersionKey currentVersion, insertOp MigrationKey layeredVersion]         upgradeDatabase (\_ -> return ()) db `shouldThrow` (== UnknownVersion (Just currentVersion))@@ -75,8 +93,38 @@         upgradeDatabase (\_ -> return ()) db `shouldReturn` nothing         retrieve db.db VersionKey `shouldReturn` Just currentVersion         (retrieve db.db MigrationKey :: IO (Maybe Word32)) `shouldReturn` Nothing-        length (columnFamilies db.db) `shouldBe` 11+        -- the merge guard and the four of the tokens+        length (columnFamilies db.db) `shouldBe` 15 +  it "takes a database of version 23 to the current one on a network without tokens" $+    withSystemTempDirectory "haskoin-store-tokens-" $ \dir ->+      openLayered net dir $ \db -> do+        insert db.db VersionKey mergesVersion+        upgradeDatabase (\_ -> return ()) db `shouldReturn` nothing+        retrieve db.db VersionKey `shouldReturn` Just currentVersion++  it "takes a database of version 23 of Bitcoin Cash to the current one, indexing its tokens" $+    withSystemTempDirectory "haskoin-store-tokens-" $ \dir ->+      openLayered bchRegTest dir $ \db -> do+        insert db.db VersionKey mergesVersion+        upgradeDatabase (\_ -> return ()) db `shouldReturn` nothing+        retrieve db.db VersionKey `shouldReturn` Just currentVersion+        (retrieve db.db MigrationKey :: IO (Maybe Word32)) `shouldReturn` Nothing++  it "indexes the tokens of a database of version 23 as the import of its blocks does" $+    withSystemTempDirectory "haskoin-store-tokens-" $ \dir -> do+      -- the same blocks, imported as version 24 does and as version 23 did+      fresh <- tokenChain bchRegTest (dir <> "/fresh")+      old <- tokenChain bchRegTest {cashAddrPrefix = Nothing} (dir <> "/old")+      fresh `shouldNotBe` old+      migrated <- openLayered bchRegTest (dir <> "/old") $ \db -> do+        insert db.db VersionKey mergesVersion+        n <- migrateTokens (\_ -> return ()) 0 db+        -- the two transactions that hold tokens, and only those+        n `shouldBe` 2+        families db+      migrated `shouldBe` fresh+   it "cannot be opened by a store that does not know the merge operators, which leaves its merge records be" $     withSystemTempDirectory "haskoin-store-merges-" $ \dir -> do       -- blocks with merge records, which are in the write-ahead log and@@ -95,5 +143,43 @@       openLayered net dir contents `shouldReturn` written   where     net = btcRegTest+    -- every column family that a block writes to, but the spenders'+    -- groups, which the tokens do not touch: those of the chain and those+    -- of the tokens+    families db = forM [0, 1, 2, 4, 5, 6, 7, 11, 12, 13, 14] $ \i -> dump db (columnFamilies db.db !! i)+    -- a chain on Bitcoin Cash with tokens, imported with the rules of a+    -- network, and what its column families hold+    tokenChain rules path = openLayered bchRegTest path $ \db -> do+      startChainAs rules db+      first <- mineAs rules db []+      coinbase <-+        Q.getBlock db first >>= \case+          Just bd | h : _ <- bd.txs -> return h+          _ -> fail "no coinbase"+      let minted = TokenData coinbase 1000 (Just (NFToken MintingCapability "\x01"))+          alice = "\x76\xa9\x14" <> B.replicate 20 0x11 <> "\x88\xac"+          bob = "\x76\xa9\x14" <> B.replicate 20 0x22 <> "\x88\xac"+          holding t lock = fromJust (encodeTokenPrefix t) <> lock+          -- alice gets coins without tokens too, so her history has the+          -- transaction already in version 23+          genesis =+            Tx+              1+              [TxIn (OutPoint coinbase 0) "" maxBound]+              [TxOut 1000 (holding minted alice), TxOut 2000 bob, TxOut 3000 alice]+              []+              0+          move =+            Tx+              1+              [TxIn (OutPoint (txHash genesis) 0) "" maxBound]+              [ TxOut 600 (holding (TokenData coinbase 400 Nothing) bob),+                TxOut 400 (holding minted {amount = 600} alice)+              ]+              []+              0+      _ <- mineAs rules db [genesis]+      _ <- mineAs rules db [move]+      families db     nothing = Migration {moved = 0, batches = 0, checked = 0, rewritten = 0}     contents db = forM (columnFamilies db.db) (dump db)
test/Haskoin/Store/Database/StallsSpec.hs view
@@ -5,6 +5,7 @@ import Data.Maybe (isNothing) import Haskoin (btcRegTest) import Haskoin.Node (LogLevel (..))+import Haskoin.Store.Data (DatabaseHealth (..), DatabaseWrites (..)) import Haskoin.Store.Database.Reader (DatabaseReader (..)) import Haskoin.Store.Database.Stalls import Haskoin.Store.Histories (openLayered)@@ -20,25 +21,42 @@       map defaultBackgroundJobs [-1, 0] `shouldBe` [2, 2]    describe "the log of write stalls" $ do-    let at w = noStall {writes = w, pending = 70000000000, rate = if w == Delayed then 16777216 else 0}+    let at w =+          noStall+            { writes = w,+              pendingCompaction = 70000000000,+              delayedWriteRate = if w == WritesDelayed then 16777216 else 0+            }         level before now = fst <$> stallNote before (at now)     it "says nothing while the state stays the same" $       mapM_ (\w -> stallNote w (at w) `shouldSatisfy` isNothing) [minBound .. maxBound]     it "warns when writes get worse" $ do-      level Flowing Delayed `shouldBe` Just LevelWarn-      level Flowing Stopped `shouldBe` Just LevelWarn-      level Delayed Stopped `shouldBe` Just LevelWarn+      level WritesFlowing WritesDelayed `shouldBe` Just LevelWarn+      level WritesFlowing WritesStopped `shouldBe` Just LevelWarn+      level WritesDelayed WritesStopped `shouldBe` Just LevelWarn     it "says so at info when they get better" $ do-      level Stopped Delayed `shouldBe` Just LevelInfo-      level Stopped Flowing `shouldBe` Just LevelInfo-      level Delayed Flowing `shouldBe` Just LevelInfo+      level WritesStopped WritesDelayed `shouldBe` Just LevelInfo+      level WritesStopped WritesFlowing `shouldBe` Just LevelInfo+      level WritesDelayed WritesFlowing `shouldBe` Just LevelInfo     it "logs once for a run of polls in the same state" $ do-      let states = [Flowing, Flowing, Delayed, Delayed, Delayed, Stopped, Stopped, Delayed, Flowing, Flowing]+      let states =+            [ WritesFlowing,+              WritesFlowing,+              WritesDelayed,+              WritesDelayed,+              WritesDelayed,+              WritesStopped,+              WritesStopped,+              WritesDelayed,+              WritesFlowing,+              WritesFlowing+            ]           notes = [l | (b, n) <- zip states (drop 1 states), Just (l, _) <- [stallNote b (at n)]]       notes `shouldBe` [LevelWarn, LevelWarn, LevelInfo, LevelInfo]    describe "reading the state from RocksDB" $-    it "finds writes flowing on a new database" $+    it "finds writes flowing on a new database, with no errors and nothing to compact" $       withSystemTempDirectory "haskoin-store-stalls-" $ \dir ->-        openLayered btcRegTest dir $ \db ->-          (.writes) <$> readStall db.db `shouldReturn` Flowing+        openLayered btcRegTest dir $ \db -> do+          d <- readStall db.db+          (d.writes, d.errors, d.pendingCompaction, d.delayedWriteRate) `shouldBe` (WritesFlowing, 0, 0, 0)
test/Haskoin/Store/Database/ViewsSpec.hs view
@@ -41,7 +41,7 @@       first <- best       takeView views first       second <- next-      keepViews views [second]+      keepViews views (return [second])       heldViews views `shouldReturn` [second]       withViewAt views first Q.getBestBlock `shouldReturn` (Nothing :: Maybe (Maybe BlockHash))       withViewAt views second Q.getBestBlock `shouldReturn` Just (Just second)@@ -52,7 +52,7 @@       takeView views first       second <- next       result <- withViewAt views first $ \old -> do-        keepViews views [second]+        keepViews views (return [second])         -- gone for anyone who asks now         heldViews views `shouldReturn` [second]         withViewAt views first Q.getBestBlock `shouldReturn` (Nothing :: Maybe (Maybe BlockHash))
+ test/Haskoin/Store/DownloadSpec.hs view
@@ -0,0 +1,276 @@+-- |+-- Module      : Haskoin.Store.DownloadSpec+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- How a store downloads the blocks of real nodes: Bitcoin Cash Node in+-- regtest, in Podman ("Haskoin.Store.Integration.Node"), reached through+-- the Unix sockets of its pod. The store has no Redis here: it syncs its+-- blocks, which is all these tests look at.+--+-- These tests replace the mock peers that served canned blocks to the store+-- in memory. A real node shows what a node does: how its headers arrive,+-- what it answers, how long it takes. A peer that hangs is a node stopped+-- with @SIGSTOP@ ('freezeNode').+--+-- Each test is a group at the top of the module, so that haskell-dev runs+-- each in a process of its own (@haskell-dev.toml@), with a pod of its own.+module Haskoin.Store.DownloadSpec (spec) where++import Conduit (ConduitT, await, yield, (.|))+import Control.Concurrent (threadDelay)+import Control.Exception (finally)+import Control.Monad (forM_, unless, when)+import Control.Monad.IO.Class (liftIO)+import Data.Aeson (Value (..))+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.Foldable (toList)+import Data.IORef (atomicModifyIORef', newIORef, readIORef)+import Data.Maybe (fromMaybe)+import Data.Serialize (decode, runGet)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time.Clock (NominalDiffTime)+import GHC.Stats (GCDetails (..), RTSStats (..), getRTSStats, getRTSStatsEnabled)+import Haskoin+import Haskoin.Node (Conduits (..), LogLevel (..), Logger (..), withConnection)+import Haskoin.Store+import Haskoin.Store.Database.Query qualified as Q+import Haskoin.Store.Integration.Node hiding (nodeNetwork)+import Haskoin.Store.Integration.Node qualified as Node+import Haskoin.Store.Integration.Temp (withRamDir)+import Network.Socket (SockAddr)+import System.Mem (performMajorGC)+import System.Timeout (timeout)+import Test.Hspec+import Test.Podman (ContainerSpec (..), Pod, PodSpec (..), pod, podmanUsable, withPod)++spec :: Spec+spec = do+  usable <- runIO podmanUsable+  case usable of+    Left why ->+      describe "Downloads from regtest nodes in Podman" $+        it "check how the store downloads blocks" $+          pendingWith why+    Right () -> do+      describe "Downloads from Bitcoin Cash Node" $+        it "asks for blocks in windows of the block window, and keeps every transaction" windowTest+      describe "Downloads from two Bitcoin Cash Nodes, one that hangs" $+        it "asks the other node for the blocks that the frozen one does not deliver" stallTest+      describe "Downloads from Bitcoin Cash Node, memory" $+        it "keeps the heap flat while syncing" heapTest++kind :: NodeKind+kind = BitcoinCashNode++net :: Network+net = Node.nodeNetwork kind++-- | A store that syncs a chain of 102 blocks asks for them 64 at a time,+-- the block window, and the last 38; and it has every transaction of each+-- block, as the node has it.+windowTest :: IO ()+windowTest = withNodes 1 $ \_ nodes -> do+  n <- one nodes+  ensureWallet n+  miner <- getNewAddress n+  _ <- generateTo n 101 miner+  _ <- sendTo n miner 100000000+  tip <- lastOf <$> generateTo n 1 miner+  requests <- newIORef []+  withStoreOf [n] (counting requests) 10 $ \store -> do+    waitBlock store tip+    sizes <- reverse <$> readIORef requests+    sum sizes `shouldBe` 102+    take 1 sizes `shouldBe` [64]+    all (<= 64) sizes `shouldBe` True+    Just stored <- Q.getBlock store.db tip+    fromNode <- rpc n "getblock" [String (blockHashToHex tip)]+    let txids = [t | Just (Array ts) <- [field "tx" fromNode], String t <- toList ts]+    map txHashToHex stored.txs `shouldBe` txids+    length txids `shouldBe` 2+  where+    counting ref = \case+      MGetData (GetData ivs) -> atomicModifyIORef' ref (\xs -> (length ivs : xs, ()))+      _ -> return ()++-- | A store with two nodes, one of which hangs, has the blocks of the other+-- in a few seconds: it waits a second for a peer that delivers nothing+-- ('blockStall'), not the minute of its timeout. The store may ask either+-- node first, so what this checks is that a frozen node does not hold it+-- back.+stallTest :: IO ()+stallTest = withNodes 2 $ \p nodes -> case nodes of+  [n0, n1] -> do+    ensureWallet n0+    miner <- getNewAddress n0+    first <- lastOf <$> generateTo n0 101 miner+    waitUntil 60 "the second node to have the chain" $+      (== Just first) . hexToBlockHash <$> bestBlockHash n1+    withStoreOf [n0, n1] (\_ -> return ()) 1 $ \store -> do+      waitBlock store first+      freezeNode p 0 kind+      flip finally (thawNode p 0 kind) $ do+        ensureWallet n1+        other <- getNewAddress n1+        tip <- lastOf <$> generateTo n1 20 other+        got <- timeout 20000000 (waitBlock store tip)+        got `shouldBe` Just ()+  _ -> expectationFailure "Not two nodes"++-- | The heap of a store does not grow with the blocks it syncs. When+-- 'forever' went through a dictionary, each of six loops kept 33 to 107+-- bytes per message, a few hundred bytes per block in all: over the 5000+-- blocks measured, megabytes. A leak of 200 bytes per block fails the test.+heapTest :: IO ()+heapTest = do+  enabled <- getRTSStatsEnabled+  unless enabled $ pendingWith "run with +RTS -T to measure the heap"+  withNodes 1 $ \_ nodes -> do+    n <- one nodes+    ensureWallet n+    miner <- getNewAddress n+    -- in pieces, each within the time that an RPC call may take+    forM_ [1 .. 6 :: Int] $ \_ -> generateTo n 1000 miner+    tip <- hashOf =<< bestBlockHash n+    at1000 <- hashOf . textOf =<< rpc n "getblockhash" [Number 1000]+    withStoreOf [n] (\_ -> return ()) 10 $ \store -> do+      waitBlock store at1000+      early <- live+      waitBlock store tip+      late <- live+      let growth = fromIntegral late - fromIntegral early :: Integer+      putStrLn $ "heap growth over 5000 blocks: " <> show growth <> " bytes"+      growth `shouldSatisfy` (< 1024 * 1024)+  where+    live = do+      performMajorGC+      (.gc.gcdetails_live_bytes) <$> getRTSStats+    textOf = \case+      String t -> t+      v -> error ("Not a string: " <> show v)++-- | A pod of so many Bitcoin Cash Nodes, each after the first a peer of the+-- one before, with their RPC answering.+withNodes :: Int -> (Pod -> [Node] -> IO a) -> IO a+withNodes count go = do+  let spec' i =+        let c = nodeContainerAt i kind+         in if i == 0+              then c+              else c {command = c.command <> ["-addnode=127.0.0.1:" <> show (18444 + 10 * (i - 1))]}+      nodes = map spec' [0 .. count - 1]+  withPod (pod "download" nodes) {readyWithin = 120} $ \p -> do+    ns <- mapM (\i -> nodeAt i kind p) [0 .. count - 1]+    mapM_ waitRpc ns+    go p ns++-- | A store that syncs from these nodes and from nothing else, with no+-- Redis: it is given the messages that it sends to its peers to look at,+-- and the seconds that a peer may deliver nothing before another is asked+-- for its blocks ('blockStall').+withStoreOf :: [Node] -> (Message -> IO ()) -> NominalDiffTime -> (Store -> IO a) -> IO a+withStoreOf nodes seen stall go =+  withRamDir $ \dir ->+    withStore (config dir) go+  where+    config dir =+      StoreConfig+        { maxPeers = 8,+          initPeers = map (.peer) nodes,+          peerPermissions = mempty,+          foreignPeers = False,+          discover = False,+          db = dir,+          net = net,+          redis = Nothing,+          gap = 32,+          initGap = 20,+          redisMaxXPubs = 10000,+          xpubs = defaultXPubConfig,+          blockWindow = 64,+          mempoolTimeout = 14,+          peerTimeout = 60,+          blockStall = stall,+          blockPing = 5,+          maxPeerLife = 48 * 3600,+          connect = tapped seen,+          nodePeerRpc = Nothing,+          nodePeerRpcSocket = Nothing,+          nodePeerZmq = Nothing,+          stats = Nothing,+          bloom = True,+          maxOpenFiles = Just 256,+          writeBufferSize = Just (16 * 1024 * 1024),+          maxWalSize = Just (64 * 1024 * 1024),+          backgroundJobs = Nothing,+          blockCache = Just (16 * 1024 * 1024),+          logger = Logger {level = LevelError, source = "", push = \_ -> return ()}+        }++-- | 'withConnection', with every message that the store sends given to a+-- function on its way.+tapped :: (Message -> IO ()) -> SockAddr -> (Conduits -> IO ()) -> IO ()+tapped seen sa f =+  withConnection sa $ \c -> f c {outboundConduit = frames B.empty .| c.outboundConduit}+  where+    frames :: ByteString -> ConduitT ByteString ByteString IO ()+    frames buf =+      await >>= \case+        Nothing -> return ()+        Just bs -> yield bs >> liftIO (split (buf <> bs)) >>= frames+    -- the messages whole in the bytes so far, and the bytes left over+    split buf+      | B.length buf < 24 = return buf+      | otherwise = case decode (B.take 24 buf) of+          Left _ -> return B.empty+          Right (MessageHeader _ _ len _) -> do+            let total = 24 + fromIntegral len+            if B.length buf < total+              then return buf+              else do+                forM_ (runGet (getMessage net) (B.take total buf)) seen+                split (B.drop total buf)++-- | Wait until the store has a block as its best, or one after it.+waitBlock :: Store -> BlockHash -> IO ()+waitBlock store h =+  waitUntil 120 ("the store to have block " <> T.unpack (blockHashToHex h)) $ do+    best <- Q.getBestBlock store.db+    case best of+      Nothing -> return False+      Just b+        | b == h -> return True+        | otherwise ->+            Q.getBlock store.db h >>= \case+              Just bd -> return (bd.height > 0)+              Nothing -> return False++waitUntil :: Int -> String -> IO Bool -> IO ()+waitUntil secs what check = go (secs * 4)+  where+    go n = do+      ok <- check+      unless ok $ do+        when (n <= 0) $ expectationFailure ("Gave up waiting for " <> what)+        threadDelay 250000+        go (n - 1)++one :: [Node] -> IO Node+one = \case+  [n] -> return n+  ns -> fail ("Expected one node, got " <> show (length ns))++-- | The last of the blocks that an RPC call mined.+lastOf :: [Text] -> BlockHash+lastOf hs = case reverse hs of+  h : _ -> fromMaybe (error ("Not a block hash: " <> T.unpack h)) (hexToBlockHash h)+  [] -> error "No block mined"++hashOf :: Text -> IO BlockHash+hashOf t = maybe (fail ("Not a block hash: " <> T.unpack t)) return (hexToBlockHash t)
+ test/Haskoin/Store/Fleet/AtomicSpec.hs view
@@ -0,0 +1,343 @@+module Haskoin.Store.Fleet.AtomicSpec (spec) where++import Control.Concurrent.Async (forConcurrently_)+import Control.Exception (throwIO, try)+import Control.Monad (forM_, replicateM_, void)+import Control.Monad.State.Strict (runState, state)+import Data.ByteString (ByteString)+import Data.ByteString.Char8 qualified as C+import Data.Functor.Identity (runIdentity)+import Data.IORef (atomicModifyIORef', newIORef)+import Data.Maybe (isJust)+import Database.Redis qualified as Redis+import Haskoin.Store.Fleet.Atomic+import Haskoin.Store.Fleet.Atomic.Redis+import Haskoin.Store.Integration.Valkey (redisContainer, redisURL)+import Haskoin.Store.Startup (redisConnectInfo)+import Test.Hspec+import Test.Hspec.QuickCheck (modifyMaxSuccess, prop)+import Test.Podman (podmanUsable, withContainer)+import Test.QuickCheck++spec :: Spec+spec = do+  describe "a decision, in the model of Redis" $ do+    modifyMaxSuccess (const 5000) $+      prop "sees what it wrote as Redis would say it, or says that it cannot tell" $+        forAll writesAndQuestion $ \(earlier, during, q) ->+          let db = foldl (flip perform) emptyDb (map (under "") earlier)+              ops = map (under "") during+              later = foldl (flip perform) db ops+              told' = runPure 0 (mapM_ write ops >> query (questionUnder "" q)) db+           in classify (either (const True) (const False) told') "cannot tell" $ case told' of+                Left _ -> property True+                Right (a, db') -> (a, db') === (answer later (questionUnder "" q), later)+    modifyMaxSuccess (const 5000) $+      prop "leaves Redis the same without the writes that a later one undoes" $+        forAll ((,) <$> listOf anOp <*> listOf anOp) $ \(earlier, during) ->+          let db = foldl (flip perform) emptyDb earlier+           in foldl (flip perform) db (tidy during) === foldl (flip perform) db during+    it "tells what it cannot tell, and no more than that" $ do+      let z = "z1"+          full = perform (HSet "h1" "a" "1") emptyDb+          cannot ops q = either (const True) (const False) (runPure 0 (mapM_ write ops >> query q) emptyDb)+      -- a member that may have been there+      cannot [ZAdd z 1 "a"] (ZCard z) `shouldBe` True+      cannot [ZRemRangeByRank z 0 0] (ZScore z "a") `shouldBe` True+      cannot [ZAdd z 1 "a"] (ZRangeByScore z MinusInf PlusInf (Just 1)) `shouldBe` True+      -- a key that was there, after a field was taken out of it+      either (const True) (const False) (runPure 0 (write (HDel "h1" "a") >> query (Exists "h1")) full)+        `shouldBe` True+      cannot [HDel "h1" "a"] (Exists "h1") `shouldBe` False+      -- and what it can+      cannot [ZAdd z 1 "a"] (ZRangeByScore z MinusInf PlusInf Nothing) `shouldBe` False+      cannot [ZAdd z 1 "a", ZRem z "a"] (ZScore z "a") `shouldBe` False+      cannot [HDel "h1" "a", HSet "h1" "b" "1"] (Exists "h1") `shouldBe` False+      cannot [Wipe "h", HIncrBy "h1" "c1" 2] (HGet "h1" "c1") `shouldBe` False+    it "writes to a key that a mark guards only while Redis has no mark, and depends on that" $ do+      let mark = "m1"+          marked = perform (HSet mark "t" "") emptyDb+          writing :: (Monad m) => Atomic m ()+          writing = guarding mark >> write (HSet "h1" "f" "v") >> write (HSet "h1" "g" "w")+          after = perform (HSet "h1" "g" "w") . perform (HSet "h1" "f" "v")+          inModel db = Backend {fetch = return . map (answer db), time = return 0}+      -- no mark: written, and the decision depends on there being none+      runPure 0 writing emptyDb `shouldBe` Right ((), after emptyDb)+      case runIdentity (runAtomic (inModel emptyDb) writing) of+        Decided () depends _ _ -> depends `shouldBe` [(Exists mark, Flag False)]+        Stuck why -> expectationFailure (show why)+      -- a mark: the decision is stopped, with nothing written+      either heldByMark (const False) (runPure 0 writing marked) `shouldBe` True+      -- a decision that says that it writes among marks does+      runPure 0 (unguarded >> writing) marked `shouldBe` Right ((), after marked)+      -- and the decision that wrote the mark itself goes on writing+      runPure 0 (write (HSet mark "t" "") >> writing) emptyDb `shouldBe` Right ((), after marked)+    it "depends on what it asked, and not on what it only had fetched" $ do+      let decision :: (Monad m) => Atomic m ()+          decision = prefetch [Get "s1", Get "n1"] >> void (get "s1")+      case runPure 0 decision emptyDb of+        Right ((), db) -> db `shouldBe` emptyDb+        Left why -> expectationFailure (show why)+    -- Redis is asked three times, and its clock is ten seconds later+    -- each time that it is read+    it "has one clock, however many times Redis is asked" $ do+      let decision :: (Monad m) => Atomic m (Integer, Integer)+          decision = do+            first <- clock+            a <- get "s1"+            b <- get (maybe "s2" (const "s3") a)+            _ <- get (maybe "n1" (const "n2") b)+            second <- clock+            return (first, second)+          ticking =+            Backend+              { fetch = return . map (answer (perform (Set "s1" "x") (perform (Set "s3" "y") emptyDb))),+                time = state (\t -> (t, t + 10000))+              }+      case runState (runAtomic ticking decision) 1000 of+        (Decided times _ _ rounds, _) -> (times, rounds) `shouldBe` ((1000, 1000), 3)+        (Stuck why, _) -> expectationFailure (show why)+    -- three keys, each holding the name of the next+    it "names questions ahead in steps, is gone through once, and depends on none of them" $ do+      let db = foldr perform emptyDb [Set "s1" "s2", Set "s2" "s3", Set "s3" "x"]+          naming next = \case+            Text (Just k) -> next k+            _ -> []+          steps = [Ahead (Get "s1") (naming (\a -> [Ahead (Get a) (naming (\b -> [Ahead (Get b) (const [])]))]))]+          decision :: (Monad m) => Atomic m (Maybe ByteString, Int)+          decision = do+            ready <- ahead steps+            -- a pass that is left, and one that is gone through+            if ready then (,1) <$> get "s3" else return (Nothing, 0)+          model = Backend {fetch = return . map (answer db), time = return 0}+      case runIdentity (runAtomic model decision) of+        Decided result depends _ rounds ->+          (result, map fst depends, rounds) `shouldBe` ((Just "x", 1), [Get "s3"], 3)+        Stuck why -> expectationFailure (show why)+  usable <- runIO podmanUsable+  describe "a decision, in Redis" $ case usable of+    Left why -> it "is carried out in one step" (pendingWith why)+    Right () -> aroundAll withRedis $ do+      -- Redis closes the connection of a command of more than 1,048,576+      -- arguments, which a decision reached as an argument for each word:+      -- the move of the tip over one block had 1,008,352.+      it "is carried out with more words than Redis takes arguments" $ \(conn, fresh) -> do+        p <- fresh+        let n = 280000 :: Int+            field i = C.pack (show (i :: Int))+            key i = p <> "h" <> field (i `mod` 7)+            large :: (Monad m) => Atomic m ()+            large = do+              was <- mapM (\i -> hget (key i) (field i)) [1 .. 2000]+              forM_ [1 .. n] $ \i -> write (HSet (key i) (field i) "v")+              write (Set (p <> "s1") (C.pack (show (length (filter isJust was)))))+        transact conn 1 large `shouldReturn` Just ()+        Right sizes <- Redis.runRedis conn (mapM (\i -> Redis.hlen (key i)) [0 .. 6] >>= return . sequence)+        sum sizes `shouldBe` toInteger n+        -- and again, with what it wrote to ask about+        transact conn 1 large `shouldReturn` Just ()+        Right said <- Redis.runRedis conn (Redis.get (p <> "s1"))+        said `shouldBe` Just "2000"+      modifyMaxSuccess (const 300) $+        it "finds Redis to say what the model says, after any writes" $ \(conn, fresh) ->+          property . forAll (listOf anOp) $ \during -> ioProperty $ do+            p <- fresh+            let ops = map (under p) during+                db = foldl (flip perform) emptyDb ops+                qs = map (questionUnder p) everyQuestion+            transact conn 1 (mapM_ write ops) `shouldReturn` Just ()+            Just answers <- transact conn 1 (queries qs)+            return (conjoin [counterexample (show q) (a === answer db q) | (q, a) <- zip qs answers])+      modifyMaxSuccess (const 300) $+        it "sees what it wrote as Redis says it afterwards" $ \(conn, fresh) ->+          property . forAll writesAndQuestion $ \(earlier, during, q) -> ioProperty $ do+            p <- fresh+            let (old, new, asked') = (map (under p) earlier, map (under p) during, questionUnder p q)+            transact conn 1 (mapM_ write old) `shouldReturn` Just ()+            planned <- (Just <$> plan conn (mapM_ write new >> query asked')) `orStuck` Nothing+            case planned of+              Nothing -> return (property True)+              Just told' -> do+                commit conn told' `shouldReturn` True+                Just [now] <- transact conn 1 (queries [asked'])+                return (told'.result === now)+      it "does not write to a key that a mark guards when the mark came after it was decided" $ \(conn, fresh) -> do+        p <- fresh+        let (mark, key) = (p <> "m1", p <> "h1")+            writing :: (Monad m) => Atomic m ()+            writing = guarding mark >> write (HSet key "f" "v")+        planned <- plan conn writing+        transact conn 1 (write (HSet mark "t" "")) `shouldReturn` Just ()+        carry conn planned `shouldReturn` Left (Exists mark)+        transact conn 1 (query (HGet key "f")) `shouldReturn` Just (Text Nothing)+        -- decided with the mark there, it is stopped before it writes+        stopped <- try (plan conn writing) :: IO (Either Failure (Planned ()))+        either (const True) (const False) stopped `shouldBe` True+        transact conn 1 (query (HGet key "f")) `shouldReturn` Just (Text Nothing)+      it "changes nothing when an answer that it depends on is no longer true" $ \(conn, fresh) -> do+        p <- fresh+        let (k, other, out) = (p <> "s1", p <> "s2", p <> "h1")+            decision :: (Monad m) => Atomic m (Maybe ByteString)+            decision = do+              v <- get k+              _ <- get other+              write (HSet out "a" "1")+              write (HSet out "seen" (maybe "nothing" id v))+              return v+        transact conn 1 (write (Set k "one")) `shouldReturn` Just ()+        stale <- plan conn decision+        stale.result `shouldBe` Just "one"+        -- another store changes what it read, before it is carried out+        transact conn 1 (write (Set k "two")) `shouldReturn` Just ()+        commit conn stale `shouldReturn` False+        transact conn 1 (hgetall out) `shouldReturn` Just mempty+        -- made again, it is carried out+        transact conn 3 decision `shouldReturn` Just (Just "two")+        transact conn 1 (hget out "seen") `shouldReturn` Just (Just "two")+        -- and what it did not ask about may change+        fine <- plan conn decision+        transact conn 1 (write (Set (p <> "s3") "x")) `shouldReturn` Just ()+        commit conn fine `shouldReturn` True+      it "notices a set or a hash that changed, in whatever order Redis lists it" $ \(conn, fresh) -> do+        p <- fresh+        let (g, h) = (p <> "g1", p <> "h1")+            members = [C.pack (show n) | n <- [1 .. 200 :: Int]]+            decision :: (Monad m) => Atomic m Int+            decision = do+              s <- smembers g+              m <- hgetall h+              write (Set (p <> "s1") "done")+              return (length s + length m)+        transact conn 1 (forM_ members (\x -> write (SAdd g x) >> write (HSet h x x))) `shouldReturn` Just ()+        same <- plan conn decision+        same.result `shouldBe` 400+        commit conn same `shouldReturn` True+        changed <- plan conn decision+        transact conn 1 (write (HSet h "7" "other")) `shouldReturn` Just ()+        commit conn changed `shouldReturn` False+        gone <- plan conn decision+        transact conn 1 (write (SRem g "200")) `shouldReturn` Just ()+        commit conn gone `shouldReturn` False+      it "loses no change when many decide at once" $ \(conn, fresh) -> do+        p <- fresh+        let k = p <> "n1"+            add :: (Monad m) => Atomic m ()+            add = do+              v <- get k+              write (Set k (C.pack (show (maybe (0 :: Integer) (maybe 0 fst . C.readInteger) v + 1))))+        forConcurrently_ [1 .. 8 :: Int] $ \_ ->+          replicateM_ 50 (transact conn 10000 add >>= (`shouldSatisfy` isJust))+        transact conn 1 (get k) `shouldReturn` Just (Just "400")+      it "reads the clock of Redis, in milliseconds" $ \(conn, _) -> do+        Just t <- transact conn 1 clock+        t `shouldSatisfy` (> 1700000000000)+  where+    -- a decision that asks what cannot be told is no failure of the test+    orStuck f x =+      try f >>= \case+        Right a -> return a+        Left (Faulty _) -> return x+        Left e -> throwIO e++-- | Writes before a decision, the writes of the decision, and a question:+-- all about a few keys, each of one kind.+writesAndQuestion :: Gen ([Op], [Op], Query)+writesAndQuestion = (,,) <$> listOf anOp <*> listOf anOp <*> elements everyQuestion++-- | A write to one of a few keys, each of the kind that the write is for:+-- a key is of the kind that the first letter of its name says.+anOp :: Gen Op+anOp =+  oneof+    [ Set "s1" <$> word,+      return (Del "s1"),+      IncrBy "n1" <$> choose (-3, 3),+      return (Del "n1"),+      HSet <$> hash <*> field <*> word,+      HDel <$> hash <*> field,+      HIncrBy <$> hash <*> return "c1" <*> choose (-3, 3),+      HDel <$> hash <*> return "c1",+      Del <$> hash,+      SAdd "g1" <$> word,+      SRem "g1" <$> word,+      return (Del "g1"),+      ZAdd <$> sorted <*> aScore <*> word,+      ZAddNX <$> sorted <*> aScore <*> word,+      ZRem <$> sorted <*> word,+      ZRemRangeByRank <$> sorted <*> choose (-3, 3) <*> choose (-3, 3),+      Del <$> sorted,+      XAdd "x1" 5 . pure . ("k",) <$> word,+      Wipe <$> elements ["h", "z", "s", "g1"]+    ]+  where+    hash = elements ["h1", "h2"]+    sorted = elements ["z1", "z2"]+    field = elements ["a", "b"]++word :: Gen ByteString+word = elements ["a", "b", "c", "", "\0\255", "a b"]++aScore :: Gen Score+aScore = fromIntegral <$> elements [-2, -1, 0, 1, 2, 1700000000000 :: Integer]++-- | Every question about the keys of 'anOp'.+everyQuestion :: [Query]+everyQuestion =+  [Get "s1", Get "n1", Exists "s1", Exists "x1", Exists "nothing"]+    <> concat+      [ [HGetAll h, HKeys h, HAbove h 0, HAbove h (-2), Exists h, HGet h "c1", HExists h "c1"]+          <> concat [[HGet h f, HExists h f] | f <- ["a", "b"]]+      | h <- ["h1", "h2"]+      ]+    <> [SMembers "g1", Exists "g1"]+    <> [SIsMember "g1" w | w <- words']+    <> concat+      [ [ZCard z, Exists z, ZRangeByScore z MinusInf PlusInf Nothing, ZRangeByScore z (At (-1)) (At 1) Nothing]+          <> [ZRangeByScore z MinusInf (At 1) (Just 2), ZRangeByScore z (At 2) PlusInf Nothing]+          <> [ZScore z w | w <- words']+      | z <- ["z1", "z2"]+      ]+  where+    words' = ["a", "b", "c", "", "\0\255", "a b"]++-- | A write to the same key under a prefix.+under :: ByteString -> Op -> Op+under p = \case+  Set k v -> Set (p <> k) v+  Del k -> Del (p <> k)+  IncrBy k n -> IncrBy (p <> k) n+  HSet k f v -> HSet (p <> k) f v+  HDel k f -> HDel (p <> k) f+  HIncrBy k f n -> HIncrBy (p <> k) f n+  SAdd k x -> SAdd (p <> k) x+  SRem k x -> SRem (p <> k) x+  ZAdd k s x -> ZAdd (p <> k) s x+  ZAddNX k s x -> ZAddNX (p <> k) s x+  ZRem k x -> ZRem (p <> k) x+  ZRemRangeByRank k a b -> ZRemRangeByRank (p <> k) a b+  XAdd k n fs -> XAdd (p <> k) n fs+  Wipe q -> Wipe (p <> q)++-- | A question about the same key under a prefix.+questionUnder :: ByteString -> Query -> Query+questionUnder p = \case+  Get k -> Get (p <> k)+  HGet k f -> HGet (p <> k) f+  HExists k f -> HExists (p <> k) f+  HGetAll k -> HGetAll (p <> k)+  HKeys k -> HKeys (p <> k)+  HAbove k n -> HAbove (p <> k) n+  SIsMember k x -> SIsMember (p <> k) x+  SMembers k -> SMembers (p <> k)+  ZScore k x -> ZScore (p <> k) x+  ZCard k -> ZCard (p <> k)+  ZRangeByScore k lo hi n -> ZRangeByScore (p <> k) lo hi n+  Exists k -> Exists (p <> k)++-- | A Valkey, and prefixes that no test has used.+withRedis :: ((Redis.Connection, IO ByteString) -> IO ()) -> IO ()+withRedis go =+  withContainer redisContainer $ \p -> do+    conn <- Redis.checkedConnect (either error id (redisConnectInfo (redisURL p)))+    counter <- newIORef (0 :: Int)+    go (conn, (\n -> C.pack ("t" <> show n <> ":")) <$> atomicModifyIORef' counter (\n -> (n + 1, n)))
test/Haskoin/Store/Fleet/CacheSpec.hs view
@@ -21,7 +21,8 @@ import Data.IntMap.Strict qualified as IntMap import Data.List (find, sortOn) import Data.List.NonEmpty (NonEmpty (..))-import Data.Maybe (catMaybes, fromMaybe)+import Data.Map.Strict qualified as Map+import Data.Maybe (catMaybes, fromMaybe, isJust) import Data.Serialize (encode) import Data.Time.Clock.POSIX (getPOSIXTime) import Data.Word (Word32, Word64, Word8)@@ -31,31 +32,39 @@     BlockHash,     BlockHeader (..),     BlockNode (..),+    NFToken (..),+    Network,     OutPoint (..),+    TokenCapability (..),+    TokenData (..),     Tx (..),     TxHash (..),     TxIn (..),     TxOut (..),     addressToScriptBS,+    bchRegTest,     btcRegTest,     buildMerkleRoot,     deriveXPubKey,     doubleSHA256,+    encodeTokenPrefix,     isValidPOW,     makeXPrvKey,+    maxTokenAmount,     nullOutPoint,     scriptToAddressBS,     txHash,   )-import Haskoin.Store.BlockStore (toFetch)-import Haskoin.Store.Common (StoreRead (..), sortTxs)+import Haskoin qualified as H+import Haskoin.Store.Common (Limits (..), Start (..), StoreRead (..), sortTxs) import Haskoin.Store.Data   ( BlockData (..),     BlockRef (..),     DeriveType (..),     Prev (..),+    TokenBalance (..),     TxData (..),-    TxRef,+    TxRef (..),     Unspent (..),     XPubBal,     XPubSpec (..),@@ -67,7 +76,7 @@ import Haskoin.Store.Database.Reader (DatabaseReader (..), Derived (..), derivedAddrs) import Haskoin.Store.Database.Views (withViewAt) import Haskoin.Store.Fleet.Member-import Haskoin.Store.Fleet.Redis (FleetKeys (..))+import Haskoin.Store.Fleet.Redis (FleetKeys (..), poolLeaving) import Haskoin.Store.Fleet.RedisSpec (withRedis) import Haskoin.Store.Fleet.XPub   ( Begun (..),@@ -81,7 +90,7 @@     xpubId,   ) import Haskoin.Store.Histories (openLayered, revert, run, startChain)-import Haskoin.Store.Integration.Podman (podmanUsable)+import Haskoin.Store.Ingest (Verdict (..)) import Haskoin.Store.Integration.Temp (withSystemTempDirectory) import Haskoin.Store.Logic (importBlock) import Haskoin.Store.TestBlocks (script)@@ -91,6 +100,7 @@ import Haskoin.Store.XPub.Service (Session (..), xpubAsk) import Test.Hspec import Test.Hspec.QuickCheck (modifyMaxSuccess)+import Test.Podman (podmanUsable) import Test.QuickCheck  spec :: Spec@@ -105,14 +115,21 @@       it "has a request answered again when the pool changes the entry it read" (`withBed` poolChangeTest)       it "has a request answered again when the tip moves" (`withBed` tipMoveTest)       it "never answers an entry that a move of the tip is writing" (`withBed` markedTest)+      it "answers a key without what a block took out of the pool, before the pool has let go of it" $+        (`withBed` leavingTest)+      it "answers a key without what a block made invalid, before the pool has let go of it" $+        (`withBed` conflictTest)       it "keeps the cache across a reorganisation, as the chain and the pool give it" (`withBed` reorgTest)       it "fills the pool again after Redis lost its data" (`withBed` refillTest)       it "fills the pool again after it started again, once after Redis lost its data" (`withBed` restartTest)       it "keeps what an abandoned block gave back when the chain moves under a move of the tip" $         (`withBed` unsettledTest)-      it "fetches no transaction that another member received" (`withBed` seenTest)+      it "counts as settled, for every member, what the pool has decided on" (`withBed` seenTest)       it "offers again a transaction that left the pool and is sent again" (`withBed` resendTest)-      it "lets go of an orphan whose parent did not come in twenty minutes" (`withBed` orphanTest)+      it "says which transaction an orphan waits for, and takes it after that one" (`withBed` orphanTest)+      it "looks at what no node of the operator vouches for, and takes anything that one does" $+        (`withBed` strangerTest)+      it "answers the tokens of the chain with what the pool does to them" (\r -> withBedOn bchRegTest r tokenTest)       modifyMaxSuccess (const 10) $         it "keeps every cached entry equal to the chain at the tip and the pool" $ \r ->           property $ \steps -> ioProperty (withBed r (\bed -> modelTest bed (take 12 steps)) >> return True)@@ -128,9 +145,9 @@   answers <- mapConcurrently (\i -> xpubAsk (if even i then bed.a else bed.b).door x) [1 .. 20 :: Int]   answers `shouldSatisfy` all (== Indexed)   threadDelay 300000-  -- one build, which Redis announced to both-  forM_ [bed.a, bed.b] $ \m ->-    (HashMap.lookupDefault 0 (xpubId x) <$> readTVarIO m.built) `shouldReturn` 1+  -- the requests that waited for the announcement are gone, and nothing of+  -- them is left: the map holds a key only while a request waits for it+  forM_ [bed.a, bed.b] $ \m -> HashMap.null <$> readTVarIO m.built `shouldReturn` True   forM_ [bed.a, bed.b] $ \m -> sameAsChain bed m x  retryTest :: Bed -> IO ()@@ -235,23 +252,22 @@   entries `shouldSatisfy` (> 0)   forM_ [bed.a, bed.b] $ \m -> sameAsChain bed m x --- | What one store received from a peer, it does not fetch again; another--- fetches it until the first has offered it to the pool, and not after:--- both ask the same set in Redis, which has only what the pool decided on.+-- | What the pool has decided on is settled for every store of the fleet,+-- which then does not fetch it when a peer names it: both ask the same+-- sets in Redis. What no store offered is not. seenTest :: Bed -> IO () seenTest bed = do   coin : _ <- coins bed   let tx = spend [coin] [(script, 100000)]       other = TxHash (doubleSHA256 ("never sent" :: ByteString))-      fetch m = toFetch (\_ -> return False) (memberSeen m) (\_ -> return False)-  fetch bed.b [txHash tx, other] `shouldReturn` [txHash tx, other]-  offer bed tx-  fetch bed.a [txHash tx, other] `shouldReturn` [other]-  fetch bed.b [txHash tx, other] `shouldReturn` [txHash tx, other]+      asked = [txHash tx, other]   settle bed+  memberSettled bed.a asked `shouldReturn` Just [False, False]+  memberSettled bed.b asked `shouldReturn` Just [False, False]+  offer bed tx   inPool bed tx `shouldReturn` True-  fetch bed.a [txHash tx, other] `shouldReturn` [other]-  fetch bed.b [txHash tx, other] `shouldReturn` [other]+  memberSettled bed.a asked `shouldReturn` Just [True, False]+  memberSettled bed.b asked `shouldReturn` Just [True, False]  -- | A transaction that a replacement pushed out of the pool, and that a -- peer sends again, takes its place back: a member that kept a set of what@@ -273,22 +289,64 @@   inPool bed first `shouldReturn` True   inPool bed second `shouldReturn` False --- | Orphans wait for their parent for twenty minutes from when the member--- heard of them, and are then let go.+-- | A transaction that only strangers named is looked at before it is+-- offered ('memberOfferTimed' with no voucher): one whose signature does+-- not verify is forged, one that spends a coin locked by a script cannot+-- be verified, and neither is in the pool after. One that spends a coin+-- locked to a key, with the signature of that key, is taken.+--+-- The same transactions with a voucher are all taken, the forged one+-- too: a node of the operator took them, and the store takes what its+-- node takes. That is what became of every transaction, from any peer,+-- before the store told its own nodes from strangers.+strangerTest :: Bed -> IO ()+strangerTest bed = do+  coin : _ <- coins bed+  now <- round <$> getPOSIXTime+  let key = fromMaybe (error "No key") (H.secKey (B.replicate 31 0 <> "\x07"))+      toKey = H.PayPKHash (H.addressHash (H.exportPubKey True (H.derivePubKey key)))+      keyScript = H.encodeSerial toKey+      -- pay to the hash of a script: only a node runs the script+      toScript = "\xa9\x14" <> B.replicate 20 7 <> "\x87"+      fund = spend [coin] [(keyScript, 100000), (keyScript, 100000), (toScript, 100000)]+      out = OutPoint (txHash fund)+      pay n = Tx 1 [TxIn (out n) "" maxBound] [TxOut 90000 script] [] 0+      allOf = if isJust bed.net.sigHashForkId then H.setForkIdFlag H.sigHashAll else H.sigHashAll+      sign n = either error id (H.signTx bed.net (pay n) [H.SigInput toKey 100000 (out n) allOf Nothing] [key])+      good = sign 0+      -- signed, and then made to pay a satoshi less+      forged = (sign 1) {outputs = [TxOut 89999 script]} :: Tx+      scripted = pay 2+      offer vouched tx = fst <$> memberOfferTimed bed.a vouched now tx+  settle bed+  memberOffer bed.a now fund `shouldReturn` Settled+  offer False forged `shouldReturn` Forged+  offer False scripted `shouldReturn` Unverified+  mapM (inPool bed) [forged, scripted] `shouldReturn` [False, False]+  offer False good `shouldReturn` Settled+  inPool bed good `shouldReturn` True+  -- vouched for, they are taken as they are+  offer True scripted `shouldReturn` Settled+  offer True forged `shouldReturn` Settled+  mapM (inPool bed) [forged, scripted] `shouldReturn` [True, True]+  -- and what the pool has is not doubted, whoever names it again+  offer False scripted `shouldReturn` Settled++-- | A transaction offered before the one that it spends from is an+-- orphan, and the member says which transaction it lacks: what the path+-- into the pool waits for before it offers the orphan again+-- ("Haskoin.Store.Ingest"). orphanTest :: Bed -> IO () orphanTest bed = do   coin : _ <- coins bed   now <- round <$> getPOSIXTime   let parent = spend [coin] [(script, 100000)]-      child v = Tx 1 [TxIn (OutPoint (txHash parent) 0) "" maxBound] [TxOut v script] [] 0-      old = child 1000-      young = child 2000-  memberReceived bed.a (now - 1201) old-  memberReceived bed.a now young+      child = Tx 1 [TxIn (OutPoint (txHash parent) 0) "" maxBound] [TxOut 1000 script] [] 0   settle bed-  held <- readTVarIO bed.a.waiting-  HashMap.member (txHash old) held `shouldBe` False-  HashMap.member (txHash young) held `shouldBe` True+  memberOffer bed.a now child `shouldReturn` Orphan [txHash parent]+  memberOffer bed.a now parent `shouldReturn` Settled+  memberOffer bed.a now child `shouldReturn` Settled+  inPool bed child `shouldReturn` True  -- | Each member counts a refill when the pool starts again, which the count -- of restarts says; and one only, not two, when Redis loses its data with@@ -354,7 +412,7 @@     Redis.hdel bed.a.keys.recent ("b" :| [])   -- the block of the payment is reverted, and the store reports its parent   revert bed.db >> noted bed-  report bed.a+  void (report bed.a)   -- and reverts the parent too before it moves the tip   revert bed.db   moveTip bed.a `shouldReturn` False@@ -430,13 +488,90 @@       tip <- fleetTipOf bed       join <$> answeringCached m tip (\_ sess _ -> seenIn sess x) +-- | The token balances, holders, transactions and unspent outputs of a+-- category, from the chain with the pool on top (CashTokens). A block makes+-- a supply of the largest amount and a non-fungible token; in the pool the+-- supply moves twice, which sums that counted it each time would not hold.+-- Once a block confirms the pool, the chain alone gives what the pool did.+tokenTest :: Bed -> IO ()+tokenTest bed = do+  c : _ <- coins bed+  let cat = c.outpoint.hash+      (alice, bob, carol) = (p2pkh 0x11, p2pkh 0x22, p2pkh 0x33)+      p2pkh n = "\x76\xa9\x14" <> B.replicate 20 n <> "\x88\xac"+      holding amount nft lock = fromMaybe (error "Bad tokens") (encodeTokenPrefix (TokenData cat amount nft)) <> lock+      addr lock = either error id (scriptToAddressBS bed.net lock)+      most = maxTokenAmount+      badge = Just (NFToken MutableCapability "x")+      minted = spend [c] [(holding most Nothing alice, 1000000), (holding 0 badge bob, 1000000)]+      -- one input and some outputs+      tx p outs = Tx 1 [TxIn p "" maxBound] [TxOut v lock | (lock, v) <- outs] [] 0+      moved =+        tx+          (OutPoint (txHash minted) 0)+          [(holding 1000 Nothing bob, 400000), (holding (most - 1000) Nothing alice, 400000)]+      onward = tx (OutPoint (txHash moved) 1) [(holding (most - 1000) Nothing carol, 300000)]+  mineBlock bed [minted]+  settle bed+  offer bed moved+  settle bed+  offer bed onward+  settle bed+  poolTxs bed >>= \txs -> map txHash txs `shouldMatchList` map txHash [moved, onward]+  let balance lock inBlocks unconfirmed nfts utxo txs received =+        TokenBalance+          { address = addr lock,+            category = cat,+            confirmedTokens = inBlocks,+            unconfirmedTokens = unconfirmed,+            nfts,+            tokenUtxo = utxo,+            tokenTxs = txs,+            receivedTokens = received+          }+      unsettled =+        [ balance alice 0 0 0 0 3 (most + most - 1000),+          balance bob 0 1000 1 2 2 1000,+          balance carol 0 (most - 1000) 0 1 1 (most - 1000)+        ]+      byAddress = sortOn (encode . (.address))+  -- an address: what the block gave it, with what the pool did+  forM_ unsettled $ \b -> atTip bed (\q -> q.getAddressTokens b.address) `shouldReturn` [b]+  -- the holders, in the order of their addresses, by the page+  atTip bed (\q -> q.getTokenHolders cat def) `shouldReturn` byAddress unsettled+  atTip bed (\q -> q.getTokenHolders cat def {offset = 1, limit = 1})+    `shouldReturn` take 1 (drop 1 (byAddress unsettled))+  -- the transactions: the two of the pool, then the block's+  txs <- atTip bed (\q -> q.getTokenTxs cat def)+  map (.txid) (take 2 txs) `shouldMatchList` map txHash [moved, onward]+  map (.txid) (drop 2 txs) `shouldBe` [txHash minted]+  -- from one of the pool: the page starts there+  later <- atTip bed (\q -> q.getTokenTxs cat def {start = Just (AtTx (txs !! 1).txid)})+  map (.txid) later `shouldBe` map (.txid) (drop 1 txs)+  -- the unspent outputs: those that the pool makes and keeps, then the+  -- block's that the pool does not spend+  outs <- atTip bed (\q -> q.getTokenUnspents cat def)+  map (.outpoint) (take 2 outs) `shouldMatchList` [OutPoint (txHash moved) 0, OutPoint (txHash onward) 0]+  map (.outpoint) (drop 2 outs) `shouldBe` [OutPoint (txHash minted) 1]+  map (.address) outs `shouldMatchList` map (Just . addr) [bob, carol, bob]+  -- confirmed, the chain alone gives the same, with what was unconfirmed+  -- now confirmed+  mineBlock bed [moved, onward]+  settle bed+  poolTxs bed `shouldReturn` []+  let settled = [b {confirmedTokens = b.confirmedTokens + b.unconfirmedTokens, unconfirmedTokens = 0} | b <- unsettled]+  forM_ settled $ \b -> atTip bed (\q -> q.getAddressTokens b.address) `shouldReturn` [b]+  outs' <- atTip bed (\q -> q.getTokenUnspents cat def)+  map (.outpoint) outs' `shouldMatchList` map (.outpoint) outs+ ------------------------------------------------------------------------------- -- The test bed -------------------------------------------------------------------------------  -- | Two members of a fleet on one database and one Redis. data Bed = Bed-  { conn :: !Redis.Connection,+  { net :: !Network,+    conn :: !Redis.Connection,     prefix :: !ByteString,     db :: !DatabaseReader,     a :: !Member,@@ -447,15 +582,19 @@ -- | A new chain with a few blocks of coins, in a new database, and two -- members on keys of Redis that no other test uses, with their indexers. withBed :: (Redis.Connection, IO FleetKeys) -> (Bed -> IO x) -> IO x-withBed (conn, fresh) go = do+withBed = withBedOn btcRegTest++-- | 'withBed' on a network.+withBedOn :: Network -> (Redis.Connection, IO FleetKeys) -> (Bed -> IO x) -> IO x+withBedOn net (conn, fresh) go = do   keys <- fresh   withSystemTempDirectory "haskoin-store-fleet-cache" $ \dir ->-    openLayered btcRegTest dir $ \db -> do+    openLayered net dir $ \db -> do       startChain db       a <- newMember (config keys.prefix "a") conn db       b <- newMember (config keys.prefix "b") conn db       salt <- newIORef 0-      let bed = Bed {conn, prefix = keys.prefix, db, a, b, salt}+      let bed = Bed {net, conn, prefix = keys.prefix, db, a, b, salt}       withAsync (memberCacheLoop a) $ \_ ->         withAsync (memberCacheLoop b) $ \_ -> do           noted bed@@ -490,6 +629,99 @@  -- | Both members take a view of the best block, as the block store has -- them do after each block.+-- | A block confirms a transaction of the pool at an address of a cached+-- key, and the store that moves the tip stops right after: the+-- transaction is marked as leaving, and still in the pool. The chain at+-- the tip has it, and so has the entry; what the pool keeps for the+-- address still counts it. A read of the key takes it out, and answers+-- what the chain and the pool give.+--+-- The address is one that the key has used already, so that the entry+-- has the addresses that a scan of the key finds, and is the one read:+-- with a new address the entry is a miss, the key is read address by+-- address, and this would pass without the cache taking anything out.+leavingTest :: Bed -> IO ()+leavingTest bed = do+  let x = xpub 9+  payKey bed x [0] True+  xpubAsk bed.a.door x `shouldReturn` Indexed+  dest <- addressScript bed x 0+  c : other : _ <- filter ((> 101000) . (.value)) <$> coins bed+  -- one that the block confirms, and one that stays in the pool: while+  -- the pool has a transaction at the key, what it keeps for each+  -- address is read+  let tx = spend [c] [(dest, 100000)]+      staying = spend [other] [(dest, 100000)]+  offer bed tx+  offer bed staying+  settle bed+  inPool bed tx `shouldReturn` True+  sameAsChain bed bed.a x+  -- the block, and a move of the tip with nothing after it+  mineBlock bed [tx]+  noted bed+  forM_ [bed.a, bed.b] (\m -> report m `shouldReturn` True)+  moveTip bed.a `shouldReturn` True+  poolLeaving bed.conn bed.a.keys `shouldReturn` [encode (txHash tx)]+  -- the entry is read, which takes the transaction out+  tip <- fleetTipOf bed+  cachedEntry bed.conn bed.a.keys tip bed.db.initGap bed.db.maxGap True x >>= \case+    Hit _ -> return ()+    _ -> expectationFailure "The entry of the key was not answered"+  poolLeaving bed.conn bed.a.keys `shouldReturn` []+  sameAsChain bed bed.a x+  settle bed+  sameAsChain bed bed.b x++-- | A block confirms a transaction that the pool never had, and that+-- spends what a transaction of the pool spends: the one of the pool pays+-- an address of a cached key, and is no longer valid. The store that+-- moves the tip stops right after, so it is marked as leaving and still+-- in the pool, with what it pays the key.+--+-- The chain does not have it and never will, so nothing of the chain's+-- side of the entry says that it is gone: only the mark does. A read of+-- the key takes it out, and answers what the chain and the pool give,+-- without the payment.+conflictTest :: Bed -> IO ()+conflictTest bed = do+  let x = xpub 11+  payKey bed x [0] True+  xpubAsk bed.a.door x `shouldReturn` Indexed+  dest <- addressScript bed x 0+  away <- addressScript bed (xpub 12) 0+  c : other : _ <- filter ((> 101000) . (.value)) <$> coins bed+  let loser = spend [c] [(dest, 100000)]+      winner = spend [c] [(away, 90000)]+      staying = spend [other] [(dest, 100000)]+  offer bed loser+  offer bed staying+  settle bed+  inPool bed loser `shouldReturn` True+  sameAsChain bed bed.a x+  before <- expected bed x+  -- the block with the other spend of the same coin, and a move of the+  -- tip with nothing after it+  mineBlock bed [winner]+  noted bed+  forM_ [bed.a, bed.b] (\m -> report m `shouldReturn` True)+  moveTip bed.a `shouldReturn` True+  poolLeaving bed.conn bed.a.keys `shouldReturn` [encode (txHash loser)]+  -- the entry is read, which takes the transaction out+  tip <- fleetTipOf bed+  cachedEntry bed.conn bed.a.keys tip bed.db.initGap bed.db.maxGap True x >>= \case+    Hit _ -> return ()+    _ -> expectationFailure "The entry of the key was not answered"+  poolLeaving bed.conn bed.a.keys `shouldReturn` []+  sameAsChain bed bed.a x+  inPool bed loser `shouldReturn` False+  inPool bed staying `shouldReturn` True+  -- and the key no longer has what the transaction paid it+  after <- expected bed x+  after `shouldNotBe` before+  settle bed+  sameAsChain bed bed.b x+ noted :: Bed -> IO () noted bed = best bed >>= \h -> mapM_ (`noteBest` h) [bed.a, bed.b] @@ -520,7 +752,7 @@       included = coinbase : map snd (sortTxs txs)       merkle = either error id (buildMerkleRoot (map txHash included))       candidate = BlockHeader 0x20000000 h merkle (parent.header.timestamp + 600) parent.header.bits-      header = fromMaybe (error "No nonce") (find (isValidPOW btcRegTest) (map candidate [0 ..]))+      header = fromMaybe (error "No nonce") (find (isValidPOW bed.net) (map candidate [0 ..]))   run bed.db (\w -> importBlock w (Block header included) (BlockNode header height 0 h))     >>= either (fail . show) (void . return)   noted bed@@ -543,7 +775,7 @@ -- not spend. coins :: Bed -> IO [Unspent] coins bed = do-  let coinAddress = either error id (scriptToAddressBS btcRegTest script)+  let coinAddress = either error id (scriptToAddressBS bed.net script)   filter (confirmed . (.block)) <$> atTip bed (\q -> q.getAddressUnspents coinAddress def)  -- | The output script of an address of the external chain of a key.@@ -573,11 +805,19 @@       if inBlock then mineBlock bed [tx] else offer bed tx       settle bed --- | Hand a transaction to member a, as a peer would.+-- | Offer a transaction to the pool through member a, as the path into+-- the pool does with what a peer sent: the pool has it, unless it is an+-- orphan. A member that has no view of the fleet tip yet takes a turn+-- first. offer :: Bed -> Tx -> IO ()-offer bed tx = do-  now <- round <$> getPOSIXTime-  memberReceived bed.a now tx+offer bed tx = go (5 :: Int)+  where+    go n = do+      now <- round <$> getPOSIXTime+      memberOffer bed.a now tx >>= \case+        Again | n > 0 -> settle bed >> go (n - 1)+        Again -> expectationFailure "The member could not offer a transaction"+        _ -> return ()  -- | Whether the pool has a transaction. inPool :: Bed -> Tx -> IO Bool
+ test/Haskoin/Store/Fleet/DecideSpec.hs view
@@ -0,0 +1,773 @@+-- | The decisions of the shared mempool ("Haskoin.Store.Fleet.Pool.Decide")+-- beside the script that they replace ("Haskoin.Store.Fleet.Oracle"), in+-- a Redis: the same steps by each, under two prefixes, and all that Redis+-- has under each compared after every step.+module Haskoin.Store.Fleet.DecideSpec (spec, Dump, everything) where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (withAsync)+import Control.Monad (foldM_, forM, forM_, forever, unless, void, when)+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.Either (isLeft)+import Data.Foldable (toList)+import Data.Functor.Identity (runIdentity)+import Data.List (sort)+import Data.List.NonEmpty qualified as NonEmpty+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe)+import Data.Sequence qualified as Seq+import Data.Serialize (encode)+import Data.Set qualified as Set+import Data.Word (Word32)+import Database.Redis qualified as Redis+import Haskoin.Store.Fleet.Atomic+  ( Atomic,+    Backend (..),+    Db,+    Op (..),+    Outcome (..),+    Value (..),+    answer,+    emptyDb,+    perform,+    runAtomic,+    runPure,+  )+import Haskoin.Store.Fleet.Atomic.Redis (Planned (..), carry, plan, transact)+import Haskoin.Store.Fleet.Oracle+import Haskoin.Store.Fleet.Pool.Decide qualified as D+import Haskoin.Store.Fleet.Redis+import Haskoin.Store.Fleet.RedisSpec (PoolStep (..), address, block, number, out, timeOf, txOf, withRedis)+import Haskoin.Store.Fleet.XPub (Begun (..), cacheBeat, cacheBegin)+import Haskoin.Store.Fleet.XPub.Decide qualified as X+import Test.Hspec+import Test.Hspec.QuickCheck (modifyMaxSuccess, prop)+import Test.Podman (podmanUsable)+import Test.QuickCheck++spec :: Spec+spec = do+  describe "a move of the tip, in the model of Redis" $ do+    modifyMaxSuccess (const 2000) $+      prop "has no answer changed by what others decide, for as long as its store says that it is at it" $+        \earlier during confirmed -> undisturbed Kept earlier during confirmed+    modifyMaxSuccess (const 2000) $+      prop "has answers changed by them ten seconds after its store last said so" $+        \earlier during confirmed -> expectFailure (undisturbed Silent earlier during confirmed)+    modifyMaxSuccess (const 2000) $+      prop "has answers changed by them when no store has the floor" $+        \earlier during confirmed -> expectFailure (undisturbed Free earlier during confirmed)+  -- The move that only marks what leaves the pool, against the one that+  -- takes it out in its own step: in the model, where thousands of+  -- histories take a minute, and with the others trying to write between+  -- two takings out. A group of its own, and so a process of its own. It+  -- passed ten thousand histories when it was written, and found in the+  -- first thousand what three hundred against Redis had not: that a+  -- count can end as a zero or as nothing ('marking').+  describe "the pool after a move of the tip, in the model of Redis" $+    modifyMaxSuccess (const 3000) $+      prop "lets go of what was marked, and ends as after the move that took it out, whatever others try" $+        \earlier during confirmed used order -> marking earlier during confirmed used order+  usable <- runIO podmanUsable+  -- a group of its own, and so a process of its own: it takes its time+  describe "the floor, in Redis" $ case usable of+    Left why -> it "is the store's for as long as it says that it is at its move" (pendingWith why)+    Right () -> aroundAll withRedis $ do+      it "is the store's for as long as it says that it is at its move: a move is carried out after twelve seconds" $+        \(conn, fresh) -> longMove True conn =<< fresh+      it "is the store's for ten seconds if it says nothing: a move is refused after twelve" $+        \(conn, fresh) -> longMove False conn =<< fresh+  describe "the shared mempool in Redis" $ case usable of+    Left why -> it "is decided in Haskell as the script decides it" (pendingWith why)+    Right () -> aroundAll withRedis $ do+      it "moves the tip over a full block while transactions are offered, stores report and keys are built" $+        \(conn, fresh) -> crowded conn =<< fresh+      -- The move names what it will ask before it is gone through+      -- ('Haskoin.Store.Fleet.Pool.Decide.foreseen'), in steps: the tip;+      -- what is asked of each transaction; what is asked of its addresses+      -- and which its children are; what is asked of the children and of+      -- the cached keys at its addresses; and what the children spend+      -- from. Then it is gone through once. A question of the move that+      -- is not named there makes these numbers one more, and the move of+      -- a full block a pass longer, which is seconds on a server.+      it "asks Redis no more times about a large block than about a small one" $ \(conn, fresh) -> do+        let asked related n = do+              keys <- fresh+              let txs = map blockTx [1 .. n]+                  -- transactions of the pool, each with a child, that+                  -- spend what a transaction of the block spends, which+                  -- the pool never had+                  rivals = [blockTx c | related, c <- [9001 .. 9010]]+                  winners = [(encode (8000000 + i :: Word32), o) | (i, r) <- zip [1 ..] rivals, o <- r.inputs]+                  change =+                    PoolChange+                      { returned = [],+                        gone = [],+                        confirmed = map (.txid) txs <> map fst winners,+                        spent =+                          [o <> tx.txid <> encode (100 :: Word32) | tx <- txs, o <- tx.inputs]+                            <> [o <> t <> encode (100 :: Word32) | (t, o) <- winners],+                        height = Just 100,+                        lost = []+                      }+                  move :: (Monad m) => Atomic m Moved+                  move =+                    D.advance+                      (D.poolKeys keys.prefix 4)+                      Nothing+                      (block 77)+                      Nothing+                      keys.size+                      (D.Changing change)+                      []+                      "token"+                  cached :: (Monad m) => Atomic m X.Step+                  cached =+                    X.build+                      (X.cacheKeys keys.prefix)+                      ""+                      "key1"+                      (0, 0)+                      1+                      [X.Addition {address = "addr3", path = "\0\0\0\0\0", balance = "", txs = [], outs = []}]+              forM_ txs $ \tx -> poolOffer conn keys 4 Nothing tx [True] [] `shouldReturn` Taken+              when related $ do+                -- one in four has a child that stays, a cached key has+                -- one of the addresses, and ten transactions with their+                -- children spend what the block spends+                forM_ [c | c <- [1 .. n], c `mod` 4 == 0] $ \c ->+                  poolOffer conn keys 4 Nothing (childTx c) [False] [] `shouldReturn` Taken+                forM_ rivals $ \r -> do+                  poolOffer conn keys 4 Nothing r [True] [] `shouldReturn` Taken+                  poolOffer conn keys 4 Nothing (childTx (number r.txid)) [False] [] `shouldReturn` Taken+                void (transact conn 1 cached)+              fleetReport conn keys Nothing 60000 "a" [block 77] [] `shouldReturn` True+              cacheBegin conn keys "token" "" `shouldReturn` Begun+              planned <- plan conn move+              planned.result `shouldBe` MovedTo (block 77)+              return planned.rounds+        mapM (asked False) [40, 400] `shouldReturn` [3, 3]+        -- one less than when the move took them out itself: it asks+        -- nothing of the addresses of what leaves+        mapM (asked True) [40, 400] `shouldReturn` [4, 4]+      -- A move marks what leaves the pool, and a read that would go by+      -- a marked transaction takes it out first. So whatever is read+      -- between the move and the end of the taking out is what is read+      -- once all of it is out: here every kind of read, of every address,+      -- transaction and output of these histories, from a pool that has+      -- only been marked, against the same pool with everything out.+      modifyMaxSuccess (const 300) $+        it "is read while a block's transactions leave as it is read once they are out" $ \(conn, fresh) ->+          property $ \steps -> ioProperty $ do+            marked <- fresh+            out' <- fresh+            foldM_ (reading conn marked out') (Nothing, 0) (steps :: [PoolStep])+      modifyMaxSuccess (const 300) $+        it "is decided in Haskell as the script decides it, state by state" $ \(conn, fresh) ->+          property $ \steps -> ioProperty $ do+            lua <- fresh+            ours <- fresh+            forM_ [lua, ours] (watched conn)+            foldM_ (both conn lua ours) ([], [], Nothing, 0) (steps :: [PoolStep])++-- | A move of the tip that is carried out twelve seconds after it was+-- decided, as that of a full block is on a slow machine, while+-- transactions that spend from those of the block are offered without a+-- pause, and with leases of ten seconds, as stores have them.+--+-- The store says every two seconds that it is at its move, as a member+-- does (@moveTip@), or says nothing. Saying it, it keeps the floor and+-- the move is carried out. Saying nothing, it has the floor for ten+-- seconds, the transactions are taken after that, and the move is+-- refused: what happened on a server at every block, the floor lasting+-- ten seconds from when it was taken.+longMove :: Bool -> Redis.Connection -> FleetKeys -> IO ()+longMove saying conn keys = do+  forM_ txs $ \tx -> poolOffer conn keys 4 Nothing tx [True] [] `shouldReturn` Taken+  fleetReport conn keys Nothing 10000 "a" [target] [] `shouldReturn` True+  cacheBegin conn keys "token" "" `shouldReturn` Begun+  poolOffer conn keys 4 Nothing (childTx 1) [False] [] `shouldReturn` Late+  planned <- plan conn move+  planned.result `shouldBe` MovedTo target+  carried <-+    withAsync (forM_ (cycle [1 .. n]) (\c -> offered c >> threadDelay 5000)) $ \_ ->+      withAsync (when saying (forever (threadDelay 2000000 >> cacheBeat conn keys "token"))) $ \_ -> do+        threadDelay 12000000+        carry conn planned+  if saying+    then do+      carried `shouldBe` Right ()+      fleetTip conn keys `shouldReturn` Just target+      cacheBeat conn keys "token" `shouldReturn` False+    else do+      carried `shouldSatisfy` isLeft+      fleetTip conn keys `shouldReturn` Nothing+  where+    n = 200 :: Word32+    target = block 77+    txs = map blockTx [1 .. n]+    offered c = void (poolOffer conn keys 4 Nothing (childTx c) [False] [])+    move :: (Monad m) => Atomic m Moved+    move =+      D.advance+        (D.poolKeys keys.prefix 4)+        Nothing+        target+        Nothing+        keys.size+        -- the move that takes everything out in one step, as a move+        -- that undoes a block still does: the long decision is what+        -- the floor is for. One that only marks what leaves depends on+        -- nothing that these offers change, and is not refused.+        (D.AtOnce (PoolChange [] [] (map (.txid) txs) [] (Just 100) []))+        []+        "token"++-- | A transaction that spends the output of one of a block, at its+-- address.+childTx :: Word32 -> PoolTx+childTx c =+  PoolTx+    { txid = encode (5000000 + c),+      time = 1700009000,+      inputs = [encode c <> encode (0 :: Word32)],+      body = B.replicate 250 7,+      entries =+        [ PoolTouches (C.pack ("addr" <> show c)),+          PoolSpends (C.pack ("addr" <> show c)) (encode c <> encode (0 :: Word32)) 1000+        ]+    }++-- | A transaction of a block, with an address of its own and one that it+-- shares with the next.+blockTx :: Word32 -> PoolTx+blockTx c =+  PoolTx+    { txid = encode c,+      time = 1700000000 + fromIntegral c,+      inputs = [encode (1000000 + c) <> encode (0 :: Word32)],+      body = B.replicate 250 7,+      entries =+        [ PoolTouches (addr c),+          PoolPays (addr c) (encode c <> encode (0 :: Word32)) 1000 "script",+          PoolTouches (addr (c + 1)),+          PoolSpends (addr (c + 1)) (encode (1000000 + c) <> encode (0 :: Word32)) 1000+        ]+    }+  where+    addr a = C.pack ("addr" <> show a)++-- | What the store that moves the tip does for the floor.+data Floor+  = -- | nothing: it moves the tip without a move of the cache+    Free+  | -- | it takes it, and says nothing after+    Silent+  | -- | it takes it, and says every seven seconds that it is at its move+    Kept++-- | A move of the tip is decided, and before it is carried out other+-- decisions are, seven seconds after each other: transactions offered,+-- withdrawn and expired, what the fleet saw trimmed, entries of the cache+-- built, dropped and evicted, another store that tries to move the tip,+-- and one that renews its lease. Every answer that the move depends on+-- must be the same after them: then the script carries the move out,+-- whatever the others did.+--+-- With the floor kept ('Haskoin.Store.Fleet.XPub.Decide.beat'), that+-- holds, however long the others go on: all of them give way, and what+-- the store says to keep the floor changes no answer of its own move.+-- With the floor taken and nothing said after, it does not: the others+-- stop giving way after ten seconds, which is how the tip of a server+-- stayed where it was, its move taking longer than that to decide. Nor+-- does it without the floor. The last two properties say so, so that the+-- first is known to see what it is for.+undisturbed :: Floor -> [PoolStep] -> [PoolStep] -> [Word32] -> Property+undisturbed how earlier during confirmed =+  case runIdentity (runAtomic (inModel begun) move) of+    Stuck why -> counterexample (show why) False+    Decided _ depends _ _ ->+      conjoin [counterexample (show q) (answer later q === a) | (q, a) <- depends]+  where+    now = 5000+    k = D.poolKeys "" 4+    kx = X.cacheKeys ""+    target = block 1000+    inModel db = Backend {fetch = return . map (answer db), time = return now}+    held = case how of+      Free -> False+      _ -> True+    -- two live stores that agree on the block, cached keys at three of+    -- the four addresses, and a pool+    start =+      foldl+        (flip perform)+        emptyDb+        ( [HSet "fleet:lease" store "900000" | store <- ["a", "b"]]+            <> [HSet "fleet:recent" store target | store <- ["a", "b"]]+            <> [SAdd ("fx:of:" <> address a) i | (a, ids) <- [(0, ["x1"]), (1, ["x1", "x2"]), (2, ["x2"])], i <- ids]+        )+    pool = foldl (flip (others now)) start earlier+    begun = if held then decided now (X.begin kx "mover" "") pool else pool+    move :: (Monad m) => Atomic m Moved+    move =+      D.advance+        k+        Nothing+        target+        (Just now)+        4+        (D.Changing (PoolChange [] [] (map block confirmed) [] (Just 100) []))+        []+        (if held then "mover" else "")+    -- the other store renews its lease, and the rest decide, each seven+    -- seconds after the one before, the store of the move saying a second+    -- before each that it is at it, if it does+    later = foldl next (perform (HSet "fleet:lease" "b" "950000") begun) (zip [1 ..] during)+    next db (i, step) =+      let at = now + 7000 * i+       in others at step $ case how of+            Kept -> decided (at - 1000) (X.beat kx "mover") db+            _ -> db+    decided :: Integer -> (forall m. (Monad m) => Atomic m a) -> Db -> Db+    decided at decision db = either (error . show) snd (runPure at decision db)+    others :: Integer -> PoolStep -> Db -> Db+    others at step = case step of+      Give t inputs replaced ->+        let outs = [(out a i, ok) | (a, i, ok) <- nubOrdOn (\(a, i, _) -> (a, i)) inputs, a < t]+         in decided at (D.offer k Nothing (map snd outs) (map block replaced) (txOf t (map fst outs)))+      Take ts -> decided at (D.withdraw k (map block ts))+      Go back dead done _ ->+        decided at (D.expire k (toInteger (timeOf (sum dead))) (length done + 1))+          . decided at (X.evict kx (length done))+          . decided at (X.drop kx "x1")+          . decided at (X.build kx "" "x3" (0, 0) 1 [added (sum dead)])+          . decided at (X.begin kx "other" "")+          . decided at (X.piece kx "other" "" [X.Piece (address (fromIntegral (length back))) "" [] [] [] []])+          . decided at (X.abort kx "other")+    added a = X.Addition {address = address a, path = "\0\0\0\0\0", balance = "", txs = [], outs = []}++-- | A pool, and a move of the tip over a block that confirms some+-- transactions and spends some outputs, made twice: taking everything out+-- in its own step, and marking what leaves, which is then taken out in an+-- order and in pieces that the test chooses.+--+-- While a transaction is marked, the others change nothing: an offer, a+-- withdrawal, an expiry, and the building, dropping and evicting of an+-- entry of the cache each leave Redis as it was. And once the last is+-- out, Redis has what the move in one step left, the events in another+-- order: a block is told before what it replaced is told as gone.+marking :: [PoolStep] -> [PoolStep] -> [Word32] -> [(Word32, Word32)] -> [Int] -> Property+marking earlier during confirmed used order =+  conjoin+    [ counterexample "the others changed Redis while a transaction was marked" quiet,+      counterexample "marks are left" (Map.notMember "pool:leaving" after),+      counterexample (show differing) (null differing)+    ]+  where+    -- the keys that the two do not end with the same in: marked and+    -- taken out first, in one step second+    differing =+      [ (key, Map.lookup key (told after), Map.lookup key (told once))+      | key <- Map.keys (Map.union after once),+        Map.lookup key (told after) /= Map.lookup key (told once)+      ]+    now = 5000+    k = D.poolKeys "" 4+    kx = X.cacheKeys ""+    target = block 1000+    start =+      foldl+        (flip perform)+        emptyDb+        ( [HSet "fleet:lease" "a" "900000", HSet "fleet:recent" "a" target]+            <> [SAdd ("fx:of:" <> address a) i | (a, ids) <- [(0, ["x1"]), (1, ["x1", "x2"]), (2, ["x2"])], i <- ids]+        )+    pool = foldl (flip (others Nothing)) start earlier+    change =+      PoolChange+        []+        []+        (map block confirmed)+        [out a i <> block ((a * 7 + i * 3) `mod` 12) <> encode (100 :: Word32) | (a, i) <- used]+        (Just 100)+        []+    move :: D.How -> (forall m. (Monad m) => Atomic m Moved)+    move how = D.advance k Nothing target (Just now) 4 how [] ""+    once = decided (move (D.AtOnce change)) pool+    begun = decided (move (D.Changing change)) pool+    leaving db = case Map.lookup "pool:leaving" db of+      Just (Hash fields) -> Map.keys fields+      _ -> []+    -- the marked, in the order that the test gives, and in pieces of one+    -- to three+    shuffled = map snd (sort (zip (order <> [0 ..]) (leaving begun)))+    pieces n xs = case splitAt (1 + n `mod` 3) xs of+      (a, []) -> [a]+      (a, rest) -> a : pieces (n + 1) rest+    (after, quiet) = foldl step (begun, True) (zip (pieces (length order) shuffled) trying)+    trying = cycle (Nothing : map Just during)+    -- the others try first, and change nothing; then some are taken out+    step (db, ok) (piece, other) =+      let tried = maybe db (\o -> others (Just target) o db) other+       in (decided (D.takeOut k piece) tried, ok && (null (leaving db) || tried == db))+    decided :: (forall m. (Monad m) => Atomic m a) -> Db -> Db+    decided decision db = either (error . show) snd (runPure now decision db)+    -- what the others decide, each with the tip as it is, so that what+    -- holds them back while a transaction is marked is the mark and not+    -- a tip that they do not know+    others :: Maybe ByteString -> PoolStep -> Db -> Db+    others tip = at (fromMaybe "" tip)+      where+        at seen = \case+          Give t inputs replaced ->+            let outs = [(out a i, ok) | (a, i, ok) <- nubOrdOn (\(a, i, _) -> (a, i)) inputs, a < t]+             in decided (D.offer k tip (map snd outs) (map block replaced) (txOf t (map fst outs)))+          Take ts -> decided (D.withdraw k (map block ts))+          Go _ dead done _ ->+            decided (D.expire k (toInteger (timeOf (sum dead))) (length done + 1))+              . decided (X.evict kx (length done))+              . decided (X.drop kx "x1")+              . decided (X.build kx seen "x3" (0, 0) 1 [added (sum dead)])+              -- a move of the cache that begins, writes a piece and is given+              -- up: nothing of it while a transaction is marked+              . decided (X.abort kx "other")+              . decided (X.piece kx "other" seen [X.Piece (address (sum dead)) "" [] [] [] []])+              . decided (X.begin kx "other" seen)+    added a = X.Addition {address = address a, path = "\0\0\0\0\0", balance = "", txs = [], outs = []}+    -- Redis with the events in no order, and with the version of an+    -- entry of the cache as whether it has one: which entry ends with the+    -- highest number depends on the order in which transactions left.+    --+    -- And with a count of zero as no count. A count is added to and+    -- taken from, one transaction at a time, and where two transactions+    -- that leave together count the same output, one as made and the+    -- other as used up, the order in which they leave decides whether+    -- the count went through one on its way to nothing: Redis keeps a+    -- zero for a count that did, and nothing for one that did not. Every+    -- read takes a count that is not there for zero (@read.lua@,+    -- @xpub.lua@), and no decision asks for one of these but the count of+    -- transactions, which each transaction adds one to.+    told = Map.mapWithKey $ \key -> \case+      Stream events -> Stream (Seq.fromList (sort (toList events)))+      Hash fields+        | "fx:e:" `B.isPrefixOf` key && ":meta" `B.isSuffixOf` key -> Hash (Map.adjust (const "some") "ver" fields)+        | any (`B.isPrefixOf` key) ["pool:asum:", "pool:csum:", "pool:tsum:"] -> Hash (Map.filter (/= "0") fields)+      other -> other++-- | A move of the tip that takes eight hundred transactions out of the+-- pool, while three others write without a pause: transactions that spend+-- from those are offered, another store renews its lease, and entries of+-- the cache are built at the addresses of the block. The move is one+-- decision that is carried out only if nothing that it read has changed,+-- so each of the three alone had it refused, every time: on a server the+-- tip stopped at the first block that confirmed a few thousand+-- transactions of the pool. The store that moves the tip has the floor+-- now, and the others give way.+crowded :: Redis.Connection -> FleetKeys -> IO ()+crowded conn keys = do+  forM_ txs $ \tx -> poolOffer conn keys 4 Nothing tx [True] [] `shouldReturn` Taken+  forM_ ["a", "b"] $ \store -> fleetReport conn keys Nothing 60000 store [target] [] `shouldReturn` True+  -- some of the addresses are those of cached keys already+  forM_ [1 .. 20] built+  withAsync (forM_ (cycle [1 .. n]) (\c -> offered c >> threadDelay 5000)) $ \_ ->+    withAsync (forever (fleetReport conn keys Nothing 60000 "b" [target] [] >> threadDelay 5000)) $ \_ ->+      withAsync (forM_ (cycle [21 .. n]) (\c -> built c >> threadDelay 5000)) $ \_ -> do+        threadDelay 300000+        cacheBegin conn keys "token" "" `shouldReturn` Begun+        fleetCommit conn keys 4 Nothing "a" Nothing target (Just change) [] "token" `shouldReturn` MovedTo target+        -- the tip is at the block, and what the block confirmed is+        -- marked and still in the pool: nothing is offered into it, and+        -- it is taken out two hundred at a time, under the same traffic+        fleetTip conn keys `shouldReturn` Just target+        marked <- poolLeaving conn keys+        length marked `shouldBe` fromIntegral n+        poolOffer conn keys 4 (Just target) (child (1 :: Word32)) [False] [] `shouldReturn` Late+        let pieces xs = case splitAt 200 xs of+              (a, []) -> [a]+              (a, rest) -> a : pieces rest+        taken <- mapM (poolTakeOut conn keys 4) (pieces marked)+        sum taken `shouldBe` fromIntegral n+        poolLeaving conn keys `shouldReturn` []+  fleetTip conn keys `shouldReturn` Just target+  left <- map fst <$> poolSpends conn keys+  filter (`elem` map (.txid) txs) left `shouldBe` []+  where+    n = 800 :: Word32+    target = block 77+    txs = map one [1 .. n]+    change = PoolChange [] [] (map (.txid) txs) [] (Just 100) []+    addr c = C.pack ("addr" <> show c)+    one c =+      PoolTx+        { txid = encode c,+          time = 1700000000 + fromIntegral c,+          inputs = [encode (1000000 + c) <> encode (0 :: Word32)],+          body = B.replicate 250 7,+          entries =+            [ PoolTouches (addr c),+              PoolPays (addr c) (encode c <> encode (0 :: Word32)) 1000 "script",+              PoolTouches (addr (c + 1)),+              PoolSpends (addr (c + 1)) (encode (1000000 + c) <> encode (0 :: Word32)) 1000+            ]+        }+    -- a transaction that spends the output of one of the block's, at its+    -- address: taken, late or an orphan, as the move goes+    offered c = void (poolOffer conn keys 4 Nothing (child c) [False] [])+    child c =+      PoolTx+        { txid = encode (5000000 + c),+          time = 1700009000,+          inputs = [encode c <> encode (0 :: Word32)],+          body = B.replicate 250 7,+          entries = [PoolTouches (addr c), PoolSpends (addr c) (encode c <> encode (0 :: Word32)) 1000]+        }+    -- a cached key with one address of the block+    built c = void (transact conn 1 (building c))+    building :: (Monad m) => Word32 -> Atomic m X.Step+    building c =+      X.build+        (X.cacheKeys keys.prefix)+        ""+        (C.pack ("key" <> show c))+        (0, 0)+        1+        [X.Addition {address = addr c, path = "\0\0\0\0\0", balance = "", txs = [], outs = []}]++-- | All that Redis has under a prefix: each key with what it holds.+type Dump = [(ByteString, [ByteString])]++-- | Where a sequence of steps is: what Redis had under each prefix after+-- the step before, the tip, and how many times it moved or tried to.+type Walk = (Dump, Dump, Maybe ByteString, Word32)++sorted :: Offered -> Offered+sorted = \case+  Conflict rivals -> Conflict (sort rivals)+  other -> other++-- cached keys that have three of the four addresses, one with a+-- transaction and an output that the chain's layer has already+watched :: Redis.Connection -> FleetKeys -> IO ()+watched conn (keys :: FleetKeys) = do+  let key k = keys.prefix <> k+      go :: Redis.Redis (Either Redis.Reply a) -> IO ()+      go f = Redis.runRedis conn f >>= either (error . show) (const (return ()))+  forM_ [(0, ["x1"]), (1, ["x1", "x2"]), (2, ["x2"])] $ \(a, ids) ->+    go (Redis.sadd (key ("fx:of:" <> address a)) (NonEmpty.fromList ids))+  go (Redis.zadd (key "fx:e:x1:txs") [(5, block 3)])+  go (Redis.zadd (key "fx:e:x1:outs") [(5, out 3 0)])++-- carry a step out by the script under one prefix and by the decision+-- in Haskell under another, and compare what each said and all that+-- Redis has under each+both :: Redis.Connection -> FleetKeys -> FleetKeys -> Walk -> PoolStep -> IO Walk+both conn (lua :: FleetKeys) (ours :: FleetKeys) (there0, here0, tip, n) step = do+  let k = D.poolKeys ours.prefix 4+      go :: Redis.Redis (Either Redis.Reply a) -> IO ()+      go f = Redis.runRedis conn f >>= either (error . show) (const (return ()))+      onBoth f = forM_ [lua, ours] (\(keys :: FleetKeys) -> f (keys.prefix <>))+  (tip', n') <- case step of+    Give t inputs replaced -> do+      let outs = [(out a i, ok) | (a, i, ok) <- nubOrdOn (\(a, i, _) -> (a, i)) inputs, a < t]+          tx = txOf t (map fst outs)+      expected <- luaOffer conn lua 4 tip tx (map snd outs) (map block replaced)+      got <- transact conn 1 (D.offer k tip (map snd outs) (map block replaced) tx)+      fmap sorted got `shouldBe` Just (sorted expected)+      return (tip, n)+    Take ts -> do+      expected <- luaWithdraw conn lua 4 (map block ts)+      got <- transact conn 1 (D.withdraw k (map block ts))+      fmap Set.fromList got `shouldBe` Just (Set.fromList expected)+      return (tip, n)+    -- the tip moves, as in the steps of the model above, in each of+    -- the three ways and with and without a move of the cache under+    -- way; then what has been in the pool since before a time leaves,+    -- and the fleet forgets what it saw first+    Go back dead done used -> do+      let target = block (1000 + n)+          height = 700 * (n + 1)+          returned' = [(block t, [out a i | (a, i) <- nubOrd ins, a < t]) | (t, ins) <- back]+          labelled = [(out a i, block ((a * 7 + i * 3 + n) `mod` 12) <> encode height) | (a, i) <- used]+          sent =+            PoolChange+              [txOf (number t) os | (t, os) <- returned']+              (map block dead)+              (map block done)+              [o <> w | (o, w) <- labelled]+              (Just height)+              [block t <> block w <> encode height | t <- take 1 dead, let w = (t * 5 + n) `mod` 12]+          token = if n `mod` 6 `elem` [2, 4] then "tok" else ""+      -- entries of the cache that a move marked, one of them gone+      when (n `mod` 4 == 1) . onBoth $ \key -> go (Redis.sadd (key "fx:marked") (NonEmpty.fromList ["x1", "x3"]))+      -- a move of the cache under way: that of the store, or none+      when (n `mod` 6 == 2) . onBoth $ \key -> go (Redis.set (key "fx:moving") "tok")+      forM_ [lua, ours] $ \keys ->+        fleetReport conn keys (Just 0) 10 "a" [target] (maybe [] pure tip) `shouldReturn` True+      (moved, decided) <-+        if n `mod` 5 == 3+          then+            (,)+              <$> luaCommit conn lua 4 (Just 0) "a" tip target Nothing [] ""+              <*> transact conn 1 (D.advance k tip target (Just 0) 4 (D.AloneNotKnowing "a") [] "")+          else+            if n `mod` 7 == 5+              then+                (,)+                  <$> luaRestart conn lua 4 (Just 0) tip target+                  <*> transact conn 1 (D.advance k tip target (Just 0) 4 D.TooLong [] "")+              else+                (,)+                  <$> luaCommit conn lua 4 (Just 0) "a" tip target (Just sent) [block n, target] token+                  <*> transact conn 1 (D.advance k tip target (Just 0) 4 (D.Changing sent) [block n, target] token)+      decided `shouldBe` Just moved+      -- The move in Haskell only marks what leaves the pool when no+      -- block is undone, where the script took it out: it is taken out+      -- here, in an order and in pieces that change from one step to+      -- the next, and the two are the same again after it. Until then+      -- nothing else is put in or taken out.+      marked <- either (error . show) id <$> Redis.runRedis conn (Redis.hkeys (ours.prefix <> "pool:leaving"))+      unless (null marked) $ do+        transact conn 1 (D.offer k (Just target) [] [] (txOf 4000 [])) `shouldReturn` Just Late+        transact conn 1 (D.withdraw k marked) `shouldReturn` Just []+        let order = if even n then marked else reverse marked+            size = 1 + fromIntegral (n `mod` 3)+            pieces xs = case splitAt size xs of+              (a, []) -> [a]+              (a, rest) -> a : pieces rest+        counts <- forM (pieces order) (\piece -> transact conn 1 (D.takeOut k piece))+        fmap sum (sequence counts) `shouldBe` Just (length marked)+        -- and taking them out again takes nothing+        transact conn 1 (D.takeOut k marked) `shouldReturn` Just 0+      let cutoff = toInteger (timeOf (sum dead))+          most = length done + 1+      expected <- luaExpire conn lua 4 cutoff most+      got <- transact conn 1 (D.expire k cutoff most)+      fmap Set.fromList got `shouldBe` Just (Set.fromList expected)+      return (if moved == MovedTo target then Just target else tip, n + 1)+  there <- everything conn lua.prefix+  here <- everything conn ours.prefix+  versions here0 here `shouldBe` versions there0 there+  return (there, here, tip', n')++-- carry a step out under two prefixes, by the decisions. After a move,+-- under the first what leaves the pool is only marked, and under the+-- second it is all taken out: every read of the first is then the read+-- of the second, and takes out what it has to. Then the rest is taken+-- out, and Redis has the same under both.+reading ::+  Redis.Connection ->+  FleetKeys ->+  FleetKeys ->+  (Maybe ByteString, Word32) ->+  PoolStep ->+  IO (Maybe ByteString, Word32)+reading conn (marked :: FleetKeys) (settled :: FleetKeys) (tip, n) step = do+  let each f = forM_ [marked, settled] (\(keys :: FleetKeys) -> f keys (D.poolKeys keys.prefix 4))+      everyone = [0 .. 12] :: [Word32]+      outs = [out t i | t <- everyone, i <- [0, 1]]+      reads at =+        [("sums", map address everyone), ("bodies", [B.concat (map block everyone)])]+          <> [("spenders", [B.concat outs]), ("replaced", map block everyone)]+          <> [("page", ["0", "0"]), ("page", ["1", "3"]), ("ids", [""]), ("ids", ["\0\0\0"])]+          <> concat+            [ [ ("txs", [address a, "", "", "100"]),+                ("outs", [address a, "", "", "100"]),+                ("spent", [address a, B.concat outs]),+                ("tokens", [address a])+              ]+            | a <- at+            ]+  case step of+    Give t inputs replaced -> do+      let spent = [(out a i, ok) | (a, i, ok) <- nubOrdOn (\(a, i, _) -> (a, i)) inputs, a < t]+          tx = txOf t (map fst spent)+      each $ \_ k -> void (transact conn 1 (D.offer k tip (map snd spent) (map block replaced) tx))+      return (tip, n)+    Take ts -> do+      each $ \_ k -> void (transact conn 1 (D.withdraw k (map block ts)))+      return (tip, n)+    Go back dead done used -> do+      let target = block (1000 + n)+          height = 700 * (n + 1)+          -- two moves in three undo no block, and so only mark+          undo = n `mod` 3 == 2+          labelled = [(out a i, block ((a * 7 + i * 3 + n) `mod` 12) <> encode height) | (a, i) <- used]+          sent =+            PoolChange+              [txOf (number (block t)) [out a i | (a, i) <- nubOrd ins, a < t] | undo, (t, ins) <- back]+              [block t | undo, t <- dead]+              (map block done)+              [o <> w | (o, w) <- labelled]+              (Just height)+              []+      results <- forM [marked, settled] $ \(keys :: FleetKeys) -> do+        fleetReport conn keys (Just 0) 10 "a" [target] (maybe [] pure tip) `shouldReturn` True+        transact conn 1 (D.advance (D.poolKeys keys.prefix 4) tip target (Just 0) 4 (D.Changing sent) [] "")+      let tip' = if all (== Just (MovedTo target)) results then Just target else tip+      take 1 results `shouldBe` drop 1 results+      -- everything out under the second prefix+      left <- poolLeaving conn settled+      unless (null left) (void (poolTakeOut conn settled 4 left))+      -- every read under the first is the read under the second; the+      -- addresses in an order of their own each time+      let at = drop (fromIntegral n `mod` 5) everyone <> take (fromIntegral n `mod` 5) everyone+      forM_ (reads at) $ \(what, args) -> do+        got <- poolRead conn marked 4 tip' what args+        expected <- poolRead conn settled 4 tip' what args+        (what, args, got) `shouldBe` (what, args, expected)+      rest <- poolLeaving conn marked+      unless (null rest) (void (poolTakeOut conn marked 4 rest))+      there <- everything conn marked.prefix+      here <- everything conn settled.prefix+      versions [] there `shouldBe` versions [] here+      return (tip', n + 1)++-- the version of an entry of the cache as whether it is new since the+-- step before. Every change to an address gives the entries that have+-- it a new version, the next number: when transactions that spend from+-- the same one leave together, in no order, which entry ends with the+-- highest number is no rule, and that each has a new one is+versions :: Dump -> Dump -> Dump+versions earlier now =+  [ if "fx:e:" `B.isPrefixOf` key && ":meta" `B.isSuffixOf` key+      then (key, [if lookup key earlier == Just v then "the version it had" else "a new version"])+      else (key, v)+  | (key, v) <- now+  ]++-- all that Redis has under a prefix. Of what the pool keeps of a+-- transaction to take it out again, which each writes in its own way,+-- only for which transactions; of the events, not their numbers nor+-- their order. What the fleet saw is left out: the script kept a set of+-- it, by which the stores decided what to fetch, and the decisions keep+-- none, since a store fetches whatever the pool has not+everything :: Redis.Connection -> ByteString -> IO Dump+everything conn p = do+  let list :: Redis.Redis (Either Redis.Reply a) -> IO a+      list = fmap (either (error . show) id) . Redis.runRedis conn+      name = B.drop (B.length p)+  ks <- sort . filter ((/= "fleet:seen") . name) <$> list (Redis.keys (p <> "*"))+  forM ks $ \key ->+    (name key,) <$> do+      kind <- list (Redis.getType key)+      case kind of+        Redis.String -> maybe [] pure <$> list (Redis.get key)+        Redis.Hash+          | name key == "pool:entries" -> sort . map fst <$> list (Redis.hgetall key)+          -- a count of zero is no count, as in the model ('marking')+          | any (`B.isPrefixOf` name key) ["pool:asum:", "pool:csum:", "pool:tsum:"] ->+              sort . map (\(f, v) -> f <> " = " <> v) . filter ((/= "0") . snd) <$> list (Redis.hgetall key)+          | otherwise -> sort . map (\(f, v) -> f <> " = " <> v) <$> list (Redis.hgetall key)+        Redis.Set -> sort <$> list (Redis.smembers key)+        Redis.ZSet ->+          map (\(x, sc) -> x <> " @ " <> C.pack (show sc)) <$> list (Redis.zrangeWithscores key 0 (-1))+        -- transactions that spend from the same one leave in the+        -- order in which Redis lists a set, which is no order+        Redis.Stream ->+          sort . map (B.intercalate " " . concatMap (\(f, v) -> [f, v]) . (.keyValues))+            <$> list (Redis.xrange key "-" "+" Nothing)+        other -> return [C.pack (show other)]
+ test/Haskoin/Store/Fleet/LeavingModel.hs view
@@ -0,0 +1,491 @@+{-# OPTIONS_GHC -O1 #-}++-- | The pool after a move of the tip, checked in small worlds: every pool,+-- every block and every order of taking out, with the decisions of the+-- store itself. @docs\/tip-first.md@ says what the protocol is, and+-- @scripts\/check-pool.sh@ runs this without building the store.+--+-- = What a world is+--+-- A few transactions that could be in a pool, the candidates: some spend+-- from others, two spend the same coin, some move tokens, and cached keys+-- may watch their addresses. From them:+--+-- * every pool: each set of candidates is offered, and the pool takes+--   those that it can;+-- * every block: each set of candidates is confirmed. A candidate that the+--   pool does not have and that spends what one of the pool spends makes+--   that one invalid;+-- * every order of taking out: from the pool as the move marked it, each+--   marked transaction is taken out next, in turn, down to none.+--+-- = What is checked+--+-- For every pool and every block:+--+-- * __What is marked.__ The move that marks, marks the transactions that+--   the move in one step takes out, and no other.+--+-- And in every state on the way, with some transactions out and some+-- still marked:+--+-- * __Writers wait.__ An offer, a withdrawal, an expiry, a build, a drop+--   and an eviction of an entry of the cache, the beginning of a move of+--   the cache and another move of the tip each leave Redis as it is. Each+--   asks for itself whether anything is marked, and a write to a key of+--   the pool or of the cache asks whatever the decision does+--   ('Haskoin.Store.Fleet.Atomic.guarding'): this holds with either of+--   the two taken away, and fails with both.+-- * __A read is exact.__ For each address, category of tokens,+--   transaction, output and cached key: if none of the transactions that+--   its read would go by is marked, then all that the read reads is+--   already what it is once everything is out. And taking out those that+--   are marked makes it so.+-- * __Any order ends the same.__ With no mark left, Redis has what the+--   move in one step left, and a new transaction is taken again.+--+-- Two states are the same here with the events in no order, the version+-- of an entry of the cache as whether it has one, and a count of zero as+-- no count ('same'): @docs\/fleet-mempool.md@ says why.+--+-- = What it does not show+--+-- Nothing about a pool of thousands. The reads are those of+-- @lua\/read.lua@ and @lua\/xpub.lua@ as this module says them again in+-- Haskell ('aims'): that the scripts read those keys and name those+-- transactions is sampled against a Redis+-- (@Haskoin.Store.Fleet.DecideSpec@), not checked here.+module Haskoin.Store.Fleet.LeavingModel+  ( World (..),+    Report (..),+    worlds,+    spoilt,+    explore,+    describeReport,+  )+where++import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.Foldable (toList)+import Data.List (nub, sort, subsequences)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Sequence qualified as Seq+import Data.Serialize (encode)+import Data.Set qualified as Set+import Data.Word (Word32, Word64)+import Haskoin.Store.Fleet.Atomic (Atomic, Db, Op (..), Value (..), emptyDb, heldByMark, perform, runPure)+import Haskoin.Store.Fleet.Pool.Decide qualified as D+import Haskoin.Store.Fleet.Pool.Types+import Haskoin.Store.Fleet.XPub.Decide qualified as X++-------------------------------------------------------------------------------+-- Worlds+-------------------------------------------------------------------------------++-- | An output: where it is, the address that it pays, its amount, and the+-- tokens that it holds, a category and how many.+data Coin = Coin+  { ref :: !ByteString,+    at :: !ByteString,+    worth :: !Word64,+    kind :: !(Maybe (ByteString, Word64))+  }++-- | A transaction that could be in the pool: its number, what it spends+-- and what it pays.+data Cand = Cand+  { number :: !Word32,+    uses :: ![Coin],+    makes :: ![Coin]+  }++-- | A world: its name, its candidates, and for some addresses the cached+-- keys that have them.+data World = World+  { name :: !String,+    cands :: ![Cand],+    watching :: ![(ByteString, [ByteString])]+  }++-- | What going through a world found: how many pairs of a pool and a+-- block, how many states between a move and the last transaction out,+-- and the first thing that did not hold.+data Report = Report+  { pairs :: !Int,+    states :: !Int,+    failure :: !(Maybe String)+  }++describeReport :: Report -> String+describeReport r = case r.failure of+  Nothing -> show r.pairs <> " pools and blocks, " <> show r.states <> " states: all hold"+  Just why -> "FAILS after " <> show r.pairs <> " pools and blocks: " <> why++idOf :: Word32 -> ByteString+idOf = encode++cand :: Word32 -> [Coin] -> [(ByteString, Word64, Maybe (ByteString, Word64))] -> Cand+cand n ins outs =+  Cand n ins [Coin (idOf n <> encode i) a v t | (i, (a, v, t)) <- zip [0 :: Word32 ..] outs]++-- | The transaction of a candidate as a store offers it+-- (@Haskoin.Store.Fleet.Member.poolTx@).+poolTxOf :: Cand -> PoolTx+poolTxOf c =+  PoolTx+    { txid = idOf c.number,+      time = 1000 + fromIntegral c.number,+      inputs = map (.ref) c.uses,+      body = "body",+      entries =+        [PoolTouches a | a <- nub (map (.at) (c.uses <> c.makes))]+          <> [PoolSpends i.at i.ref i.worth | i <- c.uses]+          <> [PoolPays o.at o.ref o.worth "script" | o <- c.makes]+          <> [PoolMakes ((tokens o t) {coins = Just (o.worth, "script")}) | o <- c.makes, Just t <- [o.kind]]+          <> [PoolUses (tokens i t) | i <- c.uses, Just t <- [i.kind]]+    }+  where+    tokens x (category, amount) =+      PoolTokenOut {address = Just x.at, output = x.ref, category, amount, nft = False, coins = Nothing}++a1, a2, cat1, cat2 :: ByteString+a1 = "addrA"+a2 = "addrB"+cat1 = "cat1"+cat2 = "cat2"++-- | Coins of the chain, unspent at the tip before the block.+c0, c1, c2, c3 :: Coin+c0 = Coin "chain-c0" a1 10 Nothing+c1 = Coin "chain-c1" a2 20 Nothing+c2 = Coin "chain-c2" a1 30 (Just (cat1, 100))+c3 = Coin "chain-c3" a2 5 Nothing++-- | The worlds. Each has a chain of transactions that spend from one+-- another and two that spend the same coin, so that a block can confirm+-- any of them, make any of them invalid, and leave the children of what+-- it confirms.+worlds :: [World]+worlds =+  [ World "a chain of three, two that spend one coin, and one that joins two" plain [],+    World "the same, with cached keys at both addresses" plain [(a1, ["x1"]), (a2, ["x1", "x2"])],+    World "tokens made, moved and used up, and two that spend one coin of tokens" coloured [(a1, ["x1"])],+    World "coins and tokens together, with cached keys" mixed [(a1, ["x1"]), (a2, ["x2"])]+  ]+  where+    plain =+      let t0 = cand 0 [c0] [(a2, 6, Nothing), (a1, 3, Nothing)]+          t1 = cand 1 (take 1 t0.makes) [(a1, 5, Nothing)]+          t2 = cand 2 t1.makes [(a2, 4, Nothing)]+          t3 = cand 3 [c0] [(a2, 9, Nothing)]+          t4 = cand 4 (c1 : drop 1 t0.makes) [(a1, 20, Nothing)]+       in [t0, t1, t2, t3, t4]+    coloured =+      let t0 = cand 0 [c2] [(a2, 29, Just (cat1, 60)), (a1, 1, Just (cat1, 40))]+          t1 = cand 1 (take 1 t0.makes) [(a1, 28, Just (cat1, 60))]+          t2 = cand 2 [c2] [(a1, 29, Just (cat1, 100))]+          t3 = cand 3 (c3 : drop 1 t0.makes) [(a2, 5, Just (cat1, 40))]+          t4 = cand 4 [c1] [(a2, 19, Just (cat2, 7))]+       in [t0, t1, t2, t3, t4]+    mixed =+      let t0 = cand 0 [c0] [(a2, 9, Nothing)]+          t1 = cand 1 t0.makes [(a1, 8, Nothing)]+          t2 = cand 2 [c0] [(a1, 9, Nothing)]+          t3 = cand 3 [c2] [(a2, 29, Just (cat1, 100))]+          t4 = cand 4 (t3.makes <> t1.makes) [(a1, 36, Just (cat1, 100))]+          t5 = cand 5 [c2, c1] [(a1, 49, Just (cat1, 100))]+       in [t0, t1, t2, t3, t4, t5]++-------------------------------------------------------------------------------+-- Redis, and the decisions+-------------------------------------------------------------------------------++now :: Integer+now = 5000++k :: D.Keys+k = D.poolKeys "" 4++kx :: X.Keys+kx = X.cacheKeys ""++target :: ByteString+target = idOf 1000++run :: (forall m. (Monad m) => Atomic m a) -> Db -> (a, Db)+run decision db = either (error . show) id (runPure now decision db)++-- | What a decision leaves of Redis. One that is stopped at a mark+-- leaves Redis as it is: a write to a key of the pool or of the cache+-- asks first whether anything is marked+-- ('Haskoin.Store.Fleet.Atomic.guarding'), whatever the decision does+-- for itself.+attempt :: (forall m. (Monad m) => Atomic m a) -> Db -> Db+attempt decision db = case runPure now decision db of+  Right (_, after) -> after+  Left why+    | heldByMark why -> db+    | otherwise -> error (show why)++hashOf :: ByteString -> Db -> Map ByteString ByteString+hashOf key db = case Map.lookup key db of+  Just (Hash fields) -> fields+  _ -> Map.empty++membersOf :: ByteString -> Db -> [ByteString]+membersOf key db = case Map.lookup key db of+  Just (Sorted members) -> Map.keys members+  Just (Group members) -> Map.keys members+  Just (Hash fields) -> Map.keys fields+  _ -> []++-- | The transactions that are marked as leaving.+marked :: Db -> [ByteString]+marked = membersOf "pool:leaving"++-- | The transactions of the pool.+pooled :: Db -> [ByteString]+pooled = membersOf "pool:spends"++-- | Redis with one live store that reported the block, and the cached+-- keys at their addresses.+start :: World -> Db+start w =+  foldl+    (flip perform)+    emptyDb+    ( [HSet "fleet:lease" "a" "900000", HSet "fleet:recent" "a" target]+        <> [SAdd ("fx:of:" <> a) i | (a, ids) <- w.watching, i <- ids]+        -- each cached key has a priority, so that an eviction has+        -- something to evict+        <> [ZAdd "fx:prio" 1 i | i <- nub (concatMap snd w.watching)]+    )++-- | Offer a candidate, with the tip that the store saw and whether each+-- coin that it spends is unspent in the chain at that tip.+offering :: Maybe ByteString -> (Coin -> Bool) -> Cand -> Db -> (Offered, Db)+offering tip unspent c = run (offer tip unspent c)++offer :: Maybe ByteString -> (Coin -> Bool) -> Cand -> (forall m. (Monad m) => Atomic m Offered)+offer tip unspent c = D.offer k tip (map unspent c.uses) [] (poolTxOf c)++-- | Whether a coin is one of the chain.+ofChain :: Coin -> Bool+ofChain c = "chain-" `B.isPrefixOf` c.ref++-- | Two states of Redis that are the same: with the events in no order,+-- the version of an entry of the cache as whether it has one, and a count+-- of zero as no count.+same :: Db -> Db+same = Map.mapWithKey $ \key -> \case+  Stream events -> Stream (Seq.fromList (sort (toList events)))+  Hash fields+    | "fx:e:" `B.isPrefixOf` key && ":meta" `B.isSuffixOf` key -> Hash (Map.adjust (const "some") "ver" fields)+    | any (`B.isPrefixOf` key) ["pool:asum:", "pool:csum:", "pool:tsum:"] -> Hash (Map.filter (/= "0") fields)+  other -> other++-------------------------------------------------------------------------------+-- What a read reads, and which transactions it goes by+-------------------------------------------------------------------------------++-- | What is read of the pool: by address, by category of tokens, a+-- transaction with what spends it, an output with what spends it, what+-- replaced a transaction, a cached key, and the list of the pool.+data Aim+  = OfAddress !ByteString+  | OfCategory !ByteString+  | OfTx !ByteString+  | OfOutput !ByteString+  | OfReplaced !ByteString+  | OfKey !ByteString+  | WholePool+  deriving (Show)++-- | Everything that a world can ask for.+aims :: World -> [Aim]+aims w =+  map OfAddress [a1, a2]+    <> map OfCategory [cat1, cat2]+    <> map (OfTx . idOf . (.number)) w.cands+    <> map (OfOutput . (.ref)) (concatMap (\c -> c.uses <> c.makes) w.cands)+    <> map (OfReplaced . idOf . (.number)) w.cands+    <> map OfKey (nub (concatMap snd w.watching))+    <> [WholePool]++-- | The transactions that a read goes by, and that are marked: those that+-- the scripts name, for the store to take out before it reads again.+inTheWay :: Aim -> Db -> [ByteString]+inTheWay aim db = filter (`elem` marked db) $ case aim of+  OfAddress a -> membersOf ("pool:atx:" <> a) db+  OfCategory c -> membersOf ("pool:ctx:" <> c) db+  OfTx t -> t : membersOf ("pool:kids:" <> t) db+  OfOutput o -> toList (Map.lookup o (hashOf "pool:spender" db))+  OfReplaced t -> [t]+  OfKey i -> membersOf ("fx:e:" <> i <> ":txs") db+  -- the list of the pool is read without what is marked: nothing is in+  -- its way+  WholePool -> []++-- | All that a read reads, as a value to compare.+readOf :: World -> Aim -> Db -> [(ByteString, String)]+readOf w aim db0 = case aim of+  OfAddress a ->+    keys (\key -> key `elem` map (<> a) atAddress || ("pool:tsum:" `B.isPrefixOf` key && a `B.isSuffixOf` key))+  OfCategory c ->+    keys (\key -> key `elem` map (<> c) ofCategory || ("pool:tsum:" <> c) `B.isPrefixOf` key)+      <> [("spender of " <> o, show (field "pool:spender" o)) | o <- membersOf ("pool:cout:" <> c) db]+  OfTx t ->+    [ ("body", show (field "pool:body" t)),+      ("kids", show (membersOf ("pool:kids:" <> t) db)),+      ("what the kids spend", show [field "pool:spends" kid | kid <- membersOf ("pool:kids:" <> t) db])+    ]+  OfOutput o ->+    let s = field "pool:spender" o+     in [("spender", show s), ("what it spends", show (s >>= field "pool:spends"))]+  OfReplaced t -> [("replaced by", show (field "pool:rep" t))]+  OfKey i ->+    keys (\key -> key `elem` map (("fx:e:" <> i) <>) [":txs", ":outs", ":oval"])+      <> concat [keys (== ("pool:asum:" <> a)) | (a, ids) <- w.watching, i `elem` ids]+      <> [("spender of " <> o, show (field "pool:spender" o)) | o <- membersOf ("fx:e:" <> i <> ":outs") db]+  WholePool -> case Map.lookup "pool:time" db of+    Just (Sorted members) -> [("the pool", show (Map.toList (Map.withoutKeys members (Set.fromList (marked db)))))]+    _ -> [("the pool", "[]")]+  where+    db = same db0+    field key f = Map.lookup f (hashOf key db)+    keys p = [(key, show v) | (key, v) <- Map.toList db, p key]+    atAddress = ["pool:atx:", "pool:aout:", "pool:aval:", "pool:aspent:", "pool:asum:", "pool:acat:"]+    ofCategory = ["pool:ctx:", "pool:cout:", "pool:cval:", "pool:csum:", "pool:chold:"]++-------------------------------------------------------------------------------+-- Going through a world+-------------------------------------------------------------------------------++-- | The first world gone through with a fault put in: what a block is in+-- conflict with is not marked. It has to fail, or the checker sees+-- nothing.+spoilt :: Report+spoilt = case worlds of+  w : _ -> exploring (Map.adjust dropRivals "pool:leaving") w+  [] -> Report 0 0 Nothing+  where+    dropRivals = \case+      Hash fields -> Hash (Map.filter B.null fields)+      other -> other++-- | Go through a world: every pool, every block, and every order of+-- taking out.+explore :: World -> Report+explore = exploring id++exploring :: (Db -> Db) -> World -> Report+exploring fault w = go (Report 0 0 Nothing) [(s, c) | s <- subsequences w.cands, c <- subsequences w.cands]+  where+    go r [] = r+    go r ((s, c) : rest) = case pair fault w s c of+      Left why -> r {pairs = r.pairs + 1, failure = Just (describe s c <> ": " <> why)}+      Right n -> go r {pairs = r.pairs + 1, states = r.states + n} rest+    describe s c =+      "a pool offered " <> show (map (.number) s) <> ", a block that confirms " <> show (map (.number) c)++-- | One pool and one block: how many states were gone through, or what+-- did not hold.+pair :: (Db -> Db) -> World -> [Cand] -> [Cand] -> Either String Int+pair fault w offered confirmed = do+  let (movedOnce, once) = run (move (D.AtOnce change)) pool+      (movedMarking, begun0) = run (move (D.Changing change)) pool+      begun = fault begun0+  check (movedOnce == MovedTo target && movedMarking == MovedTo target) "the tip did not move"+  check+    (sort (marked begun) == sort (filter (`notElem` pooled once) (pooled pool)))+    ("what is marked, " <> show (marked begun) <> ", is not what the move in one step takes out")+  -- all of them in one decision+  let (taken, atOnce) = run (D.takeOut k (marked begun)) begun+  check (taken == length (marked begun)) "taking all of them out at once did not count them all"+  check (same atOnce == same once) "taken out in one decision, Redis is not as after the move in one step"+  walk once [begun] [] 0+  where+    check ok why = if ok then Right () else Left why+    pool = foldl (\db c -> snd (offering Nothing ofChain c db)) (start w) offered+    change =+      PoolChange+        { returned = [],+          gone = [],+          confirmed = map (idOf . (.number)) confirmed,+          spent = [i.ref <> idOf c.number <> encode (100 :: Word32) | c <- confirmed, i <- c.uses],+          height = Just 100,+          lost = []+        }+    move :: D.How -> (forall m. (Monad m) => Atomic m Moved)+    move how = D.advance k Nothing target (Just now) 4 how [] ""+    -- the chain at the new tip: the coins of the chain and what the block+    -- made, without what the block spent+    spentByBlock = [i.ref | c <- confirmed, i <- c.uses]+    unspentAfter coin =+      (ofChain coin || any (\c -> coin.ref `elem` map (.ref) c.makes) confirmed) && coin.ref `notElem` spentByBlock+    -- every state between the move and the last transaction out, each+    -- once+    walk _ [] _ n = Right n+    walk once (db : todo) seen n+      | db `elem` seen = walk once todo seen n+      | otherwise = do+          let left = marked db+              final = foldl (\d t -> snd (run (D.takeOut k [t]) d)) db left+          if null left+            then do+              check (Map.notMember "pool:leaving" db) "no transaction is marked and the marks are still there"+              check (same db == same once) "with everything out, Redis is not as after the move in one step"+              -- and the pool takes a new transaction again+              let fresh = cand 99 [Coin "chain-c9" a1 7 Nothing] [(a2, 6, Nothing)]+              check (fst (offering (Just target) (const True) fresh db) == Taken) "the pool takes nothing after it"+            else do+              mapM_ (waits db) (others db)+          mapM_ (aimed db final) (aims w)+          walk once ([snd (run (D.takeOut k [t]) db) | t <- left] <> todo) (db : seen) (n + 1)+    waits db (what, f) = check (f db == db) (what <> " changed Redis while a transaction was marked")+    -- a read: exact if nothing marked is in its way, and made exact by+    -- taking out what is+    aimed db final aim = do+      let inWay = inTheWay aim db+          helped = snd (run (D.takeOut k inWay) db)+      check+        (not (null inWay) || readOf w aim db == readOf w aim final)+        (show aim <> " goes by no marked transaction, and reads other than once everything is out")+      check+        (null (inTheWay aim helped))+        (show aim <> " still goes by a marked transaction after those in its way were taken out")+      check+        (readOf w aim helped == readOf w aim final)+        (show aim <> ", with what was in its way taken out, reads other than once everything is out")+    -- what else writes to the pool or to the cache, each as a change of+    -- Redis+    others :: Db -> [(String, Db -> Db)]+    others db =+      [ ("an offer of " <> show c.number, attempt (offer (Just target) unspentAfter c))+      | c <- w.cands+      ]+        <> [ ("an offer of a child of " <> show c.number, attempt (offer (Just target) unspentAfter (child c)))+           | c <- w.cands,+             idOf c.number `elem` pooled db+           ]+        <> [ ("a withdrawal", attempt (D.withdraw k (pooled db))),+             ("an expiry", attempt (D.expire k 1000000000 100)),+             ("a build of an entry", attempt (X.build kx target "x9" (0, 0) 1 [added])),+             ("a drop of an entry", attempt (X.drop kx "x1")),+             ("an eviction", attempt (X.evict kx 0)),+             ("the beginning of a move of the cache", attempt (X.begin kx "other" target)),+             ("another move of the tip", moving)+           ]+    -- the store reports a newer block, which the tip would move to: only+    -- what the move itself changes counts+    moving db =+      let reported = perform (HSet "fleet:recent" "a" (idOf 1001 <> target)) db+          next :: (forall m. (Monad m) => Atomic m Moved)+          next = D.advance k (Just target) (idOf 1001) (Just now) 4 (D.Changing none) [] ""+          moved = attempt next reported+       in if moved == reported then db else moved+    child c = cand (90 + c.number) (take 1 c.makes) [(a1, 1, Nothing)]+    added = X.Addition {address = a1, path = "\0\0\0\0\0", balance = "", txs = [], outs = []}+    none = PoolChange [] [] [] [] (Just 101) []
+ test/Haskoin/Store/Fleet/LeavingSpec.hs view
@@ -0,0 +1,23 @@+-- | The pool after a move of the tip, in the worlds of+-- "Haskoin.Store.Fleet.LeavingModel": every pool, every block and every+-- order of taking out. @scripts\/check-pool.sh@ goes through the same+-- worlds without building the store.+--+-- Each world is a group, and so a process of its own+-- (@haskell-dev.toml@).+module Haskoin.Store.Fleet.LeavingSpec (spec) where++import Control.Monad (forM_)+import Data.Maybe (isJust)+import Haskoin.Store.Fleet.LeavingModel+import Test.Hspec++spec :: Spec+spec = do+  forM_ (zip [0 :: Int ..] worlds) $ \(i, w) ->+    describe ("The pool after a move of the tip, world " <> show i <> ": " <> w.name) $+      it "has writers wait, every read exact and every order end the same" $+        (explore w).failure `shouldBe` Nothing+  describe "The pool after a move of the tip, with what a block is in conflict with left unmarked" $+    it "fails, so that the checker is known to see a fault" $+      spoilt.failure `shouldSatisfy` isJust
+ test/Haskoin/Store/Fleet/Oracle.hs view
@@ -0,0 +1,209 @@+{-# LANGUAGE TemplateHaskell #-}++-- | The script that kept the shared mempool before its rules were written+-- in Haskell ("Haskoin.Store.Fleet.Pool.Decide"), with the functions that+-- called it, as they were. No store runs it any more. The specs run it+-- beside the decisions, under another prefix of the same Redis, and+-- compare all that Redis has under each after every step: the script is+-- what the stores ran for months, so that the two do the same is what says+-- that nothing changed for them.+module Haskoin.Store.Fleet.Oracle+  ( luaOffer,+    luaWithdraw,+    luaExpire,+    luaCommit,+    luaRestart,++    -- * The cache of extended public keys+    luaBuild,+    luaBegin,+    luaPiece,+    luaAbort,+    luaDrop,+    luaEvict,+    luaHave,+  )+where++import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.ByteString.Char8 qualified as C+import Data.FileEmbed (embedFile, makeRelativeToProject)+import Data.Maybe (fromMaybe)+import Database.Redis (Connection, Redis, Reply)+import Database.Redis qualified as R+import Haskoin.Store.Fleet (Time)+import Haskoin.Store.Fleet.Redis+import Haskoin.Store.Fleet.XPub.Decide (Addition (..), Began (..), Piece (..), Step (..))+import Haskoin.Store.XPub (greedyLua)++luaOffer :: Connection -> FleetKeys -> Int -> Maybe ByteString -> PoolTx -> [Bool] -> [ByteString] -> IO Offered+luaOffer conn keys tsize seen tx unspents replaced =+  run conn (evalScript poolScript [] args) >>= \case+    ["taken"] -> return Taken+    ["known"] -> return Known+    "conflict" : rivals -> return (Conflict rivals)+    "orphan" : outputs -> return (Orphan outputs)+    ["raced"] -> return Late+    other -> fail ("Unexpected answer of the pool script: " <> show (other :: [ByteString]))+  where+    flags = C.pack [if unspent then '1' else '0' | unspent <- unspents]+    args = ["offer", keys.prefix, num tsize, fromMaybe "" seen, flags, B.concat replaced] <> txArgs tx++luaWithdraw :: Connection -> FleetKeys -> Int -> [ByteString] -> IO [ByteString]+luaWithdraw conn keys tsize ts =+  run conn (evalScript poolScript [] ["withdraw", keys.prefix, num tsize, B.concat ts])++luaExpire :: Connection -> FleetKeys -> Int -> Integer -> Int -> IO [ByteString]+luaExpire conn keys tsize before most =+  run conn (evalScript poolScript [] ["expire", keys.prefix, num tsize, C.pack (show before), num most])++-- | The commit of a move of the tip: by a store that says what the blocks+-- did, or by one that does not know and may empty the pool if it is alone.+luaCommit ::+  Connection ->+  FleetKeys ->+  Int ->+  Maybe Time ->+  ByteString ->+  Maybe ByteString ->+  ByteString ->+  Maybe PoolChange ->+  [ByteString] ->+  ByteString ->+  IO Moved+luaCommit conn keys tsize clock store seen target known path token =+  advance conn keys tsize clock seen target how (fromMaybe unchanged known) (path, token)+  where+    how = maybe ("1|" <> store) (const "0") known+    unchanged = PoolChange [] [] [] [] Nothing []++-- | A move of the tip that empties the pool, the way being too long.+luaRestart :: Connection -> FleetKeys -> Int -> Maybe Time -> Maybe ByteString -> ByteString -> IO Moved+luaRestart conn keys tsize clock seen target =+  advance conn keys tsize clock seen target "2" (PoolChange [] [] [] [] Nothing []) ([], "")++advance ::+  Connection ->+  FleetKeys ->+  Int ->+  Maybe Time ->+  Maybe ByteString ->+  ByteString ->+  ByteString ->+  PoolChange ->+  ([ByteString], ByteString) ->+  IO Moved+advance conn keys tsize clock seen target how change (path, token) =+  run conn (evalScript poolScript [] args) >>= \case+    ["moved"] -> return (MovedTo target)+    ["stays"] -> return Stays+    ["raced"] -> return Raced+    other -> fail ("Unexpected answer of the pool script: " <> show (other :: [ByteString]))+  where+    args =+      ["advance", keys.prefix, num tsize, fromMaybe "" seen, target, maybe "" num clock, num keys.size, how]+        <> [maybe "" num change.height]+        <> [B.concat change.gone, B.concat change.confirmed, B.concat change.spent, B.concat change.lost]+        <> [num (length change.returned)]+        <> concatMap txArgs change.returned+        <> [B.concat path, token]++-- | A transaction as the arguments of the pool script.+txArgs :: PoolTx -> [ByteString]+txArgs tx =+  -- the script took whether a transaction says that it can be replaced by+  -- fee, and kept which could be: no transaction says so any more+  [tx.txid, num tx.time, B.concat tx.inputs, tx.body, "0", num (length tx.entries)]+    <> concatMap entry tx.entries+  where+    entry = \case+      PoolTouches a -> ["t", a, "", "", "", ""]+      PoolSpends a o v -> ["s", a, o, num v, "", ""]+      PoolPays a o v s -> ["o", a, o, num v, s, ""]+      PoolMakes k -> token (if k.nft then "M" else "m") k+      PoolUses k -> token (if k.nft then "U" else "u") k+    token kind k =+      [kind, fromMaybe "" k.address, k.output, num k.amount, maybe "" coins k.coins, k.category]+    coins (v, s) = num v <> " " <> s++num :: (Show a) => a -> ByteString+num = C.pack . show++run :: Connection -> Redis (Either Reply a) -> IO a+run conn f = R.runRedis conn f >>= either (fail . ("Redis error: " <>) . show) return++poolScript :: Script+poolScript = script $(makeRelativeToProject "test/Haskoin/Store/Fleet/pool.lua" >>= embedFile)+{-# NOINLINE poolScript #-}++-- | The script of the cache of extended public keys as it was when it+-- wrote as well as read ("Haskoin.Store.Fleet.XPub.Decide" writes now).+xpubScript :: Script+xpubScript = script (greedyLua <> $(makeRelativeToProject "test/Haskoin/Store/Fleet/xpub.lua" >>= embedFile))+{-# NOINLINE xpubScript #-}++xpub :: Connection -> FleetKeys -> ByteString -> [ByteString] -> IO [ByteString]+xpub conn keys what args = run conn (evalScript xpubScript [] (what : keys.prefix : "4" : args))++-- | A whole number of a score, as the script takes it.+whole :: Double -> ByteString+whole s = num (round s :: Integer)++luaHave :: Connection -> FleetKeys -> ByteString -> IO (Integer, Integer)+luaHave conn keys i =+  run conn (evalScript xpubScript [] ["have", keys.prefix, "4", i]) >>= \case+    [n0, n1] -> return (n0, n1)+    other -> fail ("Unexpected answer of the xpub script: " <> show (other :: [Integer]))++luaBuild ::+  Connection -> FleetKeys -> ByteString -> ByteString -> (Integer, Integer) -> Integer -> [Addition] -> IO Step+luaBuild conn keys tip i (n0, n1) cost additions =+  xpub conn keys "build" ([tip, i, num n0, num n1, num cost, num (length additions)] <> concatMap one additions)+    >>= \case+      ["ok"] -> return StepAdded+      ["raced"] -> return StepRaced+      ["behind"] -> return StepBehind+      ["changed"] -> return StepChanged+      ["busy"] -> return StepBusy+      other -> fail ("Unexpected answer of the xpub script: " <> show other)+  where+    one (a :: Addition) =+      [a.address, a.path, a.balance, num (length a.txs)]+        <> concat [[t, whole s] | (t, s) <- a.txs]+        <> [num (length a.outs)]+        <> concat [[o, whole s, amount, sc] | (o, s, amount, sc) <- a.outs]++luaBegin :: Connection -> FleetKeys -> ByteString -> ByteString -> IO Began+luaBegin conn keys token seen =+  xpub conn keys "begin" [token, seen] >>= \case+    ["ok"] -> return BeganMove+    ["busy"] -> return OtherMoving+    ["raced"] -> return TipElsewhere+    other -> fail ("Unexpected answer of the xpub script: " <> show other)++luaPiece :: Connection -> FleetKeys -> ByteString -> ByteString -> [Piece] -> IO Bool+luaPiece conn keys token seen pieces =+  xpub conn keys "piece" ([token, seen, num (length pieces)] <> concatMap one pieces) >>= \case+    ["ok"] -> return True+    ["raced"] -> return False+    other -> fail ("Unexpected answer of the xpub script: " <> show other)+  where+    one (p :: Piece) =+      [p.address, p.balance, num (length p.abandoned)]+        <> p.abandoned+        <> [num (length p.added)]+        <> concat [[t, whole s] | (t, s) <- p.added]+        <> [num (length p.gone)]+        <> p.gone+        <> [num (length p.unspent)]+        <> concat [[o, whole s, amount, sc] | (o, s, amount, sc) <- p.unspent]++luaAbort :: Connection -> FleetKeys -> ByteString -> IO ()+luaAbort conn keys token = () <$ xpub conn keys "abort" [token]++luaDrop :: Connection -> FleetKeys -> ByteString -> IO ()+luaDrop conn keys i = () <$ xpub conn keys "drop" [i]++luaEvict :: Connection -> FleetKeys -> Int -> IO Integer+luaEvict conn keys most = run conn (evalScript xpubScript [] ["evict", keys.prefix, "4", num most])
test/Haskoin/Store/Fleet/RedisSpec.hs view
@@ -1,6 +1,19 @@-module Haskoin.Store.Fleet.RedisSpec (spec, withRedis) where+module Haskoin.Store.Fleet.RedisSpec+  ( spec,+    withRedis, -import Control.Monad (foldM_, forM_)+    -- * 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@@ -17,11 +30,11 @@ import Haskoin.Store.Fleet qualified as F import Haskoin.Store.Fleet.Pool qualified as P import Haskoin.Store.Fleet.Redis-import Haskoin.Store.Integration.Image (testImage)-import Haskoin.Store.Integration.Podman (hostPort, podmanUsable, withContainer)-import Haskoin.Store.Integration.Valkey (redisContainer, waitRedis)+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.@@ -80,34 +93,37 @@         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-        fleetAdvance conn keys 4 Nothing (Just (block 1)) (block 2) (Just nothing) [] `shouldReturn` Raced+        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)]}-        fleetAdvance conn keys 4 Nothing (Just (block 1)) (block 2) (Just confirms) [] `shouldReturn` MovedTo (block 2)+        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 "sees what the pool decided on, and keeps the newest" $ \(conn, fresh) -> do+      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)-        -- taken, known and in conflict are seen; late and orphans are not+        -- 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]-        fleetSeen conn keys (map block [7 .. 10]) `shouldReturn` [True, True, False, False]-        -- withdrawn is seen+        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]-        fleetSeen conn keys [block 11] `shouldReturn` [True]-        fleetSeen conn keys [] `shouldReturn` []-        -- a bound of 20 is trimmed past 21, to the newest-        forM_ [100 .. 129] $ \i -> poolOffer conn keys 4 at (txOf i [out 1 i]) [True] [] `shouldReturn` Taken-        fleetTrimSeen conn keys 40 `shouldReturn` 33-        fleetTrimSeen conn keys 20 `shouldReturn` 20-        drop 10 <$> fleetSeen conn keys (map block [100 .. 129]) `shouldReturn` replicate 20 True+        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@@ -116,10 +132,21 @@         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-        fleetAdvance conn keys 4 Nothing Nothing (block 1) (Just nothing) [] `shouldReturn` MovedTo (block 1)+        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]@@ -133,7 +160,7 @@         -- 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)]}-        fleetAdvance conn keys 4 Nothing (Just (block 1)) (block 3) (Just confirms) [block 2, block 3]+        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]@@ -145,32 +172,38 @@       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-        fleetAdvance conn keys 4 (Just 0) Nothing (block 1) Nothing [] `shouldReturn` MovedTo (block 1)+        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-        fleetAdvance conn keys 4 (Just 0) (Just (block 1)) (block 2) Nothing [] `shouldReturn` Raced+        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-        fleetAdvance conn keys 4 (Just 20) (Just (block 1)) (block 2) Nothing [] `shouldReturn` MovedTo (block 2)+        -- 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 and what the fleet saw for any store when the way is too long" $ \(conn, fresh) -> do+      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-        fleetAdvance conn keys 4 (Just 0) Nothing (block 1) Nothing [] `shouldReturn` MovedTo (block 1)+        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-        fleetSeen conn keys [block 7] `shouldReturn` [True]+        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-        fleetAdvance conn keys 4 (Just 0) (Just (block 1)) (block 2) Nothing [] `shouldReturn` Raced+        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@@ -180,16 +213,51 @@         (Redis.runRedis conn (Redis.keys (keys.prefix <> "pool:*")) >>= either (fail . show) return)           `shouldReturn` []         -- the stores fetch its transactions again, and fill it again-        fleetSeen conn keys [block 7] `shouldReturn` [False]+        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-        fleetAdvance conn keys 4 (Just 0) Nothing (block 1) Nothing [] `shouldReturn` MovedTo (block 1)+        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@@ -238,12 +306,11 @@         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 whether they can be replaced by fee, and with-        -- what spends their outputs: the fifth says itself that it can be-        -- replaced and nothing spends from it; the second does not say so,-        -- and the second input of the fifth spends its first output+        -- 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", "1", "0", "", "0", "0", "body", "0", "1", out 1 0, block 4, "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])@@ -316,7 +383,7 @@                 (Just height)                 [t <> w | (t, _, w) <- lost]         fleetReport conn keys (Just 0) 10 "a" [target] (maybe [] pure tip) `shouldReturn` True-        fleetAdvance conn keys 4 (Just 0) tip target (Just sent) [] `shouldReturn` MovedTo target+        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@@ -368,10 +435,10 @@       forM_ (Map.toList model.children) $ \(t, expected) -> do         members <- list (Redis.smembers (key ("pool:kids:" <> t)))         Set.fromList members `shouldBe` expected-      -- those that can be replaced by fee are those that say so and what-      -- spends from them-      canBe <- list (Redis.smembers (key "pool:rbf"))-      Set.fromList canBe `shouldBe` P.replaceable signalling maker model+      -- 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]@@ -408,12 +475,86 @@           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]@@ -455,18 +596,41 @@  -- | 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]+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.-signalling :: ByteString -> Bool-signalling t = number t `mod` 4 == 0  -- | A transaction of the tests as the pool takes it. txOf :: Word32 -> [ByteString] -> PoolTx@@ -476,7 +640,6 @@       time = timeOf t,       inputs = spends,       body = "body",-      signals = signalling (block t),       entries = map entry (entriesOf t spends)     }   where@@ -484,6 +647,17 @@       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@@ -510,15 +684,32 @@       few :: Gen a -> Gen [a]       few one = choose (0, 3) >>= (`vectorOf` one) --- | A Redis in a container, and a way to get the keys of a fleet that no--- test has used.+-- | 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 = do-  image <- testImage-  withContainer (redisContainer image) $ \c -> do-    port <- hostPort c 6379-    let url = "redis://127.0.0.1:" <> show port-    waitRedis url-    conn <- Redis.checkedConnect (either error id (Redis.parseConnectInfo url))+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)))
+ test/Haskoin/Store/Fleet/XPubDecideSpec.hs view
@@ -0,0 +1,227 @@+-- | The decisions of the cache of extended public keys+-- ("Haskoin.Store.Fleet.XPub.Decide") beside the script that wrote the+-- cache before them ("Haskoin.Store.Fleet.Oracle"), in a Redis: the same+-- steps by each, under two prefixes, and all that Redis has under each+-- compared after every step. Both have the same pool under them, kept by+-- the same decisions, so that what differs can only be the cache.+module Haskoin.Store.Fleet.XPubDecideSpec (spec) where++import Control.Monad (foldM_, forM_, 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.Serialize (encode)+import Data.Word (Word32)+import Database.Redis qualified as Redis+import Haskoin.Store.Fleet.Atomic.Redis (transact)+import Haskoin.Store.Fleet.DecideSpec (Dump, everything)+import Haskoin.Store.Fleet.Oracle+import Haskoin.Store.Fleet.Pool.Decide qualified as P+import Haskoin.Store.Fleet.Redis+import Haskoin.Store.Fleet.RedisSpec (address, block, out, txOf, withRedis)+import Haskoin.Store.Fleet.XPub.Decide qualified as X+import Test.Hspec+import Test.Hspec.QuickCheck (modifyMaxSuccess)+import Test.Podman (podmanUsable)+import Test.QuickCheck++spec :: Spec+spec = do+  usable <- runIO podmanUsable+  describe "the cache of extended public keys in Redis" $ case usable of+    Left why -> it "is written in Haskell as the script wrote it" (pendingWith why)+    Right () -> aroundAll withRedis $ do+      modifyMaxSuccess (const 300) $+        it "is written in Haskell as the script wrote it, state by state" $ \(conn, fresh) ->+          property $ \steps -> ioProperty $ do+            lua <- fresh+            ours <- fresh+            foldM_ (both conn lua ours) (Nothing, Nothing, 0) (steps :: [CacheStep])++-- | Where a sequence of steps is: the fleet tip, the token of the move of+-- the cache that began last, and how many times the tip was moved.+type Walk = (Maybe ByteString, Maybe ByteString, Word32)++-- | A step of the cache, with keys numbered from 0 to 2, addresses from 0+-- to 3 and transactions from 0 to 11.+data CacheStep+  = -- | addresses are added to the entry of a key: with the numbers that+    -- the entry has or with others, at a cost, each address in one of the+    -- two chains of the key, with transactions and outputs of the chain+    Build !Word32 !Bool !Integer ![(Word32, Bool, [(Word32, Word32)], [(Word32, Word32, Word32)])]+  | -- | a move of the tip begins, under one of two tokens+    Begin !Bool+  | -- | a piece of a move, under one of two tokens: for each address the+    -- transactions of the abandoned blocks, those of the new ones, the+    -- outputs that are gone and those that are unspent+    Move !Bool ![(Word32, [Word32], [(Word32, Word32)], [(Word32, Word32)], [(Word32, Word32, Word32)])]+  | -- | a move is given up+    Abort !Bool+  | -- | the move under way went quiet long ago+    Quiet+  | Drop !Word32+  | Evict !Int+  | -- | a transaction is offered to the pool, spending some outputs+    Offer !Word32 ![(Word32, Word32)]+  | -- | the tip moves, with the move of the cache that began last or with+    -- none+    Commit !Bool+  | -- | the tip moves without the pool and the cache, which is left behind+    Shift+  | -- | the next step is by a store that saw another tip+    Astray !CacheStep+  deriving (Show)++instance Arbitrary CacheStep where+  arbitrary =+    frequency+      [ (6, Build <$> key <*> frequency [(5, pure True), (1, pure False)] <*> choose (0, 50) <*> few added),+        (2, Begin <$> arbitrary),+        (4, Move <$> arbitrary <*> few moved),+        (1, Abort <$> arbitrary),+        (1, pure Quiet),+        (1, Drop <$> key),+        (1, Evict <$> choose (0, 3)),+        (5, Offer <$> tx <*> few output),+        (2, Commit <$> arbitrary),+        (1, pure Shift),+        (1, Astray <$> oneof [Build <$> key <*> pure True <*> choose (0, 50) <*> few added, Begin <$> arbitrary]),+        (1, Astray <$> (Move <$> arbitrary <*> few moved))+      ]+    where+      key = choose (0, 2)+      tx = choose (0, 11)+      place = choose (1, 5)+      output = (,) <$> tx <*> choose (0, 1)+      added = (,,,) <$> choose (0, 3) <*> arbitrary <*> few ((,) <$> tx <*> place) <*> few row+      moved = (,,,,) <$> choose (0, 3) <*> few tx <*> few ((,) <$> tx <*> place) <*> few output <*> few row+      row = (,,) <$> tx <*> choose (0, 1) <*> place+      few :: Gen a -> Gen [a]+      few one = choose (0, 3) >>= (`vectorOf` one)++-- | Carry a step out by the script under one prefix and by the decisions+-- under another, and compare what each said and all that Redis has.+both :: Redis.Connection -> FleetKeys -> FleetKeys -> Walk -> CacheStep -> IO Walk+both conn lua ours (tip, under, n) (Astray step) = do+  -- a tip that no step moves to+  (_, under', n') <- both conn lua ours (Just "away", under, n) step+  return (tip, under', n')+both conn (lua :: FleetKeys) (ours :: FleetKeys) (tip, under, n) step = do+  let k = X.cacheKeys ours.prefix+      seen = maybe "" id tip+      token b = if b then "one" else "two"+      row (t, i, s) = (out t i, fromIntegral s, C.pack (show (t * 10 + i + 1)), "script")+      onBoth :: (FleetKeys -> IO a) -> IO ()+      onBoth f = forM_ [lua, ours] (void . f)+      go :: FleetKeys -> Redis.Redis (Either Redis.Reply a) -> IO ()+      go _ f = Redis.runRedis conn f >>= either (error . show) (const (return ()))+  walk <- case step of+    Build i right cost as -> do+      had <- luaHave conn lua (name i)+      let expected = if right then had else (fst had + 1, snd had)+          additions =+            [ X.Addition+                { address = address a,+                  path = B.singleton (if second then 1 else 0) <> encode a,+                  balance = if even a then "balance" else "",+                  txs = [(block t, fromIntegral s) | (t, s) <- nubOrdOn fst txs],+                  outs = map row (nubOrdOn (\(t, o, _) -> (t, o)) outs)+                }+            | (a, second, txs, outs) <- nubOrdOn (\(a, _, _, _) -> a) as+            ]+      expectedStep <- luaBuild conn lua seen (name i) expected cost additions+      transact conn 1 (X.build k seen (name i) expected cost additions) `shouldReturn` Just expectedStep+      return (tip, under, n)+    Begin b -> do+      began <- luaBegin conn lua (token b) seen+      transact conn 1 (X.begin k (token b) seen) `shouldReturn` Just began+      return (tip, if began == X.BeganMove then Just (token b) else under, n)+    Move b as -> do+      let pieces =+            [ X.Piece+                { address = address a,+                  balance = if odd a then "moved" else "",+                  abandoned = map block (nubOrd old),+                  added = [(block t, fromIntegral s) | (t, s) <- nubOrdOn fst new],+                  gone = [out t i | (t, i) <- nubOrd gone],+                  unspent = map row (nubOrdOn (\(t, o, _) -> (t, o)) unspent)+                }+            | (a, old, new, gone, unspent) <- nubOrdOn (\(a, _, _, _, _) -> a) as+            ]+      written <- luaPiece conn lua (token b) seen pieces+      transact conn 1 (X.piece k (token b) seen pieces) `shouldReturn` Just written+      return (tip, under, n)+    Abort b -> do+      luaAbort conn lua (token b)+      transact conn 1 (X.abort k (token b)) `shouldReturn` Just ()+      return (tip, under, n)+    -- the store of the move under way last said that it is at it at the+    -- start of time+    Quiet -> do+      onBoth $ \keys -> do+        Right v <- Redis.runRedis conn (Redis.get (keys.prefix <> "fx:moving"))+        forM_ v $ \_ -> go keys (Redis.set (keys.prefix <> "fx:beat") "0")+      return (tip, under, n)+    -- Where the decisions differ from the script, on purpose: while a+    -- store is moving the tip, an entry is neither dropped nor evicted,+    -- so that nothing changes what the move has read+    -- ('Haskoin.Store.Fleet.Pool.Decide.floorHeld'). The script dropped+    -- and evicted at any time, since nothing could come between its+    -- reading and its writing. So while a move is under way the script is+    -- not asked, and the decision has to change nothing.+    Drop i -> do+      held <- transact conn 1 (P.floorHeld (P.poolKeys ours.prefix 4))+      if held == Just True+        then transact conn 1 (X.drop k (name i)) `shouldReturn` Just ()+        else do+          luaDrop conn lua (name i)+          transact conn 1 (X.drop k (name i)) `shouldReturn` Just ()+      return (tip, under, n)+    Evict most -> do+      held <- transact conn 1 (P.floorHeld (P.poolKeys ours.prefix 4))+      if held == Just True+        then transact conn 1 (X.evict k most) `shouldReturn` Just 0+        else do+          evicted <- luaEvict conn lua most+          transact conn 1 (X.evict k most) `shouldReturn` Just evicted+      return (tip, under, n)+    -- the pool under both is kept by the same decisions+    Offer t inputs -> do+      let outs = [out a i | (a, i) <- nubOrd inputs, a < t]+      results <- mapM (\keys -> poolOffer conn keys 4 tip (txOf t outs) (map (const True) outs) []) [lua, ours]+      results `shouldSatisfy` \case+        [a, b] -> a == b+        _ -> False+      return (tip, under, n)+    Commit mine -> do+      let target = block (1000 + n)+          with = if mine then maybe "" id under else ""+          change = PoolChange [] [] [] [] (Just (700 * (n + 1))) []+      onBoth $ \keys -> fleetReport conn keys (Just 0) 10 "a" [target] (maybe [] pure tip)+      moved <- mapM (\keys -> fleetCommit conn keys 4 (Just 0) "a" tip target (Just change) [] with) [lua, ours]+      case moved of+        [a, b] -> do+          b `shouldBe` a+          return (if a == MovedTo target then (Just target, Nothing, n + 1) else (tip, under, n + 1))+        _ -> fail "Two fleets"+    Shift -> do+      let target = block (2000 + n)+      onBoth $ \keys -> fleetReport conn keys (Just 0) 10 "a" [target] (maybe [] pure tip)+      moved <- mapM (\keys -> fleetMove conn keys (Just 0) tip) [lua, ours]+      case moved of+        [a, b] -> do+          b `shouldBe` a+          return (if a == MovedTo target then (Just target, under, n + 1) else (tip, under, n + 1))+        _ -> fail "Two fleets"+  there <- everything conn lua.prefix+  here <- everything conn ours.prefix+  quietly here `shouldBe` quietly there+  return walk+  where+    name i = C.pack ("key" <> show i)++-- | All that Redis has, but the time at which the store of the move under+-- way last said that it is at it, which is that of each call.+quietly :: Dump -> Dump+quietly = filter ((/= "fx:beat") . fst)
test/Haskoin/Store/FleetSpec.hs view
@@ -132,8 +132,60 @@ states :: Rules -> [Op] -> [World] states rules = scanl (step rules) start +-- | What happens to a member, for the spec of its turns.+data Happening = Best | Health Bool | Timer+  deriving (Show)++instance Arbitrary Happening where+  arbitrary = elements [Best, Health True, Health False, Timer]++-- | A member that is well and has nothing to do.+idle :: Wake+idle = Wake {well = True, owed = False, block = False, due = False}++-- | What the member knows after a happening, as @memberLoop@ and+-- @setHealthy@ keep it, and whether it then takes a turn, which clears+-- what the turn sees to.+happen :: Wake -> Happening -> (Wake, Bool)+happen w = \case+  Best -> settle w {block = True}+  Health ok -> settle w {well = ok, owed = w.owed || not ok}+  Timer -> settle w {due = True}+  where+    settle v+      | turn v = (v {owed = False, block = False, due = False}, True)+      | otherwise = (v, False)++-- | Every happening with whether it brought a turn, and the member before it.+history :: [Happening] -> [(Wake, Happening, Bool)]+history = go idle+  where+    go _ [] = []+    go w (h : hs) = let (w', t) = happen w h in (w, h, t) : go w' hs+ spec :: Spec-spec = describe "fleet tip" $ do+spec = do+  turns+  tip++turns :: Spec+turns = describe "turns of a member" $ modifyMaxSuccess (const 2000) $ do+  it "takes none while the store is unwell" $+    property $+      \hs -> and [not t | (w, h, t) <- history hs, not (fst (happen w h)).well]+  it "leaves nothing undone while the store is well" $+    property $ \hs ->+      let pending v = v.owed || v.block || v.due+       in and [not (pending after) | (w, h, _) <- history hs, let after = fst (happen w h), after.well]+  it "takes a turn when the store is well again" $+    property $+      \hs -> and [t | (w, Health True, t) <- history hs, not w.well]+  it "takes a turn at each block and each time the two seconds are over, while the store is well" $+    property $ \hs ->+      and [t | (w, h, t) <- history hs, w.well, case h of Health _ -> False; _ -> True]++tip :: Spec+tip = describe "fleet tip" $ do   it "is the newest block that every live store reported" $ do     let fleet = foldl' (\f (s, bs) -> report 0 10 s bs f) (empty :: Fleet Int Int) reports'         reports' = [(0, [5, 4, 3, 2]), (1, [4, 3, 2, 1]), (2, [7, 6, 3, 2])]@@ -162,6 +214,16 @@     mayReport 1 1 (`elem` [9, 8, 7 :: Int]) fleet `shouldBe` True     -- when the store that was ahead is gone, the other may start again     mayReport 11 1 (`elem` [7, 6, 5 :: Int]) fleet `shouldBe` True++  it "lets only the one live store empty the pool for a way it does not know" $ do+    let fleet = report 0 10 1 [9, 8] (empty :: Fleet Int Int)+    mayEmptyAlone 5 1 fleet `shouldBe` True+    -- a store that is not live, though one store is+    mayEmptyAlone 5 2 fleet `shouldBe` False+    -- with another store live+    mayEmptyAlone 5 1 (report 0 10 2 [9, 8] fleet) `shouldBe` False+    -- nobody live+    mayEmptyAlone 11 1 fleet `shouldBe` False    it "answers from the tip, from its own block before there is one, or not at all" $ do     let fleet = (empty :: Fleet Int Int) {tip = Just 4}
test/Haskoin/Store/Histories.hs view
@@ -10,7 +10,9 @@     -- * Blocks     run,     startChain,+    startChainAs,     mine,+    mineAs,     revert,   ) where@@ -27,6 +29,7 @@   ( DatabaseReader (..),     layeredFamilyConfig,     mergeGuardFamily,+    tokenFamilyConfig,     withLayeredReader,     withReader,   )@@ -39,9 +42,10 @@ openLayered net dir = withLayeredReader net 20 32 dir False Nothing Nothing Nothing Nothing Nothing Nothing  -- | Open a database as a store of database version 22 did: without merge--- operators, and without the column family that is there since version 23--- to keep such a store out. It is how the tests make a database that such--- a store left, and how they try what such a store would do to a newer one.+-- operators, without the column family that is there since version 23 to+-- keep such a store out, and without those of the tokens, since version+-- 24. It is how the tests make a database that such a store left, and how+-- they try what such a store would do to a newer one. openOlder :: Network -> FilePath -> (DatabaseReader -> IO a) -> IO a openOlder net dir =   withReader older (\_ -> return ()) net 20 32 dir False Nothing Nothing Nothing Nothing Nothing Nothing@@ -49,7 +53,8 @@     older bloom cached =       [ (name, config {mergeOperator = Nothing})       | (name, config) <- layeredFamilyConfig bloom cached,-        name /= mergeGuardFamily+        name /= mergeGuardFamily,+        name `notElem` map fst (tokenFamilyConfig bloom cached)       ]  -- | Run a batch of writes, and give what it returned, or the reason why it@@ -61,8 +66,22 @@  -- | Give a new database its genesis block. startChain :: DatabaseReader -> IO ()-startChain db = run db initBest >>= either (fail . show) return+startChain db = startChainAs db.net db +-- | 'startChain' with the rules of the chain run as on another network.+startChainAs :: Network -> DatabaseReader -> IO ()+startChainAs net db = runAs net db initBest >>= either (fail . show) return++-- | 'run' with the rules of the chain run as on another network: the+-- blocks are those of the network of the database, and the scripts are+-- read as on the other. With Bitcoin Cash without its CashAddr prefix, an+-- output that holds tokens has no address and no tokens, as in a store of+-- database version 23, which read scripts with haskoin-core 2.0.+runAs :: Network -> DatabaseReader -> (Writer -> IO a) -> IO (Either ImportException a)+runAs net db = try . runWriter net (db :: DatabaseReader) {net = net} quiet+  where+    quiet = Logger {level = LevelError, source = "", push = \_ -> return ()}+ -- | Import a block with these transactions on the best block, and give its -- hash. mine :: DatabaseReader -> [Tx] -> IO BlockHash@@ -71,6 +90,16 @@   parent <- Q.getBlock db best >>= maybe (fail "no data for the best block") return   let (block, node) = nextBlock db.net parent.height parent.header txs   run db (\w -> importBlock w block node) >>= either (fail . show) (void . return)+  return (headerHash block.header)++-- | 'mine' with the rules of the chain run as on another network+-- ('runAs').+mineAs :: Network -> DatabaseReader -> [Tx] -> IO BlockHash+mineAs net db txs = do+  best <- Q.getBestBlock db >>= maybe (fail "no best block") return+  parent <- Q.getBlock db best >>= maybe (fail "no data for the best block") return+  let (block, node) = nextBlock db.net parent.height parent.header txs+  runAs net db (\w -> importBlock w block node) >>= either (fail . show) (void . return)   return (headerHash block.header)  -- | Revert the best block.
+ test/Haskoin/Store/Ingest/Model.hs view
@@ -0,0 +1,933 @@+{-# OPTIONS_GHC -O1 #-}++-- |+-- Module      : Haskoin.Store.Ingest.Model+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- A model checker for "Haskoin.Store.Ingest": the machine itself, the+-- 'step' that a store runs, put in a small world of nodes, channels and a+-- pool, and taken through __every__ order in which things can happen+-- there. @docs\/mempool-ingestion.md@ has what is checked, T1 to T7.+--+-- The module is compiled with optimisation whatever the build: going+-- through about a million states without it takes minutes.+--+-- = Why not random tests+--+-- A property test draws runs. The failures that this replaces were each+-- one particular order of two events: a header that came between a+-- request and its answer, an announcement while a queue was full. A+-- draw finds such an order seldom, and going through all of them finds+-- it always. The price is a small world: a few transactions and peers.+-- The bet, which model checkers make, is that a wrong rule shows in a+-- small world already.+--+-- = The world+--+-- Nodes hold mempools and follow the rules that the document assumes of+-- a node (A1 to A8): a node names a transaction to a peer once, names its+-- whole mempool when a source is asked, sends what it named and still+-- has, and says so when it has it no longer. Between a node and the+-- machine there is a channel each way, in order. The pool settles a+-- transaction whose parents are settled. What the machine asks of the+-- pool waits in a line, and other things happen meanwhile.+--+-- = Steps of two kinds+--+-- A node asked for a transaction sends it if it has it, whether it named+-- it to the peer or not: the machine asks for what a transaction spends+-- from when the pool lacks it (A7).+--+-- * __Things that go well__: a message is delivered, the pool answers,+--   the store is in sync again, time passes while nothing else can.+-- * __Disturbances__: a node takes or drops a transaction, a block+--   confirms one, a peer goes and comes, the pool fails to answer or+--   loses everything, a request gets no answer in time, the store is out+--   of sync, another store offers a transaction first.+--+-- Safety is checked in every state that any mix of both reaches.+-- Convergence is checked from every such state: let only things go well+-- from there, and every run must end, in a state where the pool has+-- every transaction of the mempool of every source. That is T3, "from+-- any state that the store can reach".+module Haskoin.Store.Ingest.Model+  ( Scenario (..),+    Disturbance (..),+    Result (..),+    explore,+    wander,+    scenarios,+    withoutOrder,+    large,+    describeResult,+  )+where++import Control.Monad (when)+import Data.Foldable (toList)+import Data.List (intercalate, sortOn)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Sequence (Seq, (|>))+import Data.Sequence qualified as Seq+import Data.Set (Set)+import Data.Set qualified as Set+import Haskoin.Store.Ingest++type P = Int++type H = Int++-- | A transaction body: the transactions that it spends from.+newtype B = B [H]+  deriving (Eq, Ord, Show)++-- | A world to go through.+data Scenario = Scenario+  { name :: String,+    config :: Config,+    -- | the transactions that there can be, each with those it spends from+    txs :: Map H [H],+    -- | the peers, and whether each is a source+    peers :: [(P, Bool)],+    -- | whether the peers are all connections to one node, with one+    -- mempool, and which of them are no peers at all but the RPC of that+    -- node: sources that answer and never announce. A store that is given+    -- the RPC of a node that whitelists nobody has both, a peer that+    -- announces and is no source, and a source that does not announce.+    oneNode :: Bool,+    feeds :: [P],+    -- | the peers that are nodes of the operator: the others are+    -- strangers+    owned :: [P],+    -- | the transactions that are forged, which no honest node takes, and+    -- the peers that have them all the same, from the start+    forged :: [H],+    liars :: [P],+    -- | the transactions that are good and that the store cannot verify+    scripts :: [H],+    -- | whether a source names a transaction __before__ those that it+    -- spends from, against A5: for the world that shows what A5 is needed+    -- for ('withoutOrder'), and for no world that has to pass+    backwards :: Bool,+    disturbances :: [Disturbance],+    -- | disturbances stop while more than this many messages and+    -- questions are on their way: the world is not infinitely faster+    -- than the store+    busy :: Int,+    -- | the most states to go through, after which the search says that+    -- the world is too large and stops+    limit :: Int+  }++data Disturbance+  = -- | a node takes a transaction, or drops one+    Mempools+  | -- | a block confirms a transaction+    Blocks+  | -- | the store is out of sync for a while+    Desyncs+  | -- | a peer goes, and comes back+    PeerDrops+  | -- | the pool does not answer+    PoolFails+  | -- | the pool loses what it had+    PoolEmptied+  | -- | a request gets no answer in time+    Timeouts+  | -- | a client gives the store a transaction+    Clients+  | -- | another store of the fleet offers a transaction first+    OtherStores+  deriving (Eq, Ord, Show, Enum, Bounded)++data Node = Node+  { has :: !(Set H),+    -- | what it named to the store on this connection+    told :: !(Set H),+    -- | what it named when it was last asked for its mempool, and has had+    -- ever since+    answered :: !(Set H),+    online :: !Bool,+    source :: !Bool+  }+  deriving (Eq, Ord, Show)++data ToNode = MGet ![H] | MSweep+  deriving (Eq, Ord, Show)++data ToStore = MInv ![H] | MTx !H | MNotFound ![H]+  deriving (Eq, Ord, Show)++-- | A question to the pool, or an offer with whether it is vouched for.+data Op = OCheck !P ![H] | OOffer !H !B !Bool+  deriving (Eq, Ord, Show)++data World = World+  { machine :: !(Ingest P H B),+    nodes :: !(Map P Node),+    pool :: !(Set H),+    confirmed :: !(Set H),+    toNode :: !(Map P (Seq ToNode)),+    toStore :: !(Map P (Seq ToStore)),+    asked :: !(Seq Op),+    inSync :: !Bool,+    -- | whether the store ever had the blocks of its nodes+    hadBlocks :: !Bool+  }+  deriving (Eq, Ord, Show)++-- | What a search found.+data Result = Result+  { states :: !Int,+    transitions :: !Int,+    -- | what went wrong, with the steps that lead there, if anything did+    failure :: !(Maybe (String, [String]))+  }++describeResult :: Result -> String+describeResult r = case r.failure of+  Nothing -> show r.states <> " states, " <> show r.transitions <> " transitions"+  Just (what, path) -> what <> "\nafter:\n" <> intercalate "\n" (map ("  " <>) path)++parentsOf :: B -> [H]+parentsOf (B ps) = ps++-- | How far back a time matters in the worlds here: beyond the life of an+-- orphan, every age is the same.+horizon :: Scenario -> Tick+horizon sc = sc.config.orphanLife + sc.config.patience + 2++settled :: World -> Set H+settled w = w.pool `Set.union` w.confirmed++initial :: Scenario -> World+initial sc =+  World+    { machine = start sc.config 0,+      nodes =+        Map.fromList+          [ (p, Node (if p `elem` sc.liars then Set.fromList sc.forged else Set.empty) Set.empty Set.empty False src)+          | (p, src) <- sc.peers+          ],+      pool = Set.empty,+      confirmed = Set.empty,+      toNode = Map.fromList [(p, Seq.empty) | (p, _) <- sc.peers],+      toStore = Map.fromList [(p, Seq.empty) | (p, _) <- sc.peers],+      asked = Seq.empty,+      inSync = False,+      hadBlocks = False+    }++-- | Give the machine an input: check what the step did against the rules+-- that hold of every step, and send its outputs on their way.+feed :: Scenario -> Input P H B -> World -> Either String World+feed sc input w = do+  let before = w.machine+      (after, outs) = step parentsOf input before+      -- what comes into the machine with an input: a body, and the ids+      -- that the pool was asked about; what a peer names goes to the pool+      -- first+      learned = Set.fromList $ case input of+        Body _ h _ -> [h]+        Checked _ yes no -> yes <> no+        Unchecked _ hs -> hs+        -- what the pool lacks of what a transaction spends from is+        -- learned when it gets a place, to be asked for; without one it+        -- is what the transaction waits for, and nothing of its own+        Offered _ (Orphan ps) -> filter (`Set.member` ids after) ps+        _ -> []+      gone = Set.fromList [h | Gone h _ <- outs]+  -- T1: nothing leaves in silence, and nothing comes from nowhere+  check "an id left without a word, or came from nowhere" $+    Set.union (ids before) learned == Set.union (ids after) gone+  check "an id is said to have left and is still there" $+    Set.null (Set.intersection (ids after) gone)+  -- T1 for what a peer names: it has a place or the pool is asked, once+  -- the store has had its blocks. Before that nothing of a peer is taken+  -- in, which is checked below.+  case input of+    Named p hs+      | w.hadBlocks,+        Just (Just _) <- Just (windowOf p before) ->+          check "a named id has no place and the pool is not asked" $+            all (\h -> Set.member h (ids after) || h `elem` concat [cs | Check _ cs <- outs]) hs+    _ -> return ()+  -- T6: what the pool lacks of what a held transaction spends from has a+  -- place, to be asked for, if there is a peer to ask and room. It is+  -- so for a verdict that the machine was waiting for: one that comes+  -- after the transaction was given up, and came again and waits, is not+  -- of this offer, and the machine does nothing with it. Left out, that+  -- made this check fail once in two thousand runs of the larger world.+  case input of+    Offered h (Orphan ps)+      | Just (Held _ _ Offering) <- placeOf h before,+        Just (Held _ _ (Waiting _ _)) <- placeOf h after,+        any (\(p, _) -> windowOf p after /= Nothing) sc.peers,+        Set.size (ids after) < sc.config.room ->+          check "the pool lacks what a held transaction spends from, and it is not asked for" $+            all (`Set.member` ids after) (filter (/= h) ps)+    _ -> return ()+  -- What waits for transactions that all have a place is not offered when+  -- its time comes: the pool would only say that it lacks them, and the+  -- held one is made ready when the last of them settles. A machine that+  -- offered it all the same spent most of its offers on that when a whole+  -- mempool came at once. One of them that was given up, in this step+  -- too, has no place after it.+  case input of+    Tick _ ->+      check "a held transaction is offered at its time while all that it waits for have a place" $+        and+          [ any (`Set.notMember` ids after) (Set.toList ps)+          | Offer h _ <- outs,+            Just (Held _ _ (Waiting ps _)) <- [placeOf h before]+          ]+    _ -> return ()+  -- And the other way: one of those that it waits for has no place, so+  -- nothing will wake it, and its time has come. It waits no longer: it+  -- is ready, offered, or given up for having waited too long.+  case input of+    Tick t ->+      check "a held transaction still waits after its time for a transaction that has no place" $+        and+          [ case placeOf h after of+              Just (Held _ _ (Waiting _ _)) -> False+              _ -> True+          | h <- Set.toList (ids before),+            Just (Held _ _ (Waiting ps at)) <- [placeOf h before],+            at <= t,+            any (`Set.notMember` ids before) (Set.toList ps)+          ]+    _ -> return ()+  -- T8: a stranger is not taken at its word. What a node of the operator+  -- names or sends is no longer held for one to name it.+  case input of+    Named p hs+      | p `elem` sc.owned ->+          check "a node of the operator named a transaction that is still held for one to name it" $+            and [not (doubted h) | h <- hs]+    Body (Just p) h _+      | p `elem` sc.owned,+        Just (Just _) <- Just (windowOf p before) ->+          check "a node of the operator sent a transaction that is still held for one to name it" (not (doubted h))+    -- what is forged is given up, and what cannot be verified is held for+    -- a node of the operator, offered again if one named it meanwhile, or+    -- given up for want of room: never offered as it is, and never ready+    Offered h Forged+      | Just (Held _ _ Offering) <- placeOf h before ->+          check "a forged transaction is kept" (Set.notMember h (ids after))+    Offered h Unverified+      | Just (Held _ _ Offering) <- placeOf h before ->+          check "a transaction that cannot be verified is not held for a node of the operator to name it" $+            case placeOf h after of+              Just (Held _ _ (Doubted _)) -> True+              Just (Held _ _ Later) -> vouchedFor h after+              Just (Held _ _ Offering) -> vouchedFor h after+              Nothing -> True+              _ -> False+    _ -> return ()+  -- T9: the store does not say that its pool has the mempool of its nodes+  -- before it has. When the machine starts to say so, no request for a+  -- mempool is on its way to a node of the operator, and the pool has+  -- decided on all that each such node named when it was last asked and+  -- has had ever since.+  --+  -- The machine takes a source to have answered when as long passed as+  -- a request is given (A10). A world in which requests get no answer in+  -- time breaks that on purpose, and is not held to this.+  when (Timeouts `notElem` sc.disturbances && standing before /= PoolSynced && standing after == PoolSynced) $ do+    check "the pool is said to be in sync while a node of the operator has not answered for its mempool" $+      and [MSweep `notElem` toList q | (p, q) <- Map.toList w.toNode, trustedHere p]+    check "the pool is said to be in sync and lacks a transaction that a node of the operator named and has" $+      and+        [ Set.filter (`Set.member` node.answered) node.has `Set.isSubsetOf` Set.union (settled w) (unread p)+        | (p, node) <- Map.toList w.nodes,+          trustedHere p+        ]+  -- it says so only of a node of the operator that gives its mempool:+  -- what strangers name says nothing of what the pool should have+  --+  -- A peer connects one step before the machine is told whose it is:+  -- between the two it is a stranger to the machine, and this is not asked.+  case input of+    PeerUp p _ | p `elem` sc.owned -> return ()+    _ ->+      check "the pool is said to be in sync, or syncing, with no node of the operator to measure it against" $+        (standing after == PoolUnknown) == not (or [trustedHere p | p <- Map.keys w.nodes])+  -- and a pool that lost what it had is not in sync+  case input of+    Emptied -> check "the pool lost what it had and is still said to be in sync" (standing after /= PoolSynced)+    _ -> return ()+  -- Until the store first has its blocks, nothing that a peer names or+  -- sends is taken in, and nothing is asked for it.+  let untaken =+        check "something of a peer was taken in before the store had its blocks" $+          ids after == ids before && null outs+  case input of+    Named _ _ | not w.hadBlocks -> untaken+    Body (Just _) _ _ | not w.hadBlocks -> untaken+    _ -> return ()+  -- the invariant, which has the bounds of T2+  case wellFormed after of+    [] -> return ()+    wrong -> Left ("after " <> show input <> ": " <> intercalate "; " wrong)+  -- T5+  check "the count of requests out is wrong" $+    pending after == length [() | h <- Set.toList (ids after), Just (Asked {}) <- [placeOf h after]]+  w' <- foldl' (\acc o -> acc >>= send o) (Right w) outs+  return w' {machine = rebase (horizon sc) after}+  where+    check what ok = if ok then Right () else Left (what <> ", after " <> show input)+    -- a node of the operator that is connected and gives its mempool+    trustedHere p = p `elem` sc.owned && maybe False (\n -> n.online && n.source) (Map.lookup p w.nodes)+    -- what a peer named in messages that the store has not read+    unread p = Set.fromList (concat [hs | MInv hs <- maybe [] toList (Map.lookup p w.toStore)])+    doubted h = case placeOf h (fst (step parentsOf input w.machine)) of+      Just (Held _ _ (Doubted _)) -> True+      _ -> False+    -- the transactions that another spends from+    spentFrom = Set.fromList (concat (Map.elems sc.txs))+    send o x = case o of+      Get p hs -> do+        node <- maybe (Left "asked a peer that is not there") Right (Map.lookup p x.nodes)+        -- T4: only a peer that is there, only for what it named or for+        -- what a transaction spends from, within its window+        check "asked a peer that is gone" node.online+        check "asked a peer for what it did not name and nothing spends from" $+          all (\h -> Set.member h node.told || Set.member h spentFrom) hs+        check "asked for nothing" (not (null hs))+        return x {toNode = Map.adjust (|> MGet hs) p x.toNode}+      Sweep p -> do+        node <- maybe (Left "swept a peer that is not there") Right (Map.lookup p x.nodes)+        check "asked the mempool of a peer that would drop the store for it" (node.online && node.source)+        return x {toNode = Map.adjust (|> MSweep) p x.toNode}+      Check p hs -> return x {asked = x.asked |> OCheck p hs}+      Offer h b -> do+        -- T8: what is forged is never offered as a node took it+        let vouched = vouchedFor h (fst (step parentsOf input w.machine))+        check "a forged transaction is offered as vouched for" (not (vouched && h `elem` sc.forged))+        return x {asked = x.asked |> OOffer h b vouched}+      Gone _ _ -> return x++-- | The steps in which things go well, from a world.+calm :: Scenario -> World -> [(String, Either String World)]+calm sc w = if null moves then idle else moves+  where+    moves = concat [toNodes, toStores, answers, resync]+    toNodes =+      [ ( "the node of peer " <> show p <> " reads " <> show msg,+          Right (nodeReads sc p msg w {toNode = Map.insert p rest w.toNode})+        )+      | (p, q) <- Map.toList w.toNode,+        msg Seq.:<| rest <- [q]+      ]+    toStores =+      [ ( "the store reads " <> show msg <> " of peer " <> show p,+          feed sc (storeReads p msg) w {toStore = Map.insert p rest w.toStore}+        )+      | (p, q) <- Map.toList w.toStore,+        msg Seq.:<| rest <- [q]+      ]+    answers = case w.asked of+      OCheck p hs Seq.:<| rest ->+        let (yes, no) = (filter (`Set.member` settled w) hs, filter (`Set.notMember` settled w) hs)+         in [("the pool answers the check of " <> show hs, feed sc (Checked p yes no) w {asked = rest})]+      -- the runner looks at what is not vouched for before it offers it+      OOffer h _ False Seq.:<| rest+        | h `elem` sc.forged ->+            [("the store finds " <> show h <> " forged", feed sc (Offered h Forged) w {asked = rest})]+        | h `elem` sc.scripts,+          Set.notMember h (settled w) ->+            [("the store cannot verify " <> show h, feed sc (Offered h Unverified) w {asked = rest})]+      OOffer h b _ Seq.:<| rest ->+        let missing = filter (`Set.notMember` settled w) (parentsOf b)+         in if null missing+              then+                [ ( "the pool takes " <> show h,+                    feed sc (Offered h Settled) w {asked = rest, pool = Set.insert h w.pool}+                  )+                ]+              else [("the pool lacks parents of " <> show h, feed sc (Offered h (Orphan missing)) w {asked = rest})]+      _ -> []+    resync = [("the store is in sync", feed sc (Synced True) w {inSync = True, hadBlocks = True}) | not w.inSync]+    -- time passes only when nothing else can happen: a second at a time+    idle = [("a second passes", feed sc (Tick 1) w)]+    storeReads p = \case+      MInv hs -> Named p hs+      MTx h -> Body (Just p) h (B (Map.findWithDefault [] h sc.txs))+      MNotFound hs -> Missing p hs++-- | What a node does with a message of the store (A2, A3).+nodeReads :: Scenario -> P -> ToNode -> World -> World+nodeReads sc p msg w = case Map.lookup p w.nodes of+  Nothing -> w+  Just node -> case msg of+    MSweep+      | Set.null node.has -> w+      | otherwise ->+          w+            { nodes = Map.insert p node {told = Set.union node.told node.has, answered = node.has} w.nodes,+              -- A5: parents before children, unless the world is one+              -- that breaks it+              toStore = Map.adjust (|> MInv (sortOn inOrder (Set.toAscList node.has))) p w.toStore+            }+    MGet hs ->+      let (found, lost) = (filter (`Set.member` node.has) hs, filter (`Set.notMember` node.has) hs)+          answers = map MTx found <> [MNotFound lost | not (null lost)]+          reply = foldl' (|>) (fromMaybe' (Map.lookup p w.toStore)) answers+       in w {toStore = Map.insert p reply w.toStore}+  where+    fromMaybe' = maybe Seq.empty id+    inOrder h = if sc.backwards then negate (depth h) else depth h+    depth :: H -> Int+    depth h = case Map.findWithDefault [] h sc.txs of+      [] -> 0+      ps -> 1 + maximum (map depth ps)++-- | The disturbances of a scenario, from a world.+disturbed :: Scenario -> World -> [(String, Either String World)]+disturbed sc w+  | inFlight > sc.busy = []+  | otherwise = concatMap of' sc.disturbances+  where+    inFlight =+      sum (map Seq.length (Map.elems w.toNode))+        + sum (map Seq.length (Map.elems w.toStore))+        + Seq.length w.asked+    everywhere = Set.unions (map (.has) (Map.elems w.nodes))+    of' = \case+      Mempools+        | sc.oneNode ->+            [ ("the node takes " <> show h, Right (foldl' (\x p -> arriveIn x p h) w (Map.keys w.nodes)))+            | (h, ps) <- Map.toList sc.txs,+              h `notElem` sc.forged,+              Set.notMember h everywhere,+              Set.notMember h w.confirmed,+              all (\x -> Set.member x everywhere || Set.member x w.confirmed) ps+            ]+              <> [ ( "the node drops " <> show h,+                     Right w {nodes = Map.map (\n -> without (family h) n) w.nodes}+                   )+                 | h <- Set.toList everywhere+                 ]+        | otherwise ->+            [ ("the node of peer " <> show p <> " takes " <> show h, Right (arriveIn w p h))+            | (p, node) <- Map.toList w.nodes,+              (h, ps) <- Map.toList sc.txs,+              h `notElem` sc.forged,+              Set.notMember h node.has,+              Set.notMember h w.confirmed,+              all (\x -> Set.member x node.has || Set.member x w.confirmed) ps+            ]+              <> [ ( "the node of peer " <> show p <> " drops " <> show h,+                     Right w {nodes = Map.insert p (without (family h) node) w.nodes}+                   )+                 | (p, node) <- Map.toList w.nodes,+                   h <- Set.toList node.has+                 ]+      Blocks ->+        [ ( "a block confirms " <> show h,+            Right+              w+                { confirmed = Set.insert h w.confirmed,+                  pool = Set.delete h w.pool,+                  nodes = Map.map (without (Set.singleton h)) w.nodes+                }+          )+        | h <- Set.toList everywhere,+          h `notElem` sc.forged,+          all (`Set.member` w.confirmed) (Map.findWithDefault [] h sc.txs)+        ]+      Desyncs -> [("the store is out of sync", feed sc (Synced False) w {inSync = False}) | w.inSync]+      PeerDrops ->+        [ ( "peer " <> show p <> " is gone",+            feed+              sc+              (PeerDown p)+              w+                { nodes = Map.insert p node {online = False, told = Set.empty, answered = Set.empty} w.nodes,+                  toNode = Map.insert p Seq.empty w.toNode,+                  toStore = Map.insert p Seq.empty w.toStore+                }+          )+        | (p, node) <- Map.toList w.nodes,+          node.online+        ]+      PoolFails -> case w.asked of+        OCheck p hs Seq.:<| rest ->+          [("the pool does not answer the check of " <> show hs, feed sc (Unchecked p hs) w {asked = rest})]+        OOffer h _ _ Seq.:<| rest ->+          [("the pool does not judge " <> show h, feed sc (Offered h Again) w {asked = rest})]+        _ -> []+      PoolEmptied -> [("the pool loses what it had", feed sc Emptied w {pool = Set.empty}) | not (Set.null w.pool)]+      Timeouts ->+        [ ("a request gets no answer in time", feed sc (Tick (sc.config.patience + 1)) w)+        | pending w.machine > 0+        ]+      Clients ->+        [ ("a client gives the store " <> show h, feed sc (Body Nothing h (B ps)) w)+        | (h, ps) <- Map.toList sc.txs,+          Set.notMember h w.confirmed+        ]+      OtherStores ->+        [ ("another store offers " <> show h <> " first", Right w {pool = Set.insert h w.pool})+        | (h, ps) <- Map.toList sc.txs,+          h `notElem` sc.forged,+          Set.notMember h (settled w),+          all (`Set.member` settled w) ps+        ]+    -- a node no longer has some transactions+    without gone n = n {has = Set.difference n.has gone, answered = Set.difference n.answered gone}+    -- a transaction and all that spends from it+    family h = close (Set.singleton h)+      where+        close s =+          let s' = Set.union s (Set.fromList [c | (c, ps) <- Map.toList sc.txs, any (`Set.member` s) ps])+           in if s' == s then s else close s'+    -- A1: a node names a transaction once, to a peer that is there. Its+    -- RPC names nothing by itself.+    arriveIn x p h = case Map.lookup p x.nodes of+      Just node+        | node.online && p `notElem` sc.feeds ->+            x+              { nodes = Map.insert p node {has = Set.insert h node.has, told = Set.insert h node.told} x.nodes,+                toStore = Map.adjust (|> MInv [h]) p x.toStore+              }+        | otherwise -> x {nodes = Map.insert p node {has = Set.insert h node.has} x.nodes}+      Nothing -> x++-- | A peer comes: not a disturbance, and not something that has to+-- happen. A peer that stays away is no source.+--+-- The name of a peer stands for one connection, as in haskoin-node, where+-- every connection is a peer of its own: an answer of the pool about what+-- a peer named is for that connection, never for a later one to the same+-- node. A world has few names, so a name is used again only once nothing+-- on its way mentions it, which no one can tell from a new name.+comes :: Scenario -> World -> [(String, Either String World)]+comes sc w =+  [ ( "peer " <> show p <> " connects",+      feed sc (PeerUp p node.source) w {nodes = Map.insert p node {online = True} w.nodes}+        >>= \x -> if p `elem` sc.owned then feed sc (Own p) x else Right x+    )+  | (p, node) <- Map.toList w.nodes,+    not node.online,+    null [() | OCheck q _ <- toList w.asked, q == p]+  ]++-- | T3 at rest: the pool has every transaction of the mempool of every+-- source that is connected.+--+-- Of a node that the store has the RPC of and a peer to, that is so while+-- the peer is connected: the RPC announces nothing, so what the node+-- takes while no peer is there to be told is in the pool at the next+-- reading of the RPC, which is by the clock and not by anything that+-- happens.+converged :: Scenario -> World -> Bool+converged sc w+  | sc.oneNode && not (or [node.online | (p, node) <- Map.toList w.nodes, p `notElem` sc.feeds]) = True+  | otherwise =+      and+        [ dueOf sc w p node `Set.isSubsetOf` settled w+        | (p, node) <- Map.toList w.nodes,+          node.online,+          node.source+        ]++-- | What the pool must have of what a source has. A node of the operator+-- is taken at its word: all that it has. Of a stranger, what the store+-- can verify: not what is forged, not what it cannot verify unless a node+-- of the operator that is there has it too, and nothing that spends from+-- either.+dueOf :: Scenario -> World -> P -> Node -> Set H+dueOf sc w p node+  | p `elem` sc.owned = node.has+  | otherwise = Set.filter (not . barred) node.has+  where+    barred h = h `elem` held || any barred (Map.findWithDefault [] h sc.txs)+    held = sc.forged <> [h | h <- sc.scripts, Set.notMember h vouchable]+    vouchable =+      Set.unions [n.has | (q, n) <- Map.toList w.nodes, q `elem` sc.owned, n.online, n.source]+        `Set.union` settled w++-- | Go through every state of a scenario. In each: the rules of every+-- step. From each, with only things going well: no way to go on for ever,+-- and no way to stop short of 'converged'.+explore :: Scenario -> Result+explore sc = search (Map.singleton w0 Nothing) [w0] [] 0+  where+    w0 = initial sc+    -- breadth first, so that the steps to a failure are the fewest+    search seen [] [] n = lively seen n+    search seen [] later n = search seen (reverse later) [] n+    search seen (w : rest) later n+      | Map.size seen > sc.limit =+          Result (Map.size seen) n (Just ("more states than the limit: a smaller world is needed", []))+      | otherwise = searchOne seen w rest later n+    searchOne seen w rest later n =+      let next = calm sc w <> disturbed sc w <> comes sc w+       in case [(label, why) | (label, Left why) <- next] of+            (label, why) : _ -> Result (Map.size seen) n (Just (why, trail seen w <> [label]))+            [] ->+              let new = [(x, label) | (label, Right x) <- next, Map.notMember x seen]+                  seen' = foldl' (\m (x, label) -> Map.insertWith (\_ old -> old) x (Just (label, w)) m) seen new+                  fresh = Set.toList (Set.fromList (map fst new))+               in search seen' rest (reverse fresh <> later) (n + length next)+    trail seen w = reverse (go w)+      where+        go x = case Map.lookup x seen of+          Just (Just (label, from)) -> label : go from+          _ -> []+    -- with only things going well: every run ends, and ends converged+    lively seen n = case walk Map.empty (Map.keys seen) of+      Left (what, w, path) ->+        let steps = trail seen w <> ("--- from here, only things that go well:" : path)+         in Result (Map.size seen) n (Just (what, steps))+      Right _ -> Result (Map.size seen) n Nothing+    round' = "with only things going well, the store goes round for ever without the mempool of a source"+    short = "the store is at rest and the pool lacks transactions of the mempool of a source"+    -- depth first, with the states on the way marked: meeting one again is a+    -- way to go on for ever+    walk done [] = Right done+    walk done (w : ws) = visit done w [] >>= \done' -> walk done' ws+    visit done w path = case Map.lookup w done of+      Just True -> Right done+      Just False -> Left (round', w, reverse path)+      Nothing ->+        let next = [(label, x) | (label, Right x) <- calm sc w, x /= w]+         in if null next+              then+                if converged sc w+                  then Right (Map.insert w True done)+                  else Left (short, w, reverse path)+              else do+                let on acc (label, x) = acc >>= \d -> visit d x (label : path)+                done' <- foldl' on (Right (Map.insert w False done)) next+                return (Map.insert w True done')++-- | One run through a world, with a number for each choice: the rules of+-- every step are checked along it, and at its end, with only things+-- going well from there, the store must come to rest with the mempool of+-- every source. For worlds too large to go through whole, a sample of+-- their runs: evidence of another kind, and weaker.+wander :: Scenario -> [Int] -> Either (String, [String]) ()+wander sc = go (initial sc) []+  where+    go w path [] = settleDown w path (10000 :: Int)+    go w path (n : ns) =+      let next = calm sc w <> disturbed sc w <> comes sc w+       in case next !! (abs n `mod` length next) of+            (label, Left why) -> Left (why, reverse (label : path))+            (label, Right w') -> go w' (label : path) ns+    settleDown w path fuel = case [(label, x) | (label, x) <- calm sc w, x /= Right w] of+      [] | converged sc w -> Right ()+      [] -> Left ("the store is at rest and the pool lacks transactions of the mempool of a source", reverse path)+      (label, Left why) : _ -> Left (why, reverse (label : path))+      (label, Right w') : _+        | fuel <= 0 -> Left ("with only things going well, the store does not come to rest", reverse path)+        | otherwise -> settleDown w' (label : path) (fuel - 1)++-- | A world too large to go through whole, for 'wander': two chains of+-- three, two sources and a peer that is none, and every disturbance.+large :: Scenario+large =+  Scenario+    { name = "two chains of three, three peers, every disturbance",+      config =+        Config+          { room = 5,+            heldRoom = 3,+            minWindow = 1,+            maxWindow = 3,+            patience = 2,+            orphanLife = 6,+            retry = 1,+            sweepGap = 2,+            sweepEvery = 0,+            sweepFast = 0+          },+      txs = Map.fromList [(1, []), (2, [1]), (3, [2]), (4, []), (5, [4]), (6, [5, 3])],+      peers = [(1, True), (2, True), (3, False)],+      oneNode = False,+      feeds = [],+      owned = [],+      forged = [],+      liars = [],+      scripts = [],+      backwards = False,+      disturbances = [minBound .. maxBound],+      busy = 6,+      limit = 0+    }++-- | A world that must __fail__: a chain of two and room for one id and one+-- body, as one of 'scenarios', with a source that names the child before+-- what it spends from, against A5. The child gets the only room, cannot+-- be offered without its parent and cannot wait in the last room, so it+-- is given up, and the next reading of the source goes the same way: the+-- store goes round for ever.+--+-- It is here to say what A5 is needed for. With room to spare the order+-- of names does not matter, as the worlds that ask for a child first+-- show; at the bound it decides which ids get the room. A source that+-- named in another order would make a store with less room than its+-- node's mempool has transactions never take the rest.+withoutOrder :: Scenario+withoutOrder =+  Scenario+    { name = "a chain of two, room for one id and one body, a source that names the child first",+      config =+        Config+          { room = 1,+            heldRoom = 1,+            minWindow = 1,+            maxWindow = 2,+            patience = 1,+            orphanLife = 2,+            retry = 1,+            sweepGap = 1,+            sweepEvery = 0,+            sweepFast = 0+          },+      txs = Map.fromList [(1, []), (2, [1])],+      peers = [(1, True)],+      oneNode = False,+      feeds = [],+      owned = [],+      forged = [],+      liars = [],+      scripts = [],+      backwards = True,+      disturbances = [Mempools],+      busy = 2,+      limit = 1500000+    }++-- | The worlds that the specs go through: each small enough to go+-- through whole in seconds. A world has the mempools of its nodes+-- changing and one or two other disturbances, so that every disturbance+-- meets every other in some world, two at a time; all of them at once+-- only fit with one transaction.+scenarios :: [Scenario]+scenarios =+  [ world "one transaction, every disturbance" one [(1, True)] [minBound .. maxBound] small,+    world "a chain of two, blocks" chain [(1, True)] [Mempools, Blocks] small,+    world "a chain of two, a peer that goes" chain [(1, True)] [Mempools, PeerDrops] small,+    world "a chain of two, requests that get no answer" chain [(1, True)] [Mempools, Timeouts] small,+    world "a chain of two, a pool that fails" chain [(1, True)] [Mempools, PoolFails] small,+    world "a chain of two, a pool that loses what it had" chain [(1, True)] [Mempools, PoolEmptied] small,+    world "a chain of two, a store out of sync" chain [(1, True)] [Mempools, Desyncs] small,+    world "a chain of two, clients" chain [(1, True)] [Mempools, Clients] small,+    world "a chain of two, another store" chain [(1, True)] [Mempools, OtherStores] small,+    world "a chain of two, room for one id and one body" chain [(1, True)] [Mempools, Clients] tight,+    world "a chain asked for child first, room for one body" upside [(1, True)] [Mempools] small {heldRoom = 1},+    world "a chain of three asked for child first, room for two bodies" upside3 [(1, True)] [Mempools] two,+    world "a chain of two, a peer that goes and no answers" chain [(1, True)] [Mempools, PeerDrops, Timeouts] small,+    world "a chain of two, the pool failing and emptied" chain [(1, True)] [Mempools, PoolFails, PoolEmptied] small,+    world "a chain of two, blocks and a store out of sync" chain [(1, True)] [Mempools, Blocks, Desyncs] small,+    world "one transaction, a source and a peer that is none" one mixed [Mempools, PeerDrops, Timeouts] small,+    world "one transaction, two sources" one [(1, True), (2, True)] [Mempools, PeerDrops] small,+    -- a node that whitelists nobody, and a store that has its RPC: a+    -- source that does not announce, and a peer that announces and is no+    -- source, with one mempool between them+    (world "one transaction, one node: its RPC and a peer that is no source" one mixed [Mempools, PeerDrops] small)+      { oneNode = True,+        feeds = [1]+      },+    (world "a chain of two, one node: its RPC and a peer that is no source" chain mixed [Mempools, PeerDrops] small)+      { oneNode = True,+        feeds = [1]+      },+    -- T8: peer 1 is a stranger and peer 2 a node of the operator. The+    -- store cannot verify transaction 1, and 2 spends from it.+    (world "a stranger and a node of the operator, a transaction that cannot be verified" one both wavering small)+      { owned = [2],+        scripts = [1]+      },+    (world "the same, with blocks" one both [Mempools, Blocks] small)+      { owned = [2],+        scripts = [1]+      },+    -- T9: the pool is measured against the node of the operator, and is+    -- not in sync after it lost what it had+    (world "a stranger and a node of the operator, a pool that loses what it had" one both losing small)+      { owned = [2]+      },+    -- one node with two connections, so that the two have one mempool:+    -- a peer that is a stranger, and the RPC, which is the operator's+    (world "the same, and a transaction that spends from it" chain both [Mempools] small)+      { owned = [2],+        scripts = [1],+        oneNode = True,+        feeds = [2]+      },+    -- nobody to vouch for it: the store comes to rest without it, and+    -- without what spends from it+    (world "only a stranger, a transaction that the store cannot verify" chain [(1, True)] wavering small)+      { scripts = [1]+      },+    -- the stranger has a forged transaction, and one that spends from it+    (world "a stranger that lies, and a node of the operator" one both wavering small)+      { owned = [2],+        forged = [1],+        liars = [1]+      },+    (world "the same, and a transaction that is good" pair both [Mempools] small)+      { owned = [2],+        forged = [1],+        liars = [1]+      },+    (world "only a stranger, which lies, a pool that fails" three [(1, True)] [Mempools, PoolFails] small)+      { forged = [1, 2],+        liars = [1]+      }+  ]+  where+    losing = [Mempools, PoolEmptied]+    world name txs peers disturbances config =+      Scenario+        { name,+          config,+          txs,+          peers,+          oneNode = False,+          feeds = [],+          owned = [],+          forged = [],+          liars = [],+          scripts = [],+          backwards = False,+          disturbances,+          busy = 2,+          limit = 1500000+        }+    mixed = [(1, True), (2, False)]+    both = [(1, True), (2, True)]+    wavering = [Mempools, PeerDrops]+    -- a chain of two and a transaction by itself+    three = Map.fromList [(1, []), (2, [1]), (3, [])]+    pair = Map.fromList [(1, []), (2, [])]+    tight = small {room = 1, heldRoom = 1}+    two = small {heldRoom = 2, maxWindow = 3}+    one = Map.fromList [(1, [])]+    chain = Map.fromList [(1, []), (2, [1])]+    -- the child has the smaller id, so it is asked for first+    upside = Map.fromList [(2, []), (1, [2])]+    upside3 = Map.fromList [(3, []), (2, [3]), (1, [2])]+    small =+      Config+        { room = 8,+          heldRoom = 8,+          minWindow = 1,+          maxWindow = 2,+          patience = 1,+          orphanLife = 2,+          retry = 1,+          sweepGap = 1,+          sweepEvery = 0,+          sweepFast = 0+        }
+ test/Haskoin/Store/IngestSpec.hs view
@@ -0,0 +1,307 @@+-- |+-- Module      : Haskoin.Store.IngestSpec+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- The checks of "Haskoin.Store.Ingest" against+-- @docs\/mempool-ingestion.md@. Three kinds, and what each is worth:+--+-- * __every order of events of a small world__+--   ("Haskoin.Store.Ingest.Model"): nothing is sampled, so a pass means+--   that no order of events in that world breaks a rule, and that from+--   every state the store comes to rest with the mempool of its sources;+--+-- * __sampled runs of a larger world__: weaker, and there to say whether+--   what holds in the small worlds still does with more of everything;+--+-- * __examples__, which prove nothing and show what the rules mean.+module Haskoin.Store.IngestSpec (spec) where++import Control.Monad (forM_)+import Data.IntMap.Strict qualified as IntMap+import Data.IntSet qualified as IntSet+import Data.List (foldl', partition)+import Data.Sequence qualified as Seq+import Haskoin.Store.Ingest+import Haskoin.Store.Ingest.Model+import Test.Hspec hiding (pending)+import Test.Hspec.QuickCheck (modifyMaxSuccess)+import Test.QuickCheck (arbitrary, choose, counterexample, forAll, property, vectorOf)++spec :: Spec+spec = do+  -- a group for each world, so that haskell-dev runs them in different+  -- processes (haskell-dev.toml)+  forM_ scenarios $ \sc ->+    describe ("In every order of events of " <> sc.name) $+      it "keeps the rules and converges" $ do+        let result = explore sc+        case result.failure of+          Nothing -> result.states `shouldSatisfy` (> 100)+          Just _ -> expectationFailure (describeResult result)+  describe "With a source that names a transaction before what it spends from, against A5" $+    it "a store with room for one id goes round for ever: the order is needed at the bound" $+      case (explore withoutOrder).failure of+        Just (what, _) -> what `shouldContain` "goes round for ever"+        Nothing -> expectationFailure "The world that breaks A5 converges"+  describe "in runs drawn from a larger world" $+    modifyMaxSuccess (const 2000) $+      it ("keeps the rules and converges: " <> large.name) $+        forAll (choose (0, 400) >>= \n -> vectorOf n arbitrary) $ \choices ->+          case wander large choices of+            Right () -> property True+            Left (what, path) -> counterexample (unlines (what : map ("  " <>) path)) False+  describe "A whole mempool that comes at once, most of it spending from the rest" $+    it "is offered to the pool once each, and no transaction twice" $ do+      -- as many as a full mempool of Bitcoin, in chains of 24+      let count = 65000+          (taken, refused, time) = refill count+      -- every one is in the pool, in the time of that many offers and of+      -- the seconds in which the machine waits for nothing+      taken `shouldBe` count+      time `shouldSatisfy` (< count + 5000)+      -- and the pool was asked for nothing that it could only refuse+      refused `shouldBe` 0+  describe "for example" $ do+    it "offers a chain root first, whatever the order its transactions come in" $ do+      -- 3 spends from 2, which spends from 1, and they come child first+      let came = [Body (Just 1) 3 [2], Body (Just 1) 2 [1], Body (Just 1) 1 []]+          (s, outs) = run ([Named 1 [1, 2, 3], Checked 1 [] [1, 2, 3]] <> came)+      [h | Offer h _ <- outs] `shouldBe` [1 :: Int]+      let (_, more) = run' [Offered 1 Settled, Offered 2 Settled, Offered 3 Settled] s+      [h | Offer h _ <- more] `shouldBe` [2, 3]+      [h | Gone h Done <- more] `shouldBe` [1, 2, 3]+    it "keeps what a peer names while the store is out of sync, and asks for it after" $ do+      let (s, outs) = run' [Synced False, Named 1 [7], Checked 1 [] [7]] ready+      [() | Get {} <- outs] `shouldBe` []+      placeOf 7 s `shouldSatisfy` \case+        Just (Wanted _) -> True+        _ -> False+      snd (run' [Synced True] s) `shouldBe` [Get 1 [7 :: Int]]+    it "reads its source again after it gave something up" $ do+      let tight = (start defaultConfig {room = 1} 0 :: Ingest Int Int [Int])+          (s, outs) = run' [PeerUp 1 True, Synced True, Named 1 [1, 2], Checked 1 [] [1, 2]] tight+      [h | Gone h (GaveUp NoRoom) <- outs] `shouldBe` [2]+      isDirty s `shouldBe` True+      -- not sooner than the gap, and then it does+      snd (run' [Tick 1000] s) `shouldBe` []+      snd (run' [Tick 10000] s) `shouldBe` [Sweep 1]+    it "reads its source after thirty seconds while transactions come, and ever less often when none do" $ do+      -- a transaction that the pool lacks is named, comes and is taken+      let came h = [Named 1 [h], Checked 1 [] [h], Body (Just 1) h [], Offered h Settled]+          readings t s = [() | Sweep _ <- snd (run' [Tick t] s)]+          at t s = fst (run' [Tick t] s)+          (s1, _) = run (came 1)+      -- not before thirty seconds, and then+      readings 29999 s1 `shouldBe` []+      readings 30000 s1 `shouldBe` [()]+      -- one more comes: thirty seconds again+      let (s2, _) = run' (came 2) (at 30000 s1)+      readings 59999 s2 `shouldBe` []+      readings 60000 s2 `shouldBe` [()]+      -- none comes: thirty seconds, and then a minute for good+      let times = [90000, 150000, 210000, 270000, 330000]+          quiet = scanl (flip at) (at 60000 s2) times+      forM_ (zip quiet times) $ \(s, t) -> do+        readings (t - 1) s `shouldBe` []+        readings t s `shouldBe` [()]+      -- and thirty seconds after one comes again+      let (s4, _) = run' (came 3) (last quiet)+      readings (330000 + 29999) s4 `shouldBe` []+      readings (330000 + 30000) s4 `shouldBe` [()]+    it "asks a peer for no more than its window, which grows as the peer answers" $ do+      let (s, outs) = run [Named 1 [1 .. 100], Checked 1 [] [1 .. 100]]+      [length hs | Get _ hs <- outs] `shouldBe` [16]+      pending s `shouldBe` 16+      let (s', more) = run' [Body (Just 1) 1 []] s+      [length hs | Get _ hs <- more] `shouldBe` [2]+      windowOf 1 s' `shouldBe` Just 17+    it "does not offer at its time what waits for a transaction that has a place, and does once it has none" $ do+      -- 2 spends from 1, and comes first: it waits for 1, which is asked for+      let (s, outs) = run [Named 1 [1, 2], Checked 1 [] [1, 2], Body (Just 1) 2 [1]]+      [h | Offer h _ <- outs] `shouldBe` []+      -- its time comes, after two seconds, four and eight, and 1 is still+      -- on its way: nothing to offer+      let (s', more) = run' [Tick 2000, Tick 4000, Tick 8000] s+      [h | Offer h _ <- more] `shouldBe` []+      -- the node says that it has not 1, which is given up: at its next+      -- time 2 is offered, since nothing else would wake it+      let (_, last') = run' [Missing 1 [1], Tick 16000] s'+      [h | Gone h (GaveUp NodeHasNot) <- last'] `shouldBe` [1]+      [h | Offer h _ <- last'] `shouldBe` [2 :: Int]+    it "holds what a stranger sent and the store cannot verify until a node of the operator names it" $ do+      -- peer 1 is a stranger, and what it sent is not vouched for+      let (s, outs) = run [Named 1 [7], Checked 1 [] [7], Body (Just 1) 7 []]+      [h | Offer h _ <- outs] `shouldBe` [7 :: Int]+      vouchedFor 7 s `shouldBe` False+      -- the store cannot verify it: held, and not offered when time passes+      let (doubting, more) = run' [Offered 7 Unverified, Tick 1000, Tick 2000] s+      [h | Offer h _ <- more] `shouldBe` []+      placeOf 7 doubting `shouldSatisfy` \case+        Just (Held _ _ (Doubted _)) -> True+        _ -> False+      -- peer 2, a node of the operator, names it: offered again, as+      -- vouched for+      let (named, last') = run' [PeerUp 2 True, Own 2, Named 2 [7]] doubting+      [h | Offer h _ <- last'] `shouldBe` [7]+      vouchedFor 7 named `shouldBe` True+    it "gives up what nobody vouched for after twenty minutes, and reads no source for it" $ do+      let (s, _) = run [Named 1 [7], Checked 1 [] [7], Body (Just 1) 7 [], Offered 7 Unverified]+          (later', outs) = run' [Tick 1199000, Tick 1201000] s+      [h | Gone h (GaveUp NotVouched) <- outs] `shouldBe` [7 :: Int]+      isDirty later' `shouldBe` False+    it "gives up a forged transaction with all that waits for it, and reads no source for them" $ do+      -- 8 spends from 7, and waits for it+      let came = [Named 1 [7, 8], Checked 1 [] [7, 8], Body (Just 1) 8 [7], Body (Just 1) 7 []]+          (s, outs) = run' [Offered 7 Forged] (fst (run came))+      [h | Gone h (GaveUp IsForged) <- outs] `shouldBe` [7, 8 :: Int]+      isDirty s `shouldBe` False+    it "takes a node of the operator at its word, for what it sends and for what that spends from" $ do+      -- peer 1 is a node of the operator; 8 spends from 7, which the pool+      -- lacks and nobody named+      let own = fst (run' [Own 1] ready)+          (s, _) = run' [Named 1 [8], Checked 1 [] [8], Body (Just 1) 8 [7], Offered 8 (Orphan [7])] own+      vouchedFor 8 s `shouldBe` True+      vouchedFor 7 s `shouldBe` True+    it "takes nothing of a peer in until the store first has its blocks, and reads its source when it has" $ do+      let cold = fst (run' [PeerUp 1 True, Own 1] (start defaultConfig 0)) :: Ingest Int Int [Int]+          (s, outs) = run' [Named 1 [7], Body (Just 1) 8 [], Tick 30000] cold+      outs `shouldBe` []+      idCount s `shouldBe` 0+      -- it has them: the source is asked for its mempool, which has all+      -- that its node has now+      let (s1, outs1) = run' [Synced True] s+      [p | Sweep p <- outs1] `shouldBe` [1]+      -- and what is named from then on is asked of the pool+      [hs | Check _ hs <- snd (run' [Named 1 [7]] s1)] `shouldBe` [[7]]+      -- a block behind for a moment, it still keeps what is named, and+      -- asks no peer for it until it has the block+      let (s2, outs2) = run' [Synced False, Named 1 [9], Checked 1 [] [9]] s1+      idCount s2 `shouldBe` 1+      [() | Get _ _ <- outs2] `shouldBe` []+      [hs | Get _ hs <- snd (run' [Synced True] s2)] `shouldBe` [[9]]+    it "says that the pool is syncing until its node had the time to answer and nothing is on its way" $ do+      -- the node was asked for its mempool when it connected+      standing ours `shouldBe` PoolSyncing+      standing (fst (run' [Tick 19999] ours)) `shouldBe` PoolSyncing+      -- twenty seconds, and it named nothing: it has nothing+      standing (fst (run' [Tick 20000] ours)) `shouldBe` PoolSynced+      -- what it named is on its way: asked of the pool, then fetched+      let (asking, _) = run' [Named 1 [7], Tick 20000] ours+      standing asking `shouldBe` PoolSyncing+      let (fetching, _) = run' [Checked 1 [] [7]] asking+      standing fetching `shouldBe` PoolSyncing+      let (full, _) = run' [Body (Just 1) 7 [], Offered 7 Settled] fetching+      standing full `shouldBe` PoolSynced+      -- and it stays so while transactions come and go+      standing (fst (run' [Named 1 [8], Checked 1 [] [8]] full)) `shouldBe` PoolSynced+      -- until the pool loses what it had+      standing (fst (run' [Emptied] full)) `shouldBe` PoolSyncing+    it "cannot tell how the pool stands without a node of the operator that gives its mempool" $ do+      let alone = fst (run' [PeerUp 1 False, Synced True] (start defaultConfig 0)) :: Ingest Int Int [Int]+      standing alone `shouldBe` PoolUnknown+      -- a stranger that gives its mempool is nothing to measure against+      standing ready `shouldBe` PoolUnknown+      standing (fst (run' [Tick 60000] ready)) `shouldBe` PoolUnknown+      -- nor a node of the operator that does not give it+      standing (fst (run' [Own 1] alone)) `shouldBe` PoolUnknown+    it "is in sync while a stranger's transaction is held for a node of the operator to name it" $ do+      -- peer 2 is a stranger, whose transaction the store cannot verify:+      -- it is held for twenty minutes, and is no part of what the pool+      -- should have. A store among strangers said that it was filling+      -- for as long as one was held.+      let both = fst (run' [PeerUp 2 True, Tick 20000] ours)+      standing both `shouldBe` PoolSynced+      let held = fst (run' [Named 2 [7], Checked 2 [] [7], Body (Just 2) 7 [], Offered 7 Unverified] both)+      holding held `shouldBe` 1+      standing held `shouldBe` PoolSynced+      -- the same from a start: the held transaction does not keep the+      -- store from being in sync+      let waiting = [PeerUp 2 True, Named 2 [7], Checked 2 [] [7], Body (Just 2) 7 [], Offered 7 Unverified]+      standing (fst (run' (waiting <> [Tick 20000]) ours)) `shouldBe` PoolSynced+    it "is in sync when its node is read more often than a request is given" $ do+      -- read at 0 and after ten seconds: at twenty it is twenty seconds+      -- since the first reading, and ten since the last. Counted from the+      -- last, a node read this often never answered.+      let brisk = defaultConfig {sweepGap = 5000, sweepFast = 5000}+          often = fst (run' [PeerUp 1 True, Own 1, Synced True] (start brisk 0)) :: Ingest Int Int [Int]+          (s, outs) = run' [Tick 10000, Tick 20000] often+      length [() | Sweep _ <- outs] `shouldBe` 1+      standing s `shouldBe` PoolSynced+    it "does not stay in sync when its last node of the operator goes" $ do+      let synced = fst (run' [Tick 20000] ours)+      standing synced `shouldBe` PoolSynced+      let gone = fst (run' [PeerDown 1] synced)+      standing gone `shouldBe` PoolUnknown+      -- back, it has not read what the node took meanwhile+      standing (fst (run' [PeerUp 1 True, Own 1] gone)) `shouldBe` PoolSyncing+  where+    ready :: Ingest Int Int [Int]+    ready = fst (run' [PeerUp 1 True, Synced True] (start defaultConfig 0))+    -- the same, with the peer a node of the operator+    ours :: Ingest Int Int [Int]+    ours = fst (run' [Own 1] ready)+    run = flip run' ready+    run' inputs s0 = foldl' (\(s, outs) i -> let (s', o) = step id i s in (s', outs <> o)) (s0, []) inputs++-- | A store with an empty pool and one source whose mempool has so many+-- transactions, in chains of 24: what a store goes through when its Redis+-- lost its data, or when it starts with a new pool. Gives how many+-- transactions the pool took, how many offers it refused for lack of what+-- the transaction spends from, and the time that it all took.+--+-- It is the runner in small: it carries out what the machine says, one+-- output at a time, and tells the machine the time once a second. The+-- node names its whole mempool when asked and gives every transaction+-- that it is asked for. The pool takes a transaction when it has all+-- that it spends from. Only an offer takes time, a millisecond: about+-- what one took on a server, and what made the futile ones matter.+--+-- The ids are scattered, as hashes are, so that the order in which the+-- machine asks for transactions says nothing of which spends from which:+-- most come before what they spend from, and wait for it.+refill :: Int -> (Int, Int, Tick)+refill count = go (start defaultConfig 0) IntSet.empty 0 0 0 0 (Seq.fromList [PeerUp 1 True, Synced True])+  where+    -- a prime above the count: multiplying by a number below it scatters+    -- the ids and gives no two the same+    prime = 65537+    idOf k = ((k + 1) * 48271) `mod` prime+    bodies = IntMap.fromList [(idOf k, [idOf (k - 1) | k `mod` 24 /= 0]) | k <- [0 .. count - 1]]+    names = IntMap.keys bodies+    cost = 1+    go ::+      Ingest Int Int [Int] ->+      IntSet.IntSet ->+      Tick ->+      Tick ->+      Int ->+      Int ->+      Seq.Seq (Input Int Int [Int]) ->+      (Int, Int, Tick)+    go s pool now told taken refused queue+      -- all in, or an hour gone: the test says which+      | IntSet.size pool == count || now > 3600000 = (taken, refused, now)+      | otherwise = case Seq.viewl queue of+          -- nothing to do until the next second+          Seq.EmptyL -> let t = told + 1000 in feed (Tick t) s pool t t taken refused Seq.empty+          i Seq.:< rest+            | now - told >= 1000 -> feed (Tick now) s pool now now taken refused queue+            | otherwise -> feed i s pool now told taken refused rest+    feed i s pool now told taken refused queue =+      let (s', outs) = step id i s+          (pool', now', taken', refused', answers) = foldl' perform (pool, now, taken, refused, []) outs+       in go s' pool' now' told taken' refused' (queue <> Seq.fromList (reverse answers))+    perform (pool, now, taken, refused, answers) = \case+      Sweep p -> (pool, now, taken, refused, Named p names : answers)+      Check p hs ->+        let (yes, no) = partition (`IntSet.member` pool) hs+         in (pool, now, taken, refused, Checked p yes no : answers)+      Get p hs -> (pool, now, taken, refused, reverse [Body (Just p) h (bodies IntMap.! h) | h <- hs] <> answers)+      Offer h b -> case filter (`IntSet.notMember` pool) b of+        [] -> (IntSet.insert h pool, now + cost, taken + 1, refused, Offered h Settled : answers)+        lacks -> (pool, now + cost, taken, refused + 1, Offered h (Orphan lacks) : answers)+      Gone _ _ -> (pool, now, taken, refused, answers)
test/Haskoin/Store/IntegrationSpec.hs view
@@ -25,19 +25,42 @@ -- is filled in the background, so the comparison is retried for up to 30 -- seconds before it fails. --+-- Each environment is a pod of podman-test ("Test.Podman"): Valkey on a Unix+-- socket of its own, and the node with its RPC and peer-to-peer ports+-- bridged to sockets. The store reaches all three through the sockets,+-- with @--redis-url unix:PATH@, the peer @unix:PATH@ and+-- @--node-rpc-socket@, so the pod has no network and environments that run+-- at once never meet. The web servers of the store listen on Unix sockets+-- of their own too ('listening'), and the tests reach them there: no test+-- names an address or a port of the machine.+-- -- The tests are skipped when Podman cannot run containers, or when--- @HASKOIN_STORE_NO_PODMAN@ is set. Containers are removed when the tests--- end, data is kept in tmpfs mounts and in a temporary directory under--- @\/dev\/shm@ (or @$XDG_RUNTIME_DIR@), and every container has a memory--- limit. Set @HASKOIN_TEST_LOG@ to see the log of the store.-module Haskoin.Store.IntegrationSpec (spec) where+-- @PODMAN_TEST_SKIP@ is set. Pods are removed when the tests end, data is+-- kept in tmpfs mounts and in a temporary directory under @\/dev\/shm@ (or+-- @$XDG_RUNTIME_DIR@), and every container has a memory limit. Set+-- @HASKOIN_TEST_LOG@ to see the log of the store.+module Haskoin.Store.IntegrationSpec+  ( spec, +    -- * For the other specs that run a store against a node+    Server (..),+    arr,+    getJSON,+    grantedBy,+    listening,+    storeConfig,+    webConfig,+    withTestLog,+  )+where+ import Control.Concurrent (threadDelay) import Control.Concurrent.Async (async, cancel, forConcurrently, link, withAsync) import Control.Exception (throwIO, try) import Control.Lens ((&), (.~), (?~), (^.)) import Control.Monad (forM_, forever, replicateM_, unless, void, when) import Data.Aeson (Value (..), eitherDecode, object, toJSON, (.=))+import Data.Aeson qualified as Aeson import Data.Aeson.Key qualified as Key import Data.Aeson.KeyMap qualified as KeyMap import Data.ByteString.Char8 qualified as C8@@ -49,14 +72,16 @@ import Data.Foldable (toList) import Data.HashMap.Strict qualified as HashMap import Data.HashSet qualified as HashSet-import Data.IORef (IORef, modifyIORef', newIORef, readIORef)+import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef) import Data.IntMap.Strict qualified as IntMap-import Data.List (nub, sort, sortOn)+import Data.List (isInfixOf, nub, sort, sortOn) import Data.List.NonEmpty qualified as NonEmpty import Data.Map.Strict qualified as Map import Data.Maybe (fromMaybe, isJust, isNothing, mapMaybe) import Data.Ord (Down (..))+import Data.Sequence qualified as Seq import Data.Serialize (decode, encode)+import Data.Set qualified as Set import Data.String.Conversions (cs) import Data.Text (Text) import Data.Text qualified as T@@ -69,6 +94,7 @@     BloomFlags (..),     Network (..),     OutPoint (..),+    TokenData (..),     Tx (..),     TxHash (..),     TxIn (..),@@ -90,6 +116,7 @@     prvSubKey,     pubSubKey,     sha256,+    textToAddr,     txHash,     txHashToHex,     xPrvWif,@@ -99,7 +126,7 @@     xPubWitnessAddr,   ) import Haskoin qualified as H-import Haskoin.Node (LogLevel (..), Logger (..), getPeers, withConnection, withLogger)+import Haskoin.Node (LogLevel (..), Logger (..), Permission (..), Permissions, getPeers, withConnection, withLogger) import Haskoin.Store   ( DeriveType (..),     Store (..),@@ -111,6 +138,7 @@     decodeTxBody,     defaultXPubConfig,     runWebSocket,+    unixSocketManager,     withStore,   ) import Haskoin.Store.Common (Limits (..), StoreEvent (..))@@ -119,17 +147,22 @@     BlockData (..),     BlockHealth (..),     BlockRef (..),+    DatabaseHealth (..),     Event (..),     EventCommand (..),     Except (..),     HealthCheck (..),+    MempoolHealth (..),     RawResult (..),     SerialList (..),     Spender (..),+    TokenBalance (..),     Transaction (..),     TxData (..),     TxRef (..),+    Unspent (..),     XPubBal (..),+    scriptTokens,   ) import Haskoin.Store.Database.Query qualified as Q import Haskoin.Store.Exception (bracket, tryAny)@@ -138,15 +171,17 @@ import Haskoin.Store.Fleet.XPub (cacheHave, xpubId) import Haskoin.Store.Integration.Image (testImage) import Haskoin.Store.Integration.Node-import Haskoin.Store.Integration.Podman-import Haskoin.Store.Integration.Temp (withSystemTempDirectory)-import Haskoin.Store.Integration.Valkey+import Haskoin.Store.Integration.Temp (withRamDir, withSystemTempDirectory)+import Haskoin.Store.Integration.Valkey (redisContainer)+import Haskoin.Store.Integration.Valkey qualified as Valkey+import Haskoin.Store.Startup (redisConnectInfo) import Haskoin.Store.WebClient qualified as Client-import Haskoin.Store.WebCommon (ApiResource, NoCache (..), NoTx (..))+import Haskoin.Store.WebCommon (ApiResource, LimitsParam (..), NoCache (..), NoTx (..), OffsetParam (..)) import Haskoin.Store.XPub (EntryMoved (..), XPubReads (..)) import Haskoin.Store.XPub.Indexer (Settings (..)) import Haskoin.Store.XPub.Service (XPubConfig (..)) import NQE (publish, receive, withSubscription)+import Network.HTTP.Client (Manager, newManager) import Network.HTTP.Types (ResponseHeaders) import Network.Socket qualified as Socket import Network.WebSockets qualified as WS@@ -154,30 +189,53 @@ import Network.Wreq.Types (FormParam ((:=))) import System.Environment (lookupEnv) import System.Exit (ExitCode (..))-import System.Log.FastLogger (toLogStr)+import System.FilePath (takeDirectory, (</>))+import System.IO (hPutStrLn, stderr)+import System.Log.FastLogger (fromLogStr, toLogStr) import System.Process (readProcessWithExitCode) import Test.Hspec+import Test.Podman+  ( ContainerSpec (..),+    Endpoint (..),+    PodSpec (..),+    PodmanError,+    address,+    container,+    execWithin,+    pod,+    podmanUsable,+    socketFolder,+    socketInside,+    withPod,+  )+import Test.Podman qualified as Podman (Address (..)) import Text.Read (readMaybe) +-- | Each environment, a node, a Redis and a store of its own, is a group at+-- the top of the module, so that haskell-dev (of jprupp/tools) runs each in+-- a process of its own, at the same time as the others (@haskell-dev.toml@).+-- Their containers have names and ports of their own, and each process a+-- temporary folder of its own, so nothing is shared between them. spec :: Spec spec = do   usable <- runIO podmanUsable-  describe "Regtest chains in Podman" $ case usable of+  case usable of     Left why ->-      it "check the store against Bitcoin Core and Bitcoin Cash Node" $-        pendingWith why+      describe "Regtest chains in Podman" $+        it "check the store against Bitcoin Core and Bitcoin Cash Node" $+          pendingWith why     Right () -> do       forM_ [BitcoinCore, BitcoinCashNode] $ \kind ->         aroundAll (withEnvOf False kind) $-          describe (name kind <> " that does not whitelist the store") $+          describe ("Regtest " <> name kind <> " that does not whitelist the store") $             it "publishes what it verified, and keeps its node when sent what it cannot verify" strangerTest       aroundAll (withEnvAt True (Just (30 * 24 * 3600)) BitcoinCore) $-        describe "Bitcoin Core with blocks of a month ago" $+        describe "Regtest Bitcoin Core with blocks of a month ago" $           it "keeps what a reorganisation of an old block put back in the mempool" oldBlockTest       aroundAll (withEnv BitcoinCore) $-        describe "Bitcoin Core" (chainSpec BitcoinCore)+        describe "Regtest Bitcoin Core" (chainSpec BitcoinCore)       aroundAll (withEnv BitcoinCashNode) $-        describe "Bitcoin Cash Node" (chainSpec BitcoinCashNode)+        describe "Regtest Bitcoin Cash Node" (chainSpec BitcoinCashNode)  -- | The name of a node, as people write it. name :: NodeKind -> String@@ -222,11 +280,11 @@     node :: !Node,     net :: !Network,     store :: !Store,-    -- | base URL of the first web server-    cached :: !String,-    -- | base URL of the second web server of the same store, which answers-    -- xpubs from the same cache-    plain :: !String,+    -- | the first web server+    cached :: !Server,+    -- | the second web server of the same store, which answers xpubs from+    -- the same cache+    plain :: !Server,     -- | address of the wallet of the node, to mine to     miner :: !Text,     -- | connection to Redis, to look at the keys@@ -235,7 +293,9 @@     -- directory, to start another one     configIn :: FilePath -> StoreConfig,     -- | the same for a store that is a member of a fleet-    memberIn :: FilePath -> StoreConfig+    memberIn :: FilePath -> StoreConfig,+    -- | the last lines of the log of the store ('withTestLog')+    logTail :: IO [String]   }  -- | Initial gap and gap of the store under test, the defaults.@@ -257,85 +317,157 @@ -- the node's clock is set back for them with @setmocktime@, and left so. withEnvAt :: Bool -> Maybe Int -> NodeKind -> (Env -> IO ()) -> IO () withEnvAt whitelisted ago kind go = do-  image <- testImage-  withContainer (redisContainer image) $ \redis -> do-    redisPort <- hostPort redis 6379-    let redisURL = "redis://127.0.0.1:" <> show redisPort-    waitRedis redisURL+  -- Valkey and the node in one pod, reached through sockets of the pod:+  -- tests that run at once each have their own, and no port of the+  -- machine is taken+  let nodeSpec = (if whitelisted then nodeContainer else strangerContainer) kind+      envPod = (pod "env" [redisContainer, nodeSpec]) {readyWithin = 120}+  withPod envPod $ \p -> do+    let redisURL = Valkey.redisURL p     writeOldKeys redisURL-    withContainer ((if whitelisted then nodeContainer else strangerContainer) kind image) $ \c -> do-      rpcPort <- hostPort c 18443-      p2pPort <- hostPort c 18444-      let node =-            Node-              { kind = kind,-                url = "http://127.0.0.1:" <> show rpcPort <> "/",-                p2p = p2pPort-              }-      waitRpc node-      -- before the wallet is made: a wallet does not look at blocks older-      -- than itself-      forM_ ago $ \secs -> do-        now <- round <$> getPOSIXTime-        void $ rpc node "setmocktime" [Number (fromIntegral (now - secs :: Int))]-      ensureWallet node-      miner <- getNewAddress node-      -- enough mature coinbases for the wallet to fund every test without-      -- long chains of unconfirmed change-      void $ generateTo node 150 miner-      withRamDir $ \dir -> withTestLogger $ \logger -> do-        let net = nodeNetwork kind-            cfg = storeConfig net logger dir redisURL p2pPort-        withStore cfg $ \store -> do-          listening $ \(cachedSock, cachedPort) -> listening $ \(plainSock, plainPort) -> do-            let web s = runWebSocket (webConfig logger s)-            conn <- Redis.checkedConnect (either error id (Redis.parseConnectInfo redisURL))-            withAsync (web store cachedSock) $ \a1 ->-              -- a second server of the same store: the cache cannot be-              -- turned off, so both answer xpubs from it-              withAsync (web store plainSock) $ \a2 -> do-                link a1-                link a2-                let env =-                      Env-                        { kind = kind,-                          node = node,-                          net = net,-                          store = store,-                          cached = "http://127.0.0.1:" <> show cachedPort,-                          plain = "http://127.0.0.1:" <> show plainPort,-                          miner = miner,-                          redis = conn,-                          configIn = \d -> storeConfig net logger d redisURL p2pPort,-                          memberIn = \d -> storeConfig net logger d redisURL p2pPort-                        }-                waitSynced env-                go env+    node <- nodeOf kind p+    waitRpc node+    -- before the wallet is made: a wallet does not look at blocks older+    -- than itself+    forM_ ago $ \secs -> do+      now <- round <$> getPOSIXTime+      void $ rpc node "setmocktime" [Number (fromIntegral (now - secs :: Int))]+    ensureWallet node+    miner <- getNewAddress node+    -- enough mature coinbases for the wallet to fund every test without+    -- long chains of unconfirmed change+    void $ generateTo node 150 miner+    withRamDir $ \dir -> withTestLog $ \logger logTail -> do+      let net = nodeNetwork kind+          granted = grantedBy whitelisted kind+          cfg = storeConfig net logger dir redisURL node.peer granted+      withStore cfg $ \store -> do+        listening $ \(cachedSock, cachedServer) -> listening $ \(plainSock, plainServer) -> do+          let web s = runWebSocket (webConfig logger s)+          conn <- Redis.checkedConnect (either error id (redisConnectInfo redisURL))+          withAsync (web store cachedSock) $ \a1 ->+            -- a second server of the same store: the cache cannot be+            -- turned off, so both answer xpubs from it+            withAsync (web store plainSock) $ \a2 -> do+              link a1+              link a2+              let env =+                    Env+                      { kind = kind,+                        node = node,+                        net = net,+                        store = store,+                        cached = cachedServer,+                        plain = plainServer,+                        miner = miner,+                        redis = conn,+                        configIn = \d -> storeConfig net logger d redisURL node.peer granted,+                        memberIn = \d -> storeConfig net logger d redisURL node.peer granted,+                        logTail+                      }+              waitSynced env+              go env +-- | Print what the node and the store say of their sync, and the last lines+-- of the log of the store, to the standard error: for a store that did not+-- sync in time. The node gives its chain and, for each peer, the height it+-- started at and the headers and blocks that it knows the peer has; the+-- store gives its health, which has its blocks and headers, and its peers;+-- and the log of its block store says which blocks it asked for, which came,+-- and which peer it let go and why.+syncDiagnostics :: Env -> IO ()+syncDiagnostics env = do+  say "--- the store did not sync: what the node and the store say"+  report "the node's chain" (rpc env.node "getblockchaininfo" [])+  report "the node's peers" (rpc env.node "getpeerinfo" [])+  report "the store's health" (snd <$> getJSON env.plain "/health")+  report "the store's peers" (snd <$> getJSON env.plain "/peers")+  recent <- env.logTail+  say ("--- the last " <> show (length recent) <> " lines of the log of the store")+  mapM_ say recent+  say "--- end of the diagnostics"+  where+    say = hPutStrLn stderr+    report what get =+      tryAny get >>= \case+        Right v -> say (what <> ": " <> cs (BL.toStrict (Aeson.encode v)))+        Left e -> say (what <> ": could not be read: " <> show e)+ -- | A logger that prints the log of the store if @HASKOIN_TEST_LOG@ is set, -- and discards it otherwise. Each line starts with the time it was logged -- at, as seconds of the hour to the millisecond: what several stores do at -- once can only be put in order, and a wait told from a hang, by the time. withTestLogger :: (Logger -> IO a) -> IO a-withTestLogger f =+withTestLogger f = withTestLog (\logger _ -> f logger)++-- | 'withTestLogger' that also keeps the last 'tailLines' lines of the log,+-- at the level of debugging whether it prints them or not, and gives them+-- to the action: what a test prints when the store does something it should+-- not, such as stop syncing, which happens too seldom to be run again with+-- the log on ('syncDiagnostics').+--+-- It keeps as many lines again of those above the level of debugging, and+-- gives them first. A store that is stuck goes on answering the test and+-- waiting for events, a line of debugging for each, and what made it+-- stuck is soon out of the last lines: a test of the mempool failed with+-- four hundred lines of a store that did nothing, and nothing of the+-- half minute before, in which it lost four transactions.+withTestLog :: (Logger -> IO [String] -> IO a) -> IO a+withTestLog f = do+  kept <- newIORef Seq.empty+  said <- newIORef Seq.empty+  let after ref line = atomicModifyIORef' ref $ \q -> (Seq.drop (Seq.length q + 1 - tailLines) (q Seq.|> line), ())+      keep line = do+        after kept line+        unless ("[Debug" `isInfixOf` line) (after said line)+      recent = do+        above <- toList <$> readIORef said+        every <- toList <$> readIORef kept+        return (["--- above the level of debugging"] <> above <> ["--- at every level"] <> every)+      recording printed =+        Logger+          { level = LevelDebug,+            source = "",+            push = \line -> do+              at <- stamp+              let stamped = at <> line+              keep (cs (fromLogStr stamped))+              printed stamped+          }   lookupEnv "HASKOIN_TEST_LOG" >>= \case-    Just v | v `notElem` ["", "0"] -> withLogger LevelDebug (f . timed)-    _ -> f Logger {level = LevelError, source = "", push = \_ -> return ()}+    Just v | v `notElem` ["", "0"] -> withLogger LevelDebug $ \l -> f (recording l.push) recent+    _ -> f (recording (\_ -> return ())) recent   where-    timed l = l {push = \line -> stamp >>= \at -> l.push (at <> line)} :: Logger     stamp = do       now <- getPOSIXTime       let (seconds, millis) = (floor (now * 1000) `mod` 3600000 :: Int) `divMod` 1000           padded = replicate (3 - length (show millis)) '0' <> show millis       return (toLogStr (show seconds <> "." <> padded <> " ")) +-- | The permissions that the node of an environment grants the store, as+-- its operator would tell the store with @--peer-permission@: a bare+-- @-whitelist@ gives @noban@, @mempool@ and @relay@ ('nodeContainer'), and+-- the node that does not whitelist the store gives Bitcoin Core's+-- @mempool@ alone ('strangerContainer').+grantedBy :: Bool -> NodeKind -> Permissions+grantedBy whitelisted kind+  | whitelisted = Set.fromList [PermNoBan, PermMempool, PermRelay]+  | kind == BitcoinCore = Set.singleton PermMempool+  | otherwise = Set.empty++-- | How many of the last lines of the log of a store a test keeps.+tailLines :: Int+tailLines = 400+ -- | Store with the default gaps, caching every used xpub, with small RocksDB -- buffers and caches.-storeConfig :: Network -> Logger -> FilePath -> String -> Int -> StoreConfig-storeConfig net logger dir redisURL p2pPort =+storeConfig :: Network -> Logger -> FilePath -> String -> String -> Permissions -> StoreConfig+storeConfig net logger dir redisURL peer granted =   StoreConfig     { maxPeers = 1,-      initPeers = ["127.0.0.1:" <> show p2pPort],+      initPeers = [peer],+      peerPermissions = granted,+      foreignPeers = False,       discover = False,       db = dir,       net = net,@@ -353,6 +485,9 @@       blockPing = 5,       maxPeerLife = 48 * 3600,       connect = withConnection,+      nodePeerRpc = Nothing,+      nodePeerRpcSocket = Nothing,+      nodePeerZmq = Nothing,       stats = Nothing,       bloom = True,       maxOpenFiles = Just 256,@@ -366,7 +501,9 @@ webConfig :: Logger -> Store -> WebConfig webConfig logger store =   WebConfig-    { host = "127.0.0.1",+    { -- not used: each server of the tests is given its Unix socket+      -- ('listening')+      host = "localhost",       port = 0,       store = store,       maxLaggingBlocks = 100,@@ -376,26 +513,48 @@       version = "test",       stats = Nothing,       tickerRefresh = 90 * 1000 * 1000,-      tickerURL = "http://127.0.0.1:9/",-      priceHistoryURL = "http://127.0.0.1:9/",+      -- a name that never resolves (RFC 2606): nothing is asked of a+      -- port, and the store does without its prices+      tickerURL = "http://ticker.invalid/",+      priceHistoryURL = "http://ticker.invalid/",       noBlockchainInfo = False,       healthCheckInterval = 5,       accessLog = False,       nodeRpc = Nothing,+      nodeRpcSocket = Nothing,+      nodeZmq = Nothing,       tls = Nothing,       logger = logger     } --- | A socket that listens on a port of the loopback interface that the--- system chose, with that port. Nothing else can take the port between--- choosing it and serving on it.-listening :: ((Socket.Socket, Int) -> IO a) -> IO a-listening f =-  bracket (Socket.socket Socket.AF_INET Socket.Stream Socket.defaultProtocol) Socket.close $ \s -> do-    Socket.bind s (Socket.SockAddrInet 0 (Socket.tupleToHostAddress (127, 0, 0, 1)))+-- | A web server of the tests, on a Unix socket of its own: the URL that the+-- requests name, whose host is never looked up, the socket, and an HTTP+-- client whose every connection goes to the socket.+data Server = Server+  { url :: !String,+    socket :: !FilePath,+    manager :: !Manager+  }++-- | The options of a request to a server, through its socket, that take+-- every status for an answer.+through :: Server -> Wreq.Options+through server =+  Wreq.defaults+    & Wreq.manager .~ Right server.manager+    & Wreq.checkResponse ?~ (\_ _ -> return ())++-- | A socket that listens on a Unix socket in a folder of its own, and the+-- server that it is to a client. Tests that run at once never meet, and no+-- port of the machine is taken.+listening :: ((Socket.Socket, Server) -> IO a) -> IO a+listening f = withRamDir $ \dir -> do+  let path = dir <> "/web.sock"+  manager <- newManager (unixSocketManager path)+  bracket (Socket.socket Socket.AF_UNIX Socket.Stream Socket.defaultProtocol) Socket.close $ \s -> do+    Socket.bind s (Socket.SockAddrUnix path)     Socket.listen s 128-    port <- Socket.socketPort s-    f (s, fromIntegral port)+    f (s, Server {url = "http://localhost", socket = path, manager})  ------------------------------------------------------------------------------- -- Talking to the store@@ -403,20 +562,16 @@  -- | Status and JSON body of a request. A body that is not JSON, as the -- plain-text Blockchain.info queries give, is returned as a string.-getJSON :: String -> String -> IO (Int, Value)-getJSON base path = do-  r <- Wreq.getWith opts (base <> path)+getJSON :: Server -> String -> IO (Int, Value)+getJSON server path = do+  r <- Wreq.getWith (through server) (server.url <> path)   return (r ^. Wreq.responseStatus . Wreq.statusCode, body (r ^. Wreq.responseBody))-  where-    opts = Wreq.defaults & Wreq.checkResponse ?~ (\_ _ -> return ())  -- | Like 'getJSON', posting a form.-postForm :: String -> String -> [(C8.ByteString, Text)] -> IO (Int, Value)-postForm base path params = do-  r <- Wreq.postWith opts (base <> path) [k := v | (k, v) <- params]+postForm :: Server -> String -> [(C8.ByteString, Text)] -> IO (Int, Value)+postForm server path params = do+  r <- Wreq.postWith (through server) (server.url <> path) [k := v | (k, v) <- params]   return (r ^. Wreq.responseStatus . Wreq.statusCode, body (r ^. Wreq.responseBody))-  where-    opts = Wreq.defaults & Wreq.checkResponse ?~ (\_ _ -> return ())  body :: BL.ByteString -> Value body b = either (const (String (cs b))) id (eitherDecode b)@@ -495,6 +650,7 @@               (_, b) <- getJSON env.plain "/block/best?notx=true"               (_, m) <- getJSON env.plain "/mempool"               let ours = [t | String t <- arr m]+              syncDiagnostics env               expectationFailure $                 "The store did not sync to block "                   <> cs best@@ -1075,7 +1231,7 @@   forM_ [block <> "/raw", "/block/best/raw"] $ \p ->     (field "result" <$> plainJSON env p) `shouldReturn` Just hex   plainJSON env ("/block/height/" <> show height <> "/raw") `shouldReturn` toJSON [hex]-  text <- Wreq.get (env.plain <> "/blockchain/rawblock/" <> cs best <> "?format=hex")+  text <- Wreq.getWith (through env.plain) (env.plain.url <> "/blockchain/rawblock/" <> cs best <> "?format=hex")   String (cs (text ^. Wreq.responseBody)) `shouldBe` hex   lookup "Content-Length" (text ^. Wreq.responseHeaders) `shouldBe` Nothing   -- the transactions of a block@@ -1127,12 +1283,20 @@   map (textField "hash") hs `shouldBe` [Just best]   tx <- plainJSON env ("/transaction/" <> cs t1)   textField "txid" tx `shouldBe` Just t1+  -- Whether a transaction can be replaced by fee is a fact of its+  -- network and of whether a block confirms it: every unconfirmed one can+  -- on Bitcoin, whatever it signals, none on Bitcoin Cash, and none that+  -- is confirmed. The second payment signals nothing.+  field "rbf" tx `shouldBe` Just (Bool False)+  waitFor "the second payment in the store" ((== 200) . fst <$> getJSON env.plain ("/transaction/" <> cs t2))+  unconfirmed <- plainJSON env ("/transaction/" <> cs t2)+  field "rbf" unconfirmed `shouldBe` Just (Bool env.net.replaceByFee)   rawNode <- rpc env.node "getrawtransaction" [String t1, Bool False]   raw <- plainJSON env ("/transaction/" <> cs t1 <> "/raw")   field "result" raw `shouldBe` Just rawNode   -- the same bytes as a list of one, and as the text of Blockchain.info   plainJSON env ("/transactions/raw?txids=" <> cs t1) `shouldReturn` toJSON [rawNode]-  rawText <- Wreq.get (env.plain <> "/blockchain/rawtx/" <> cs t1 <> "?format=hex")+  rawText <- Wreq.getWith (through env.plain) (env.plain.url <> "/blockchain/rawtx/" <> cs t1 <> "?format=hex")   String (cs (rawText ^. Wreq.responseBody)) `shouldBe` rawNode   bal <- plainJSON env ("/address/" <> cs a <> "/balance")   num "confirmed" bal `shouldBe` 400000@@ -1444,7 +1608,7 @@  writeOldKeys :: String -> IO () writeOldKeys url = do-  conn <- Redis.checkedConnect (either error id (Redis.parseConnectInfo url))+  conn <- Redis.checkedConnect (either error id (redisConnectInfo url))   void . Redis.runRedis conn $ mapM_ (uncurry Redis.set) oldKeys   Redis.disconnect conn @@ -1455,11 +1619,8 @@ errorFormatTest env = do   let unknown = "/transaction/" <> replicate 64 'a'       ask accept = do-        let opts =-              Wreq.defaults-                & Wreq.checkResponse ?~ (\_ _ -> return ())-                & maybe id (\a -> Wreq.header "Accept" .~ [a]) accept-        r <- Wreq.getWith opts (env.plain <> unknown)+        let opts = through env.plain & maybe id (\a -> Wreq.header "Accept" .~ [a]) accept+        r <- Wreq.getWith opts (env.plain.url <> unknown)         return           ( r ^. Wreq.responseStatus . Wreq.statusCode,             r ^. Wreq.responseHeader "Content-Type",@@ -1479,14 +1640,19 @@   let x = newXPub env "client" DeriveNormal       -- the client puts the name of the network in the path, as       -- api.haskoin.com has it, and the server of the tests has none-      conf = Client.ApiConfig {net = env.net {name = ""}, host = env.plain}+      conf = Client.ApiConfig {net = env.net {name = ""}, host = env.plain.url, socket = Just env.plain.socket}       call :: (ApiResource a b) => a -> IO b       call r = Client.apiCall conf r >>= either (fail . show) return   heard <- newIORef []   listener <- async . Client.apiEvents conf $ \e -> modifyIORef' heard (e :) >> return True-  -- the client is listening once it hears of a block-  void (mine env 1)-  waitFor "the client to listen" (not . null <$> readIORef heard)+  -- the client is listening once it hears of a block. Its stream may not+  -- be open yet when a block comes, and the event of that block is then+  -- gone, so another block is mined at each look until it hears one.+  let listening =+        readIORef heard >>= \case+          [] -> False <$ mine env 1+          _ -> return True+  waitFor "the client to listen" listening   ref <- newLedger   paid <- pay env x ref [([0, 0], 100000)]   txid <- maybe (fail "Not a hash") return (hexToTxHash paid)@@ -1506,6 +1672,10 @@   sum (map (.balance.confirmed) keys.get) `shouldBe` 100000   health <- call Client.GetHealth   health.blocks.blocks `shouldSatisfy` (> 0)+  -- the node of the tests whitelists the store, so it is a source+  fmap (\(m :: MempoolHealth) -> m.sources) health.mempool `shouldBe` Just 1+  -- the database is in the check, with what RocksDB said at its last poll+  fmap (\(d :: DatabaseHealth) -> d.errors) health.database `shouldBe` Just 0   -- an error comes back as the error that it is   unknown <- Client.apiCall conf (Client.GetTx (TxHash (sha256 ("nothing" :: C8.ByteString))))   either Just (const Nothing) unknown `shouldBe` Just ThingNotFound@@ -1515,28 +1685,54 @@  -- | A web server on the store of the tests, given a certificate that is -- made for the occasion: it answers over HTTPS, and does not answer a--- request that is not encrypted. The requests are made with curl, told--- not to mind who signed the certificate.+-- request that is not encrypted.+--+-- openssl makes the certificate and curl makes the requests, both in a+-- container of the test image ("Haskoin.Store.Integration.Image"), not+-- from the machine: the server listens on a Unix socket of the folder of+-- the pod, where the container reaches it, and curl is told not to mind+-- who signed the certificate. tlsTest :: Env -> IO ()-tlsTest env = withSystemTempDirectory "haskoin-store-tls-" $ \dir -> withTestLogger $ \logger -> do-  let certificate = dir <> "/cert.pem"-      key = dir <> "/key.pem"+tlsTest env = withTestLogger $ \logger -> withPod (pod "tls" [tools]) {ready = []} $ \p -> do+  path <- case address p "web" of+    Podman.UnixSocket at -> return at+    a -> fail ("The endpoint of the server is not a socket: " <> show a)+  -- the folder of the pod, as the tests and as the container see it+  let here = takeDirectory path+      there = socketFolder+      run = execWithin 60 p "tools"       subject = ["-subj", "/CN=localhost", "-days", "1"]-      files = ["-keyout", key, "-out", certificate]-  (made, _, why) <--    readProcessWithExitCode "openssl" (["req", "-x509", "-newkey", "rsa:2048", "-nodes"] <> files <> subject) ""-  (made, why) `shouldSatisfy` ((== ExitSuccess) . fst)-  listening $ \(sock, port) -> do-    let config = (webConfig logger env.store) {tls = Just (certificate, key)} :: WebConfig-        status scheme = do-          let url = scheme <> "://127.0.0.1:" <> show port <> "/health"-          let quietly = ["-sk", "-m", "5", "-o", "/dev/null", "-w", "%{http_code}"]-          (_, code, _) <- readProcessWithExitCode "curl" (quietly <> [url]) ""-          return code+      files = ["-keyout", there </> "key.pem", "-out", there </> "cert.pem"]+  _ <- run (["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes"] <> files <> subject)+  let config = (webConfig logger env.store) {tls = Just (here </> "cert.pem", here </> "key.pem")} :: WebConfig+      status scheme = do+        let quietly = ["-sk", "-m", "5", "-o", "/dev/null", "-w", "%{http_code}"]+            url = scheme <> "://localhost/health"+        -- curl prints the status, and 000 with no answer, and then fails+        r <- try @PodmanError (run (["curl", "--unix-socket", socketInside "web"] <> quietly <> [url]))+        return (either (const "000") id r)+  bracket (Socket.socket Socket.AF_UNIX Socket.Stream Socket.defaultProtocol) Socket.close $ \sock -> do+    Socket.bind sock (Socket.SockAddrUnix path)+    Socket.listen sock 128     withAsync (runWebSocket config sock) $ \web -> do       link web       waitFor "the server to answer over HTTPS" ((== "200") <$> status "https")       status "http" `shouldNotReturn` "200"+  where+    -- the test image, idle until the test runs its programs; the socket+    -- of the server is in the folder of the pod, as a socket of the+    -- container would be. SELinux lets the tests connect to a socket that a+    -- container made, not a container connect to one that the tests made,+    -- so this container, which has no network and only reaches that+    -- socket, runs without its label.+    tools =+      (container "tools" testImage)+        { entrypoint = Just "sleep",+          command = ["infinity"],+          memory = Just "256m",+          endpoints = [Native "web"],+          options = ["--security-opt", "label=disable"]+        }  -- | The parts of HTTP that are not about any one endpoint: a request for -- the headers alone, the question that a browser asks before a request@@ -1546,19 +1742,19 @@ httpTest env = do   let x = newXPub env "http" DeriveNormal       addresses = T.intercalate "," [at env x [0, i] | i <- [0 .. 2]]-      quiet = Wreq.defaults & Wreq.checkResponse ?~ (\_ _ -> return ())+      quiet = through env.plain       statusOf r = r ^. Wreq.responseStatus . Wreq.statusCode   -- the headers of an answer, without the answer-  headed <- Wreq.headWith quiet (env.plain <> "/block/best")+  headed <- Wreq.headWith quiet (env.plain.url <> "/block/best")   (statusOf headed, headed ^. Wreq.responseHeader "Content-Type") `shouldBe` (200, "application/json")   -- what may be asked from another site-  asked <- Wreq.optionsWith quiet (env.plain <> "/transactions")+  asked <- Wreq.optionsWith quiet (env.plain.url <> "/transactions")   statusOf asked `shouldBe` 204   asked ^. Wreq.responseHeader "Access-Control-Allow-Methods" `shouldBe` "GET, HEAD, POST, DELETE, OPTIONS"   asked ^. Wreq.responseHeader "Access-Control-Allow-Origin" `shouldBe` "*"   -- compressed for a client that reads it, and the same answer   let balances = "/address/balances?addresses=" <> T.unpack addresses-  packed <- Wreq.getWith (quiet & Wreq.header "Accept-Encoding" .~ ["gzip"]) (env.plain <> balances)+  packed <- Wreq.getWith (quiet & Wreq.header "Accept-Encoding" .~ ["gzip"]) (env.plain.url <> balances)   packed ^. Wreq.responseHeader "Content-Encoding" `shouldBe` "gzip"   (_, inQuery) <- getJSON env.plain balances   -- the same list in the body of a request, where it may be as long as it likes@@ -1567,10 +1763,10 @@   inBody `shouldBe` inQuery   length (arr inBody) `shouldBe` 3   -- the reference of the API, as a page and as what the page shows-  page <- Wreq.getWith quiet (env.plain <> "/")+  page <- Wreq.getWith quiet (env.plain.url <> "/")   (statusOf page, page ^. Wreq.responseHeader "Content-Type") `shouldBe` (200, "text/html; charset=utf-8")   BL.toStrict (page ^. Wreq.responseBody) `shouldSatisfy` C8.isInfixOf "swagger-ui"-  reference <- Wreq.getWith quiet (env.plain <> "/swagger.yaml")+  reference <- Wreq.getWith quiet (env.plain.url <> "/swagger.yaml")   statusOf reference `shouldBe` 200   -- one server, the one that served it, wherever it is mounted   let described = BL.toStrict (reference ^. Wreq.responseBody)@@ -1688,10 +1884,8 @@  publishBody :: Env -> C8.ByteString -> IO (Int, Value) publishBody env bytes = do-  r <- Wreq.postWith opts (env.plain <> "/transactions") bytes+  r <- Wreq.postWith (through env.plain) (env.plain.url <> "/transactions") bytes   return (r ^. Wreq.responseStatus . Wreq.statusCode, body (r ^. Wreq.responseBody))-  where-    opts = Wreq.defaults & Wreq.checkResponse ?~ (\_ _ -> return ())  -- | A good transaction whose input the store cannot judge, because it -- would have to run a script: it spends a coin locked by a script of its@@ -1824,34 +2018,35 @@ -- what the store verified goes to the peers. Each that is published is -- answered 202. askTest :: Env -> IO ()-askTest env = withTestLogger $ \logger -> listening $ \(sock, port) -> listening $ \(deaf, deafPort) -> do-  let rpcURL = "http://test:test@" <> drop (length ("http://" :: String)) env.node.url-      config url = (webConfig logger env.store) {nodeRpc = Just url} :: WebConfig-      asking = env {plain = "http://127.0.0.1:" <> show port} :: Env-      unanswered = env {plain = "http://127.0.0.1:" <> show deafPort} :: Env-      up e = (== 200) . fst <$> getJSON e.plain "/block/best?notx=true"-      refused why (code, v) = (code, fmap (T.isInfixOf why) (textField "message" v)) `shouldBe` (400, Just True)-  -- nothing listens on port 1-  let withBoth go =-        withAsync (runWebSocket (config rpcURL) sock) $ \a ->-          withAsync (runWebSocket (config "http://127.0.0.1:1/") deaf) $ \b ->-            link a >> link b >> go-  withBoth $ do-    waitFor "the server that has the RPC of the node" (up asking)-    waitFor "the server whose node does not answer" (up unanswered)-    unsentFree env >>= publishTx asking >>= refused "min relay fee not met"-    unsent env >>= publishTx asking >>= \(code, v) -> do-      code `shouldBe` 202-      fmap (T.isInfixOf "full node took") (textField "message" v) `shouldBe` Just True-    -- not judged by the store: over RPC only-    first <- unjudged env-    publishTx env first >>= refused "cannot verify"-    publishTx unanswered first >>= refused "cannot verify"-    publishTx asking first >>= \(code, _) -> code `shouldBe` 202-    -- verified by the store: to the peers when the RPC does not answer-    unsent env >>= publishTx unanswered >>= \(code, v) -> do-      code `shouldBe` 202-      fmap (T.isInfixOf "Handed over") (textField "message" v) `shouldBe` Just True+askTest env = withTestLogger $ \logger -> listening $ \(sock, server) -> listening $ \(deaf, deafServer) ->+  withRamDir $ \dir -> do+    let rpc' socket =+          (webConfig logger env.store) {nodeRpc = Just env.node.url, nodeRpcSocket = Just socket} :: WebConfig+        asking = env {plain = server} :: Env+        unanswered = env {plain = deafServer} :: Env+        up e = (== 200) . fst <$> getJSON e.plain "/block/best?notx=true"+        refused why (code, v) = (code, fmap (T.isInfixOf why) (textField "message" v)) `shouldBe` (400, Just True)+        -- an RPC that does not answer: a socket that nothing listens on+        withBoth go =+          withAsync (runWebSocket (rpc' env.node.rpcSocket) sock) $ \a ->+            withAsync (runWebSocket (rpc' (dir <> "/nothing.sock")) deaf) $ \b ->+              link a >> link b >> go+    withBoth $ do+      waitFor "the server that has the RPC of the node" (up asking)+      waitFor "the server whose node does not answer" (up unanswered)+      unsentFree env >>= publishTx asking >>= refused "min relay fee not met"+      unsent env >>= publishTx asking >>= \(code, v) -> do+        code `shouldBe` 202+        fmap (T.isInfixOf "full node took") (textField "message" v) `shouldBe` Just True+      -- not judged by the store: over RPC only+      first <- unjudged env+      publishTx env first >>= refused "cannot verify"+      publishTx unanswered first >>= refused "cannot verify"+      publishTx asking first >>= \(code, _) -> code `shouldBe` 202+      -- verified by the store: to the peers when the RPC does not answer+      unsent env >>= publishTx unanswered >>= \(code, v) -> do+        code `shouldBe` 202+        fmap (T.isInfixOf "Handed over") (textField "message" v) `shouldBe` Just True  -- | Pay a script from the wallet of the node, and give the coin: where it -- is, and the output that holds it.@@ -1958,7 +2153,7 @@                 <> [H.OP_2, H.OP_NUMEQUAL]           internal = H.derivePubKey (secret '\x0e')           tree = H.TaprootOutput {internalKey = internal, mast = Just (H.MASTLeaf H.tapscriptLeafVersion leaf)}-      (coin, out) <- payScript env (H.taprootScriptOutput tree)+      (coin, out) <- payScript env (either error id (H.taprootScriptOutput tree))       unsigned <- spendingTo env coin       let leafOf = Just (H.leafHash H.tapscriptLeafVersion leaf, 0xffffffff)       digest <- right (H.taprootSigHash unsigned [out] 0 H.sigHashDefault Nothing leafOf)@@ -1970,7 +2165,7 @@                   -- an item for each key, that of the last key first                   stack = [sign (secrets !! 2), "", sign (head secrets)],                   script = leaf,-                  extIsOdd = odd (H.keyParity (H.taprootOutputKey tree)),+                  extIsOdd = odd (H.keyParity (either error id (H.taprootOutputKey tree))),                   leafVersion = H.tapscriptLeafVersion,                   internalKey = internal,                   control = [],@@ -1996,6 +2191,13 @@ -- tokens, and one that spends the output that holds them, are published: -- the store verifies their signatures, which cover the tokens, and does -- not take them for forged. A forged spend of the tokens is refused.+--+-- Then the four endpoints of tokens answer, through the client of+-- haskoin-store-data: the token balance of the address that holds them,+-- the holders, the unspent outputs and the transactions of the category,+-- first with both transactions in the mempool, then confirmed by a block.+-- Both outputs hold 1000 tokens at the same address, so its balance has+-- 1000 tokens in one output and two transactions, and has received 2000. tokenTest :: Env -> IO () tokenTest env = do   coins <- arr <$> rpc env.node "listunspent" []@@ -2029,6 +2231,41 @@     code `shouldBe` 400     fmap (T.isInfixOf "does not verify") (textField "message" v) `shouldBe` Just True   published spend+  category <- case coin ! "txid" of+    String t | Just c <- hexToTxHash t -> return c+    other -> fail ("Not a category: " <> show other)+  owner <- maybe (fail "Not an address") return (textToAddr env.net to)+  let conf = Client.ApiConfig {net = env.net {name = ""}, host = env.plain.url, socket = Just env.plain.socket}+      call :: (ApiResource a b) => a -> IO b+      call r = Client.apiCall conf r >>= either (fail . show) return+      everything = LimitsParam Nothing (OffsetParam 0) Nothing+      catPath = "/token/" <> cs (txHashToHex category)+      endpoints confirmed unconfirmed = do+        let expected =+              TokenBalance+                { address = owner,+                  category,+                  confirmedTokens = confirmed,+                  unconfirmedTokens = unconfirmed,+                  nfts = 0,+                  tokenUtxo = 1,+                  tokenTxs = 2,+                  receivedTokens = 2000+                }+        call (Client.GetAddrTokens owner) `shouldReturn` SerialList [expected]+        call (Client.GetTokenHolders category Nothing (OffsetParam 0)) `shouldReturn` SerialList [expected]+        SerialList outs <- call (Client.GetTokenUnspent category everything)+        map (.outpoint) outs `shouldBe` [OutPoint (txHash spend) 0]+        map (fmap (\t -> (t.category, t.amount)) . scriptTokens env.net . (.script)) outs+          `shouldBe` [Just (category, 1000)]+        SerialList refs <- call (Client.GetTokenTxs category everything)+        map (.txid) refs `shouldMatchList` [txHash genesis, txHash spend]+        -- the JSON gives the amounts as strings, as the API reference says+        (_, holders) <- getJSON env.plain (catPath <> "/holders")+        map (field "confirmed") (arr holders) `shouldBe` [Just (String (cs (show confirmed)))]+  endpoints 0 1000+  void (mine env 1)+  endpoints 1000 0  -- | The events of the server over a WebSocket. A client that says nothing -- hears of every transaction; one that names an extended public key, an@@ -2042,8 +2279,11 @@ eventsTest env = do   let x = newXPub env "events" DeriveNormal       y = newXPub env "events-other" DeriveNormal-      port = read (reverse (takeWhile (/= ':') (reverse env.plain))) :: Int-      client path = WS.runClient "127.0.0.1" port path+      client :: String -> WS.ClientApp a -> IO a+      client path app =+        bracket (Socket.socket Socket.AF_UNIX Socket.Stream Socket.defaultProtocol) Socket.close $ \s -> do+          Socket.connect s (Socket.SockAddrUnix env.plain.socket)+          WS.runClientWithSocket s "localhost" path WS.defaultConnectionOptions [] app       json = BL.toStrict . marshalJSON env.net       -- every event that a client hears after saying something, in order       hearing path say heard = client path $ \c -> do@@ -2114,10 +2354,10 @@   cancel resumed   (reverse <$> readIORef again) `shouldReturn` [two, three, four, block]   -- and the same without a WebSocket, one event to a line-  streamed <- eventLines (env.plain <> since) 4+  streamed <- eventLines env.plain since 4   map (either error id . eitherDecode . BL.fromStrict) streamed `shouldBe` [two, three, four, block]   -- the stream too can be of what touches an address-  chosen <- eventLines (env.plain <> since <> "&addresses=" <> T.unpack (at env y [0, 1])) 2+  chosen <- eventLines env.plain (since <> "&addresses=" <> T.unpack (at env y [0, 1])) 2   map (either error id . eitherDecode . BL.fromStrict) chosen `shouldBe` [three, block]   fst <$> getJSON env.plain "/events?addresses=nonsense" `shouldReturn` 400   fst <$> getJSON env.plain "/events?derive=segwit" `shouldReturn` 400@@ -2127,27 +2367,31 @@   refused <- tryAny (client ("/events?after=" <> replicate 64 '0') (\_ -> return ()))   either (const True) (const False) refused `shouldBe` True   -- a command that cannot be read ends the connection, with the reason,-  -- and so does a binary frame+  -- and so does a binary frame. The frame that closes it is read as it+  -- comes, without the answer that the library would send: on a Unix+  -- socket the server is gone by then, and the answer fails.   let sent message = do-        closed <- try . client "/events" $ \c -> do+        closed <- client "/events" $ \c -> do           WS.sendDataMessage c message-          void (WS.receiveDataMessage c)-        case closed of-          Left (WS.CloseRequest code why) -> (code, why) `shouldBe` (1008, "Could not read the command")-          wrong -> expectationFailure ("Not closed: " <> show wrong)+          let next =+                WS.receive c >>= \case+                  WS.ControlMessage (WS.Close code why) -> return (code, why)+                  _ -> next+          next+        closed `shouldBe` (1008, "Could not read the command")   sent (WS.Text "{\"type\":\"nonsense\"}" Nothing)   sent (WS.Binary "\x06")  -- | The first lines of a stream of events, which has no end: the request -- is given up once they are there.-eventLines :: String -> Int -> IO [C8.ByteString]-eventLines url n = do+eventLines :: Server -> String -> Int -> IO [C8.ByteString]+eventLines server path n = do   got <- newIORef C8.empty   let collect () chunk = do         modifyIORef' got (<> chunk)         enough <- (>= n) . C8.count '\n' <$> readIORef got         when enough (throwIO (userError "enough"))-  _ <- tryAny (Wreq.foldGet collect () url)+  _ <- tryAny (Wreq.foldGetWith (through server) collect () (server.url <> path))   take n . C8.lines <$> readIORef got  -- | Two more stores, each with its own database, syncing from the same@@ -2261,8 +2505,8 @@   -- and a client that heard of the payment from one takes up on the other   let since = "/events?after=" <> T.unpack txid       then' = "{\"type\":\"block\",\"id\":\"" <> cs best <> "\"}"-  eventLines (urlA <> since) 1 `shouldReturn` [then']-  eventLines (urlB <> since) 1 `shouldReturn` [then']+  eventLines urlA since 1 `shouldReturn` [then']+  eventLines urlB since 1 `shouldReturn` [then']   (_, confirmed) <- getJSON urlB ("/transaction/" <> T.unpack txid)   (confirmed ! "block") `shouldSatisfy` \case     Object o -> KeyMap.member "height" o@@ -2272,6 +2516,14 @@   waitFor "the health check of a member to pass" ((== 200) . fst <$> getJSON urlA "/health")   (_, health) <- getJSON urlA "/health"   ((health ! "redis") ! "ok") `shouldBe` Bool True+  -- what the store and each check found, in words+  (health ! "text") `shouldSatisfy` \case+    String t -> "The store is healthy: it has every block up to height " `T.isPrefixOf` t+    _ -> False+  forM_ ["blocks", "last-block", "last-tx", "pending-txs", "peers", "redis", "database", "mempool"] $ \check ->+    ((health ! check) ! "text") `shouldSatisfy` \case+      String t -> not (T.null t)+      _ -> False   -- a payment that a reorganisation replaced, as in 'reorgTest': both   -- stores answer 410 alike, from what the pool kept as the tip moved   let y = newXPub env "fleet-replaced" DeriveNormal@@ -2316,9 +2568,9 @@           shared = config.logger           named = shared {push = \line -> shared.push (name <> " " <> line)} :: Logger       withStore ((config :: StoreConfig) {logger = named}) $ \s ->-        listening $ \(sock, port) ->+        listening $ \(sock, server) ->           withAsync (runWebSocket (webConfig named s) sock) $ \web ->-            link web >> f s ("http://127.0.0.1:" <> show port)+            link web >> f s server  -- | Run a second store, with its own database, syncing from the same node -- and sharing the same Redis, while an action runs.@@ -2334,16 +2586,14 @@     return (fmap blockHashToHex ours == Just best)  -- | GET a path, with the status, the headers and the body of the answer.-getWithHeaders :: String -> String -> IO (Int, ResponseHeaders, Value)-getWithHeaders base path = do-  r <- Wreq.getWith opts (base <> path)+getWithHeaders :: Server -> String -> IO (Int, ResponseHeaders, Value)+getWithHeaders server path = do+  r <- Wreq.getWith (through server) (server.url <> path)   return     ( r ^. Wreq.responseStatus . Wreq.statusCode,       r ^. Wreq.responseHeaders,       body (r ^. Wreq.responseBody)     )-  where-    opts = Wreq.defaults & Wreq.checkResponse ?~ (\_ _ -> return ())  -- | The clock of Redis, in milliseconds. redisNowMs :: Env -> IO Integer
test/Haskoin/Store/LogicSpec.hs view
@@ -2,24 +2,33 @@  import Control.Monad (forM) import Data.ByteString qualified as B+import Data.Maybe (fromJust) import Data.Serialize (encode) import Database.RocksDB (columnFamilies) import Haskoin   ( Block (..),+    NFToken (..),     Network (..),     OutPoint (..),+    TokenCapability (..),+    TokenData (..),     Tx (..),     TxHash (..),     TxIn (..),     TxOut (..),+    bchRegTest,     btcRegTest,+    eitherToMaybe,+    encodeTokenPrefix,+    scriptToAddressBS,     sha256,     txHash,   ) import Haskoin.Store.Common (sortTxs) import Haskoin.Store.Data (BlockData (..)) import Haskoin.Store.Database.Query qualified as Q-import Haskoin.Store.Database.Reader (DatabaseReader (..))+import Haskoin.Store.Database.Reader (DatabaseReader (..), catOutCF, catTxCF, holderCF, tokBalCF)+import Haskoin.Store.Database.Types (TokBalVal (..)) import Haskoin.Store.Histories import Haskoin.Store.Integration.Temp (withSystemTempDirectory) import Haskoin.Store.Logic (PreparedBlock (..), PreparedTx (..), prepareBlock)@@ -56,6 +65,61 @@         Q.getTxData db (txHash spend) >>= (`shouldBe` Nothing) . fmap (const ())         chainFamilies db `shouldReturn` kept +  it "index the tokens of Bitcoin Cash, and take out with a revert exactly what they put in" $+    withSystemTempDirectory "haskoin-store-tokens-" $ \dir ->+      openLayered bchRegTest dir $ \db -> do+        startChain db+        first <- mine db []+        coinbase <-+          Q.getBlock db first >>= \case+            Just bd | h : _ <- bd.txs -> return h+            _ -> fail "no coinbase"+        kept <- tokenFamilies db+        before <- chainFamilies db+        -- the first input spends output 0 of the coinbase, so the category+        -- is the coinbase's id: 1000 tokens and a minting token to one+        -- address, the coins to another+        let category = coinbase+            minted = TokenData category 1000 (Just (NFToken MintingCapability "\x01"))+            alice = "\x76\xa9\x14" <> B.replicate 20 0x11 <> "\x88\xac"+            bob = "\x76\xa9\x14" <> B.replicate 20 0x22 <> "\x88\xac"+            holding t lock = fromJust (encodeTokenPrefix t) <> lock+            genesis =+              Tx+                1+                [TxIn (OutPoint coinbase 0) "" maxBound]+                [TxOut 1000 (holding minted alice), TxOut 2000 bob]+                []+                0+            -- 400 tokens go to bob, the rest and the minting token stay+            move =+              Tx+                1+                [TxIn (OutPoint (txHash genesis) 0) "" maxBound]+                [ TxOut 600 (holding (TokenData category 400 Nothing) bob),+                  TxOut 400 (holding minted {amount = 600} alice)+                ]+                []+                0+            [a, b] = map (fromJust . eitherToMaybe . scriptToAddressBS bchRegTest) [alice, bob]+        second <- mine db [genesis]+        Q.getTokBal db a category `shouldReturn` Just (TokBalVal 1000 1 1 1 1000)+        _ <- mine db [move]+        Q.getTokBal db a category `shouldReturn` Just (TokBalVal 600 1 1 2 1600)+        Q.getTokBal db b category `shouldReturn` Just (TokBalVal 400 0 1 1 400)+        -- under the category too, the two holders, two transactions and two+        -- unspent outputs+        [holders, txs, outs] <- mapM (fmap length . dump db) [holderCF db.db, catTxCF db.db, catOutCF db.db]+        (holders, txs, outs) `shouldBe` (2, 2, 2)+        revert db+        Q.getTokBal db a category `shouldReturn` Just (TokBalVal 1000 1 1 1 1000)+        Q.getTokBal db b category `shouldReturn` Nothing+        revert db+        Q.getBestBlock db `shouldReturn` Just first+        fmap (.main) <$> Q.getBlock db second `shouldReturn` Just False+        tokenFamilies db `shouldReturn` kept+        chainFamilies db `shouldReturn` before+   describe "prepareBlock" $     modifyMaxSuccess (const 50) $       it "gives the hash of each transaction, the order of sortTxs, and the size and weight of the block" $@@ -73,6 +137,9 @@     -- takes out: addresses, outputs, transactions, unspent outputs,     -- spenders and balances     chainFamilies db = forM [0, 1, 2, 3, 4, 7] $ \i -> dump db (columnFamilies db.db !! i)+    -- the column families of the tokens: balances by address and by+    -- category, transactions and unspent outputs of the categories+    tokenFamilies db = mapM (dump db . ($ db.db)) [tokBalCF, holderCF, catTxCF, catOutCF]  -- | Transactions that spend one another and some coins, some with a -- witness, in a random order.
+ test/Haskoin/Store/MempoolSpec.hs view
@@ -0,0 +1,1157 @@+-- |+-- Module      : Haskoin.Store.MempoolSpec+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- That the shared mempool of a store converges to the mempool of its node,+-- against a real node in Podman: the theorem of @docs\/mempool-ingestion.md@+-- as a test, in the situations in which stores were found not to converge.+--+-- On 21 November 2026 the btc store of a server fell 17,000 transactions+-- behind its node, and three fixes in a row each broke something else on+-- that server, because nothing reproduced the failures off it. Each test+-- here is one of them, on a regtest node whose mempool is filled the way+-- that node's was: with chains of 24 transactions, a root and its+-- descendants, all taken within seconds, each with an output of value 0+-- that holds data and one that pays, as the mints of Runes are.+--+-- The transactions spend outputs that anyone can spend, pay-to-script-hash+-- of @OP_TRUE@, so that the tests make thousands of them without a wallet+-- and without signing. Both nodes take them as standard.+--+-- A test is a group with a pod of its own, so that they run at the same+-- time, each in a process (@haskell-dev.toml@).+module Haskoin.Store.MempoolSpec+  ( spec,++    -- * For the specs of what a node does+    Bed (..),+    withBed,+    withBedOf,+    bare,+    chainOf,+    fund,+    send,+    submit,+  )+where++import Control.Concurrent (threadDelay)+import Control.Concurrent.Async (forConcurrently_, link, poll, withAsync)+import Control.Concurrent.STM (atomically)+import Control.Exception (finally, throwIO, try)+import Control.Monad (forM_, unless, void, when)+import Data.Aeson (Value (..))+import Data.Aeson.KeyMap qualified as KeyMap+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.List (isInfixOf, transpose)+import Data.Maybe (fromMaybe)+import Data.Serialize (encode)+import Data.Set qualified as Set+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time.Clock.POSIX (getPOSIXTime)+import Data.Word (Word32, Word64)+import Database.Redis qualified as Redis+import Haskoin+  ( Network,+    OutPoint (..),+    Tx (..),+    TxIn (..),+    TxOut (..),+    addrToText,+    addressHash,+    encodeHex,+    hexToTxHash,+    scriptToAddressBS,+    txHash,+    txHashToHex,+  )+import Haskoin.Node (Logger, Permissions)+import Haskoin.Store (Store (..), StoreConfig (..), WebConfig (..), cachePrefix, runWebSocket, withStore)+import Haskoin.Store.Data (BlockData (..))+import Haskoin.Store.Database.Query qualified as Q+import Haskoin.Store.Fleet.Redis (fleetKeys, poolWithdraw)+import Haskoin.Store.Ingest.Run (IngestState (..), ingestState)+import Haskoin.Store.Integration.Node+import Haskoin.Store.Integration.Temp (withRamDir)+import Haskoin.Store.Integration.Valkey (redisContainer)+import Haskoin.Store.Integration.Valkey qualified as Valkey+import Haskoin.Store.IntegrationSpec+  ( Server,+    arr,+    getJSON,+    grantedBy,+    listening,+    storeConfig,+    webConfig,+    withTestLog,+  )+import Haskoin.Store.NodePeer (fresh)+import Haskoin.Store.Startup (redisConnectInfo)+import Network.HTTP.Client (HttpException)+import System.IO (hPutStrLn, stderr)+import System.Timeout (timeout)+import Test.Hspec+import Test.Podman (ContainerSpec (..), Pod, PodSpec (..), containerName, pod, podman, podmanUsable, withPod)++spec :: Spec+spec = do+  describe "What a node without a ZeroMQ socket is taken to have announced" $+    it "is what its mempool has that it had not at the last reading, in the order of the node" $ do+      fresh (Set.fromList "abd") "dcbea" `shouldBe` "ce"+      fresh Set.empty "cab" `shouldBe` "cab"+      fresh (Set.fromList "abc") "" `shouldBe` ""+  usable <- runIO podmanUsable+  case usable of+    Left why -> describe "The mempool of a store and that of its node" $ it "are the same" (pendingWith why)+    Right () -> do+      forM_ [BitcoinCore, BitcoinCashNode] $ \kind -> do+        -- a group for each test on each node, with a pod of its own+        let on what = describe (what <> ", on " <> name kind)+        on "A store that starts from nothing" $+          it "has the mempool of its node once it has its blocks" (withBed kind fromNothing)+        on "A store that starts at the tip with an empty pool" $+          it "takes the whole mempool of its node, and stays healthy and connected" (withBed kind atTheTip)+        on "A store that was away while transactions came" $+          it "has them when it is back" (withBed kind (away False))+        on "A store that was away while transactions and a block came" $+          it "has what the block left in the mempool when it is back" (withBed kind (away True))+        on "A store whose Valkey is stopped and started again under it" $+          it "has the mempool of its node again, without being started again" (withBed kind valkeyRestart)+        on "A store whose Valkey is emptied under it" $+          it "says so, and has the mempool of its node again within fifteen seconds" (withBed kind valkeyFlush)+        on "A store whose pool let transactions go that its node still has" $+          it "has them again when it next reads the mempool of its node" (withBed kind letGo)+        on "A store whose pool lost transactions that its node then takes children of" $+          it "asks its node for them, and has them and their children" (withBed kind bereft)+        on "A store whose node takes chains while it finds blocks" $+          it "has every transaction that no block confirmed" (withBed kind busy)+        on "A store whose only peer is its node through its RPC and its ZeroMQ socket" $+          it "has its blocks, its mempool, what the node takes next and its next block, with no other connection" $+            withBed kind (alone . \bed -> bed {viaRpc = True, viaZmq = True})+        on "A store whose only peer is its node through its RPC and its ZeroMQ socket, when the node stops" $+          it "has no peer and says so, and has its node again when the node goes on" $+            withBed kind (nodeStops . \bed -> bed {viaRpc = True, viaZmq = True})+        on "A store whose only peer is its node through its RPC, with no ZeroMQ socket" $+          it "warns of it, and has what its node takes and finds within twelve seconds, three times over" $+            withBed kind (polls . \bed -> bed {viaRpc = True})+        forM_ [False, True] $ \zmq ->+          on ("A store that never has a peer, from no chain at all, with the RPC of its node" <> withZmq zmq) $+            it "has a chain of more than 2,500 blocks, the mempool, and what the node finds and takes next" $+              withBed kind (noPeerEver . \bed -> bed {viaRpc = True, viaZmq = zmq})+        on "A store that hears of the coinbase of a block that its node took back" $+          it "does not show it as an unconfirmed transaction" $+            withBed kind (staleCoinbase . \bed -> bed {viaRpc = True, viaZmq = True})+        on "A store that starts while its node takes transactions without a pause" $+          it "says that its mempool is in sync while they still come" (withBed kind underTraffic)+        on "A store whose node never stops taking transactions" $+          it "answers from each new block within seconds of it" (withBed kind unceasing)+      describe "A store whose only peer is a node of somebody else, on Bitcoin Core" $+        it "takes of it what it can verify, and not what it cannot" (withBed BitcoinCore (strangers False))+      -- Bitcoin Cash Node names what it takes to a peer that it+      -- whitelists as fast as it takes it+      describe "A store whose node takes transactions faster than it names them, on Bitcoin Core" $+        it "has them within the time of a reading of the node's mempool, and not at the node's pace" $+          withBed BitcoinCore burst+      describe "A store with a node of somebody else and the RPC of its own, on Bitcoin Core" $+        it "takes at the word of its own node what it cannot verify of the other" $+          withBed BitcoinCore (strangers True . \bed -> bed {viaRpc = True})+      describe "A store that hears what its node publishes over ZeroMQ, on Bitcoin Core" $+        it "has what the node takes as fast as the node takes it, with no reading of its mempool" $+          withBed BitcoinCore (hears . \bed -> bed {viaRpc = True, viaZmq = True})+      -- Bitcoin Cash Node replaces nothing by fee+      describe "A store whose node replaces transactions by ones that pay more, on Bitcoin Core" $+        it "has the replacements, and nothing of what they replaced" (withBed BitcoinCore outbid)+      -- Bitcoin Cash Node gives its mempool to any peer, so only a store+      -- of Bitcoin Core can have no peer that is a source+      forM_ [False, True] $ \block ->+        describe ("A store that no peer gives a mempool to, with the RPC of its node" <> withBlock block) $+          it "has what came while it was away" $+            withBedOf (bare BitcoinCore) BitcoinCore (away block . rpcOnly)+      describe "A store with the RPC of its node, whose node takes transactions while the two are not connected" $+        it "has them once it is connected again" $+          withBedOf (bare BitcoinCore) BitcoinCore (cutOff . rpcOnly)+  where+    name BitcoinCore = "Bitcoin Core"+    name BitcoinCashNode = "Bitcoin Cash Node"+    withBlock block = if block then ", and a block while it is away" else ""+    withZmq zmq = if zmq then " and its ZeroMQ socket" else " alone"+    -- the node grants the store nothing, and the store has its RPC+    rpcOnly bed = bed {granted = Set.empty, viaRpc = True}++-------------------------------------------------------------------------------+-- The tests+-------------------------------------------------------------------------------++-- | A store with no database and an empty pool, started on a node that has+-- 150 blocks and a mempool: it has the blocks to sync first.+fromNothing :: Bed -> IO ()+fromNothing bed = do+  roots <- fund bed 40+  submit bed (map (chainOf 24) roots)+  withMember bed $ \_ server -> do+    -- its health says that its mempool is syncing, from the moment that+    -- it has its node to read+    standing server "syncing" 20+    converges bed server 90+    -- it has every block: it is healthy, whether it says so of its+    -- mempool yet or not+    (_, health) <- getJSON server "/health"+    field "ok" health `shouldBe` Just (Bool True)+    -- and within the time that a node is given to answer, it says that+    -- its mempool is in sync+    standing server "synced" 120++-- | Wait, for so many half seconds, until the health of a store says this+-- of its mempool: @syncing@, @synced@ or @unknown@.+standing :: Server -> Text -> Int -> IO ()+standing server want halves = do+  (_, health) <- getJSON server "/health"+  let says = field "mempool" health >>= field "sync"+  unless (says == Just (String want)) $+    if halves <= 0+      then+        expectationFailure . unwords $+          ["The store does not come to say that its mempool is", T.unpack want <> ":", "it says", show says]+      else threadDelay 500000 >> standing server want (halves - 1)++-- | A store that starts while its node takes transactions, and goes on+-- taking them: some sixty a second, as in 'unceasing'. Its health must+-- come to say that its mempool is in sync while they still come.+--+-- The machine says so at a moment when nothing that a node of the+-- operator named is on its way. On a node that is quiet there is such a+-- moment as soon as the first reading is in. This is the test that there+-- is one on a node that is not.+underTraffic :: Bed -> IO ()+underTraffic bed = do+  roots <- fund bed 200+  let slowly tx = send bed tx >> threadDelay 60000+      lanes n xs = [[x | (i, x) <- zip [0 :: Int ..] xs, i `mod` n == l] | l <- [0 .. n - 1]]+      trickle = forConcurrently_ (lanes 4 (map (chainOf 24) roots)) (mapM_ slowly . concat)+  withAsync trickle $ \sending -> do+    link sending+    threadDelay 2000000+    withMember bed $ \_ server -> do+      standing server "synced" 120+      -- they were still coming when it said so+      poll sending >>= \case+        Nothing -> return ()+        Just _ ->+          expectationFailure "The node had stopped taking transactions before the store said that it was in sync"++-- | The experiment that was made on the server: a store whose database is+-- at the tip of its node, started with an empty pool on a node with a+-- large mempool. While it takes the mempool, its health never fails for+-- the transactions that it asked for, and it keeps its peer.+atTheTip :: Bed -> IO ()+atTheTip bed = withRamDir $ \dir -> do+  roots <- fund bed 200+  withMemberIn bed dir $ \_ server -> converges bed server 60+  submit bed (map (chainOf 24) roots)+  flush bed+  withMemberIn bed dir $ \_ server -> do+    -- the most requests out, whether the peer was seen, and whether it+    -- was lost after that+    worst <- newIORef (0 :: Integer, False, False)+    let sample = do+          (_, h) <- getJSON server "/health"+          let count k = fromMaybe 0 (field k h >>= field "count" >>= number)+              there = count "peers" > 0+          modifyIORef' worst $ \(p, seen, lost) ->+            (max p (count "pending-txs"), seen || there, lost || (seen && not there))+    convergesWith sample bed server 120+    -- the store may have its node's mempool before its health is next+    -- checked, which is when it first says that it has a peer: look until+    -- it does, for longer than the time between two checks+    let awaited n = do+          (_, seen, _) <- readIORef worst+          unless (seen || n <= (0 :: Int)) (threadDelay 500000 >> sample >> awaited (n - 1))+    awaited 120+    (pending, seen, lost) <- readIORef worst+    -- what the health check of a store allows, by default+    pending `shouldSatisfy` (<= 10000)+    (seen, lost) `shouldBe` (True, False)+  where+    number = \case+      Number n -> Just (round n)+      _ -> Nothing++-- | A store that ran, stopped, and starts again on its database and its+-- pool, after its node took transactions that it could not hear of, and+-- perhaps a block, which leaves the store behind its node when it starts.+away :: Bool -> Bed -> IO ()+away block bed = withRamDir $ \dir -> do+  roots <- fund bed 40+  let (before, after) = splitAt 10 roots+  withMemberIn bed dir $ \_ server -> do+    submit bed (map (chainOf 24) before)+    converges bed server 60+  -- half of each chain while the store is away, then a block, then the rest+  let chains = map (chainOf 24) after+  submit bed (map (take 12) chains)+  when block . void $ generateTo bed.node 1 bed.miner+  submit bed (map (drop 12) chains)+  withMemberIn bed dir $ \_ server -> converges bed server 60++-- | A node that takes 2,500 transactions in a few seconds. Bitcoin Core+-- names about five hundred of them to a peer at once, and then seventy+-- every five seconds, to a peer that it whitelists too+-- (@namesAtItsPace@ in "Haskoin.Store.NodeAxiomsSpec"): at that pace the+-- store would have them all after two minutes and a half. It reads the+-- mempool of its node every thirty seconds while transactions come+-- (@told@ in "Haskoin.Store.Ingest"), so it has them all within the+-- time of a reading and of taking them in: here 31 seconds after the+-- first came, where it has 1,800 of them after a minute without.+--+-- A server was a minute and more behind its node, by thousands of+-- transactions, whenever the node took more than fourteen a second, and+-- read the node's mempool every ten minutes.+burst :: Bed -> IO ()+burst bed = do+  roots <- fund bed 2500+  withMember bed $ \_ server -> do+    converges bed server 60+    submit bed (map (chainOf 1) roots)+    converges bed server 60++-- | A store that is given no peer at all, and the RPC of its node with+-- the address of its ZeroMQ socket (@--node-rpc@, @--node-zmq@): the+-- node is its one peer, through those two ("Haskoin.Store.NodePeer"),+-- and there is no connection of the peer-to-peer protocol.+--+-- It starts from nothing on a node that has 150 blocks and a mempool.+-- It must have the blocks, which come over the RPC; the mempool, which+-- the node names when asked; what the node takes after that, which the+-- node publishes; and the block that the node finds then, which it+-- publishes too. Its health says that it has one peer.+alone :: Bed -> IO ()+alone bed = withRamDir $ \dir -> do+  roots <- fund bed 40+  let (before, after) = splitAt 20 roots+  submit bed (map (chainOf 4) before)+  withMemberOf (\c -> c {initPeers = []} :: StoreConfig) bed dir $ \_ server -> do+    converges bed server 120+    (_, health) <- getJSON server "/health"+    (field "peers" health >>= field "count") `shouldBe` Just (Number 1)+    -- with both, there is nothing to put right+    field "warnings" health `shouldBe` Nothing+    submit bed (map (chainOf 4) after)+    converges bed server 30+    void (generateTo bed.node 1 bed.miner)+    converges bed server 30++-- | A node publishes over ZeroMQ the id of every transaction of a block+-- that stops being part of its chain, the coinbase too, as it does of one+-- that it takes into its mempool. The others go back to its mempool. The+-- coinbase goes nowhere: only its block had it. And the node still gives+-- it when asked, since it keeps the block.+--+-- A store that had the node as a peer through its RPC and its ZeroMQ+-- socket took such a coinbase on the word of its node, and showed it as+-- an unconfirmed transaction that would never confirm: two of them, on+-- every store of a testnet of a server, for as long as nothing emptied+-- the pool.+--+-- The node here is told to take its last block back, and finds two+-- others in its place. The store must end with the mempool of its node,+-- which does not have the coinbase.+staleCoinbase :: Bed -> IO ()+staleCoinbase bed = withRamDir $ \dir -> do+  roots <- fund bed 4+  submit bed (map (chainOf 2) roots)+  other <-+    rpc bed.node "getnewaddress" [] >>= \case+      String a -> return a+      v -> fail ("Unexpected answer to getnewaddress: " <> show v)+  withMemberOf (\c -> c {initPeers = []} :: StoreConfig) bed dir $ \_ server -> do+    converges bed server 120+    -- Two good blocks at one height, as when two miners find one each.+    -- The node is made to forget the first while it finds the second,+    -- paid to another address or it would be the same block, and to+    -- remember the first again. It saw that one first, and goes back to+    -- it: it takes the second back, which stays a block that it has and+    -- gives, and publishes the ids of its transactions, the coinbase+    -- among them.+    first <- generateTo bed.node 1 bed.miner+    converges bed server 30+    forM_ first $ \b -> void (rpc bed.node "invalidateblock" [String b])+    -- the store stays on the first: the second is no more work+    second <- generateTo bed.node 1 other+    forM_ first $ \b -> void (rpc bed.node "reconsiderblock" [String b])+    bestBlockHash bed.node >>= \best -> [best] `shouldBe` first+    second `shouldNotBe` first+    -- the store follows once that chain is the longer+    void (generateTo bed.node 1 other)+    converges bed server 60+    -- and it stays so: nothing comes late+    threadDelay 5000000+    converges bed server 10++-- | A store that never connects to a peer: it is given none, discovery+-- is off, and all that it has is the RPC of its node, with the node's+-- ZeroMQ socket or without. It starts with no chain at all, on a node+-- whose chain is longer than what a node gives of headers in one answer,+-- two thousand: the other tests of such a store have 150 blocks, and+-- never ask for headers a second time.+--+-- It must have every block, then the mempool, then the next block and+-- the next transactions, and say all along that it has one peer: the+-- node, through its RPC.+noPeerEver :: Bed -> IO ()+noPeerEver bed = withRamDir $ \dir -> do+  roots <- fund bed 60+  let (before, rest) = splitAt 10 roots+      (during, after) = splitAt 40 rest+  -- 2,400 more blocks, in pieces that the RPC answers in time+  forM_ [1 :: Int .. 6] $ \_ -> void (generateTo bed.node 400 bed.miner)+  submit bed (map (chainOf 4) before)+  top <-+    rpc bed.node "getblockcount" [] >>= \case+      Number n -> return n+      v -> fail ("Unexpected answer to getblockcount: " <> show v)+  withMemberOf (\c -> c {initPeers = []} :: StoreConfig) bed dir $ \store server -> do+    -- While it has not every block, the store takes no transaction in:+    -- it could not place one, and most would be in a block by the time+    -- that it could. The node goes on taking some meanwhile, which it+    -- announces or names when read. A store on a server fetched and+    -- held thousands while it took its blocks, and gave them up for+    -- minutes after it had them.+    early <- catchingUp store (round top) (concatMap (chainOf 1) during) []+    length early `shouldSatisfy` (> 5)+    filter (/= 0) early `shouldBe` []+    converges bed server 600+    (_, health) <- getJSON server "/health"+    let count name = field "blocks" health >>= field name+    count "blocks" `shouldBe` count "headers"+    count "blocks" `shouldSatisfy` \case+      Just (Number n) -> n > 2500+      _ -> False+    field "ok" health `shouldBe` Just (Bool True)+    (field "peers" health >>= field "count") `shouldBe` Just (Number 1)+    standing server "synced" 120+    void (generateTo bed.node 1 bed.miner)+    submit bed (map (chainOf 4) after)+    converges bed server 30+    (_, later') <- getJSON server "/health"+    (field "peers" later' >>= field "count") `shouldBe` Just (Number 1)+  where+    -- how many transaction ids the path into the pool had a place for,+    -- each time that it was looked at before the database had every+    -- block, with the node taking one more transaction at each look+    --+    -- Both are read from the store itself, the count first and the best+    -- block of the database after it: a database that is behind at the+    -- second look was behind at the first. They are not read from the web+    -- server. It answers at the tip of the fleet, which moves after the+    -- database: in two runs of twelve it still said a lower block, the+    -- first of the chain in one, when the database had them all and the+    -- store had begun. And the height in its health is read once a second.+    catchingUp :: Store -> Int -> [Tx] -> [Int] -> IO [Int]+    catchingUp store top txs seen = do+      path <- atomically (ingestState store.ingest)+      height <-+        Q.getBestBlock store.db >>= \case+          Nothing -> return 0+          Just h -> maybe 0 (fromIntegral . (.height)) <$> Q.getBlock store.db h+      if height == top+        then return (reverse seen)+        else do+          txs' <- case txs of+            tx : more -> send bed tx >> return more+            [] -> return []+          threadDelay 100000+          catchingUp store top txs' (path.known : seen)++-- | A store that is given no peer at all, and the RPC of its node with+-- no ZeroMQ socket (@--node-rpc@ alone). The node is its one peer all the+-- same, and nothing announces: the peer asks the node every five seconds+-- for its best block and for its mempool ("Haskoin.Store.NodePeer"). Its+-- health is good, and warns that the socket is missing.+--+-- The store reads the mempool of a source by the clock too, thirty+-- seconds after a reading in which something new was named, and that+-- reading would bring one batch within any limit. So three batches go in+-- thirteen seconds apart, each with twelve seconds to be in the store:+-- readings thirty seconds apart cannot fall in all three. With the peer+-- asking every sixty seconds, this test failed.+polls :: Bed -> IO ()+polls bed = withRamDir $ \dir -> do+  roots <- fund bed 30+  withMemberOf (\c -> c {initPeers = []} :: StoreConfig) bed dir $ \_ server -> do+    converges bed server 120+    (_, health) <- getJSON server "/health"+    (field "peers" health >>= field "count") `shouldBe` Just (Number 1)+    field "ok" health `shouldBe` Just (Bool True)+    case field "warnings" health of+      Just v@(Array _) | [String w] <- arr v -> T.unpack w `shouldSatisfy` isInfixOf "ZeroMQ"+      other -> expectationFailure ("Expected one warning, and the health says: " <> show other)+    forM_ (batches roots) $ \batch -> do+      from <- getPOSIXTime+      submit bed (map (chainOf 2) batch)+      converges bed server 12+      took <- subtract from <$> getPOSIXTime+      threadDelay (max 0 (round ((13 - took) * 1000000)))+    void (generateTo bed.node 1 bed.miner)+    converges bed server 12+  where+    batches hs = case splitAt 10 hs of+      (some, []) -> [some | not (null some)]+      (some, rest) -> some : batches rest++-- | The same store when its node stops in its tracks, as a node that+-- hangs: the pipe to the peer is in memory and never breaks, and the+-- thread at its other end could answer for a node that is gone. It+-- answers a ping only once the node answered a call, so the store finds+-- its peer silent and lets it go, as it does of any peer: its health+-- says that it has none. When the node goes on, the store has it as a+-- peer again, with what the node took meanwhile.+nodeStops :: Bed -> IO ()+nodeStops bed = withRamDir $ \dir -> do+  roots <- fund bed 20+  let (before, after) = splitAt 10 roots+      quick c = c {initPeers = [], peerTimeout = 10} :: StoreConfig+  withMemberOf quick bed dir $ \_ server -> do+    submit bed (map (chainOf 4) before)+    converges bed server 120+    freezeNode bed.pod 0 bed.node.kind+    peers server 0 90 `finally` thawNode bed.pod 0 bed.node.kind+    submit bed (map (chainOf 4) after)+    peers server 1 90+    converges bed server 90+  where+    -- until the health of the store says that it has so many peers+    peers server n seconds = do+      (_, health) <- getJSON server "/health"+      unless ((field "peers" health >>= field "count") == Just (Number n)) $+        if seconds <= (0 :: Int)+          then expectationFailure ("The store does not come to have " <> show n <> " peers")+          else threadDelay 1000000 >> peers server n (seconds - 1)++-- | A store that has its node as a peer twice, over the peer-to-peer+-- protocol and through its RPC and its ZeroMQ socket (@--node-rpc@,+-- @--node-zmq@), while the node takes hundreds of transactions in a few+-- seconds, twice.+--+-- Bitcoin Core names to a peer about five hundred at once and then+-- fourteen a second (A8), so that a store that only listens to its peer+-- is behind for as long as a burst lasts, until it reads the mempool of+-- its node, every thirty seconds. Over ZeroMQ the node publishes the id+-- of each transaction as it takes it (F2), and the store fetches it over+-- the RPC: it has them all within five seconds of the last.+--+-- A reading of the mempool would bring them too, and one may fall in any+-- five seconds. So the test looks at two bursts, which are less than+-- thirty seconds apart: a reading cannot fall in both. In one of them at+-- least the store must have had everything with no reading, and in none+-- may it be late without one.+hears :: Bed -> IO ()+hears bed = withRamDir $ \dir -> do+  roots <- fund bed 1600+  -- two peers: the node over the peer-to-peer protocol, and the same node+  -- through its RPC and its ZeroMQ socket+  withMemberOf (\c -> c {maxPeers = 2} :: StoreConfig) bed dir $ \_ server -> do+    converges bed server 60+    both server 90+    let (first, second) = splitAt 800 roots+    rounds <- mapM (round' server) [first, second]+    -- a round that a reading fell in says nothing, and both cannot be+    filter fst rounds `shouldSatisfy` (not . null)+    [late | (True, late) <- rounds] `shouldSatisfy` all not+  where+    -- whether no reading fell in the round, and whether the store was+    -- then late+    round' server some = do+      before <- readings+      submit bed (map (chainOf 1) some)+      inTime <- timeout 5000000 (awaitSame server)+      after <- readings+      -- whatever happened, the store ends with the mempool of its node+      converges bed server 60+      return (after == before, inTime == Nothing)+    -- until the store has its two peers+    both server seconds = do+      (_, health) <- getJSON server "/health"+      unless ((field "peers" health >>= field "count") == Just (Number 2)) $+        if seconds <= (0 :: Int)+          then expectationFailure "The store does not come to have two peers"+          else threadDelay 1000000 >> both server (seconds - 1)+    awaitSame server = do+      node <- Set.fromList <$> rawMempool bed.node+      (_, m) <- getJSON server "/mempool?limit=1000000"+      let ours = Set.fromList [t | String t <- case m of v@(Array _) -> arr v; _ -> []]+      unless (node == ours) (threadDelay 200000 >> awaitSame server)+    -- how many times the store asked a source for its whole mempool+    readings = do+      said <- takeWhile (/= "--- at every level") <$> bed.logTail+      return (length (filter (\l -> "for its mempool" `isInfixOf` l || "Reading the mempool" `isInfixOf` l) said))++-- | A node that takes chains of transactions, and then, for the first of+-- each chain, another that spends the same output and pays more: it+-- replaces the first and drops what spent from it (replace-by-fee, which+-- a node of Bitcoin does for any unconfirmed transaction). The store has+-- to follow: a node is the judge of what is in its mempool, and a store+-- that kept what its node dropped, or turned away what its node took,+-- would answer what no node would. The replacements pay ten times the+-- fees of what they replace.+outbid :: Bed -> IO ()+outbid bed = do+  roots <- fund bed 8+  withMember bed $ \_ server -> do+    submit bed (map (chainOf 3) roots)+    converges bed server 60+    forM_ roots $ \(op, value) -> send bed (spend op [TxOut 0 note, TxOut (value - 30 * fee) lock])+    converges bed server 60++-- | A store that has the RPC of a node that whitelists nobody, and is its+-- peer: the node closes its connections, takes transactions, and takes+-- connections again. It names to a peer nothing that it took before the+-- peer connected (A1), and its RPC names nothing by itself, so the store+-- has them only by reading the RPC again once it is connected: a peer+-- that connects owes what its node took before.+--+-- A store read the RPC of its node when it started and connected to the+-- node a moment later. What the node took in between was in neither: one+-- run in many of another test here lost four transactions so, one for+-- each of the four that are sent at once, and ended with the 84 that+-- spent from them waiting.+cutOff :: Bed -> IO ()+cutOff bed = do+  roots <- fund bed 6+  withMember bed $ \_ server -> do+    converges bed server 60+    -- A store that starts on a new database starts its pool again once it+    -- has its blocks, and reads the RPC again for that, ten seconds after+    -- the first time. The node is cut off after that reading, so that+    -- nothing but the peer that connects again makes the store read.+    threadDelay 15000000+    void (rpc bed.node "setnetworkactive" [Bool False])+    -- the node closes its connections a moment after it is told to+    let alone = null . arr <$> rpc bed.node "getpeerinfo" []+        awaitAlone n = do+          gone <- alone+          unless gone $+            if n > (0 :: Int) then threadDelay 100000 >> awaitAlone (n - 1) else fail "The node kept its peer"+    awaitAlone 100+    -- transactions that nothing spends from: nothing asks for them+    submit bed (map (chainOf 1) roots)+    void (rpc bed.node "setnetworkactive" [Bool True])+    converges bed server 60++-- | A store that runs while its pool loses transactions, without the+-- store being told, and whose node then takes a transaction that spends+-- from each. The node named the lost ones once and will not name them+-- again, so nothing brings them back but the store asking for them when+-- the pool says that it lacks what a child spends from (@seek@ in+-- "Haskoin.Store.Ingest").+--+-- Without that the children waited, tried again after two seconds, four,+-- eight, and were given up after twenty minutes, when the store read the+-- mempool of its node again: a test ended with 84 transactions waiting+-- behind four.+bereft :: Bed -> IO ()+bereft bed = do+  roots <- fund bed 6+  let chains = map (chainOf 2) roots+  withMember bed $ \_ server -> do+    submit bed (map (take 1) chains)+    converges bed server 60+    conn <- Redis.checkedConnect (either error id (redisConnectInfo bed.redisURL))+    left <- poolWithdraw conn (fleetKeys (cachePrefix bed.net) 32) 32 [encode (txHash tx) | tx : _ <- chains]+    Redis.disconnect conn+    length left `shouldBe` 6+    submit bed (map (drop 1) chains)+    converges bed server 60++-- | A store that stops, whose pool then lets go of the first transaction+-- of each chain and of all that spends it, as when another transaction+-- took their place and was itself taken out later, and that starts+-- again: the node has them all, so the store has them all again.+--+-- The fleet remembers what its pool decided on, the transactions that it+-- let go among them, and a store did not fetch what the fleet remembered:+-- on a server, a transaction that the node held for hours stayed out of+-- the store through every reading of the node's mempool. Only what the+-- pool has counts as settled now.+letGo :: Bed -> IO ()+letGo bed = withRamDir $ \dir -> do+  roots <- fund bed 6+  let chains = map (chainOf 3) roots+  withMemberIn bed dir $ \_ server -> do+    submit bed chains+    converges bed server 60+  conn <- Redis.checkedConnect (either error id (redisConnectInfo bed.redisURL))+  left <- poolWithdraw conn (fleetKeys (cachePrefix bed.net) 32) 32 [encode (txHash tx) | tx : _ <- chains]+  Redis.disconnect conn+  length left `shouldBe` 18+  withMemberIn bed dir $ \_ server -> converges bed server 60++-- | A store whose Valkey is stopped and started again while it runs, as+-- when the package of Valkey is upgraded on a server. The Valkey of the+-- tests keeps nothing, so it comes back empty: every connection of the+-- store is broken at once, the pool is gone, and the store has to notice+-- both, and fill the pool again from its node, by itself. Half of the+-- transactions come before the restart and half after.+valkeyRestart :: Bed -> IO ()+valkeyRestart bed = do+  roots <- fund bed 40+  let (before, after) = splitAt 20 roots+  withMember bed $ \_ server -> do+    submit bed (map (chainOf 24) before)+    converges bed server 60+    void (podman ["restart", "--time", "1", containerName bed.pod redisContainer.name])+    submit bed (map (chainOf 24) after)+    converges bed server 120++-- | A store that was told that its peer is a node of somebody else+-- (@--foreign-peers@), and so has no node of its operator: it takes of+-- the peer only what it can verify.+--+-- The wallet of the node pays an output: a transaction that spends coins+-- locked to one key each, with their signatures, which the store verifies+-- and takes. A transaction then spends that output, which is locked by a+-- script, as all the chains of these tests are: the node runs the script+-- and takes it, and the store, which runs none, does not take it on the+-- word of a stranger. So the store ends with the first and without the+-- second, and says in its health that it holds one transaction.+--+-- The same store with the peer as a node of its operator takes both, as+-- every other test of this module has it.+strangers :: Bool -> Bed -> IO ()+strangers vouched bed = withRamDir $ \dir -> do+  let foreign' c = c {foreignPeers = True} :: StoreConfig+      address = case scriptToAddressBS bed.net lock >>= maybe (Left "no text") Right . addrToText bed.net of+        Right a -> a+        Left e -> error ("No address for the script: " <> e)+  (verified, scripted) <- withMemberOf foreign' bed dir $ \_ server -> do+    converges bed server 60+    -- from the wallet of the node, signed by its keys+    paid <- sendTo bed.node address 1000000+    paying <- getRawTx bed.node paid+    let index = case [n | o <- maybe [] arr (field "vout" paying), isLock o, Just (Number n) <- [field "n" o]] of+          [n] -> round n :: Word32+          _ -> error "The wallet did not pay the script once"+    hash <- maybe (fail "Not a transaction id") return (hexToTxHash paid)+    -- and what spends it, by a script+    let spending = spend (OutPoint hash index) [TxOut 990000 lock]+    send bed spending+    let spent = txHashToHex (txHash spending)+    has server paid 30+    if vouched+      then do+        -- the node of the operator, through its RPC, names both: the+        -- store has the second too, on its word+        has server spent 30+        pool server `shouldReturn` Set.fromList [paid, spent]+      else do+        -- the store has the first within seconds, and never the second+        threadDelay 5000000+        -- among strangers it cannot tell how its mempool stands, also+        -- while it holds what it cannot verify+        standing server "unknown" 1+        pool server `shouldReturn` Set.singleton paid+        Set.fromList <$> rawMempool bed.node `shouldReturn` Set.fromList [paid, spent]+        (_, health) <- getJSON server "/health"+        (field "mempool" health >>= field "held") `shouldBe` Just (Number 1)+    return (paid, spent)+  -- the same store, told nothing of the kind: the peer is a node of its+  -- operator, and what it took is taken+  withMemberIn bed dir $ \_ server -> do+    has server scripted 60+    pool server `shouldReturn` Set.fromList [verified, scripted]+  where+    isLock o = (field "scriptPubKey" o >>= textField "hex") == Just (encodeHex lock)+    pool server = do+      (_, m) <- getJSON server "/mempool?limit=1000000"+      return (Set.fromList [t | String t <- case m of v@(Array _) -> arr v; _ -> []])+    has server h seconds = do+      got <- pool server+      if Set.member h got+        then return ()+        else+          if seconds <= (0 :: Int)+            then expectationFailure ("The store does not have " <> T.unpack h)+            else threadDelay 1000000 >> has server h (seconds - 1)++-- | A store whose Valkey is emptied while it runs, as by @FLUSHALL@. Unlike+-- 'valkeyRestart', Valkey goes on answering and the store keeps its+-- connections: nothing fails, and only the epoch tells the store that the+-- pool is gone ('Haskoin.Store.Fleet.Member.noteEpoch'). The store must+-- say so, once, and have the mempool of its node again within fifteen+-- seconds. Then the node takes as much again, which the store must take+-- into the new pool.+--+-- A store reads the mempool of its node by the clock too, thirty seconds+-- after a reading in which the node named something new. That reading+-- brought the pool back, 26 seconds after it was emptied, in a store that+-- had been made unable to notice the loss, and so within any limit that+-- is safe for a slow machine. So the test waits for that reading before it+-- empties the pool: the next one is then thirty seconds away or more, the+-- node taking nothing meanwhile, and what brings the pool back in fifteen+-- is the store noticing.+valkeyFlush :: Bed -> IO ()+valkeyFlush bed = do+  roots <- fund bed 40+  let (before, after) = splitAt 20 roots+  withMember bed $ \_ server -> do+    submit bed (map (chainOf 24) before)+    converges bed server 60+    byTheClock 280+    flush bed+    converges bed server 15+    lost <- said "Redis lost its data"+    lost `shouldBe` 1+    submit bed (map (chainOf 24) after)+    converges bed server 60+  where+    -- how many lines of the log of the store, above the level of+    -- debugging, have these words+    said :: String -> IO Int+    said what = length . filter (what `isInfixOf`) . takeWhile (/= "--- at every level") <$> bed.logTail+    -- wait for the second reading of the mempool of the node, the first+    -- being that of when the node connected, for so many quarters of a+    -- second+    byTheClock :: Int -> IO ()+    byTheClock n = do+      readings <- said "for its mempool"+      unless (readings >= 2) $+        if n <= 0+          then expectationFailure "The store did not read the mempool of its node a second time in 70 seconds"+          else threadDelay 250000 >> byTheClock (n - 1)++-- | A store that runs while its node takes chains and finds blocks at the+-- same time, round after round: an announcement may reach the store while+-- it is a block behind.+busy :: Bed -> IO ()+busy bed = do+  roots <- fund bed 200+  withMember bed $ \_ server -> do+    converges bed server 60+    forM_ (pieces 10 roots) $ \some ->+      withAsync (submit bed (map (chainOf 24) some)) $ \sending -> do+        link sending+        -- two blocks while the chains go in+        forM_ [1 :: Int, 2] $ \_ -> threadDelay 150000 >> generateTo bed.node 1 bed.miner+        -- what the blocks left out goes in after them+        threadDelay 500000+    converges bed server 60+  where+    pieces _ [] = []+    pieces n xs = let (a, b) = splitAt n xs in a : pieces n b++-- | A block that confirms thousands of transactions of the pool comes+-- while the node goes on taking transactions without a pause, about sixty+-- a second, as the node of a busy network always does. The store has to+-- answer from the block within seconds, while they keep coming.+--+-- The other situations here let the node go quiet before they look, and so+-- passed on a store that could not move its tip while anything was+-- offered: on a server, such a store imported every block and answered+-- from an old one for as long as it ran, with its health saying that all+-- was well. Taking the block's transactions out of the pool is one+-- decision, carried out only if nothing that it read has changed, and+-- every transaction offered meanwhile changed something+-- ('Haskoin.Store.Fleet.Pool.Decide.floorHeld').+unceasing :: Bed -> IO ()+unceasing bed = do+  -- fewer in the first load than Bitcoin Core remembers having named to+  -- a peer, 3,500: asked for one that it named before those, it says+  -- that it has it not+  roots <- fund bed 160+  let (first, rest) = splitAt 100 roots+  withMember bed $ \_ server -> do+    submit bed (map (chainOf 24) first)+    converges bed server 180+    -- four chains at a time, the transactions of each in their order, with+    -- a pause after each: about sixty a second between them+    let slowly tx = send bed tx >> threadDelay 60000+        trickle = forConcurrently_ (lanes 4 (map (chainOf 24) rest)) (mapM_ slowly . concat)+    withAsync trickle $ \sending -> do+      link sending+      forM_ [1 :: Int, 2] $ \_ -> do+        threadDelay 3000000+        void (generateTo bed.node 1 bed.miner)+        best <- bestBlockHash bed.node+        follows server best 20+    converges bed server 180+  where+    lanes n xs = [[x | (i, x) <- zip [0 :: Int ..] xs, i `mod` n == l] | l <- [0 .. n - 1]]+    -- within so many seconds, the store answers from a block+    follows server best seconds = do+      start <- getPOSIXTime+      let go = do+            (_, b) <- getJSON server "/block/best?notx=true"+            now <- getPOSIXTime+            if textField "hash" b == Just best+              then return ()+              else+                if now - start > fromIntegral (seconds :: Int)+                  then+                    expectationFailure . unwords $+                      [ "After",+                        show seconds,+                        "seconds, with transactions still coming, the store answers from",+                        maybe "no block" T.unpack (textField "hash" b),+                        "and not from the best block of its node,",+                        T.unpack best+                      ]+                  else threadDelay 250000 >> go+      go++-------------------------------------------------------------------------------+-- Convergence+-------------------------------------------------------------------------------++-- | Within so many seconds, the store has the best block of its node and+-- its mempool is that of the node, the same transactions and no other; and+-- it is still so two seconds later, the node having taken nothing since.+converges :: Bed -> Server -> Int -> IO ()+converges = convergesWith (return ())++-- | 'converges', with something to do at each look.+convergesWith :: IO () -> Bed -> Server -> Int -> IO ()+convergesWith each bed server seconds = do+  start <- getPOSIXTime+  let go = do+        each+        (node, ours, same) <- look+        now <- getPOSIXTime+        if same && node == ours+          then return ()+          else+            if now - start > fromIntegral seconds+              then do+                recent <- bed.logTail+                (_, health) <- getJSON server "/health"+                when (Set.size node /= Set.size ours || node /= ours) $+                  hPutStrLn stderr . unlines $+                    ["--- the last lines of the log of the store"] <> recent+                expectationFailure . unwords $+                  [ "After",+                    show seconds,+                    "seconds the node has",+                    show (Set.size node),+                    "transactions in its mempool and the store",+                    show (Set.size ours) <> ":",+                    show (Set.size (node `Set.difference` ours)),+                    "that the store lacks,",+                    show (Set.size (ours `Set.difference` node)),+                    "that only the store has; same best block:",+                    show same <> ".",+                    "The store says of its path into the pool:",+                    maybe "nothing" T.unpack (field "mempool" health >>= textField "text")+                  ]+              else threadDelay 250000 >> go+  go+  -- and it stays: nothing was on its way out+  threadDelay 2000000+  (node, ours, same) <- look+  unless (same && node == ours) $+    expectationFailure "The store had the mempool of its node, and no longer has two seconds later"+  where+    look = do+      best <- bestBlockHash bed.node+      node <- Set.fromList <$> rawMempool bed.node+      (_, b) <- getJSON server "/block/best?notx=true"+      (_, m) <- getJSON server "/mempool?limit=1000000"+      let ours = Set.fromList [t | String t <- list m]+      return (node, ours, textField "hash" b == Just best)+    list = \case+      v@(Array _) -> arr v+      _ -> []+    field name = \case+      Object o -> KeyMap.lookup name o+      _ -> Nothing++-------------------------------------------------------------------------------+-- Chains of transactions+-------------------------------------------------------------------------------++-- | The script that anyone can spend: @OP_TRUE@.+redeem :: ByteString+redeem = B.singleton 0x51++-- | An output script that pays to the hash of 'redeem'.+lock :: ByteString+lock = B.concat [B.pack [0xa9, 0x14], encode (addressHash redeem), B.singleton 0x87]++-- | An output script that holds data, of value 0: @OP_RETURN@ and twenty+-- bytes.+note :: ByteString+note = B.pack [0x6a, 0x14] <> B.replicate 20 0x2a++-- | A transaction that spends an output locked by 'lock'.+spend :: OutPoint -> [TxOut] -> Tx+spend op outs = Tx 2 [TxIn op (B.pack [0x01, 0x51]) maxBound] outs [] 0++-- | What each transaction of a chain pays its node.+fee :: Word64+fee = 5000++-- | A chain of so many transactions from an output and its value: each+-- has an output of value 0 that holds data and pays the rest to the next.+chainOf :: Int -> (OutPoint, Word64) -> [Tx]+chainOf 0 _ = []+chainOf n (op, value) =+  let tx = spend op [TxOut 0 note, TxOut (value - fee) lock]+   in tx : chainOf (n - 1) (OutPoint (txHash tx) 1, value - fee)++-- | So many confirmed outputs that anyone can spend, each with its value,+-- for chains to start from: the wallet of the node pays one output, a+-- transaction splits it, and a block confirms both.+fund :: Bed -> Int -> IO [(OutPoint, Word64)]+fund bed count = do+  let each = 1000000+      total = fromIntegral count * each + 100000+  address <- case scriptToAddressBS bed.net lock >>= maybe (Left "no text") Right . addrToText bed.net of+    Right a -> return a+    Left e -> fail ("No address for the script: " <> e)+  txid <- sendTo bed.node address total+  paid <- getRawTx bed.node txid+  let outs = maybe [] arr (field "vout" paid)+      mine =+        [ n+        | o <- outs,+          (field "scriptPubKey" o >>= textField "hex") == Just (encodeHex lock),+          Just (Number n) <- [field "n" o]+        ]+  index <- case mine of+    [n] -> return (round n)+    _ -> fail "The wallet did not pay the script once"+  hash <- maybe (fail "Not a transaction id") return (hexToTxHash txid)+  let split = spend (OutPoint hash index) (replicate count (TxOut each lock))+  send bed split+  void $ generateTo bed.node 1 bed.miner+  return [(OutPoint (txHash split) i, each) | i <- [0 .. fromIntegral count - 1]]++-- | Give the node a transaction. The socket of its RPC takes few+-- connections at once, and refuses one more with an error of the HTTP+-- client: such a call is made again, a few times.+send :: Bed -> Tx -> IO ()+send bed tx = go (5 :: Int)+  where+    go n =+      try (rpc bed.node "sendrawtransaction" [String (encodeHex (encode tx))]) >>= \case+        Right _ -> return ()+        Left (e :: HttpException)+          | n > 0 -> threadDelay 100000 >> go (n - 1)+          | otherwise -> throwIO e++-- | Give the node chains of transactions, each in its order, four chains+-- at a time.+submit :: Bed -> [[Tx]] -> IO ()+submit bed chains = forConcurrently_ (transpose (groups chains)) (mapM_ (mapM_ (send bed)))+  where+    groups [] = []+    groups xs = let (a, b) = splitAt 4 xs in a : groups b++-------------------------------------------------------------------------------+-- The bed of a test+-------------------------------------------------------------------------------++-- | A node that whitelists the store, with 150 blocks, and a Valkey, in a+-- pod: what a store needs, without the store.+data Bed = Bed+  { -- | the pod, to stop and start its containers+    pod :: !Pod,+    node :: !Node,+    net :: !Network,+    -- | address of the wallet of the node, to mine to+    miner :: !Text,+    redisURL :: !String,+    granted :: !Permissions,+    -- | whether the stores of the bed are given the RPC of the node+    viaRpc :: !Bool,+    -- | and hears what the node publishes over ZeroMQ+    viaZmq :: !Bool,+    logger :: !Logger,+    -- | the last lines of the log of the stores of the bed+    logTail :: !(IO [String])+  }++withBed :: NodeKind -> (Bed -> IO ()) -> IO ()+withBed kind = withBedOf (nodeContainer kind) kind++-- | The container of a node that whitelists nobody: to its peers it is+-- what a node of somebody else is.+bare :: NodeKind -> ContainerSpec+bare kind = c {name = c.name <> "-bare", command = filter (/= "-whitelist=0.0.0.0/0") c.command}+  where+    c = nodeContainer kind++-- | 'withBed' with the container of the node given, for a node that is+-- started with other options.+withBedOf :: ContainerSpec -> NodeKind -> (Bed -> IO ()) -> IO ()+withBedOf nodeSpec kind go =+  withPod (pod "mempool" [redisContainer, nodeSpec]) {readyWithin = 120} $ \p -> do+    node <- nodeOf kind p+    waitRpc node+    ensureWallet node+    miner <- getNewAddress node+    void $ generateTo node 150 miner+    withTestLog $ \logger logTail ->+      go+        Bed+          { pod = p,+            node,+            net = nodeNetwork kind,+            miner,+            redisURL = Valkey.redisURL p,+            granted = grantedBy True kind,+            viaRpc = False,+            viaZmq = False,+            logger,+            logTail+          }++-- | Empty the Valkey of the bed, as a server whose Redis lost its data.+flush :: Bed -> IO ()+flush bed = do+  conn <- Redis.checkedConnect (either error id (redisConnectInfo bed.redisURL))+  void (Redis.runRedis conn Redis.flushall)+  Redis.disconnect conn++-- | A store of the bed with its web server, on a database in a folder,+-- while an action runs.+withMemberIn :: Bed -> FilePath -> (Store -> Server -> IO a) -> IO a+withMemberIn = withMemberOf id++-- | 'withMemberIn', with the configuration of the store changed.+withMemberOf :: (StoreConfig -> StoreConfig) -> Bed -> FilePath -> (Store -> Server -> IO a) -> IO a+withMemberOf change bed dir f =+  withStore (change (heard (storeConfig bed.net bed.logger dir bed.redisURL bed.node.peer bed.granted))) $ \store ->+    listening $ \(sock, server) ->+      withAsync (runWebSocket (web store) sock) $ \running ->+        link running >> f store server+  where+    -- with the node as a peer through its RPC, and its ZeroMQ socket+    -- where the bed has it+    -- the node is then one peer more+    heard c+      | bed.viaRpc =+          c+            { maxPeers = c.maxPeers + 1,+              nodePeerRpc = Just bed.node.url,+              nodePeerRpcSocket = Just bed.node.rpcSocket,+              nodePeerZmq = if bed.viaZmq then Just bed.node.zmq else Nothing+            }+      | otherwise = c+    web store+      | bed.viaRpc =+          (webConfig bed.logger store)+            { nodeRpc = Just bed.node.url,+              nodeRpcSocket = Just bed.node.rpcSocket,+              nodeZmq = if bed.viaZmq then Just bed.node.zmq else Nothing+            } ::+            WebConfig+      | otherwise = webConfig bed.logger store++-- | 'withMemberIn' a new folder.+withMember :: Bed -> (Store -> Server -> IO a) -> IO a+withMember bed f = withRamDir $ \dir -> withMemberIn bed dir f
+ test/Haskoin/Store/NodeAxiomsSpec.hs view
@@ -0,0 +1,434 @@+-- |+-- Module      : Haskoin.Store.NodeAxiomsSpec+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- What @docs\/mempool-ingestion.md@ assumes of a node, A1 to A8, checked+-- against Bitcoin Core and Bitcoin Cash Node in Podman.+--+-- The proofs and the model checker of the path into the pool+-- ("Haskoin.Store.Ingest") take these for granted: they are what the world+-- is assumed to do, and no proof can establish them. A test against the+-- real program can at least catch the day one of them stops being true,+-- with a new release of a node. One of them was false in the code for+-- months and nobody had written it down: "a peer announces again".+--+-- The tests speak to the node as a peer of their own, a few lines that+-- connect, shake hands and keep what the node sends, so that what is+-- checked is what the node does and not what the store makes of it.+module Haskoin.Store.NodeAxiomsSpec (spec) where++import Control.Concurrent (newEmptyMVar, putMVar, takeMVar, threadDelay)+import Control.Concurrent.Async (async, wait, withAsync)+import Control.Exception (IOException, bracket, try)+import Control.Monad (forM_)+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.List (elemIndex, sort)+import Data.Maybe (mapMaybe)+import Data.Serialize (encode, runGet, runPut)+import Data.Set qualified as Set+import Data.Text qualified as T+import Data.Time.Clock.POSIX (getPOSIXTime)+import Haskoin+  ( GetData (..),+    Inv (..),+    InvType (..),+    InvVector (..),+    Message (..),+    Network (..),+    NetworkAddress (..),+    NotFound (..),+    Ping (..),+    Pong (..),+    Tx,+    TxHash (..),+    VarString (..),+    Version (..),+    doubleSHA256,+    encodeHex,+    getMessage,+    putMessage,+    sockToHostAddress,+    txHash,+    txHashToHex,+  )+import Haskoin.Store.Ingest.Run (Feed (..))+import Haskoin.Store.Integration.Node+import Haskoin.Store.MempoolSpec (Bed (..), bare, chainOf, fund, send, submit, withBed, withBedOf)+import Haskoin.Store.NodeRpc (RpcFailure (..), nodeFeed, nodeSession)+import Haskoin.Store.NodeZmq (ZmqMessage (..), parseZmqAddress, zmqSubscribe)+import Network.Socket (SockAddr (..), Socket, close)+import Network.Socket.ByteString (recv, sendAll)+import System.Timeout (timeout)+import Test.Hspec+import Test.Podman (address, connectTo, podmanUsable)++spec :: Spec+spec = do+  usable <- runIO podmanUsable+  case usable of+    Left why -> describe "What is assumed of a node" $ it "is what the nodes do" (pendingWith why)+    Right () -> forM_ [BitcoinCore, BitcoinCashNode] $ \kind -> do+      let on what = describe (name kind <> " " <> what)+      on "names a transaction to a peer" $+        it "once, and never one that it took before the peer connected (A1)" (withBed kind namesOnce)+      on "asked for what a transaction that it named spends from" $+        it "sends it though it never named it, or says that it has it not (A7)" (withBed kind (sendsParents kind))+      on "that takes many transactions at once" $+        it "names them to a peer that it whitelists no faster than it chooses to (A8)" $+          withBed kind (namesAtItsPace kind)+      on "asked for its mempool by a peer that it allows" $+        it "names all of it, each after those it spends from, and sends or says it has not (A2, A3, A5)" $+          withBed kind namesAll+      on "asked for its mempool by a peer that it gives no permission" $+        it "closes the connection, or answers if it serves Bloom filters (A2)" $+          withBedOf (bare kind) kind (noSource kind)+      on "asked for its mempool over its RPC" $+        it "gives all of it, the transactions asked for, and its word for one that it has not" $+          withBed kind overRpc+      on "publishes over ZeroMQ" $+        it "the id of each transaction that it takes and the hash of each new tip, with a counter (F2)" $+          withBed kind publishes+  where+    name BitcoinCore = "Bitcoin Core"+    name BitcoinCashNode = "Bitcoin Cash Node"++-- | F2. A subscriber of the node's ZeroMQ socket hears the id of a+-- transaction when the node takes it, and again when a block that has it+-- becomes the tip; and the hash of that block. The ids and the hash are+-- in the order in which the RPC writes them. Each topic has a counter that+-- goes up by one with each message, which is how a subscriber knows that+-- it lost one.+--+-- The store reads this with a client of its own+-- ("Haskoin.Store.NodeZmq"), so this is also the test of that client+-- against the library of ZeroMQ that the nodes are built with.+publishes :: Bed -> IO ()+publishes bed = do+  roots <- fund bed 2+  heard <- newIORef []+  ready <- newEmptyMVar+  where' <- either fail return (parseZmqAddress bed.node.zmq)+  let listen = zmqSubscribe where' ["hashtx", "hashblock"] (putMVar ready ()) (\m -> modifyIORef' heard (m :))+      of' t = filter ((== t) . (.topic)) . reverse <$> readIORef heard+      -- until so many messages of a topic were heard, for ten seconds+      until' t n = do+        r <- timeout 10000000 (awaiting t n)+        maybe (expectationFailure ("Not " <> show n <> " messages of " <> show t)) return r+      awaiting t n = do+        got <- of' t+        if length got >= n then return () else threadDelay 100000 >> awaiting t n+  withAsync listen $ \_ -> do+    timeout 10000000 (takeMVar ready) >>= maybe (expectationFailure "No subscription to the node") return+    -- a publisher takes a moment to act on a subscription+    threadDelay 1000000+    -- A node publishes a block a moment after it finds it, and the last+    -- block that paid for this test may be published only now: on a Unix+    -- socket the subscription is there at once, and it was heard, where+    -- behind a bridge of TCP it never was. What came so far is not what+    -- the test sends.+    writeIORef heard []+    case concatMap (chainOf 1) roots of+      [a, b] -> do+        send bed a+        send bed b+        until' "hashtx" 2+        taken <- of' "hashtx"+        -- as the RPC writes an id: the reverse of its bytes+        sort (map (.body) taken) `shouldBe` sort [B.reverse (encode (txHash t)) | t <- [a, b]]+        block : _ <- generateTo bed.node 1 bed.miner+        until' "hashblock" 1+        tips <- of' "hashblock"+        map (encodeHex . (.body)) tips `shouldBe` [block]+        -- the block has both, and a coinbase: each is published again+        until' "hashtx" 5+        all' <- of' "hashtx"+        length (filter ((`elem` map (.body) taken) . (.body)) all') `shouldBe` 4+        -- each message is the one after the last of its topic+        let numbers = map (.number) all'+        zipWith (-) (drop 1 numbers) numbers `shouldSatisfy` all (== 1)+      _ -> expectationFailure "Not two transactions"++-- | A1. The node takes one transaction, a peer connects, and the node+-- takes another: the peer is told of the second once, and of the first+-- never.+namesOnce :: Bed -> IO ()+namesOnce bed = do+  roots <- fund bed 2+  case concatMap (chainOf 1) roots of+    [old, new] -> do+      send bed old+      withProbe bed $ \p -> do+        send bed new+        named <- namedIn <$> collect p 10+        filter (== txHash new) named `shouldBe` [txHash new]+        filter (== txHash old) named `shouldBe` []+    _ -> expectationFailure "Not two transactions"++-- | A7. The node takes a transaction, a peer connects, and the node takes+-- one that spends from the first: the peer is told of the second only+-- (A1). Asked for the first, Bitcoin Core sends it, and Bitcoin Cash Node+-- says that it has it not, though it has: it sends a peer what it named+-- to that peer and nothing else.+--+-- The path into the pool asks for what a transaction spends from when+-- the pool lacks it (@seek@ in "Haskoin.Store.Ingest"). With Bitcoin Core+-- that brings it at once. With Bitcoin Cash Node it brings it only if the+-- node named it on this connection, and otherwise the transaction waits,+-- as it did before, for the next reading of the node's mempool, which a+-- store of Bitcoin Cash always has a source for (A2).+sendsParents :: NodeKind -> Bed -> IO ()+sendsParents kind bed = do+  roots <- fund bed 1+  case concatMap (chainOf 2) roots of+    [parent, child] -> do+      send bed parent+      withProbe bed $ \p -> do+        send bed child+        named <- namedIn <$> collect p 10+        named `shouldBe` [txHash child]+        tell p (MGetData (GetData [InvVector InvTx (txHash parent).get]))+        answers <- collect p 6+        let sent = [txHash tx | MTx tx <- answers]+            denied = [TxHash h | MNotFound (NotFound ivs) <- answers, InvVector _ h <- ivs]+        (sent, denied) `shouldBe` case kind of+          BitcoinCore -> ([txHash parent], [])+          BitcoinCashNode -> ([], [txHash parent])+    _ -> expectationFailure "Not two transactions"++-- | A8. The node takes 800 transactions in a second or so, with a peer+-- that it whitelists connected. Bitcoin Core names about five hundred of+-- them at once and then seventy every five seconds: ten seconds on, the+-- peer has not been told of them all, and it has within forty-five.+-- Bitcoin Cash Node names them all in the first seconds.+--+-- So a store of Bitcoin is behind its node whenever the node takes more+-- than fourteen transactions a second for a while, however fast the+-- store is, unless it asks the node for its mempool, which has them all+-- (A2). The path into the pool reads its sources every thirty seconds+-- while transactions come, for that (@told@ in "Haskoin.Store.Ingest").+namesAtItsPace :: NodeKind -> Bed -> IO ()+namesAtItsPace kind bed = do+  roots <- fund bed 800+  let txs = concatMap (chainOf 1) roots+  withProbe bed $ \p -> do+    sender <- async (submit bed (map pure txs))+    early <- length . namedIn <$> collect p 10+    late <- length . namedIn <$> collect p 35+    wait sender+    case kind of+      BitcoinCore -> do+        early `shouldSatisfy` (< 800)+        early + late `shouldBe` 800+      BitcoinCashNode -> (early, late) `shouldBe` (800, 0)++-- | A2, A3 and A5. A peer that the node allows asks for its mempool: the+-- node names every transaction of it, those of a chain in their order;+-- asked for one of them, it sends it; asked for one that it never had, it+-- says so.+namesAll :: Bed -> IO ()+namesAll bed = do+  roots <- fund bed 3+  let chains = map (chainOf 5) roots+  submit bed chains+  withProbe bed $ \p -> do+    tell p MMempool+    named <- namedIn <$> collect p 6+    has <- rawMempool bed.node+    Set.fromList (map txHashToHex named) `shouldBe` Set.fromList has+    forM_ chains $ \chain -> do+      let places = mapMaybe ((`elemIndex` named) . txHash) chain+      length places `shouldBe` length chain+      places `shouldBe` sort places+    root <- case chains of+      (tx : _) : _ -> return (txHash tx)+      _ -> fail "No chain"+    let never = TxHash (doubleSHA256 ("never sent" :: ByteString))+    tell p (MGetData (GetData [InvVector InvTx root.get, InvVector InvTx never.get]))+    answers <- collect p 6+    [txHash tx | MTx tx <- answers] `shouldBe` [root]+    [TxHash h | MNotFound (NotFound ivs) <- answers, InvVector _ h <- ivs] `shouldBe` [never]++-- | A2, for a peer with no permission. Bitcoin Core closes the connection+-- of one that asks for its mempool; Bitcoin Cash Node serves Bloom+-- filters, and answers anyone.+noSource :: NodeKind -> Bed -> IO ()+noSource kind bed = do+  roots <- fund bed 1+  let txs = concatMap (chainOf 1) roots :: [Tx]+  mapM_ (send bed) txs+  withProbe bed $ \p -> do+    tell p MMempool+    case kind of+      BitcoinCore -> closes p 15 `shouldReturn` True+      BitcoinCashNode -> do+        named <- namedIn <$> collect p 8+        Set.fromList named `shouldBe` Set.fromList (map txHash txs)++-- | What the path into the pool assumes of the RPC of a node as a source+-- ('nodeFeed'), which is A2 and A3 for something that is no peer: it gives+-- the id of every transaction of the mempool; asked for transactions, it+-- gives each that it has and says of one that it never had that it has it+-- not. And a node that does not answer, or does not let the store in, is+-- an exception: it is never taken for an empty mempool, or for a+-- transaction that is gone.+overRpc :: Bed -> IO ()+overRpc bed = do+  roots <- fund bed 3+  let chains = map (chainOf 5) roots+  submit bed chains+  session <- nodeSession (Just bed.node.rpcSocket)+  let feed = nodeFeed session bed.node.url+  named <- feed.names+  has <- rawMempool bed.node+  length named `shouldBe` 15+  Set.fromList (map txHashToHex named) `shouldBe` Set.fromList has+  -- each after those it spends from, as a peer names them (A5)+  forM_ chains $ \chain -> do+    let places = mapMaybe ((`elemIndex` named) . txHash) chain+    places `shouldBe` sort places+  let mine = map txHash (concat chains)+      never = TxHash (doubleSHA256 ("never sent" :: ByteString))+      asked = take 2 mine <> [never] <> drop 13 mine+  found <- feed.bodies asked+  map (fmap txHash) found `shouldBe` map Just (take 2 mine) <> [Nothing] <> map Just (drop 13 mine)+  -- nobody listens+  deaf <- nodeSession (Just "/nowhere/rpc.sock")+  (nodeFeed deaf bed.node.url).names `shouldThrow` anyException+  (nodeFeed deaf bed.node.url).bodies asked `shouldThrow` anyException+  -- the node does not know the account+  let stranger = nodeFeed session (T.unpack (T.replace "test:test@" "test:other@" (T.pack bed.node.url)))+  bed.node.url `shouldContain` "test:test@"+  stranger.names `shouldThrow` \(RpcFailure _) -> True+  stranger.bodies asked `shouldThrow` \(RpcFailure _) -> True++-- | The transactions that messages name, in their order.+namedIn :: [Message] -> [TxHash]+namedIn msgs = [TxHash h | MInv (Inv ivs) <- msgs, InvVector t h <- ivs, t == InvTx || t == InvWitnessTx]++-------------------------------------------------------------------------------+-- A peer of the tests+-------------------------------------------------------------------------------++-- | A connection to a node, after the handshake, with the bytes read and+-- not yet made into a message.+data Probe = Probe+  { sock :: !Socket,+    net :: !Network,+    unread :: !(IORef ByteString)+  }++-- | What reading a message gave.+data Heard = Heard !Message | Quiet | Closed++-- | Connect to the node of a bed as a peer, shake hands, and run an action+-- on the connection. The peer says of itself what the network's own+-- constants say.+withProbe :: Bed -> (Probe -> IO a) -> IO a+withProbe bed f = bracket (connectTo (address bed.pod "p2p")) close $ \sock -> do+  unread <- newIORef B.empty+  let p = Probe {sock, net = bed.net, unread}+  now <- round <$> getPOSIXTime+  tell p (MVersion (version now))+  shake p False False+  f p+  where+    nobody = NetworkAddress 0 (sockToHostAddress (SockAddrInet 0 0))+    version now =+      Version+        { version = 70015,+          services = 0,+          timestamp = now,+          addrRecv = nobody,+          addrSend = nobody,+          nonce = 0x70726f6265,+          userAgent = VarString bed.net.userAgent,+          startHeight = 0,+          relay = True+        }+    shake _ True True = return ()+    shake p theirs ack =+      hear p 20000000 >>= \case+        Heard (MVersion _) -> tell p MVerAck >> shake p True ack+        Heard MVerAck -> shake p theirs True+        Heard _ -> shake p theirs ack+        _ -> fail "The node did not shake hands"++-- | Send a message.+tell :: Probe -> Message -> IO ()+tell p msg = sendAll p.sock (runPut (putMessage p.net msg))++-- | The next message of the node, within so many microseconds. A ping is+-- answered here, and is a message like another.+hear :: Probe -> Int -> IO Heard+hear p micros = do+  got <- timeout micros (try message)+  case got of+    Nothing -> return Quiet+    Just (Left (_ :: IOException)) -> return Closed+    Just (Right Nothing) -> return Closed+    Just (Right (Just msg)) -> do+      case msg of+        MPing (Ping n) -> tell p (MPong (Pong n))+        _ -> return ()+      return (Heard msg)+  where+    -- a header of 24 bytes, whose bytes 16 to 19 are the length of what+    -- follows+    message = do+      header <- exactly 24+      case header of+        Nothing -> return Nothing+        Just h -> do+          let size = sum [fromIntegral (B.index h (16 + i)) * 256 ^ i | i <- [0 .. 3 :: Int]]+          payload <- exactly size+          case payload of+            Nothing -> return Nothing+            Just body -> either fail (return . Just) (runGet (getMessage p.net) (h <> body))+    -- so many bytes, or nothing if the node closed the connection first;+    -- what was read stays for the next call if this one runs out of time+    exactly n = do+      have <- readIORef p.unread+      if B.length have >= n+        then writeIORef p.unread (B.drop n have) >> return (Just (B.take n have))+        else do+          more <- recv p.sock 65536+          if B.null more+            then return Nothing+            else writeIORef p.unread (have <> more) >> exactly n++-- | Every message of the node for so many seconds.+collect :: Probe -> Int -> IO [Message]+collect p seconds = do+  start <- getPOSIXTime+  let go heard = do+        now <- getPOSIXTime+        let left = fromIntegral seconds - realToFrac (now - start) :: Double+        if left <= 0+          then return (reverse heard)+          else+            hear p (round (left * 1000000)) >>= \case+              Heard msg -> go (msg : heard)+              _ -> return (reverse heard)+  go []++-- | Whether the node closes the connection within so many seconds.+closes :: Probe -> Int -> IO Bool+closes p seconds = do+  start <- getPOSIXTime+  let go = do+        now <- getPOSIXTime+        let left = fromIntegral seconds - realToFrac (now - start) :: Double+        if left <= 0+          then return False+          else+            hear p (round (left * 1000000)) >>= \case+              Closed -> return True+              Quiet -> return False+              Heard _ -> go+  go
test/Haskoin/Store/Web/PublishSpec.hs view
@@ -14,7 +14,7 @@ import Data.Word (Word32, Word64, Word8) import Haskoin hiding (Coin (..)) import Haskoin.Store.Web.Publish-import Network.Socket (SockAddr (..), tupleToHostAddress)+import Network.Socket (SockAddr (..)) import Test.Hspec  -- | An output, told apart by a number.@@ -55,9 +55,10 @@       | i.script == saying "script" = InputUndecided       | otherwise = InputVerified --- | A peer, told apart by a number.+-- | A peer, told apart by a number: a Unix socket by name, which nothing+-- opens, since the courier of these tests is a function. node :: Int -> SockAddr-node n = SockAddrInet 8333 (tupleToHostAddress (10, 0, 0, fromIntegral n))+node n = SockAddrUnix ("peer-" <> show n)  -- | A desk to publish at: every output is a coin of 1000, the store has no -- transaction, there is no node to ask over RPC, and there are as many@@ -88,143 +89,11 @@ taking :: Int -> Tx -> Delivery taking _ _ = Took --- | The front of the script of an output that holds tokens: the category,--- the flags, the commitment if there is one, and the amount if not zero.-withTokens :: ByteString -> Maybe (Word8, ByteString) -> Word64 -> ByteString-withTokens category nft amount =-  B.concat-    [ "\xef",-      category,-      B.singleton (nftFlags .|. (if amount > 0 then 0x10 else 0)),-      maybe "" (\(_, c) -> if B.null c then "" else B.singleton (fromIntegral (B.length c)) <> c) nft,-      if amount > 0 then compact amount else "",-      "\x76\xa9\x14" <> B.replicate 20 7 <> "\x88\xac"-    ]-  where-    nftFlags = case nft of-      Nothing -> 0-      Just (capability, c) -> 0x20 .|. capability .|. (if B.null c then 0 else 0x40)-    compact v-      | v < 0xfd = B.singleton (fromIntegral v)-      | otherwise = "\xfd" <> B.pack [fromIntegral v, fromIntegral (v `div` 256)]-    a .|. b = a + b- spec :: Spec spec = do-  let check = judge rulesOf-  describe "what the store can check" $ do-    let tx = spending [output 1, output 2] 1500-    it "lets through a transaction that spends what is there" $-      check tx [held 1000, held 500] `shouldBe` Right Nothing-    it "refuses an output it does not know, and one spent in a block" $ do-      check tx [held 1000, Missing] `shouldBe` Left (UnknownOutput (output 2))-      let by = (output 9).hash-      check tx [Spent by, held 1000] `shouldBe` Left (SpentOutput (output 1) by)-    it "refuses outputs worth more than the inputs" $-      check tx [held 1000, held 499] `shouldBe` Left Overspent-    it "refuses the same output twice, a coinbase, and nothing to spend or pay" $ do-      check (spending [output 1, output 1] 1) [held 1, held 1] `shouldBe` Left (DuplicateInput (output 1))-      check (spending [nullOutPoint] 1) [Missing] `shouldBe` Left IsCoinbase-      check (spending [] 1) [] `shouldBe` Left NoInputs-      check (spending [output 1] 1) {outputs = []} [held 1] `shouldBe` Left NoOutputs-    it "refuses a coinbase that is not a hundred blocks old" $ do-      let young h = Coin {output = TxOut 1000 "", mined = Just h, coinbase = True}-          one = spending [output 1] 900-      check one [young 902] `shouldBe` Left (Immature (output 1))-      check one [young 901] `shouldBe` Right Nothing-      check one [(young 902) {coinbase = False}] `shouldBe` Right Nothing-    it "refuses a lock time that has not passed, unless every input waives it" $ do-      let locked n = (spending [output 1] 900) {locktime = n, inputs = [TxIn (output 1) "" 0]} :: Tx-      check (locked 1000) [held 1000] `shouldBe` Right Nothing-      check (locked 1001) [held 1000] `shouldBe` Left (NotFinal 1001)-      check (locked 1599999999) [held 1000] `shouldBe` Right Nothing-      check (locked 1600000000) [held 1000] `shouldBe` Left (NotFinal 1600000000)-      check ((locked 1001) {inputs = [TxIn (output 1) "" maxBound]} :: Tx) [held 1000] `shouldBe` Right Nothing-    it "refuses an output worth less than it costs to spend, and not one that holds data" $ do-      let paying v script = (spending [output 1] 0) {outputs = [TxOut v script]} :: Tx-          keyHash = "\x76\xa9\x14" <> B.replicate 20 7 <> "\x88\xac"-          witnessKeyHash = "\x00\x14" <> B.replicate 20 7-      check (paying 545 keyHash) [held 1000] `shouldBe` Left (Dust 0)-      check (paying 546 keyHash) [held 1000] `shouldBe` Right Nothing-      check (paying 293 witnessKeyHash) [held 1000] `shouldBe` Left (Dust 0)-      check (paying 294 witnessKeyHash) [held 1000] `shouldBe` Right Nothing-      check (paying 0 "\x6a\x04data") [held 1000] `shouldBe` Right Nothing-    it "refuses a forged signature, and names the input it cannot judge" $ do-      let signedBy items = (spending [output 1, output 2] 900) {inputs = zipWith input [1 ..] items} :: Tx-          input n item = TxIn (output n) (saying item) maxBound-      check (signedBy ["good", "forged"]) [held 1000, held 1000] `shouldBe` Left (Forged 1)-      check (signedBy ["good", "script"]) [held 1000, held 1000] `shouldBe` Right (Just 1)-      check (signedBy ["good", "good"]) [held 1000, held 1000] `shouldBe` Right Nothing-    it "refuses a version that nodes do not take: 1 to 3 on Bitcoin, 1 and 2 on Bitcoin Cash" $ do-      let versioned v = (spending [output 1] 900) {version = v} :: Tx-          cash = judge rulesOf {net = bch}-      check (versioned 3) [held 1000] `shouldBe` Right Nothing-      check (versioned 0) [held 1000] `shouldBe` Left (BadVersion 0)-      check (versioned 4) [held 1000] `shouldBe` Left (BadVersion 4)-      cash (versioned 2) [held 1000] `shouldBe` Right Nothing-      cash (versioned 3) [held 1000] `shouldBe` Left (BadVersion 3)-    it "refuses an input script that does more than push, or pushes in a longer form than it needs" $ do-      let scripted ops = (spending [output 1] 900) {inputs = [TxIn (output 1) (encode (Script ops)) maxBound]} :: Tx-          signature = B.replicate 71 1-      check (scripted [opPushData signature, opPushData (B.replicate 33 2)]) [held 1000] `shouldBe` Right Nothing-      -- a push of 71 bytes takes one byte for its length, not two-      check (scripted [OP_PUSHDATA signature OPDATA1]) [held 1000] `shouldBe` Left (NotMinimal 0)-      -- the number 1 is OP_1, and the empty string OP_0-      check (scripted [OP_PUSHDATA "\x01" OPCODE]) [held 1000] `shouldBe` Left (NotMinimal 0)-      check (scripted [OP_0, OP_1, OP_1NEGATE]) [held 1000] `shouldBe` Right Nothing-      check (scripted [opPushData signature, OP_DUP]) [held 1000] `shouldBe` Left (NotPushOnly 0)-      -- bytes that are not a script at all-      check ((spending [output 1] 900) {inputs = [TxIn (output 1) "\x4c" maxBound]} :: Tx) [held 1000]-        `shouldBe` Left (NotPushOnly 0)--  describe "the tokens of Bitcoin Cash" $ do-    let category = B.replicate 32 9-        -- a category made by this transaction: the id of what its first-        -- input spends, whose index is 0-        newCategory = encode (OutPoint (TxHash (doubleSHA256 ("genesis" :: ByteString))) 0).hash-        from n = OutPoint (output n).hash n-        tx ins outs = (spending ins 0) {outputs = [TxOut 1000 s | s <- outs]} :: Tx-        coin s = TxOut 1000 s-        plain = "\x76\xa9\x14" <> B.replicate 20 7 <> "\x88\xac"-        fungible c n = withTokens c Nothing n-        nft c capability commitment = withTokens c (Just (capability, commitment)) 0-    it "lets tokens through as the inputs hold them" $ do-      tokenRules (tx [from 1] [fungible category 400, fungible category 600]) [coin (fungible category 1000)]-        `shouldBe` Right ()-      -- burnt: fewer out than in-      tokenRules (tx [from 1] [fungible category 10]) [coin (fungible category 1000)] `shouldBe` Right ()-      tokenRules (tx [from 1] [plain]) [coin plain] `shouldBe` Right ()-    it "refuses more fungible tokens out than in" $-      tokenRules (tx [from 1, from 2] [fungible category 2000]) [coin (fungible category 1000), coin plain]-        `shouldBe` Left (TokensUnbacked (concatMap (const "09") [1 .. 32 :: Int]))-    it "makes tokens of a new category at will, from an input that spends an output 0" $ do-      let genesisId = TxHash (doubleSHA256 ("genesis" :: ByteString))-          genesis =-            (tx [] [fungible newCategory 5000, nft newCategory 2 ""])-              { inputs = [TxIn (OutPoint genesisId 0) "" maxBound]-              } ::-              Tx-      tokenRules genesis [coin plain] `shouldBe` Right ()-      -- the same category from an input that spends an output 1 is not new-      let notNew = genesis {inputs = [TxIn (OutPoint genesisId 1) "" maxBound]} :: Tx-      tokenRules notNew [coin plain] `shouldSatisfy` either (const True) (const False)-    it "refuses tokens not written as tokens are" $-      tokenRules (tx [from 1] ["\xef\x01"]) [coin plain] `shouldBe` Left (BadTokens 0)-    it "keeps non-fungible tokens to what the inputs allow" $ do-      let keep = tx [from 1] [nft category 0 "a"]-      -- the same immutable token passes on; another commitment does not-      tokenRules keep [coin (nft category 0 "a")] `shouldBe` Right ()-      tokenRules keep [coin (nft category 0 "b")] `shouldSatisfy` either (const True) (const False)-      -- a mutable one becomes any one token, not two-      tokenRules keep [coin (nft category 1 "x")] `shouldBe` Right ()-      tokenRules (tx [from 1] [nft category 0 "a", nft category 0 "b"]) [coin (nft category 1 "x")]-        `shouldSatisfy` either (const True) (const False)-      -- a minting one makes any, and only a minting one makes one that mints-      tokenRules (tx [from 1] [nft category 0 "a", nft category 2 "b"]) [coin (nft category 2 "")]-        `shouldBe` Right ()-      tokenRules (tx [from 1] [nft category 2 "b"]) [coin (nft category 1 "")]-        `shouldSatisfy` either (const True) (const False)-+  -- What the store checks of a transaction is tested in haskoin-core,+  -- where the checks are ("Haskoin.Transaction.JudgeSpec"): here is what+  -- the store does with the answer.   describe "publishing" $ do     let tx = spending [output 1] 900     it "hands a transaction to every peer and answers at once, then asks for it" $@@ -297,5 +166,13 @@       let (ready, after) = due (at 30) (HashMap.fromList [(h 1, (at 30, []))])       ready `shouldBe` [h 1]       after `shouldBe` HashMap.empty+    it "moves a transaction on its schedule only once it was asked for" $ do+      let m = HashMap.fromList [(h 1, (at 10, [25])), (h 2, (at 10, []))]+          once = asked (at 10) (h 1) m+      -- the second, not asked for yet, is still due+      fst (due (at 10) once) `shouldBe` [h 2]+      HashMap.lookup (h 1) once `shouldBe` Just (at 35, [])+      -- at its last delay, it goes once asked for+      HashMap.lookup (h 2) (asked (at 10) (h 2) once) `shouldBe` Nothing     it "asks past the two minutes in which nodes give back what they took" $       sum askAgain `shouldSatisfy` (> 120)
test/Haskoin/Store/WebSpec.hs view
@@ -19,8 +19,7 @@     MaxHealth (..),     TimeHealth (..),   )-import Haskoin.Store.Database.Stalls (Stall (..), Writes (..), noStall)-import Haskoin.Store.Web (ailments, decodeTxBody, logIt, withDatabase)+import Haskoin.Store.Web (ailments, decodeTxBody, logIt) import Network.HTTP.Types (status200, status404, status500, status503) import Network.Wai (Request (..), defaultRequest, responseLBS) import Network.Wai.Internal (ResponseReceived (..))@@ -88,7 +87,10 @@       network = "btc",       version = "0",       time = 0,-      redis = Nothing+      redis = Nothing,+      database = Nothing,+      mempool = Nothing,+      warnings = []     }  spec :: Spec@@ -132,19 +134,6 @@           alone = behind {peers = CountHealth {count = 0, min = 1}} :: HealthCheck       ailments behind `shouldBe` "5 blocks behind the headers"       ailments alone `shouldBe` "5 blocks behind the headers, 0 peers"-  describe "the health check with the database" $ do-    let field k v = case v of-          A.Object o -> KeyMap.lookup k o-          _ -> Nothing-        db w = withDatabase noStall {writes = w, pending = 7, rate = 0} well-    it "is ok while writes flow or are only delayed" $ do-      field "ok" (db Flowing) `shouldBe` Just (A.Bool True)-      field "ok" (db Delayed) `shouldBe` Just (A.Bool True)-      (field "database" (db Delayed) >>= field "writes") `shouldBe` Just (A.String "delayed")-      (field "database" (db Delayed) >>= field "pending-compaction-bytes") `shouldBe` Just (A.Number 7)-    it "is not ok when writes are stopped" $ do-      field "ok" (db Stopped) `shouldBe` Just (A.Bool False)-      (field "database" (db Stopped) >>= field "ok") `shouldBe` Just (A.Bool False)   describe "decodeTxBody" $ do     -- The id is the double SHA-256 of the bytes of plainTxHex, reversed. It     -- was computed outside this library. The witness is not part of the id,
test/Haskoin/Store/XPub/IndexerSpec.hs view
@@ -4,8 +4,8 @@ module Haskoin.Store.XPub.IndexerSpec (spec) where  import Control.Concurrent (threadDelay)-import Control.Concurrent.Async (async, forConcurrently, wait, withAsync)-import Control.Concurrent.MVar (newEmptyMVar, putMVar, readMVar)+import Control.Concurrent.Async (async, cancel, forConcurrently, wait, withAsync)+import Control.Concurrent.MVar (newEmptyMVar, putMVar, readMVar, takeMVar) import Control.Monad (forM_, replicateM, void, when) import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef, writeIORef) import Data.List (sort)@@ -143,6 +143,23 @@       void (runNext t.indexer >> runNext t.indexer >> runNext t.indexer >> runNext t.indexer)       (.median) <$> indexerStats t.indexer `shouldReturn` 200 +    it "undoes the reservation of a request that is killed while it takes the lock" $ do+      t <- testbed settings+      entered <- newEmptyMVar+      gate <- newEmptyMVar+      writeIORef t.acquiring (putMVar entered () >> takeMVar gate)+      a <- async (request t.indexer 'x' [1])+      takeMVar entered+      cancel a+      writeIORef t.acquiring (return ())+      -- the lock, which it might have taken, is let go+      readIORef t.locks `shouldReturn` ["release x"]+      -- nothing of the request is left: upkeep for the key is queued and+      -- run, where a job left reserved would have taken it and never run+      upkeep t.indexer 'x' [2]+      runNext t.indexer `shouldReturn` True+      readIORef t.ran `shouldReturn` [('x', [2])]+     it "takes nothing for a key that another store holds, and gives the payload of upkeep back" $ do       t <- testbed settings       writeIORef t.other (Just 4000000)@@ -316,6 +333,8 @@     locks :: IORef [String],     -- | what letting go of a lock does after it is noted     onRelease :: IORef (IO ()),+    -- | what taking a lock does before it answers+    acquiring :: IORef (IO ()),     -- | when another store holds every lock, until when     other :: IORef (Maybe Int),     ready' :: IORef Bool,@@ -336,6 +355,7 @@   size <- newIORef Nothing   locks <- newIORef []   onRelease <- newIORef (return ())+  acquiring <- newIORef (return ())   other <- newIORef Nothing   ready' <- newIORef True   abandoned <- newIORef []@@ -347,7 +367,7 @@       lock =         Lock           { acquire = \k _ ->-              readIORef other >>= \case+              (readIORef acquiring >>= id) >> readIORef other >>= \case                 Just t -> return (Held t)                 Nothing -> note locks ("take " <> [k]) >> return Took,             renew = \ks -> note renewed (sort ks) >> return 0,@@ -383,6 +403,7 @@         size,         locks,         onRelease,+        acquiring,         other,         ready',         abandoned,
− test/Haskoin/StoreSpec.hs
@@ -1,366 +0,0 @@-{-# LANGUAGE RecordWildCards #-}--module Haskoin.StoreSpec (spec) where--import Conduit-import Control.Concurrent (threadDelay)-import Control.Concurrent.Async (withAsync)-import Control.Concurrent.STM (TVar, atomically, modifyTVar', newTVarIO, readTVarIO)-import Control.Monad-import Data.ByteString (ByteString)-import Data.ByteString qualified as B-import Data.ByteString.Base64-import Data.Either-import Data.HashMap.Strict qualified as HashMap-import Data.Maybe-import Data.Serialize-import Data.Time.Clock.POSIX-import Data.Word-import GHC.Stats (GCDetails (..), RTSStats (..), getRTSStats, getRTSStatsEnabled)-import Haskoin-import Haskoin.Node-import Haskoin.Store-import Haskoin.Store.Database.Query qualified as Q-import Haskoin.Store.Integration.Temp (withSystemTempDirectory)-import Haskoin.Store.TestBlocks (nextBlock)-import NQE-import Network.Socket-import System.Mem (performMajorGC)-import System.Random-import System.Timeout (timeout)-import Test.Hspec--data TestStore = TestStore-  { testStoreDB :: !DatabaseReader,-    testStoreBlockStore :: !BlockStore,-    testStoreChain :: !Chain,-    testStoreEvents :: !(Inbox StoreEvent),-    -- | How many blocks each getdata sent to the mock peer asked for, oldest first.-    testStoreBlockRequests :: !(TVar [Int])-  }--spec :: Spec-spec = do-  describe "Download" $ do-    it "gets 8 blocks" $-      withTestStore bchRegTest "eight-blocks" $ \TestStore {..} -> do-        bs <- replicateM 8 . receiveMatch testStoreEvents $ \case-          StoreBestBlock b -> Just b-          _ -> Nothing-        let bestHash = last bs-        bestNodeM <- chainGetBlock testStoreChain bestHash-        bestNodeM `shouldSatisfy` isJust-        let bestNode = fromJust bestNodeM-            bestHeight = bestNode.height-        bestHeight `shouldBe` 8-    it "get a block and its transactions" $-      withTestStore bchRegTest "get-block-txs" $ \TestStore {..} ->-        do-          let h1 = "5369ef2386c72acdf513ffd80aeba2a1774e2f004d120761e54a8bf614173f3e"-              get_the_block h =-                receive testStoreEvents >>= \case-                  StoreBestBlock b-                    | h <= 1 -> return b-                    | otherwise ->-                        get_the_block ((h :: Int) - 1)-                  _ -> get_the_block h-          bh <- get_the_block 15-          m <- Q.getBlock testStoreDB bh-          let bd = fromMaybe (error "Could not get block") m-          t1 <- Q.getTxData testStoreDB h1-          bd.height `shouldBe` 15-          length bd.txs `shouldBe` 1-          listToMaybe bd.txs `shouldBe` Just h1-          fmap (txHash . (.tx)) t1 `shouldBe` Just h1-    it "downloads 80 blocks with a request for 64 and one for the remaining 16" $-      withTestStore bchRegTest "block-window" $ \TestStore {..} -> do-        bs <- replicateM 80 . receiveMatch testStoreEvents $ \case-          StoreBestBlock b -> Just b-          _ -> Nothing-        bestNodeM <- chainGetBlock testStoreChain (last bs)-        fmap (.height) bestNodeM `shouldBe` Just 80-        readTVarIO testStoreBlockRequests `shouldReturn` [64, 16]-    it "asks another peer for the blocks that the first one does not deliver" $-      -- The first peer to connect sends headers and never a block; the-      -- second connects a second later and delivers. With a stall of one-      -- second the store has its blocks in a few; waiting out the timeout-      -- of the first peer, as it used to, would take a minute.-      withStalledStore bchRegTest "stalled-peer" $ \TestStore {..} -> do-        got <- timeout 20000000 . replicateM 8 . receiveMatch testStoreEvents $ \case-          StoreBestBlock b -> Just b-          _ -> Nothing-        fmap length got `shouldBe` Just 8-        -- both were asked: the silent one first, then the one that delivers-        length <$> readTVarIO testStoreBlockRequests `shouldReturn` 2--  describe "Memory" $-    it "keeps the heap flat while syncing" $ do-      enabled <- getRTSStatsEnabled-      unless enabled $ pendingWith "run with +RTS -T to measure the heap"-      -- Each block passes messages through the peer, node and store loops.-      -- When forever went through a dictionary, each of six loops kept 33 to-      -- 107 bytes per message, a few hundred bytes per block in all: over-      -- the 5000 blocks measured, megabytes. The heap normally grows by about-      -- 330 kB here, and a leak of 500 bytes per block fails the test. The-      -- length is a multiple of 2000, so the last headers message the mock-      -- peer sends is empty, which haskoin-node before 2.1.2 did not handle.-      let blocks = chainOf 6000-      withTestStoreBlocks blocks bchRegTest "heap" $ \TestStore {..} -> do-        let wait_for height =-              receive testStoreEvents >>= \case-                StoreBestBlock b ->-                  chainGetBlock testStoreChain b >>= \case-                    Just n | n.height >= height -> return ()-                    _ -> wait_for height-                _ -> wait_for height-            live = do-              performMajorGC-              (.gc.gcdetails_live_bytes) <$> getRTSStats-        wait_for 1000-        live_before <- live-        wait_for 6000-        live_after <- live-        let growth = fromIntegral live_after - fromIntegral live_before :: Integer-        putStrLn $ "heap growth over 5000 blocks: " <> show growth <> " bytes"-        growth `shouldSatisfy` (< 1024 * 1024)--withTestStore ::-  Network ->-  String ->-  (TestStore -> IO a) ->-  IO a-withTestStore = withTestStoreBlocks allBlocks---- | Like 'withTestStore', with the mock peer serving these blocks.-withTestStoreBlocks ::-  [Block] ->-  Network ->-  String ->-  (TestStore -> IO a) ->-  IO a-withTestStoreBlocks blocks = withTestStoreConfig (dummyPeerConnect 0 mockPeerReact blocks) id---- | A store with two mock peers: one that connects at once and never sends--- a block, and one that connects a second later and behaves. The store--- passes over a peer that delivers nothing for a second.-withStalledStore ::-  Network ->-  String ->-  (TestStore -> IO a) ->-  IO a-withStalledStore = withTestStoreConfig peers $ \cfg ->-  cfg {initPeers = ["127.0.0.1:18444", "127.0.0.1:18445"], blockStall = 1}-  where-    peers requests net ad sa = case sa of-      SockAddrInet 18444 _ -> dummyPeerConnect 0 silent allBlocks requests net ad sa-      _ -> dummyPeerConnect 1000000 mockPeerReact allBlocks requests net ad sa-    silent _ (MGetData _) = []-    silent blocks msg = mockPeerReact blocks msg---- | A store whose peers are made by a function, with its configuration--- changed by another.-withTestStoreConfig ::-  (TVar [Int] -> Network -> NetworkAddress -> SockAddr -> WithConnection) ->-  (StoreConfig -> StoreConfig) ->-  Network ->-  String ->-  (TestStore -> IO a) ->-  IO a-withTestStoreConfig peers change net t f =-  withSystemTempDirectory ("haskoin-store-test-" <> t <> "-") $ \w -> do-    requests <- newTVarIO []-    let ad =-          NetworkAddress-            nodeNetwork-            (sockToHostAddress (SockAddrInet 0 0))-        cfg =-          change-            StoreConfig-              { maxPeers = 20,-                -- the mock peer, by name: since haskoin-node 2.5 the seed of-                -- a regtest network is not an address that discovery takes-                initPeers = ["127.0.0.1:18444"],-                discover = False,-                db = w,-                net = net,-                redis = Nothing,-                gap = gap,-                initGap = 20,-                redisMaxXPubs = 10000,-                xpubs = defaultXPubConfig,-                blockWindow = 64,-                mempoolTimeout = 14,-                peerTimeout = 60,-                blockStall = 10,-                blockPing = 5,-                maxPeerLife = 48 * 3600,-                connect = peers requests net ad,-                stats = Nothing,-                bloom = True,-                maxOpenFiles = Nothing,-                writeBufferSize = Nothing,-                maxWalSize = Nothing,-                backgroundJobs = Nothing,-                blockCache = Nothing,-                logger = Logger {level = LevelError, source = "", push = \_ -> return ()}-              }-    withStore cfg $ \store ->-      withSubscription store.pub $ \sub ->-        f-          TestStore-            { testStoreDB = store.db,-              testStoreBlockStore = store.block,-              testStoreChain = store.chain,-              testStoreEvents = sub,-              testStoreBlockRequests = requests-            }--gap :: Word32-gap = 32---- | The 15 canned blocks followed by 65 mined on top of them: more than one--- 64-block window, so that a download needs a second request.-allBlocks :: [Block]-allBlocks = chainOf 80---- | The canned blocks followed by blocks mined on top of them, this many in--- all.-chainOf :: Int -> [Block]-chainOf n = take n (cannedBlocks <> mined (length cannedBlocks) (last cannedBlocks))-  where-    mined height parent = block : mined (height + 1) block-      where-        (block, _) = nextBlock bchRegTest (fromIntegral height) parent.header []--cannedBlocks :: [Block]-cannedBlocks =-  fromRight (error "Could not decode blocks") $-    runGet f (decodeBase64Lenient cannedBlocksBase64)-  where-    f = mapM (const get) [(1 :: Int) .. 15]--cannedBlocksBase64 :: ByteString-cannedBlocksBase64 =-  "AAAAIAYibkYRGgtZyq8SYEPrW78ow086XjMqH8eytzzxiJEPakRJalmWTFwdvzNuH8fHLZEjn+4N\-  \FNMANdB7ez2M4a3TFbNe//9/IAMAAAABAgAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\-  \AAAAAP////8MUQEBCC9FQjMyLjAv/////wEA8gUqAQAAACMhAwTspkCjMezKs47BPpafou1jjsHf\-  \1OHjgkqxnwEYkK9zrAAAAAAAAAAge0RDjOrqVayGUoQsbNTJcTXUM+psaHpmuiFy6hwo2T8yn0CL\-  \7WDJw9hxl1kf5c4JySq3WJF8OPsoguzF7mXH3tQVs17//38gAAAAAAECAAAAAQAAAAAAAAAAAAAA\-  \AAAAAAAAAAAAAAAAAAAAAAAAAAAA/////wxSAQEIL0VCMzIuMC//////AQDyBSoBAAAAIyEDBOym\-  \QKMx7MqzjsE+lp+i7WOOwd/U4eOCSrGfARiQr3OsAAAAAAAAACCKlhzDaFkrsmO2FhmeQS9ONS8D\-  \QsU4H97yNxVhyIXYJuG3a9cyQpdeETjCQ6JybgkwI0OOfa4eYazf7WWI5UAk1BWzXv//fyAEAAAA\-  \AQIAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////DFMBAQgvRUIzMi4wL///\-  \//8BAPIFKgEAAAAjIQME7KZAozHsyrOOwT6Wn6LtY47B39Th44JKsZ8BGJCvc6wAAAAAAAAAIP/S\-  \XiIJZqvUyBY90z72dv6+/GG50R3vc3UAK8AHP89wChmkVP6nefjOt+sNyhbKk9zia47F08oTNtC0\-  \OG1zyuXVFbNe//9/IAEAAAABAgAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//\-  \//8MVAEBCC9FQjMyLjAv/////wEA8gUqAQAAACMhAwTspkCjMezKs47BPpafou1jjsHf1OHjgkqx\-  \nwEYkK9zrAAAAAAAAAAgeQtE1s3YV/uS2jUouo3S9DJAVf5OGk+Nyx+No1mPH24b5JCkr/tSP0E/\-  \NYVkVcE0ZHxbO/fu5wOd+8VolvPQYtUVs17//38gAAAAAAECAAAAAQAAAAAAAAAAAAAAAAAAAAAA\-  \AAAAAAAAAAAAAAAAAAAA/////wxVAQEIL0VCMzIuMC//////AQDyBSoBAAAAIyEDBOymQKMx7Mqz\-  \jsE+lp+i7WOOwd/U4eOCSrGfARiQr3OsAAAAAAAAACBgtvss8QiesqxISt/1RJkykhGcLe2eCY49\-  \b6CSNe2UMOVYGZ++uRCKvaJ2+jo7akr7XsdXCYSAmuw6DwSO8lvF1RWzXv//fyAAAAAAAQIAAAAB\-  \AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////DFYBAQgvRUIzMi4wL/////8BAPIF\-  \KgEAAAAjIQME7KZAozHsyrOOwT6Wn6LtY47B39Th44JKsZ8BGJCvc6wAAAAAAAAAID92Jp1mAeny\-  \N0dMCWoMyTiBk3sWT5VxzI75ycVflYkMCnXLFhuwrMdBbZmXJinAJBUpN7BV0XvlM2PRmb7HQebV\-  \FbNe//9/IAEAAAABAgAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////8MVwEB\-  \CC9FQjMyLjAv/////wEA8gUqAQAAACMhAwTspkCjMezKs47BPpafou1jjsHf1OHjgkqxnwEYkK9z\-  \rAAAAAAAAAAgxEgEkhjf5p+ql8dETmdSCdCdk+vB26+V2SGLEuE1+kA1acGCdQoQBqec8P/knItJ\-  \M213OIrDX6U5IB6fgIas7dYVs17//38gAQAAAAECAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\-  \AAAAAAAAAAAA/////wxYAQEIL0VCMzIuMC//////AQDyBSoBAAAAIyEDBOymQKMx7MqzjsE+lp+i\-  \7WOOwd/U4eOCSrGfARiQr3OsAAAAAAAAACDku4EB5X7htWpHg+aMzzW1AABttpNQTew7K3Aj2fh/\-  \OuOCPhJApmcXq5o42tkksFSuhYvcfqaSHCuuFgjo6ohz1hWzXv//fyAAAAAAAQIAAAABAAAAAAAA\-  \AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////DFkBAQgvRUIzMi4wL/////8BAPIFKgEAAAAj\-  \IQME7KZAozHsyrOOwT6Wn6LtY47B39Th44JKsZ8BGJCvc6wAAAAAAAAAIKWpAhOWbkEN9vWf1uCu\-  \eXtVOZIE9V1OE87iC+H9atBRtY4LPgaWUSVMNh9SeZK1NViIFMklbjsfqYiC4eA/VuLWFbNe//9/\-  \IAAAAAABAgAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////8MWgEBCC9FQjMy\-  \LjAv/////wEA8gUqAQAAACMhAwTspkCjMezKs47BPpafou1jjsHf1OHjgkqxnwEYkK9zrAAAAAAA\-  \AAAgZ4T81y9DXuJanHjsr8cY5HM6ZvbETRj5dvpViqc1yH0oN9OOruaO5mjdITJwweVCzjSQ5Wsl\-  \vSOKaKvEX5j9l9YVs17//38gAAAAAAECAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\-  \AAAA/////wxbAQEIL0VCMzIuMC//////AQDyBSoBAAAAIyEDBOymQKMx7MqzjsE+lp+i7WOOwd/U\-  \4eOCSrGfARiQr3OsAAAAAAAAACCV3J2A3qneSJ7Q/RuF8OPd8O1izIXvKElR/xg/+InGNEafu0Ul\-  \3VYJR93zbAQuns9hUfAhA8MTBPk8bbDabDfo1hWzXv//fyAAAAAAAQIAAAABAAAAAAAAAAAAAAAA\-  \AAAAAAAAAAAAAAAAAAAAAAAAAAD/////DFwBAQgvRUIzMi4wL/////8BAPIFKgEAAAAjIQME7KZA\-  \ozHsyrOOwT6Wn6LtY47B39Th44JKsZ8BGJCvc6wAAAAAAAAAINcGedRly1+dXQrcCaZRXTIG2GHV\-  \0tPCGpZtFnvfhuhSx8d3Azdv/MXRJgsb56qqmD5gsXiWUdi7ia7wsBZVylvWFbNe//9/IAEAAAAB\-  \AgAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP////8MXQEBCC9FQjMyLjAv////\-  \/wEA8gUqAQAAACMhAwTspkCjMezKs47BPpafou1jjsHf1OHjgkqxnwEYkK9zrAAAAAAAAAAgDxu3\-  \+7op0n6+s1ZJTqqzjHWH84YorH8hTbLiuYGgNyWIkhaj0zR7Vc+fSRm4UYUaPsefRhq3fUt8glyS\-  \D8P/5tcVs17//38gAwAAAAECAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////\-  \/wxeAQEIL0VCMzIuMC//////AQDyBSoBAAAAIyEDBOymQKMx7MqzjsE+lp+i7WOOwd/U4eOCSrGf\-  \ARiQr3OsAAAAAAAAACDYVJqsPyQ8MwR+LRafufm1LB97SQoyFJdvKVohBvNyfD4/FxT2i0rlYQcS\-  \TQAvTnehousK2P8T9c0qx4Yj72lT1xWzXv//fyAAAAAAAQIAAAABAAAAAAAAAAAAAAAAAAAAAAAA\-  \AAAAAAAAAAAAAAAAAAD/////DF8BAQgvRUIzMi4wL/////8BAPIFKgEAAAAjIQME7KZAozHsyrOO\-  \wT6Wn6LtY47B39Th44JKsZ8BGJCvc6wAAAAA"---- | A mock peer that waits so many microseconds before it says anything,--- and then answers each message with a function of the blocks that it has.-dummyPeerConnect ::-  Int ->-  ([Block] -> Message -> [Message]) ->-  [Block] ->-  TVar [Int] ->-  Network ->-  NetworkAddress ->-  SockAddr ->-  WithConnection-dummyPeerConnect wait react blocks requests net ad sa f = do-  r <- newInbox-  s <- newInbox-  let s' = inboxToMailbox s-  withAsync (go r s') $ \_ -> do-    let o = conduitMailbox r-        i = repeatMC (receive s)-    f (Conduits i o) :: IO ()-  where-    go :: Inbox ByteString -> Mailbox ByteString -> IO ()-    go r s = do-      threadDelay wait-      nonce <- randomIO-      now <- round <$> getPOSIXTime-      let rmt = NetworkAddress 0 (sockToHostAddress sa)-          ver = buildVersion net nonce (fromIntegral (length blocks)) ad rmt now-      runPut (putMessage net (MVersion ver)) `send` s-      runConduit $-        repeatMC (receive r)-          .| inc-          .| iterMC (recordBlockRequest requests)-          .| concatMapC (react blocks)-          .| outc-          .| conduitMailbox s-    outc = mapMC $ \msg' -> return $ runPut (putMessage net msg')-    inc = forever $ do-      x <- takeCE 24 .| foldC-      case decode x of-        Left _ ->-          error "Dummy peer not decode message header"-        Right (MessageHeader _ _ len _) -> do-          y <- takeCE (fromIntegral len) .| foldC-          case runGet (getMessage net) $ x `B.append` y of-            Right msg' -> yield msg'-            Left e ->-              error $-                "Dummy peer could not decode payload: " <> show e---- | Note how many blocks a getdata asks for.-recordBlockRequest :: TVar [Int] -> Message -> IO ()-recordBlockRequest requests (MGetData (GetData ivs)) =-  atomically $ modifyTVar' requests (<> [length [() | InvVector InvBlock _ <- ivs]])-recordBlockRequest _ _ = return ()--mockPeerReact :: [Block] -> Message -> [Message]-mockPeerReact _ (MPing (Ping n)) = [MPong (Pong n)]-mockPeerReact _ (MVersion _) = [MVerAck]-mockPeerReact blocks (MGetHeaders (GetHeaders _ locator _)) = [MHeaders (Headers hs')]-  where-    f b = (b.header, VarInt $ fromIntegral $ length b.txs)-    -- Up to 2000 headers after the first block of the locator that the-    -- peer has, like a real peer; from the start if it has none of them.-    heights = HashMap.fromList (zip (map (headerHash . (.header)) blocks) [1 :: Int ..])-    start = fromMaybe 0 (listToMaybe (mapMaybe (`HashMap.lookup` heights) locator))-    hs' = map f (take 2000 (drop start blocks))-mockPeerReact blocks (MGetData (GetData ivs)) = mapMaybe f ivs-  where-    f (InvVector InvBlock h) = MBlock <$> HashMap.lookup (BlockHash h) byHash-    f _ = Nothing-    byHash = HashMap.fromList [(headerHash b.header, b) | b <- blocks]-mockPeerReact _ _ = []