haskoin-store-data 2.0.2 → 3.0.0
raw patch · 11 files changed
+553/−403 lines, 11 filesdep ~haskoin-corePVP ok
version bump matches the API change (PVP)
Dependency ranges changed: haskoin-core
API changes (from Hackage documentation)
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Store.Data.BinfoBalance
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Store.Data.BinfoBlock
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Store.Data.BinfoMempool
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Store.Data.BinfoMultiAddr
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Store.Data.BinfoRawAddr
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Store.Data.BinfoTx
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Store.Data.BinfoTxInput
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Store.Data.BinfoTxOutput
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Store.Data.BinfoUnspent
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Store.Data.BinfoUnspents
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Store.Data.BinfoXPubPath
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) Haskoin.Store.Data.EventCommand
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) [Haskoin.Store.Data.BinfoBalance]
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) [Haskoin.Store.Data.BinfoBlock]
- Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON (Haskoin.Network.Data.Network, Crypto.Secp256k1.Internal.Context.Ctx) [Haskoin.Store.Data.BinfoTx]
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Store.Data.BinfoBalance
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Store.Data.BinfoBlock
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Store.Data.BinfoMempool
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Store.Data.BinfoMultiAddr
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Store.Data.BinfoRawAddr
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Store.Data.BinfoTx
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Store.Data.BinfoTxInput
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Store.Data.BinfoTxOutput
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Store.Data.BinfoUnspent
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Store.Data.BinfoUnspents
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Store.Data.BinfoXPubPath
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network Haskoin.Store.Data.EventCommand
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network [Haskoin.Store.Data.BinfoBalance]
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network [Haskoin.Store.Data.BinfoBlock]
+ Haskoin.Store.Data: instance Haskoin.Util.Marshal.MarshalJSON Haskoin.Network.Data.Network [Haskoin.Store.Data.BinfoTx]
- Haskoin.Store.Data: parseBinfoAddr :: Network -> Ctx -> Text -> Maybe [BinfoAddr]
+ Haskoin.Store.Data: parseBinfoAddr :: Network -> Text -> Maybe [BinfoAddr]
- Haskoin.Store.Data: toTransaction :: Network -> Ctx -> TxData -> Transaction
+ Haskoin.Store.Data: toTransaction :: Network -> TxData -> Transaction
- Haskoin.Store.Data: toTransactionWithId :: Network -> Ctx -> TxHash -> TxData -> Transaction
+ Haskoin.Store.Data: toTransactionWithId :: Network -> TxHash -> TxData -> Transaction
- Haskoin.Store.WebClient: apiBatch :: Batchable a b => Ctx -> Natural -> ApiConfig -> a -> IO (Either Except b)
+ Haskoin.Store.WebClient: apiBatch :: Batchable a b => Natural -> ApiConfig -> a -> IO (Either Except b)
- Haskoin.Store.WebClient: apiCall :: ApiResource a b => Ctx -> ApiConfig -> a -> IO (Either Except b)
+ Haskoin.Store.WebClient: apiCall :: ApiResource a b => ApiConfig -> a -> IO (Either Except b)
- Haskoin.Store.WebCommon: encodeParam :: Param a => Network -> Ctx -> a -> Maybe [Text]
+ Haskoin.Store.WebCommon: encodeParam :: Param a => Network -> a -> Maybe [Text]
- Haskoin.Store.WebCommon: parseParam :: Param a => Network -> Ctx -> [Text] -> Maybe a
+ Haskoin.Store.WebCommon: parseParam :: Param a => Network -> [Text] -> Maybe a
- Haskoin.Store.WebCommon: parseResponse :: ApiResponse b => Network -> Ctx -> Value -> Parser b
+ Haskoin.Store.WebCommon: parseResponse :: ApiResponse b => Network -> Value -> Parser b
- Haskoin.Store.WebCommon: pathEncodes :: ApiResource a b => Network -> Ctx -> a -> Bool
+ Haskoin.Store.WebCommon: pathEncodes :: ApiResource a b => Network -> a -> Bool
- Haskoin.Store.WebCommon: queryPath :: ApiResource a b => Network -> Ctx -> a -> Text
+ Haskoin.Store.WebCommon: queryPath :: ApiResource a b => Network -> a -> Text
Files
- CHANGELOG.md +91/−0
- README.md +6/−5
- haskoin-store-data.cabal +3/−3
- src/Haskoin/Store/Data.hs +193/−152
- src/Haskoin/Store/WebClient.hs +24/−31
- src/Haskoin/Store/WebCommon.hs +74/−74
- test/Haskoin/Store/DataSpec.hs +31/−32
- test/Haskoin/Store/Gen.hs +45/−45
- test/Haskoin/Store/Laws.hs +39/−14
- test/Haskoin/Store/RobustSpec.hs +19/−19
- test/Haskoin/Store/WebCommonSpec.hs +28/−28
CHANGELOG.md view
@@ -4,6 +4,97 @@ 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) +## [3.0.0] - 2026-11-15++The context of libsecp256k1 (`Ctx`) is gone from the whole API. It is+global now, kept inside secp256k1-haskell 3.0.0, and haskoin-core 2.0.0+no longer takes it. This release follows them. Every program that uses+this package has to change, but only by deleting: no name was removed or+renamed, and no JSON or binary encoding changed.++### Changed+- **Breaking: depends on haskoin-core 2.0.0** and so on secp256k1-haskell+ 3.0.0.+- **Breaking: no function takes a `Ctx`.** Each lost that argument and+ kept the order of the others:+ - the client: `apiCall` and `apiBatch`;+ - the requests: `queryPath`, `pathEncodes`, and the methods+ `encodeParam` and `parseParam` of `Param` and `parseResponse` of+ `ApiResponse`;+ - the data: `toTransaction`, `toTransactionWithId` and+ `parseBinfoAddr`.+- **Breaking: the JSON instances that were `MarshalJSON (Network, Ctx)`+ are `MarshalJSON Network`**: `EventCommand`, `BinfoMultiAddr`,+ `BinfoRawAddr`, `BinfoBalance`, `[BinfoBalance]`, `BinfoUnspent`,+ `BinfoUnspents`, `BinfoBlock`, `[BinfoBlock]`, `BinfoTx`, `[BinfoTx]`,+ `BinfoTxInput`, `BinfoTxOutput`, `BinfoXPubPath` and `BinfoMempool`.+ The JSON itself is the same.+- **The records of the database are written and read through cereal+ several times faster.** The `Serialize` instances of `TxData`, `Unspent`,+ `Balance`, `BlockData`, `Spender`, `Prev`, `BlockRef`, `TxRef`, `XPubSpec`+ and `XPubBal` no longer run the `Serial` code of the type through the+ builder and the continuations of cereal, a closure for each field. They+ run it on a buffer directly, with `putDirect` and `getDirect` of+ `Haskoin.Util.Direct`, a module that haskoin-core 2.0.0 has for this.+ `Spender`, `Prev`, `BlockRef` and `TxRef` are read that way and still+ written through the builder, which is cheaper for two or three fields. The+ `Serial` methods are `INLINEABLE`, so that `encodeSerial` and+ `decodeSerial` of haskoin-core are compiled for these types too, and those+ two are the cheapest way to the bytes of one record: `encode` of cereal+ allocates a buffer of 4 kB before it writes anything. The bytes are the+ same, and so is the error for bytes that do not parse: the tests give+ cereal damaged bytes and compare. The `Serial` and `Binary` instances+ are as they were. The module is in haskoin-core from its commit+ `64a336ffd94d09a77ed8f9ab5cd3743dc4cf26d7` on.++ The timings are from a benchmark built as haskoin-store builds this+ package, with GHC 9.12.4 at `-O2` with `-fspecialise-aggressively` and+ `-fexpose-all-unfoldings`, on an AMD Ryzen 9 3900X, before this change and+ after it, each with the haskoin-core of its day. They are in+ nanoseconds, the lowest of two or three runs, with the memory that one+ call allocates. A timing moves by about a tenth from one run to the next,+ and the memory does not move.++ | ns | before | now | allocated before | now |+ | --- | ---: | ---: | ---: | ---: |+ | `TxData` of a SegWit transaction, 2 inputs and 2 outputs, `encode` | 2,440 | 626 | 14 kB | 6.0 kB |+ | `TxData` of a SegWit transaction, 2 inputs and 2 outputs, `decode` | 1,870 | 643 | 11 kB | 3.4 kB |+ | `TxData` of a SegWit transaction, 2 inputs and 2 outputs, `encodeSerial` | 2,370 | 286 | 14 kB | 903 B |+ | `TxData` of a SegWit transaction, 2 inputs and 2 outputs, `decodeSerial` | 1,740 | 633 | 11 kB | 3.3 kB |+ | `BlockData` of 3,000 transactions, `encode` | 260,000 | 37,800 | 1.5 MB | 103 kB |+ | `BlockData` of 3,000 transactions, `decode` | 246,000 | 49,600 | 1.4 MB | 291 kB |+ | `BlockData` of 3,000 transactions, `encodeSerial` | 264,000 | 31,900 | 1.5 MB | 99 kB |+ | `BlockData` of 3,000 transactions, `decodeSerial` | 264,000 | 49,000 | 1.4 MB | 291 kB |+ | `Unspent`, `encode` | 423 | 247 | 5.6 kB | 4.9 kB |+ | `Unspent`, `decode` | 228 | 64 | 1.6 kB | 463 B |+ | `Unspent`, `encodeSerial` | 432 | 39 | 5.6 kB | 231 B |+ | `Unspent`, `decodeSerial` | 238 | 55 | 1.6 kB | 383 B |+ | `Balance`, `encode` | 243 | 239 | 4.8 kB | 4.8 kB |+ | `Balance`, `decode` | 101 | 34 | 791 B | 271 B |+ | `Balance`, `encodeSerial` | 265 | 29 | 4.8 kB | 167 B |+ | `Balance`, `decodeSerial` | 111 | 23 | 815 B | 191 B |+ | `Spender`, `encode` | 239 | 211 | 4.7 kB | 4.6 kB |+ | `Spender`, `decode` | 55 | 19 | 407 B | 151 B |+ | `Spender`, `encodeSerial` | 228 | 22 | 4.6 kB | 119 B |+ | `Spender`, `decodeSerial` | 61 | 10 | 431 B | 87 B |+ | `BlockRef`, `encode` | 197 | 199 | 4.5 kB | 4.5 kB |+ | `BlockRef`, `decode` | 15 | 11 | 143 B | 111 B |+ | `BlockRef`, `encodeSerial` | 195 | 14 | 4.5 kB | 87 B |+ | `BlockRef`, `decodeSerial` | 18 | 7 | 167 B | 31 B |++### Migrating+- Delete `withContext`, `createContext` and every `ctx` you passed to this+ package: `apiCall ctx cfg req` becomes `apiCall cfg req`, and+ `toTransaction net ctx td` becomes `toTransaction net td`.+- Where you gave a pair to a JSON function, give the network:+ `marshalValue (net, ctx) x` becomes `marshalValue net x`, and the same+ for `marshalEncoding`, `unmarshalValue`, `marshalJSON` and+ `unmarshalJSON`.+- In an instance of `Param` or `ApiResponse` of your own, drop the context+ from the arguments of the methods.+- For your own use of haskoin-core, see the "Migrating" section of its+ changelog for 2.0.0.+ ## [2.0.2] - 2026-11-14 ### Added
README.md view
@@ -22,14 +22,14 @@ ```haskell import Data.Default (def)-import Haskoin (btc, textToAddr, withContext)+import Haskoin (btc, textToAddr) import Haskoin.Store.WebClient main :: IO ()-main = withContext $ \ctx -> do+main = do let cfg = def {net = btc} -- https://api.haskoin.com/btc/... Just addr = textToAddr btc "bc1q…"- r <- apiCall ctx cfg (GetAddrBalance addr)+ r <- apiCall cfg (GetAddrBalance addr) print r ``` @@ -57,7 +57,7 @@ import Haskoin.Store.Data (EventCommand (..)) -- a text frame: {"type":"watch","addresses":["bc1q…"]}-frame = marshalJSON (net, ctx) (EventWatch [addr])+frame = marshalJSON net (EventWatch [addr]) ``` Blocks are always told. A connection that has sent no command hears of@@ -83,7 +83,8 @@ 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, the binary encodings of the database round-trip and agree between Serial,-cereal and binary, and the format of the basic types is pinned.+cereal and binary, on good bytes and on bad ones, and the format of the basic+types is pinned. ## Versions
haskoin-store-data.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: haskoin-store-data-version: 2.0.2+version: 3.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 >=1.6.1 && <1.7+ , haskoin-core >=2.0.0 && <2.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 >=1.6.1 && <1.7+ , haskoin-core >=2.0.0 && <2.1 , haskoin-store-data , hspec >=2.11.18 && <2.12 , http-client >=0.7.19 && <0.8
src/Haskoin/Store/Data.hs view
@@ -21,6 +21,22 @@ -- (the @marshal@ functions of 'MarshalJSON'), since the text form of an -- address depends on the network. --+-- The binary encoding is written once for each type, in its 'Serial'+-- instance, for any monad. The server reads a record from its database for+-- every transaction, balance and unspent output that it returns, and writes+-- one for each that it imports, so the 'Serialize' instances of these types+-- do not run that code through the builder and the continuations of cereal:+-- they run it on a buffer directly, with 'putDirect' and 'getDirect' of+-- "Haskoin.Util.Direct", which give the same bytes and the same errors. The+-- smallest records, of two or three fields, are only read that way: the+-- builder writes them for less than a buffer of their own would cost. At+-- @-O2@, a transaction record is written in a quarter of the time that way+-- and read in a third of it. To write or read a record on its own,+-- 'encodeSerial' and 'decodeSerial' of haskoin-core are cheaper still,+-- because @encode@ of cereal allocates a buffer of 4 kB before it writes+-- anything. The 'Serial' methods are marked @INLINEABLE@ so that GHC can+-- compile them for those functions wherever they are called.+-- -- Types whose names start with @Binfo@ belong to the API compatible with -- Blockchain.info. -- These types live in their own package, @haskoin-store-data@, so that clients of@@ -138,7 +154,7 @@ import Control.Applicative ((<|>)) import Control.DeepSeq (NFData) import Control.Exception (Exception)-import Control.Monad (guard, join, mzero, when, unless)+import Control.Monad (guard, join, mzero, unless, when) import Data.Aeson ( FromJSON (..), ToJSON (..),@@ -198,6 +214,7 @@ import Data.Word (Word32, Word64, Word8) import GHC.Generics (Generic) import Haskoin+import Haskoin.Util.Direct (getDirect, putDirect) import Text.Read (readMaybe) -- | Type of the addresses derived from an extended public key.@@ -236,6 +253,8 @@ deriveTypeToText DeriveP2WPKH = "segwit" instance Serial DeriveType where+ {-# INLINEABLE serialize #-}+ {-# INLINEABLE deserialize #-} serialize DeriveNormal = putWord8 0x00 serialize DeriveP2SH = putWord8 0x01 serialize DeriveP2WPKH = putWord8 0x02@@ -271,6 +290,8 @@ hashWithSalt i = hashWithSalt i . (.key.key) instance Serial XPubSpec where+ {-# INLINEABLE serialize #-}+ {-# INLINEABLE deserialize #-} serialize XPubSpec {key = k, deriv = t} = do putWord8 k.depth serialize k.parent@@ -291,8 +312,8 @@ return XPubSpec {key = XPubKey {..}, deriv} instance Serialize XPubSpec where- put = serialize- get = deserialize+ put x = putDirect (serialize x)+ get = getDirect deserialize instance Binary XPubSpec where put = serialize@@ -307,10 +328,12 @@ -- | Binary such that ordering is inverted. putUnixTime :: (MonadPut m) => Word64 -> m () putUnixTime w = putWord64be $ maxBound - w+{-# INLINE putUnixTime #-} -- | Inverse of 'putUnixTime'. getUnixTime :: (MonadGet m) => m Word64 getUnixTime = (maxBound -) <$> getWord64be+{-# INLINE getUnixTime #-} -- | Reference to a block where a transaction is stored. data BlockRef@@ -329,6 +352,8 @@ -- | Serial entities will sort in reverse order. instance Serial BlockRef where+ {-# INLINEABLE serialize #-}+ {-# INLINEABLE deserialize #-} serialize MemRef {timestamp = t} = do putWord8 0x00 putUnixTime t@@ -351,7 +376,7 @@ instance Serialize BlockRef where put = serialize- get = deserialize+ get = getDirect deserialize instance Binary BlockRef where put = serialize@@ -401,6 +426,8 @@ deriving (Show, Eq, Ord, Generic, Hashable, NFData) instance Serial TxRef where+ {-# INLINEABLE serialize #-}+ {-# INLINEABLE deserialize #-} serialize (TxRef b h) = do serialize b serialize h@@ -414,7 +441,7 @@ instance Serialize TxRef where put = serialize- get = deserialize+ get = getDirect deserialize instance ToJSON TxRef where toJSON x =@@ -455,6 +482,8 @@ deriving (Show, Read, Eq, Ord, Generic, Hashable, NFData) instance Serial Balance where+ {-# INLINEABLE serialize #-}+ {-# INLINEABLE deserialize #-} serialize b = do serialize b.address putWord64be b.confirmed@@ -477,8 +506,8 @@ get = deserialize instance Serialize Balance where- put = serialize- get = deserialize+ put x = putDirect (serialize x)+ get = getDirect deserialize -- | Balance of an address that was never used. zeroBalance :: Address -> Balance@@ -552,6 +581,8 @@ deriving (Show, Eq, Ord, Generic, Hashable, NFData) instance Serial Unspent where+ {-# INLINEABLE serialize #-}+ {-# INLINEABLE deserialize #-} serialize u = do serialize u.block serialize u.outpoint@@ -572,16 +603,16 @@ get = deserialize instance Serialize Unspent where- put = serialize- get = deserialize+ put x = putDirect (serialize x)+ get = getDirect deserialize instance Coin Unspent where coinValue = (.value) coinInputKind = scriptInputKind . (.script) -- | Kind of the input that spends an output with this script, for fee--- estimation. Read from the script bytes, as no context is at hand to parse--- public keys. A script hash or witness script hash does not tell what it+-- estimation. Read from the script bytes, without parsing public keys: their+-- shape is enough to tell the kind. A script hash or witness script hash does not tell what it -- hides: they are taken for the most common single-key case, a nested -- witness public key hash and a one-of-one witness multisig. Any other -- script counts as a public key hash.@@ -687,6 +718,8 @@ deriving (Show, Read, Eq, Ord, Generic, Hashable, NFData) instance Serial BlockData where+ {-# INLINEABLE serialize #-}+ {-# INLINEABLE deserialize #-} serialize b = do putWord32be b.height serialize b.main@@ -713,8 +746,8 @@ return BlockData {..} instance Serialize BlockData where- put = serialize- get = deserialize+ put x = putDirect (serialize x)+ get = getDirect deserialize instance Binary BlockData where put = serialize@@ -912,6 +945,8 @@ deriving (Show, Read, Eq, Ord, Generic, Hashable, NFData) instance Serial Spender where+ {-# INLINEABLE serialize #-}+ {-# INLINEABLE deserialize #-} serialize s = do serialize s.txid putWord32be s.index@@ -919,7 +954,7 @@ instance Serialize Spender where put = serialize- get = deserialize+ get = getDirect deserialize instance Binary Spender where put = serialize@@ -996,6 +1031,8 @@ deriving (Show, Eq, Ord, Generic, Hashable, NFData) instance Serial Prev where+ {-# INLINEABLE serialize #-}+ {-# INLINEABLE deserialize #-} serialize p = do putLengthBytes p.script putWord64be p.value@@ -1010,18 +1047,18 @@ instance Serialize Prev where put = serialize- get = deserialize+ get = getDirect deserialize -- | Input with information about the output it spends, which is missing for a coinbase.-toInput :: Network -> Ctx -> TxIn -> Maybe Prev -> WitnessStack -> StoreInput-toInput _ _ i Nothing w =+toInput :: Network -> TxIn -> Maybe Prev -> WitnessStack -> StoreInput+toInput _ i Nothing w = StoreCoinbase { outpoint = i.outpoint, sequence = i.sequence, script = i.script, witness = w }-toInput net ctx i (Just p) w =+toInput net i (Just p) w = StoreInput { outpoint = i.outpoint, sequence = i.sequence,@@ -1029,17 +1066,17 @@ pkscript = p.script, value = p.value, witness = w,- address = eitherToMaybe (scriptToAddressBS net ctx p.script)+ address = eitherToMaybe (scriptToAddressBS net p.script) } -- | Output with its address and spender.-toOutput :: Network -> Ctx -> TxOut -> Maybe Spender -> StoreOutput-toOutput net ctx o s =+toOutput :: Network -> TxOut -> Maybe Spender -> StoreOutput+toOutput net o s = StoreOutput { value = o.value, script = o.script, spender = s,- address = eitherToMaybe (scriptToAddressBS net ctx o.script)+ address = eitherToMaybe (scriptToAddressBS net o.script) } -- | Transaction as stored in the database.@@ -1062,6 +1099,8 @@ deriving (Show, Eq, Ord, Generic, NFData) instance Serial TxData where+ {-# INLINEABLE serialize #-}+ {-# INLINEABLE deserialize #-} serialize t = do serialize t.block serialize t.tx@@ -1081,8 +1120,8 @@ return TxData {..} instance Serialize TxData where- put = serialize- get = deserialize+ put x = putDirect (serialize x)+ get = getDirect deserialize instance Binary TxData where put = serialize@@ -1139,8 +1178,8 @@ -- Cash, for example. The id is the hash of the transaction without its -- witness; where it is known, as it is for a transaction read by its id, -- 'toTransactionWithId' saves serializing and hashing the transaction.-toTransaction :: Network -> Ctx -> TxData -> Transaction-toTransaction net ctx t = toTransactionWithId net ctx (txHash t.tx) t+toTransaction :: Network -> TxData -> Transaction+toTransaction net t = toTransactionWithId net (txHash t.tx) t -- | 'toTransaction' for a transaction whose id is known, given here. It -- serializes nothing: the size and the weight are counted from the lengths@@ -1148,8 +1187,8 @@ -- transaction took a quarter of the time of building its API form, for -- bytes that the store had just read. The id is taken as given, so it has -- to be the id of the transaction.-toTransactionWithId :: Network -> Ctx -> TxHash -> TxData -> Transaction-toTransactionWithId net ctx txid t =+toTransactionWithId :: Network -> TxHash -> TxData -> Transaction+toTransactionWithId net txid t = Transaction { version = t.tx.version, locktime = t.tx.locktime,@@ -1173,8 +1212,8 @@ inv = sum (map (.value) ins) outs = zipWith g [0 ..] t.tx.outputs outv = sum $ map (.value) outs- f n i w = toInput net ctx i (IntMap.lookup n t.prevs) w- g n o = toOutput net ctx o $ IntMap.lookup n t.spenders+ f n i w = toInput net i (IntMap.lookup n t.prevs) w+ g n o = toOutput net o $ IntMap.lookup n t.spenders -- | The length of a transaction serialized, and its length without the -- witness, counted from the lengths of its parts as 'serialize' writes@@ -1385,6 +1424,8 @@ deriving (Show, Ord, Eq, Generic, NFData) instance Serial XPubBal where+ {-# INLINEABLE serialize #-}+ {-# INLINEABLE deserialize #-} serialize b = do putList putWord32be b.path serialize b.balance@@ -1394,8 +1435,8 @@ return XPubBal {..} instance Serialize XPubBal where- put = serialize- get = deserialize+ put x = putDirect (serialize x)+ get = getDirect deserialize instance Binary XPubBal where put = serialize@@ -1812,10 +1853,10 @@ | B.length d > maxFilterAddSize = fail "Filter element too long" | otherwise = return d --- | The text of an address depends on the network, and that of an extended--- public key needs the context of the library that checks it.-instance MarshalJSON (Network, Ctx) EventCommand where- marshalValue (net, ctx) = \case+-- | The text of an address and that of an extended public key depend on the+-- network.+instance MarshalJSON Network EventCommand where+ marshalValue net = \case EventWatch as -> addresses "watch" as EventUnwatch as -> addresses "unwatch" as EventWatchXPub x -> xpub "watch" x@@ -1839,11 +1880,11 @@ xpub t x = A.object [ "type" .= String t,- "xpub" .= marshalValue (net, ctx) x.key,+ "xpub" .= marshalValue net x.key, "derive" .= deriveTypeToText x.deriv ] - unmarshalValue (net, ctx) =+ unmarshalValue net = A.withObject "EventCommand" $ \o -> o .: "type" >>= \case "watch" -> watched o EventWatch EventWatchXPub@@ -1866,7 +1907,7 @@ watched o as xs = o .:? "xpub" >>= \case Just v -> do- key <- unmarshalValue (net, ctx) v+ key <- unmarshalValue net v name <- o .:? "derive" .!= "legacy" deriv <- maybe (fail "Unknown derivation") return (textToDeriveType name) return $ xs XPubSpec {..}@@ -2178,12 +2219,12 @@ } deriving (Eq, Show, Generic, NFData) -instance MarshalJSON (Network, Ctx) BinfoMultiAddr where- marshalValue (net', ctx) m =+instance MarshalJSON Network BinfoMultiAddr where+ marshalValue net' m = A.object $- [ "addresses" .= map (marshalValue (net, ctx)) m.addresses,+ [ "addresses" .= map (marshalValue net) m.addresses, "wallet" .= m.wallet,- "txs" .= map (marshalValue (net, ctx)) m.txs,+ "txs" .= map (marshalValue net) m.txs, "info" .= m.info, "recommend_include_fee" .= m.recommendFee ]@@ -2191,22 +2232,22 @@ where net = if not m.cashAddr && net' == bch then btc else net' - unmarshalValue (net, ctx) =+ unmarshalValue net = A.withObject "BinfoMultiAddr" $ \o -> do- addresses <- mapM (unmarshalValue (net, ctx)) =<< o .: "addresses"+ addresses <- mapM (unmarshalValue net) =<< o .: "addresses" wallet <- o .: "wallet"- txs <- mapM (unmarshalValue (net, ctx)) =<< o .: "txs"+ txs <- mapM (unmarshalValue net) =<< o .: "txs" info <- o .: "info" recommendFee <- o .: "recommend_include_fee" cashAddr <- o .:? "cash_addr" .!= False return BinfoMultiAddr {..} - marshalEncoding (net', ctx) m =+ marshalEncoding net' m = A.pairs $ mconcat- [ "addresses" `A.pair` A.list (marshalEncoding (net, ctx)) m.addresses,+ [ "addresses" `A.pair` A.list (marshalEncoding net) m.addresses, "wallet" `A.pair` toEncoding m.wallet,- "txs" `A.pair` A.list (marshalEncoding (net, ctx)) m.txs,+ "txs" `A.pair` A.list (marshalEncoding net) m.txs, "info" `A.pair` toEncoding m.info, "recommend_include_fee" `A.pair` A.bool m.recommendFee, if m.cashAddr then "cash_addr" `A.pair` A.bool True else mempty@@ -2233,8 +2274,8 @@ } deriving (Eq, Show, Generic, NFData) -instance MarshalJSON (Network, Ctx) BinfoRawAddr where- marshalValue (net, ctx) r =+instance MarshalJSON Network BinfoRawAddr where+ marshalValue net r = A.object [ "hash160" .= h160, "address" .= address,@@ -2243,19 +2284,19 @@ "total_received" .= r.received, "total_sent" .= r.sent, "final_balance" .= r.balance,- "txs" .= map (marshalValue (net, ctx)) r.txs+ "txs" .= map (marshalValue net) r.txs ] where address = case r.address of BinfoAddr a -> marshalValue net a- BinfoXpub x -> marshalValue (net, ctx) x+ BinfoXpub x -> marshalValue net x h160 = encodeHex . runPutS . serialize <$> case r.address of BinfoAddr a -> addressHash160 a _ -> Nothing - marshalEncoding (net, ctx) r =+ marshalEncoding net r = A.pairs $ mconcat [ "hash160" `A.pair` fromMaybe A.null_ h160,@@ -2265,30 +2306,30 @@ "total_received" `A.pair` A.word64 r.received, "total_sent" `A.pair` A.int64 r.sent, "final_balance" `A.pair` A.word64 r.balance,- "txs" `A.pair` A.list (marshalEncoding (net, ctx)) r.txs+ "txs" `A.pair` A.list (marshalEncoding net) r.txs ] where address = case r.address of BinfoAddr a -> marshalEncoding net a- BinfoXpub x -> marshalEncoding (net, ctx) x+ BinfoXpub x -> marshalEncoding net x h160 = hexEncoding . runPutL . serialize <$> case r.address of BinfoAddr a -> addressHash160 a _ -> Nothing - unmarshalValue (net, ctx) =+ unmarshalValue net = A.withObject "BinfoRawAddr" $ \o -> do addr <- o .: "address" address <- BinfoAddr <$> unmarshalValue net addr- <|> BinfoXpub <$> unmarshalValue (net, ctx) addr+ <|> BinfoXpub <$> unmarshalValue net addr balance <- o .: "final_balance" utxo <- o .: "n_unredeemed" ntx <- o .: "n_tx" received <- o .: "total_received" sent <- o .: "total_sent"- txs <- mapM (unmarshalValue (net, ctx)) =<< o .: "txs"+ txs <- mapM (unmarshalValue net) =<< o .: "txs" return BinfoRawAddr {..} -- | Balance of an address or xpub in @\/blockchain\/balance@.@@ -2359,8 +2400,8 @@ } deriving (Eq, Show, Generic, NFData) -instance MarshalJSON (Network, Ctx) BinfoBalance where- marshalValue (net, _ctx) b@BinfoAddrBalance {} =+instance MarshalJSON Network BinfoBalance where+ marshalValue net b@BinfoAddrBalance {} = A.object [ "address" .= marshalValue net b.address, "final_balance" .= b.balance,@@ -2368,9 +2409,9 @@ "total_received" .= b.received, "total_sent" .= b.sent ]- marshalValue (net, ctx) b@BinfoXPubBalance {} =+ marshalValue net b@BinfoXPubBalance {} = A.object- [ "address" .= marshalValue (net, ctx) b.xpub,+ [ "address" .= marshalValue net b.xpub, "change_index" .= b.change, "account_index" .= b.external, "final_balance" .= b.balance,@@ -2379,11 +2420,11 @@ "total_sent" .= b.sent ] - unmarshalValue (net, ctx) =+ unmarshalValue net = A.withObject "BinfoBalance" $ \o -> x o <|> a o where x o = do- xpub <- unmarshalValue (net, ctx) =<< o .: "address"+ xpub <- unmarshalValue net =<< o .: "address" change <- o .: "change_index" external <- o .: "account_index" balance <- o .: "final_balance"@@ -2399,7 +2440,7 @@ sent <- o .: "total_sent" return BinfoAddrBalance {..} - marshalEncoding (net, _ctx) b@BinfoAddrBalance {} =+ marshalEncoding net b@BinfoAddrBalance {} = A.pairs $ mconcat [ "address" `A.pair` marshalEncoding net b.address,@@ -2408,10 +2449,10 @@ "total_received" `A.pair` A.word64 b.received, "total_sent" `A.pair` A.word64 b.sent ]- marshalEncoding (net, ctx) b@BinfoXPubBalance {} =+ marshalEncoding net b@BinfoXPubBalance {} = A.pairs $ mconcat- [ "address" `A.pair` marshalEncoding (net, ctx) b.xpub,+ [ "address" `A.pair` marshalEncoding net b.xpub, "change_index" `A.pair` A.word32 b.change, "account_index" `A.pair` A.word32 b.external, "final_balance" `A.pair` A.word64 b.balance,@@ -2420,14 +2461,14 @@ "total_sent" `A.pair` A.word64 b.sent ] -instance MarshalJSON (Network, Ctx) [BinfoBalance] where- marshalValue (net, ctx) addrs =- toJSON $ map (marshalValue (net, ctx)) addrs- marshalEncoding (net, ctx) =- A.list (marshalEncoding (net, ctx))- unmarshalValue (net, ctx) =+instance MarshalJSON Network [BinfoBalance] where+ marshalValue net addrs =+ toJSON $ map (marshalValue net) addrs+ marshalEncoding net =+ A.list (marshalEncoding net)+ unmarshalValue net = A.withArray "[BinfoBalance]" $- fmap V.toList . mapM (unmarshalValue (net, ctx))+ fmap V.toList . mapM (unmarshalValue net) -- | Totals of all addresses and xpubs in @\/blockchain\/multiaddr@. data BinfoWallet = BinfoWallet@@ -2505,8 +2546,8 @@ } deriving (Eq, Show, Generic, NFData) -instance MarshalJSON (Network, Ctx) BinfoUnspent where- marshalValue (net, ctx) u =+instance MarshalJSON Network BinfoUnspent where+ marshalValue net u = A.object $ [ "tx_hash_big_endian" .= u.txid, "tx_hash" .= encodeHex (runPutS (serialize u.txid.get)),@@ -2517,11 +2558,11 @@ "confirmations" .= u.confirmations, "tx_index" .= u.txidx ]- <> [ "xpub" .= marshalValue (net, ctx) x+ <> [ "xpub" .= marshalValue net x | x <- maybeToList u.xpub ] - marshalEncoding (net, ctx) u =+ marshalEncoding net u = A.pairs $ mconcat [ "tx_hash_big_endian" `A.pair` toEncoding u.txid,@@ -2532,10 +2573,10 @@ "value_hex" `A.pair` A.text (binfoHexValue u.value), "confirmations" `A.pair` A.int32 u.confirmations, "tx_index" `A.pair` toEncoding u.txidx,- maybe mempty (("xpub" `A.pair`) . marshalEncoding (net, ctx)) u.xpub+ maybe mempty (("xpub" `A.pair`) . marshalEncoding net) u.xpub ] - unmarshalValue (net, ctx) =+ unmarshalValue net = A.withObject "BinfoUnspent" $ \o -> do txid <- o .: "tx_hash_big_endian" index <- o .: "tx_output_n"@@ -2543,7 +2584,7 @@ value <- o .: "value" confirmations <- o .: "confirmations" txidx <- o .: "tx_index"- xpub <- mapM (unmarshalValue (net, ctx)) =<< o .:? "xpub"+ xpub <- mapM (unmarshalValue net) =<< o .:? "xpub" return BinfoUnspent {..} -- | Response of @\/blockchain\/unspent@.@@ -2551,23 +2592,23 @@ deriving stock (Eq, Show, Generic) deriving anyclass (NFData) -instance MarshalJSON (Network, Ctx) BinfoUnspents where- marshalValue (net, ctx) (BinfoUnspents us) =+instance MarshalJSON Network BinfoUnspents where+ marshalValue net (BinfoUnspents us) = A.object [ "notice" .= T.empty,- "unspent_outputs" .= map (marshalValue (net, ctx)) us+ "unspent_outputs" .= map (marshalValue net) us ] - marshalEncoding (net, ctx) (BinfoUnspents us) =+ marshalEncoding net (BinfoUnspents us) = A.pairs $ mconcat [ "notice" `A.pair` A.text T.empty,- "unspent_outputs" `A.pair` A.list (marshalEncoding (net, ctx)) us+ "unspent_outputs" `A.pair` A.list (marshalEncoding net) us ] - unmarshalValue (net, ctx) =+ unmarshalValue net = A.withObject "BinfoUnspents" $ \o -> do- us <- mapM (unmarshalValue (net, ctx)) =<< o .: "unspent_outputs"+ us <- mapM (unmarshalValue net) =<< o .: "unspent_outputs" return (BinfoUnspents us) -- | Block in the Blockchain.info format, from its data, its transactions and the hashes of its children.@@ -2629,8 +2670,8 @@ } deriving (Eq, Show, Generic, NFData) -instance MarshalJSON (Network, Ctx) BinfoBlock where- marshalValue (net, ctx) b =+instance MarshalJSON Network BinfoBlock where+ marshalValue net b = A.object [ "hash" .= b.hash, "ver" .= b.version,@@ -2647,10 +2688,10 @@ "main_chain" .= b.main, "height" .= b.height, "weight" .= b.weight,- "tx" .= map (marshalValue (net, ctx)) b.txs+ "tx" .= map (marshalValue net) b.txs ] - marshalEncoding (net, ctx) b =+ marshalEncoding net b = A.pairs $ mconcat [ "hash" `A.pair` toEncoding b.hash,@@ -2668,10 +2709,10 @@ "main_chain" `A.pair` A.bool b.main, "height" `A.pair` A.word32 b.height, "weight" `A.pair` A.word32 b.weight,- "tx" `A.pair` A.list (marshalEncoding (net, ctx)) b.txs+ "tx" `A.pair` A.list (marshalEncoding net) b.txs ] - unmarshalValue (net, ctx) =+ unmarshalValue net = A.withObject "BinfoBlock" $ \o -> do hash <- o .: "hash" version <- o .: "ver"@@ -2688,19 +2729,19 @@ main <- o .: "main_chain" height <- o .: "height" weight <- o .: "weight"- txs <- o .: "tx" >>= mapM (unmarshalValue (net, ctx))+ txs <- o .: "tx" >>= mapM (unmarshalValue net) return BinfoBlock {..} -instance MarshalJSON (Network, Ctx) [BinfoBlock] where- marshalValue (net, ctx) blocks =- A.object ["blocks" .= map (marshalValue (net, ctx)) blocks]+instance MarshalJSON Network [BinfoBlock] where+ marshalValue net blocks =+ A.object ["blocks" .= map (marshalValue net) blocks] - marshalEncoding (net, ctx) blocks =- A.pairs $ "blocks" `A.pair` A.list (marshalEncoding (net, ctx)) blocks+ marshalEncoding net blocks =+ A.pairs $ "blocks" `A.pair` A.list (marshalEncoding net) blocks - unmarshalValue (net, ctx) =+ unmarshalValue net = A.withObject "blocks" $ \o ->- mapM (unmarshalValue (net, ctx)) =<< o .: "blocks"+ mapM (unmarshalValue net) =<< o .: "blocks" -- | Transaction in the Blockchain.info format. data BinfoTx = BinfoTx@@ -2744,8 +2785,8 @@ } deriving (Eq, Show, Generic, NFData) -instance MarshalJSON (Network, Ctx) BinfoTx where- marshalValue (net, ctx) t =+instance MarshalJSON Network BinfoTx where+ marshalValue net t = A.object $ [ "hash" .= t.txid, "ver" .= t.version,@@ -2761,8 +2802,8 @@ "time" .= t.timestamp, "block_index" .= t.blockIndex, "block_height" .= t.blockHeight,- "inputs" .= map (marshalValue (net, ctx)) t.inputs,- "out" .= map (marshalValue (net, ctx)) t.outputs+ "inputs" .= map (marshalValue net) t.inputs,+ "out" .= map (marshalValue net) t.outputs ] ++ bal ++ rbf@@ -2773,7 +2814,7 @@ Just (r, b) -> ["result" .= r, "balance" .= b] rbf = ["rbf" .= True | t.rbf] - marshalEncoding (net, ctx) t =+ marshalEncoding net t = A.pairs $ mconcat [ "hash" `A.pair` toEncoding t.txid,@@ -2790,8 +2831,8 @@ "time" `A.pair` A.word64 t.timestamp, "block_index" `A.pair` toEncoding t.blockIndex, "block_height" `A.pair` maybe A.null_ A.word32 t.blockHeight,- "inputs" `A.pair` A.list (marshalEncoding (net, ctx)) t.inputs,- "out" `A.pair` A.list (marshalEncoding (net, ctx)) t.outputs,+ "inputs" `A.pair` A.list (marshalEncoding net) t.inputs,+ "out" `A.pair` A.list (marshalEncoding net) t.outputs, bal, rbf ]@@ -2803,7 +2844,7 @@ "result" `A.pair` A.int64 r <> "balance" `A.pair` A.int64 b rbf = if t.rbf then "rbf" .= True else mempty - unmarshalValue (net, ctx) = A.withObject "BinfoTx" $ \o -> do+ unmarshalValue net = A.withObject "BinfoTx" $ \o -> do txid <- o .: "hash" version <- o .: "ver" inputCount <- o .: "vin_sz"@@ -2818,22 +2859,22 @@ timestamp <- o .: "time" blockIndex <- o .: "block_index" blockHeight <- o .: "block_height"- inputs <- o .: "inputs" >>= mapM (unmarshalValue (net, ctx))- outputs <- o .: "out" >>= mapM (unmarshalValue (net, ctx))+ inputs <- o .: "inputs" >>= mapM (unmarshalValue net)+ outputs <- o .: "out" >>= mapM (unmarshalValue net) rbf <- o .:? "rbf" .!= False res <- o .:? "result" bal <- o .:? "balance" let balance = (,) <$> res <*> bal return BinfoTx {..} -instance MarshalJSON (Network, Ctx) [BinfoTx] where- marshalValue (net, ctx) txs =- toJSON $ map (marshalValue (net, ctx)) txs- marshalEncoding (net, ctx) =- A.list (marshalEncoding (net, ctx))- unmarshalValue (net, ctx) =+instance MarshalJSON Network [BinfoTx] where+ marshalValue net txs =+ toJSON $ map (marshalValue net) txs+ marshalEncoding net =+ A.list (marshalEncoding net)+ unmarshalValue net = A.withArray "[BinfoTx]" $- fmap V.toList . mapM (unmarshalValue (net, ctx))+ fmap V.toList . mapM (unmarshalValue net) -- | Transaction input in the Blockchain.info format. data BinfoTxInput = BinfoTxInput@@ -2850,27 +2891,27 @@ } deriving (Eq, Show, Generic, NFData) -instance MarshalJSON (Network, Ctx) BinfoTxInput where- marshalValue (net, ctx) i =+instance MarshalJSON Network BinfoTxInput where+ marshalValue net i = A.object [ "sequence" .= i.sequence, "witness" .= encodeHex i.witness, "script" .= encodeHex i.script, "index" .= i.index,- "prev_out" .= marshalValue (net, ctx) i.output+ "prev_out" .= marshalValue net i.output ] - marshalEncoding (net, ctx) i =+ marshalEncoding net i = A.pairs $ mconcat [ "sequence" `A.pair` A.word32 i.sequence, "witness" `A.pair` hexEncoding (B.fromStrict i.witness), "script" `A.pair` hexEncoding (B.fromStrict i.script), "index" `A.pair` A.word32 i.index,- "prev_out" `A.pair` marshalEncoding (net, ctx) i.output+ "prev_out" `A.pair` marshalEncoding net i.output ] - unmarshalValue (net, ctx) =+ unmarshalValue net = A.withObject "BinfoTxInput" $ \o -> do sequence <- o .: "sequence" witness <-@@ -2882,7 +2923,7 @@ index <- o .: "index" output <- o .: "prev_out"- >>= unmarshalValue (net, ctx)+ >>= unmarshalValue net return BinfoTxInput {..} -- | Transaction output in the Blockchain.info format.@@ -2908,8 +2949,8 @@ } deriving (Eq, Show, Generic, NFData) -instance MarshalJSON (Network, Ctx) BinfoTxOutput where- marshalValue (net, ctx) o =+instance MarshalJSON Network BinfoTxOutput where+ marshalValue net o = A.object $ [ "type" .= o.typ, "spent" .= o.spent,@@ -2922,11 +2963,11 @@ <> [ "addr" .= marshalValue net a | a <- maybeToList o.address ]- <> [ "xpub" .= marshalValue (net, ctx) x+ <> [ "xpub" .= marshalValue net x | x <- maybeToList o.xpub ] - marshalEncoding (net, ctx) o =+ marshalEncoding net o = A.pairs $ mconcat $ [ "type" `A.pair` A.int o.typ,@@ -2940,11 +2981,11 @@ <> [ "addr" `A.pair` marshalEncoding net a | a <- maybeToList o.address ]- <> [ "xpub" `A.pair` marshalEncoding (net, ctx) x+ <> [ "xpub" `A.pair` marshalEncoding net x | x <- maybeToList o.xpub ] - unmarshalValue (net, ctx) =+ unmarshalValue net = A.withObject "BinfoTxOutput" $ \o -> do typ <- o .: "type" spent <- o .: "spent"@@ -2954,7 +2995,7 @@ txidx <- o .: "tx_index" script <- maybe mzero return . decodeHex =<< o .: "script" address <- o .:? "addr" >>= mapM (unmarshalValue net)- xpub <- o .:? "xpub" >>= mapM (unmarshalValue (net, ctx))+ xpub <- o .:? "xpub" >>= mapM (unmarshalValue net) return BinfoTxOutput {..} -- | Input that spends an output, in the Blockchain.info format.@@ -3010,23 +3051,23 @@ b.key.key.get ) -instance MarshalJSON (Network, Ctx) BinfoXPubPath where- marshalValue (net, ctx) p =+instance MarshalJSON Network BinfoXPubPath where+ marshalValue net p = A.object- [ "m" .= marshalValue (net, ctx) p.key,+ [ "m" .= marshalValue net p.key, "path" .= ("M" ++ pathToStr p.deriv) ] - marshalEncoding (net, ctx) p =+ marshalEncoding net p = A.pairs $ mconcat- [ "m" `A.pair` marshalEncoding (net, ctx) p.key,+ [ "m" `A.pair` marshalEncoding net p.key, "path" `A.pair` A.string ("M" ++ pathToStr p.deriv) ] - unmarshalValue (net, ctx) =+ unmarshalValue net = A.withObject "BinfoXPubPath" $ \o -> do- key <- o .: "m" >>= unmarshalValue (net, ctx)+ key <- o .: "m" >>= unmarshalValue net deriv <- o .: "path" >>= \t -> maybe (fail ("Not a derivation path: " <> t)) return (parseSoft t) return BinfoXPubPath {..} @@ -3639,15 +3680,15 @@ deriving (Eq, Show, Generic, Hashable, NFData) -- | Parse addresses and xpubs separated by pipes or commas. Returns 'Nothing' if any is invalid.-parseBinfoAddr :: Network -> Ctx -> Text -> Maybe [BinfoAddr]-parseBinfoAddr _net _ctx "" = Just []-parseBinfoAddr net ctx s =+parseBinfoAddr :: Network -> Text -> Maybe [BinfoAddr]+parseBinfoAddr _net "" = Just []+parseBinfoAddr net s = mapM f $ concatMap (filter (not . T.null) . T.splitOn ",") (T.splitOn "|" s) where f x = BinfoAddr <$> textToAddr net x- <|> BinfoXpub <$> xPubImport net ctx x+ <|> BinfoXpub <$> xPubImport net x -- | Block header with its transactions in the Blockchain.info format. data BinfoHeader = BinfoHeader@@ -3698,16 +3739,16 @@ deriving stock (Eq, Show, Generic) deriving anyclass (NFData) -instance MarshalJSON (Network, Ctx) BinfoMempool where- marshalValue (net, ctx) (BinfoMempool txs) =- A.object ["txs" .= map (marshalValue (net, ctx)) txs]+instance MarshalJSON Network BinfoMempool where+ marshalValue net (BinfoMempool txs) =+ A.object ["txs" .= map (marshalValue net) txs] - marshalEncoding (net, ctx) (BinfoMempool txs) =- A.pairs $ A.pair "txs" $ A.list (marshalEncoding (net, ctx)) txs+ marshalEncoding net (BinfoMempool txs) =+ A.pairs $ A.pair "txs" $ A.list (marshalEncoding net) txs - unmarshalValue (net, ctx) =+ unmarshalValue net = A.withObject "BinfoMempool" $ \o ->- BinfoMempool <$> (mapM (unmarshalValue (net, ctx)) =<< o .: "txs")+ BinfoMempool <$> (mapM (unmarshalValue net) =<< o .: "txs") -- | List of short block information. newtype BinfoBlockInfos = BinfoBlockInfos {get :: [BinfoBlockInfo]}
src/Haskoin/Store/WebClient.hs view
@@ -16,8 +16,8 @@ -- @ -- import Data.Default (def) ----- balance :: Ctx -> Address -> IO (Either Except Balance)--- balance ctx addr = 'apiCall' ctx def ('GetAddrBalance' addr)+-- balance :: Address -> IO (Either Except Balance)+-- balance addr = 'apiCall' def ('GetAddrBalance' addr) -- @ -- -- Requests that take long lists of addresses, transactions or blocks can be@@ -104,7 +104,6 @@ import Data.Text qualified as Text import Data.Text.Encoding qualified as Text import Haskoin.Block (blockHashToHex)-import Haskoin.Crypto (Ctx) import Haskoin.Network import Haskoin.Store.Data qualified as Store import Haskoin.Store.WebCommon@@ -145,11 +144,11 @@ -- -- Usage (default options): ----- > apiCall ctx def $ GetAddrsTxs addrs def+-- > apiCall def $ GetAddrsTxs addrs def -- -- With options: ----- > apiCall ctx def $ GetAddrsUnspent addrs def {limit = Just 10}+-- > apiCall def $ GetAddrsUnspent addrs def {limit = Just 10} -- -- Only @GET@ and @POST@ endpoints are supported. The result is the error -- that the server answered with, or the response. A request that could@@ -157,44 +156,42 @@ -- the reason): no exception of the HTTP client leaves this function. apiCall :: (ApiResource a b) =>- Ctx -> ApiConfig -> a -> IO (Either Store.Except b)-apiCall ctx (ApiConfig net apiHost) res =- case toOptions net ctx res of+apiCall (ApiConfig net apiHost) res =+ case toOptions net res of Left e -> return (Left e) -- as for a parameter of the query string that cannot be written- Right _ | not (pathEncodes net ctx res) -> return (Left (Store.UserError "Invalid Param"))+ Right _ | not (pathEncodes net res) -> return (Left (Store.UserError "Invalid Param")) Right args ->- let url = apiHost <> net.name <> cs (queryPath net ctx res)+ let url = apiHost <> net.name <> cs (queryPath net res) in case resourceMethod $ asProxy res of- GET -> getJSON net ctx args url+ GET -> getJSON net args url POST -> case resourceBody res of- Just (PostBox body) -> postJSON net ctx args url body+ Just (PostBox body) -> postJSON net args url body _ -> return . Left $ Store.StringError "Could not post resource" _ -> return . Left $ Store.StringError "Unsupported HTTP method" -- | Batch commands that have a large list of arguments: ----- > apiBatch ctx 20 def (GetAddrsTxs addrs def)+-- > apiBatch 20 def (GetAddrsTxs addrs def) -- -- The list is split into chunks of the given size, one call is made per chunk, -- and the results are concatenated. The calls stop at the first error. A -- size of zero is taken for one. apiBatch :: (Batchable a b) =>- Ctx -> Natural -> ApiConfig -> a -> IO (Either Store.Except b)-apiBatch ctx i conf res = go mempty (resourceBatch i res)+apiBatch i conf res = go mempty (resourceBatch i res) where go acc [] = return (Right acc) go acc (r : rs) =- apiCall ctx conf r >>= \case+ apiCall conf r >>= \case Left e -> return (Left e) Right b -> go (acc <> b) rs @@ -312,25 +309,23 @@ toOptions :: (ApiResource a b) => Network ->- Ctx -> a -> Either Store.Except (Endo HTTP.Options)-toOptions net ctx res =+toOptions net res = mconcat <$> mapM f (snd $ queryParams res) where- f (ParamBox p) = toOption net ctx p+ f (ParamBox p) = toOption net p -- | HTTP option for one query string parameter. toOption :: (Param a) => Network ->- Ctx -> a -> Either Store.Except (Endo HTTP.Options)-toOption net ctx a = do+toOption net a = do res <- maybeToEither (Store.UserError "Invalid Param") $- encodeParam net ctx a+ encodeParam net a return $ applyOpt (paramLabel a) res -- | Set a query string parameter to comma-separated values.@@ -341,26 +336,24 @@ getJSON :: (ApiResponse a) => Network ->- Ctx -> Endo HTTP.Options -> String -> IO (Either Store.Except a)-getJSON net ctx opts url = do+getJSON net opts url = do r <- reaching (HTTP.getWith (jsonOpts opts) url)- return (r >>= readResponse net ctx)+ return (r >>= readResponse net) -- | Make a @POST@ request with a body of text and read the JSON response. postJSON :: (ApiResponse a) => Network ->- Ctx -> Endo HTTP.Options -> String -> Text -> IO (Either Store.Except a)-postJSON net ctx opts url body = do+postJSON net opts url body = do r <- reaching (HTTP.postWith (jsonOpts opts) url (Raw "text/plain" (RequestBodyBS (Text.encodeUtf8 body))))- return (r >>= readResponse net ctx)+ return (r >>= readResponse net) -- | Make a request, and give the error that the server answered with -- ('checkStatus'), or the reason why there was no answer, as a value. A@@ -375,9 +368,9 @@ unreached (InvalidUrlException url why) = Store.StringError ("Not a URL: " <> url <> ": " <> why) -- | Read a response from the JSON of its body.-readResponse :: (ApiResponse a) => Network -> Ctx -> HTTP.Response BSL.ByteString -> Either Store.Except a-readResponse net ctx res =- case A.eitherDecode (res ^. HTTP.responseBody) >>= A.parseEither (parseResponse net ctx) of+readResponse :: (ApiResponse a) => Network -> HTTP.Response BSL.ByteString -> Either Store.Except a+readResponse net res =+ case A.eitherDecode (res ^. HTTP.responseBody) >>= A.parseEither (parseResponse net) of Left e -> Left (Store.StringError ("Could not read the response: " <> e)) Right a -> Right a
src/Haskoin/Store/WebCommon.hs view
@@ -96,8 +96,8 @@ import Data.Aeson.Types qualified as A import Data.Bytes.Put (runPutS) import Data.Bytes.Serial-import Data.Foldable (toList) import Data.Default (Default, def)+import Data.Foldable (toList) import Data.Proxy (Proxy (..)) import Data.String.Conversions (cs) import Data.Text (Text)@@ -109,7 +109,7 @@ blockHashToHex, hexToBlockHash, )-import Haskoin.Crypto (Ctx, Hash256)+import Haskoin.Crypto (Hash256) import Haskoin.Crypto.Keys import Haskoin.Network.Data import Haskoin.Store.Data qualified as Store@@ -155,65 +155,65 @@ -- -- The API speaks JSON only. Many responses hold addresses, whose text -- depends on the network ('MarshalJSON'), so the reader is given the--- network and the context, and a type that needs neither ignores them.--- A class of its own, rather than @MarshalJSON (Network, Ctx)@, lets each+-- network, and a type that does not need it ignores it.+-- A class of its own, rather than @MarshalJSON Network@, lets each -- response say which of its JSON instances to use, without new instances -- on the data types. class ApiResponse b where -- | Read a response from its JSON.- parseResponse :: Network -> Ctx -> A.Value -> A.Parser b+ parseResponse :: Network -> A.Value -> A.Parser b instance ApiResponse Store.BlockData where- parseResponse net _ = unmarshalValue net+ parseResponse net = unmarshalValue net instance ApiResponse Store.Transaction where- parseResponse net _ = unmarshalValue net+ parseResponse net = unmarshalValue net instance ApiResponse Store.Balance where- parseResponse net _ = unmarshalValue net+ parseResponse net = unmarshalValue net instance ApiResponse Store.Unspent where- parseResponse net _ = unmarshalValue net+ parseResponse net = unmarshalValue net instance ApiResponse Store.XPubBal where- parseResponse net _ = unmarshalValue net+ parseResponse net = unmarshalValue net instance ApiResponse Store.XPubUnspent where- parseResponse net _ = unmarshalValue net+ parseResponse net = unmarshalValue net instance ApiResponse Store.TxRef where- parseResponse _ _ = A.parseJSON+ parseResponse _ = A.parseJSON instance ApiResponse Store.XPubSummary where- parseResponse _ _ = A.parseJSON+ parseResponse _ = A.parseJSON instance ApiResponse Store.PeerInfo where- parseResponse _ _ = A.parseJSON+ parseResponse _ = A.parseJSON instance ApiResponse Store.HealthCheck where- parseResponse _ _ = A.parseJSON+ parseResponse _ = A.parseJSON instance ApiResponse Store.TxId where- parseResponse _ _ = A.parseJSON+ parseResponse _ = A.parseJSON instance ApiResponse Store.Event where- parseResponse _ _ = A.parseJSON+ parseResponse _ = A.parseJSON instance ApiResponse TxHash where- parseResponse _ _ = A.parseJSON+ parseResponse _ = A.parseJSON instance (A.FromJSON a) => ApiResponse (Store.GenericResult a) where- parseResponse _ _ = A.parseJSON+ parseResponse _ = A.parseJSON instance (Serial a) => ApiResponse (Store.RawResult a) where- parseResponse _ _ = A.parseJSON+ parseResponse _ = A.parseJSON instance (Serial a) => ApiResponse (Store.RawResultList a) where- parseResponse _ _ = A.parseJSON+ parseResponse _ = A.parseJSON instance (ApiResponse a) => ApiResponse (Store.SerialList a) where- parseResponse net ctx =- A.withArray "list" $ fmap Store.SerialList . mapM (parseResponse net ctx) . toList+ parseResponse net =+ A.withArray "list" $ fmap Store.SerialList . mapM (parseResponse net) . toList -- | Parameter value of any type. data ParamBox = forall p. (Eq p, Param p) => ParamBox !p@@ -607,21 +607,21 @@ -- | Whether the path parameters of a request can be written for the -- network: an address of another network cannot. 'queryPath' fails with -- 'error' when they cannot, so ask this first.-pathEncodes :: (ApiResource a b) => Network -> Ctx -> a -> Bool-pathEncodes net ctx a = all ok (fst (queryParams a))+pathEncodes :: (ApiResource a b) => Network -> a -> Bool+pathEncodes net a = all ok (fst (queryParams a)) where- ok (ParamBox p) = case encodeParam net ctx p of+ ok (ParamBox p) = case encodeParam net p of Just [_] -> True _ -> False -- | Path of a request, with its path parameters filled in. Fails with -- 'error' for a parameter that the network cannot write ('pathEncodes').-queryPath :: (ApiResource a b) => Network -> Ctx -> a -> Text-queryPath net ctx a = f $ encParam <$> fst (queryParams a)+queryPath :: (ApiResource a b) => Network -> a -> Text+queryPath net a = f $ encParam <$> fst (queryParams a) where f = resourcePath $ asProxy a encParam (ParamBox p) =- case encodeParam net ctx p of+ case encodeParam net p of Just [res] -> res _ -> error "Invalid query param" @@ -650,21 +650,21 @@ -- | Encode a value as one or more strings. A list parameter is sent as -- comma-separated values.- encodeParam :: Network -> Ctx -> a -> Maybe [Text]+ encodeParam :: Network -> a -> Maybe [Text] -- | Parse a value from one or more strings.- parseParam :: Network -> Ctx -> [Text] -> Maybe a+ parseParam :: Network -> [Text] -> Maybe a instance Param Address where proxyLabel = const "address"- encodeParam net _ctx a = (: []) <$> addrToText net a- parseParam net _ctx [a] = textToAddr net a- parseParam _net _ctx _ = Nothing+ encodeParam net a = (: []) <$> addrToText net a+ parseParam net [a] = textToAddr net a+ parseParam _net _ = Nothing instance Param [Address] where proxyLabel = const "addresses"- encodeParam net _ctx = mapM (addrToText net)- parseParam net _ctx = mapM (textToAddr net)+ encodeParam net = mapM (addrToText net)+ parseParam net = mapM (textToAddr net) -- | Where a page of results starts. In URLs it is a transaction hash, a block -- height, or a Unix timestamp. Numbers up to 1230768000 are heights and larger@@ -680,7 +680,7 @@ instance Param StartParam where proxyLabel = const "height"- encodeParam _net _ctx p =+ encodeParam _net p = case p of StartParamHash h -> return [txHashToHex (TxHash h)] StartParamHeight h -> do@@ -689,7 +689,7 @@ StartParamTime t -> do guard $ t > 1230768000 return [cs $ show t]- parseParam _net _ctx [s] =+ parseParam _net [s] = parseHash <|> parseHeight <|> parseUnix where parseHash = do@@ -704,7 +704,7 @@ x <- bounded s guard $ x > 1230768000 return $ StartParamTime x- parseParam _net _ctx _ = Nothing+ parseParam _net _ = Nothing -- | A whole number written in decimal digits and nothing else. -- 'Text.Read.readMaybe' also takes hexadecimal and spaces around, and at@@ -731,9 +731,9 @@ instance Param OffsetParam where proxyLabel = const "offset"- encodeParam _net _ctx (OffsetParam o) = Just [cs $ show o]- parseParam _net _ctx [s] = OffsetParam <$> natural s- parseParam _net _ctx _ = Nothing+ encodeParam _net (OffsetParam o) = Just [cs $ show o]+ parseParam _net [s] = OffsetParam <$> natural s+ parseParam _net _ = Nothing -- | Maximum number of results (@limit@). newtype LimitParam = LimitParam {get :: Natural}@@ -741,9 +741,9 @@ instance Param LimitParam where proxyLabel = const "limit"- encodeParam _net _ctx (LimitParam l) = Just [cs $ show l]- parseParam _net _ctx [s] = LimitParam <$> natural s- parseParam _net _ctx _ = Nothing+ encodeParam _net (LimitParam l) = Just [cs $ show l]+ parseParam _net [s] = LimitParam <$> natural s+ parseParam _net _ = Nothing -- | Pagination of a list of results. data LimitsParam = LimitsParam@@ -766,9 +766,9 @@ instance Param HeightParam where proxyLabel = const "height"- encodeParam _net _ctx (HeightParam h) = Just [cs $ show h]- parseParam _net _ctx [s] = HeightParam <$> natural s- parseParam _net _ctx _ = Nothing+ encodeParam _net (HeightParam h) = Just [cs $ show h]+ parseParam _net [s] = HeightParam <$> natural s+ parseParam _net _ = Nothing -- | List of block heights (@heights@). newtype HeightsParam = HeightsParam {get :: [Natural]}@@ -776,8 +776,8 @@ instance Param HeightsParam where proxyLabel = const "heights"- encodeParam _net _ctx (HeightsParam hs) = Just $ cs . show <$> hs- parseParam _net _ctx xs = HeightsParam <$> mapM natural xs+ encodeParam _net (HeightsParam hs) = Just $ cs . show <$> hs+ parseParam _net xs = HeightsParam <$> mapM natural xs -- | Unix timestamp in seconds (@time@). newtype TimeParam = TimeParam {get :: Store.UnixTime}@@ -785,22 +785,22 @@ instance Param TimeParam where proxyLabel = const "time"- encodeParam _net _ctx (TimeParam t) = Just [cs $ show t]- parseParam _net _ctx [s] = TimeParam <$> bounded s- parseParam _net _ctx _ = Nothing+ encodeParam _net (TimeParam t) = Just [cs $ show t]+ parseParam _net [s] = TimeParam <$> bounded s+ parseParam _net _ = Nothing instance Param XPubKey where proxyLabel = const "xpub"- encodeParam net ctx p = Just [xPubExport net ctx p]- parseParam net ctx [s] = xPubImport net ctx s- parseParam _net _ctx _ = Nothing+ encodeParam net p = Just [xPubExport net p]+ parseParam net [s] = xPubImport net s+ parseParam _net _ = Nothing instance Param Store.DeriveType where proxyLabel = const "derive"- encodeParam net _ctx p = do+ encodeParam net p = do guard (net.segWit || p == Store.DeriveNormal) Just [Store.deriveTypeToText p]- parseParam net _ctx d = do+ parseParam net d = do res <- case d of [x] -> Store.textToDeriveType x _ -> Nothing@@ -816,9 +816,9 @@ instance Param NoCache where proxyLabel = const "nocache"- encodeParam _net _ctx (NoCache True) = Just ["true"]- encodeParam _net _ctx (NoCache False) = Just ["false"]- parseParam _net _ctx = \case+ encodeParam _net (NoCache True) = Just ["true"]+ encodeParam _net (NoCache False) = Just ["false"]+ parseParam _net = \case ["true"] -> Just $ NoCache True ["false"] -> Just $ NoCache False _ -> Nothing@@ -833,31 +833,31 @@ instance Param NoTx where proxyLabel = const "notx"- encodeParam _net _ctx (NoTx True) = Just ["true"]- encodeParam _net _ctx (NoTx False) = Just ["false"]- parseParam _net _ctx = \case+ encodeParam _net (NoTx True) = Just ["true"]+ encodeParam _net (NoTx False) = Just ["false"]+ parseParam _net = \case ["true"] -> Just $ NoTx True ["false"] -> Just $ NoTx False _ -> Nothing instance Param BlockHash where proxyLabel = const "block"- encodeParam _net _ctx b = Just [blockHashToHex b]- parseParam _net _ctx [s] = hexToBlockHash s- parseParam _net _ctx _ = Nothing+ encodeParam _net b = Just [blockHashToHex b]+ parseParam _net [s] = hexToBlockHash s+ parseParam _net _ = Nothing instance Param [BlockHash] where proxyLabel = const "blocks"- encodeParam _net _ctx bs = Just $ blockHashToHex <$> bs- parseParam _net _ctx = mapM hexToBlockHash+ encodeParam _net bs = Just $ blockHashToHex <$> bs+ parseParam _net = mapM hexToBlockHash instance Param TxHash where proxyLabel = const "txid"- encodeParam _net _ctx t = Just [txHashToHex t]- parseParam _net _ctx [s] = hexToTxHash s- parseParam _net _ctx _ = Nothing+ encodeParam _net t = Just [txHashToHex t]+ parseParam _net [s] = hexToTxHash s+ parseParam _net _ = Nothing instance Param [TxHash] where proxyLabel = const "txids"- encodeParam _net _ctx ts = Just $ txHashToHex <$> ts- parseParam _net _ctx = mapM hexToTxHash+ encodeParam _net ts = Just $ txHashToHex <$> ts+ parseParam _net = mapM hexToTxHash
test/Haskoin/Store/DataSpec.hs view
@@ -24,7 +24,7 @@ import Test.QuickCheck spec :: Spec-spec = prepareContext $ \ctx -> do+spec = do -- only the types that the server keeps in its database and caches have -- a binary encoding: the API speaks JSON describe "Binary encoding" $ do@@ -33,13 +33,13 @@ binaryLaws (arbitrary :: Gen BlockData) binaryLaws (arbitrary :: Gen Spender) binaryLaws (arbitrary :: Gen Prev)- binaryLaws (arbitraryTxData ctx)+ binaryLaws arbitraryTxData -- also covered inside the types below, but each has its own cereal and -- binary instances binaryLaws (anyNet arbitraryBalance) binaryLaws (anyNet arbitraryUnspent) binaryLaws (anyNet arbitraryDeriveType)- binaryLaws (anyNet (`arbitraryXPubSpec` ctx))+ binaryLaws (anyNet arbitraryXPubSpec) binaryLaws (anyNet arbitraryXPubBal) describe "JSON" $ do@@ -71,20 +71,19 @@ -- Balance, Unspent, StoreInput, StoreOutput and the inputs and outputs of -- BinfoTx are encoded through their own instances inside these. describe "JSON of a network" $ do- let withCtx = (,ctx)- marshalLaws id arbitraryXPubBal- marshalLaws id arbitraryXPubUnspent- marshalLaws id arbitraryBlockData- marshalLaws id arbitraryTransaction- marshalLaws withCtx (`arbitraryEventCommand` ctx)- marshalLaws withCtx (`arbitraryBinfoMultiAddr` ctx)- marshalLaws withCtx (`arbitraryBinfoBalance` ctx)- marshalLaws withCtx (`arbitraryBinfoBlock` ctx)- marshalLaws withCtx (`arbitraryBinfoTx` ctx)- marshalLaws withCtx (`arbitraryBinfoXPubPath` ctx)- marshalLaws withCtx (`arbitraryBinfoUnspent` ctx)- marshalLaws withCtx (`arbitraryBinfoRawAddr` ctx)- marshalLaws withCtx (`arbitraryBinfoMempool` ctx)+ marshalLaws arbitraryXPubBal+ marshalLaws arbitraryXPubUnspent+ marshalLaws arbitraryBlockData+ marshalLaws arbitraryTransaction+ marshalLaws arbitraryEventCommand+ marshalLaws arbitraryBinfoMultiAddr+ marshalLaws arbitraryBinfoBalance+ marshalLaws arbitraryBinfoBlock+ marshalLaws arbitraryBinfoTx+ marshalLaws arbitraryBinfoXPubPath+ marshalLaws arbitraryBinfoUnspent+ marshalLaws arbitraryBinfoRawAddr+ marshalLaws arbitraryBinfoMempool describe "Health check" $ do let bare =@@ -174,15 +173,15 @@ `shouldBe` ["00", "01", "7f", "0080", "00ff", "0100", "00ffff"] it "reads addresses and xpubs separated by bars or commas" $ forAll (vectorOf 3 (arbitraryAddress btc)) $ \as ->- forAll (arbitraryXPubKey ctx) $ \x ->- let txt = mconcat [t <> sep | (a, sep) <- zip as ["|", ",", "|"], Just t <- [addrToText btc a]] <> xPubExport btc ctx x- in parseBinfoAddr btc ctx txt `shouldBe` Just (map BinfoAddr as <> [BinfoXpub x])+ forAll (arbitraryXPubKey) $ \x ->+ let txt = mconcat [t <> sep | (a, sep) <- zip as ["|", ",", "|"], Just t <- [addrToText btc a]] <> xPubExport btc x+ in parseBinfoAddr btc txt `shouldBe` Just (map BinfoAddr as <> [BinfoXpub x]) it "refuses anything that is neither an address nor an xpub" $- parseBinfoAddr btc ctx "nonsense" `shouldBe` Nothing+ parseBinfoAddr btc "nonsense" `shouldBe` Nothing it "reads nothing from nothing" $- parseBinfoAddr btc ctx "" `shouldBe` Just []+ parseBinfoAddr btc "" `shouldBe` Just [] it "gives the next indices of an xpub and counts only payments to it" $- forAll (arbitraryXPubSpec btc ctx) $ \x ->+ forAll (arbitraryXPubSpec btc) $ \x -> forAll (vectorOf 3 (arbitraryAddress btc)) $ \as -> case as of [a1, a2, a3] -> let bal a r c = (zeroBalance a) {received = r, confirmed = c, txs = 1}@@ -215,8 +214,8 @@ describe "Coin instance of Unspent" $ it "reads the input kind from the output script" $ property $- forAll (arbitraryScriptOutput btc ctx) $ \so ->- case encodeOutput ctx so of+ forAll (arbitraryScriptOutput btc) $ \so ->+ case encodeOutput so of Left _ -> discard Right script -> let u =@@ -244,14 +243,14 @@ timestamp = 0, spenders = IntMap.empty }- in map (marshalValue net) (toTransaction net ctx td).outputs+ in map (marshalValue net) (toTransaction net td).outputs -- Pay to witness public key hash, from the examples of BIP 173. p2wpkh = "0014751e76e8199196d454941c45d1b3a323f1433bd6" -- OP_HASH256, a push of 32 bytes, OP_EQUAL. hashLock = "aa20bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb87" it "computes the id, size, weight and witnesses of the transaction" $- forAll (arbitraryTxData ctx) $ \td ->- let t = toTransaction btc ctx td+ forAll (arbitraryTxData) $ \td ->+ let t = toTransaction btc td len :: Tx -> Int len = B.length . runPutS . serialize witless = let Tx {..} = td.tx in Tx {witness = [], ..}@@ -263,17 +262,17 @@ ws ) it "gives the same with the id given" $- forAll (arbitraryTxData ctx) $ \td ->- toTransactionWithId btc ctx (txHash td.tx) td `shouldBe` toTransaction btc ctx td+ forAll (arbitraryTxData) $ \td ->+ toTransactionWithId btc (txHash td.tx) td `shouldBe` toTransaction btc td it "counts sizes as serializing does, with large counts and pushes" $ -- counts and lengths of 253 and more take more than a byte- forAll (arbitraryTxData ctx) $ \td -> forAll (choose (0, 3)) $ \k ->+ forAll (arbitraryTxData) $ \td -> forAll (choose (0, 3)) $ \k -> let big = B.replicate (0xfc + k * 0x100) 0x51 Tx {..} = td.tx grown = case outputs of TxOut v _ : os -> Tx {outputs = TxOut v big : os, ..} [] -> Tx {..}- t = toTransaction btc ctx (td {tx = grown} :: TxData)+ t = toTransaction btc (td {tx = grown} :: TxData) in t.size `shouldBe` fromIntegral (B.length (runPutS (serialize grown))) -- an output has an address only where the network has that kind forM_
test/Haskoin/Store/Gen.hs view
@@ -58,11 +58,11 @@ instance Arbitrary Prev where arbitrary = Prev <$> arbitraryBS1 <*> arbitrary -arbitraryTxData :: Ctx -> Gen TxData-arbitraryTxData ctx =+arbitraryTxData :: Gen TxData+arbitraryTxData = TxData <$> arbitrary- <*> arbitraryTx btc ctx+ <*> arbitraryTx btc <*> arbitrary <*> arbitrary <*> arbitrary@@ -182,8 +182,8 @@ RejectCheckpoint ] -arbitraryXPubSpec :: Network -> Ctx -> Gen XPubSpec-arbitraryXPubSpec net ctx = XPubSpec <$> arbitraryXPubKey ctx <*> arbitraryDeriveType net+arbitraryXPubSpec :: Network -> Gen XPubSpec+arbitraryXPubSpec net = XPubSpec <$> arbitraryXPubKey <*> arbitraryDeriveType net arbitraryDeriveType :: Network -> Gen DeriveType arbitraryDeriveType net =@@ -268,13 +268,13 @@ ] -- | A command for the events of a network, of every kind.-arbitraryEventCommand :: Network -> Ctx -> Gen EventCommand-arbitraryEventCommand net ctx =+arbitraryEventCommand :: Network -> Gen EventCommand+arbitraryEventCommand net = oneof [ EventWatch <$> listOf (arbitraryAddress net), EventUnwatch <$> listOf (arbitraryAddress net),- EventWatchXPub <$> arbitraryXPubSpec net ctx,- EventUnwatchXPub <$> arbitraryXPubSpec net ctx,+ EventWatchXPub <$> arbitraryXPubSpec net,+ EventUnwatchXPub <$> arbitraryXPubSpec net, EventFilterLoad <$> arbitraryBloomFilter, EventFilterAdd . B.pack <$> (choose (0, maxFilterAddSize) >>= vector), return EventFilterClear,@@ -307,43 +307,43 @@ BinfoTxIdIndex <$> arbitrary ] -arbitraryBinfoMultiAddr :: Network -> Ctx -> Gen BinfoMultiAddr-arbitraryBinfoMultiAddr net ctx = do- b <- arbitraryBinfoBalance net ctx+arbitraryBinfoMultiAddr :: Network -> Gen BinfoMultiAddr+arbitraryBinfoMultiAddr net = do+ b <- arbitraryBinfoBalance net let addresses = [b] wallet <- arbitrary- txs <- small (arbitraryBinfoTx net ctx)+ txs <- small (arbitraryBinfoTx net) info <- arbitrary recommendFee <- arbitrary let cashAddr = isJust net.cashAddrPrefix return BinfoMultiAddr {..} -arbitraryBinfoRawAddr :: Network -> Ctx -> Gen BinfoRawAddr-arbitraryBinfoRawAddr net ctx = do+arbitraryBinfoRawAddr :: Network -> Gen BinfoRawAddr+arbitraryBinfoRawAddr net = do address <- oneof [ BinfoAddr <$> arbitraryAddress net,- BinfoXpub <$> arbitraryXPubKey ctx+ BinfoXpub <$> arbitraryXPubKey ] balance <- arbitrary ntx <- arbitrary utxo <- arbitrary received <- arbitrary sent <- arbitrary- txs <- small (arbitraryBinfoTx net ctx)+ txs <- small (arbitraryBinfoTx net) return $ BinfoRawAddr {..} instance Arbitrary BinfoShortBal where arbitrary = BinfoShortBal <$> arbitrary <*> arbitrary <*> arbitrary -arbitraryBinfoBalance :: Network -> Ctx -> Gen BinfoBalance-arbitraryBinfoBalance net ctx = do+arbitraryBinfoBalance :: Network -> Gen BinfoBalance+arbitraryBinfoBalance net = do address <- arbitraryAddress net txs <- arbitrary received <- arbitrary sent <- arbitrary balance <- arbitrary- xpub <- arbitraryXPubKey ctx+ xpub <- arbitraryXPubKey external <- arbitrary change <- arbitrary elements [BinfoAddrBalance {..}, BinfoXPubBalance {..}]@@ -357,8 +357,8 @@ sent <- arbitrary return BinfoWallet {..} -arbitraryBinfoBlock :: Network -> Ctx -> Gen BinfoBlock-arbitraryBinfoBlock net ctx = do+arbitraryBinfoBlock :: Network -> Gen BinfoBlock+arbitraryBinfoBlock net = do hash <- arbitraryBlockHash version <- arbitrary prev <- arbitraryBlockHash@@ -374,15 +374,15 @@ main <- arbitrary height <- arbitrary weight <- arbitrary- txs <- small (arbitraryBinfoTx net ctx)+ txs <- small (arbitraryBinfoTx net) return BinfoBlock {..} -arbitraryBinfoTx :: Network -> Ctx -> Gen BinfoTx-arbitraryBinfoTx net ctx = do+arbitraryBinfoTx :: Network -> Gen BinfoTx+arbitraryBinfoTx net = do txid <- arbitraryTxHash version <- arbitrary- inputs <- small1 (arbitraryBinfoTxInput net ctx)- outputs <- small1 (arbitraryBinfoTxOutput net ctx)+ inputs <- small1 (arbitraryBinfoTxInput net)+ outputs <- small1 (arbitraryBinfoTxOutput net) let inputCount = fromIntegral $ length inputs outputCount = fromIntegral $ length outputs size <- arbitrary@@ -399,17 +399,17 @@ balance <- arbitrary return BinfoTx {..} -arbitraryBinfoTxInput :: Network -> Ctx -> Gen BinfoTxInput-arbitraryBinfoTxInput net ctx = do+arbitraryBinfoTxInput :: Network -> Gen BinfoTxInput+arbitraryBinfoTxInput net = do sequence <- arbitrary witness <- B.pack <$> listOf arbitrary script <- B.pack <$> listOf arbitrary index <- arbitrary- output <- arbitraryBinfoTxOutput net ctx+ output <- arbitraryBinfoTxOutput net return BinfoTxInput {..} -arbitraryBinfoTxOutput :: Network -> Ctx -> Gen BinfoTxOutput-arbitraryBinfoTxOutput net ctx = do+arbitraryBinfoTxOutput :: Network -> Gen BinfoTxOutput+arbitraryBinfoTxOutput net = do typ <- arbitrary spent <- arbitrary value <- arbitrary@@ -418,7 +418,7 @@ script <- B.pack <$> listOf arbitrary spenders <- arbitrary address <- arbitraryMaybe (arbitraryAddress net)- xpub <- arbitraryMaybe $ arbitraryBinfoXPubPath net ctx+ xpub <- arbitraryMaybe $ arbitraryBinfoXPubPath net return BinfoTxOutput {..} instance Arbitrary BinfoSpender where@@ -427,9 +427,9 @@ input <- arbitrary return BinfoSpender {..} -arbitraryBinfoXPubPath :: Network -> Ctx -> Gen BinfoXPubPath-arbitraryBinfoXPubPath _net ctx = do- key <- arbitraryXPubKey ctx+arbitraryBinfoXPubPath :: Network -> Gen BinfoXPubPath+arbitraryBinfoXPubPath _net = do+ key <- arbitraryXPubKey deriv <- arbitrarySoftPath return BinfoXPubPath {..} @@ -485,20 +485,20 @@ fee <- arbitrary return BinfoHistory {..} -arbitraryBinfoUnspent :: Network -> Ctx -> Gen BinfoUnspent-arbitraryBinfoUnspent net ctx = do+arbitraryBinfoUnspent :: Network -> Gen BinfoUnspent+arbitraryBinfoUnspent net = do txid <- arbitraryTxHash index <- arbitrary script <- B.pack <$> listOf arbitrary value <- arbitrary confirmations <- arbitrary txidx <- arbitrary- xpub <- arbitraryMaybe $ arbitraryBinfoXPubPath net ctx+ xpub <- arbitraryMaybe $ arbitraryBinfoXPubPath net return BinfoUnspent {..} -arbitraryBinfoUnspents :: Network -> Ctx -> Gen BinfoUnspents-arbitraryBinfoUnspents net ctx =- BinfoUnspents <$> small (arbitraryBinfoUnspent net ctx)+arbitraryBinfoUnspents :: Network -> Gen BinfoUnspents+arbitraryBinfoUnspents net =+ BinfoUnspents <$> small (arbitraryBinfoUnspent net) instance Arbitrary BinfoHeader where arbitrary =@@ -509,9 +509,9 @@ <*> arbitrary <*> arbitrary -arbitraryBinfoMempool :: Network -> Ctx -> Gen BinfoMempool-arbitraryBinfoMempool net ctx =- BinfoMempool <$> small (arbitraryBinfoTx net ctx)+arbitraryBinfoMempool :: Network -> Gen BinfoMempool+arbitraryBinfoMempool net =+ BinfoMempool <$> small (arbitraryBinfoTx net) instance Arbitrary BinfoBlockInfos where arbitrary = BinfoBlockInfos <$> small arbitrary
test/Haskoin/Store/Laws.hs view
@@ -20,6 +20,8 @@ import Data.Aeson.Types (parseMaybe) import Data.Binary (Binary) import Data.Binary qualified as Binary+import Data.ByteString (ByteString)+import Data.ByteString qualified as B import Data.ByteString.Lazy qualified as BL import Data.Bytes.Get (runGetS) import Data.Bytes.Put (runPutS)@@ -29,25 +31,50 @@ import Data.Serialize qualified as Cereal import Data.Typeable (Typeable, typeRep) import Haskoin (Network (..), allNets)-import Haskoin.Util (MarshalJSON (..))+import Haskoin.Util (MarshalJSON (..), decodeSerial, encodeSerial) import Test.Hspec (Spec) import Test.Hspec.QuickCheck (prop)-import Test.QuickCheck (Gen, counterexample, elements, forAll, (.&&.), (===))+import Test.QuickCheck (Gen, arbitrary, choose, counterexample, elements, forAll, oneof, (.&&.), (===)) -- | Name of the type of a generator, for the description of a test. name :: forall a. (Typeable a) => Gen a -> String name _ = show (typeRep (Proxy @a)) -- | The value comes back from its bytes, and the three binary classes--- ('Serial', cereal and binary) agree on the bytes.+-- ('Serial', cereal and binary) agree on the bytes, as do 'encodeSerial' and+-- 'decodeSerial'.+--+-- The reference is the 'Serial' instance run through cereal with 'runPutS'+-- and 'runGetS'. The cereal instances and the two functions do not run it+-- that way: they write and read on a buffer directly, for speed. So the+-- law also gives cereal bytes that are cut short, changed or followed by+-- others, and wants the result of the reference for them, error included. binaryLaws :: forall a. (Eq a, Show a, Typeable a, Serial a, Serialize a, Binary a) => Gen a -> Spec binaryLaws g = prop (name g) . forAll g $ \x -> let bytes = runPutS (serialize x)- in runGetS deserialize bytes === Right x+ reference :: ByteString -> Either String a+ reference = runGetS deserialize+ in reference bytes === Right x .&&. Cereal.encode x === bytes .&&. BL.toStrict (Binary.encode x) === bytes+ .&&. encodeSerial x === bytes .&&. Cereal.decode bytes === Right x+ .&&. Binary.decode (BL.fromStrict bytes) === x+ .&&. decodeSerial bytes === Right x+ .&&. forAll (damaged bytes) (\bad -> Cereal.decode bad === reference bad) +-- | Bytes that are not what was written: cut short, with a byte changed, or+-- with a byte after them.+damaged :: ByteString -> Gen ByteString+damaged bytes =+ oneof+ [ (`B.take` bytes) <$> choose (0, B.length bytes),+ change <$> choose (0, max 0 (B.length bytes - 1)) <*> arbitrary,+ B.snoc bytes <$> arbitrary+ ]+ where+ change i w = B.take i bytes <> B.pack [w | i < B.length bytes] <> B.drop (i + 1) bytes+ -- | The value comes back from its JSON, and the fast encoder ('A.toEncoding') -- writes the same JSON as 'A.toJSON': the two are written by hand and could -- drift apart.@@ -61,16 +88,14 @@ anyNet g = elements allNets >>= g -- | Like 'jsonLaws', for JSON that depends on the network, which is random--- for each case; @s@ is what the encoding takes, made from the network.+-- for each case. marshalLaws ::- forall s a.- (Eq a, Show a, Typeable a, MarshalJSON s a) =>- (Network -> s) ->+ forall a.+ (Eq a, Show a, Typeable a, MarshalJSON Network a) => (Network -> Gen a) -> Spec-marshalLaws mk g = prop (name (g undefined)) . forAll (elements allNets) $ \net ->- let s = mk net- in counterexample net.name . forAll (g net) $ \x ->- parseMaybe (unmarshalValue s) (marshalValue s x) === Just x- .&&. (A.decode (encodingToLazyByteString (marshalEncoding s x)) :: Maybe Value)- === Just (marshalValue s x)+marshalLaws g = prop (name (g undefined)) . forAll (elements allNets) $ \net ->+ counterexample net.name . forAll (g net) $ \x ->+ parseMaybe (unmarshalValue net) (marshalValue net x) === Just x+ .&&. (A.decode (encodingToLazyByteString (marshalEncoding net x)) :: Maybe Value)+ === Just (marshalValue net x)
test/Haskoin/Store/RobustSpec.hs view
@@ -73,7 +73,7 @@ hex n = let (q, r) = n `divMod` 16 in (if q > 0 then hex q else "") <> [("0123456789abcdef" !! r)] spec :: Spec-spec = prepareContext $ \ctx -> do+spec = do describe "Encoders" $ do it "write a peer whose user agent is not UTF-8" $ do let peer =@@ -89,9 +89,9 @@ describe "Parsers" $ do it "refuse a path of an xpub that is not one, instead of failing later" $ do- key <- generate (arbitraryXPubKey ctx)- let good = marshalValue (btc, ctx) BinfoXPubPath {key = key, deriv = Deriv :/ 0 :/ 1}- parse v = A.parseEither (unmarshalValue (btc, ctx)) v :: Either String BinfoXPubPath+ key <- generate (arbitraryXPubKey)+ let good = marshalValue btc BinfoXPubPath {key = key, deriv = Deriv :/ 0 :/ 1}+ parse v = A.parseEither (unmarshalValue btc) v :: Either String BinfoXPubPath parse good `shouldSatisfy` (not . failed) forM_ ["M/0'/1", "0/1", "nonsense"] $ \path -> evaluate (failed (parse (with "path" (A.String path) good))) `shouldReturn` True@@ -102,7 +102,7 @@ parse (A.object ["error" A..= ("user-error" :: Text), "message" A..= (5 :: Int)]) `shouldBe` Right (UserError "5") it "refuse bytes after a raw value" $ do- tx <- generate (arbitraryTx btc ctx)+ tx <- generate (arbitraryTx btc) let good = A.toJSON (RawResult tx) hex = case good of A.Object o | Just (A.String t) <- KeyMap.lookup "result" o -> t@@ -132,24 +132,24 @@ parseBinfoTxId "18446744073709551616" `shouldBe` Nothing parseBinfoFilter " 0x6 " `shouldSatisfy` (not . isJust) parseBinfoFilter "6" `shouldSatisfy` isJust- (parseParam btc ctx ["-1"] :: Maybe TimeParam) `shouldBe` Nothing- (parseParam btc ctx ["18446744073709551616"] :: Maybe TimeParam) `shouldBe` Nothing- (parseParam btc ctx ["1700000000"] :: Maybe TimeParam) `shouldBe` Just (TimeParam 1700000000)- (parseParam btc ctx ["-5"] :: Maybe StartParam) `shouldBe` Nothing- (parseParam btc ctx [" 5"] :: Maybe LimitParam) `shouldBe` Nothing- (parseParam btc ctx ["0x10"] :: Maybe OffsetParam) `shouldBe` Nothing- (parseParam btc ctx ["5"] :: Maybe LimitParam) `shouldBe` Just (LimitParam 5)+ (parseParam btc ["-1"] :: Maybe TimeParam) `shouldBe` Nothing+ (parseParam btc ["18446744073709551616"] :: Maybe TimeParam) `shouldBe` Nothing+ (parseParam btc ["1700000000"] :: Maybe TimeParam) `shouldBe` Just (TimeParam 1700000000)+ (parseParam btc ["-5"] :: Maybe StartParam) `shouldBe` Nothing+ (parseParam btc [" 5"] :: Maybe LimitParam) `shouldBe` Nothing+ (parseParam btc ["0x10"] :: Maybe OffsetParam) `shouldBe` Nothing+ (parseParam btc ["5"] :: Maybe LimitParam) `shouldBe` Just (LimitParam 5) it "of a date before 1970 are refused" $ do parseBinfoDate "01-01-1960" `shouldBe` Nothing parseBinfoDate "01-01-2020" `shouldBe` Just (BinfoDate 1577836800) it "do not wrap around when one is taken from a smaller one" $ do- td <- generate (arbitraryTxData ctx)+ td <- generate (arbitraryTxData) txDataFee td {prevs = IntMap.empty} `shouldBe` 0 isOK BlockHealth {headers = 3000000000, blocks = 10, max = 2} `shouldBe` False describe "Order" $ it "of xpub paths has no two different ones equal" $ do- key <- generate (arbitraryXPubKey ctx)+ key <- generate (arbitraryXPubKey) let a = BinfoXPubPath {key = key, deriv = Deriv :/ 0} b = BinfoXPubPath {key = key {index = key.index + 1}, deriv = Deriv :/ 0} (a == b, compare a b == EQ) `shouldBe` (False, False)@@ -160,20 +160,20 @@ reason (Left (StringError why)) = why reason _ = "" it "answers an error for an address that the network cannot write" $- apiCall ctx (ApiConfig bch nowhere) (GetAddrBalance segwit) `shouldReturn` Left (UserError "Invalid Param")+ 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 ctx (ApiConfig btc nowhere) (GetAddrBalance segwit)+ r <- apiCall (ApiConfig btc nowhere) (GetAddrBalance segwit) reason r `shouldSatisfy` ("Could not reach the server" `isPrefixOf`) e <- apiEvents (ApiConfig btc nowhere) (\_ -> return True) reason e `shouldSatisfy` ("Could not reach the server" `isPrefixOf`) it "ends a batch of size zero" $ do- r <- apiBatch ctx 0 (ApiConfig btc nowhere) (GetTxs [TxHash (sha256 ("a" :: B.ByteString))])+ r <- apiBatch 0 (ApiConfig btc nowhere) (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 ctx (ApiConfig btc host) (GetAddrBalance segwit)+ apiCall (ApiConfig btc host) (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 +182,7 @@ <> C.pack (show (B.length page)) <> "\r\n\r\n" <> page- r <- serving [answer] $ \host -> apiCall ctx (ApiConfig btc host) (GetAddrBalance segwit)+ r <- serving [answer] $ \host -> apiCall (ApiConfig btc host) (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))
test/Haskoin/Store/WebCommonSpec.hs view
@@ -2,6 +2,8 @@ module Haskoin.Store.WebCommonSpec (spec) where +import Data.Aeson qualified as A+import Data.Aeson.Types qualified as A import Data.ByteString qualified as B import Data.Maybe (fromJust) import Data.Proxy (Proxy (..))@@ -9,8 +11,6 @@ import Data.Text (Text) import Data.Word (Word64) import Haskoin-import Data.Aeson qualified as A-import Data.Aeson.Types qualified as A import Haskoin.Store.Data (DeriveType (..), SerialList (..), TxRef) import Haskoin.Store.Gen (arbitraryDeriveType, arbitraryTransaction) import Haskoin.Store.WebCommon@@ -20,33 +20,33 @@ import Test.QuickCheck spec :: Spec-spec = prepareContext $ \ctx -> do+spec = do -- each case on a random network: they differ in their address prefixes describe "Parameters" $ do- roundTrip ctx arbitraryAddress- roundTrip ctx (listOf . arbitraryAddress)- roundTrip ctx (const (arbitrary :: Gen StartParam))- roundTrip ctx (const (arbitrarySizedNatural :: Gen OffsetParam))- roundTrip ctx (const (arbitrarySizedNatural :: Gen LimitParam))- roundTrip ctx (const (arbitrarySizedNatural :: Gen HeightParam))- roundTrip ctx (const (arbitrary :: Gen HeightsParam))- roundTrip ctx (const (arbitrarySizedNatural :: Gen TimeParam))- roundTrip ctx (const (arbitraryXPubKey ctx))- roundTrip ctx arbitraryDeriveType- roundTrip ctx (const (NoCache <$> arbitrary))- roundTrip ctx (const (NoTx <$> arbitrary))- roundTrip ctx (const (listOf arbitraryBlockHash))- roundTrip ctx (const (listOf arbitraryTxHash))+ roundTrip arbitraryAddress+ roundTrip (listOf . arbitraryAddress)+ roundTrip (const (arbitrary :: Gen StartParam))+ roundTrip (const (arbitrarySizedNatural :: Gen OffsetParam))+ roundTrip (const (arbitrarySizedNatural :: Gen LimitParam))+ roundTrip (const (arbitrarySizedNatural :: Gen HeightParam))+ roundTrip (const (arbitrary :: Gen HeightsParam))+ roundTrip (const (arbitrarySizedNatural :: Gen TimeParam))+ roundTrip (const (arbitraryXPubKey))+ roundTrip arbitraryDeriveType+ roundTrip (const (NoCache <$> arbitrary))+ roundTrip (const (NoTx <$> arbitrary))+ roundTrip (const (listOf arbitraryBlockHash))+ roundTrip (const (listOf arbitraryTxHash)) -- the client reads what the server writes: lists in the JSON of the -- network, and the rest in plain JSON describe "Responses" $ do prop "a list of transactions" . forAll (elements allNets) $ \net -> forAll (listOf (arbitraryTransaction net)) $ \xs ->- A.parseEither (parseResponse net ctx) (A.toJSON (map (marshalValue net) xs))+ A.parseEither (parseResponse net) (A.toJSON (map (marshalValue net) xs)) === Right (SerialList xs) prop "a list of references" . forAll (listOf arbitrary) $ \xs ->- A.parseEither (parseResponse btc ctx) (A.toJSON (xs :: [TxRef]))+ A.parseEither (parseResponse btc) (A.toJSON (xs :: [TxRef])) === Right (SerialList xs) describe "Start of a page" $ do@@ -59,13 +59,13 @@ describe "Derivation" $ it "is only normal on networks without SegWit" $ do- encodeParam bch ctx DeriveP2WPKH `shouldBe` Nothing- encodeParam btc ctx DeriveP2WPKH `shouldBe` Just ["segwit"]+ encodeParam bch DeriveP2WPKH `shouldBe` Nothing+ encodeParam btc DeriveP2WPKH `shouldBe` Just ["segwit"] describe "Paths" $ do let addr = fromJust (textToAddr btc "1111111111111111111114oLvT2") path :: (ApiResource a b) => a -> String- path = cs . queryPath btc ctx+ path = cs . queryPath btc it "of a block" $ do path (GetBlockBest (NoTx False)) `shouldBe` "/block/best" path (GetBlockHeight (HeightParam 5) (NoTx False)) `shouldBe` "/block/height/5"@@ -74,19 +74,19 @@ it "of an address" $ path (GetAddrBalance addr) `shouldBe` "/address/1111111111111111111114oLvT2/balance" prop "of an xpub" $- forAll (arbitraryXPubKey ctx) $ \x ->+ forAll (arbitraryXPubKey) $ \x -> path (GetXPubBalances x DeriveNormal (NoCache False))- `shouldBe` "/xpub/" <> cs (xPubExport btc ctx x) <> "/balances"+ `shouldBe` "/xpub/" <> cs (xPubExport btc x) <> "/balances" where z = TxHash (sha256 B.empty)- parse = parseParam btc undefined :: [Text] -> Maybe StartParam+ parse = parseParam btc :: [Text] -> Maybe StartParam -- | A parameter comes back from its encoding in a URL, on a random network.-roundTrip :: forall a. (Eq a, Show a, Param a) => Ctx -> (Network -> Gen a) -> Spec-roundTrip ctx g =+roundTrip :: forall a. (Eq a, Show a, Param a) => (Network -> Gen a) -> Spec+roundTrip g = prop (cs (proxyLabel (Proxy :: Proxy a))) . forAll (elements allNets) $ \net -> counterexample net.name . forAll (g net) $ \p ->- (encodeParam net ctx p >>= parseParam net ctx) `shouldBe` Just p+ (encodeParam net p >>= parseParam net) `shouldBe` Just p instance Arbitrary StartParam where arbitrary =