haskoin-store-data 3.0.1 → 4.0.0
raw patch · 9 files changed
+1236/−71 lines, 9 filesdep +temporarydep ~haskoin-corePVP ok
version bump matches the API change (PVP)
Dependencies added: temporary
Dependency ranges changed: haskoin-core
API changes (from Hackage documentation)
+ Haskoin.Store.Data: DatabaseHealth :: !DatabaseWrites -> !Word64 -> !Word64 -> !Word32 -> !Word32 -> !Word32 -> !Word64 -> !Word64 -> !Word64 -> DatabaseHealth
+ Haskoin.Store.Data: MempoolHealth :: !Word32 -> !Bool -> !Word32 -> !Word32 -> !MempoolSync -> MempoolHealth
+ Haskoin.Store.Data: MempoolSynced :: MempoolSync
+ Haskoin.Store.Data: MempoolSyncing :: MempoolSync
+ Haskoin.Store.Data: MempoolUnknown :: MempoolSync
+ Haskoin.Store.Data: TokenBalance :: !Address -> !TxHash -> !Word64 -> !Word64 -> !Word64 -> !Word64 -> !Word64 -> !Word64 -> TokenBalance
+ Haskoin.Store.Data: WritesDelayed :: DatabaseWrites
+ Haskoin.Store.Data: WritesFlowing :: DatabaseWrites
+ Haskoin.Store.Data: WritesStopped :: DatabaseWrites
+ Haskoin.Store.Data: [category] :: TokenBalance -> !TxHash
+ Haskoin.Store.Data: [compactions] :: DatabaseHealth -> !Word32
+ Haskoin.Store.Data: [confirmedTokens] :: TokenBalance -> !Word64
+ Haskoin.Store.Data: [database] :: HealthCheck -> !Maybe DatabaseHealth
+ Haskoin.Store.Data: [delayedWriteRate] :: DatabaseHealth -> !Word64
+ Haskoin.Store.Data: [dirty] :: MempoolHealth -> !Bool
+ Haskoin.Store.Data: [errors] :: DatabaseHealth -> !Word64
+ Haskoin.Store.Data: [flushes] :: DatabaseHealth -> !Word32
+ Haskoin.Store.Data: [held] :: MempoolHealth -> !Word32
+ Haskoin.Store.Data: [known] :: MempoolHealth -> !Word32
+ Haskoin.Store.Data: [liveData] :: DatabaseHealth -> !Word64
+ Haskoin.Store.Data: [mempool] :: HealthCheck -> !Maybe MempoolHealth
+ Haskoin.Store.Data: [memtables] :: DatabaseHealth -> !Word32
+ Haskoin.Store.Data: [nfts] :: TokenBalance -> !Word64
+ Haskoin.Store.Data: [pendingCompaction] :: DatabaseHealth -> !Word64
+ Haskoin.Store.Data: [receivedTokens] :: TokenBalance -> !Word64
+ Haskoin.Store.Data: [sources] :: MempoolHealth -> !Word32
+ Haskoin.Store.Data: [sync] :: MempoolHealth -> !MempoolSync
+ Haskoin.Store.Data: [tokenTxs] :: TokenBalance -> !Word64
+ Haskoin.Store.Data: [tokenUtxo] :: TokenBalance -> !Word64
+ Haskoin.Store.Data: [unconfirmedTokens] :: TokenBalance -> !Word64
+ Haskoin.Store.Data: [warnings] :: HealthCheck -> ![Text]
+ Haskoin.Store.Data: [writes] :: DatabaseHealth -> !DatabaseWrites
+ Haskoin.Store.Data: blocksText :: BlockHealth -> Text
+ Haskoin.Store.Data: data DatabaseHealth
+ Haskoin.Store.Data: data DatabaseWrites
+ Haskoin.Store.Data: data MempoolHealth
+ Haskoin.Store.Data: data MempoolSync
+ Haskoin.Store.Data: data TokenBalance
+ Haskoin.Store.Data: databaseText :: DatabaseHealth -> Text
+ Haskoin.Store.Data: healthText :: HealthCheck -> Text
+ Haskoin.Store.Data: instance Control.DeepSeq.NFData Haskoin.Store.Data.DatabaseHealth
+ Haskoin.Store.Data: instance Control.DeepSeq.NFData Haskoin.Store.Data.DatabaseWrites
+ Haskoin.Store.Data: instance Control.DeepSeq.NFData Haskoin.Store.Data.MempoolHealth
+ Haskoin.Store.Data: instance Control.DeepSeq.NFData Haskoin.Store.Data.MempoolSync
+ Haskoin.Store.Data: instance Control.DeepSeq.NFData Haskoin.Store.Data.TokenBalance
+ Haskoin.Store.Data: instance Data.Aeson.Types.FromJSON.FromJSON Haskoin.Store.Data.DatabaseHealth
+ Haskoin.Store.Data: instance Data.Aeson.Types.FromJSON.FromJSON Haskoin.Store.Data.DatabaseWrites
+ Haskoin.Store.Data: instance Data.Aeson.Types.FromJSON.FromJSON Haskoin.Store.Data.MempoolHealth
+ Haskoin.Store.Data: instance Data.Aeson.Types.FromJSON.FromJSON Haskoin.Store.Data.MempoolSync
+ Haskoin.Store.Data: instance Data.Aeson.Types.ToJSON.ToJSON Haskoin.Store.Data.DatabaseHealth
+ Haskoin.Store.Data: instance Data.Aeson.Types.ToJSON.ToJSON Haskoin.Store.Data.DatabaseWrites
+ Haskoin.Store.Data: instance Data.Aeson.Types.ToJSON.ToJSON Haskoin.Store.Data.MempoolHealth
+ Haskoin.Store.Data: instance Data.Aeson.Types.ToJSON.ToJSON Haskoin.Store.Data.MempoolSync
+ Haskoin.Store.Data: instance Data.Binary.Class.Binary Haskoin.Store.Data.TokenBalance
+ Haskoin.Store.Data: instance Data.Bytes.Serial.Serial Haskoin.Store.Data.TokenBalance
+ Haskoin.Store.Data: instance Data.Hashable.Class.Hashable Haskoin.Store.Data.TokenBalance
+ Haskoin.Store.Data: instance Data.Serialize.Serialize Haskoin.Store.Data.TokenBalance
+ Haskoin.Store.Data: instance GHC.Classes.Eq Haskoin.Store.Data.DatabaseHealth
+ Haskoin.Store.Data: instance GHC.Classes.Eq Haskoin.Store.Data.DatabaseWrites
+ Haskoin.Store.Data: instance GHC.Classes.Eq Haskoin.Store.Data.MempoolHealth
+ Haskoin.Store.Data: instance GHC.Classes.Eq Haskoin.Store.Data.MempoolSync
+ Haskoin.Store.Data: instance GHC.Classes.Eq Haskoin.Store.Data.TokenBalance
+ Haskoin.Store.Data: instance GHC.Classes.Ord Haskoin.Store.Data.DatabaseWrites
+ Haskoin.Store.Data: instance GHC.Classes.Ord Haskoin.Store.Data.MempoolSync
+ Haskoin.Store.Data: instance GHC.Classes.Ord Haskoin.Store.Data.TokenBalance
+ Haskoin.Store.Data: instance GHC.Internal.Enum.Bounded Haskoin.Store.Data.DatabaseWrites
+ Haskoin.Store.Data: instance GHC.Internal.Enum.Bounded Haskoin.Store.Data.MempoolSync
+ Haskoin.Store.Data: instance GHC.Internal.Enum.Enum Haskoin.Store.Data.DatabaseWrites
+ Haskoin.Store.Data: instance GHC.Internal.Enum.Enum Haskoin.Store.Data.MempoolSync
+ Haskoin.Store.Data: instance GHC.Internal.Generics.Generic Haskoin.Store.Data.DatabaseHealth
+ Haskoin.Store.Data: instance GHC.Internal.Generics.Generic Haskoin.Store.Data.DatabaseWrites
+ Haskoin.Store.Data: instance GHC.Internal.Generics.Generic Haskoin.Store.Data.MempoolHealth
+ Haskoin.Store.Data: instance GHC.Internal.Generics.Generic Haskoin.Store.Data.MempoolSync
+ Haskoin.Store.Data: instance GHC.Internal.Generics.Generic Haskoin.Store.Data.TokenBalance
+ Haskoin.Store.Data: instance GHC.Internal.Read.Read Haskoin.Store.Data.TokenBalance
+ Haskoin.Store.Data: instance GHC.Internal.Show.Show Haskoin.Store.Data.DatabaseHealth
+ Haskoin.Store.Data: instance GHC.Internal.Show.Show Haskoin.Store.Data.DatabaseWrites
+ Haskoin.Store.Data: instance GHC.Internal.Show.Show Haskoin.Store.Data.MempoolHealth
+ Haskoin.Store.Data: instance GHC.Internal.Show.Show Haskoin.Store.Data.MempoolSync
+ Haskoin.Store.Data: instance GHC.Internal.Show.Show Haskoin.Store.Data.TokenBalance
+ Haskoin.Store.Data: instance Haskoin.Store.Data.Healthy Haskoin.Store.Data.DatabaseHealth
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Store.Data.TokenBalance
+ Haskoin.Store.Data: lastBlockText :: TimeHealth -> Text
+ Haskoin.Store.Data: lastTxText :: TimeHealth -> Text
+ Haskoin.Store.Data: mempoolSyncWord :: MempoolSync -> Text
+ Haskoin.Store.Data: mempoolText :: MempoolHealth -> Text
+ Haskoin.Store.Data: peersText :: CountHealth -> Text
+ Haskoin.Store.Data: pendingTxsText :: MaxHealth -> Text
+ Haskoin.Store.Data: redisText :: Bool -> Text
+ Haskoin.Store.Data: scriptTokens :: Network -> ByteString -> Maybe TokenData
+ Haskoin.Store.Data: zeroTokenBalance :: Address -> TxHash -> TokenBalance
+ Haskoin.Store.WebClient: GetAddrTokens :: Address -> GetAddrTokens
+ Haskoin.Store.WebClient: GetTokenHolders :: !TxHash -> !Maybe LimitParam -> !OffsetParam -> GetTokenHolders
+ Haskoin.Store.WebClient: GetTokenTxs :: !TxHash -> !LimitsParam -> GetTokenTxs
+ Haskoin.Store.WebClient: GetTokenUnspent :: !TxHash -> !LimitsParam -> GetTokenUnspent
+ Haskoin.Store.WebClient: [socket] :: ApiConfig -> !Maybe FilePath
+ Haskoin.Store.WebClient: data GetTokenHolders
+ Haskoin.Store.WebClient: data GetTokenTxs
+ Haskoin.Store.WebClient: data GetTokenUnspent
+ Haskoin.Store.WebClient: newtype GetAddrTokens
+ Haskoin.Store.WebCommon: GetAddrTokens :: Address -> GetAddrTokens
+ Haskoin.Store.WebCommon: GetTokenHolders :: !TxHash -> !Maybe LimitParam -> !OffsetParam -> GetTokenHolders
+ Haskoin.Store.WebCommon: GetTokenTxs :: !TxHash -> !LimitsParam -> GetTokenTxs
+ Haskoin.Store.WebCommon: GetTokenUnspent :: !TxHash -> !LimitsParam -> GetTokenUnspent
+ Haskoin.Store.WebCommon: data GetTokenHolders
+ Haskoin.Store.WebCommon: data GetTokenTxs
+ Haskoin.Store.WebCommon: data GetTokenUnspent
+ Haskoin.Store.WebCommon: instance Haskoin.Store.WebCommon.ApiResource Haskoin.Store.WebCommon.GetAddrTokens (Haskoin.Store.Data.SerialList Haskoin.Store.Data.TokenBalance)
+ Haskoin.Store.WebCommon: instance Haskoin.Store.WebCommon.ApiResource Haskoin.Store.WebCommon.GetTokenHolders (Haskoin.Store.Data.SerialList Haskoin.Store.Data.TokenBalance)
+ Haskoin.Store.WebCommon: instance Haskoin.Store.WebCommon.ApiResource Haskoin.Store.WebCommon.GetTokenTxs (Haskoin.Store.Data.SerialList Haskoin.Store.Data.TxRef)
+ Haskoin.Store.WebCommon: instance Haskoin.Store.WebCommon.ApiResource Haskoin.Store.WebCommon.GetTokenUnspent (Haskoin.Store.Data.SerialList Haskoin.Store.Data.Unspent)
+ Haskoin.Store.WebCommon: instance Haskoin.Store.WebCommon.ApiResponse Haskoin.Store.Data.TokenBalance
+ Haskoin.Store.WebCommon: newtype GetAddrTokens
- Haskoin.Store.Data: HealthCheck :: !BlockHealth -> !TimeHealth -> !TimeHealth -> !MaxHealth -> !CountHealth -> !String -> !String -> !Word64 -> !Maybe Bool -> HealthCheck
+ Haskoin.Store.Data: HealthCheck :: !BlockHealth -> !TimeHealth -> !TimeHealth -> !MaxHealth -> !CountHealth -> !String -> !String -> !Word64 -> !Maybe Bool -> !Maybe DatabaseHealth -> !Maybe MempoolHealth -> ![Text] -> HealthCheck
- Haskoin.Store.WebClient: ApiConfig :: !Network -> !String -> ApiConfig
+ Haskoin.Store.WebClient: ApiConfig :: !Network -> !String -> !Maybe FilePath -> ApiConfig
Files
- CHANGELOG.md +107/−0
- README.md +75/−0
- haskoin-store-data.cabal +4/−3
- src/Haskoin/Store/Data.hs +681/−25
- src/Haskoin/Store/WebClient.hs +49/−8
- src/Haskoin/Store/WebCommon.hs +47/−0
- test/Haskoin/Store/DataSpec.hs +199/−8
- test/Haskoin/Store/Gen.hs +38/−0
- test/Haskoin/Store/RobustSpec.hs +36/−27
CHANGELOG.md view
@@ -4,6 +4,113 @@ 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]++## [4.0.0] - 2026-11-25++The types and requests of the tokens of Bitcoin Cash (CashTokens), for+haskoin-store 2.0.0, on haskoin-core 3.0.++This breaks code that builds a `MempoolHealth` or a `HealthCheck` field+by field or by position: each has one field more.++### Added++- **Tokens of Bitcoin Cash (CashTokens).** `scriptTokens` reads the tokens+ that the script field of an output holds, on the Bitcoin Cash networks.+ The JSON of `StoreOutput`, `StoreInput` and `Unspent` has a `token` field+ there, `null` for an output without tokens; on Bitcoin the JSON is as it+ was. The types themselves are unchanged, with the same binary encoding:+ the tokens are read from the script, which they carry already.+- `TokenBalance`, the tokens of one category that an address holds (amounts,+ non-fungible tokens, unspent outputs, transactions, amount received), with+ `zeroTokenBalance`.+- The requests `GetAddrTokens`, `GetTokenHolders`, `GetTokenUnspent` and+ `GetTokenTxs` for the new endpoints of haskoin-store.+- **The health check says in words what it found.** The JSON of a+ `HealthCheck` has a `text` for the whole store, such as "The store is+ healthy: it has every block up to height 812,347, with 8 peers+ connected, and its Redis answers.", or what is wrong when it is not, and+ a `text` in each check. `healthText` and the functions of each check+ (`blocksText`, `lastBlockText`, `lastTxText`, `pendingTxsText`,+ `peersText`, `databaseText`, `redisText`) write them, from the numbers;+ a program should read `ok` and the numbers, since the wording may change.+ The texts are written and not read back, so a `HealthCheck` reads the+ same with or without them.+- **`MempoolHealth`, how the store stands with the mempool of its nodes**,+ in a new field `mempool` of `HealthCheck`: how many sources it has to+ read a whole mempool from again (peers that give theirs when asked, and+ the RPC of a node), whether it may have missed transactions and has not+ read a source since, and how many transaction ids are on their way to+ the shared mempool and held. It is no check: a store with no source is+ healthy, and the `text` of the whole store says what it lacks.+ `mempoolText` writes it.+- **`DatabaseHealth`, the state of the store's database**, in a new field+ `database` of `HealthCheck`: whether RocksDB lets writes through+ (`DatabaseWrites`: flowing, delayed or stopped), the compaction pending,+ the rate writes are slowed to, the compactions and flushes running, the+ full tables in memory, the size of the files and of their live data, and+ the errors in the background. Stopped writes fail the check, and so+ `isOK` of the `HealthCheck`. haskoin-store wrote the state of writes into+ its JSON before, outside the type, where a client could not read it.++- **`sync` in `MempoolHealth`**, and in the `mempool` object of+ `/health`: how the shared mempool stands with the mempools of the nodes+ of the operator, in one word (`MempoolSync`). `syncing`: the store 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. `synced`: it has. `unknown`: it has no such node, only+ strangers or nobody, and cannot tell. A store is healthy in all three,+ and this says how it stands to whoever looks: an operator, or a deploy+ that waits for `synced` before giving the store traffic. `mempoolText`+ and `healthText` say it in words. The field reads as `unknown` from a+ store from before it. It was first a boolean, `filling`, for a few+ hours: a store among strangers said that it was filling for ever.+- **`warnings` in `HealthCheck`**, and in the JSON of `/health` when there+ are any: what the operator of a store should put right in how it is set+ up, a sentence each. A warning is not a check, and a store with warnings+ is as healthy as one without. `healthText` says them after the rest. A+ store from before the field reads as having none.++### Changed++- **Breaking: `HealthCheck` has two new fields, `database`** (`Maybe+ DatabaseHealth`) **and `mempool`** (`Maybe MempoolHealth`), so code that+ builds one has to give them. In JSON they may be missing, as in the+ output of an older store, and read as `Nothing`.+- **The client reaches a store on a Unix socket.** `ApiConfig` has a new+ field, `socket`: when it names one, every request goes to it, whatever+ host the URL names, as a store serves with `--socket`. The tests of the+ client serve on a Unix socket, and name no port.+- **Version 4.0.0**: needs haskoin-core 3.0, which reads the token prefix+ and adds a field to `Network`. The types of this package hold those of+ haskoin-core, so a program that uses both moves to haskoin-core 3.0 with+ it.+- CI runs through the workflow that the Haskell packages of jprupp share in+ [jprupp/tools](https://github.com/jprupp/tools), with the check of+ `stack.yaml` for local paths (`check-stack-paths`) and the cache of the+ Nix build kept per release of nixpkgs.+- `scripts/format` is gone: `haskell-format`, from jprupp/tools, formats+ every Haskell file.+- The README has a table of the requests of the token endpoints, what the+ fields of a `TokenBalance` mean, and an example of the client for tokens.+- `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+ several processes. What it needs to know about this package, the slow+ spec module, is in the new `haskell-dev.toml`.++- **A store is healthy whatever the state of its mempool.** `isOK` of a+ `HealthCheck`, and so `ok` in the JSON of `/health`, no longer depends on+ the two checks that look at transactions: `lastTx`, that one came lately,+ and `pendingTxs`, that few are asked for and not received. A store that+ has the blocks of its nodes answers every request rightly from what it+ has, and it was taken out of service for the state of its mempool while+ it had every block. Both checks are still made, each with its own `ok`+ and `text`; `healthText` no longer counts either among what is wrong.+ The health of a store is now: its database keeps up with the headers, the+ best header is recent, enough peers are connected, and the database+ takes writes.+ ## [3.0.1] - 2026-11-19 ### Changed
README.md view
@@ -36,6 +36,66 @@ The client appends the name of the network to the host, as in the layout of api.haskoin.com. The API speaks JSON, and so does the client. +A store on the same machine may listen on a Unix socket (`--socket`). Give+its path in `socket`, and every request goes to it, whatever host the URL+names:++```haskell+let cfg = def {net = btc, host = "http://localhost/", socket = Just "/run/haskoin-store/web.sock"}+```++## Tokens of Bitcoin Cash++On Bitcoin Cash an output can hold tokens (CashTokens), written at the+front of its script field. `scriptTokens net script` reads them from the+script of a `StoreOutput`, a `StoreInput` or an `Unspent`, which have no+field of their own for them. Their JSON has a `token` field on the Bitcoin+Cash networks: the category, the fungible amount as a string, and the+non-fungible token, or `null`. On Bitcoin the field is not there.++The requests of the token endpoints of haskoin-store 2.0.0:++| Request | Endpoint | Answer |+| --- | --- | --- |+| `GetAddrTokens address` | `/address/:address/tokens` | a `TokenBalance` per category that the address holds |+| `GetTokenHolders category limit offset` | `/token/:category/holders` | a `TokenBalance` per address that holds the category |+| `GetTokenUnspent category limits` | `/token/:category/unspent` | the `Unspent` outputs that hold it, newest first |+| `GetTokenTxs category limits` | `/token/:category/transactions` | the `TxRef`s that moved it, newest first |++A `TokenBalance` counts the mempool, as a `Balance` does:+`confirmedTokens` is what blocks hold and the mempool does not spend, and+`unconfirmedTokens` what the mempool adds, so their sum is what the address+holds now. `nfts` counts its non-fungible tokens, `tokenUtxo` the unspent+outputs that hold the category, `tokenTxs` the transactions that moved it+to or from the address, and `receivedTokens` every fungible token it ever+received. A category is the `TxHash` of the transaction whose output 0 the+first transaction of the tokens spent. On Bitcoin the server answers these+requests with empty lists.++```haskell+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}++import Data.Default (def)+import Haskoin (bch, textToAddr)+import Haskoin.Store.Data (SerialList (..), TokenBalance (..), Unspent (..), scriptTokens)+import Haskoin.Store.WebClient++main :: IO ()+main = do+ let cfg = def {net = bch}+ Just addr = textToAddr bch "bitcoincash:qz…"+ Right (SerialList balances) <- apiCall cfg (GetAddrTokens addr)+ mapM_ (\b -> print (b.category, b.confirmedTokens + b.unconfirmedTokens)) balances+ -- the outputs of the first category, with the tokens of each+ case balances of+ b : _ -> do+ let limits = LimitsParam Nothing (OffsetParam 0) Nothing+ Right (SerialList outs) <- apiCall cfg (GetTokenUnspent b.category limits)+ mapM_ (\u -> print (u.outpoint, scriptTokens bch u.script)) outs+ [] -> return ()+```+ Errors come back as `Left` an `Except`. ## Events@@ -79,6 +139,21 @@ stack build stack test ```++These commands build the package as it is released, with optimisation. For+the time between two commits there is a faster loop: `haskell-dev`, from+[jprupp/tools](https://github.com/jprupp/tools), on your `PATH`.++```sh+haskell-dev build # build without optimisation+haskell-dev test # run the tests in several processes at once+haskell-dev docs # build the documentation and check its comments+```++`haskell-dev.toml` tells it which spec modules are slow, so that it shares+them between the test processes. Do not mix the two kinds of build in one+folder: the flags differ, so each switch compiles everything again. Never+time code with `haskell-dev`. The tests check every type by law: JSON round-trips, the fast encoders write the same JSON as `toJSON`, the client reads what the server writes,
haskoin-store-data.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: haskoin-store-data-version: 3.0.1+version: 4.0.0 synopsis: Data types and API client of Haskoin Store description: The types of the data that Haskoin Store serves (blocks, transactions, balances, unspent outputs, extended public keys, health checks, events and@@ -57,7 +57,7 @@ , data-default >=0.8.0.2 && <0.9 , deepseq >=1.5.1.0 && <1.6 , hashable >=1.5.1.0 && <1.6- , haskoin-core >=2.0.0 && <2.1+ , haskoin-core >=3.0.0 && <3.1 , http-client >=0.7.19 && <0.8 , http-types >=0.12.6 && <0.13 , lens >=5.3.6 && <5.4@@ -100,7 +100,7 @@ , data-default >=0.8.0.2 && <0.9 , deepseq >=1.5.1.0 && <1.6 , hashable >=1.5.1.0 && <1.6- , haskoin-core >=2.0.0 && <2.1+ , haskoin-core >=3.0.0 && <3.1 , haskoin-store-data , hspec >=2.11.18 && <2.12 , http-client >=0.7.19 && <0.8@@ -108,6 +108,7 @@ , lens >=5.3.6 && <5.4 , network , string-conversions >=0.4.0.1 && <0.5+ , temporary , text >=2.1.4 && <2.2 , time ==1.14.* , unordered-containers >=0.2.21 && <0.3
src/Haskoin/Store/Data.hs view
@@ -52,6 +52,11 @@ zeroBalance, nullBalance, + -- * Tokens+ TokenBalance (..),+ zeroTokenBalance,+ scriptTokens,+ -- * Block Data BlockData (..), confirmed,@@ -101,7 +106,21 @@ TimeHealth (..), CountHealth (..), MaxHealth (..),+ DatabaseWrites (..),+ DatabaseHealth (..),+ MempoolHealth (..), HealthCheck (..),+ MempoolSync (..),+ mempoolSyncWord,+ healthText,+ blocksText,+ lastBlockText,+ lastTxText,+ pendingTxsText,+ peersText,+ databaseText,+ mempoolText,+ redisText, Event (..), EventCommand (..), Except (..),@@ -166,7 +185,8 @@ ) import Data.Aeson qualified as A import Data.Aeson.Encoding qualified as A-import Data.Aeson.Types (Parser)+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Pair, Parser) import Data.Binary (Binary (get, put)) import Data.Bits (Bits (..)) import Data.Bool (bool)@@ -176,7 +196,7 @@ import Data.Bytes.Put import Data.Bytes.Serial import Data.Default (Default (..))-import Data.Foldable (toList)+import Data.Foldable (find, toList) import Data.Function (on) import Data.HashMap.Strict (HashMap) import Data.HashMap.Strict qualified as HashMap@@ -533,6 +553,154 @@ } = True nullBalance _ = False +-- | The tokens of one category that an address holds (CashTokens, on+-- Bitcoin Cash).+--+-- It is the counterpart of t'Balance' for the tokens of a category:+-- @confirmedTokens@ plus @unconfirmedTokens@ is the fungible amount the+-- address holds now, counting the mempool, as in t'Balance'. The amounts are+-- in tokens of the category, not in satoshis; the coins of the same outputs+-- are in the address's t'Balance', as those of any output.+--+-- The fields have names of their own, not those of t'Balance': a record+-- update that names only fields that both types have would be ambiguous,+-- and code that updates a t'Balance' would stop compiling. The JSON keys+-- are those of t'Balance'.+--+-- The amounts are written as strings in JSON, as in+-- 'Haskoin.Script.CashToken.TokenData': a category can have up to+-- 'maxTokenAmount' tokens, more than a JSON number holds exactly in many+-- languages.+data TokenBalance = TokenBalance+ { -- | address that holds the tokens+ address :: !Address,+ -- | category of the tokens+ category :: !TxHash,+ -- | fungible tokens in outputs in blocks that are not being spent+ confirmedTokens :: !Word64,+ -- | fungible tokens that the mempool adds, as in t'Balance'+ unconfirmedTokens :: !Word64,+ -- | number of non-fungible tokens, counting the mempool+ nfts :: !Word64,+ -- | number of unspent outputs that hold tokens of the category, counting+ -- the mempool+ tokenUtxo :: !Word64,+ -- | number of transactions that moved tokens of the category to or from+ -- the address, counting the mempool+ tokenTxs :: !Word64,+ -- | fungible tokens of the category that all the outputs of the address+ -- ever received, counting the mempool and spent outputs+ receivedTokens :: !Word64+ }+ deriving (Show, Read, Eq, Ord, Generic, Hashable, NFData)++instance Serial TokenBalance where+ {-# INLINEABLE serialize #-}+ {-# INLINEABLE deserialize #-}+ serialize b = do+ serialize b.address+ serialize b.category+ putWord64be b.confirmedTokens+ putWord64be b.unconfirmedTokens+ putWord64be b.nfts+ putWord64be b.tokenUtxo+ putWord64be b.tokenTxs+ putWord64be b.receivedTokens++ deserialize = do+ address <- deserialize+ category <- deserialize+ confirmedTokens <- getWord64be+ unconfirmedTokens <- getWord64be+ nfts <- getWord64be+ tokenUtxo <- getWord64be+ tokenTxs <- getWord64be+ receivedTokens <- getWord64be+ return TokenBalance {..}++instance Binary TokenBalance where+ put = serialize+ get = deserialize++instance Serialize TokenBalance where+ put x = putDirect (serialize x)+ get = getDirect deserialize++instance MarshalJSON Network TokenBalance where+ marshalValue net b =+ A.object+ [ "address" .= marshalValue net b.address,+ "category" .= b.category,+ "confirmed" .= show b.confirmedTokens,+ "unconfirmed" .= show b.unconfirmedTokens,+ "nfts" .= b.nfts,+ "utxo" .= b.tokenUtxo,+ "txs" .= b.tokenTxs,+ "received" .= show b.receivedTokens+ ]++ marshalEncoding net b =+ A.pairs $+ mconcat+ [ "address" `A.pair` marshalEncoding net b.address,+ "category" `A.pair` toEncoding b.category,+ "confirmed" `A.pair` A.string (show b.confirmedTokens),+ "unconfirmed" `A.pair` A.string (show b.unconfirmedTokens),+ "nfts" `A.pair` A.word64 b.nfts,+ "utxo" `A.pair` A.word64 b.tokenUtxo,+ "txs" `A.pair` A.word64 b.tokenTxs,+ "received" `A.pair` A.string (show b.receivedTokens)+ ]++ unmarshalValue net =+ A.withObject "TokenBalance" $ \o -> do+ address <- o .: "address" >>= unmarshalValue net+ category <- o .: "category"+ confirmedTokens <- o .: "confirmed" >>= amount+ unconfirmedTokens <- o .: "unconfirmed" >>= amount+ nfts <- o .: "nfts"+ tokenUtxo <- o .: "utxo"+ tokenTxs <- o .: "txs"+ receivedTokens <- o .: "received" >>= amount+ return TokenBalance {..}+ where+ amount = maybe (fail "Not a token amount") return . readMaybe . T.unpack++-- | The tokens of a category that an address that never held any holds.+zeroTokenBalance :: Address -> TxHash -> TokenBalance+zeroTokenBalance address category =+ TokenBalance {address, category, confirmedTokens = 0, unconfirmedTokens = 0, nfts = 0, tokenUtxo = 0, tokenTxs = 0, receivedTokens = 0}++-- | The tokens that the script field of an output holds (CashTokens), on the+-- Bitcoin Cash networks.+--+-- The tokens are not a field of their own in t'StoreOutput', t'StoreInput'+-- or t'Unspent': they are written at the front of the script field, which+-- these types carry already, so they are read from it whenever they are+-- needed. The JSON of these types has them in a @token@ field.+--+-- 'Nothing' on the other networks, where the byte 0xef that starts a token+-- prefix is only an undefined opcode, and for a script field whose prefix is+-- not valid, which consensus keeps out of the chain.+scriptTokens :: Network -> ByteString -> Maybe TokenData+scriptTokens net script+ | isJust net.cashAddrPrefix = either (const Nothing) fst (splitTokenData script)+ | otherwise = Nothing++-- | The @token@ field of the JSON of an output: on the Bitcoin Cash networks+-- only, so that the JSON of the other networks stays as it was, and @null@+-- for an output without tokens.+tokenPairs :: Network -> ByteString -> [Pair]+tokenPairs net script+ | isJust net.cashAddrPrefix = ["token" .= scriptTokens net script]+ | otherwise = []++-- | 'tokenPairs' as an encoding.+tokenSeries :: Network -> ByteString -> A.Series+tokenSeries net script+ | isJust net.cashAddrPrefix = "token" `A.pair` toEncoding (scriptTokens net script)+ | otherwise = mempty+ instance MarshalJSON Network Balance where marshalValue net b = A.object@@ -660,7 +828,7 @@ instance MarshalJSON Network Unspent where marshalValue net u =- A.object+ A.object $ [ "address" .= fmap (marshalValue net) u.address, "block" .= u.block, "txid" .= u.outpoint.hash,@@ -668,6 +836,7 @@ "pkscript" .= encodeHex u.script, "value" .= u.value ]+ <> tokenPairs net u.script marshalEncoding net u = A.pairs $@@ -677,7 +846,8 @@ "txid" `A.pair` toEncoding u.outpoint.hash, "index" `A.pair` A.word32 u.outpoint.index, "pkscript" `A.pair` hexEncoding (B.fromStrict u.script),- "value" `A.pair` A.word64 u.value+ "value" `A.pair` A.word64 u.value,+ tokenSeries net u.script ] unmarshalValue net =@@ -860,7 +1030,7 @@ instance MarshalJSON Network StoreInput where marshalValue net StoreInput {..} =- A.object+ A.object $ [ "coinbase" .= False, "txid" .= outpoint.hash, "output" .= outpoint.index,@@ -871,8 +1041,9 @@ "address" .= (marshalValue net <$> address), "witness" .= map encodeHex witness ]- marshalValue _net StoreCoinbase {..} =- A.object+ <> tokenPairs net pkscript+ marshalValue net StoreCoinbase {..} =+ A.object $ [ "coinbase" .= True, "txid" .= outpoint.hash, "output" .= outpoint.index,@@ -883,6 +1054,7 @@ "address" .= Null, "witness" .= map encodeHex witness ]+ <> tokenPairs net B.empty marshalEncoding net StoreInput {..} = A.pairs $@@ -895,9 +1067,10 @@ "pkscript" `A.pair` hexEncoding (B.fromStrict pkscript), "value" `A.pair` A.word64 value, "address" `A.pair` maybe A.null_ (marshalEncoding net) address,- "witness" `A.pair` A.list (hexEncoding . B.fromStrict) witness+ "witness" `A.pair` A.list (hexEncoding . B.fromStrict) witness,+ tokenSeries net pkscript ]- marshalEncoding _net StoreCoinbase {..} =+ marshalEncoding net StoreCoinbase {..} = A.pairs $ mconcat [ "coinbase" .= True,@@ -908,7 +1081,8 @@ "pkscript" `A.pair` A.null_, "value" `A.pair` A.null_, "address" `A.pair` A.null_,- "witness" `A.pair` A.list (hexEncoding . B.fromStrict) witness+ "witness" `A.pair` A.list (hexEncoding . B.fromStrict) witness,+ tokenSeries net B.empty ] unmarshalValue net =@@ -993,13 +1167,14 @@ instance MarshalJSON Network StoreOutput where marshalValue net o =- A.object+ A.object $ [ "address" .= (marshalValue net <$> o.address), "pkscript" .= encodeHex o.script, "value" .= o.value, "spent" .= isJust o.spender, "spender" .= o.spender ]+ <> tokenPairs net o.script marshalEncoding net o = A.pairs $@@ -1008,7 +1183,8 @@ "pkscript" `A.pair` hexEncoding (B.fromStrict o.script), "value" `A.pair` A.word64 o.value, "spent" `A.pair` A.bool (isJust o.spender),- "spender" `A.pair` toEncoding o.spender+ "spender" `A.pair` toEncoding o.spender,+ tokenSeries net o.script ] unmarshalValue net =@@ -1679,9 +1855,210 @@ max <- o .: "max" return MaxHealth {..} --- | Health of the store, as returned by @\/health@. It is healthy if every check--- passes.+-- | Whether RocksDB lets the writes of the store through.+data DatabaseWrites+ = -- | at full speed+ WritesFlowing+ | -- | slowed down, to let compactions catch up+ WritesDelayed+ | -- | stopped, until compactions or flushes catch up+ WritesStopped+ deriving (Show, Eq, Ord, Enum, Bounded, Generic, NFData)++instance ToJSON DatabaseWrites where+ toJSON = A.String . writesName++instance FromJSON DatabaseWrites where+ parseJSON = A.withText "DatabaseWrites" $ \t ->+ maybe (fail ("Not a state of writes: " <> cs t)) return $+ find ((== t) . writesName) [minBound .. maxBound]++-- | The name of a state of writes in JSON.+writesName :: DatabaseWrites -> Text+writesName = \case+ WritesFlowing -> "flowing"+ WritesDelayed -> "delayed"+ WritesStopped -> "stopped"++-- | The state of the database of the store, as RocksDB reports it: whether+-- it takes writes, and how much work it has in hand. --+-- RocksDB writes to memory first, flushes what it wrote to files, and+-- merges the files in the background (compaction). When compaction falls+-- behind, it slows writes down and then stops them, and a store whose+-- writes are stopped imports nothing. Only that fails the check: delayed+-- writes are normal while a store syncs, and if they make it fall behind,+-- t'BlockHealth' says so. The other numbers say why writes are slow, and+-- are not judged: a store that syncs runs compactions all the time.+data DatabaseHealth = DatabaseHealth+ { -- | whether writes go through+ writes :: !DatabaseWrites,+ -- | bytes that RocksDB estimates it has to compact, over every column+ -- family+ pendingCompaction :: !Word64,+ -- | bytes a second that writes are slowed to, 0 when they are not+ delayedWriteRate :: !Word64,+ -- | compactions running+ compactions :: !Word32,+ -- | flushes of memory to files running+ flushes :: !Word32,+ -- | tables in memory that are full and wait to be flushed, over every+ -- column family+ memtables :: !Word32,+ -- | bytes of the files of the database, over every column family+ size :: !Word64,+ -- | bytes of those files that hold live data, as RocksDB estimates+ liveData :: !Word64,+ -- | errors of the work in the background since the database opened;+ -- after one, RocksDB may refuse writes+ errors :: !Word64+ }+ deriving (Show, Eq, Generic, NFData)++instance Healthy DatabaseHealth where+ isOK d = d.writes /= WritesStopped++instance ToJSON DatabaseHealth where+ toJSON d =+ A.object+ [ "writes" .= d.writes,+ "pending-compaction-bytes" .= d.pendingCompaction,+ "delayed-write-rate" .= d.delayedWriteRate,+ "running-compactions" .= d.compactions,+ "running-flushes" .= d.flushes,+ "immutable-memtables" .= d.memtables,+ "size-bytes" .= d.size,+ "live-data-bytes" .= d.liveData,+ "background-errors" .= d.errors,+ "ok" .= isOK d,+ "text" .= databaseText d+ ]++instance FromJSON DatabaseHealth where+ parseJSON =+ A.withObject "DatabaseHealth" $ \o -> do+ writes <- o .: "writes"+ pendingCompaction <- o .: "pending-compaction-bytes"+ delayedWriteRate <- o .: "delayed-write-rate"+ compactions <- o .: "running-compactions"+ flushes <- o .: "running-flushes"+ memtables <- o .: "immutable-memtables"+ size <- o .: "size-bytes"+ liveData <- o .: "live-data-bytes"+ errors <- o .: "background-errors"+ return DatabaseHealth {..}++-- | How the store stands with the mempool of its nodes: whether it can+-- read one whole again, and what is on its way to the shared mempool.+--+-- A node announces a transaction to a peer once. A store that misses one,+-- because it was away, or behind, or had no room, gets it back only by+-- reading the whole mempool of a node again, and what lets it do that is a+-- /source/: a peer whose node allows it, or the RPC of a node. 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 store with no source is not unhealthy: it answers every request, and a+-- store whose peers are all strangers on Bitcoin has none by nature. So+-- this is no check that passes or fails, and it has no @ok@. It is what an+-- operator needs to see when a store shows fewer transactions than a node.+data MempoolHealth = MempoolHealth+ { -- | what the store can read a whole mempool from: peers that give+ -- theirs when asked, and the RPC of a node while it answers+ sources :: !Word32,+ -- | whether the store 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+ dirty :: !Bool,+ -- | transaction ids on their way to the shared mempool: wanted,+ -- asked of a peer, or held+ known :: !Word32,+ -- | transactions held: being offered, or waiting for one that they+ -- spend from+ held :: !Word32,+ -- | how the shared mempool stands with the mempools of the nodes of+ -- the operator, a t'MempoolSync'. It reads as 'MempoolUnknown' from a+ -- store from before the field.+ sync :: !MempoolSync+ }+ deriving (Show, Eq, Generic, NFData)++-- | How the shared mempool stands with the mempools of the nodes that the+-- operator of a store trusts, in one word: @sync@ in the JSON of a+-- t'MempoolHealth'.+--+-- It was a boolean once, whether the mempool is still filling. A store+-- whose peers are all strangers cannot say either: what a stranger names+-- is not what the mempool should have, so there is nothing to measure it+-- against, and such a store said that it was filling for ever.+data MempoolSync+ = -- | @syncing@: the store has a node of its operator to read a whole+ -- mempool from, and since it started, or since the shared mempool+ -- lost what it had, it has not yet read every such node and taken in+ -- all that they named. Until then it shows fewer unconfirmed+ -- transactions than its node has.+ MempoolSyncing+ | -- | @synced@: it has+ MempoolSynced+ | -- | @unknown@: the store has no node of its operator to read a whole+ -- mempool from, only strangers or nobody, and cannot tell+ MempoolUnknown+ deriving (Show, Eq, Ord, Enum, Bounded, Generic, NFData)++instance ToJSON MempoolSync where+ toJSON = A.String . mempoolSyncWord++instance FromJSON MempoolSync where+ parseJSON = A.withText "MempoolSync" $ \t ->+ case [s | s <- [minBound .. maxBound], mempoolSyncWord s == t] of+ [s] -> return s+ _ -> fail ("Not a state of the mempool: " <> T.unpack t)++-- | The word of a t'MempoolSync' in JSON: one word, in lower case.+mempoolSyncWord :: MempoolSync -> Text+mempoolSyncWord = \case+ MempoolSyncing -> "syncing"+ MempoolSynced -> "synced"+ MempoolUnknown -> "unknown"++instance ToJSON MempoolHealth where+ toJSON m =+ A.object+ [ "sources" .= m.sources,+ "dirty" .= m.dirty,+ "known" .= m.known,+ "held" .= m.held,+ "sync" .= m.sync,+ "text" .= mempoolText m+ ]++instance FromJSON MempoolHealth where+ parseJSON =+ A.withObject "MempoolHealth" $ \o -> do+ sources <- o .: "sources"+ dirty <- o .: "dirty"+ known <- o .: "known"+ held <- o .: "held"+ sync <- o .:? "sync" .!= MempoolUnknown+ return MempoolHealth {..}++-- | Health of the store, as returned by @\/health@. It is healthy if it+-- has the blocks of its nodes: the database keeps up with the headers,+-- the best header is recent, enough peers are connected, and the database+-- takes writes ('isOK').+--+-- Nothing of the mempool decides it. A store that is at the head of the+-- chain answers every request rightly from what it has, whatever the+-- state of its mempool: one that just started and is still filling it,+-- one whose node has gone quiet, one that waits for transactions that it+-- asked for. The two checks that look at transactions, 'lastTx' and+-- 'pendingTxs', are still made and still say whether they pass, each with+-- its own @ok@, and the health of the store does not depend on them. They+-- did decide it once, and a store was taken out of service for the state+-- of its mempool while it had every block. What an operator wants to know+-- of the mempool is in 'mempool', and 'sync' above all.+-- -- The check of Redis is not one of them. A store that has a Redis cache and -- cannot reach it still answers every request, from its own database, so it -- is fit to serve, and 'isOK' says so. What it lost is that its answers are@@ -1692,6 +2069,12 @@ -- The field may be missing in the JSON, where it reads as 'Nothing'. So the output of a store -- from before the field can still be read, and a client from before it -- reads the output of a new store.+--+-- 'warnings' are not checks either. A warning is something about how the+-- store is set up that its operator should put right, and that does not+-- keep it from answering rightly: a store that has the RPC of its node+-- and not its ZeroMQ socket. It is a sentence for people, and it is in+-- 'healthText' too. data HealthCheck = HealthCheck { -- | the database keeps up with the headers blocks :: !BlockHealth,@@ -1711,7 +2094,15 @@ time :: !Word64, -- | whether the Redis cache answers; 'Nothing' for a store that has -- none- redis :: !(Maybe Bool)+ redis :: !(Maybe Bool),+ -- | the state of the database; 'Nothing' from a store from before it+ database :: !(Maybe DatabaseHealth),+ -- | how the store stands with the mempool of its nodes; 'Nothing'+ -- from a store from before it. It is not one of the checks.+ mempool :: !(Maybe MempoolHealth),+ -- | what the operator should put right in how the store is set up, a+ -- sentence each; none from a store from before it. Not checks.+ warnings :: ![Text] } deriving (Show, Eq, Generic, NFData) @@ -1720,25 +2111,34 @@ and [ isOK h.blocks, isOK h.lastBlock,- isOK h.lastTx,- isOK h.pendingTxs,- isOK h.peers+ isOK h.peers,+ all isOK h.database ] instance ToJSON HealthCheck where toJSON h = A.object $- [ "blocks" .= h.blocks,- "last-block" .= h.lastBlock,- "last-tx" .= h.lastTx,- "pending-txs" .= h.pendingTxs,- "peers" .= h.peers,+ [ "blocks" .= explained (blocksText h.blocks) h.blocks,+ "last-block" .= explained (lastBlockText h.lastBlock) h.lastBlock,+ "last-tx" .= explained (lastTxText h.lastTx) h.lastTx,+ "pending-txs" .= explained (pendingTxsText h.pendingTxs) h.pendingTxs,+ "peers" .= explained (peersText h.peers) h.peers, "net" .= h.network, "version" .= h.version, "time" .= show (posixSecondsToUTCTime $ fromIntegral h.time),- "ok" .= isOK h+ "ok" .= isOK h,+ "text" .= healthText h ]- <> ["redis" .= A.object ["ok" .= up] | Just up <- [h.redis]]+ <> ["redis" .= A.object ["ok" .= up, "text" .= redisText up] | Just up <- [h.redis]]+ <> ["database" .= d | Just d <- [h.database]]+ <> ["mempool" .= m | Just m <- [h.mempool]]+ <> ["warnings" .= h.warnings | not (null h.warnings)]+ where+ -- the JSON of a check with what it means: the text depends on which+ -- check it is, so it is added here and not by the check's own JSON+ explained text x = case toJSON x of+ A.Object o -> A.Object (KeyMap.insert "text" (A.String text) o)+ v -> v instance FromJSON HealthCheck where parseJSON =@@ -1755,7 +2155,263 @@ utcTime <- o .: "time" >>= \t -> maybe (fail ("Not a time: " <> t)) return (readMaybe t) time <- maybe (fail "A time before 1970, or too far ahead") return (unixSeconds utcTime) redis <- o .:? "redis" >>= mapM (.: "ok")+ database <- o .:? "database"+ mempool <- o .:? "mempool"+ warnings <- o .:? "warnings" .!= [] return HealthCheck {..}++-- | What the health check says of the whole store, in a sentence or two for+-- people: whether it is healthy, and if not, what is wrong, from the checks+-- that fail. In the JSON of a t'HealthCheck' as @text@, beside the @text@ of+-- each check, which says what that check found.+--+-- The checks say what they found with their numbers; this says what it+-- means for whoever looks at a store, and so does the store's log when its+-- health changes. A program should read @ok@ and the numbers, not the text,+-- which may change between versions.+--+-- A store whose Redis does not answer is healthy by 'isOK', since it has+-- what it needs to import blocks, but it answers no request (see+-- t'HealthCheck'). The text says so, as the status of @\/health@ does.+healthText :: HealthCheck -> Text+healthText h+ | null problems =+ T.unwords $+ [ "The store is healthy:",+ "it has every block up to height " <> shown h.blocks.headers <> ",",+ "with " <> plural h.peers.count "peer" <> " connected" <> case h.redis of+ Just True -> ", and its Redis answers."+ _ -> "."+ ]+ <> [slow | Just d <- [h.database], d.writes == WritesDelayed]+ <> [noSourceText | Just m <- [h.mempool], m.sources == 0]+ <> [syncingText | Just m <- [h.mempool], m.sync == MempoolSyncing]+ <> warned+ | otherwise = "The store is not healthy. " <> T.unwords (problems <> warned)+ where+ slow = "RocksDB delays writes while it compacts the database."+ warned = ["Warning: " <> w <> "." | w <- h.warnings]+ problems =+ [blocksText h.blocks | not (isOK h.blocks)]+ <> [lastBlockText h.lastBlock | not (isOK h.lastBlock)]+ <> [peersText h.peers | not (isOK h.peers)]+ <> [databaseText d | Just d <- [h.database], not (isOK d)]+ <> [redisText False | h.redis == Just False]++-- | What the check of the blocks found, a t'BlockHealth', for people.+blocksText :: BlockHealth -> Text+blocksText b+ | behind < 0 =+ T.unwords+ [ "The database is at height " <> shown b.blocks <> ",",+ "ahead of the best header at " <> shown b.headers <> ":",+ "the headers catch up in a moment."+ ]+ | behind == 0 = "The database has every block up to the best header, at height " <> shown b.headers <> "."+ | isOK b =+ T.unwords+ [ "The database is " <> plural behind "block" <> " behind the best header,",+ "at height " <> shown b.headers <> ", within the " <> shown b.max <> " allowed."+ ]+ | otherwise =+ T.unwords+ [ "The database is " <> plural behind "block" <> " behind the best header,",+ "at height " <> shown b.headers <> ", more than the " <> shown b.max <> " allowed:",+ "the store is syncing, or cannot import blocks fast enough."+ ]+ where+ behind = toInteger b.headers - toInteger b.blocks++-- | What the check of the age of the best header found, for people.+lastBlockText :: TimeHealth -> Text+lastBlockText t+ -- a header dated ahead of the clock, as miners may date them+ | t.age <= 0 = "The best header is new, within the " <> duration t.max <> " allowed."+ | isOK t =+ T.unwords+ [ "The best header is " <> duration t.age <> " old,",+ "within the " <> duration t.max <> " allowed."+ ]+ | otherwise =+ T.unwords+ [ "The best header is " <> duration t.age <> " old,",+ "more than the " <> duration t.max <> " allowed:",+ "the store's peers may be stuck or behind, or the network has found no block for that long."+ ]++-- | What the check of the age of the last transaction or block found, for+-- people.+lastTxText :: TimeHealth -> Text+lastTxText t+ | t.age <= 0 = "A transaction or block came just now, within the " <> duration t.max <> " allowed."+ | isOK t =+ T.unwords+ [ "The last transaction or block came " <> duration t.age <> " ago,",+ "within the " <> duration t.max <> " allowed."+ ]+ | otherwise =+ T.unwords+ [ "No transaction or block came for " <> duration t.age <> ",",+ "more than the " <> duration t.max <> " allowed:",+ "the store may hear nothing from its peers."+ ]++-- | What the check of the transactions asked of peers found, for people.+pendingTxsText :: MaxHealth -> Text+pendingTxsText m+ | isOK m =+ T.unwords+ [ plural m.count "transaction" <> " asked of peers " <> isAre <> " still to come,",+ "within the " <> shown m.max <> " allowed."+ ]+ | otherwise =+ T.unwords+ [ plural m.count "transaction" <> " asked of peers " <> isAre <> " still to come,",+ "more than the " <> shown m.max <> " allowed:",+ "the peers do not send what the store asks for, or it cannot take it in fast enough."+ ]+ where+ isAre = if m.count == 1 then "is" else "are"++-- | What the check of the peers found, for people.+peersText :: CountHealth -> Text+peersText c+ | isOK c = plural c.count "peer" <> " connected, and at least " <> shown c.min <> " needed."+ | otherwise =+ T.unwords+ [ plural c.count "peer" <> " connected, fewer than the " <> shown c.min <> " needed:",+ "the store hears too little of the network."+ ]++-- | What the check of the database found, a t'DatabaseHealth', for people:+-- the state of the writes, the size of its files, and the work that RocksDB+-- has in hand, of which only what there is.+databaseText :: DatabaseHealth -> Text+databaseText d =+ T.unwords $+ [ case d.writes of+ WritesFlowing -> "RocksDB writes at full speed."+ WritesDelayed ->+ T.unwords+ [ "RocksDB delays writes to " <> bytes d.delayedWriteRate <> " a second,",+ "to let compactions catch up."+ ]+ WritesStopped -> "RocksDB stopped writes until compactions or flushes catch up: the store imports nothing.",+ if d.size == 0+ then "The database has written no files yet: what it holds is in memory."+ else "Its files hold " <> bytes d.size <> ", " <> bytes d.liveData <> " of them live data.",+ if null work+ then "Nothing waits to be compacted or flushed."+ else T.intercalate ", " work <> "."+ ]+ <> [ plural d.errors "error" <> " in the background since the database opened: see the log of the store."+ | d.errors > 0+ ]+ where+ -- what RocksDB has to do, without the parts that are nothing+ work =+ capitalised $+ [bytes d.pendingCompaction <> " to compact" | d.pendingCompaction > 0]+ <> [plural d.compactions "compaction" <> " running" | d.compactions > 0]+ <> [plural d.flushes "flush" <> " running" | d.flushes > 0]+ <> [plural d.memtables "full table" <> " in memory to flush" | d.memtables > 0]+ capitalised (w : ws) = (T.toUpper (T.take 1 w) <> T.drop 1 w) : ws+ capitalised [] = []++-- | What a store with no source has to say, in 'healthText' and in+-- 'mempoolText'.+noSourceText :: Text+noSourceText =+ "The store has nothing to read a whole mempool from again, no peer that gives its \+ \own and no RPC of a node: a transaction that it misses stays missed until a block has it."++-- | What is said of a store whose shared mempool is still syncing.+syncingText :: Text+syncingText =+ "Its mempool is still syncing: it has not yet taken in all that its nodes have, \+ \and shows fewer unconfirmed transactions than its node until it has."++-- | What is said of a store that cannot tell how its mempool stands.+unknownSyncText :: Text+unknownSyncText =+ "It has no node of its operator to measure its mempool against, \+ \and cannot tell whether it has all that a node has."++-- | How the store stands with the mempool of its nodes, a+-- t'MempoolHealth', for people.+mempoolText :: MempoolHealth -> Text+mempoolText m =+ T.unwords $+ [ if m.sources == 0+ then noSourceText+ else+ "The store has "+ <> plural m.sources "source"+ <> " to read a whole mempool from again, which it does when it may have missed a transaction."+ ]+ <> [ if m.sources == 0+ then "It may have missed some."+ else "It may have missed some, and is about to read again."+ | m.dirty+ ]+ <> [ T.unwords+ [ plural m.known "transaction",+ isAre,+ "on the way to the shared mempool,",+ shown m.held <> " held."+ ]+ | m.known > 0+ ]+ <> [syncingText | m.sync == MempoolSyncing]+ <> [unknownSyncText | m.sync == MempoolUnknown, m.sources > 0]+ where+ isAre = if m.known == 1 then "is" else "are"++-- | What the check of Redis found, for people: whether it answers.+redisText :: Bool -> Text+redisText True = "Redis answers."+redisText False =+ "Redis does not answer: the store knows no mempool and answers no request, with 503, until it is back."++-- | A whole number in decimal, with its thousands set apart by commas, as+-- people read them: @812,347@.+shown :: (Integral a) => a -> Text+shown n+ | n < 0 = "-" <> shown (negate (toInteger n))+ | otherwise = T.intercalate "," (groups (T.pack (show (toInteger n))))+ where+ groups t+ | T.length t <= 3 = [t]+ | otherwise = groups (T.dropEnd 3 t) <> [T.takeEnd 3 t]++-- | A count of things, with the plural of the noun when it is not one:+-- @plural 2 "peer"@ is @2 peers@.+plural :: (Integral a) => a -> Text -> Text+plural 1 noun = "1 " <> noun+plural n noun+ | "sh" `T.isSuffixOf` noun = shown n <> " " <> noun <> "es"+ | otherwise = shown n <> " " <> noun <> "s"++-- | Seconds in the largest unit that keeps them above one: @90@ is+-- @1 minute@, @7200@ is @2 hours@. Whole units, rounded down, which is+-- what a person reads at a glance.+duration :: Int64 -> Text+duration s+ | s < 0 = "0 seconds"+ | s < 60 = plural s "second"+ | s < 3600 = plural (s `div` 60) "minute"+ | s < 86400 = plural (s `div` 3600) "hour"+ | otherwise = plural (s `div` 86400) "day"++-- | Bytes in the largest unit of powers of 1,000 that keeps them above one,+-- with one decimal: @70000000000@ is @70.0 GB@.+bytes :: Word64 -> Text+bytes n = case dropWhile ((> toInteger n) . fst) units of+ (size, unit) : _ | size > 1 -> tenths (toInteger n * 10 `div` size) <> " " <> unit+ _ -> plural n "byte"+ where+ units = [(10 ^ (12 :: Int), "TB"), (10 ^ (9 :: Int), "GB"), (10 ^ (6 :: Int), "MB"), (1000, "kB")]+ tenths t = shown (t `div` 10) <> "." <> shown (t `mod` 10) -- | Event streamed by @\/events@. data Event
src/Haskoin/Store/WebClient.hs view
@@ -63,6 +63,10 @@ GetAddrBalance (..), GetAddrsBalance (..), GetAddrUnspent (..),+ GetAddrTokens (..),+ GetTokenHolders (..),+ GetTokenUnspent (..),+ GetTokenTxs (..), GetAddrsUnspent (..), -- * Extended public keys@@ -109,9 +113,17 @@ import Haskoin.Store.WebCommon import Haskoin.Transaction import Haskoin.Util-import Network.HTTP.Client (HttpException (..), Request (..), RequestBody (..))+import Network.HTTP.Client+ ( HttpException (..),+ ManagerSettings (..),+ Request (..),+ RequestBody (..),+ defaultManagerSettings,+ )+import Network.HTTP.Client.Internal (socketConnection) import Network.HTTP.Types (StdMethod (..)) import Network.HTTP.Types.Status+import Network.Socket qualified as Socket import Network.Wreq qualified as HTTP import Network.Wreq.Types (Payload (..), ResponseChecker) import Numeric.Natural (Natural)@@ -123,13 +135,23 @@ -- ApiConfig -- { net = bch -- , host = "https://api.haskoin.com/"+-- , socket = Nothing -- } -- @+--+-- A server on the same machine may listen on a Unix socket, as haskoin-store+-- does with @--socket@. Give its path in 'socket', and every request+-- goes to it, whatever host the URL names, which then only has to be a URL+-- of plain HTTP, such as @http:\/\/localhost\/@: a socket of the machine+-- needs no encryption. data ApiConfig = ApiConfig { -- | network to query; its name is appended to the host net :: !Network, -- | base URL of the API, ending in a slash- host :: !String+ host :: !String,+ -- | a Unix socket that every request goes to, in place of the host and+ -- port of the URL+ socket :: !(Maybe FilePath) } deriving (Eq, Show) @@ -137,7 +159,8 @@ def = ApiConfig { net = bch,- host = "https://api.haskoin.com/"+ host = "https://api.haskoin.com/",+ socket = Nothing } -- | Make a call to the haskoin-store API.@@ -159,7 +182,7 @@ ApiConfig -> a -> IO (Either Store.Except b)-apiCall (ApiConfig net apiHost) res =+apiCall (ApiConfig net apiHost through) res = case toOptions net res of Left e -> return (Left e) -- as for a parameter of the query string that cannot be written@@ -167,10 +190,10 @@ Right args -> let url = apiHost <> net.name <> cs (queryPath net res) in case resourceMethod $ asProxy res of- GET -> getJSON net args url+ GET -> getJSON net (args <> via through) url POST -> case resourceBody res of- Just (PostBox body) -> postJSON net args url body+ Just (PostBox body) -> postJSON net (args <> via through) url body _ -> return . Left $ Store.StringError "Could not post resource" _ -> return . Left $ Store.StringError "Unsupported HTTP method" @@ -224,8 +247,8 @@ -- | The events of a server, from now or from after one of them. listenEvents :: ApiConfig -> Maybe Store.Event -> (Store.Event -> IO Bool) -> IO (Either Store.Except ())-listenEvents (ApiConfig net apiHost) after handle = do- r <- try (reaching (HTTP.foldGetWith (jsonOpts mempty) step BS.empty url))+listenEvents (ApiConfig net apiHost through) after handle = do+ r <- try (reaching (HTTP.foldGetWith (jsonOpts (via through)) step BS.empty url)) return $ case r of Left Stopped -> Right () Right (Left e) -> Left e@@ -327,6 +350,24 @@ maybeToEither (Store.UserError "Invalid Param") $ encodeParam net a return $ applyOpt (paramLabel a) res++-- | Send the requests through a Unix socket, if one is given. The settings+-- make a manager for each request, which a client that calls a local+-- server now and then does not notice.+via :: Maybe FilePath -> Endo HTTP.Options+via Nothing = mempty+via (Just path) = Endo $ HTTP.manager .~ Left (unixSocket path)++-- | Settings of an HTTP client whose every connection goes to a Unix+-- socket, whatever host and port the URL names.+unixSocket :: FilePath -> ManagerSettings+unixSocket path =+ defaultManagerSettings+ { managerRawConnection = return $ \_ _ _ -> do+ s <- Socket.socket Socket.AF_UNIX Socket.Stream Socket.defaultProtocol+ Socket.connect s (Socket.SockAddrUnix path) `onException` Socket.close s+ socketConnection s 8192+ } -- | Set a query string parameter to comma-separated values. applyOpt :: Text -> [Text] -> Endo HTTP.Options
src/Haskoin/Store/WebCommon.hs view
@@ -57,6 +57,10 @@ GetAddrBalance (..), GetAddrsBalance (..), GetAddrUnspent (..),+ GetAddrTokens (..),+ GetTokenHolders (..),+ GetTokenUnspent (..),+ GetTokenTxs (..), GetAddrsUnspent (..), GetXPub (..), GetXPubTxs (..),@@ -172,6 +176,9 @@ instance ApiResponse Store.Balance where parseResponse net = unmarshalValue net +instance ApiResponse Store.TokenBalance where+ parseResponse net = unmarshalValue net+ instance ApiResponse Store.Unspent where parseResponse net = unmarshalValue net @@ -324,6 +331,24 @@ -- | Request for unspent outputs of several addresses: @GET \/address\/unspent?addresses=…@. data GetAddrsUnspent = GetAddrsUnspent ![Address] !LimitsParam +-- | Request for the token balances of an address, one per category+-- (CashTokens): @GET \/address\/:address\/tokens@.+newtype GetAddrTokens = GetAddrTokens Address++-- Tokens++-- | Request for the holders of the tokens of a category, one token balance+-- per address: @GET \/token\/:category\/holders@.+data GetTokenHolders = GetTokenHolders !TxHash !(Maybe LimitParam) !OffsetParam++-- | Request for the unspent outputs that hold tokens of a category:+-- @GET \/token\/:category\/unspent@.+data GetTokenUnspent = GetTokenUnspent !TxHash !LimitsParam++-- | Request for the transactions that touch tokens of a category:+-- @GET \/token\/:category\/transactions@.+data GetTokenTxs = GetTokenTxs !TxHash !LimitsParam+ -- XPubs -- | Request for summary of an extended public key: @GET \/xpub\/:xpub@.@@ -514,6 +539,28 @@ resourcePath _ _ = "/address/unspent" queryParams (GetAddrsUnspent as (LimitsParam l o sM)) = ([], [ParamBox as] <> noMaybeBox l <> noDefBox o <> noMaybeBox sM)++instance ApiResource GetAddrTokens (Store.SerialList Store.TokenBalance) where+ resourcePath _ = "/address/" <+> "/tokens"+ queryParams (GetAddrTokens a) = ([ParamBox a], [])+ captureParams _ = [ProxyBox (Proxy :: Proxy Address)]++instance ApiResource GetTokenHolders (Store.SerialList Store.TokenBalance) where+ resourcePath _ = "/token/" <+> "/holders"+ queryParams (GetTokenHolders c l o) = ([ParamBox c], noMaybeBox l <> noDefBox o)+ captureParams _ = [ProxyBox (Proxy :: Proxy TxHash)]++instance ApiResource GetTokenUnspent (Store.SerialList Store.Unspent) where+ resourcePath _ = "/token/" <+> "/unspent"+ queryParams (GetTokenUnspent c (LimitsParam l o sM)) =+ ([ParamBox c], noMaybeBox l <> noDefBox o <> noMaybeBox sM)+ captureParams _ = [ProxyBox (Proxy :: Proxy TxHash)]++instance ApiResource GetTokenTxs (Store.SerialList Store.TxRef) where+ resourcePath _ = "/token/" <+> "/transactions"+ queryParams (GetTokenTxs c (LimitsParam l o sM)) =+ ([ParamBox c], noMaybeBox l <> noDefBox o <> noMaybeBox sM)+ captureParams _ = [ProxyBox (Proxy :: Proxy TxHash)] ----------- -- XPubs --
test/Haskoin/Store/DataSpec.hs view
@@ -12,8 +12,9 @@ import Data.Bytes.Serial (Serial, serialize) import Data.HashMap.Strict qualified as HashMap import Data.IntMap qualified as IntMap-import Data.Maybe (fromJust)+import Data.Maybe (fromJust, fromMaybe) import Data.Text (Text)+import Data.Text qualified as T import Data.Text.Encoding (encodeUtf8) import Haskoin import Haskoin.Store.Data@@ -37,6 +38,7 @@ -- also covered inside the types below, but each has its own cereal and -- binary instances binaryLaws (anyNet arbitraryBalance)+ binaryLaws (anyNet arbitraryTokenBalance) binaryLaws (anyNet arbitraryUnspent) binaryLaws (anyNet arbitraryDeriveType) binaryLaws (anyNet arbitraryXPubSpec)@@ -72,6 +74,7 @@ -- BinfoTx are encoded through their own instances inside these. describe "JSON of a network" $ do marshalLaws arbitraryXPubBal+ marshalLaws arbitraryTokenBalance marshalLaws arbitraryXPubUnspent marshalLaws arbitraryBlockData marshalLaws arbitraryTransaction@@ -96,8 +99,29 @@ network = "btc", version = "1.9.0", time = 1700000000,- redis = Nothing+ redis = Nothing,+ database = Nothing,+ mempool = Nothing,+ warnings = [] }+ database =+ DatabaseHealth+ { writes = WritesFlowing,+ pendingCompaction = 0,+ delayedWriteRate = 0,+ compactions = 0,+ flushes = 1,+ memtables = 0,+ size = 70000000000,+ liveData = 69000000000,+ errors = 0+ }+ text key = \case+ A.Object o ->+ KeyMap.lookup key o >>= \case+ A.Object c -> KeyMap.lookup "text" c+ _ -> Nothing+ _ -> Nothing without key = \case A.Object o -> A.Object (KeyMap.delete key o) v -> v@@ -110,10 +134,158 @@ (A.fromJSON (badly (A.toJSON bare)) :: A.Result HealthCheck) `shouldSatisfy` \case A.Error _ -> True A.Success _ -> False+ it "says in words what the whole store and each check found" $ do+ let json = A.toJSON bare {database = Just database, redis = Just True}+ json `shouldSatisfy` \case+ A.Object o ->+ KeyMap.lookup "text" o+ == Just+ ( A.String+ "The store is healthy: it has every block up to height 10, \+ \with 3 peers connected, and its Redis answers."+ )+ _ -> False+ text "blocks" json `shouldBe` Just (A.String "The database has every block up to the best header, at height 10.")+ text "peers" json `shouldBe` Just (A.String "3 peers connected, and at least 1 needed.")+ text "redis" json `shouldBe` Just (A.String "Redis answers.")+ text "database" json+ `shouldBe` Just+ ( A.String . T.unwords $+ [ "RocksDB writes at full speed.",+ "Its files hold 70.0 GB, 69.0 GB of them live data.",+ "1 flush running."+ ]+ )+ it "says what is wrong with a store that is not healthy, and nothing else" $ do+ let sick = bare {blocks = BlockHealth 100 10 2, database = Just database {writes = WritesStopped}}+ healthText sick+ `shouldBe` T.unwords+ [ "The store is not healthy.",+ "The database is 90 blocks behind the best header, at height 100, more than the 2 allowed:",+ "the store is syncing, or cannot import blocks fast enough.",+ "RocksDB stopped writes until compactions or flushes catch up: the store imports nothing.",+ "Its files hold 70.0 GB, 69.0 GB of them live data.",+ "1 flush running."+ ]+ isOK bare {database = Just database {writes = WritesStopped}} `shouldBe` False+ isOK bare {database = Just database {writes = WritesDelayed}} `shouldBe` True+ it "writes numbers as people read them, and leaves out the work that is nothing" $ do+ let busy = database {pendingCompaction = 1234567890123, compactions = 3, flushes = 0, memtables = 2}+ databaseText busy+ `shouldBe` T.unwords+ [ "RocksDB writes at full speed.",+ "Its files hold 70.0 GB, 69.0 GB of them live data.",+ "1.2 TB to compact, 3 compactions running, 2 full tables in memory to flush."+ ]+ databaseText database {size = 0, liveData = 0, flushes = 0}+ `shouldBe` "RocksDB writes at full speed. The database has written no files yet: \+ \what it holds is in memory. Nothing waits to be compacted or flushed."+ pendingTxsText (MaxHealth 12345 10000)+ `shouldBe` "12,345 transactions asked of peers are still to come, more than the 10,000 allowed: \+ \the peers do not send what the store asks for, or it cannot take it in fast enough."+ lastBlockText (TimeHealth (-24) 14400) `shouldBe` "The best header is new, within the 4 hours allowed."+ it "writes the example of the API reference of haskoin-store" $ do+ let example =+ HealthCheck+ { blocks = BlockHealth 688798 688794 2,+ lastBlock = TimeHealth 3279 7200,+ lastTx = TimeHealth 0 300,+ pendingTxs = MaxHealth 0 100,+ peers = CountHealth 0 1,+ network = "bch",+ version = "2.0.0",+ time = 1623666103,+ redis = Just True,+ database = Just database {size = 412000000000, liveData = 405300000000, flushes = 0},+ mempool = Just (MempoolHealth 1 False 0 0 MempoolSynced),+ warnings = []+ }+ healthText example+ `shouldBe` T.unwords+ [ "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."+ ]+ lastBlockText example.lastBlock `shouldBe` "The best header is 54 minutes old, within the 2 hours allowed."+ lastTxText example.lastTx `shouldBe` "A transaction or block came just now, within the 5 minutes allowed."+ pendingTxsText example.pendingTxs+ `shouldBe` "0 transactions asked of peers are still to come, within the 100 allowed."+ fmap databaseText example.database+ `shouldBe` Just+ "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."+ it "says how the store stands with the mempool of its nodes, which is no check" $ do+ let alone = MempoolHealth {sources = 0, dirty = True, known = 3, held = 1, sync = MempoolUnknown}+ sourced = MempoolHealth {sources = 2, dirty = False, known = 0, held = 0, sync = MempoolSynced}+ mempoolText sourced+ `shouldBe` "The store has 2 sources to read a whole mempool from again, \+ \which it does when it may have missed a transaction."+ mempoolText sourced {dirty = True, sources = 1}+ `shouldBe` "The store has 1 source to read a whole mempool from again, \+ \which it does when it may have missed a transaction. \+ \It may have missed some, and is about to read again."+ mempoolText alone+ `shouldBe` "The store has nothing to read a whole mempool from again, \+ \no peer that gives its own and no RPC of a node: \+ \a transaction that it misses stays missed until a block has it. \+ \It may have missed some. \+ \3 transactions are on the way to the shared mempool, 1 held."+ -- a store with no source is healthy, and says what it lacks+ isOK bare {mempool = Just alone} `shouldBe` True+ healthText bare {mempool = Just alone}+ `shouldBe` "The store is healthy: it has every block up to height 10, with 3 peers connected. \+ \The store has nothing to read a whole mempool from again, \+ \no peer that gives its own and no RPC of a node: \+ \a transaction that it misses stays missed until a block has it."+ A.fromJSON (without "mempool" (A.toJSON bare {mempool = Just alone})) `shouldBe` A.Success bare+ it "is healthy at the head of the chain, whatever the state of the mempool" $ do+ -- no transaction for an hour, and more asked for than allowed: each+ -- check says so, and the store is healthy+ let quiet = bare {lastTx = TimeHealth 3600 300, pendingTxs = MaxHealth 20000 10000}+ isOK quiet.lastTx `shouldBe` False+ isOK quiet.pendingTxs `shouldBe` False+ isOK quiet `shouldBe` True+ healthText quiet `shouldBe` healthText bare+ -- behind on its blocks, it is not+ isOK (quiet {blocks = BlockHealth 100 10 2} :: HealthCheck) `shouldBe` False+ it "says how the mempool stands in one word, which is no check either" $ do+ let syncing = MempoolHealth {sources = 1, dirty = False, known = 60000, held = 20000, sync = MempoolSyncing}+ isOK bare {mempool = Just syncing} `shouldBe` True+ healthText bare {mempool = Just syncing}+ `shouldBe` "The store is healthy: it has every block up to height 10, with 3 peers connected. \+ \Its mempool is still syncing: it has not yet taken in all that its nodes have, \+ \and shows fewer unconfirmed transactions than its node until it has."+ mempoolText syncing `shouldSatisfy` T.isInfixOf "Its mempool is still syncing"+ -- among strangers, the store cannot tell, and says so+ mempoolText syncing {sync = MempoolUnknown} `shouldSatisfy` T.isInfixOf "cannot tell"+ mempoolText syncing {sync = MempoolSynced} `shouldSatisfy` (not . T.isInfixOf "syncing")+ -- one word in lower case each+ map A.toJSON [MempoolSyncing, MempoolSynced, MempoolUnknown]+ `shouldBe` map A.String ["syncing", "synced", "unknown"]+ forM_ [minBound .. maxBound :: MempoolSync] $ \s -> A.fromJSON (A.toJSON s) `shouldBe` A.Success s+ (A.fromJSON (A.String "full") :: A.Result MempoolSync) `shouldSatisfy` \case+ A.Error _ -> True+ A.Success _ -> False+ A.fromJSON (A.toJSON syncing) `shouldBe` A.Success syncing+ -- a store from before the field says nothing of it: unknown+ A.fromJSON (without "sync" (A.toJSON syncing)) `shouldBe` A.Success syncing {sync = MempoolUnknown}+ it "says what the operator should put right, which is no check either" $ do+ let warned = bare {warnings = ["The store lacks something"]} :: HealthCheck+ isOK warned `shouldBe` True+ healthText warned+ `shouldBe` "The store is healthy: it has every block up to height 10, with 3 peers connected. \+ \Warning: The store lacks something."+ A.fromJSON (A.toJSON warned) `shouldBe` A.Success warned+ -- a store without warnings writes no field, and one from before it has none+ without "warnings" (A.toJSON bare) `shouldBe` A.toJSON bare+ A.fromJSON (without "warnings" (A.toJSON warned)) `shouldBe` A.Success bare+ it "reads what a store wrote before the database had a check" $ do+ A.fromJSON (without "database" (A.toJSON bare {database = Just database})) `shouldBe` A.Success bare it "is fit to serve without its Redis, and says that it is without" $ do isOK bare {redis = Just False} `shouldBe` True A.toJSON bare {redis = Just False} `shouldSatisfy` \case- A.Object o -> KeyMap.lookup "redis" o == Just (A.object ["ok" A..= False])+ A.Object o -> KeyMap.lookup "redis" o == Just (A.object ["ok" A..= False, "text" A..= redisText False]) _ -> False A.toJSON bare `shouldSatisfy` \case A.Object o -> not (KeyMap.member "redis" o)@@ -203,6 +375,23 @@ === (b.confirmed == 0 && b.unconfirmed == 0 && b.utxo == 0 && b.txs == 0 && b.received == 0) .&&. nullBalance (zeroBalance b.address) + describe "Tokens" $ do+ it "are read from the script field on Bitcoin Cash only" $+ forAll arbitraryTokenData $ \t ->+ forAll arbitraryBS1 $ \lock ->+ let script = maybe B.empty (<> lock) (encodeTokenPrefix t)+ in (scriptTokens bch script, scriptTokens btc script, scriptTokens bch lock)+ === (Just t, Nothing, Nothing)+ it "are in the JSON of an output on Bitcoin Cash, with null for none" $+ forAll arbitraryTokenData $ \t ->+ let script = fromMaybe B.empty (encodeTokenPrefix t) <> "\x51"+ out s = StoreOutput {value = 1, script = s, spender = Nothing, address = Nothing}+ field net s = case marshalValue net (out s) of+ A.Object o -> KeyMap.lookup "token" o+ _ -> Nothing+ in (field bch script, field bch "\x51", field btc script)+ === (Just (A.toJSON (Just t)), Just A.Null, Nothing)+ describe "Derivation types" $ it "are named legacy, compat and segwit, and read normal as legacy" $ do map deriveTypeToText [DeriveNormal, DeriveP2SH, DeriveP2WPKH]@@ -276,11 +465,11 @@ in t.size `shouldBe` fromIntegral (B.length (runPutS (serialize grown))) -- an output has an address only where the network has that kind forM_- [ ("a SegWit output an address on Bitcoin", btc, p2wpkh, "\"bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4\""),- ("a SegWit-shaped output no address on Bitcoin Cash", bch, p2wpkh, "null"),- ("a 256-bit hash lock no address on Bitcoin", btc, hashLock, "null")+ [ ("a SegWit output an address on Bitcoin", btc, p2wpkh, "\"bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4\"", ""),+ ("a SegWit-shaped output no address on Bitcoin Cash", bch, p2wpkh, "null", ",\"token\":null"),+ ("a 256-bit hash lock no address on Bitcoin", btc, hashLock, "null", "") ]- $ \(what, net, script, addr) ->+ $ \(what, net, script, addr, token) -> it ("gives " <> what) $ outputJson net script `shouldBe` [ json@@ -288,7 +477,9 @@ <> addr <> ",\"pkscript\":\"" <> BL.fromStrict (encodeUtf8 script)- <> "\",\"value\":1000,\"spent\":false,\"spender\":null}"+ <> "\",\"value\":1000,\"spent\":false,\"spender\":null"+ <> token+ <> "}" ) ] where
test/Haskoin/Store/Gen.hs view
@@ -17,6 +17,7 @@ arbitraryEventCommand, arbitraryDeriveType, arbitraryBalance,+ arbitraryTokenBalance, arbitraryUnspent, arbitraryBlockData, arbitraryXPubBal,@@ -156,6 +157,28 @@ <$> arbitrary <*> arbitrary +instance Arbitrary DatabaseWrites where+ arbitrary = arbitraryBoundedEnum++instance Arbitrary DatabaseHealth where+ arbitrary =+ DatabaseHealth+ <$> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary++instance Arbitrary MempoolSync where+ arbitrary = arbitraryBoundedEnum++instance Arbitrary MempoolHealth where+ arbitrary = MempoolHealth <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary+ instance Arbitrary HealthCheck where arbitrary = HealthCheck@@ -168,6 +191,9 @@ <*> arbitrary <*> arbitrary <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> (map cs <$> (arbitrary :: Gen [String])) instance Arbitrary RejectCode where arbitrary =@@ -201,6 +227,18 @@ arbitraryBalance net = Balance <$> arbitraryAddress net+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary+ <*> arbitrary++arbitraryTokenBalance :: Network -> Gen TokenBalance+arbitraryTokenBalance net =+ TokenBalance+ <$> arbitraryAddress net+ <*> arbitraryTxHash+ <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
test/Haskoin/Store/RobustSpec.hs view
@@ -31,6 +31,7 @@ import Haskoin.Util.Arbitrary import Network.Socket qualified as S import Network.Socket.ByteString qualified as S+import System.IO.Temp (withSystemTempDirectory) import Test.Hspec import Test.QuickCheck (generate) @@ -42,26 +43,34 @@ failed :: Either String a -> Bool failed = either (const True) (const False) --- | A server that answers one request with these pieces, a moment apart,--- and closes. The action is given its address.-serving :: [B.ByteString] -> (String -> IO a) -> IO a+-- | A server on a Unix socket of a folder of its own that answers one+-- request with these pieces, a moment apart, and closes. The action is given+-- a client of it, for a network.+serving :: [B.ByteString] -> ((Network -> ApiConfig) -> IO a) -> IO a serving pieces go =- bracket open S.close $ \sock -> do- port <- S.socketPort sock- void . forkIO $ do- (conn, _) <- S.accept sock- void (S.recv conn 65536)- forM_ pieces $ \piece -> S.sendAll conn piece >> threadDelay 50000- S.close conn- go ("http://127.0.0.1:" <> show port <> "/")+ withSystemTempDirectory "haskoin-store-data-" $ \dir -> do+ let path = dir <> "/server.sock"+ bracket (open path) S.close $ \sock -> do+ void . forkIO $ do+ (conn, _) <- S.accept sock+ void (S.recv conn 65536)+ forM_ pieces $ \piece -> S.sendAll conn piece >> threadDelay 50000+ S.close conn+ go (\n -> ApiConfig n "http://localhost/" (Just path)) where- open = do- sock <- S.socket S.AF_INET S.Stream S.defaultProtocol- S.setSocketOption sock S.ReuseAddr 1- S.bind sock (S.SockAddrInet 0 (S.tupleToHostAddress (127, 0, 0, 1)))+ open path = do+ sock <- S.socket S.AF_UNIX S.Stream S.defaultProtocol+ S.bind sock (S.SockAddrUnix path) S.listen sock 1 return sock +-- | A client of a server that is not there: a Unix socket in a folder of+-- its own, that nothing listens on.+nowhere :: ((Network -> ApiConfig) -> IO a) -> IO a+nowhere go =+ withSystemTempDirectory "haskoin-store-data-" $ \dir ->+ go (\n -> ApiConfig n "http://localhost/" (Just (dir <> "/nothing.sock")))+ -- | The head of a response whose body comes in chunks. chunked :: B.ByteString -> B.ByteString chunked status =@@ -155,25 +164,25 @@ (a == b, compare a b == EQ) `shouldBe` (False, False) describe "Client" $ do- let nowhere = "http://127.0.0.1:1/"- segwit = fromJust (textToAddr btc "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4")+ let segwit = fromJust (textToAddr btc "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4") reason (Left (StringError why)) = why reason _ = "" it "answers an error for an address that the network cannot write" $- apiCall (ApiConfig bch nowhere) (GetAddrBalance segwit) `shouldReturn` Left (UserError "Invalid Param")- it "answers an error, and throws nothing, when there is no server" $ do- r <- apiCall (ApiConfig btc nowhere) (GetAddrBalance segwit)+ nowhere $+ \conf -> apiCall (conf bch) (GetAddrBalance segwit) `shouldReturn` Left (UserError "Invalid Param")+ it "answers an error, and throws nothing, when there is no server" $ nowhere $ \conf -> do+ r <- apiCall (conf btc) (GetAddrBalance segwit) reason r `shouldSatisfy` ("Could not reach the server" `isPrefixOf`)- e <- apiEvents (ApiConfig btc nowhere) (\_ -> return True)+ e <- apiEvents (conf btc) (\_ -> return True) reason e `shouldSatisfy` ("Could not reach the server" `isPrefixOf`)- it "ends a batch of size zero" $ do- r <- apiBatch 0 (ApiConfig btc nowhere) (GetTxs [TxHash (sha256 ("a" :: B.ByteString))])+ it "ends a batch of size zero" $ nowhere $ \conf -> do+ r <- apiBatch 0 (conf btc) (GetTxs [TxHash (sha256 ("a" :: B.ByteString))]) reason r `shouldSatisfy` ("Could not reach the server" `isPrefixOf`) it "reads an error that comes in pieces" $ do let body = BL.toStrict (A.encode ThingNotFound) (one, two) = B.splitAt 10 body- r <- serving [chunked "404 Not Found", chunk one, chunk two, "0\r\n\r\n"] $ \host ->- apiCall (ApiConfig btc host) (GetAddrBalance segwit)+ r <- serving [chunked "404 Not Found", chunk one, chunk two, "0\r\n\r\n"] $ \conf ->+ apiCall (conf btc) (GetAddrBalance segwit) r `shouldBe` Left ThingNotFound it "says the status and the start of an answer that is not from the server" $ do let page = "<html>Bad Gateway</html>"@@ -182,7 +191,7 @@ <> C.pack (show (B.length page)) <> "\r\n\r\n" <> page- r <- serving [answer] $ \host -> apiCall (ApiConfig btc host) (GetAddrBalance segwit)+ r <- serving [answer] $ \conf -> apiCall (conf btc) (GetAddrBalance segwit) r `shouldBe` Left (StringError "HTTP 502: <html>Bad Gateway</html>") it "goes on after a line of events that it does not know" $ do let one = TxHash (sha256 ("one" :: B.ByteString))@@ -196,6 +205,6 @@ chunk end, "0\r\n\r\n" ]- $ \host -> apiEvents (ApiConfig btc host) (\e -> modifyIORef' heard (<> [e]) >> return True)+ $ \conf -> apiEvents (conf btc) (\e -> modifyIORef' heard (<> [e]) >> return True) r `shouldBe` Right () readIORef heard `shouldReturn` [EventTx one, EventTx two]