haskoin-store 2.0.0 → 2.1.0
raw patch · 16 files changed
+615/−84 lines, 16 files
Files
- CHANGELOG.md +34/−0
- README.md +2/−1
- app/Main.hs +20/−0
- bench/Main.hs +1/−0
- haskoin-store.cabal +2/−1
- src/Haskoin/Store/Ingest.hs +160/−51
- src/Haskoin/Store/Ingest/Run.hs +104/−14
- src/Haskoin/Store/Manager.hs +30/−4
- src/Haskoin/Store/NodePeer.hs +10/−1
- src/Haskoin/Store/Web.hs +15/−3
- test/Haskoin/Store/CommandLineSpec.hs +76/−0
- test/Haskoin/Store/DownloadSpec.hs +1/−0
- test/Haskoin/Store/Ingest/Model.hs +59/−9
- test/Haskoin/Store/IngestSpec.hs +58/−0
- test/Haskoin/Store/IntegrationSpec.hs +1/−0
- test/Haskoin/Store/MempoolSpec.hs +42/−0
CHANGELOG.md view
@@ -6,6 +6,40 @@ ## [Unreleased] +## [2.1.0] - 2026-12-02++A store whose node is given with `--node-rpc` says that its mempool is in+sync a moment after it has its blocks, where it waited twenty seconds+after each start. A regtest that waited for that before each of its tests+took four times as long.++### Added+- **`--mempool-wait` (`MEMPOOL_WAIT`)**: the seconds that a peer asked for+ its mempool is given to name all of it, before the store says that its+ mempool is `synced`; twenty by default, as before, and at least one. The+ protocol has no word for the end of the answer, so for a peer the store+ can only wait (`Haskoin.Store.Ingest.sweepWait`).++### Changed+- **The node of `--node-rpc` is not waited for.** Its answer to `mempool`+ is all of `getrawmempool` at once, and it answers one message after the+ other: the store sends it a ping after `mempool`, and its pong is the end+ of the answer. The machine of the path into the pool takes such a source+ to have answered when it says so (`SourceUp`, `Answered` in+ `Haskoin.Store.Ingest`), and not when twenty seconds passed. A reading+ asked before the store may have missed something counts no more than it+ did. Measured on a regtest, from the start of a store at the tip to+ `synced`, on Bitcoin Core and on Bitcoin Cash Node: 20.1 seconds before,+ 1.0 after (`readyAtOnce` in `Haskoin.Store.MempoolSpec`).+- **A long move of the chain makes the store say `syncing` at once.** When+ the store finds that it has to take back and take in more than two blocks+ to reach the best header of its node, its mempool is `syncing` from that+ moment (`Moved`), and not only once its health noticed that it is+ behind, which let a client that asked in between take it for ready. It+ reads its sources again as soon as it has the blocks, without the gap+ after the last reading, and is `synced` when they answered. The health+ check is also run again at once when that word changes.+ ## [2.0.0] - 2026-11-25 This release brings the tokens of Bitcoin Cash (CashTokens,
README.md view
@@ -342,6 +342,7 @@ | Option | Environment | Default | Meaning | | --- | --- | --- | --- | | `--mempool-timeout` | `MEMPOOL_TIMEOUT` | `14` | Days after which unconfirmed transactions are deleted (0 = never) |+| `--mempool-wait` | `MEMPOOL_WAIT` | `20` | Seconds that a peer asked for its mempool is given to name all of it, at least 1. The protocol has no word for the end of the answer, so the store waits this long before it says that its mempool is `synced` (`/health`). The node of `--node-rpc` says when it has named all of it and is not waited for. A regtest whose only node is a peer may set 1 or 2 | ### Web server and limits @@ -486,7 +487,7 @@ | Field | What it says | | --- | --- | | `sources` | How many nodes the store can read a whole mempool from |-| `sync` | How the mempool stands with the mempools of your nodes, in one word. `syncing`: the store has not yet read your node and taken in all that it named, since it started or since Redis lost its data, and shows fewer unconfirmed transactions than the node meanwhile; for twenty seconds at least after a start. `synced`: it has. `unknown`: the store has no node of yours to read a whole mempool from, only strangers or nobody, and cannot tell |+| `sync` | How the mempool stands with the mempools of your nodes, in one word. `syncing`: the store has not yet read your node and taken in all that it named, since it started, since Redis lost its data, or since the chain moved by more than two blocks at once, and shows other unconfirmed transactions than the node meanwhile. After a start, a node that is a peer is given `--mempool-wait`, twenty seconds by default, to name its mempool; the node of `--node-rpc` says when it has, and a store on a regtest with it says `synced` a moment after it has its blocks. `synced`: it has. `unknown`: the store has no node of yours to read a whole mempool from, only strangers or nobody, and cannot tell | | `known`, `held` | How many transactions are on their way to the mempool, and how many of them the store holds | | `dirty` | Whether the store gave something up and is about to read its sources again |
app/Main.hs view
@@ -133,6 +133,7 @@ blockStall :: !Int, blockPing :: !Int, maxPeerLife :: !Int,+ mempoolWait :: !Int, mempoolTimeout :: !Int, maxPeers :: !Int, statsd :: !Bool,@@ -224,6 +225,8 @@ env "BLOCK_PING" 5 readMaybe maxPeerLife <- env "MAX_PEER_LIFE" (48 * 3600) readMaybe+ mempoolWait <-+ env "MEMPOOL_WAIT" 20 readMaybe maxPeers <- env "MAX_PEERS" 20 readMaybe statsd <-@@ -684,6 +687,19 @@ <> helpEnv "MAX_PEER_LIFE" "Longest connection to a peer found by discovery; the peers of --peer are kept" <> showDefault <> value c.maxPeerLife+ mempoolWait <-+ option auto $+ metavar "SECONDS"+ <> long "mempool-wait"+ <> helpEnv+ "MEMPOOL_WAIT"+ ( unwords+ [ "How long a peer asked for its mempool is given to name all of it, before the store",+ "says that its mempool is in sync; the node of --node-rpc says when it has, and is not waited for"+ ]+ )+ <> showDefault+ <> value c.mempoolWait maxPeers <- option auto $ metavar "COUNT"@@ -894,6 +910,9 @@ -- the cache of xpubs cannot be turned off: its size is all that is set when (c.redisMaxXPubs < 1) $ misconfigured "--redis-max-xpubs (or REDIS_MAX_XPUBS) must be at least 1"+ -- a peer that is given no time has named nothing+ when (c.mempoolWait < 1) $+ misconfigured "--mempool-wait (or MEMPOOL_WAIT) must be at least 1 second" -- the ZeroMQ socket announces, and what it announces is fetched over -- the RPC: one without the other is no peer when (not (null c.nodeZmq) && null c.nodeRpc) $@@ -981,6 +1000,7 @@ blockStall = fromIntegral cfg.blockStall, blockPing = fromIntegral cfg.blockPing, maxPeerLife = fromIntegral cfg.maxPeerLife,+ mempoolWait = fromIntegral cfg.mempoolWait, connect = withConnection, nodePeerRpc = if null cfg.nodeRpc then Nothing else Just cfg.nodeRpc, nodePeerRpcSocket = if null cfg.nodeRpcSocket then Nothing else Just cfg.nodeRpcSocket,
bench/Main.hs view
@@ -214,6 +214,7 @@ peerTimeout = 60, blockStall = 10, blockPing = 5,+ mempoolWait = 20, maxPeerLife = 48 * 3600, connect = mockPeer blocks mock net ad, nodePeerRpc = Nothing,
haskoin-store.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: haskoin-store-version: 2.0.0+version: 2.1.0 synopsis: Storage and index for Bitcoin and Bitcoin Cash description: An indexer for Bitcoin and Bitcoin Cash. It downloads blocks and mempool transactions from the peer-to-peer network, indexes the chain in RocksDB and@@ -316,6 +316,7 @@ main-is: Spec.hs other-modules: Haskoin.Store.BlockStore.SyncSpec+ Haskoin.Store.CommandLineSpec Haskoin.Store.CommonSpec Haskoin.Store.Database.MergeSpec Haskoin.Store.Database.MigrateSpec
src/Haskoin/Store/Ingest.hs view
@@ -44,6 +44,13 @@ -- connects; when a peer that is none connects, the sources are read -- again. --+-- * __A source has answered when it says so, or when it had the time.__+-- A peer cannot say that it has named its whole mempool: the protocol+-- has no word for it, so it is given a time ('sweepWait'). The RPC of a+-- node can ('SourceUp', 'Answered'), and is not waited for. What the+-- store says of its mempool ('standing') depends on it, and nothing+-- that the machine does.+-- -- * __Giving up is allowed, and remembered.__ When there is no room, when -- a peer goes, when a request gets no answer, the id is given up with a -- reason and the machine is /dirty/. A dirty machine reads the whole@@ -166,6 +173,11 @@ maxWindow :: !Int, -- | how long a request waits for its answer patience :: !Tick,+ -- | how long a source that does not say when it has named its whole+ -- mempool is given to name it, from when it was asked, before the+ -- machine says that the pool has caught up ('standing'): a peer,+ -- whose protocol has no word for that+ sweepWait :: !Tick, -- | how long a transaction is held for transactions that it spends -- from and that do not come orphanLife :: !Tick,@@ -185,7 +197,8 @@ -- | The bounds of a store: room for the ids of two full mempools of -- Bitcoin Core, a hundred thousand bodies, windows from 16 to 4,096, a--- request given twenty seconds and an orphan twenty minutes, offered again+-- request and a peer asked for its mempool each given twenty seconds,+-- an orphan twenty minutes, offered again -- after two seconds and then twice as long each time, and a reading of the -- sources at most every ten seconds, every thirty while transactions -- come, and at least every minute.@@ -197,6 +210,7 @@ minWindow = 16, maxWindow = 4096, patience = 20000,+ sweepWait = 20000, orphanLife = 1200000, retry = 2000, sweepGap = 10000,@@ -234,7 +248,20 @@ -- have missed something of it ('missed'): a reading from which -- nothing is known to be missing, and which is whole once the peer -- had the time to answer ('standing')- since :: !(Maybe Tick)+ since :: !(Maybe Tick),+ -- | whether it says when it has named its whole mempool ('Answered'):+ -- the RPC of a node can, a peer of the protocol cannot+ tells :: !Bool,+ -- | of a source that says so, how many readings asked of it it has+ -- not yet said that it answered: it answers them in the order asked+ unanswered :: !Int,+ -- | of those, how many were asked before the store last may have+ -- missed something of it ('missed'): what they name says nothing of+ -- what was missed+ stale :: !Int,+ -- | whether it said that it answered a reading asked since 'since':+ -- it has answered, and no time need pass ('settleUp')+ answered :: !Bool } deriving (Eq, Ord, Show) @@ -283,12 +310,22 @@ Tick !Tick | -- | a peer connected; whether it is a source PeerUp !p !Bool+ | -- | a source connected that says when it has named its whole mempool+ -- ('Answered'): the RPC of a node+ SourceUp !p+ | -- | a source that says so has named all that the oldest reading that+ -- it had not answered asked for+ Answered !p | -- | a peer that is there is a node of the operator Own !p | -- | a peer is gone PeerDown !p | -- | whether the store has the blocks of its nodes Synced !Bool+ | -- | the chain moved by more than a block or two, and the store does+ -- not have the blocks of its nodes: until it has them, what the pool+ -- has is not the mempool of the nodes+ Moved | -- | a peer named transactions (@inv@) Named !p ![h] | -- | a transaction came: from a peer, or from a client of the store@@ -414,24 +451,34 @@ -- | Note that the machine caught up, when it did: it is in sync, a node -- of the operator gives its mempool, each such node was asked for it and--- had the time to answer, none owes a reading, nothing was given up that+-- answered, none owes a reading, nothing was given up that -- a node may still have, no question to the pool is on its way, and -- nothing that a node of the operator vouched for has a place. -- -- Nothing in the protocol says that the answer of a source is all there. -- A node names its mempool in as many messages as it takes, and in none -- when it has nothing; and what it names while it is asked may be a--- transaction that it just took, and no part of the answer. So a source--- has answered when as long passed as a request is given: a node that--- named nothing by then is taken to have nothing. The ids that it named--- are then on their way, and the machine has caught up when none is--- left. A store therefore says that it is syncing for that long at--- least, twenty seconds, after it starts.+-- transaction that it just took, and no part of the answer. So a peer+-- has answered when as long passed as it is given ('sweepWait'): a node+-- that named nothing by then is taken to have nothing. The ids that it+-- named are then on their way, and the machine has caught up when none+-- is left. A store whose nodes are peers therefore says that it is+-- syncing for that long at least, twenty seconds by default, after it+-- starts. --+-- A source that says when it has named all of its mempool ('SourceUp',+-- 'Answered') has answered when it says so, and no time need pass. The+-- RPC of a node does: what @getrawmempool@ returns is the whole mempool+-- at once. A store whose node of the operator is its RPC is in sync as+-- soon as it has taken in what the node named, a second after it starts+-- on a regtest, where it waited the twenty seconds of a peer before. An+-- answer counts only for a reading asked since the store last may have+-- missed something of the node, as the time does ('missed').+-- -- The time is counted from the first reading since the store last may -- have missed something of the node ('since', 'missed'), and not from--- the last reading: a node that is read more often than a request is--- given would otherwise never have answered. A reading that is owed for+-- the last reading: a node that is read more often than it is given to+-- answer would otherwise never have answered. A reading that is owed for -- a node of the operator to vouch for what a stranger named ('oweOwn') -- does not start the count again: nothing of the node was missed, and a -- store that strangers kept naming such transactions to would never@@ -453,15 +500,30 @@ | otherwise = s where nodes = trusted s- heard l = case l.since of- Just at -> s.now - at >= s.config.patience- Nothing -> False+ heard l+ | l.answered = True+ | otherwise = case l.since of+ Just at -> s.now - at >= s.config.sweepWait+ Nothing -> False -- | The store may have missed something that a source has: it owes a -- reading, and what it read before is no longer all that the source has.+-- The readings that it has not answered yet were asked before: their+-- answers are no longer whole either. missed :: Link h -> Link h-missed l = l {owed = True, since = Nothing}+missed l = l {owed = True, since = Nothing, stale = l.unanswered, answered = False} +-- | A source that says when it has named its whole mempool said so, for+-- the oldest reading that it had not answered. It answers in the order+-- asked, so that reading is known. One asked before the store last may+-- have missed something answers nothing ('missed'). Of a peer that does+-- not say so, or that owes no answer, it is no word at all.+answer :: Link h -> Link h+answer l+ | not l.tells || l.unanswered <= 0 = l+ | l.stale > 0 = l {unanswered = l.unanswered - 1, stale = l.stale - 1}+ | otherwise = l {unanswered = l.unanswered - 1, answered = True}+ -- | Whether a peer gives its whole mempool when asked. Without one, what -- the store misses stays missed. hasSource :: Ingest p h b -> Bool@@ -495,41 +557,25 @@ react :: (Ord p, Ord h) => (b -> [h]) -> Input p h b -> Ingest p h b -> (Ingest p h b, [Output p h b]) react parents input s = case input of Tick t -> done (onTick (max s.now t) (s {now = max s.now t}, []))- PeerUp p src- | Map.member p s.links -> (s, [])- | otherwise ->- let link =- Link- { source = src,- window = s.config.minWindow,- out = 0,- queue = Set.empty,- asks = Set.empty,- swept = Nothing,- owed = False,- every = max s.config.sweepGap s.config.sweepFast,- lively = False,- own = False,- since = Nothing- }- -- A node names to a peer nothing that it took before the peer- -- connected (A1). A peer that is a source is asked for its- -- mempool, which has it. One that is none is not, so what its- -- node took until now is owed by the sources: one of them may- -- be that node, as its RPC is, and was read before.- --- -- Without this, a store that had the RPC of a node and was- -- its peer read the RPC, connected a moment later, and never- -- had what the node took in between: one test in many ended- -- with four transactions lost, one for each of four that were- -- sent at once, and all that spent from them waiting.- others- | src = s.links- | otherwise = Map.map (\l -> if l.source then missed l else l) s.links- in (s {links = Map.insert p link others}, [])+ PeerUp p src -> (connect p src False s, [])+ SourceUp p -> (connect p True True s, [])+ Answered p -> (s {links = Map.adjust answer p s.links}, []) Own p -> (s {links = Map.adjust (\l -> l {own = True}) p s.links}, []) PeerDown p -> done (peerDown p (s, [])) Synced b -> (s {synced = b, begun = s.begun || b}, [])+ -- A long move of the chain: the blocks that the store does not have yet+ -- confirm transactions that the pool still has, or put back in the+ -- mempool of a node those of the blocks that it left, which a node does+ -- not announce. The store says that it is syncing from that moment,+ -- and not only once it is a few blocks behind, and its health had the+ -- time to say so. Every source is read again as soon as the store has+ -- the blocks, without the gap after its last reading: the move is+ -- reason enough. The store has caught up again when they answered and+ -- the pool decided on what they named ('settleUp'): on a regtest with+ -- the RPC of its node, a moment after it has the blocks.+ Moved -> (s {synced = False, caughtUp = False, links = Map.map moved s.links}, [])+ where+ moved l = if l.source then (missed l) {swept = Nothing} else l -- Until the store first has the blocks of its nodes, nothing that a -- peer names or sends is taken in. The store could not place it: the -- pool decides on a transaction from the outputs that it spends, and@@ -585,6 +631,47 @@ where put place = edit (retarget h place) s +-- | A peer connects: whether it is a source, and whether it says when it+-- has named its whole mempool. A peer that is there already is left as+-- it is.+connect :: (Ord p) => p -> Bool -> Bool -> Ingest p h b -> Ingest p h b+connect p src tells s+ | Map.member p s.links = s+ | otherwise =+ let link =+ Link+ { source = src,+ window = s.config.minWindow,+ out = 0,+ queue = Set.empty,+ asks = Set.empty,+ swept = Nothing,+ owed = False,+ every = max s.config.sweepGap s.config.sweepFast,+ lively = False,+ own = False,+ since = Nothing,+ tells,+ unanswered = 0,+ stale = 0,+ answered = False+ }+ -- A node names to a peer nothing that it took before the peer+ -- connected (A1). A peer that is a source is asked for its+ -- mempool, which has it. One that is none is not, so what its+ -- node took until now is owed by the sources: one of them may+ -- be that node, as its RPC is, and was read before.+ --+ -- Without this, a store that had the RPC of a node and was+ -- its peer read the RPC, connected a moment later, and never+ -- had what the node took in between: one test in many ended+ -- with four transactions lost, one for each of four that were+ -- sent at once, and all that spent from them waiting.+ others+ | src = s.links+ | otherwise = Map.map (\l -> if l.source then missed l else l) s.links+ in s {links = Map.insert p link others}+ -- | Put an id, wanted of a peer since now, among those to ask it for. queued :: (Ord p, Ord h) => p -> h -> Ingest p h b -> Ingest p h b queued p h s = s {links = Map.adjust (\l -> l {queue = Set.insert (s.now, h) l.queue}) p s.links}@@ -1076,7 +1163,15 @@ map Sweep due ) where- asked l = l {swept = Just s.now, owed = False, lively = False, every = after l, since = first l}+ asked l =+ l+ { swept = Just s.now,+ owed = False,+ lively = False,+ every = after l,+ since = first l,+ unanswered = if l.tells then l.unanswered + 1 else l.unanswered+ } -- the first reading since something may have been missed first l = case l.since of Nothing -> Just s.now@@ -1127,6 +1222,20 @@ l <- Map.elems s.links, l.every > max (max s.config.sweepGap s.config.sweepFast) s.config.sweepEvery ],+ [ "a peer that does not say when it answered owes answers"+ | l <- Map.elems s.links,+ not l.tells,+ l.unanswered /= 0+ ],+ [ "more readings asked before a miss than readings unanswered"+ | l <- Map.elems s.links,+ l.stale < 0 || l.stale > l.unanswered+ ],+ [ "a reading was answered and none was asked since a miss"+ | l <- Map.elems s.links,+ l.answered,+ l.since == Nothing+ ], ["a peer that is gone is still named" | ps <- namers, not (ps `Set.isSubsetOf` Map.keysSet s.links)], ["an id that nobody named is waiting to be asked for" | Wanted ms <- map snd placed, Map.null ms], [ "every body held waits for another, or to be vouched for"@@ -1200,11 +1309,11 @@ where rel t = max (negate bound) (t - s.now) link l = l {queue = times l.queue, asks = times l.asks, swept = rel <$> l.swept, since = first <$> l.since}- -- 'since' is only asked whether it is as long ago as a request is- -- given, and not at all by a machine that caught up, which forgets it+ -- 'since' is only asked whether it is as long ago as a source is+ -- given to answer, and not at all by a machine that caught up, which forgets it -- before it asks again ('missed'): longer ago is all the same first t | s.caughtUp = long | otherwise = max long (t - s.now)- long = negate s.config.patience+ long = negate s.config.sweepWait times = Set.map (\(t, h) -> (rel t, h))
src/Haskoin/Store/Ingest/Run.hs view
@@ -52,10 +52,21 @@ -- -- To the machine a feed is one more peer that is a source: it is told that -- the feed came, asks it for its mempool and for transactions with the--- same outputs, within the same window, and gets the same inputs back. So--- nothing of the machine, of its proofs or of its model is particular to a--- feed. A feed that fails is a peer that went, and one that answers again--- is a new peer, with a new number (U1).+-- same outputs, within the same window, and gets the same inputs back. A+-- feed that fails is a peer that went, and one that answers again is a+-- new peer, with a new number (U1).+--+-- = A source that says when it has answered+--+-- The machine takes a peer to have named its whole mempool when as long+-- passed as it is given: the protocol has no word for the end of the+-- answer. A feed has one: its reading returns when it has all of it, and+-- the runner tells the machine so ('Answered'). So does the node that a+-- store has through its RPC as a peer ("Haskoin.Store.NodePeer"): it+-- answers each message in the order that it came, so a ping sent after+-- @mempool@ comes back after the whole answer, and its pong is the end of+-- it ('inOrder'). Bitcoin Core answers a ping before the @mempool@ that+-- came first, and the ping is sent to no other peer for that. module Haskoin.Store.Ingest.Run ( Ingester, IngestConfig (..),@@ -73,6 +84,7 @@ ingestNamedSTM, ingestTxSTM, ingestMissingSTM,+ ingestPongSTM, ingestLookSTM, ingestEmptiedSTM, )@@ -104,6 +116,8 @@ import Data.List (find, nub) import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map+import Data.Set (Set)+import Data.Set qualified as Set import Data.String.Conversions (cs) import Data.Text (Text) import Data.Text qualified as T@@ -117,6 +131,7 @@ Message (..), Network (..), OutPoint (..),+ Ping (..), Tx (..), TxHash (..), TxIn (..),@@ -128,6 +143,7 @@ import Haskoin.Store.Fleet.Member (Member, OfferCost (..), memberOfferTimed, memberSettled) import Haskoin.Store.Ingest import System.Metrics.StatsD (StatCounter, StatGauge, Stats, incrementCounter, newStatCounter, newStatGauge, setGauge)+import System.Random (randomIO) -- | What the runner needs of the store. data IngestConfig = IngestConfig@@ -147,6 +163,16 @@ -- word ("Haskoin.Store.Ingest"). A feed always is: the operator gave -- the store the RPC of that node. own :: !(Peer -> IO Bool),+ -- | whether a peer answers every message in the order that it came,+ -- so that the pong of a ping sent after @mempool@ is the end of the+ -- answer: the node that the store has through its RPC+ -- ("Haskoin.Store.NodePeer"), and no node of the network+ inOrder :: !(Peer -> IO Bool),+ -- | how many blocks the store has to take back and take in to have+ -- the best header of its node: 0 when it has it. A move of more than+ -- two blocks makes the store say that its mempool is syncing at once+ -- ('Moved').+ behind :: !(IO Int), stats :: !(Maybe Stats), logger :: !Logger }@@ -186,6 +212,10 @@ | Names !Link ![TxHash] | Came !Link !Tx | Lacks !Link ![TxHash]+ | -- | a peer answered a ping, with its nonce+ Ponged !Link !Word64+ | -- | a feed returned the whole mempool of its node, all of it named+ Whole !Link | -- | the store may be in sync now, or no longer Look | PoolLost@@ -274,6 +304,13 @@ ingestMissingSTM :: Peer -> [TxHash] -> Ingester -> STM () ingestMissingSTM p hs = bulk (Lacks (Wire p) hs) +-- | A peer answered a ping (@pong@), with its nonce: the end of the answer+-- to @mempool@ of a peer that answers in order ('inOrder'), when the+-- nonce is that of the ping that the runner sent after it. Any other is+-- no word of the runner's, and is left alone.+ingestPongSTM :: Peer -> Word64 -> Ingester -> STM ()+ingestPongSTM p n = always (Ponged (Wire p) n)+ -- | The store has a new best header or a new best block: it may be in -- sync now, or no longer. ingestLookSTM :: Ingester -> STM ()@@ -338,6 +375,8 @@ ReadAll -> do hs <- feed.names forM_ (pieces hs) $ \some -> atomically (patient (Names me some) ing)+ -- after what it named, in the same queue: the reading is whole+ atomically (always (Whole me) ing) Fetch hs -> do found <- feed.bodies hs forM_ found . mapM_ $ \tx -> atomically (patient (Came me tx) ing)@@ -444,10 +483,29 @@ t <- milliseconds costs <- newIORef noCosts saidAt <- newIORef t- loopWith costs saidAt cfg ing metrics run0 t+ pings <- newIORef Map.empty+ loopWith costs pings saidAt cfg ing metrics run0 t -loopWith :: IORef Costs -> IORef Tick -> IngestConfig -> Ingester -> Maybe Metrics -> Run -> Tick -> IO a-loopWith costs saidAt cfg ing metrics run0 t0 = go False t0 run0+-- | The blocks that a move of the chain may take, back and in, for the+-- store to go on saying that its mempool is in sync: a block found, or+-- two at one height. A longer move makes it say that it is syncing at+-- once ('Moved').+longMove :: Int+longMove = 2++loopWith ::+ IORef Costs ->+ -- | the peers that answer in order, by their numbers, with the nonces+ -- of the pings sent after a request for their mempools and not answered+ IORef (Map Int (Set Word64)) ->+ IORef Tick ->+ IngestConfig ->+ Ingester ->+ Maybe Metrics ->+ Run ->+ Tick ->+ IO a+loopWith costs pings saidAt cfg ing metrics run0 t0 = go False t0 run0 where -- the time that an action takes, added to what the runner spent timed :: (Costs -> Word64 -> Costs) -> IO x -> IO x@@ -519,8 +577,15 @@ Just Look -> True _ -> tick -- whether the store is in sync is looked at when it may have changed,- -- and at every tick+ -- and at every tick; and when it is not, how far the chain moved synced <- if looks then cfg.inSync else return wasSynced+ distance <- if looks && not synced then cfg.behind else return 0+ let moved = distance > longMove+ when (moved && standing run'.machine == PoolSynced) . say LevelInfo . T.unwords $+ [ "The chain moved by",+ shown distance,+ "blocks: the mempool is syncing until the store has them and has read its sources again"+ ] -- one attempt at the pool a pass while it fails failing <- newIORef False -- what the machine gives up in this pass, by reason@@ -528,6 +593,7 @@ let all' = [Emptied | lost > 0] <> [Synced synced | synced /= wasSynced]+ <> [Moved | moved] <> inputs <> [Tick now | tick] machine <- drive run'.peers failing lostNow run'.machine all'@@ -566,7 +632,7 @@ when (droppable e) (atomically (modifyTVar' ing.waiting (subtract 1))) case e of PeerCame p -> do- (src, ours) <- case p of+ (src, ours, orderly) <- case p of Wire peer -> do src <- cfg.source peer unless src . say LevelInfo . T.unwords $@@ -581,16 +647,33 @@ if ours then "Peer " <> shown peer <> " is a node of the operator: what it names is taken at its word" else "Peer " <> shown peer <> " is a stranger: what only strangers name is verified first"- return (src, ours)- -- a feed is nothing but a source, of a node of the operator- Fed {} -> return (True, True)+ orderly <- if src then cfg.inOrder peer else return False+ -- its pongs say when it has named its whole mempool+ when orderly (modifyIORef' pings (Map.insert run.next Set.empty))+ return (src, ours, orderly)+ -- a feed is nothing but a source, of a node of the operator,+ -- and it says when it has read the whole mempool+ Fed {} -> return (True, True, True) return ( run {peers = Map.insert run.next p run.peers, next = run.next + 1},- PeerUp run.next src : [Own run.next | ours]+ (if orderly then SourceUp run.next else PeerUp run.next src) : [Own run.next | ours] ) PeerLeft p -> case keyOf run p of- Just k -> return (run {peers = Map.delete k run.peers}, [PeerDown k])+ Just k -> do+ modifyIORef' pings (Map.delete k)+ return (run {peers = Map.delete k run.peers}, [PeerDown k]) Nothing -> return (run, [])+ Ponged p n -> case keyOf run p of+ Just k -> do+ out <- Map.lookup k <$> readIORef pings+ case out of+ Just ns+ | Set.member n ns -> do+ modifyIORef' pings (Map.insert k (Set.delete n ns))+ return (run, [Answered k])+ _ -> return (run, [])+ Nothing -> return (run, [])+ Whole p -> return (run, [Answered k | Just k <- [keyOf run p]]) Names p hs -> return (run, [Named k hs | Just k <- [keyOf run p]]) Came from tx -- Only a block has a coinbase, and no mempool: one is not@@ -634,6 +717,13 @@ Wire p -> do say LevelInfo ("Asking peer " <> shown p <> " for its mempool") MMempool `sendMessage` p+ -- of a peer that answers in order, a ping after it: its pong+ -- is the end of the answer+ orderly <- Map.member k <$> readIORef pings+ when orderly $ do+ n <- randomIO+ modifyIORef' pings (Map.adjust (Set.insert n) k)+ MPing (Ping n) `sendMessage` p Fed _ label jobs -> do say LevelInfo ("Reading " <> label) atomically (writeTQueue jobs ReadAll)
src/Haskoin/Store/Manager.hs view
@@ -72,6 +72,8 @@ Permissions, WithConnection, chainGetBest,+ chainGetBlock,+ chainGetSplitBlock, chainHasHeaders, getPeers, judgeMessage,@@ -115,7 +117,7 @@ noteBest, ) import Haskoin.Store.Fleet.Redis (FleetEvent (..))-import Haskoin.Store.Ingest (defaultConfig)+import Haskoin.Store.Ingest (Config (sweepWait), defaultConfig) import Haskoin.Store.Ingest.Run ( IngestConfig (..), Ingester,@@ -125,6 +127,7 @@ ingestNamedSTM, ingestPeerDownSTM, ingestPeerUpSTM,+ ingestPongSTM, ingestTxSTM, withIngest, )@@ -234,6 +237,14 @@ -- | a peer is asked for blocks if it answers a ping within this long, -- or if none does blockPing :: !NominalDiffTime,+ -- | how long a peer asked for its mempool is given to name all of it,+ -- before the store takes its answer to be whole and may say that its+ -- mempool is in sync ('Haskoin.Store.Ingest.sweepWait'). The protocol+ -- has no word for the end of the answer, so the store can only wait.+ -- The node through its RPC ('nodePeerRpc') says when it has named+ -- all of it, and is not waited for. Twenty seconds in+ -- 'Haskoin.Store.Ingest.defaultConfig'.+ mempoolWait :: !NominalDiffTime, -- | disconnect peer if it has been connected this long maxPeerLife :: !NominalDiffTime, -- | connect to peers using the function 'Haskoin.Node.withConnection'@@ -540,13 +551,15 @@ -- the member of the fleet, whether the best block of the database is the -- best header of the node, and the first time whether the node has the -- headers of its peers too, which peers give their mempools when asked,--- as the model of each peer's node says ('judgeMessage'), and which are--- nodes of the operator ('ownPeer').+-- as the model of each peer's node says ('judgeMessage'), which are+-- nodes of the operator ('ownPeer'), which answer in order (the node+-- through its RPC), and how far the chain moved, back to where the best+-- block of the database and the best header split and on to the header. ingestCfg :: IORef Bool -> StoreConfig -> Node -> DatabaseReader -> Maybe Member -> IngestConfig ingestCfg begun cfg node db member = IngestConfig { net = cfg.net,- config = defaultConfig,+ config = defaultConfig {sweepWait = max 1 (round (cfg.mempoolWait * 1000))}, member, -- The first time, the headers too: while the node still takes -- them, two thousand at a time, the database catches up with the@@ -570,6 +583,18 @@ return headers, source = \p -> (== Allowed) <$> judgeMessage p MMempool, own = ownPeer cfg,+ -- the thread of the node through its RPC answers one message after+ -- the other ("Haskoin.Store.NodePeer")+ inOrder = return . isNodePeer,+ behind = do+ top <- chainGetBest node.chain+ here <- maybe (return Nothing) (chainGetBlock node.chain) =<< Q.getBestBlock db+ case here of+ -- no block yet: the whole chain is ahead+ Nothing -> return (fromIntegral top.height)+ Just b -> do+ split <- chainGetSplitBlock node.chain b top+ return (fromIntegral (top.height - split.height) + fromIntegral (b.height - split.height)), stats = cfg.stats, logger = withSource "Ingest" cfg.logger }@@ -636,6 +661,7 @@ MPong (Pong n) -> do publishSTM (StorePeerPong p n) pub blockStorePongSTM p n b+ ingestPongSTM p n ing -- the headers of a message are a chain: the last says what the -- peer has MHeaders (Headers hs)
src/Haskoin/Store/NodePeer.hs view
@@ -37,7 +37,16 @@ -- > a transaction to relay sendrawtransaction -- > (a new block, a new transaction) ZeroMQ: hashblock, hashtx ----- So nothing else of the store knows the difference. The node counts as+-- So nothing else of the store knows the difference, but one thing. A+-- peer of the network cannot say when it has named its whole mempool, and+-- the store gives it twenty seconds. This one can: it answers one message+-- after the other, so the pong of a ping that the store sends after+-- @mempool@ comes after the whole answer ("Haskoin.Store.Ingest.Run",+-- 'Haskoin.Store.Ingest.Run.ingestPongSTM'). Keep it so: a message that+-- it answered out of order would make the store say that its mempool is in+-- sync before it has what the node named.+--+-- The node counts as -- a peer in the health of the store, it is a node of the operator, whose -- word is taken ("Haskoin.Store.Ingest"), and it is a source: it says -- that it serves Bloom filters, which is what tells the store that a peer
src/Haskoin/Store/Web.hs view
@@ -984,16 +984,28 @@ -- costs little to run often; but a store that is catching up imports -- thousands of small blocks a second, and a check for each would be -- work for nothing, so there is a tenth of a second between two.+ --+ -- It is run at once too when the path into the pool says otherwise of+ -- the mempool: after a long move of the chain it says @syncing@ as+ -- soon as the store knows of the move ("Haskoin.Store.Ingest"), and+ -- the blocks of the check, which the store does not have yet, are to+ -- say the same at the same moment, not up to a second later. healthCheckLoop v up misses saidWell saidRedis pinged newBlock =- bracket (subscribe config.store.pub (heard newBlock)) (unsubscribe config.store.pub) $ \_ ->+ bracket (subscribe config.store.pub (heard newBlock)) (unsubscribe config.store.pub) $ \_ -> do+ said <- (.standing) <$> atomically (ingestState config.store.ingest)+ lastSaid <- newIORef said loopForever $ do threadDelay 100000 due <- registerDelay (config.healthCheckInterval * 1000 * 1000)- atomically $ do+ before <- readIORef lastSaid+ saidNow <- atomically $ do block <- readTVar newBlock time <- readTVar due- check (block || time)+ path <- (.standing) <$> ingestState config.store.ingest+ check (block || time || path /= before) writeTVar newBlock False+ return path+ writeIORef lastSaid saidNow h <- runHealthCheck atomically (writeTVar v h) tellHealth saidWell h
+ test/Haskoin/Store/CommandLineSpec.hs view
@@ -0,0 +1,76 @@+-- |+-- Module : Haskoin.Store.CommandLineSpec+-- Copyright : (c) Haskoin Developers+-- License : MIT+-- Maintainer : jprupp@protonmail.ch+-- Stability : experimental+-- Portability : POSIX+--+-- The command line of the program, run as it was built. Its parser is in+-- @app\/Main.hs@, which the tests cannot import, so they run the program+-- with arguments and an environment, and read what it says and how it+-- ends: an option that its variable does not set, or a value that is not+-- refused, shows there.+--+-- The program is beside the test suite, in the build folder of Stack and+-- of Cabal (@build\/haskoin-store\/haskoin-store@ next to+-- @build\/spec\/spec@). A suite run without it says that the tests are+-- pending.+module Haskoin.Store.CommandLineSpec (spec) where++import Data.List (isInfixOf)+import System.Directory (doesFileExist)+import System.Environment (getEnvironment, getExecutablePath)+import System.Exit (ExitCode (..))+import System.FilePath (takeDirectory, (</>))+import System.Process (CreateProcess (..), proc, readCreateProcessWithExitCode)+import Test.Hspec++spec :: Spec+spec =+ describe "The wait for a peer's mempool, --mempool-wait or MEMPOOL_WAIT" $ do+ it "is in the help, with its variable and its default of twenty seconds" $+ withProgram $ \run -> do+ (code, out, _) <- run [] ["--help"]+ code `shouldBe` ExitSuccess+ let text = unwords (words out)+ text `shouldSatisfy` ("--mempool-wait SECONDS" `isInfixOf`)+ text `shouldSatisfy` ("[env: MEMPOOL_WAIT] (default: 20)" `isInfixOf`)+ it "takes its default from the variable" $+ withProgram $ \run -> do+ (_, out, _) <- run [("MEMPOOL_WAIT", "3")] ["--help"]+ unwords (words out) `shouldSatisfy` ("[env: MEMPOOL_WAIT] (default: 3)" `isInfixOf`)+ it "takes a number of seconds on the command line" $+ withProgram $ \run -> do+ (code, _, _) <- run [] ["--mempool-wait", "3", "--version"]+ code `shouldBe` ExitSuccess+ (code', _, err) <- run [] ["--mempool-wait", "soon", "--version"]+ code' `shouldBe` ExitFailure 1+ err `shouldSatisfy` ("--mempool-wait" `isInfixOf`)+ it "refuses no time at all, from the command line, which comes first, and from the variable" $+ withProgram $ \run -> do+ let refused (code, _, err) = do+ code `shouldBe` ExitFailure 1+ err `shouldSatisfy` ("--mempool-wait (or MEMPOOL_WAIT) must be at least 1 second" `isInfixOf`)+ refused =<< run [] ["--mempool-wait", "0"]+ refused =<< run [] ["--mempool-wait", "-5"]+ refused =<< run [("MEMPOOL_WAIT", "3")] ["--mempool-wait", "0"]+ refused =<< run [("MEMPOOL_WAIT", "0")] []++-- | Run an action with a way to run the program: with variables added to+-- the environment of the tests, less any of the program's that the+-- action does not set, and arguments. Gives how it ended, what it wrote+-- and what it wrote as errors.+withProgram ::+ (([(String, String)] -> [String] -> IO (ExitCode, String, String)) -> Expectation) ->+ Expectation+withProgram action = do+ here <- getExecutablePath+ let program = takeDirectory (takeDirectory here) </> "haskoin-store" </> "haskoin-store"+ built <- doesFileExist program+ if not built+ then pendingWith ("The program is not built at " <> program)+ else do+ outer <- filter ((/= "MEMPOOL_WAIT") . fst) <$> getEnvironment+ action $ \vars args ->+ readCreateProcessWithExitCode (proc program args) {env = Just (vars <> outer)} ""
test/Haskoin/Store/DownloadSpec.hs view
@@ -198,6 +198,7 @@ peerTimeout = 60, blockStall = stall, blockPing = 5,+ mempoolWait = 20, maxPeerLife = 48 * 3600, connect = tapped seen, nodePeerRpc = Nothing,
test/Haskoin/Store/Ingest/Model.hs view
@@ -131,6 +131,9 @@ Blocks | -- | the store is out of sync for a while Desyncs+ | -- | the chain moves by more than a block or two, and the store is+ -- out of sync until it has the blocks+ Moves | -- | a peer goes, and comes back PeerDrops | -- | the pool does not answer@@ -160,7 +163,9 @@ data ToNode = MGet ![H] | MSweep deriving (Eq, Ord, Show) -data ToStore = MInv ![H] | MTx !H | MNotFound ![H]+-- | What a node sends; 'MDone' is what its RPC says when it has named its+-- whole mempool, and a peer never sends.+data ToStore = MInv ![H] | MTx !H | MNotFound ![H] | MDone deriving (Eq, Ord, Show) -- | A question to the pool, or an offer with whether it is vouched for.@@ -200,7 +205,7 @@ -- | How far back a time matters in the worlds here: beyond the life of an -- orphan, every age is the same. horizon :: Scenario -> Tick-horizon sc = sc.config.orphanLife + sc.config.patience + 2+horizon sc = sc.config.orphanLife + max sc.config.patience sc.config.sweepWait + 2 settled :: World -> Set H settled w = w.pool `Set.union` w.confirmed@@ -336,9 +341,10 @@ -- decided on all that each such node named when it was last asked and -- has had ever since. --- -- The machine takes a source to have answered when as long passed as- -- a request is given (A10). A world in which requests get no answer in- -- time breaks that on purpose, and is not held to this.+ -- The machine takes a peer to have answered when as long passed as it+ -- is given (A10), and the RPC of a node when it says so. A world in+ -- which requests get no answer in time breaks A10 on purpose, and is+ -- not held to this. when (Timeouts `notElem` sc.disturbances && standing before /= PoolSynced && standing after == PoolSynced) $ do check "the pool is said to be in sync while a node of the operator has not answered for its mempool" $ and [MSweep `notElem` toList q | (p, q) <- Map.toList w.toNode, trustedHere p]@@ -355,12 +361,15 @@ -- between the two it is a stranger to the machine, and this is not asked. case input of PeerUp p _ | p `elem` sc.owned -> return ()+ SourceUp p | p `elem` sc.owned -> return () _ -> check "the pool is said to be in sync, or syncing, with no node of the operator to measure it against" $ (standing after == PoolUnknown) == not (or [trustedHere p | p <- Map.keys w.nodes])- -- and a pool that lost what it had is not in sync+ -- and a pool that lost what it had is not in sync, nor one whose chain+ -- moved far case input of Emptied -> check "the pool lost what it had and is still said to be in sync" (standing after /= PoolSynced)+ Moved -> check "the chain moved far and the pool is still said to be in sync" (standing after /= PoolSynced) _ -> return () -- Until the store first has its blocks, nothing that a peer names or -- sends is taken in, and nothing is asked for it.@@ -460,20 +469,23 @@ MInv hs -> Named p hs MTx h -> Body (Just p) h (B (Map.findWithDefault [] h sc.txs)) MNotFound hs -> Missing p hs+ MDone -> Answered p -- | What a node does with a message of the store (A2, A3). nodeReads :: Scenario -> P -> ToNode -> World -> World nodeReads sc p msg w = case Map.lookup p w.nodes of Nothing -> w Just node -> case msg of+ -- the RPC of a node says when it has named all of it, an empty+ -- mempool too MSweep- | Set.null node.has -> w+ | Set.null node.has -> if rpc then w {toStore = Map.adjust (|> MDone) p w.toStore} else w | otherwise -> w { nodes = Map.insert p node {told = Set.union node.told node.has, answered = node.has} w.nodes, -- A5: parents before children, unless the world is one -- that breaks it- toStore = Map.adjust (|> MInv (sortOn inOrder (Set.toAscList node.has))) p w.toStore+ toStore = Map.adjust (\q -> done (q |> MInv (sortOn inOrder (Set.toAscList node.has)))) p w.toStore } MGet hs -> let (found, lost) = (filter (`Set.member` node.has) hs, filter (`Set.notMember` node.has) hs)@@ -481,6 +493,8 @@ reply = foldl' (|>) (fromMaybe' (Map.lookup p w.toStore)) answers in w {toStore = Map.insert p reply w.toStore} where+ rpc = p `elem` sc.feeds+ done q = if rpc then q |> MDone else q fromMaybe' = maybe Seq.empty id inOrder h = if sc.backwards then negate (depth h) else depth h depth :: H -> Int@@ -543,6 +557,7 @@ all (`Set.member` w.confirmed) (Map.findWithDefault [] h sc.txs) ] Desyncs -> [("the store is out of sync", feed sc (Synced False) w {inSync = False}) | w.inSync]+ Moves -> [("the chain moves far", feed sc Moved w {inSync = False}) | w.inSync] PeerDrops -> [ ( "peer " <> show p <> " is gone", feed@@ -611,13 +626,18 @@ comes :: Scenario -> World -> [(String, Either String World)] comes sc w = [ ( "peer " <> show p <> " connects",- feed sc (PeerUp p node.source) w {nodes = Map.insert p node {online = True} w.nodes}+ feed sc (connecting p node) w {nodes = Map.insert p node {online = True} w.nodes} >>= \x -> if p `elem` sc.owned then feed sc (Own p) x else Right x ) | (p, node) <- Map.toList w.nodes, not node.online, null [() | OCheck q _ <- toList w.asked, q == p] ]+ where+ -- the RPC of a node is a source that says when it has answered+ connecting p node+ | p `elem` sc.feeds = SourceUp p+ | otherwise = PeerUp p node.source -- | T3 at rest: the pool has every transaction of the mempool of every -- source that is connected.@@ -744,6 +764,7 @@ minWindow = 1, maxWindow = 3, patience = 2,+ sweepWait = 2, orphanLife = 6, retry = 1, sweepGap = 2,@@ -787,6 +808,7 @@ minWindow = 1, maxWindow = 2, patience = 1,+ sweepWait = 1, orphanLife = 2, retry = 1, sweepGap = 1,@@ -842,6 +864,32 @@ { oneNode = True, feeds = [1] },+ -- the same, with the node one of the operator, as the RPC that a+ -- store is given always is: its readings count for T9, and they are+ -- whole when the RPC says so, with no time to wait. A reading asked+ -- before the store gave something up, and answered after, is not+ -- whole: with room for one id, the store gives the child up as the+ -- RPC names it.+ (world "one transaction, one node of the operator: its RPC and a peer that is no source" one mixed wavering small)+ { oneNode = True,+ feeds = [1],+ owned = [1]+ },+ (world "a chain of two, room for one id, the RPC of a node of the operator and a peer" chain mixed wavering tight)+ { oneNode = True,+ feeds = [1],+ owned = [1]+ },+ -- a long move of the chain: the store says that it is syncing until+ -- it has the blocks, and then that it has caught up+ (world "a chain of two, a node of the operator, long moves of the chain" chain [(1, True)] [Mempools, Moves] small)+ { owned = [1]+ },+ (world "one transaction, the RPC of a node of the operator and a peer, long moves" one mixed moving small)+ { oneNode = True,+ feeds = [1],+ owned = [1]+ }, -- T8: peer 1 is a stranger and peer 2 a node of the operator. The -- store cannot verify transaction 1, and 2 spends from it. (world "a stranger and a node of the operator, a transaction that cannot be verified" one both wavering small)@@ -888,6 +936,7 @@ ] where losing = [Mempools, PoolEmptied]+ moving = [Mempools, Moves] world name txs peers disturbances config = Scenario { name,@@ -925,6 +974,7 @@ minWindow = 1, maxWindow = 2, patience = 1,+ sweepWait = 1, orphanLife = 2, retry = 1, sweepGap = 1,
test/Haskoin/Store/IngestSpec.hs view
@@ -231,6 +231,64 @@ (s, outs) = run' [Tick 10000, Tick 20000] often length [() | Sweep _ <- outs] `shouldBe` 1 standing s `shouldBe` PoolSynced+ it "is in sync as soon as its node's RPC has named its whole mempool, with no time to wait" $ do+ -- the RPC is asked for the mempool of the node when it connects+ let (rpc, outs) = run' [SourceUp 1, Own 1, Synced True] (start defaultConfig 0 :: Ingest Int Int [Int])+ [p | Sweep p <- outs] `shouldBe` [1]+ standing rpc `shouldBe` PoolSyncing+ -- an empty mempool: in sync at once, at the same moment+ standing (fst (run' [Answered 1] rpc)) `shouldBe` PoolSynced+ -- one transaction: in sync once the pool has it, with no tick+ let (named, _) = run' [Named 1 [7], Answered 1] rpc+ standing named `shouldBe` PoolSyncing+ standing (fst (run' [Checked 1 [] [7], Body (Just 1) 7 [], Offered 7 Settled] named)) `shouldBe` PoolSynced+ it "does not take the answer of the RPC to a reading asked before it may have missed something" $ do+ let rpc = fst (run' [SourceUp 1, Own 1, Synced True] (start defaultConfig 0)) :: Ingest Int Int [Int]+ -- a peer that is no source connects while the reading is on its+ -- way: what the node took before it is owed by the RPC+ (late, outs) = run' [PeerUp 2 False, Answered 1] rpc+ outs `shouldBe` []+ standing late `shouldBe` PoolSyncing+ -- read again after the gap, and that answer counts+ let (again, more) = run' [Tick 10000] late+ [p | Sweep p <- more] `shouldBe` [1]+ standing again `shouldBe` PoolSyncing+ standing (fst (run' [Answered 1] again)) `shouldBe` PoolSynced+ it "waits for a peer the time that it is given, which the configuration says, and takes no word of it" $ do+ let quick = (start defaultConfig {sweepWait = 3000} 0 :: Ingest Int Int [Int])+ peer = fst (run' [PeerUp 1 True, Own 1, Synced True] quick)+ -- a peer of the protocol cannot say that it answered: no word of it+ -- is taken+ standing (fst (run' [Answered 1] peer)) `shouldBe` PoolSyncing+ standing (fst (run' [Tick 2999] peer)) `shouldBe` PoolSyncing+ standing (fst (run' [Tick 3000] peer)) `shouldBe` PoolSynced+ -- and twenty seconds by default+ standing (fst (run' [Tick 19999] ours)) `shouldBe` PoolSyncing+ standing (fst (run' [Tick 20000] ours)) `shouldBe` PoolSynced+ it "says that it is syncing at once when the chain moves far, and is in sync once it has the blocks" $ do+ let rpc = fst (run' [SourceUp 1, Own 1, Synced True, Answered 1] (start defaultConfig 0)) :: Ingest Int Int [Int]+ standing rpc `shouldBe` PoolSynced+ -- a block behind for a moment: still in sync+ standing (fst (run' [Synced False] rpc)) `shouldBe` PoolSynced+ -- the chain moved by more than a block or two: syncing, from the+ -- moment that the store knows it, and while it takes the blocks+ let (moved, outs) = run' [Moved] rpc+ outs `shouldBe` []+ standing moved `shouldBe` PoolSyncing+ standing (fst (run' [Tick 60000] moved)) `shouldBe` PoolSyncing+ -- it has them: the node is read again at once, not ten seconds+ -- after its last reading, and the store is in sync when it answered+ let (back, more) = run' [Synced True] moved+ [p | Sweep p <- more] `shouldBe` [1]+ standing back `shouldBe` PoolSyncing+ standing (fst (run' [Answered 1] back)) `shouldBe` PoolSynced+ -- what the node named while the store was behind is taken in first+ let (busy, _) = run' [Moved, Named 1 [7], Checked 1 [] [7], Synced True, Answered 1] rpc+ standing busy `shouldBe` PoolSyncing+ standing (fst (run' [Body (Just 1) 7 [], Offered 7 Settled] busy)) `shouldBe` PoolSynced+ -- an answer to a reading asked before the move is not whole+ let asked = fst (run' [Tick 60000] rpc)+ standing (fst (run' [Moved, Answered 1, Synced True] asked)) `shouldBe` PoolSyncing it "does not stay in sync when its last node of the operator goes" $ do let synced = fst (run' [Tick 20000] ours) standing synced `shouldBe` PoolSynced
test/Haskoin/Store/IntegrationSpec.hs view
@@ -483,6 +483,7 @@ peerTimeout = 120, blockStall = 10, blockPing = 5,+ mempoolWait = 20, maxPeerLife = 48 * 3600, connect = withConnection, nodePeerRpc = Nothing,
test/Haskoin/Store/MempoolSpec.hs view
@@ -135,6 +135,9 @@ on "A store whose only peer is its node through its RPC and its ZeroMQ socket" $ it "has its blocks, its mempool, what the node takes next and its next block, with no other connection" $ withBed kind (alone . \bed -> bed {viaRpc = True, viaZmq = True})+ on "A store whose only peer is its node through its RPC and its ZeroMQ socket, started again" $+ it "says that its mempool is in sync within seconds, and syncing at once after a long move" $+ withBed kind (readyAtOnce . \bed -> bed {viaRpc = True, viaZmq = True}) on "A store whose only peer is its node through its RPC and its ZeroMQ socket, when the node stops" $ it "has no peer and says so, and has its node again when the node goes on" $ withBed kind (nodeStops . \bed -> bed {viaRpc = True, viaZmq = True})@@ -346,6 +349,45 @@ converges bed server 30 void (generateTo bed.node 1 bed.miner) converges bed server 30++-- | A store whose only peer is its node through its RPC, started again+-- on a database at the tip. The RPC says when it has named the whole+-- mempool of the node ("Haskoin.Store.Ingest"): the store says that its+-- mempool is in sync as soon as it has taken in what the node named, and+-- not after the time that a peer is given to name it, twenty seconds by+-- default. A regtest that waited for that before each of its tests took+-- four times as long. It prints the time, which the report of the change+-- quotes.+readyAtOnce :: Bed -> IO ()+readyAtOnce bed = withRamDir $ \dir -> do+ roots <- fund bed 4+ submit bed (map (chainOf 2) roots)+ let only = withMemberOf (\c -> c {initPeers = []} :: StoreConfig) bed dir+ only $ \_ server -> do+ converges bed server 120+ standing server "synced" 120+ -- Twenty blocks at once. When the store learns of them in one piece+ -- it says that it is syncing at once, and reads its node again as+ -- soon as it has them; in pieces of a block or two, it goes on saying+ -- that it is in sync. Either way it is in sync a moment after it has+ -- them, with no wait for a peer, nor for the gap between readings.+ -- This is before the store is started again: the store that was+ -- stopped keeps its report in the fleet for the ten seconds of its+ -- lease, and the tip of the fleet waits for it.+ hs <- generateTo bed.node 20 bed.miner+ mined <- getPOSIXTime+ converges bed server 60+ standing server "synced" 20+ back <- getPOSIXTime+ hPutStrLn stderr ("It was in sync again " <> show (back - mined) <> " after twenty blocks were found")+ (back - mined) `shouldSatisfy` (< 10)+ length hs `shouldBe` 20+ begun <- getPOSIXTime+ only $ \_ server -> do+ standing server "synced" 120+ ready <- getPOSIXTime+ hPutStrLn stderr ("The store said that its mempool is in sync " <> show (ready - begun) <> " after it started")+ (ready - begun) `shouldSatisfy` (< 10) -- | A node publishes over ZeroMQ the id of every transaction of a block -- that stops being part of its chain, the coinbase too, as it does of one