packages feed

haskoin-node 2.6.1 → 2.7.0

raw patch · 30 files changed

+3117/−939 lines, 30 filesdep +podman-testdep ~asyncdep ~bytestringdep ~cerealPVP ok

version bump matches the API change (PVP)

Dependencies added: podman-test

Dependency ranges changed: async, bytestring, cereal, conduit, containers, fast-logger, haskoin-core, network, nqe, random, rocksdb-haskell-jprupp, stm, text, time

API changes (from Hackage documentation)

- Haskoin.Node.Peer: wrapPeer :: PeerConfig -> TVar (Lock Owner) -> TVar Int -> Mailbox PeerMessage -> Peer
+ Haskoin.Node: Allowed :: Judgement
+ Haskoin.Node: PermAddr :: Permission
+ Haskoin.Node: PermBloomFilter :: Permission
+ Haskoin.Node: PermDownload :: Permission
+ Haskoin.Node: PermForceRelay :: Permission
+ Haskoin.Node: PermImplicit :: Permission
+ Haskoin.Node: PermMempool :: Permission
+ Haskoin.Node: PermNoBan :: Permission
+ Haskoin.Node: PermRelay :: Permission
+ Haskoin.Node: Refused :: !Action -> !Cite -> Judgement
+ Haskoin.Node: Unanswered :: !Cite -> Judgement
+ Haskoin.Node: [permissions] :: NodeConfig -> !Permissions
+ Haskoin.Node: data Judgement
+ Haskoin.Node: data Permission
+ Haskoin.Node: expectsReject :: Network -> Version -> Bool
+ Haskoin.Node: judgementText :: Judgement -> Text
+ Haskoin.Node: type Permissions = Set Permission
+ Haskoin.Node.Address: peerHostAddress :: SockAddr -> HostAddress
+ Haskoin.Node.Address: seenAs :: SockAddr -> (AddressNetwork, Bool)
+ Haskoin.Node.Chain: chainHasHeaders :: Chain -> IO Bool
+ Haskoin.Node.Peer: NotSent :: !Message -> !Judgement -> PeerMessage
+ Haskoin.Node.Peer: [bestBlock] :: PeerConfig -> !IO BlockNode
+ Haskoin.Node.Peer: [closing] :: Peer -> !TVar Bool
+ Haskoin.Node.Peer: [facts] :: Peer -> !Message -> IO Facts
+ Haskoin.Node.Peer: [owed] :: Peer -> !TVar (Maybe Word64)
+ Haskoin.Node.Peer: [remote] :: Peer -> !TVar Remote
+ Haskoin.Node.Peer: [requestLock] :: Peer -> !TMVar ()
+ Haskoin.Node.Peer: judgeMessage :: Peer -> Message -> IO Judgement
+ Haskoin.Node.Peer: newPeer :: PeerConfig -> Mailbox PeerMessage -> IO Peer
+ Haskoin.Node.Peer.Remote: Allowed :: Judgement
+ Haskoin.Node.Peer.Remote: Facts :: !Micros -> !BlockNode -> !Map BlockHash BlockNode -> Facts
+ Haskoin.Node.Peer.Remote: Refused :: !Action -> !Cite -> Judgement
+ Haskoin.Node.Peer.Remote: Unanswered :: !Cite -> Judgement
+ Haskoin.Node.Peer.Remote: [best] :: Facts -> !BlockNode
+ Haskoin.Node.Peer.Remote: [known] :: Facts -> !Map BlockHash BlockNode
+ Haskoin.Node.Peer.Remote: [now] :: Facts -> !Micros
+ Haskoin.Node.Peer.Remote: data Facts
+ Haskoin.Node.Peer.Remote: data Judgement
+ Haskoin.Node.Peer.Remote: data Remote
+ Haskoin.Node.Peer.Remote: expectsReject :: Network -> Version -> Bool
+ Haskoin.Node.Peer.Remote: instance GHC.Classes.Eq Haskoin.Node.Peer.Remote.Judgement
+ Haskoin.Node.Peer.Remote: instance GHC.Internal.Show.Show Haskoin.Node.Peer.Remote.Judgement
+ Haskoin.Node.Peer.Remote: judge :: Facts -> Message -> Remote -> (Judgement, Remote)
+ Haskoin.Node.Peer.Remote: judgementText :: Judgement -> Text
+ Haskoin.Node.Peer.Remote: learnVersion :: Version -> Remote -> Remote
+ Haskoin.Node.Peer.Remote: learnedVersion :: Remote -> Maybe Version
+ Haskoin.Node.Peer.Remote: newRemote :: Network -> Permissions -> AddressNetwork -> Bool -> Micros -> Word64 -> Remote
+ Haskoin.Node.Peer.Remote: predict :: Facts -> Message -> Remote -> ([Effect], Remote)
+ Haskoin.Node.Peer.Remote: remoteClock :: Remote -> Micros
+ Haskoin.Node.Peer.Remote: remoteConnection :: Remote -> Connection
+ Haskoin.Node.Peer.Remote: remoteSetup :: Remote -> Setup
+ Haskoin.Node.Peer.Request: Disconnected :: RequestInput
+ Haskoin.Node.Peer.Request: Received :: !Message -> RequestInput
+ Haskoin.Node.Peer.Request: data RequestInput
+ Haskoin.Node.Peer.Request: instance GHC.Classes.Eq Haskoin.Node.Peer.Request.RequestInput
+ Haskoin.Node.Peer.Request: instance GHC.Internal.Show.Show Haskoin.Node.Peer.Request.RequestInput
+ Haskoin.Node.PeerMgr: [bestBlock] :: PeerMgrConfig -> !IO BlockNode
+ Haskoin.Node.PeerMgr: [configured] :: OnlinePeer -> !Bool
+ Haskoin.Node.PeerMgr: [permissions] :: PeerMgrConfig -> !Permissions
+ Haskoin.Node.PeerMgr.Addresses: configuredBackoff :: NominalDiffTime
+ Haskoin.Node.PeerMgr.Addresses: roomForOthers :: Eq a => Int -> [[a]] -> [a] -> Bool
+ Haskoin.Node.PeerMgr.Lifecycle: Abort :: !DisconnectReason -> PeerAction
+ Haskoin.Node.Router: Announce :: !k -> RouterAction k m
+ Haskoin.Node.Router: Announced :: Route m
+ Haskoin.Node.Router: Arrived :: !k -> !m -> RouterInput k m
+ Haskoin.Node.Router: Awaiting :: !Seq m -> Route m
+ Haskoin.Node.Router: Connected :: !k -> RouterInput k m
+ Haskoin.Node.Router: Deliver :: !k -> !m -> RouterAction k m
+ Haskoin.Node.Router: Discard :: !k -> !m -> RouterAction k m
+ Haskoin.Node.Router: Disconnected :: !k -> RouterInput k m
+ Haskoin.Node.Router: Early :: !k -> !m -> RouterAction k m
+ Haskoin.Node.Router: HandshakeDone :: !k -> RouterInput k m
+ Haskoin.Node.Router: Retire :: !k -> RouterAction k m
+ Haskoin.Node.Router: data Route m
+ Haskoin.Node.Router: data Router k m
+ Haskoin.Node.Router: data RouterAction k m
+ Haskoin.Node.Router: data RouterInput k m
+ Haskoin.Node.Router: instance (GHC.Classes.Eq k, GHC.Classes.Eq m) => GHC.Classes.Eq (Haskoin.Node.Router.Router k m)
+ Haskoin.Node.Router: instance (GHC.Classes.Eq m, GHC.Classes.Eq k) => GHC.Classes.Eq (Haskoin.Node.Router.RouterAction k m)
+ Haskoin.Node.Router: instance (GHC.Classes.Eq m, GHC.Classes.Eq k) => GHC.Classes.Eq (Haskoin.Node.Router.RouterInput k m)
+ Haskoin.Node.Router: instance (GHC.Internal.Show.Show k, GHC.Internal.Show.Show m) => GHC.Internal.Show.Show (Haskoin.Node.Router.Router k m)
+ Haskoin.Node.Router: instance (GHC.Internal.Show.Show m, GHC.Internal.Show.Show k) => GHC.Internal.Show.Show (Haskoin.Node.Router.RouterAction k m)
+ Haskoin.Node.Router: instance (GHC.Internal.Show.Show m, GHC.Internal.Show.Show k) => GHC.Internal.Show.Show (Haskoin.Node.Router.RouterInput k m)
+ Haskoin.Node.Router: instance GHC.Classes.Eq m => GHC.Classes.Eq (Haskoin.Node.Router.Route m)
+ Haskoin.Node.Router: instance GHC.Internal.Show.Show m => GHC.Internal.Show.Show (Haskoin.Node.Router.Route m)
+ Haskoin.Node.Router: newRouter :: Router k m
+ Haskoin.Node.Router: routeOf :: Eq k => k -> Router k m -> Maybe (Route m)
+ Haskoin.Node.Router: stepRouter :: Eq k => RouterInput k m -> Router k m -> (Router k m, [RouterAction k m])
- Haskoin.Node: NodeConfig :: !Int -> !DB -> !Maybe ColumnFamily -> ![String] -> !Bool -> !NetworkAddress -> !Network -> !Publisher NodeEvent -> !NominalDiffTime -> !NominalDiffTime -> !SockAddr -> WithConnection -> !Logger -> NodeConfig
+ Haskoin.Node: NodeConfig :: !Int -> !DB -> !Maybe ColumnFamily -> ![String] -> !Bool -> !NetworkAddress -> !Network -> !Publisher NodeEvent -> !NominalDiffTime -> !NominalDiffTime -> !SockAddr -> WithConnection -> !Logger -> !Permissions -> NodeConfig
- Haskoin.Node.Peer: Peer :: !Mailbox PeerMessage -> !Publisher PeerEvent -> !Text -> !TVar (Lock Owner) -> !TVar Int -> Peer
+ Haskoin.Node.Peer: Peer :: !Mailbox PeerMessage -> !Publisher PeerEvent -> !Text -> !TVar (Lock Owner) -> !TVar Int -> !TVar Remote -> !Message -> IO Facts -> !TVar Bool -> !TMVar () -> !TVar (Maybe Word64) -> Peer
- Haskoin.Node.Peer: PeerConfig :: !Publisher PeerEvent -> !Network -> !Text -> !WithConnection -> !Logger -> !BlockHash -> IO (Maybe BlockNode) -> PeerConfig
+ Haskoin.Node.Peer: PeerConfig :: !Publisher PeerEvent -> !Network -> !Text -> !WithConnection -> !Logger -> !BlockHash -> IO (Maybe BlockNode) -> !IO BlockNode -> !Remote -> PeerConfig
- Haskoin.Node.Peer.Request: newRequest :: Word64 -> [InvVector] -> RequestStep
+ Haskoin.Node.Peer.Request: newRequest :: Maybe Word64 -> Word64 -> [InvVector] -> RequestStep
- Haskoin.Node.Peer.Request: stepRequest :: Request -> Message -> RequestStep
+ Haskoin.Node.Peer.Request: stepRequest :: Request -> RequestInput -> RequestStep
- Haskoin.Node.PeerMgr: Disconnecting :: !DisconnectReason -> Stage
+ Haskoin.Node.PeerMgr: Disconnecting :: !DisconnectReason -> !UTCTime -> Stage
- Haskoin.Node.PeerMgr: OnlinePeer :: !SockAddr -> !PeerState -> !Async () -> !Peer -> !Word64 -> OnlinePeer
+ Haskoin.Node.PeerMgr: OnlinePeer :: !SockAddr -> !PeerState -> !Async () -> !Peer -> !Word64 -> !Bool -> OnlinePeer
- Haskoin.Node.PeerMgr: PeerMgrConfig :: !Int -> ![String] -> !Bool -> !NetworkAddress -> !Network -> !Publisher PeerEvent -> !NominalDiffTime -> !NominalDiffTime -> !SockAddr -> WithConnection -> !Logger -> !BlockHash -> IO (Maybe BlockNode) -> PeerMgrConfig
+ Haskoin.Node.PeerMgr: PeerMgrConfig :: !Int -> ![String] -> !Bool -> !NetworkAddress -> !Network -> !Publisher PeerEvent -> !NominalDiffTime -> !NominalDiffTime -> !SockAddr -> WithConnection -> !Logger -> !BlockHash -> IO (Maybe BlockNode) -> !IO BlockNode -> !Permissions -> PeerMgrConfig
- Haskoin.Node.PeerMgr.Lifecycle: Disconnecting :: !DisconnectReason -> Stage
+ Haskoin.Node.PeerMgr.Lifecycle: Disconnecting :: !DisconnectReason -> !UTCTime -> Stage
- Haskoin.Node.PeerMgr.Lifecycle: GotHandshake :: !HandshakeEvent -> PeerInput
+ Haskoin.Node.PeerMgr.Lifecycle: GotHandshake :: !UTCTime -> !HandshakeEvent -> PeerInput
- Haskoin.Node.PeerMgr.Lifecycle: Limits :: !NominalDiffTime -> !NominalDiffTime -> Limits
+ Haskoin.Node.PeerMgr.Lifecycle: Limits :: !NominalDiffTime -> !Maybe NominalDiffTime -> Limits
- Haskoin.Node.PeerMgr.Lifecycle: Refused :: !HandshakeError -> PeerInput
+ Haskoin.Node.PeerMgr.Lifecycle: Refused :: !UTCTime -> !HandshakeError -> PeerInput
- Haskoin.Node.PeerMgr.Lifecycle: [maxLife] :: Limits -> !NominalDiffTime
+ Haskoin.Node.PeerMgr.Lifecycle: [maxLife] :: Limits -> !Maybe NominalDiffTime

Files

CHANGELOG.md view
@@ -4,6 +4,206 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [Unreleased]++## [2.7.0] - 2026-11-25++Peers on Unix sockets, a model of the node at the other end of each+connection, and haskoin-core 3.0, for haskoin-store 2.0.0.++Configured peers are kept. This breaks code that builds an `OnlinePeer`+or a `Limits` by hand: `OnlinePeer` has a new field, and `maxLife` of+`Limits` is a `Maybe`.++### Added+- **A model of each peer's node.** Every connection runs the state machine+  of haskoin-core's `Haskoin.Network.Protocol` for its network: Bitcoin+  Core 32.1 or Bitcoin Cash Node 29.2.0, translated from their source, with+  this node as the peer (`Haskoin.Node.Peer.Remote`). `sendMessage`+  judges every message as it queues it, so that the model sees the messages+  in the order in which they go out. One that the node would punish+  (ban score, discouragement, a ban, or a disconnection for a rule of the+  protocol) is not sent, and the log says why, with the upstream line. A+  request in `getData`, `getBlocks` or `getTxs` that the node would drop+  without an answer gives `Nothing` at once rather than wait for the+  timeout. `judgeMessage` asks without sending. The model takes the options+  of the node from its version message (Bloom filters, pruning, blocks-only)+  and plays the messages sent before it again with them. It takes the node+  to have every block it is asked for, and leaves to happen what depends on+  the guessed state of the node, such as its upload limit.+- `permissions` in `NodeConfig` and `PeerMgrConfig`: the permissions that+  the nodes of `peers` grant this node with `-whitelist` or `-whitebind`,+  such as `PermMempool`. Nothing in the protocol tells a peer, so the+  operator says it. Discovered peers grant none. `Permission` and+  `Permissions` are re-exported from `Haskoin.Node`.+- `expectsReject`: whether the node of a network answers a transaction that+  it refuses with a `reject` message (BIP 61), as Bitcoin Cash Node does and+  Bitcoin Core never does, asked of the model.+- `newPeer` builds a `Peer` handle with a free lock, no pending messages and+  the model of its configuration.+- `seenAs` in `Haskoin.Node.Address`: the address network of a peer and+  whether the node sees this node at a local address, for its model.+- Tests: the model's rules for the mempool request, the handshake order,+  filtered blocks and the replay after the version. In regtest, against+  both nodes: the messages that the node sends up to its verack are the+  ones that the model predicts, a mempool request goes only where the node+  takes it, and a node that whitelists the store with `mempool` answers it.+- **Peers on Unix sockets.** A configured peer can be a Unix socket, written+  `unix:PATH` as Bitcoin Core writes the socket of a proxy, and+  `withConnection` opens it. Neither Bitcoin Core nor Bitcoin Cash Node+  listens on one, so something joins the socket to a node, such as socat or+  the bridge of a test in a container: tests that run at once then reach+  their nodes without taking a port of the machine. Such a peer is in the+  local network group, and the version message gives it the zero address,+  with the new `peerHostAddress`: haskoin-core's `sockToHostAddress` stops+  the program on an address that is not IPv4 or IPv6. A peer or a DNS seed+  can never give a Unix address.+- `chainHasHeaders`: whether a peer is connected and headers are awaited+  from none. Unlike `chainIsSynced` it does not ask that the best block be+  recent, and it is not kept once true: it tells a node that is still+  taking headers from one that has them, on a network where no block was+  found for hours too.+- `configured` in `OnlinePeer`: whether the peer is one of the+  configuration.++### Fixed+- **A peer is announced before its messages.** A peer's messages come from+  its reader and its announcement from the peer manager, through one queue+  with no order between them. Messages sent right behind the handshake could+  reach the chain and the application before `PeerConnected`, and the chain+  dropped the headers of a peer it did not know yet. The router now runs a+  pure machine (`Haskoin.Node.Router`) that holds such messages until the+  announcement comes through the queue: for each peer, `PeerConnected` comes+  before any message past the handshake, and `PeerDisconnected` after all+  of them.+- **A disconnection always ends.** `killPeer` queued `KillPeer` behind the+  messages to send, and a writer blocked on a peer that stopped reading+  never took it: the connection kept its slot and network group forever,+  and `PeerDisconnected` never came. The process now races its connection+  against a `closing` flag that `killPeer` sets, and the peer manager+  cancels the thread of a process that is still there a timeout after it+  was told to disconnect (the new `Abort` action of+  `Haskoin.Node.PeerMgr.Lifecycle`). `killPeer` no longer sends the+  messages queued before it.+- **Requests end when their peer goes.** `getData`, `getBlocks`, `getTxs`+  and `pingPeer` give `Nothing` or `False` at once when `PeerDisconnected`+  comes for their peer, or when the peer is closing as they start, rather+  than wait for the timeout.+- **Requests on one peer no longer disturb each other.** Two at once took+  each other's blocks and failed as out of order, and so did a request after+  one that timed out, from its late answers. Requests now run one at a time+  per peer, the timeout counting the wait, and a request first ignores what+  the peer sends until the pong of the request before it, if that is still+  owed.+- **The model of a peer never sees time go back.** Two threads sending at+  once read the clock before their transactions and could commit in the+  other order. The model keeps the latest time it has seen, and judges with+  the later of that and the time of the facts (`remoteClock`).++### Changed+- **fast-logger 3.3 is accepted** (`>= 3.2 && < 3.4`, where it was+  `< 3.3`), which Stackage asked for+  ([stackage#8183](https://github.com/commercialhaskell/stackage/issues/8183)).+  No code changes. Tested: the whole suite passes with fast-logger 3.3.0,+  against both nodes too. `stack.yaml` still builds with 3.2.9, the+  version of its snapshot.+- **Every concurrent protocol is a pure machine.** The new+  [docs/concurrency.md](docs/concurrency.md) says, for every thread, what it+  owns, the machine that decides what it does, and why no two threads can+  race. The README links it.+- `Stage`: `Disconnecting` holds when the disconnection began, as+  `Disconnecting reason time`. `PeerInput`: `GotHandshake` and `Refused`+  take the time first. `PeerAction` has `Abort`.+- `Haskoin.Node.Peer.Request`: `stepRequest` takes a `RequestInput`+  (`Received` a message, or `Disconnected`), and `newRequest` takes first+  the nonce of the ping that the request before it is still owed, if any.+  A notfound or block for an item not asked for is ignored, as before; the+  rule is now written down.+- `Peer` has three new fields, `closing`, `requestLock` and `owed`.+  `wrapPeer` is gone: `newPeer` is the one way to build a `Peer`.+- `peerMessageDone` documents its invariant: once for each message, by one+  consumer. The router disposes of every message exactly once.+- Tests: QuickCheck properties of the router over arbitrary interleavings of+  three peers, of the abort of a disconnection, of requests after an owed+  pong and of the model's clock; a peer process that stops while its writer+  is blocked; requests that end when their peer goes; overlapping requests+  and the late answers of a request that timed out; and a node that+  publishes a peer before the burst it sends right behind its handshake.+- `PeerConfig` has two new fields, `bestBlock` and `remote` (the model when+  the connection opens). `Peer` has two, `remote` and `facts`. Build a+  `Peer` with `newPeer`.+  `PeerMessage` has a new constructor, `NotSent`, for a message that the+  model refused, which the peer process logs.+- **Tests of an honest peer run against real nodes.** What the mock peers+  of the unit tests did as an honest node would, the regtest tests now+  check against Bitcoin Core and Bitcoin Cash Node in Podman: a block as the+  node keeps it, with its witness; a block of more than 2 MiB on Bitcoin+  Cash; a peer that hangs (a node stopped with `SIGSTOP`), whose blocks and+  pings give nothing and which is dropped; a peer kept past its longest+  life; the pings of the node; a pruned node, refused; the wait before+  trying a failed peer again; the minimum chain work; the parents of a+  block; and no more requests for headers once the node has them all. The+  mock versions are gone. Peers that break the rules stay scripted in+  memory, since no real node does, and every peer of a test is named by a+  Unix socket, not by an address and a port. Each node has two groups of+  regtest tests, its chain and its one peer, which run at the same time.+- Needs haskoin-core 3.0, for its protocol machines. 3.0 also reads the+  token prefix of Bitcoin Cash outputs (CashTokens) and adds a field to+  `Network`, which change nothing here: haskoin-node passes outputs on as+  they are, and builds no `Network` of its own.+- CI runs through the workflow that the Haskell packages of jprupp share in+  [jprupp/tools](https://github.com/jprupp/tools), with the check of+  `stack.yaml` for local paths (`check-stack-paths`) and the cache of the+  Nix build kept per release of nixpkgs.+- `scripts/check-local-deps.sh` is gone: `check-stack-paths`, from+  jprupp/tools, replaces it.+- `haskell-dev`, from jprupp/tools, is the fast loop of work on the code:+  `build`, `test` and `docs`, without optimisation and with the unit tests+  in several processes. What it needs to know about this package, the slow+  spec modules, is in the new `haskell-dev.toml`.+- `.gitignore` ignores `TAGS` and `dist-newstyle/` again, which ran+  together on one line, and the documentation's work folder.+- The regtest tests run their containers through+  [podman-test](https://github.com/jprupp/podman-test), in place of the code+  of their own in `Regtest.Podman`: each container is in a pod with no+  network, the peer-to-peer port of each of its nodes is bridged to a Unix+  socket, and the node under test reaches the nodes as the peers+  `unix:PATH`. Inside the container the ports are fixed, where they were+  random. `PODMAN_TEST_SKIP` skips the tests, as `HASKOIN_NODE_SKIP_REGTEST`+  still does, and the Containerfile makes its script executable as it+  copies it, since podman-test writes the files of the context without+  their modes.+- The regtest tests are in the `spec` suite (`Haskoin.Node.RegtestSpec`),+  so that `stack test` and `haskell-dev test` run every test; the `regtest`+  suite is gone. They are still skipped without Podman or with+  `HASKOIN_NODE_SKIP_REGTEST` set, and CI still runs them in a job of their+  own. The container of the nodes may use 2 GiB of memory.+- **The peers of the configuration are sticky.** They are the peers that+  the operator trusts, and the only reason for one to have no connection+  is now that it takes none.+  - **Never rotated.** `maxPeerLife` no longer applies to a configured+    peer. Rotation defends against peers that nobody chose. `maxLife` of+    `Limits` is `Nothing` for such a connection.+  - **Tried again within ten seconds, for ever.** A configured address+    that failed waited twice as long each time, up to ten minutes, and+    ten minutes after its peer broke the protocol. It now waits ten+    seconds at most, whatever ended the last connection+    (`configuredBackoff`). A node of the operator that restarts is a peer+    again within seconds.+  - **Its slot is kept.** While a configured peer had no connection, seed+    and gossiped addresses filled every slot, and the peer found none+    when it came back, until one of them left. A slot is now kept for+    each configured peer that has no connection, and no other address+    takes it (`roomForOthers`). One name is one peer, whatever it+    resolves to.+  - Tested: the two rules of the address book, as examples and with a+    property; that a connection without a longest life is not dropped+    for its age; and, against Bitcoin Core and Bitcoin Cash Node, that a+    configured peer stays past `maxPeerLife`, where the same test said+    before that it was dropped. Not tested end to end: a store with+    discovery whose configured peer is away, which needs a network of+    strangers.+ ## [2.6.1] - 2026-11-18  ### Fixed
README.md view
@@ -79,6 +79,18 @@   written down as a pure state machine. A message that does not fit the current   state is refused instead of handled by accident, and every rule is tested   without a network.+- **Races ruled out by construction.** Every concurrent protocol, from the+  threads of one connection to the routing of events, is a pure state+  machine; the threads only carry out what it decides. Each piece of state has+  one owner, or changes in one STM transaction per decision, or keeps its+  order through a single queue. [docs/concurrency.md](docs/concurrency.md)+  says which, protocol by protocol.+- **The rules of the other node, not guesses.** Bitcoin Core and Bitcoin+  Cash Node decide what a peer may send, and much of it is in no BIP. Every+  message to a peer is first judged by a model of the node at the other end,+  the state machines that haskoin-core translates from the source of both+  nodes. A message that the node would punish is not sent, and the log cites+  the upstream line of the rule. See [What a peer allows](#what-a-peer-allows). - **Plain `IO`.** Every function runs in `IO`, with no monad transformers and   no `MonadIO` or `MonadUnliftIO` constraints. Types say exactly what runs, GHC   has nothing to specialise, and long-running loops cannot leak through an@@ -96,10 +108,11 @@ | --------------- | ---------------------------------------------------------------------------------------------- | | Networks        | Every network of haskoin-core: Bitcoin and Bitcoin Cash mainnet, testnets and regtest           | | Peer discovery  | DNS seeds and addresses relayed by peers, or a static list of peers                             |-| Peer management | Version handshake, ping-based latency, peers sorted by median ping, rotation after a maximum age, retry backoff and bans for bad addresses, random choice among learned addresses with one connection per network group |+| Peer management | Version handshake, ping-based latency, peers sorted by median ping, rotation after a maximum age, retry backoff and bans for bad addresses, random choice among learned addresses with one connection per network group; configured peers kept: never rotated, tried again within ten seconds for ever, with a slot kept for each while it is away | | Header sync     | Headers downloaded from one peer at a time, with a deadline per turn, connected to the chain with the most work, stored in RocksDB; new blocks followed whether peers announce them with headers or inventory, announcing peers asked at once, and peers polled after a quiet period | | Events          | Best header changes, sync completion, peer connections and every message received              | | Data requests   | Fetch blocks and transactions from a peer, with a timeout; every block checked against its header's Merkle root and witness commitment |+| Protocol model  | Every outgoing message judged by a model of the node at the other end (Bitcoin Core 32.1 or Bitcoin Cash Node 29.2.0, from haskoin-core): what the node would punish is not sent, and a request it would drop fails at once | | Protection      | Strict parsing, per-command size limits, linear-time reads, back-pressure, bounded address pool, explicit handshake states, connect timeout |  ### What is not included@@ -239,7 +252,8 @@                     timeout = 120,                     maxPeerLife = 48 * 3600,                     connect = withConnection,-                    logger = logger+                    logger = logger,+                    permissions = mempty                   }           withNode cfg $ \_node -> forever $             receive events >>= \case@@ -355,9 +369,12 @@ | `Haskoin.Node.Chain.Sync`        | Which peer to ask for headers, and when headers count as synced | | `Haskoin.Node.Peer.Request`      | Receiving requested blocks and transactions                    | | `Haskoin.Node.Peer.Lock`         | Who may hold a peer for a long conversation                    |+| `Haskoin.Node.Router`            | The order of each peer's events: announced before its messages |  The processes store the state and carry out what a transition says. Time is an input to the transitions, so every timing rule is tested without waiting.+[docs/concurrency.md](docs/concurrency.md) has, for every thread, what it owns+and why no two threads get in each other's way.  `Haskoin.Node.Block` is a pure check of another kind: whether the transactions of a block are the ones its header commits to. Every block a peer@@ -379,7 +396,10 @@ | `PeerEvent (PeerMessage peer msg)`      | An online peer sent a message: `MInv`, `MBlock`, `MTx` and so on |  Messages are published only from peers that are online, except `version` and-`verack`, which are the handshake itself. A block in an `MBlock` message has+`verack`, which are the handshake itself. For each peer, `PeerConnected` comes+before any other message of the peer, and `PeerDisconnected` after all of+them, even when the peer sends right behind its handshake: the node holds such+messages until the announcement has gone out (`Haskoin.Node.Router`). A block in an `MBlock` message has passed `blockMutation`: its transactions hash to the Merkle root of its header, and its witness data matches its coinbase when the node knows its parent. Nothing else about it is checked, and a transaction in an `MTx` message is not@@ -432,17 +452,23 @@  `getBlocks`, `getTxs` and `getData` return `Nothing` if the peer does not send everything, in order, before the timeout in seconds. Unrelated messages that the-peer sends in between are ignored. `pingPeer` measures a round trip.+peer sends in between are ignored. If the peer disconnects, they return+`Nothing` at once. Requests on one peer run one after the other, and the+timeout counts the wait: two at once would take each other's blocks for their+own. The late answers of a request that timed out do not disturb the next one.+`pingPeer` measures a round trip, and gives `False` at once if the peer+disconnects.  A block that `getBlocks` returns holds the transactions its header commits to. A peer that sends another block under the requested header is disconnected,-and the request gives `Nothing` when it times out. The transactions are not+and the request gives `Nothing`. The transactions are not validated otherwise. A transaction from `getTxs` is matched by its id, which does not cover its witness, so treat its witness data as unauthenticated until you find the transaction in a block.  `getPeers` leaves out peers that are being disconnected, even before their-connection closes.+connection closes. `killPeer` closes a connection at once, without sending the+messages still queued for it, even when the peer has stopped reading.  For a conversation that spans many messages, such as downloading a long run of blocks, reserve the peer first so that no other task uses it at the same time.@@ -489,10 +515,70 @@ ### Custom connections  `connect` decides how to open a connection. `withConnection` opens a plain TCP-socket, and gives up if it does not open within five seconds (`connectTimeout`,-as in Bitcoin Core). Replace it to go through a proxy, or to plug in mock peers-in tests, as the test suite does.+socket, or a Unix socket for a peer written `unix:PATH`, and gives up if it+does not open within five seconds (`connectTimeout`, as in Bitcoin Core).+Replace it to go through a proxy, or to plug in scripted peers in tests, as the+test suite does. +### Peers on Unix sockets++A peer in `peers` can be a Unix socket, written `unix:PATH`, as Bitcoin Core+writes the socket of a proxy. Neither Bitcoin Core nor Bitcoin Cash Node+listens on a Unix socket, so something joins the socket to a node: socat, or+the bridge of a test that runs its node in a container, such as+[podman-test](https://github.com/jprupp/podman-test). Tests that run at once+then reach their nodes through sockets of their own, with no port of the+machine taken. The version message gives such a peer the zero address, as+Bitcoin Core does when it does not know one. A peer or a DNS seed can never+give the node a Unix address: relayed addresses are IPv4 or IPv6.++### What a peer allows++Bitcoin Core and Bitcoin Cash Node punish a peer for things that no BIP+mentions. Ask either for its mempool without being whitelisted, and unless+it offers Bloom filters it closes the connection. haskoin-core translates+both nodes into pure state machines (`Haskoin.Network.Protocol`), and every+peer runs one, as a model of the node at the other end+(`Haskoin.Node.Peer.Remote`). Each message is judged on its way out:++- `Allowed`: the node takes it, and answers it if it is a request.+- `Unanswered`: the node drops it without a word. `getData`, `getBlocks` and+  `getTxs` give `Nothing` at once rather than wait for their timeout.+- `Refused`: the node would add to this node's ban score, discourage it,+  ban it, or close the connection. The peer process does not send it, and+  logs a warning with the reason and the upstream line, such as+  `not sending cmd "mempool": the node would disconnect (ProtocolViolation):+  mempool request with bloom filters disabled (src/net_processing.cpp:5195)`.++To ask before sending, use `judgeMessage`:++```haskell+judgeMessage peer MMempool >>= \case+  Allowed -> MMempool `sendMessage` peer+  verdict -> putStrLn ("Not asking: " <> T.unpack (judgementText verdict))+```++The model learns the options of the node from its version message: whether+it offers Bloom filters, whether it is pruned, whether it relays+transactions. What the node does not say is which permissions it gave this+node with `-whitelist` or `-whitebind`. If you run the nodes of `peers`, say+it in `permissions`:++```haskell+cfg {peers = ["127.0.0.1:8335"], permissions = Set.fromList [PermMempool, PermNoBan]}+```++The permissions apply to the configured peers only, since a peer found+through discovery has granted none.++The model knows the protocol exactly and the chain of the node only as well+as this node does. It takes the node to have every block it is asked for, so+it never fails a request on a guess that the node lacks a block. It also+does not refuse a message over a disconnection that depends on the state of+the node, such as an upload limit it reached. The haskoin-core report+[`doc/protocol`](https://github.com/jprupp/haskoin-core/tree/master/doc/protocol)+describes the rules of both nodes in prose.+ ### Logging  `withLogger level` logs to standard error, one line per message, such as@@ -515,15 +601,16 @@ | `maxPeers`    | Maximum number of peers to connect to                                     | | `db`          | RocksDB handle for the headers                                            | | `cf`          | Column family for the headers, or `Nothing` for the default one           |-| `peers`       | Static peers, as `host`, `host:port` or `[ipv6]:port`                     |+| `peers`       | Static peers, as `host`, `host:port`, `[ipv6]:port` or `unix:PATH`        | | `discover`    | Use DNS seeds and addresses relayed by peers                              | | `address`     | This node's address, sent in version messages                             | | `net`         | Network constants from haskoin-core (`btc`, `bch`, `btcTest`, ...)        | | `pub`         | Publisher that receives every `NodeEvent`                                 | | `timeout`     | Seconds of silence, without a pong, or without completing the handshake, before a peer is dropped; also how long the syncing peer may take to send headers, and the quiet period after which every peer is asked for headers |-| `maxPeerLife` | Seconds after which a peer is dropped, so that connections rotate         |+| `maxPeerLife` | Seconds after which a peer is dropped, so that connections rotate. Not the peers of `peers`: a configured peer is kept | | `connect`     | How to open a connection; usually `withConnection`                        | | `logger`      | Where to log; see `withLogger`                                            |+| `permissions` | Permissions that the nodes of `peers` grant this node with `-whitelist` or `-whitebind`, such as `PermMempool`; see [What a peer allows](#what-a-peer-allows) |  ## Module overview @@ -532,10 +619,11 @@ | Part           | Contents                                                                    | | -------------- | --------------------------------------------------------------------------- | | Node           | `NodeConfig`, `NodeEvent`, `Node`, `withNode`, `withConnection`              |-| Peers          | `Peer`, `PeerEvent`, `PeerException`, `sendMessage`, `getBlocks`, `getTxs`, `getData`, `pingPeer`, `killPeer`, `newOwner`, `reservePeer`, `releasePeer` |+| Peers          | `Peer`, `PeerEvent`, `PeerException`, `sendMessage`, `judgeMessage`, `getBlocks`, `getTxs`, `getData`, `pingPeer`, `killPeer`, `newOwner`, `reservePeer`, `releasePeer`, `newPeer` |+| Models of peers | `Judgement`, `judgementText`, `expectsReject`, `Permission`, `Permissions` | | Blocks         | `blockMutation`, `BlockMutation`, `witnessCheck`, `WitnessCheck`, `segWitHeight` | | Peer manager   | `PeerMgr`, `OnlinePeer`, `PeerState`, `Stage`, `DisconnectReason`, `getPeers`, `getOnlinePeer`, `toSockAddr`, `isRoutable` |-| Chain          | `Chain`, `ChainEvent`, `chainGetBest`, `chainGetBlock`, `chainGetAncestor`, `chainGetParents`, `chainGetSplitBlock`, `chainBlockMain`, `chainIsSynced`, `chainRunHeaders` |+| Chain          | `Chain`, `ChainEvent`, `chainGetBest`, `chainGetBlock`, `chainGetAncestor`, `chainGetParents`, `chainGetSplitBlock`, `chainBlockMain`, `chainIsSynced`, `chainHasHeaders`, `chainRunHeaders` | | Logging        | `Logger`, `LogLevel`, `withLogger`, `withSource`, `logDebug` ... `logError`  |  The lower-level functions that feed messages to the peer manager and the chain@@ -547,7 +635,9 @@ | -------------------------------- | ----------------------------------------------------------- | | `Haskoin.Node.Peer`              | The process that talks to one peer, and data requests       | | `Haskoin.Node.Peer.Request`      | State machine for receiving requested blocks and transactions |+| `Haskoin.Node.Peer.Remote`       | The model of the node at the other end, which judges each message sent to it | | `Haskoin.Node.Peer.Lock`         | State machine for reserving a peer                          |+| `Haskoin.Node.Router`            | State machine for the order of each peer's events           | | `Haskoin.Node.Block`             | Whether a block holds the transactions its header commits to | | `Haskoin.Node.PeerMgr`           | Finds, connects, ranks and drops peers                      | | `Haskoin.Node.PeerMgr.Lifecycle` | State machine for the life of a connection                  |@@ -599,6 +689,9 @@   gossip cannot crowd out the seeds. When the room for one is full, a new   address replaces one that has failed to connect. - A connection that does not open within five seconds is given up.+- A peer that stops reading cannot keep its slot: a connection told to close+  closes at once, even with a write blocked, and the peer manager cancels the+  process of one still there `timeout` seconds later. - An address whose connection fails waits twice as long after each failure   before it is tried again, up to ten minutes. A relayed address whose peer   broke the protocol is not tried again for a day. Static peers are never@@ -628,50 +721,75 @@ On NixOS, or with `stack --nix`, the `nix` section of `stack.yaml` provides RocksDB and libsecp256k1. +These commands build the library as it is released, with optimisation. For+the time between two commits there is a faster loop: `haskell-dev`, from+[jprupp/tools](https://github.com/jprupp/tools), on your `PATH`.++```sh+haskell-dev build          # build without optimisation+haskell-dev test PeerMgr   # run the tests in several processes at once+haskell-dev docs           # build the documentation and check its comments+```++`haskell-dev test` runs every test, those against real nodes too, in about+50 seconds. `haskell-dev.toml` tells it which spec modules are slow, so that it shares them between the+test processes. Do not mix the two kinds of build in one folder: the flags+differ, so each switch compiles everything again. Never time code with+`haskell-dev`.+ `package.yaml` is the source of the package description. Change it rather than `haskoin-node.cabal`, which [hpack](https://github.com/sol/hpack) generates.  The package also builds with [Cabal](https://www.haskell.org/cabal) (`cabal build`, `cabal test`). -There are two test suites, using [hspec](https://hspec.github.io/) and-[QuickCheck](https://hackage.haskell.org/package/QuickCheck):--- `spec` (`test/unit`) tests the state machines with properties, and runs the-  peer, peer manager, chain and node against in-memory mock peers. It needs no-  Internet access.--  ```sh-  stack test haskoin-node:spec-  ```+The tests are one suite, `spec`, using [hspec](https://hspec.github.io/) and+[QuickCheck](https://hackage.haskell.org/package/QuickCheck), and+`stack test` runs all of them: -- `regtest` (`test/regtest`) runs the node against+- The unit tests (`test/unit`) test the state machines with properties, and+  run the peer, peer manager, chain and node against peers scripted in+  memory, which break the rules as no real node does: wrong magic,+  oversized messages, forged blocks, a second `verack`. They need no+  Internet access, and name their peers by Unix sockets, never by a port.+  What an honest node does, the regtest tests show with real ones.+- The regtest tests (`Haskoin.Node.RegtestSpec`) run the node against   [Bitcoin Core](https://bitcoincore.org) and   [Bitcoin Cash Node](https://bitcoincashnode.org) in regression test mode. The   nodes run in a [Podman](https://podman.io) container built from   `test/regtest/Containerfile`, whose script `test/regtest/install-nodes.sh`   installs the official release binaries on Ubuntu after checking their SHA-256-  hashes. The image is built the first time-  the suite runs. Nodes use random ports, so runs do not collide. The suite is-  skipped if Podman is missing or `HASKOIN_NODE_SKIP_REGTEST` is set.+  hashes. The image is built the first time the tests run, which needs+  Internet access. The containers run through+  [podman-test](https://github.com/jprupp/podman-test), each in a pod with no+  network: the peer-to-peer port of each node is bridged to a Unix socket of+  the pod, and the node under test connects to it as the peer `unix:PATH`.+  So runs never collide, and no port of the machine is taken. A peer that+  hangs is a node stopped with `SIGSTOP`. A container may use 2 GiB of+  memory. The tests are skipped if Podman is missing, or if+  `HASKOIN_NODE_SKIP_REGTEST` or `PODMAN_TEST_SKIP` is set.    ```sh-  stack test haskoin-node:regtest+  stack test --ta '--match /Haskoin.Node.Regtest/'   # only these+  HASKOIN_NODE_SKIP_REGTEST=1 stack test               # all but these   ```  Set `HASKOIN_TEST_LOG` to see the node's logs while tests run. -CI builds and tests every change with the OS libraries, with `stack --nix`,-and against the regtest nodes. Its steps call the scripts in `scripts/`, which-you can also run locally: `scripts/check-local-deps.sh` fails if `stack.yaml`-points at a package outside the repository, which CI cannot build, and-`scripts/install-system-libraries.sh` installs the C libraries on Ubuntu.+CI builds and tests every change with the OS libraries and with+`stack --nix`, through the workflow that the packages of this family share in+[jprupp/tools](https://github.com/jprupp/tools), without the regtest tests,+and runs those in a job of its own. You can run its checks locally: `check-stack-paths`, from+jprupp/tools, fails if `stack.yaml` points at a package outside the+repository, which CI cannot build, and `scripts/install-system-libraries.sh`+installs the C libraries on Ubuntu.  ### Contributing  Pull requests are welcome. -- Format the code with [Ormolu](https://github.com/tweag/ormolu).+- Format the code with [Ormolu](https://github.com/tweag/ormolu):+  `haskell-format`, from [jprupp/tools](https://github.com/jprupp/tools). - Add tests for the behaviour you change. - Keep lines of code, including scripts, workflows and the examples in the   documentation, shorter than 120 columns.
+ docs/concurrency.md view
@@ -0,0 +1,218 @@+# Concurrency in haskoin-node++haskoin-node is a handful of threads that share a little state. This document+says, for each of them, what it owns, what decides what it does, and why no+two threads can get in each other's way. It is for anyone who changes the+code: read the part about a protocol before you change it.++## The rule++Every concurrent protocol is a pure state machine. Its transitions are a+function in a module of its own, tested with QuickCheck through arbitrary+sequences of events. The threads only store the state and carry out the+actions that a transition gives back. Races are ruled out by construction, in+one of three ways:++- **A single owner.** One thread changes the state; others at most read it.+- **One transaction per decision.** The state is read, the transition run and+  the new state written in one STM transaction, so two threads cannot both+  act on the same old state.+- **The order of a single queue.** Events that must keep an order go+  through one queue that one thread reads.++Time and randomness are inputs of the transitions, never read inside them.++## The threads++| Thread | Runs | Owns |+| --- | --- | --- |+| Peer writer | `Haskoin.Node.Peer.peer`, one per connection | the socket's write side |+| Peer reader | the same, in a linked thread | the socket's read side |+| Housekeeping | `withHousekeeping`, one per connection | nothing: sends `CheckPeer` ticks |+| Peer manager | `Haskoin.Node.PeerMgr.peerManager` | the list of connections and their `PeerState`, the address book |+| Connect loop | `withConnectLoop` | nothing: sends `Connect` |+| Chain | `Haskoin.Node.Chain` | the header database, `ChainState` |+| Router | `Haskoin.Node.peerEvents` | its `Router`: the order of each peer's events |+| Chain events | `Haskoin.Node.chainEvents` | nothing: forwards |+| Publishers | NQE, one for peer events, one for chain events, the application's | their subscriber lists |+| Callers | the application: `getData`, `pingPeer`, `sendMessage` | their own request |++## Peer process++Two threads per connection, and a `Peer` handle that other threads use.++- **Writer.** Takes `SendMessage`, `NotSent` and `KillPeer` from the mailbox,+  in order, and writes. It owns the write side.+- **Reader.** Reads and checks messages, waits for room in the allowance,+  and publishes each message. It owns the read side.+- **Closing.** The connection runs in a race against the `closing` flag of+  the handle. `killPeer` sets it, together with queuing `KillPeer`, in one+  transaction, and the process sets it as it ends, however it ends.++The state in the handle:++| State | Changed by | How |+| --- | --- | --- |+| `remote` (the model) | `sendMessage`; the reader on `version` | one transaction per message: judge and commit |+| `pending` (allowance) | up: the reader; down: the router | the reader waits for room and counts in one transaction |+| `busy` (reservation) | `reservePeer`, `releasePeer` | one transaction each, rules in `Haskoin.Node.Peer.Lock` |+| `closing` | `killPeer`; the process as it ends | a flag that only goes from `False` to `True` |+| `requestLock` | `getData` | held for the whole request |+| `owed` | set by `getData` as it queues its ping; cleared by the reader | see Requests |++**Audit: a kill could be lost.** `killPeer` only queued `KillPeer`. A peer+that stopped reading left the writer blocked in a write, `KillPeer` was never+taken, and the process never ended. **Now** the process races its+connection against `closing`, so it stops at once, and the peer manager+cancels the thread if it is still there after a timeout (see Peer manager).+`killPeer` no longer waits for messages queued before it.++## Remote model++`Haskoin.Node.Peer.Remote` runs haskoin-core's protocol machine of the node+at the other end. `sendMessage` judges a message and commits the new model+in one transaction, so the model sees messages in the order they are queued.++**Audit: time could go backwards.** The time in the facts of a message is+read before the transaction. Two threads sending at once could commit in the+other order than they read the clock. **Now** the model keeps the latest time+it has seen (`remoteClock`), and every judgement uses the later of that and+the time of its facts. The clamp is part of the transition, so of the one+transaction. A QuickCheck property feeds times in any order and checks that+the clock never goes down.++## Allowance of pending messages++The reader stops when a peer has `maxPendingMessages` (16) messages+published and not handled. It counts a message up in the transaction that+waits for room; the router counts it down once it is handled+(`peerMessageDone`).++**Invariant.** Each `PeerMessage` is given back exactly once, by its one+consumer. The router's machine disposes of every message exactly once, by+`Early`, `Deliver` or `Discard`, and a property checks it over arbitrary+interleavings. The count never goes below zero (`max 0`), so a stray extra+call cannot give a peer more than its allowance, but the invariant is what+keeps the count right; the clamp is a guard, not a rule to rely on.++**Audit.** The `max 0` hid the question of a double decrement. **Now** the+invariant is documented on `peerMessageDone` and checked on the router. A+token in each message, to make a second call impossible, was left out: it+would change `PeerEvent` for every consumer, for a rule that one place keeps.++## Peer manager++`Haskoin.Node.PeerMgr` is a single thread. It is the only writer of the list+of connections, and changes the state of a connection with+`Haskoin.Node.PeerMgr.Lifecycle.stepPeer` in one transaction (`peerInput`),+then carries out the actions: reply with `verack`, announce, ping,+disconnect, abort. Other threads read the list (`getPeers`,+`getOnlinePeer`).++A connection is `Handshaking`, `Online` or `Disconnecting`. Ticks come from+the housekeeping thread of each connection, every quarter to half of the+timeout.++**Audit: a disconnection could last forever.** `Disconnecting` ignored every+input, the clock too. If the process never stopped, the slot, the network+group and the `PeerDisconnected` were lost. **Now** `Disconnecting` records+when it began, and a tick more than the timeout later gives `Abort`: the+peer manager cancels the thread of the process (in a thread of its own,+since `cancel` waits), which then dies, and `PeerDied` follows as for any+end. `Abort` comes again after each further timeout. Properties check that+an abort always follows a disconnection that has not ended a timeout later,+and that `Abort` only comes after `Disconnect`, for the same reason.++## Router++`Haskoin.Node.peerEvents` reads the one queue of peer events and passes them+to the peer manager, the chain and the application. Its machine is+`Haskoin.Node.Router`.++**Audit: messages before the announcement.** A peer's messages come from its+reader, and `PeerConnected` from the peer manager, which publishes it after+handling the message that completes the handshake. By then the reader may+have queued more messages, ahead of the announcement. The router asked+whether the peer was online, which it was, and passed them on first: the+chain dropped the headers of a peer it did not know yet. A test reproduced it+on every run.++**Now** the router keeps a route for each peer:++- No route: the handshake is not complete. `version` and `verack` go to the+  peer manager, which the router waits for; pings are answered; the rest is+  dropped.+- `Awaiting`: right after the message that completes the handshake, the+  router asks the peer manager whether it announced the peer. If it did,+  messages are held, in order, until `PeerConnected` comes through the queue.+- `Announced`: the held messages, then every new one, are handled as from an+  online peer.+- `PeerDisconnected` ends the route.++The order is that of the single queue and the single thread that reads it.+Held messages count against the allowance, so at most 16 are held for a+peer. Properties over arbitrary interleavings of three peers check that+`PeerConnected` comes before any message past the handshake and+`PeerDisconnected` after all of them, that messages keep their order, and+that none past the handshake is dropped. `version` and `verack` are still+published before `PeerConnected`: they are the handshake itself.++## Chain++`Haskoin.Node.Chain` is a single thread, the only writer of `ChainState` and+of the database. Which peer syncs is `Haskoin.Node.Chain.Sync`, a pure+machine. Headers and inventory come from the router, in the order the peer+sent them; the router's handling of the next message of the same peer waits+in the chain's mailbox (`chainThen`), so the chain sees a peer's headers in+order. The chain reserves the peer it syncs from (`reservePeer`) and drops+peers with `killPeer`.++## Reservations++`Haskoin.Node.Peer.Lock` decides who holds a peer for a long conversation.+Each reservation or release is one transaction. Only the holder can+release.++## Requests++`getData`, `getBlocks` and `getTxs` feed what the peer sends to+`Haskoin.Node.Peer.Request`. After the request, the node sends a ping;+peers answer in order, so every item comes before the pong.++**Audit.**++- A request ignored the disconnection of its peer and waited for its+  timeout. So did `pingPeer`.+- Two requests at once on one peer saw each other's blocks and failed with+  "out of order". The late answers of a request that had timed out did the+  same to the next one.++**Now:**++- `Disconnected` is an input of the machine: a request ends at once when+  `PeerDisconnected` comes for its peer, and at once if the peer is closing+  when it starts. `pingPeer` does the same.+- Requests run one at a time per peer, under `requestLock`. The timeout+  counts from the call, the wait for the lock included.+- The nonce of the ping of the last request (`owed`) is set in the+  transaction that queues that ping, and cleared by the reader in the+  transaction that counts its pong, before the pong is published. A new+  request subscribes, then reads `owed`: if it is set, the pong is still to+  be published, and the request ignores everything until it comes, since all+  that comes before it answers the earlier request.+- A block, transaction or notfound for an item that the request did not ask+  for is ignored. One that it asked for, out of order, still fails it.++## Known limits++- **The application's subscription is unbounded.** NQE publishers do not+  wait for their subscribers, and a subscription is an unbounded queue. A+  subscriber that falls behind holds every event it has not read. The+  allowance bounds what each peer can make the node buffer inside, not what+  the application leaves unread. This is by design, and documented in the+  README.+- `getData`'s own subscription to the peer events is unbounded too, for the+  length of a request.+- A peer outside a peer manager, as in the tests of `Haskoin.Node.Peer`,+  publishes no `PeerDisconnected`, so a request on it ends at its timeout if+  the peer dies during the request.
haskoin-node.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack  name:           haskoin-node-version:        2.6.1+version:        2.7.0 synopsis:       P2P library for Bitcoin and Bitcoin Cash description:    Connect to Bitcoin (BTC) and Bitcoin Cash (BCH) peers, keep them healthy, and                 sync block headers into a RocksDB database. Blocks and transactions can be@@ -28,6 +28,7 @@ extra-doc-files:     README.md     CHANGELOG.md+    docs/concurrency.md  source-repository head   type: git@@ -45,11 +46,13 @@       Haskoin.Node.Loop       Haskoin.Node.Peer       Haskoin.Node.Peer.Lock+      Haskoin.Node.Peer.Remote       Haskoin.Node.Peer.Request       Haskoin.Node.PeerMgr       Haskoin.Node.PeerMgr.Addresses       Haskoin.Node.PeerMgr.Handshake       Haskoin.Node.PeerMgr.Lifecycle+      Haskoin.Node.Router   hs-source-dirs:       src   default-extensions:@@ -67,8 +70,8 @@     , conduit ==1.3.*     , conduit-extra ==1.3.*     , containers >=0.6 && <0.8-    , fast-logger ==3.2.*-    , haskoin-core >=2.0.1 && <2.1+    , fast-logger >=3.2 && <3.4+    , haskoin-core ==3.0.*     , network >=3.1 && <3.3     , nqe >=0.7.0 && <0.8     , random >=1.2 && <1.4@@ -82,46 +85,6 @@     , transformers ==0.6.*   default-language: GHC2024 -test-suite regtest-  type: exitcode-stdio-1.0-  main-is: Main.hs-  other-modules:-      Regtest.Podman-      Haskoin.Node.Test-      Paths_haskoin_node-  hs-source-dirs:-      test/regtest-      test/common-  default-extensions:-      DuplicateRecordFields-      MultiWayIf-      NoFieldSelectors-      OverloadedRecordDot-      OverloadedStrings-  ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wpartial-fields -Wredundant-constraints -Wunused-packages -threaded -rtsopts -with-rtsopts=-N-  build-depends:-      HUnit-    , async-    , base >=4.20 && <5-    , bytestring-    , cereal-    , conduit-    , data-default-    , directory-    , haskoin-core-    , haskoin-node-    , hspec >=2.10-    , network-    , nqe-    , process-    , random-    , rocksdb-haskell-jprupp-    , stm-    , temporary-    , text-    , time-  default-language: GHC2024- test-suite spec   type: exitcode-stdio-1.0   main-is: Spec.hs@@ -131,18 +94,23 @@       Haskoin.Node.Chain.SyncSpec       Haskoin.Node.ChainSpec       Haskoin.Node.Peer.LockSpec+      Haskoin.Node.Peer.RemoteSpec       Haskoin.Node.Peer.RequestSpec       Haskoin.Node.PeerMgr.AddressesSpec       Haskoin.Node.PeerMgr.HandshakeSpec       Haskoin.Node.PeerMgr.LifecycleSpec       Haskoin.Node.PeerMgrSpec       Haskoin.Node.PeerSpec+      Haskoin.Node.RegtestSpec+      Haskoin.Node.RouterSpec       Haskoin.NodeSpec       Haskoin.Node.Test+      Regtest.Podman       Paths_haskoin_node   hs-source-dirs:       test/unit       test/common+      test/regtest   default-extensions:       DuplicateRecordFields       MultiWayIf@@ -159,12 +127,16 @@     , bytestring     , cereal     , conduit+    , containers     , data-default+    , directory     , haskoin-core     , haskoin-node     , hspec >=2.10     , network     , nqe+    , podman-test+    , process     , random     , rocksdb-haskell-jprupp     , stm
src/Haskoin/Node.hs view
@@ -59,7 +59,11 @@ -- * __Processes with one job each.__ The peer manager, the chain and every --   peer connection are separate NQE processes. Each owns its state and is fed --   by messages, which keeps the concurrency easy to reason about and lets a---   failing peer die without disturbing the rest.+--   failing peer die without disturbing the rest. What each thread does is+--   decided by a pure state machine, and the order in which the events of a+--   peer are passed on is one too ("Haskoin.Node.Router"). docs\/concurrency.md+--   in the repository says, for every thread, what it owns and why threads+--   cannot race. -- -- * __Plain 'IO'.__ Every function runs in 'IO', without monad transformers --   or @MonadIO@ and @MonadUnliftIO@ constraints. The types say exactly what@@ -123,6 +127,13 @@     -- * Peers     module Haskoin.Node.Peer, +    -- * Models of peers+    Judgement (..),+    judgementText,+    expectsReject,+    P.Permission (..),+    P.Permissions,+     -- * Blocks     module Haskoin.Node.Block, @@ -139,17 +150,21 @@  import Control.Concurrent.Async (link, withAsync) import Control.Concurrent.STM (atomically)+import Control.Monad (foldM) import Data.Functor ((<&>)) import Data.Time.Clock (NominalDiffTime) import Database.RocksDB (ColumnFamily, DB) import Haskoin+import Haskoin.Network.Protocol qualified as P import Haskoin.Node.Address (withConnection) import Haskoin.Node.Block import Haskoin.Node.Chain import Haskoin.Node.Logger import Haskoin.Node.Loop (loopForever) import Haskoin.Node.Peer+import Haskoin.Node.Peer.Remote (Judgement (..), expectsReject, judgementText) import Haskoin.Node.PeerMgr+import Haskoin.Node.Router qualified as R import NQE import Network.Socket (SockAddr) @@ -164,7 +179,8 @@     db :: !DB,     -- | database column family     cf :: !(Maybe ColumnFamily),-    -- | static list of peers to connect to+    -- | static list of peers to connect to, as 'toHostService' reads them,+    -- or a Unix socket written @unix:PATH@ ('toSockAddr')     peers :: ![String],     -- | activate peer discovery     discover :: !Bool,@@ -185,7 +201,15 @@     -- 'withConnection', but can be replaced to use a proxy or for testing     connect :: !(SockAddr -> WithConnection),     -- | log messages here-    logger :: !Logger+    logger :: !Logger,+    -- | the permissions that the nodes of @peers@ grant this node with+    -- @-whitelist@ or @-whitebind@, such as+    -- 'Haskoin.Network.Protocol.PermMempool' to ask for their+    -- mempool. Nothing in the protocol tells a peer its permissions, so the+    -- operator who set them up says them here. Every message to a peer is+    -- judged by a model of its node first, which knows these permissions+    -- ("Haskoin.Node.Peer.Remote"). Peers that the node discovers grant none.+    permissions :: !P.Permissions   }  -- | A running node, as given by 'withNode'. Use its fields to query and@@ -220,6 +244,21 @@ -- | Route events from peers to the peer manager and chain, and publish them -- to the application. --+-- = Order+--+-- The messages of a peer come from the thread that reads its socket, and its+-- announcements, 'PeerConnected' and 'PeerDisconnected', from the peer+-- manager. This loop keeps the order of the two with the pure machine of+-- "Haskoin.Node.Router": the chain and the application see 'PeerConnected'+-- before any message of the peer past its handshake, and 'PeerDisconnected'+-- after all of them. Messages that arrive between the end of the handshake+-- and the announcement are held, in order, until the announcement comes+-- through the queue. Before, they were passed on at once, ahead of the+-- announcement, and the chain dropped the headers of a peer it did not know+-- yet.+--+-- = Handling+-- -- A message from a peer is handled to completion before the peer may send -- another one past its small allowance of pending messages (see -- 'maxPendingMessages'), so that the node's own queues cannot grow faster@@ -245,28 +284,63 @@ -- -- Messages for the peer manager, which is quick, are handled the same way, -- except @version@ and @verack@: the loop waits for those, since whether the--- next message of that peer is taken depends on them.+-- next message of that peer is taken depends on them. Once the peer manager+-- has handled one, the loop asks it whether it announced the peer, and if+-- so starts holding the messages of the peer until the announcement comes. -- -- Messages reach the application only from online peers, except @version@--- and @verack@, which are the handshake itself. Bitcoin Core ignores--- anything else a peer sends before the handshake is done, and so does the--- node: a peer whose version may still be refused cannot feed the--- application blocks and transactions.+-- and @verack@, which are the handshake itself and come before+-- 'PeerConnected'. Bitcoin Core ignores anything else a peer sends before+-- the handshake is done, and so does the node: a peer whose version may+-- still be refused cannot feed the application blocks and transactions.+-- Pings are answered from the start.+--+-- Each message is disposed of exactly once, by one of the actions of the+-- machine, and gives back the allowance of its peer exactly once. peerEvents ::   Chain -> PeerMgr -> Inbox PeerEvent -> Publisher NodeEvent -> IO ()-peerEvents ch mgr input output = loopForever $ do-  event <- receive input-  case event of-    PeerConnected p -> do-      chainPeerConnected ch p-      atomically (forward event)-    PeerDisconnected p -> do-      chainPeerDisconnected ch p-      atomically (forward event)-    PeerMessage p m -> do-      ticklePeer mgr p-      online <- isOnline p-      let done+peerEvents ch mgr input output = go R.newRouter+  where+    go !router = do+      event <- receive input+      router' <- route router $ case event of+        PeerConnected p -> R.Connected p+        PeerDisconnected p -> R.Disconnected p+        PeerMessage p m -> R.Arrived p m+      go router'+    route router i = do+      let (router', actions) = R.stepRouter i router+      foldM perform router' actions+    perform router = \case+      R.Announce p -> do+        chainPeerConnected ch p+        atomically (forward (PeerConnected p))+        return router+      R.Retire p -> do+        chainPeerDisconnected ch p+        atomically (forward (PeerDisconnected p))+        return router+      R.Discard p _ -> do+        atomically (peerMessageDoneSTM p)+        return router+      R.Early p m -> do+        ticklePeer mgr p+        handle False p m+        -- the handshake may be complete now; if the peer manager announced+        -- the peer, hold its next messages until the announcement comes+        if handshake m+          then do+            announced <- maybe False (.state.announced) <$> getOnlinePeer mgr p+            if announced then route router (R.HandshakeDone p) else return router+          else return router+      R.Deliver p m -> do+        ticklePeer mgr p+        online <- isOnline p+        handle online p m+        return router+    handle online p m = do+      let event = PeerMessage p m+          done             | handshake m || online = forward event >> peerMessageDoneSTM p             | otherwise = peerMessageDoneSTM p           now = atomically done@@ -289,7 +363,6 @@             bhs@(_ : _) <- [BlockHash iv.invHash | iv <- ivs, isBlock iv] ->               chainBlocksAnnounced ch p bhs >> later (chainThen ch)         _ -> now-  where     forward event = publishSTM (PeerEvent event) output     isOnline p =       getOnlinePeer mgr p <&> \case@@ -342,5 +415,7 @@           maxPeerLife = cfg.maxPeerLife,           connect = cfg.connect,           logger = withSource "PeerMgr" cfg.logger,-          lookupBlock = chainGetBlock chain+          lookupBlock = chainGetBlock chain,+          bestBlock = chainGetBest chain,+          permissions = cfg.permissions         }
src/Haskoin/Node/Address.hs view
@@ -7,8 +7,16 @@ -- Portability : POSIX -- -- Peer addresses: parsing them, deciding which relayed addresses are worth--- connecting to, and opening TCP connections.+-- connecting to, and opening connections, over TCP or a Unix socket. --+-- A configured peer may be a Unix socket, written @unix:PATH@ as Bitcoin+-- Core writes the socket of a proxy. Neither Bitcoin Core nor Bitcoin Cash+-- Node listens on one, so the socket is something that joins it to a node,+-- such as socat, or the bridge of a test in a container: tests that run at+-- once then reach their nodes without taking a port of the machine. A peer+-- or a DNS seed can never give a Unix address, since relayed addresses are+-- IPv4 or IPv6 and 'isRoutable' refuses everything else.+-- -- "Haskoin.Node.PeerMgr" re-exports 'toHostService', 'toSockAddr' and -- 'isRoutable', and "Haskoin.Node" re-exports 'withConnection', where they -- used to be defined. They live here because none of them depends on the@@ -21,13 +29,15 @@     netGroup,     withConnection,     connectTimeout,+    peerHostAddress,+    seenAs,   ) where  import Conduit (liftIO, yield) import Control.Applicative ((<|>)) import Control.Arrow (second)-import Control.Exception (IOException, catch, finally)+import Control.Exception (IOException, bracketOnError, catch, finally) import Control.Monad (unless) import Data.Bits (complement, shiftR, (.&.), (.|.)) import Data.ByteString (ByteString)@@ -38,18 +48,22 @@ import Data.String.Conversions (cs) import Data.Time.Clock (NominalDiffTime) import Data.Word (Word16, Word8)-import Haskoin (Network (..))+import Haskoin (AddressNetwork (..), HostAddress, Network (..), sockToHostAddress) import Haskoin.Node.Peer (Conduits (..), WithConnection) import Network.Socket   ( AddrInfo (..),-    Family (AF_UNSPEC),+    Family (AF_UNIX, AF_UNSPEC),     NameInfoFlag (..),     SockAddr (..),+    SocketType (Stream),     close,+    connect,+    defaultProtocol,     getAddrInfo,     getNameInfo,     hostAddress6ToTuple,     hostAddressToTuple,+    socket,     tupleToHostAddress6,   ) import Network.Socket.ByteString (recv)@@ -83,13 +97,17 @@    in (host, srv)  -- | Resolve a peer address given as in 'toHostService' into socket addresses,--- using the default port of the network if none is given. Returns an empty list--- if it cannot be resolved.+-- using the default port of the network if none is given, or give the Unix+-- socket of an address written @unix:PATH@. Returns an empty list if it+-- cannot be resolved. -- -- Only resolver failures, which are 'IOException's, are caught. Catching -- every exception would also swallow the asynchronous exception that cancels -- the thread doing the lookup, and the node could then never shut down. toSockAddr :: Network -> String -> IO [SockAddr]+toSockAddr _ ('u' : 'n' : 'i' : 'x' : ':' : path)+  | null path = return []+  | otherwise = return [SockAddrUnix path] toSockAddr net str =   resolve `catch` \(_ :: IOException) -> return []   where@@ -159,7 +177,8 @@ netGroup = \case   SockAddrInet _ h -> v4 (hostAddressToTuple h)   SockAddrInet6 _ _ h _ -> v6 (hostAddress6ToTuple h)-  _ -> UnroutableGroup+  -- a socket of this machine+  SockAddrUnix _ -> LocalGroup   where     v4 t@(a, b, _, _)       | a == 127 || a == 0 = LocalGroup@@ -201,14 +220,15 @@   | a >= 224 = False -- multicast and reserved   | otherwise = True --- | Longest wait for a TCP connection to open: @DEFAULT_CONNECT_TIMEOUT@ in+-- | Longest wait for a connection to open: @DEFAULT_CONNECT_TIMEOUT@ in -- Bitcoin Core 32.1, 5 seconds. connectTimeout :: NominalDiffTime connectTimeout = 5 --- | Open a TCP connection to a peer address and pass its conduits to a--- function. The connection is closed when the function returns. Calls 'error'--- if the address cannot be converted into a host and port.+-- | Open a connection to a peer address, over TCP or to a Unix socket, and+-- pass its conduits to a function. The connection is closed when the+-- function returns. Calls 'error' if a TCP address cannot be converted into+-- a host and port. -- -- Opening the connection fails with an 'IOException' after 'connectTimeout'. -- Without the limit, an address that drops connection requests held a slot@@ -217,22 +237,51 @@ -- because the peer process reads its mailbox only once the connection is -- open. withConnection :: SockAddr -> WithConnection-withConnection sa f =-  fromSockAddr sa >>= \case-    Nothing -> error $ "Invalid address " <> show sa-    Just (host, port) ->-      timeout micros (getSocketFamilyTCP host port AF_UNSPEC) >>= \case+withConnection sa f = case sa of+  SockAddrUnix _ -> opened (bracketOnError (socket AF_UNIX Stream defaultProtocol) close (\s -> s <$ connect s sa))+  _ ->+    fromSockAddr sa >>= \case+      Nothing -> error $ "Invalid address " <> show sa+      Just (host, port) -> opened (fst <$> getSocketFamilyTCP host port AF_UNSPEC)+  where+    opened open =+      timeout micros open >>= \case         Nothing -> ioError (userError ("Connection to " <> show sa <> " timed out"))-        Just (s, _) ->+        Just s ->           f Conduits {inboundConduit = source s, outboundConduit = sinkSocket s}             `finally` close s-  where     micros = floor (connectTimeout * 1000000)     -- Pieces of the size that the TCP client of streaming-commons reads.     size = getReadBufferSize (clientSettingsTCP 0 "")     source s = do       bs <- liftIO (recv s size)       unless (B.null bs) (yield bs >> source s)++-- | The address of a peer as the version message carries it: the zero+-- address for a Unix socket, which has none, as Bitcoin Core sends when it+-- does not know the address. haskoin-core's 'sockToHostAddress' takes only+-- IPv4 and IPv6 addresses, and stops the program on any other.+peerHostAddress :: SockAddr -> HostAddress+peerHostAddress = \case+  SockAddrUnix _ -> sockToHostAddress (SockAddrInet 0 0)+  sa -> sockToHostAddress sa++-- | How the node at a socket address sees this node, for its model+-- ("Haskoin.Node.Peer.Remote"): the network of the address, and whether it is+-- a local one. Over the loopback interface or a Unix socket it is local,+-- which some rules of the nodes treat apart. A Unix socket has no address+-- network; it is given as IPv4, which the rules treat as they treat any other+-- local address.+seenAs :: SockAddr -> (AddressNetwork, Bool)+seenAs = \case+  SockAddrInet _ h -> (AddrIPv4, fst4 (hostAddressToTuple h) == 127)+  SockAddrInet6 _ _ h _ -> case hostAddress6ToTuple h of+    (0, 0, 0, 0, 0, 0, 0, 1) -> (AddrIPv6, True)+    (0, 0, 0, 0, 0, 0xffff, hi, _) -> (AddrIPv6, hi `shiftR` 8 == 127)+    _ -> (AddrIPv6, False)+  SockAddrUnix _ -> (AddrIPv4, True)+  where+    fst4 (a, _, _, _) = a  -- | Turn a socket address into a numeric host and a port, or 'Nothing' if it -- cannot be converted.
src/Haskoin/Node/Chain.hs view
@@ -88,6 +88,7 @@     chainPeerConnected,     chainPeerDisconnected,     chainIsSynced,+    chainHasHeaders,     chainBlockMain,     chainHeaders,     chainBlocksAnnounced,@@ -563,6 +564,25 @@ -- chain falls behind later. chainIsSynced :: Chain -> IO Bool chainIsSynced ch = (.beenInSync) <$> readTVarIO ch.state++-- | Whether the chain has the headers of its peers: a peer is connected,+-- and headers are awaited from none, neither the one that is being synced+-- against nor one that waits its turn.+--+-- This is not 'chainIsSynced', which also asks that the best block be+-- recent and have the work of the network, and which stays 'True' once it+-- was. A network where no block was found for hours has no recent block,+-- and a node that has every header of it is at its tip all the same. Use+-- this to tell a node that is still taking headers, two thousand at a+-- time, from one that has them: while they come, an application that+-- imports the blocks catches up with the last header that the node has+-- again and again, and is at no tip.+--+-- With no peer it is 'False': there is nobody to have the headers of.+chainHasHeaders :: Chain -> IO Bool+chainHasHeaders ch = do+  s <- (.sync) <$> readTVarIO ch.state+  return (not (null (connectedPeers s)) && isNothing (syncingPeer s) && null (queuedPeers s))  -- | Peer sends a bunch of headers to the chain process. "Haskoin.Node" calls -- this for every headers message received from an online peer.
src/Haskoin/Node/Peer.hs view
@@ -41,8 +41,45 @@ --   receives. It is done here, once, so that 'getBlocks', 'getData' and the --   'PeerMessage' events all see only blocks that passed it. --+-- * Every message on its way out is judged first by a model of the node at+--   the other end ("Haskoin.Node.Peer.Remote"). One that the node would+--   punish this node for is not sent, and is logged with the upstream line+--   of the rule. A request in 'getData' that the node would drop without an+--   answer fails at once.+-- -- * Reading pauses when the node falls behind ('maxPendingMessages'), so the --   speed of the node, not the speed of the peer, sets the pace.+--+-- = Threads and the state they share+--+-- A peer process is two threads: the writer, which takes commands from the+-- mailbox and writes them to the socket, and the reader, which reads the+-- socket and publishes what it reads. Other threads touch the 'Peer' handle:+-- whoever sends messages, the router of "Haskoin.Node", and requests. Each+-- piece of state is changed in one place or in one transaction:+--+-- * The model of the peer (@remote@) is judged and changed in the+--   transaction that queues a message ('sendMessage'), and by the reader in+--   the transaction that counts a version message it read. The model keeps+--   its own clock, so threads that read the time in another order than they+--   commit cannot make it go back ("Haskoin.Node.Peer.Remote").+--+-- * The allowance of pending messages (@pending@) goes up in the reader, in+--   one transaction with the wait for room, and down once for each message+--   published, in the router ('peerMessageDone').+--+-- * Whether the peer is closing (@closing@) is set by 'killPeer' and when the+--   process ends, and the process races its connection against it. A writer+--   blocked in a write to a peer that stopped reading never looks at its+--   mailbox, so a request to disconnect cannot wait behind it there.+--+-- * Requests ('getData') run one at a time on a peer, under a lock, and the+--   nonce of the ping that ends the last one (@owed@) is set as that ping is+--   queued and cleared by the reader, in the transaction that counts its+--   pong. A new request knows from it whether answers to an earlier one may+--   still come ("Haskoin.Node.Peer.Request").+--+-- docs\/concurrency.md in the repository has the whole picture. module Haskoin.Node.Peer   ( PeerConfig (..),     PeerEvent (..),@@ -52,13 +89,14 @@     Peer (..),     PeerMessage (..),     peer,-    wrapPeer,+    newPeer,     sendMessage,     killPeer,     getBlocks,     getTxs,     getData,     pingPeer,+    judgeMessage,     Owner,     newOwner,     ownerName,@@ -75,24 +113,28 @@ where  import Conduit-import Control.Concurrent.Async (link, withAsync)+import Control.Concurrent.Async (link, race_, withAsync) import Control.Concurrent.STM-import Control.Exception (Exception, throwIO)+import Control.Exception (Exception, bracket_, finally, throwIO) import Control.Monad import Data.Bool (bool) import Data.ByteString (ByteString) import Data.ByteString qualified as B import Data.Function (on)-import Data.Maybe (isJust)+import Data.Int (Int64)+import Data.Map.Strict qualified as Map+import Data.Maybe (catMaybes, isJust) import Data.Serialize (decode, runGet, runPut) import Data.String.Conversions (cs) import Data.Text (Text)-import Data.Word (Word32)+import Data.Time.Clock.POSIX (getPOSIXTime)+import Data.Word (Word32, Word64) import Haskoin import Haskoin.Node.Block import Haskoin.Node.Logger import Haskoin.Node.Loop (loopForever) import Haskoin.Node.Peer.Lock+import Haskoin.Node.Peer.Remote import Haskoin.Node.Peer.Request import NQE import System.Random@@ -131,7 +173,13 @@     -- (see 'witnessCheck'). "Haskoin.Node" passes 'Haskoin.Node.chainGetBlock'.     -- A function that always gives 'Nothing' still checks the Merkle root of     -- every block, but not its witness data.-    lookupBlock :: !(BlockHash -> IO (Maybe BlockNode))+    lookupBlock :: !(BlockHash -> IO (Maybe BlockNode)),+    -- | the best block header that the node has stored, which the model of+    -- the peer takes for the tip of the peer ("Haskoin.Node.Peer.Remote").+    -- "Haskoin.Node" passes 'Haskoin.Node.Chain.chainGetBest'.+    bestBlock :: !(IO BlockNode),+    -- | the model of the peer when the connection opens, from 'newRemote'+    remote :: !Remote   }  -- | Events published about peers.@@ -184,7 +232,20 @@     -- 'reservePeer'     busy :: !(TVar (Lock Owner)),     -- | messages from this peer that the node has not finished handling-    pending :: !(TVar Int)+    pending :: !(TVar Int),+    -- | the model of the peer, which judges the messages sent to it+    remote :: !(TVar Remote),+    -- | what the node knows that a judgement of a message needs+    facts :: !(Message -> IO Facts),+    -- | whether the process is told to stop, or has stopped; the process+    -- races its connection against it+    closing :: !(TVar Bool),+    -- | held by the request that is running on the peer ('getData'), so that+    -- requests do not see each other's answers+    requestLock :: !(TMVar ()),+    -- | the nonce of the ping that ends the last request on the peer, until+    -- the reader reads its pong+    owed :: !(TVar (Maybe Word64))   }  instance Eq Peer where@@ -195,28 +256,80 @@  -- | Incoming messages that a peer accepts. data PeerMessage-  = -- | disconnect from the peer+  = -- | disconnect from the peer, once the messages queued before it are+    -- sent; 'killPeer' queues it, but does not wait for it     KillPeer   | -- | send a network message to the peer     SendMessage !Message+  | -- | a message that 'sendMessage' did not send, because the model of the+    -- peer said that the peer would punish the node for it; the peer process+    -- logs it, in the order of the messages that it sends+    NotSent !Message !Judgement --- | Build a 'Peer' handle from its configuration, its lock (which starts--- 'Free'), its counter of pending messages, and the mailbox of its process.-wrapPeer ::-  PeerConfig ->-  TVar (Lock Owner) ->-  TVar Int ->-  Mailbox PeerMessage ->-  Peer-wrapPeer cfg busy pending mbox =-  Peer-    { mailbox = mbox,-      pub = cfg.pub,-      label = cfg.label,-      busy = busy,-      pending = pending-    }+-- | A 'Peer' handle for a configuration and the mailbox of its process,+-- with a free lock, no pending messages, the model of the configuration, and+-- no request.+--+-- The handle holds the state that the threads of the process and its users+-- share, so there is one way to make it: the @wrapPeer@ of earlier releases,+-- which took some of that state from the caller, is gone.+newPeer :: PeerConfig -> Mailbox PeerMessage -> IO Peer+newPeer cfg mbox = do+  busy <- newTVarIO Free+  pending <- newTVarIO 0+  remote <- newTVarIO cfg.remote+  closing <- newTVarIO False+  requestLock <- newTMVarIO ()+  owed <- newTVarIO Nothing+  return+    Peer+      { mailbox = mbox,+        pub = cfg.pub,+        label = cfg.label,+        busy = busy,+        pending = pending,+        remote = remote,+        facts = gatherFacts cfg,+        closing = closing,+        requestLock = requestLock,+        owed = owed+      } +-- | What the node knows that a judgement of a message needs: the time, its+-- best header, and its headers of the blocks that the message names, up to+-- 'factsLookups' of them. A block past that, or one that the node does not+-- know, is taken to be at the tip, which changes no judgement of the+-- protocol.+gatherFacts :: PeerConfig -> Message -> IO Facts+gatherFacts cfg m = do+  t <- getPOSIXTime+  best <- cfg.bestBlock+  found <- forM (take factsLookups named) $ \h -> fmap (h,) <$> cfg.lookupBlock h+  return+    Facts+      { now = floor (t * 1000000) :: Int64,+        best = best,+        known = Map.fromList (catMaybes found)+      }+  where+    named = case m of+      MGetData (GetData ivs) -> [BlockHash iv.invHash | iv <- ivs, isBlock iv.invType]+      MGetHeaders gh -> gh.locator+      MGetBlocks gb -> gb.locator+      _ -> []+    isBlock = (`elem` [InvBlock, InvWitnessBlock, InvMerkleBlock, InvCompactBlock])++-- | Most block headers looked up to judge one message.+factsLookups :: Int+factsLookups = 64++-- | What the peer would do with a message if it were queued now, after the+-- messages queued before it, without queuing it.+judgeMessage :: Peer -> Message -> IO Judgement+judgeMessage p m = do+  f <- p.facts m+  fst . judge f m <$> readTVarIO p.remote+ -- | Most messages from one peer that may wait for the node to handle them. -- When a peer gets this far ahead, the node stops reading from its socket -- until it catches up, so that a peer that sends faster than the node can@@ -226,6 +339,18 @@  -- | Tell the peer process that the node has finished handling one of the -- messages that it published, so that it may read another one.+--+-- Call it exactly once for each 'PeerMessage', from one consumer of the+-- events of the peer: in a node, the router of "Haskoin.Node" does, and the+-- machine it runs ("Haskoin.Node.Router") disposes of every message exactly+-- once. A second call for the same message would let the peer get one more+-- message ahead of the node than 'maxPendingMessages'; a missing call would+-- stop the peer for good once it misses 'maxPendingMessages' of them. The+-- count never goes below zero, so a stray call cannot make room for more+-- than the allowance, but it is a fault of the caller, not a case to rely+-- on. A token in each message to make a second call impossible was+-- considered, and left out: it would change 'PeerEvent' for every consumer,+-- for a rule that one place keeps. peerMessageDone :: Peer -> IO () peerMessageDone = atomically . peerMessageDoneSTM @@ -234,26 +359,34 @@ peerMessageDoneSTM p = modifyTVar' p.pending (max 0 . subtract 1)  -- | Run peer process in current thread. The 'Peer' must be the one that--- 'wrapPeer' built with the mailbox of this inbox.+-- 'newPeer' built with the mailbox of this inbox. -- -- Opens the connection, then reads and publishes messages from the peer while -- sending the messages that arrive in the inbox. Returns when 'killPeer' is -- called or the connection is closed, and throws if the peer sends invalid -- data.+--+-- The connection runs in a race against the @closing@ flag of the peer,+-- which 'killPeer' sets: the process stops at once, even when its writer is+-- blocked in a write to a peer that stopped reading. The flag is set when+-- the process ends, however it ends, so that requests started after that+-- give up at once. peer ::   PeerConfig ->   Peer ->   Inbox PeerMessage ->   IO () peer cfg@PeerConfig {label, net, pub, logger} p inbox =-  cfg.connect peer_session+  race_ (cfg.connect peer_session) closed+    `finally` atomically (writeTVar p.closing True)   where+    closed = atomically (readTVar p.closing >>= check)     -- Commands from the mailbox, as a stream of messages to send.     go = do       m <- liftIO $ do         logDebug logger $ label <> " awaiting event..."         receive inbox-      dispatchMessage cfg m >>= bool (return ()) go+      dispatchMessage cfg p m >>= bool (return ()) go     peer_session ad = do       let ins = ad.inboundConduit           ons = ad.outboundConduit@@ -272,18 +405,32 @@         n <- readTVar p.pending         check (n < maxPendingMessages)         writeTVar p.pending (n + 1)+        case m of+          MVersion v -> modifyTVar' p.remote (learnVersion v)+          -- the last request on the peer is no longer owed its pong; this+          -- comes before the pong is published, so a request that reads+          -- @owed@ after it subscribed sees the pong if it still waits+          MPong (Pong k) -> modifyTVar' p.owed (\o -> if o == Just k then Nothing else o)+          _ -> return ()       publish (PeerMessage p m) pub --- | Internal function to dispatch peer messages.+-- | Internal function to dispatch peer messages. 'sendMessage' judged each+-- message as it queued it; one that the peer would punish the node for+-- comes as 'NotSent', and is logged. dispatchMessage ::   PeerConfig ->+  Peer ->   PeerMessage ->   ConduitT i Message IO Bool-dispatchMessage PeerConfig {label, logger} (SendMessage m) = do+dispatchMessage PeerConfig {label, logger} _ (SendMessage m) = do   liftIO $ logDebug logger (label <> " sending cmd " <> cs (show (msgType m)))   yield m   return True-dispatchMessage PeerConfig {label, logger} KillPeer = do+dispatchMessage PeerConfig {label, logger} _ (NotSent m j) = do+  liftIO . logWarn logger $+    label <> " not sending cmd " <> cs (show (msgType m)) <> ": " <> judgementText j+  return True+dispatchMessage PeerConfig {label, logger} _ KillPeer = do   liftIO $ logDebug logger (label <> " disconnecting")   return False @@ -354,15 +501,42 @@ outPeerConduit :: (Monad m) => Network -> ConduitT Message ByteString m () outPeerConduit net = awaitForever $ yield . runPut . putMessage net --- | Ask a peer to disconnect. The peer process stops after sending any messages--- queued before this one.+-- | Tell a peer to disconnect. The peer process stops at once: messages+-- queued before may not be sent.+--+-- It sets the @closing@ flag that the process races its connection against,+-- and queues 'KillPeer' too, in the same transaction, for those that watch+-- the mailbox. It used to queue 'KillPeer' only, which waited behind every+-- message queued before it, and forever behind a write to a peer that+-- stopped reading. killPeer :: Peer -> IO ()-killPeer p = KillPeer `send` p.mailbox+killPeer p = atomically $ do+  writeTVar p.closing True+  KillPeer `sendSTM` p.mailbox  -- | Send a network message to peer. Returns as soon as the message is queued.+--+-- The model of the peer judges the message as it is queued, in the same+-- transaction, so that the model sees the messages in the order in which+-- they go out ("Haskoin.Node.Peer.Remote"). A message that the peer would+-- punish the node for is not sent; the peer process logs it. sendMessage :: Message -> Peer -> IO ()-sendMessage m p = SendMessage m `send` p.mailbox+sendMessage m p = do+  f <- p.facts m+  void (atomically (queueMessage f m p)) +-- | Judge a message with the given facts and queue it, in one transaction.+-- Gives whether it is sent: 'False' for a message that the peer would punish+-- the node for, which goes to the process as 'NotSent'. The model clamps the+-- time of the facts to the latest it has seen, so facts read before the+-- transaction cannot make its clock go back.+queueMessage :: Facts -> Message -> Peer -> STM Bool+queueMessage f m p = do+  (j, r) <- judge f m <$> readTVar p.remote+  case j of+    Refused _ _ -> NotSent m j `sendSTM` p.mailbox >> return False+    _ -> writeTVar p.remote r >> SendMessage m `sendSTM` p.mailbox >> return True+ -- | Try to reserve a peer for a long conversation, such as syncing headers -- or downloading blocks. Returns 'True' if the peer was free and the owner now -- holds it, or 'False' if anyone holds it, including the same owner.@@ -416,8 +590,9 @@ -- Every block returned has passed 'blockMutation': its transactions hash to -- the Merkle root of its header, and, when the node knows its parent, its -- witness data matches the commitment in its coinbase. A peer that sends a--- block that fails is disconnected, and the request then gives 'Nothing'--- when it times out. The blocks are not validated otherwise: their+-- block that fails is disconnected, and the request then gives 'Nothing' as+-- soon as its disconnection is published (or at its timeout, for a peer that+-- no peer manager runs, which publishes none). The blocks are not validated otherwise: their -- transactions may still be invalid. getBlocks ::   Network ->@@ -461,46 +636,87 @@     ivs = map (InvVector c . (.get)) ths  -- | Request transactions and/or blocks from peer. Return 'Nothing' if any--- single inventory fails to be retrieved, if they come out of order, or if--- timeout is reached.+-- single inventory fails to be retrieved, if they come out of order, if the+-- peer disconnects, or if timeout is reached. ----- The first argument is the timeout in seconds. A ping is sent right after the--- request; since peers answer in order, receiving the matching pong before all--- items means that the peer will not send the rest. Unrelated messages that--- arrive meanwhile are ignored. Transactions are returned as 'Left' and blocks--- as 'Right', in the order they were requested. "Haskoin.Node.Peer.Request"--- has the rules. Blocks are checked as 'getBlocks' says, and transactions as--- 'getTxs' says.+-- The first argument is the timeout in seconds, which counts from the call,+-- including any wait for an earlier request on the same peer. Each item is+-- judged by the model of the peer first ("Haskoin.Node.Peer.Remote"): if the+-- peer would refuse the request, or drop one of its items without an answer,+-- the request gives 'Nothing' at once. A ping is sent right after the+-- request; since peers answer in order, receiving the matching pong before+-- all items means that the peer will not send the rest. Unrelated messages+-- that arrive meanwhile are ignored, and so are blocks, transactions and+-- notfound messages for items that the request did not ask for.+-- Transactions are returned as 'Left' and blocks as 'Right', in the order+-- they were requested. "Haskoin.Node.Peer.Request" has the rules. Blocks are+-- checked as 'getBlocks' says, and transactions as 'getTxs' says.+--+-- Requests on one peer run one at a time, under a lock of the peer: two at+-- once would each take the other's blocks for its own and fail. A request+-- that ended before the pong of its ping came back leaves that nonce behind,+-- and the next request ignores what the peer sends until that pong, which+-- answers the earlier request. A request ends as soon as+-- 'PeerDisconnected' comes for its peer, and at once if the peer is+-- closing when it starts. getData ::   Int -> Peer -> GetData -> IO (Maybe [Either Tx Block])-getData seconds p gd@(GetData ivs) =-  withSubscription p.pub $ \inb -> do-    r <- randomIO-    MGetData gd `sendMessage` p-    MPing (Ping r) `sendMessage` p-    join <$> timeout (seconds * 1000 * 1000) (step inb (newRequest r ivs))+getData seconds p gd@(GetData ivs) = do+  whole <- judgeMessage p (MGetData gd)+  items <- mapM (judgeMessage p . MGetData . GetData . pure) ivs+  if all (== Allowed) (whole : items)+    then fmap join . timeout (seconds * 1000 * 1000) . withRequestLock p $+      withSubscription p.pub $ \inb ->+        readTVarIO p.closing >>= \case+          True -> return Nothing+          False -> do+            r <- randomIO+            let request = MGetData gd+                ping = MPing (Ping r)+            fr <- p.facts request+            fp <- p.facts ping+            stale <- atomically $ do+              stale <- readTVar p.owed+              _ <- queueMessage fr request p+              sent <- queueMessage fp ping p+              when sent $ writeTVar p.owed (Just r)+              return stale+            step inb (newRequest stale r ivs)+    else return Nothing   where     step inb = \case       Complete items -> return (Just items)       Failed _ -> return Nothing       Continue req -> filterReceive p inb >>= step inb . stepRequest req +-- | Run a request while holding the request lock of a peer.+withRequestLock :: Peer -> IO a -> IO a+withRequestLock p =+  bracket_ (atomically (takeTMVar p.requestLock)) (atomically (putTMVar p.requestLock ()))+ -- | Ping a peer and await response. Return 'False' if response not received--- before timeout. The first argument is the timeout in seconds.+-- before timeout, or at once if the peer disconnects or is closing. The+-- first argument is the timeout in seconds. pingPeer :: Int -> Peer -> IO Bool pingPeer time p =-  fmap isJust . withSubscription p.pub $ \sub -> do-    r <- randomIO-    MPing (Ping r) `sendMessage` p-    receiveMatchS time sub $ \case-      PeerMessage p' (MPong (Pong r'))-        | p == p' && r == r' -> Just ()-      _ -> Nothing+  withSubscription p.pub $ \sub ->+    readTVarIO p.closing >>= \case+      True -> return False+      False -> do+        r <- randomIO+        MPing (Ping r) `sendMessage` p+        fmap (== Just True) . receiveMatchS time sub $ \case+          PeerMessage p' (MPong (Pong r'))+            | p == p' && r == r' -> Just True+          PeerDisconnected p'+            | p == p' -> Just False+          _ -> Nothing --- | Receive the next message from the given peer, discarding events about other--- peers.-filterReceive :: Peer -> Inbox PeerEvent -> IO Message+-- | Receive the next message from the given peer, or its disconnection,+-- discarding events about other peers.+filterReceive :: Peer -> Inbox PeerEvent -> IO RequestInput filterReceive p inb =   receive inb >>= \case-    PeerMessage p' m | p == p' -> return m+    PeerMessage p' m | p == p' -> return (Received m)+    PeerDisconnected p' | p == p' -> return Disconnected     _ -> filterReceive p inb
+ src/Haskoin/Node/Peer/Remote.hs view
@@ -0,0 +1,354 @@+-- |+-- Module      : Haskoin.Node.Peer.Remote+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Stability   : experimental+-- Portability : POSIX+--+-- What the node at the other end of a connection will do with a message,+-- before it is sent.+--+-- The peer-to-peer protocol is what Bitcoin Core and Bitcoin Cash Node do,+-- not what a specification says, and they punish a peer for things that no+-- BIP mentions. A @mempool@ message, for example, closes the connection+-- unless the node offers Bloom filters or whitelisted the peer. haskoin-core+-- translates both nodes into pure state machines ("Haskoin.Network.Protocol"),+-- each modelling how its node treats one peer. A t'Remote' runs that machine+-- for one connection, with this node as the peer, and gives a t'Judgement' of+-- each message this node is about to send.+--+-- "Haskoin.Node.Peer" judges every message on its way out. One that the node+-- would punish this node for is not sent ('Refused'), and a request that the+-- node would drop without an answer fails at once ('Unanswered'), rather than+-- wait for a timeout.+--+-- = What the model knows, and what it guesses+--+-- A machine reads the state of the node from an+-- t'Haskoin.Network.Protocol.Env': its chain, its+-- mempool, its other peers. This node knows none of it for certain. It knows+-- its own chain of headers, which follows the node's, and the version message+-- of the node. So a t'Remote' is exact about the rules of the protocol, and+-- generous about the chain:+--+-- * The options of the node come from its version message ('learnVersion'):+--   whether it offers Bloom filters, whether it is pruned, whether it relays+--   transactions. Until that message arrives, the machine has the defaults+--   of the node. When it arrives, the machine starts again with the options+--   it gives, and the messages sent so far.+-- * The permissions of this node, which the operator of the other node grants+--   with @-whitelist@ or @-whitebind@, are configured: nothing in the protocol+--   tells a peer about them.+-- * The node is taken to have every block that this node asks for, at the+--   height of this node's header of it when there is one. A judgement never+--   says that a request goes unanswered because the node lacks a block. This+--   node's chain is a lower bound of the node's, not a copy of it, and a+--   guess that the node lacks a block would fail requests that it serves.+-- * A disconnection that depends on what is guessed, such as the node+--   running out of upload bandwidth or having pruned a block, is left to+--   happen. A message is refused only for what the rules decide whatever the+--   chain holds.+--+-- = Time only goes forward+--+-- The machine has timers, and it reads the time of each message from its+-- t'Facts'. Two threads that send to one peer at once read the clock first,+-- and commit their judgements one after the other in a transaction, in an+-- order that need not be the order of their clocks. The machine would then+-- see time go backwards. So a t'Remote' keeps the latest time it has seen+-- ('remoteClock'), and 'judge' and 'predict' use the later of that and the+-- time of the facts: the clamp is part of the transition, and so of the one+-- transaction that judges and commits a message.+--+-- = Why not a list of rules here+--+-- haskoin-node used to know such rules one at a time, written where they were+-- needed, and learned most of them when a node disconnected it. The machines+-- of haskoin-core cite the upstream line behind each decision, and follow the+-- releases of both nodes. A rule they learn reaches this node with the next+-- version of haskoin-core.+module Haskoin.Node.Peer.Remote+  ( -- * The model of a connection+    Remote,+    newRemote,+    remoteSetup,+    remoteConnection,+    learnVersion,+    learnedVersion,+    remoteClock,++    -- * Judging messages+    Facts (..),+    Judgement (..),+    judge,+    predict,+    judgementText,++    -- * What the node answers+    expectsReject,+  )+where++import Data.Bits ((.&.))+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (mapMaybe)+import Data.Set qualified as Set+import Data.Text (Text)+import Data.Text qualified as T+import Data.Word (Word64)+import Haskoin+import Haskoin.Network.Protocol qualified as P+import Haskoin.Network.Protocol.BitcoinCashNode qualified as BCHN+import Haskoin.Network.Protocol.BitcoinCore qualified as Core++-- | The model of the node at the other end of one connection.+data Remote = Remote+  { -- | the rules of the node, with its options+    machine :: !P.Machine,+    -- | the connection as the node sees it+    setup :: !P.Setup,+    -- | the version of the node, once it arrived+    version :: !(Maybe Version),+    -- | the messages sent before the version of the node arrived, newest+    -- first, with the facts they were judged with, to run again with the+    -- options that the version gives+    replay :: ![(P.Env, Message)],+    -- | the state of the machine+    connection :: !P.Connection,+    -- | the latest time that the machine has seen, which no later judgement+    -- goes below+    clock :: !P.Micros+  }++-- | A model for a connection to a node of this network. This node opened+-- the connection, so it is an inbound peer of the node.+newRemote ::+  Network ->+  -- | the permissions that the node grants this node, as configured+  P.Permissions ->+  -- | the address network of the connection, as the node sees it+  AddressNetwork ->+  -- | whether the node sees this node at a local address, as over a Unix+  -- socket or the loopback interface+  Bool ->+  -- | the time the connection opened+  P.Micros ->+  -- | a seed for the randomness of the machine+  Word64 ->+  Remote+newRemote net perms addrNet local opened seed =+  Remote+    { machine = m,+      setup = s,+      version = Nothing,+      replay = [],+      connection = P.start m s,+      clock = opened+    }+  where+    m = P.machine net+    s =+      P.Setup+        { connectionType = P.Inbound,+          permissions = perms,+          peerNetwork = addrNet,+          peerIsLocal = local,+          transport = P.TransportV1,+          openedAt = opened,+          seed = seed+        }++-- | The setup of the connection that the model runs.+remoteSetup :: Remote -> P.Setup+remoteSetup r = r.setup++-- | The state of the machine, to inspect with the functions of+-- "Haskoin.Network.Protocol.BitcoinCore" and+-- "Haskoin.Network.Protocol.BitcoinCashNode".+remoteConnection :: Remote -> P.Connection+remoteConnection r = r.connection++-- | The latest time that the machine has seen, in microseconds: the time+-- the connection opened, or the latest time of the facts of a message judged+-- since. Every judgement takes the later of this and the time of its facts.+remoteClock :: Remote -> P.Micros+remoteClock r = r.clock++-- | The version message of the node, once 'learnVersion' has seen it.+learnedVersion :: Remote -> Maybe Version+learnedVersion r = r.version++-- | Take the options of the node from its version message, and run the+-- messages sent so far again with them. Only the first version counts: a+-- second one is a fault of the node, which "Haskoin.Node.PeerMgr" handles.+--+-- A version message tells the services of the node, which say whether it+-- offers Bloom filters (@NODE_BLOOM@) and whether it is pruned+-- (@NODE_NETWORK_LIMITED@ without @NODE_NETWORK@), and its relay flag, which+-- a node in blocks-only mode clears.+learnVersion :: Version -> Remote -> Remote+learnVersion v r+  | Just _ <- r.version = r+  | otherwise =+      let m = adjust r.machine+          again c (e, out) = fst (P.step e c (P.Receive out))+          c' = foldl again (P.start m r.setup) (reverse r.replay)+       in r {machine = m, version = Just v, replay = [], connection = c'}+  where+    bloom = v.services .&. nodeBloom /= 0+    pruned = v.services .&. nodeNetwork == 0 && v.services .&. nodeNetworkLimited /= 0+    blocksOnly = not v.relay+    adjust = \case+      P.BitcoinCore o ->+        P.BitcoinCore+          o {Core.peerBloomFilters = bloom, Core.prune = pruned, Core.blocksOnly = blocksOnly}+      P.BitcoinCashNode o ->+        P.BitcoinCashNode+          o {BCHN.peerBloomFilters = bloom, BCHN.prune = pruned, BCHN.blocksOnly = blocksOnly}++-- | What this node knows of the chain when it judges a message: the time,+-- its best header, and its headers of the blocks that the message names. A+-- time earlier than the 'remoteClock' of the model counts as that clock.+data Facts = Facts+  { now :: !P.Micros,+    best :: !BlockNode,+    known :: !(Map BlockHash BlockNode)+  }++-- | What the node will do with a message.+data Judgement+  = -- | the node acts on it, and answers it if it is a request+    Allowed+  | -- | the node drops it without an answer, for this reason+    Unanswered !P.Cite+  | -- | the node would punish this node for it, or close the connection:+    -- what it would do, and why+    Refused !P.Action !P.Cite+  deriving (Eq, Show)++-- | Judge a message before it is sent, and give the model as it is after the+-- node got it. Keep the new model only if the message is sent.+--+-- A message is 'Refused' when the node would add to this node's ban score,+-- discourage it, ban it, or close the connection for breaking a rule of the+-- protocol, for misbehaviour, or because this node lacks what the connection+-- needs. It is not refused for a disconnection that depends on the guessed+-- state of the node, such as its upload limit.+--+-- A message is 'Unanswered' when the node only drops it: no message goes+-- back, and nothing else happens.+judge :: Facts -> Message -> Remote -> (Judgement, Remote)+judge facts out r = let (effects, r') = predict facts out r in (classify effects, r')++-- | What the node would do with a message, effect by effect, and the model+-- as it is after the node got it: what 'judge' decides from. The tests use+-- it to compare the model with a running node.+--+-- The machine sees the later of the time of the facts and 'remoteClock', and+-- the model keeps it as its clock, so that the time the machine sees never+-- goes back, whatever order the threads that read the clock commit in.+predict :: Facts -> Message -> Remote -> ([P.Effect], Remote)+predict facts out r =+  (effects, r {connection = c, replay = replay', clock = t})+  where+    t = max r.clock facts.now+    env = factsEnv (P.networkOf r.machine) facts {now = t}+    (c, effects) = P.step env r.connection (P.Receive out)+    replay' = case r.version of+      Nothing -> (env, out) : r.replay+      Just _ -> []++classify :: [P.Effect] -> Judgement+classify effects =+  case mapMaybe punished effects of+    e : _ -> Refused e.action e.because+    []+      | any (sends . (.action)) effects -> Allowed+      | e : _ <- filter ((== P.Ignore) . (.action)) effects,+        all ((== P.Ignore) . (.action)) effects ->+          Unanswered e.because+      | otherwise -> Allowed+  where+    punished e = case e.action of+      P.Misbehave n | n > 0 -> Just e+      P.Discourage -> Just e+      P.Ban _ -> Just e+      P.Disconnect why | why `elem` [P.ProtocolViolation, P.Misbehaviour, P.Unsuitable] -> Just e+      _ -> Nothing+    sends = \case+      P.Send _ -> True+      _ -> False++-- | A judgement in words, for the log, with the upstream line behind it.+judgementText :: Judgement -> Text+judgementText = \case+  Allowed -> "the node takes it"+  Unanswered c -> "the node drops it without an answer: " <> citeText c+  Refused a c -> "the node would " <> actionText a <> ": " <> citeText c+  where+    citeText c = c.reason <> " (" <> T.pack c.file <> ":" <> T.pack (show c.line) <> ")"+    actionText = \case+      P.Misbehave n -> "add " <> T.pack (show n) <> " to the ban score of this node"+      P.Discourage -> "discourage this node"+      P.Ban s -> "ban this node for " <> T.pack (show s) <> " seconds"+      P.Disconnect why -> "disconnect (" <> T.pack (show why) <> ")"+      other -> T.pack (show other)++-- | The environment of the machine, from what this node knows. The node is+-- out of initial block download, its tip is this node's best header, and it+-- has the data of every block that it is asked for. A block that this node+-- knows has its height and time; another one is taken to be at the tip. The+-- content of a block is never needed to judge a request for it, so the+-- genesis block stands in for every block.+factsEnv :: Network -> Facts -> P.Env+factsEnv net facts =+  (P.defaultEnv tip (genesisBlock net) facts.now)+    { P.initialBlockDownload = False,+      P.lookupBlock = Just . lookupInfo,+      P.headerOf = \h -> (.header) <$> Map.lookup h facts.known,+      P.blockData = const (Just (genesisBlock net)),+      P.blockAtHeight = \n ->+        if n == facts.best.height+          then Just tip+          else info <$> atHeight n,+      P.bestHeader = tip+    }+  where+    info n =+      P.BlockInfo+        { hash = headerHash n.header,+          height = n.height,+          status = P.HaveData,+          inActiveChain = True,+          work = n.work,+          time = n.header.timestamp+        }+    tip = info facts.best+    lookupInfo h = maybe (tip {P.hash = h} :: P.BlockInfo) info (Map.lookup h facts.known)+    atHeight n = case filter ((== n) . (.height)) (Map.elems facts.known) of+      x : _ -> Just x+      [] -> Nothing++-- | Whether the node answers a transaction that its mempool refuses with a+-- @reject@ message (BIP 61): Bitcoin Cash Node does by default, and Bitcoin+-- Core never does. The machine of the network is asked, not a table: a+-- connection is opened with this version message, its handshake completed,+-- and a transaction that the mempool refuses by policy is sent.+expectsReject :: Network -> Version -> Bool+expectsReject net ours =+  any isReject (snd (P.step refusing handshaken (P.Receive (MTx net.genesisTx))))+  where+    best = genesisNode net+    facts = Facts {now = 1, best = best, known = Map.empty}+    env = factsEnv net facts+    refusing = env {P.checkTx = const (P.TxPolicyReject "policy")}+    remote = newRemote net Set.empty AddrIPv4 False 1 0+    handshaken =+      foldl+        (\c out -> fst (P.step env c (P.Receive out)))+        (remoteConnection remote)+        [MVersion ours, MVerAck]+    isReject e = case e.action of+      P.Send (MReject _) -> True+      _ -> False
src/Haskoin/Node/Peer/Request.hs view
@@ -8,7 +8,7 @@ -- -- Receiving the answer to a request for blocks or transactions, as an -- explicit state machine. 'Haskoin.Node.Peer.getData' feeds it the messages--- that a peer sends after the request.+-- that a peer sends after the request, and the disconnection of the peer. -- -- = Why it works this way --@@ -24,13 +24,36 @@ -- * A notfound message naming a requested item, or the pong arriving early, --   means the peer will not send everything, so the request fails. ----- * Anything else is unrelated traffic and is ignored. Peers send pings,---   inventory and other chatter whenever they like, and failing a long---   download because of one of them would only make the application retry it.+-- * The disconnection of the peer ends the request at once ('Disconnected'):+--   nothing more can come, and waiting for the timeout would only hold up+--   the caller. --+-- * Anything else is unrelated traffic and is ignored: a block, transaction+--   or notfound for an item that this request did not ask for, pings,+--   inventory and other chatter. Peers send such messages whenever they like,+--   and failing a long download because of one of them would only make the+--   application retry it.+-- -- Keeping these rules in a pure function means each one can be tested on its -- own, without a connection. --+-- = Requests do not see each other's answers+--+-- "Haskoin.Node.Peer" runs one request at a time on a peer, so two requests+-- never wait on the same stream of answers. That leaves the answers to a+-- request that ended before its pong came back: one that timed out, failed,+-- or got all its items. They are still on their way, and the next request+-- may ask for the same items. Its rules above would take an earlier answer+-- for a skipped item and fail.+--+-- So a request starts by draining: if the request before it on the peer is+-- still owed its pong, 'newRequest' takes the nonce of that ping, and the+-- request ignores everything until that pong arrives. Peers answer in order,+-- so whatever comes before it answers the earlier request, and whatever+-- comes after answers this one. The alternative, matching answers to a+-- request by their content alone, cannot tell a late copy of a block from+-- the one asked for now.+-- -- A block is matched to a request by the hash of its header only. That is -- enough because the peer process checks every block before passing it on, -- with 'Haskoin.Node.Block.blockMutation': a block that arrives here holds@@ -38,6 +61,7 @@ -- id, which does not cover its witness. module Haskoin.Node.Peer.Request   ( Request,+    RequestInput (..),     RequestStep (..),     newRequest,     stepRequest,@@ -48,15 +72,25 @@ import Data.Word (Word64) import Haskoin --- | A request in progress: the nonce of the ping that follows it, the items--- still expected, and the items received so far, newest first.+-- | A request in progress: the nonce of the ping of the earlier request that+-- it waits for first, if any, the nonce of the ping that follows it, the+-- items still expected, and the items received so far, newest first. data Request = Request-  { nonce :: !Word64,+  { draining :: !(Maybe Word64),+    nonce :: !Word64,     remaining :: ![InvVector],     received :: ![Either Tx Block]   }   deriving stock (Eq, Show) +-- | What happens on the peer while a request waits.+data RequestInput+  = -- | the peer sent a message+    Received !Message+  | -- | the peer disconnected+    Disconnected+  deriving stock (Eq, Show)+ -- | Outcome of feeding a message to a request. data RequestStep   = -- | more items are expected@@ -69,24 +103,32 @@   deriving stock (Eq, Show)  -- | Start a request for the given items, followed by a ping with the given--- nonce. A request for nothing is complete at once.-newRequest :: Word64 -> [InvVector] -> RequestStep-newRequest n ivs = check Request {nonce = n, remaining = ivs, received = []}+-- nonce. The first argument is the nonce of the ping of the earlier request+-- on the peer, if that request is still owed its pong: everything before+-- that pong is ignored. A request for nothing is complete at once.+newRequest :: Maybe Word64 -> Word64 -> [InvVector] -> RequestStep+newRequest stale n ivs =+  check Request {draining = stale, nonce = n, remaining = ivs, received = []} --- | Feed a message from the peer to a request.-stepRequest :: Request -> Message -> RequestStep-stepRequest r message =-  case (r.remaining, message) of-    ([], _) -> Complete (reverse r.received)-    (next : _, MTx tx)+-- | Feed what happened to a request.+stepRequest :: Request -> RequestInput -> RequestStep+stepRequest _ Disconnected = Failed "peer disconnected"+stepRequest r (Received message) =+  case (r.draining, r.remaining, message) of+    (_, [], _) -> Complete (reverse r.received)+    (Just stale, _, MPong (Pong n))+      | n == stale -> Continue r {draining = Nothing}+      | n == r.nonce -> Failed "incomplete response"+    (Just _, _, _) -> Continue r+    (Nothing, next : _, MTx tx)       | isTx next tx -> accept (Left tx)       | any (`isTx` tx) r.remaining -> Failed "transaction out of order"-    (next : _, MBlock b)+    (Nothing, next : _, MBlock b)       | isBlock next b -> accept (Right b)       | any (`isBlock` b) r.remaining -> Failed "block out of order"-    (_, MNotFound (NotFound ivs))+    (Nothing, _, MNotFound (NotFound ivs))       | any (`elem` r.remaining) ivs -> Failed "item not found"-    (_, MPong (Pong n))+    (Nothing, _, MPong (Pong n))       | n == r.nonce -> Failed "incomplete response"     _ -> Continue r   where
src/Haskoin/Node/PeerMgr.hs view
@@ -22,6 +22,11 @@ -- in time, or has been connected for longer than 'maxPeerLife'. A -- 'PeerDisconnected' event is published when an announced peer goes away. --+-- The static peers of the configuration are the peers that the operator+-- trusts, and they are kept: never rotated, tried again within seconds+-- when their connection ends, for as long as it takes, and with a slot+-- kept for each while it is away.+-- -- Most of the @peerMgr*@ functions are used by "Haskoin.Node" to feed messages -- received from peers to the peer manager; applications rarely need to call -- them directly.@@ -49,13 +54,25 @@ --   isolate from the honest network, and stuck with them if they degrade. --   Rotation keeps the peer set fresh. --+-- * __Configured peers stay.__ Rotation is a defence against peers that+--   nobody chose. A configured peer is a node that the operator trusts,+--   often their own, and the one whose word an application takes: it is+--   never rotated. When its connection ends it is tried again every ten+--   seconds at most ('configuredBackoff'), and meanwhile its slot is kept:+--   seed and gossiped addresses cannot take it ('roomForOthers'). The only+--   reason for a configured peer to have no connection is that it takes+--   none.+-- -- * __Silence is failure.__ A peer that sends nothing, or ignores a ping, for --   longer than 'timeout' is dropped. Waiting for a peer that has gone away --   would stall whatever was waiting on it. -- -- * __A dropped peer is gone at once.__ A peer told to disconnect is no longer --   offered by 'getPeers' and its messages are no longer routed, even before---   its connection closes.+--   its connection closes. Its process stops at once ('killPeer'), and one+--   that is still there a timeout later has its thread cancelled (the+--   'Abort' of "Haskoin.Node.PeerMgr.Lifecycle"), so that a peer that stopped+--   reading cannot keep its slot. -- -- * __Bad addresses wait.__ An address that fails is tried again later each --   time, and one whose peer broke the protocol is not tried again for a long@@ -102,25 +119,27 @@ where  import Control.Applicative ((<|>))-import Control.Concurrent (threadDelay)-import Control.Concurrent.Async (Async, ExceptionInLinkedThread (..), link, withAsync)+import Control.Concurrent (forkIO, threadDelay)+import Control.Concurrent.Async (Async, ExceptionInLinkedThread (..), cancel, link, withAsync) import Control.Concurrent.STM import Control.Exception (SomeException, fromException)-import Control.Monad (forM_, when, (<=<))+import Control.Monad (forM_, void, when, (<=<)) import Data.Function (on) import Data.List (find, sort) import Data.Maybe (fromMaybe)+import Data.Set qualified as Set import Data.String.Conversions (cs) import Data.Time.Clock import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) import Data.Word (Word32, Word64) import GHC.Records (HasField (..)) import Haskoin-import Haskoin.Node.Address (NetGroup, isRoutable, netGroup, toHostService, toSockAddr)+import Haskoin.Network.Protocol qualified as P+import Haskoin.Node.Address (NetGroup, isRoutable, netGroup, peerHostAddress, seenAs, toHostService, toSockAddr) import Haskoin.Node.Logger import Haskoin.Node.Loop (loopForever) import Haskoin.Node.Peer-import Haskoin.Node.Peer.Lock (Lock (..))+import Haskoin.Node.Peer.Remote (newRemote) import Haskoin.Node.PeerMgr.Addresses import Haskoin.Node.PeerMgr.Handshake import Haskoin.Node.PeerMgr.Lifecycle@@ -155,7 +174,15 @@     logger :: !Logger,     -- | look up a stored block header; given to every peer as the     -- @lookupBlock@ of its t'PeerConfig', to check the blocks it sends-    lookupBlock :: !(BlockHash -> IO (Maybe BlockNode))+    lookupBlock :: !(BlockHash -> IO (Maybe BlockNode)),+    -- | the best stored block header; given to every peer as the+    -- @bestBlock@ of its t'PeerConfig'+    bestBlock :: !(IO BlockNode),+    -- | the permissions that the nodes of @peers@ grant this node with+    -- @-whitelist@ or @-whitebind@. The model of each such peer judges the+    -- messages sent to it with them ("Haskoin.Node.Peer.Remote"). Peers+    -- found any other way grant none.+    permissions :: !P.Permissions   }  -- | Handle to a running peer manager. Obtain one with 'withPeerMgr', or from@@ -173,6 +200,8 @@     addresses :: !(TVar (AddressBook SockAddr)),     -- | open connections, fastest peers first     peers :: !(TVar [OnlinePeer]),+    -- | the addresses of each configured peer, as its name last resolved+    configured :: !(TVar [[SockAddr]]),     -- | how well connected the log last said the node was ('Connected')     told :: !(TVar Connected)   }@@ -230,7 +259,10 @@     mailbox :: !Peer,     -- | nonce of the version message we sent, used to detect connections to     -- ourselves-    nonce :: !Word64+    nonce :: !Word64,+    -- | whether it is a static peer of the configuration, which the+    -- operator trusts: it is never rotated+    configured :: !Bool   }  instance Eq OnlinePeer where@@ -253,7 +285,7 @@   getField o = case o.state.stage of     Handshaking h -> hasVerAck h     Online _ _ -> True-    Disconnecting _ -> False+    Disconnecting _ _ -> False  -- | Time and nonce of the ping awaiting an answer, if any. instance HasField "ping" OnlinePeer (Maybe (UTCTime, Word64)) where@@ -285,6 +317,7 @@     best <- newTVarIO 0     addresses <- newTVarIO emptyBook     peers <- newTVarIO []+    configured <- newTVarIO []     told <- newTVarIO NoPeers     let mgr =           PeerMgr@@ -294,6 +327,7 @@               best = best,               addresses = addresses,               peers = peers,+              configured = configured,               told = told             }     withAsync (peerManager mgr inbox) $ \a ->@@ -311,9 +345,14 @@     logDebug mgr.config.logger "Awaiting event..."     dispatch mgr =<< receive inbox --- | Time limits of connections.-limits :: PeerMgr -> Limits-limits mgr = Limits {timeout = mgr.config.timeout, maxLife = mgr.config.maxPeerLife}+-- | Time limits of a connection. One to a configured peer is never+-- rotated.+limits :: PeerMgr -> OnlinePeer -> Limits+limits mgr o =+  Limits+    { timeout = mgr.config.timeout,+      maxLife = if o.configured then Nothing else Just mgr.config.maxPeerLife+    }  -- | Handle a message sent to the peer manager. dispatch :: PeerMgr -> PeerMgrMessage -> IO ()@@ -321,10 +360,13 @@   PeerVersion p v -> do     logDebug mgr.config.logger ("Received version from peer " <> p.label)     nonces <- map (.nonce) <$> readTVarIO mgr.peers-    peerInput mgr p $ either Refused (GotHandshake . GotVersion) (checkVersion mgr.config.net nonces v)+    now <- getCurrentTime+    peerInput mgr p $+      either (Refused now) (GotHandshake now . GotVersion) (checkVersion mgr.config.net nonces v)   PeerVerAck p -> do     logDebug mgr.config.logger ("Received version ack from peer " <> p.label)-    peerInput mgr p (GotHandshake GotVerAck)+    now <- getCurrentTime+    peerInput mgr p (GotHandshake now GotVerAck)   PeerPong p n -> do     now <- getCurrentTime     peerInput mgr p (GotPong now n)@@ -348,7 +390,7 @@     case find ((== p) . (.mailbox)) ops of       Nothing -> return Nothing       Just o -> do-        let (st, actions) = stepPeer (limits mgr) input o.state+        let (st, actions) = stepPeer (limits mgr o) input o.state             o' = o {state = st}         writeTVar mgr.peers (sort (o' : filter (/= o) ops))         return (Just (o', actions))@@ -367,6 +409,13 @@           mgr.config.logger           ("Disconnecting peer " <> p.label <> ": " <> cs (show r))         killPeer p+      Abort r -> do+        logWarn+          mgr.config.logger+          ("Cancelling peer " <> p.label <> ", which did not stop in time: " <> cs (show r))+        -- in a thread of its own, since 'cancel' waits for the thread to end+        -- and the peer manager must not+        void (forkIO (cancel o.async))  -- | Record that a peer just sent a message, so that it is not disconnected for -- being idle. "Haskoin.Node" calls this for every message received.@@ -436,9 +485,9 @@ connectionOutcome :: PeerState -> Maybe SomeException -> Outcome connectionOutcome st e =   case (st.stage, peerException =<< e) of-    (Disconnecting TooOld, _) -> Disconnected-    (Disconnecting (Rejected _), _) -> Misbehaved-    (Disconnecting _, _) -> Failed+    (Disconnecting TooOld _, _) -> Disconnected+    (Disconnecting (Rejected _) _, _) -> Misbehaved+    (Disconnecting _ _, _) -> Failed     (_, Just ConnectionClosed)       | st.announced -> Disconnected       | otherwise -> Failed@@ -474,7 +523,9 @@ -- -- Configured peers come first. Otherwise an address is picked at random among -- those in a network group that the node is not connected to yet, as Bitcoin--- Core requires of its automatic outbound connections (see 'netGroup').+-- Core requires of its automatic outbound connections (see 'netGroup'), and+-- only while a slot is free that no configured peer is waiting for+-- ('othersFit'). getNewPeer :: PeerMgr -> IO (Maybe SockAddr) getNewPeer mgr = do   now <- getCurrentTime@@ -483,11 +534,21 @@   r <- randomIO   atomically $ do     used <- usedGroups <$> readTVar mgr.peers+    room <- othersFit mgr     stateTVar mgr.addresses $ \book ->-      case takeAddress now r ((`notElem` used) . netGroup) book of+      case takeAddress now r (\sa -> room && netGroup sa `notElem` used) book of         Just (sa, book') -> (Just sa, book')         Nothing -> (Nothing, book) +-- | Whether a seed or gossiped address may be connected to now: a slot is+-- free, and no configured peer that has no connection is waiting for it+-- ('roomForOthers').+othersFit :: PeerMgr -> STM Bool+othersFit mgr = do+  open <- map (.address) <$> readTVar mgr.peers+  names <- readTVar mgr.configured+  return (roomForOthers mgr.config.maxPeers names open)+ -- | Network groups of the open connections. usedGroups :: [OnlinePeer] -> [NetGroup] usedGroups = map (netGroup . (.address))@@ -502,35 +563,49 @@ loadPeers mgr now = do   let net = mgr.config.net       resolve = fmap concat . mapM (toSockAddr net)-  configured <- resolve mgr.config.peers+  -- one list for each name: a name is one peer, whatever it resolves to+  names <- mapM (toSockAddr net) mgr.config.peers+  let configured = concat names   seeds <- if mgr.config.discover then filter isRoutable <$> resolve net.seeds else return []-  atomically . modifyTVar' mgr.addresses $ \book ->-    markLoaded now $-      foldr (addAddress Seeded) (foldr (addAddress Configured) book configured) seeds+  atomically $ do+    writeTVar mgr.configured names+    modifyTVar' mgr.addresses $ \book ->+      markLoaded now $+        foldr (addAddress Seeded) (foldr (addAddress Configured) book configured) seeds  -- | Start a peer process for an address taken from the address book and send -- it our version, unless there are no free slots, the address is connected -- already, or it is a seed or gossiped address in a network group that the--- node is connected to already. Then the address is given back.+-- node is connected to already, or one that would take the slot kept for a+-- configured peer that has no connection. Then the address is given back. connectPeer :: PeerMgr -> SockAddr -> IO () connectPeer mgr sa = do   ops <- readTVarIO mgr.peers   source <- addressSource sa <$> readTVarIO mgr.addresses+  room <- atomically (othersFit mgr)   if     | length ops >= mgr.config.maxPeers -> giveBack "no free slots"     | any ((== sa) . (.address)) ops -> giveBack "already connected"+    | source /= Just Configured && not room -> giveBack "the free slots are kept for configured peers"     | source /= Just Configured && netGroup sa `elem` usedGroups ops ->         giveBack "network group in use"     | otherwise -> do         logDebug mgr.config.logger ("Connecting to peer " <> cs (show sa))         nonce <- randomIO+        seed <- randomIO         height <- readTVarIO mgr.best         now <- getCurrentTime         let net = mgr.config.net             services = if net.segWit then 8 else 0-            rmt = NetworkAddress services (sockToHostAddress sa)+            rmt = NetworkAddress services (peerHostAddress sa)             unix = floor (utcTimeToPOSIXSeconds now)             ver = buildVersion net nonce height mgr.config.address rmt unix+            (addrNet, local) = seenAs sa+            granted+              | source == Just Configured = mgr.config.permissions+              | otherwise = Set.empty+            opened = floor (utcTimeToPOSIXSeconds now * 1000000)+            model = newRemote net granted addrNet local opened seed             pc =               PeerConfig                 { pub = mgr.config.pub,@@ -538,12 +613,12 @@                   label = cs (show sa),                   connect = mgr.config.connect sa,                   logger = withSource "Peer" mgr.config.logger,-                  lookupBlock = mgr.config.lookupBlock+                  lookupBlock = mgr.config.lookupBlock,+                  bestBlock = mgr.config.bestBlock,+                  remote = model                 }         (inbox, mailbox) <- newMailbox-        busy <- newTVarIO Free-        pending <- newTVarIO 0-        let p = wrapPeer pc busy pending mailbox+        p <- newPeer pc mailbox         -- The peer manager handles messages one at a time, so the peer cannot         -- die before it is in the list.         a <- mgr.supervisor `addChild` withHousekeeping mgr p (peer pc p inbox)@@ -555,7 +630,8 @@                 state = newPeerState now,                 async = a,                 mailbox = p,-                nonce = nonce+                nonce = nonce,+                configured = source == Just Configured               }               : x   where
src/Haskoin/Node/PeerMgr/Addresses.hs view
@@ -23,11 +23,17 @@ -- -- * __Configured peers are trusted more.__ Addresses from the configuration --   are what the operator asked for, so they are never banned and never---   forgotten: they back off at most 'maxBackoff', even after misbehaving.---   They are also tried first. Addresses from DNS seeds and gossip are---   banned for misbehaving, and at most 'maxDiscovered' of each are kept, so---   gossip cannot exhaust memory.+--   forgotten. They are tried first, and tried again every+--   'configuredBackoff' at most, whatever ended the last connection: a node+--   of the operator that comes back is a peer again within seconds.+--   Addresses from DNS seeds and gossip are banned for misbehaving, and at+--   most 'maxDiscovered' of each are kept, so gossip cannot exhaust memory. --+-- * __A configured peer keeps its place.__ While a configured peer has no+--   connection, a slot is kept for it, and no seed or gossiped address may+--   take it ('roomForOthers'). Before, the others filled every slot while+--   a configured peer was away, and it found none when it came back.+-- -- * __Seeds and gossip are kept apart.__ Addresses from DNS seeds count --   against their own limit. A peer that gossips thousands of addresses can --   fill the room for gossip, but not crowd out the seeds. Before, both@@ -65,8 +71,10 @@     needsReload,     markLoaded,     knownAddresses,+    roomForOthers,     retryDelay,     maxBackoff,+    configuredBackoff,     banTime,     reloadInterval,     maxDiscovered,@@ -149,6 +157,13 @@ maxBackoff :: NominalDiffTime maxBackoff = 600 +-- | Longest wait before a configured address is tried again, whatever+-- ended its last connection. The only reason for a configured peer to have+-- no connection is that it takes none, and the node must find out soon+-- when it does again.+configuredBackoff :: NominalDiffTime+configuredBackoff = 10+ -- | Wait after a discovered address misbehaved. banTime :: NominalDiffTime banTime = 24 * 3600@@ -237,12 +252,27 @@ finishAddress now outcome = adjust $ \e ->   let wait d f = e {state = Waiting (d `addUTCTime` now) f, failures = f}       backoff f = min maxBackoff (retryDelay * 2 ^ min f 30)+      most = if e.source == Configured then configuredBackoff else maxBackoff    in case outcome of         Disconnected -> wait retryDelay 0-        Failed -> let f = e.failures + 1 in wait (backoff f) f+        Failed -> let f = e.failures + 1 in wait (min most (backoff f)) f         Misbehaved-          | e.source == Configured -> wait maxBackoff (e.failures + 1)+          | e.source == Configured -> wait configuredBackoff (e.failures + 1)           | otherwise -> wait banTime (e.failures + 1)++-- | Whether a seed or gossiped address may be connected to: whether a slot+-- is free that no configured peer is waiting for.+--+-- Given the most connections, the addresses of each configured peer, as+-- its name resolved, and the addresses of the open connections. A+-- configured peer that has no connection to any of its addresses has a+-- slot kept for it, also one whose name resolved to nothing. One name is+-- one peer: a name with two addresses, as @localhost@ has, keeps one slot+-- and not two.+roomForOthers :: (Eq a) => Int -> [[a]] -> [a] -> Bool+roomForOthers most configured open = length open + length away < most+  where+    away = [() | addresses <- configured, not (any (`elem` open) addresses)]  -- | State of an address, or 'Nothing' if it is not known. addressState :: (Ord a) => a -> AddressBook a -> Maybe AddressState
src/Haskoin/Node/PeerMgr/Lifecycle.hs view
@@ -20,11 +20,22 @@ --   exactly like an online one until its process died: it was still offered --   to applications, still had its messages routed, and could be told to --   disconnect again. 'Disconnecting' makes that window explicit, and every---   input in it is ignored.+--   input in it is ignored but the clock. --+-- * __A disconnection always ends.__ Telling a peer process to disconnect+--   is a request, and a process can fail to carry it out: one blocked in a+--   write to a peer that stopped reading never looked at its mailbox, and+--   the connection kept its slot and its network group forever, with no+--   'Haskoin.Node.Peer.PeerDisconnected'. So 'Disconnecting' records when it+--   began, and a 'Tick' more than the timeout later gives 'Abort': the peer+--   manager cancels the thread of the process, which then dies like any+--   other, and its end is handled as usual. 'Abort' comes again after each+--   further timeout until the process is gone, so a cancellation that did not+--   take is tried again.+-- -- * __Time is an input.__ The rules about silence, pings and age depend on---   the clock. Instead of reading it, 'stepPeer' takes the time in 'Tick',---   'Heard' and 'GotPong'. Every timing rule can then be tested by passing+--   the clock. Instead of reading it, 'stepPeer' takes the time in every+--   input. Every timing rule can then be tested by passing --   times, without waiting. -- -- * __Randomness is an input.__ A ping needs a fresh nonce. 'Tick' carries@@ -61,8 +72,9 @@   | -- | the handshake is complete; holds the version of the peer and the ping     -- awaiting an answer, with the time it was sent and its nonce     Online !Version !(Maybe (UTCTime, Word64))-  | -- | the peer was told to disconnect, for the given reason-    Disconnecting !DisconnectReason+  | -- | the peer was told to disconnect, for the given reason, at the given+    -- time, or the time of its last 'Abort'+    Disconnecting !DisconnectReason !UTCTime   deriving stock (Eq, Show)  -- | Why the node disconnects from a peer.@@ -99,8 +111,9 @@ data Limits = Limits   { -- | longest silence, unanswered ping or handshake     timeout :: !NominalDiffTime,-    -- | longest connection, after which it is rotated-    maxLife :: !NominalDiffTime+    -- | longest connection, after which it is rotated; 'Nothing' for a+    -- connection that is never rotated, as one to a configured peer+    maxLife :: !(Maybe NominalDiffTime)   }   deriving stock (Eq, Show) @@ -108,10 +121,11 @@ data PeerInput   = -- | the peer sent a message at the given time     Heard !UTCTime-  | -- | the peer sent a handshake message-    GotHandshake !HandshakeEvent-  | -- | the version of the peer was refused (see 'checkVersion')-    Refused !HandshakeError+  | -- | the peer sent a handshake message, handled at the given time+    GotHandshake !UTCTime !HandshakeEvent+  | -- | the version of the peer was refused (see 'checkVersion'), at the+    -- given time+    Refused !UTCTime !HandshakeError   | -- | the peer answered a ping with the given nonce at the given time     GotPong !UTCTime !Word64   | -- | the clock ticked; holds the time, and a nonce for a ping if one is due@@ -128,6 +142,9 @@     SendPing !Word64   | -- | tell the peer process to disconnect     Disconnect !DisconnectReason+  | -- | the peer process was told to disconnect more than the timeout ago+    -- and is still there: cancel its thread+    Abort !DisconnectReason   deriving stock (Eq, Show)  -- | A connection opened at the given time, with our version sent.@@ -146,15 +163,22 @@ -- On a 'Tick', the checks come in this order: the connection is too old, the -- peer has been silent too long, the handshake took too long, a ping went -- unanswered too long. If none applies and no ping is pending, a ping is sent.+--+-- While 'Disconnecting', only a 'Tick' counts: once more than the timeout has+-- passed since the disconnection began, or since the last 'Abort', it gives+-- 'Abort'. stepPeer :: Limits -> PeerInput -> PeerState -> (PeerState, [PeerAction]) stepPeer limits input st =   case (st.stage, input) of-    (Disconnecting _, _) -> (st, [])+    (Disconnecting r began, Tick now _)+      | now `diffUTCTime` began > limits.timeout ->+          (st {stage = Disconnecting r now}, [Abort r])+    (Disconnecting _ _, _) -> (st, [])     (_, Heard t) -> (st {lastHeard = t}, [])-    (_, Refused e) -> disconnect (Rejected e)-    (Handshaking h, GotHandshake e) -> handshake h e-    (Online _ _, GotHandshake (GotVersion _)) -> disconnect (Rejected DuplicateVersion)-    (Online _ _, GotHandshake GotVerAck) -> disconnect (Rejected DuplicateVerAck)+    (_, Refused t e) -> disconnect t (Rejected e)+    (Handshaking h, GotHandshake t e) -> handshake t h e+    (Online _ _, GotHandshake t (GotVersion _)) -> disconnect t (Rejected DuplicateVersion)+    (Online _ _, GotHandshake t GotVerAck) -> disconnect t (Rejected DuplicateVerAck)     (Online v (Just (sent, n)), GotPong t n')       | n == n' ->           ( st@@ -165,23 +189,23 @@           )     (_, GotPong _ _) -> (st, [])     (stage, Tick now nonce)-      | now `since` st.connected > limits.maxLife -> disconnect TooOld-      | now `since` st.lastHeard > limits.timeout -> disconnect Silent+      | Just life <- limits.maxLife, now `since` st.connected > life -> disconnect now TooOld+      | now `since` st.lastHeard > limits.timeout -> disconnect now Silent       | Handshaking _ <- stage,         now `since` st.connected > limits.timeout ->-          disconnect HandshakeTimeout+          disconnect now HandshakeTimeout       | Online _ (Just (sent, _)) <- stage,         now `since` sent > limits.timeout ->-          disconnect NoPong+          disconnect now NoPong       | Online v Nothing <- stage ->           (st {stage = Online v (Just (now, nonce))}, [SendPing nonce])       | otherwise -> (st, [])   where     since = diffUTCTime-    disconnect r = (st {stage = Disconnecting r}, [Disconnect r])-    handshake h e =+    disconnect t r = (st {stage = Disconnecting r t}, [Disconnect r])+    handshake t h e =       case stepHandshake h e of-        Left err -> disconnect (Rejected err)+        Left err -> disconnect t (Rejected err)         Right (Established v, acts) ->           (st {stage = Online v Nothing, announced = True}, map action acts)         Right (h', acts) -> (st {stage = Handshaking h'}, map action acts)@@ -200,7 +224,7 @@ stageVersion st = case st.stage of   Handshaking h -> handshakeVersion h   Online v _ -> Just v-  Disconnecting _ -> Nothing+  Disconnecting _ _ -> Nothing  -- | The ping awaiting an answer: when it was sent, and its nonce. pendingPing :: PeerState -> Maybe (UTCTime, Word64)
+ src/Haskoin/Node/Router.hs view
@@ -0,0 +1,154 @@+-- |+-- Module      : Haskoin.Node.Router+-- Copyright   : (c) Haskoin Developers+-- License     : MIT+-- Maintainer  : jprupp@protonmail.ch+-- Stability   : experimental+-- Portability : POSIX+--+-- The order in which the node passes on what each peer does, as an explicit+-- state machine. "Haskoin.Node" runs it in the loop that routes the events of+-- peers to the peer manager, the chain and the application.+--+-- = The problem+--+-- The events of a peer come from two threads. Its messages come from the+-- thread that reads its socket; that it is connected, and later that it is+-- gone, come from the peer manager. Both publish to the one queue that the+-- router reads, and nothing orders the two. The peer manager announces a+-- peer once it has handled the message that completes the handshake, and by+-- then the reader may have queued more messages of the peer, which reach the+-- router first. The router used to ask the peer manager whether the peer was+-- online, which it was, and pass those messages on before the announcement:+-- the chain dropped the headers of a peer it did not know yet, and the+-- application saw messages from a peer that had not connected.+--+-- = The rule+--+-- For every peer, those that the router passes events to see+-- 'Haskoin.Node.Peer.PeerConnected' before any message that needs it, and+-- 'Haskoin.Node.Peer.PeerDisconnected' after all of them. The router keeps a+-- t'Route' for each peer:+--+-- * __No route__: the handshake is not complete. A message is handled as+--   from a peer that is not online ('Early'): @version@ and @verack@ go to+--   the peer manager, pings are answered, and the rest is dropped, as Bitcoin+--   Core does.+--+-- * 'Awaiting': the handshake completed ('HandshakeDone', which the router+--   learns from the peer manager right after it handles the message that+--   completes it), but the announcement has not come through the queue yet.+--   Messages are held, in order.+--+-- * 'Announced': the announcement came ('Connected'). The held messages are+--   handled first, in order, then every new one, as from an online peer+--   ('Deliver').+--+-- * 'Disconnected' ends the route: the announcement of the disconnection is+--   passed on ('Retire') and the route forgotten.+--+-- Order comes from the single queue and the single thread that reads it, not+-- from timing: whatever a peer's events were interleaved with, the actions+-- for one peer come out in this order.+--+-- = Bounded+--+-- Held messages count against the allowance of the peer+-- ('Haskoin.Node.Peer.maxPendingMessages'): the peer stops reading its socket+-- until they are handled, so at most that many are held for a peer. Every+-- message that arrives is disposed of exactly once, by 'Early', 'Deliver' or+-- 'Discard', which is what the allowance of the peer needs to be given back+-- exactly once per message.+module Haskoin.Node.Router+  ( Router,+    Route (..),+    RouterInput (..),+    RouterAction (..),+    newRouter,+    stepRouter,+    routeOf,+  )+where++import Data.Foldable (toList)+import Data.Sequence (Seq, (|>))+import Data.Sequence qualified as Seq++-- | Where a peer is in the order of its events. A peer without a route has+-- not completed the handshake.+data Route m+  = -- | the handshake completed and the announcement has not come yet; holds+    -- the messages that arrived since, oldest first+    Awaiting !(Seq m)+  | -- | the announcement came+    Announced+  deriving stock (Eq, Show)++-- | The routes of the peers, by a key that tells the peers apart. There are+-- as many as the peers with a complete handshake, so a list is enough, and+-- the key needs only equality.+newtype Router k m = Router [(k, Route m)]+  deriving stock (Eq, Show)++-- | What the router learns about a peer.+data RouterInput k m+  = -- | the peer sent a message+    Arrived !k !m+  | -- | the peer manager has completed the handshake of the peer and+    -- announced it; the announcement is on its way through the queue+    HandshakeDone !k+  | -- | the announcement that the peer is connected came through the queue+    Connected !k+  | -- | the announcement that the peer is gone came through the queue+    Disconnected !k+  deriving stock (Eq, Show)++-- | What the router does.+data RouterAction k m+  = -- | handle a message from a peer whose handshake is not complete+    Early !k !m+  | -- | handle a message from a peer that has been announced+    Deliver !k !m+  | -- | give back the allowance of a message and do nothing else with it+    Discard !k !m+  | -- | pass on that the peer is connected+    Announce !k+  | -- | pass on that the peer is gone+    Retire !k+  deriving stock (Eq, Show)++-- | A router that knows no peer.+newRouter :: Router k m+newRouter = Router []++-- | The route of a peer, if it has one.+routeOf :: (Eq k) => k -> Router k m -> Maybe (Route m)+routeOf k (Router rs) = lookup k rs++-- | Apply an input.+--+-- Inputs that the order of the queue rules out, such as a disconnection of+-- a peer that was never announced, still give a sensible answer: held+-- messages are discarded, and nothing is passed on about a peer that was+-- not announced.+stepRouter :: (Eq k) => RouterInput k m -> Router k m -> (Router k m, [RouterAction k m])+stepRouter input router@(Router rs) =+  case input of+    Arrived k m -> case lookup k rs of+      Nothing -> (router, [Early k m])+      Just (Awaiting q) -> (set k (Awaiting (q |> m)), [])+      Just Announced -> (router, [Deliver k m])+    HandshakeDone k -> case lookup k rs of+      Nothing -> (set k (Awaiting Seq.empty), [])+      Just _ -> (router, [])+    Connected k -> case lookup k rs of+      Nothing -> (set k Announced, [Announce k])+      Just (Awaiting q) -> (set k Announced, Announce k : map (Deliver k) (toList q))+      Just Announced -> (router, [])+    Disconnected k -> case lookup k rs of+      Nothing -> (router, [])+      Just (Awaiting q) -> (unset k, map (Discard k) (toList q))+      Just Announced -> (unset k, [Retire k])+  where+    set k r = Router ((k, r) : filter ((/= k) . fst) rs)+    unset k = Router (filter ((/= k) . fst) rs)
test/common/Haskoin/Node/Test.hs view
@@ -3,6 +3,10 @@   ( -- * Logging     withTestLogger, +    -- * Models of peers+    testRemote,+    testFacts,+     -- * Timing     within,     eventually,@@ -65,6 +69,7 @@ import Data.List (elemIndex) import Data.Maybe (fromMaybe, listToMaybe, mapMaybe) import Data.Serialize (decode, encode, runGet, runPut)+import Data.Set qualified as Set import Data.Text (Text) import Data.Time.Clock (NominalDiffTime) import Data.Time.Clock.POSIX (getPOSIXTime)@@ -74,6 +79,7 @@ import Haskoin import Haskoin.Node import Haskoin.Node qualified as NC (NodeConfig (..))+import Haskoin.Node.Peer.Remote qualified as Model import NQE import Network.Socket (SockAddr (..)) import System.Environment (lookupEnv)@@ -426,7 +432,8 @@                     timeout = 120,                     maxPeerLife = 48 * 3600,                     connect = connect,-                    logger = logger+                    logger = logger,+                    permissions = Set.empty                   }           withNode (modify cfg) $ \n ->             f TestNode {node = n, events = sub, net = net}@@ -454,3 +461,24 @@ waitForBest s t f = do   eventually s "best block header" $ f <$> chainGetBest t.node.chain   chainGetBest t.node.chain++-- | The model of a peer for a test that starts a peer process itself: a+-- local connection, with no permissions, whose handshake is complete, as it+-- is for every peer that "Haskoin.Node.PeerMgr" offers. The tests talk to the+-- peer process without a handshake, and the model of a real node would drop+-- their requests.+testRemote :: Network -> Model.Remote+testRemote net =+  Model.learnVersion theirs $+    foldl sendOne (Model.newRemote net Set.empty AddrIPv4 True 0 0) [MVersion ours, MVerAck]+  where+    facts = Model.Facts {now = 0, best = genesisNode net, known = mempty}+    sendOne r m = snd (Model.judge facts m r)+    zero = NetworkAddress 0 (sockToHostAddress (SockAddrInet 0 0))+    ours = buildVersion net 1 0 zero zero 0+    theirs = (buildVersion net 2 0 zero zero 0) {services = nodeNetwork .|. nodeWitness, relay = True}++-- | What a test peer knows of the chain when it judges a message: only the+-- genesis block.+testFacts :: Network -> Message -> IO Model.Facts+testFacts net _ = return Model.Facts {now = 0, best = genesisNode net, known = mempty}
test/regtest/Containerfile view
@@ -1,6 +1,8 @@ # Regtest image with official Bitcoin Core and Bitcoin Cash Node binaries. #-# Build with:+# The tests build it through podman-test (test/regtest/Regtest/Podman.hs),+# tagged by a hash of this file and the script, so a change builds a new+# image. To build it by hand: #   podman build -t haskoin-node-regtest test/regtest # # Hashes come from the official SHA256SUMS files published by each project:@@ -25,11 +27,14 @@  && rm -rf /var/lib/apt/lists/*  # The script reads the versions and hashes above from the build arguments.-COPY install-nodes.sh /usr/local/bin/install-nodes.sh+# podman-test writes the files of the context without their modes, so the+# copy makes the script executable.+COPY --chmod=0755 install-nodes.sh /usr/local/bin/install-nodes.sh RUN /usr/local/bin/install-nodes.sh -# Peer-to-peer ports for up to three nodes per container.-EXPOSE 18444 18445 18446+# Peer-to-peer ports for up to three nodes per container, which the tests+# bridge to Unix sockets.+EXPOSE 18444 18446 18448  # Nodes are started with "podman exec" by the test suite. CMD ["sleep", "infinity"]
− test/regtest/Main.hs
@@ -1,196 +0,0 @@--- | Test the library against Bitcoin Core and Bitcoin Cash Node in regtest--- mode. Nodes run in Podman containers built from the Containerfile in this--- directory. Set HASKOIN_NODE_SKIP_REGTEST to skip.-module Main (main) where--import Control.Monad (forM_, replicateM_, void)-import Data.List (isInfixOf)-import Data.Maybe (isJust)-import Data.String (fromString)-import Haskoin-import Haskoin.Node-import Haskoin.Node.Test-import Regtest.Podman-import System.Environment (lookupEnv)-import Test.Hspec--main :: IO ()-main = do-  skip <- isJust <$> lookupEnv "HASKOIN_NODE_SKIP_REGTEST"-  available <- podmanAvailable-  if-    | skip -> hspec $ it "regtest" $ pendingWith "HASKOIN_NODE_SKIP_REGTEST set"-    | not available -> hspec $ it "regtest" $ pendingWith "podman not available"-    | otherwise -> buildImage >> hspec spec---- | Node connected to the given nodes in the container. The timeout is long--- so that the stall recovery poll does not hide announcement handling bugs.-withRegtestNode :: Container -> [Int] -> (TestNode -> IO a) -> IO a-withRegtestNode c is f = do-  addrs <- mapM (hostAddress c) is-  withTestNode-    (implNet c.impl)-    addrs-    withConnection-    (setTimeout 600)-    f---- | Wait until our best header is the tip of node number @i@.-waitForTip :: Container -> Int -> TestNode -> IO BlockNode-waitForTip c i t = do-  tip <- fromString <$> cli c i ["getbestblockhash"]-  waitForBest 60 t ((== tip) . headerHash . (.header))--blockHashAt :: Container -> Int -> Int -> IO BlockHash-blockHashAt c i h = fromString <$> cli c i ["getblockhash", show h]---- | Node 0 with blocks mined so that it leaves initial block download.-withMinedNode :: Impl -> Int -> (Container -> IO a) -> IO a-withMinedNode impl n f =-  withContainer impl $ \c -> do-    startNode c 0 []-    _ <- mine c 0 n-    f c--spec :: Spec-spec = forM_ [BitcoinCore, BitcoinCashNode] $ \impl ->-  describe (implName impl) $ do-    let net = implNet impl--    it "completes the handshake" $ withMinedNode impl 1 $ \c ->-      withRegtestNode c [0] $ \t -> do-        p <- waitForPeer t-        Just o <- getOnlinePeer t.node.peerMgr p-        Just v <- return o.version-        v.version `shouldSatisfy` (>= 70012)-        let VarString ua = v.userAgent-            expected = case impl of-              BitcoinCore -> "Satoshi"-              BitcoinCashNode -> "Bitcoin Cash Node"-        show ua `shouldSatisfy` (expected `isInfixOf`)--    it "syncs a chain longer than one header batch" $-      withMinedNode impl 2100 $ \c ->-        withRegtestNode c [0] $ \t -> do-          bn <- receiveWithin 120 "synced" t.events $ \case-            ChainEvent (ChainSynced bn) -> Just bn-            _ -> Nothing-          bn.height `shouldBe` 2100-          void $ waitForTip c 0 t--    it "follows blocks mined one at a time" $ withMinedNode impl 1 $ \c ->-      withRegtestNode c [0] $ \t -> do-        _ <- waitForTip c 0 t-        replicateM_ 5 $ mine c 0 1 >> waitForTip c 0 t--    it "follows bursts of blocks without stalling" $-      withMinedNode impl 1 $ \c ->-        withRegtestNode c [0] $ \t -> do-          _ <- waitForTip c 0 t-          replicateM_ 3 $ mine c 0 99 >> waitForTip c 0 t--    it "follows a burst longer than a header batch" $-      withMinedNode impl 1 $ \c ->-        withRegtestNode c [0] $ \t -> do-          _ <- waitForTip c 0 t-          _ <- mine c 0 2500-          bn <- waitForTip c 0 t-          bn.height `shouldBe` 2501--    it "follows a reorganization" $ withMinedNode impl 10 $ \c ->-      withRegtestNode c [0] $ \t -> do-        old <- waitForTip c 0 t-        h8 <- cli c 0 ["getblockhash", "8"]-        void $ cli c 0 ["invalidateblock", h8]-        _ <- mineTo c 0 5 otherAddress-        new <- waitForTip c 0 t-        new.height `shouldBe` 12-        chainBlockMain t.node.chain (headerHash old.header) `shouldReturn` False-        split <- chainGetSplitBlock t.node.chain old new-        split.height `shouldBe` 7--    it "follows a reorganization found in a burst" $-      withMinedNode impl 120 $ \c ->-        withRegtestNode c [0] $ \t -> do-          _ <- waitForTip c 0 t-          h <- cli c 0 ["getblockhash", "70"]-          void $ cli c 0 ["invalidateblock", h]-          _ <- mineTo c 0 99 otherAddress-          new <- waitForTip c 0 t-          new.height `shouldBe` 168--    it "downloads blocks" $ withMinedNode impl 5 $ \c ->-      withRegtestNode c [0] $ \t -> do-        p <- waitForPeer t-        _ <- waitForTip c 0 t-        hs <- mapM (blockHashAt c 0) [1 .. 5]-        Just bs <- getBlocks net 10 p hs-        map (headerHash . (.header)) bs `shouldBe` hs-        forM_ bs $ \b ->-          buildMerkleRoot (map txHash b.txs) `shouldBe` Right b.header.merkle-        let unknown = headerHash (mkHeaders net 9 net.genesisHeader 0 1 !! 0)-        getBlocks net 10 p [unknown] `shouldReturn` Nothing--    it "downloads announced transactions" $ withContainer impl $ \c -> do-      startNode c 0 []-      -- Bitcoin Cash Node also loads a default wallet, so name ours-      let wallet args = cli c 0 ("-rpcwallet=w" : args)-      void $ cli c 0 ["createwallet", "w"]-      addr <- wallet ["getnewaddress"]-      void $ mineTo c 0 101 addr-      withRegtestNode c [0] $ \t -> do-        p <- waitForPeer t-        _ <- waitForTip c 0 t-        txid <- fromString <$> wallet ["sendtoaddress", mineAddress, "1"]-        receiveWithin 60 "transaction announcement" t.events $ \case-          PeerEvent (PeerMessage p' (MInv (Inv ivs)))-            | p == p' && any ((== txid) . TxHash . (.invHash)) ivs -> Just ()-          _ -> Nothing-        Just [tx] <- getTxs net 10 p [txid]-        txHash tx `shouldBe` txid--    it "pings a peer" $ withMinedNode impl 1 $ \c ->-      withRegtestNode c [0] $ \t -> do-        p <- waitForPeer t-        pingPeer 10 p `shouldReturn` True--    it "reconnects to a restarted peer and catches up" $-      withMinedNode impl 5 $ \c ->-        withRegtestNode c [0] $ \t -> do-          p <- waitForPeer t-          _ <- waitForTip c 0 t-          stopNode c 0-          waitForDisconnect t p-          startNode c 0 []-          _ <- mine c 0 3-          _ <- waitForPeer t-          bn <- waitForTip c 0 t-          bn.height `shouldBe` 8--    it "keeps following the chain when a peer goes away" $-      withMinedNode impl 5 $ \c -> do-        startNode c 1 ["-addnode=" <> nodeAddress c 0]-        eventually 60 "nodes in sync" $-          (== "5") <$> cli c 1 ["getblockcount"]-        withRegtestNode c [0, 1] $ \t -> do-          _ <- waitForPeer t-          _ <- waitForPeer t-          _ <- waitForTip c 0 t-          stopNode c 0-          _ <- mine c 1 5-          bn <- waitForTip c 1 t-          bn.height `shouldBe` 10--    it "follows bursts announced by several peers" $-      withMinedNode impl 1 $ \c -> do-        startNode c 1 ["-addnode=" <> nodeAddress c 0]-        withRegtestNode c [0, 1] $ \t -> do-          _ <- waitForPeer t-          _ <- waitForPeer t-          _ <- waitForTip c 0 t-          replicateM_ 3 $ mine c 0 99 >> waitForTip c 0 t-          eventually 60 "nodes in sync" $-            (== "298") <$> cli c 1 ["getblockcount"]-          expectNothingWithin 1 "peer disconnection" t.events $ \case-            PeerEvent (PeerDisconnected _) -> Just ()-            _ -> Nothing
test/regtest/Regtest/Podman.hs view
@@ -1,14 +1,29 @@--- | Bitcoin Core and Bitcoin Cash Node regtest nodes in Podman containers.+-- | Bitcoin Core and Bitcoin Cash Node regtest nodes in a Podman container,+-- run by podman-test ("Test.Podman").+--+-- A container holds up to three nodes, which the tests start and stop with+-- @podman exec@. The container is in a pod of its own with no network: each+-- node's peer-to-peer port is bridged to a Unix socket of the pod, and the+-- node under test connects to it as the peer @unix:PATH@. Tests that run at+-- once each have their own sockets, so they never meet and take no port of+-- the machine. Inside the container, where nothing else runs, the ports are+-- fixed, and the nodes reach each other on @127.0.0.1@.+--+-- The image is built from @test\/regtest\/Containerfile@ and the script it+-- runs, read from the package folder, where the tests run. podman-test+-- tags it by a hash of both, and builds it once for every test process of+-- the machine. module Regtest.Podman   ( Impl (..),     implName,     implNet,     Container (..),-    podmanAvailable,-    buildImage,+    podmanUsable,     withContainer,     startNode,     stopNode,+    freezeNode,+    thawNode,     cli,     hostAddress,     nodeAddress,@@ -20,16 +35,28 @@ where  import Control.Concurrent (threadDelay)-import Control.Exception (bracket) import Control.Monad (unless, void)-import Data.Char (isHexDigit, isSpace)-import Data.List (dropWhileEnd)+import Data.ByteString qualified as B+import Data.Char (isHexDigit) import Haskoin (Network, bchRegTest, btcRegTest)-import System.Directory (findExecutable) import System.Exit (ExitCode (..))-import System.Process (readProcessWithExitCode)-import System.Random (randomRIO)-import System.Timeout (timeout)+import Test.Podman+  ( Address (..),+    ContainerSpec (..),+    Endpoint (..),+    Image (..),+    ImageSpec (..),+    Pod,+    PodSpec (..),+    address,+    container,+    containerName,+    execWithin,+    pod,+    podmanUsable,+    withPod,+  )+import Test.Podman.Command (podmanStatus)  data Impl = BitcoinCore | BitcoinCashNode   deriving stock (Eq, Show)@@ -46,106 +73,64 @@ implDir BitcoinCore = "/opt/bitcoin-core/bin/" implDir BitcoinCashNode = "/opt/bchn/bin/" --- | Running container with ports for up to three nodes.+-- | A running container for up to three nodes, in its pod. data Container = Container-  { cid :: !String,-    impl :: !Impl,-    -- | peer-to-peer port of each node inside the container-    p2pPorts :: ![Int],-    -- | RPC port of each node inside the container-    rpcPorts :: ![Int]+  { pod :: !Pod,+    impl :: !Impl   } +-- | The peer-to-peer port of node number @i@ in the container. They are two+-- apart, and the RPC ports are above them, because a node may listen on the+-- port above its own for Tor.+p2pPort :: Int -> Int+p2pPort i = 18444 + 2 * i++-- | The RPC port of node number @i@ in the container.+rpcPort :: Int -> Int+rpcPort i = 18454 + 2 * i+ -- | Number of nodes that can run in a container. maxNodes :: Int maxNodes = 3 -image :: String-image = "localhost/haskoin-node-regtest:latest"---- | Build context of the image: the directory with the Containerfile and the--- @install-nodes.sh@ script it runs, relative to the package root.-imageDir :: FilePath-imageDir = "test/regtest"---- | Run podman and return its standard output. Throws on failure or if it--- takes longer than two minutes.-podman :: [String] -> IO String-podman = podmanWithin 120---- | Run podman with a timeout in seconds.-podmanWithin :: Int -> [String] -> IO String-podmanWithin secs args =-  timeout (secs * 1000000) (readProcessWithExitCode "podman" args "") >>= \case-    Nothing ->-      fail $-        "podman " <> unwords args <> " timed out after " <> show secs <> "s"-    Just (ExitSuccess, out, _) -> return (dropWhileEnd isSpace out)-    Just (ExitFailure c, out, err) ->-      fail $-        "podman "-          <> unwords args-          <> " exited with "-          <> show c-          <> ": "-          <> out-          <> err--podmanAvailable :: IO Bool-podmanAvailable =-  findExecutable "podman" >>= \case-    Nothing -> return False-    Just _ -> do-      (c, _, _) <- readProcessWithExitCode "podman" ["info"] ""-      return (c == ExitSuccess)+-- | The name of the container in its pod.+regtest :: String+regtest = "regtest" --- | Build the image. Cached layers make this quick after the first time.-buildImage :: IO ()-buildImage = void $ podmanWithin 1800 ["build", "--quiet", "--tag", image, imageDir]+-- | The image of the nodes, from the Containerfile and its script in the+-- package folder.+nodeImage :: IO Image+nodeImage = do+  recipe <- B.readFile "test/regtest/Containerfile"+  script <- B.readFile "test/regtest/install-nodes.sh"+  return $+    Built+      ImageSpec+        { name = "haskoin-node-regtest",+          containerfile = recipe,+          files = [("install-nodes.sh", script)]+        } --- | Run a container. Node ports inside it are random, and are published to--- random ports on the loopback interface of the host.+-- | Run a container, idle until the tests start its nodes, and remove it+-- afterwards. Its pod is ready at once: the bridges listen on the sockets+-- before any node does, and 'startNode' waits for its node. The container+-- may use 2 GiB of memory, for its three nodes at most, so that a node that+-- runs away fails its test instead of taking the memory of the machine. withContainer :: Impl -> (Container -> IO a) -> IO a-withContainer impl = bracket start stop-  where-    start = do-      ports <- randomPorts (2 * maxNodes)-      let (p2p, rpc) = splitAt maxNodes ports-      cid <--        podman $-          ["run", "--detach", "--rm"]-            <> concat [["--publish", "127.0.0.1::" <> show p] | p <- p2p]-            <> [image]-      return Container {cid = cid, impl = impl, p2pPorts = p2p, rpcPorts = rpc}-    stop :: Container -> IO ()-    stop c = void $ podman ["rm", "--force", "--time", "0", c.cid]---- | Distinct random ports. They are at least two apart because nodes may--- also listen on the next port up for Tor.-randomPorts :: Int -> IO [Int]-randomPorts n = go []-  where-    go ps-      | length ps == n = return (reverse ps)-      | otherwise = do-          p <- randomRIO (20000, 60000)-          if any (\q -> abs (p - q) < 2) ps then go ps else go (p : ps)--p2pPort :: Container -> Int -> Int-p2pPort c i = c.p2pPorts !! i--rpcPort :: Container -> Int -> Int-rpcPort c i = c.rpcPorts !! i+withContainer impl f = do+  image <- nodeImage+  let spec =+        (container regtest image)+          { memory = Just "2g",+            endpoints = [Bridged ("p2p" <> show i) (p2pPort i) | i <- [0 .. maxNodes - 1]]+          }+  withPod (pod "regtest" [spec]) {ready = []} $ \p -> f Container {pod = p, impl}  dataDir :: Int -> FilePath dataDir i = "/data/node" <> show i  exec :: Container -> [String] -> IO String-exec c args = podman (["exec", c.cid] <> args)---- | Like 'exec' with a timeout in seconds.-execWithin :: Int -> Container -> [String] -> IO String-execWithin secs c args = podmanWithin secs (["exec", c.cid] <> args)+exec c = execWithin 120 c.pod regtest  -- | Start node number @i@ in the container with extra arguments. Data -- persists across restarts.@@ -157,9 +142,9 @@       "-regtest",       "-daemon",       "-datadir=" <> dataDir i,-      "-port=" <> show (p2pPort c i),-      "-bind=0.0.0.0:" <> show (p2pPort c i),-      "-rpcport=" <> show (rpcPort c i),+      "-port=" <> show (p2pPort i),+      "-bind=0.0.0.0:" <> show (p2pPort i),+      "-rpcport=" <> show (rpcPort i),       "-listen=1",       "-listenonion=0",       "-fallbackfee=0.0002",@@ -174,20 +159,33 @@   void $ cli c i ["stop"]   let pidfile = dataDir i <> "/regtest/bitcoind.pid"       wait n = do-        (code, _, _) <--          readProcessWithExitCode "podman" ["exec", c.cid, "test", "-e", pidfile] ""+        (code, _, _) <- podmanStatus 60 ["exec", containerName c.pod regtest, "test", "-e", pidfile]         unless (code /= ExitSuccess || n > (300 :: Int)) $           threadDelay 100000 >> wait (n + 1)   wait 0   threadDelay 500000 +-- | Stop node number @i@ in its tracks, with @SIGSTOP@: its connections stay+-- open and it answers nothing on them, as a peer that hangs does. Its RPC+-- does not answer either until 'thawNode'.+freezeNode :: Container -> Int -> IO ()+freezeNode c i = signalNode c i "STOP"++-- | Let node number @i@ go on after 'freezeNode', with @SIGCONT@.+thawNode :: Container -> Int -> IO ()+thawNode c i = signalNode c i "CONT"++signalNode :: Container -> Int -> String -> IO ()+signalNode c i sig =+  void $ exec c ["sh", "-c", "kill -" <> sig <> " $(cat " <> dataDir i <> "/regtest/bitcoind.pid)"]+ cli' :: Int -> Container -> Int -> [String] -> IO String cli' secs c i args =-  execWithin secs c $+  execWithin secs c.pod regtest $     [ implDir c.impl <> "bitcoin-cli",       "-regtest",       "-datadir=" <> dataDir i,-      "-rpcport=" <> show (rpcPort c i)+      "-rpcport=" <> show (rpcPort i)     ]       <> args @@ -197,15 +195,14 @@  -- | Address of node number @i@ for other nodes in the container. nodeAddress :: Container -> Int -> String-nodeAddress c i = "127.0.0.1:" <> show (p2pPort c i)+nodeAddress _ i = "127.0.0.1:" <> show (p2pPort i) --- | Address and port on the host for node number @i@.+-- | The peer of node number @i@ for the node under test: the Unix socket+-- of the pod that is bridged to its peer-to-peer port, as @unix:PATH@. hostAddress :: Container -> Int -> IO String-hostAddress c i = do-  out <- podman ["port", c.cid, show (p2pPort c i) <> "/tcp"]-  case lines out of-    a : _ -> return a-    [] -> fail $ "No port mapping for node " <> show i+hostAddress c i = case address c.pod ("p2p" <> show i) of+  UnixSocket path -> return ("unix:" <> path)+  a -> fail ("The peer-to-peer endpoint of node " <> show i <> " is not a socket: " <> show a)  -- | Regtest address valid for both implementations. mineAddress :: String
test/unit/Haskoin/Node/AddressSpec.hs view
@@ -1,16 +1,21 @@ module Haskoin.Node.AddressSpec (spec) where +import Conduit (await, runConduit, yield, (.|))+import Control.Concurrent.Async (withAsync) import Control.Exception (IOException, bracket, try) import Control.Monad (forM_)+import Data.ByteString.Char8 qualified as C+import Data.IORef (newIORef, readIORef, writeIORef) import Data.Time.Clock (diffUTCTime, getCurrentTime) import Data.Word (Word16, Word8)-import Haskoin (Network (..), btcRegTest)-import Haskoin.Node (toHostService, toSockAddr)-import Haskoin.Node.Address (NetGroup (..), isRoutable, netGroup, withConnection)+import Haskoin (Network (..), btcRegTest, sockToHostAddress)+import Haskoin.Node (Conduits (..), toHostService, toSockAddr)+import Haskoin.Node.Address (NetGroup (..), isRoutable, netGroup, peerHostAddress, withConnection) import Network.Socket-  ( Family (AF_INET),+  ( Family (AF_INET, AF_UNIX),     SockAddr (..),     SocketType (Stream),+    accept,     bind,     close,     connect,@@ -21,6 +26,8 @@     tupleToHostAddress,     tupleToHostAddress6,   )+import Network.Socket.ByteString (recv, sendAll)+import System.IO.Temp (withSystemTempDirectory) import Test.Hspec import Test.Hspec.QuickCheck (prop) @@ -87,6 +94,42 @@           end <- getCurrentTime           either (\(_ :: IOException) -> True) (const False) r `shouldBe` True           end `diffUTCTime` start `shouldSatisfy` (\d -> d >= 4.5 && d < 8)++  describe "Unix sockets" $ do+    it "reads unix:PATH as a Unix socket, and an empty path as nothing" $ do+      toSockAddr btcRegTest "unix:/run/node/p2p.sock" `shouldReturn` [SockAddrUnix "/run/node/p2p.sock"]+      toSockAddr btcRegTest "unix:" `shouldReturn` []++    it "never takes a Unix socket for an address worth relaying, and groups it as local" $ do+      isRoutable (SockAddrUnix "/run/node/p2p.sock") `shouldBe` False+      netGroup (SockAddrUnix "/run/node/p2p.sock") `shouldBe` LocalGroup++    it "gives the zero address of a Unix socket for the version message" $ do+      peerHostAddress (SockAddrUnix "/run/node/p2p.sock") `shouldBe` sockToHostAddress (SockAddrInet 0 0)+      peerHostAddress (v4 (45, 1, 2, 3)) `shouldBe` sockToHostAddress (v4 (45, 1, 2, 3))++    it "opens a connection to a Unix socket, which carries bytes both ways" $+      withSystemTempDirectory "haskoin-node-unix" $ \dir -> do+        let path = dir <> "/peer.sock"+            listener = do+              s <- socket AF_UNIX Stream defaultProtocol+              bind s (SockAddrUnix path)+              listen s 1+              return s+            -- answer what the node sends with the same bytes+            echo srv = bracket (fst <$> accept srv) close $ \c -> recv c 64 >>= sendAll c+        bracket listener close $ \srv ->+          withAsync (echo srv) $ \_ -> do+            got <- newIORef Nothing+            withConnection (SockAddrUnix path) $ \conduits -> do+              runConduit (yield (C.pack "version") .| conduits.outboundConduit)+              runConduit (conduits.inboundConduit .| await) >>= writeIORef got+            readIORef got `shouldReturn` Just (C.pack "version")++    it "fails to open a connection to a Unix socket that is not there" $+      withSystemTempDirectory "haskoin-node-unix" $ \dir -> do+        r <- try (withConnection (SockAddrUnix (dir <> "/nobody.sock")) (\_ -> return ()))+        either (\(_ :: IOException) -> True) (const False) r `shouldBe` True    describe "network groups" $ do     -- 45.1.2.3 is 0x2d010203.
test/unit/Haskoin/Node/BlockSpec.hs view
@@ -1,3 +1,8 @@+{-# OPTIONS_GHC -Wno-deprecations #-}++-- testnet3 (btcTest) is deprecated in haskoin-core 3.0.0 but still works,+-- and its witness rule is still tested here.+ -- | Whether a block holds the transactions its header commits to, against -- blocks mined by Bitcoin Core 32.1 and copies of them changed the ways a -- peer could change them.
test/unit/Haskoin/Node/ChainSpec.hs view
@@ -48,9 +48,26 @@   (inbox, mailbox) <- newMailbox   busy <- newTVarIO Free   pending <- newTVarIO 0+  remote <- newTVarIO (testRemote ct.net)+  closing <- newTVarIO False+  requestLock <- newTMVarIO ()+  owed <- newTVarIO Nothing+  let facts = testFacts ct.net   return     FakePeer-      { peer = Peer {mailbox, pub = ct.peerPub, label, busy, pending},+      { peer =+          Peer+            { mailbox,+              pub = ct.peerPub,+              label,+              busy,+              pending,+              remote,+              facts,+              closing,+              requestLock,+              owed+            },         inbox       } @@ -63,6 +80,7 @@ describeMessage :: PeerMessage -> String describeMessage KillPeer = "disconnection" describeMessage (SendMessage m) = show (commandToString (msgType m))+describeMessage (NotSent m _) = "refused " <> show (commandToString (msgType m))  -- | Next header request sent to the peer, skipping 'MSendHeaders'. expectGetHeaders :: FakePeer -> IO GetHeaders@@ -207,6 +225,24 @@         let old = mkHeaders net 0 net.genesisHeader 1500000000 10         _ <- syncPeer ct "a" old         chainIsSynced ct.chain `shouldReturn` False++      it "has the headers of its peers when none is awaited, however old they are, and not without a peer" $+        slow $ \ct -> do+          -- nobody to have the headers of+          chainHasHeaders ct.chain `shouldReturn` False+          let old = mkHeaders net 0 net.genesisHeader 1500000000 10+          _ <- syncPeer ct "a" old+          chainHasHeaders ct.chain `shouldReturn` True+          chainIsSynced ct.chain `shouldReturn` False++      it "does not have the headers of its peers while a peer still sends them" $ slow $ \ct -> do+        a <- connectPeer ct "a"+        var <- newTVarIO main+        -- the peer is asked, and has not answered+        chainHasHeaders ct.chain `shouldReturn` False+        withServer ct a var $ \_ -> do+          _ <- waitHeight ct 4500+          eventually 10 "the chain to have the headers of its peer" (chainHasHeaders ct.chain)        it "stops asking a peer that sends no headers" $ slow $ \ct -> do         a <- connectPeer ct "a"
+ test/unit/Haskoin/Node/Peer/RemoteSpec.hs view
@@ -0,0 +1,121 @@+module Haskoin.Node.Peer.RemoteSpec (spec) where++import Data.Bits ((.|.))+import Data.Int (Int64)+import Data.Set qualified as Set+import Data.Word (Word64)+import Haskoin+import Haskoin.Network.Protocol qualified as P+import Haskoin.Node (buildVersion)+import Haskoin.Node.Peer.Remote+import Network.Socket (SockAddr (..))+import Test.Hspec+import Test.Hspec.QuickCheck (prop)+import Test.QuickCheck ((.&&.), (===))++spec :: Spec+spec = do+  describe "a mempool request" $ do+    it "is refused by Bitcoin Core without the mempool permission" $+      fst (judge (facts btc) MMempool (handshaken btc Set.empty plain)) `shouldSatisfy` refused+    it "is allowed by Bitcoin Core with the mempool permission" $+      fst (judge (facts btc) MMempool (handshaken btc (Set.singleton P.PermMempool) plain))+        `shouldBe` Allowed+    it "is dropped without a word by Bitcoin Core with noban" $+      fst (judge (facts btc) MMempool (handshaken btc (Set.singleton P.PermNoBan) plain))+        `shouldSatisfy` unanswered+    it "is allowed by a node that offers Bloom filters" $+      fst (judge (facts btc) MMempool (handshaken btc Set.empty bloom)) `shouldBe` Allowed+    it "is refused by Bitcoin Cash Node that offers no Bloom filters" $+      fst (judge (facts bch) MMempool (handshaken bch Set.empty plain)) `shouldSatisfy` refused+    it "is allowed by Bitcoin Cash Node that offers Bloom filters" $+      fst (judge (facts bch) MMempool (handshaken bch Set.empty bloom)) `shouldBe` Allowed++  describe "the version of the node" $ do+    it "replays the messages sent before it with the options it gives" $ do+      -- the mempool request is judged with the defaults of Bitcoin Cash+      -- Node, which offer Bloom filters; the node then says it offers none+      let r0 = sendAll bch (fresh bch Set.empty) [MVersion ours, MVerAck]+          r1 = learnVersion (theirs plain) r0+      fst (judge (facts bch) MMempool r0) `shouldBe` Allowed+      fst (judge (facts bch) MMempool r1) `shouldSatisfy` refused+    it "counts only once" $ do+      let r = learnVersion (theirs bloom) (handshaken bch Set.empty plain)+      fst (judge (facts bch) MMempool r) `shouldSatisfy` refused++  describe "the order of the handshake" $ do+    it "lets Bitcoin Core drop a request before the version without a word" $+      fst (judge (facts btc) MGetAddr (fresh btc Set.empty)) `shouldSatisfy` unanswered+    it "refuses a request before the version to Bitcoin Cash Node" $+      fst (judge (facts bch) MGetAddr (fresh bch Set.empty)) `shouldSatisfy` refused+    it "allows the version first" $+      fst (judge (facts btc) (MVersion ours) (fresh btc Set.empty)) `shouldBe` Allowed++  describe "a request for blocks" $ do+    it "is allowed for a block that this node does not know" $ do+      let unknown :: BlockHash+          unknown = "0000000000000000000000000000000000000000000000000000000000000001"+          iv = InvVector InvWitnessBlock unknown.get+      fst (judge (facts btc) (MGetData (GetData [iv])) (handshaken btc Set.empty plain))+        `shouldBe` Allowed+    it "of a filtered block is refused by a node without Bloom filters" $ do+      let iv = InvVector InvMerkleBlock (headerHash btc.genesisHeader).get+      fst (judge (facts btc) (MGetData (GetData [iv])) (handshaken btc Set.empty plain))+        `shouldSatisfy` refused++  describe "the clock of the model" $ do+    -- two threads that send to a peer at once read the clock, then commit+    -- in either order: the facts of a later commit can be older+    prop "never goes back, whatever the order of the times of the facts" $ \(ts :: [Int64]) ->+      let start = handshaken btc Set.empty plain+          tick r t = snd (judge (facts btc) {now = t} MSendHeaders r)+          clocks = map remoteClock (scanl tick start ts)+       in and (zipWith (<=) clocks (drop 1 clocks))+            .&&. clocks === scanl max (remoteClock start) ts+    it "starts at the time the connection opened" $+      remoteClock (newRemote btc Set.empty AddrIPv4 False 1234 7) `shouldBe` 1234+    it "keeps its time when the facts are older" $ do+      let r = snd (judge (facts btc) MSendHeaders (handshaken btc Set.empty plain))+          r' = snd (judge (facts btc) {now = 5} MSendHeaders r)+      remoteClock r' `shouldBe` remoteClock r++  describe "the answer to a refused transaction" $ do+    it "is a reject on Bitcoin Cash Node" $ expectsReject bch ours `shouldBe` True+    it "is nothing on Bitcoin Core" $ expectsReject btc ours `shouldBe` False+  where+    refused = \case+      Refused _ _ -> True+      _ -> False+    unanswered = \case+      Unanswered _ -> True+      _ -> False++-- | The services of a node that offers no Bloom filters, and of one that+-- does.+plain, bloom :: Word64+plain = nodeNetwork .|. nodeWitness+bloom = plain .|. nodeBloom++facts :: Network -> Facts+facts net = Facts {now = 1000000, best = genesisNode net, known = mempty}++fresh :: Network -> P.Permissions -> Remote+fresh net perms = newRemote net perms AddrIPv4 False 0 7++sendAll :: Network -> Remote -> [Message] -> Remote+sendAll net = foldl (\r m -> snd (judge (facts net) m r))++-- | A model whose handshake is complete, with a node that offers these+-- services.+handshaken :: Network -> P.Permissions -> Word64 -> Remote+handshaken net perms services =+  learnVersion (theirs services) (sendAll net (fresh net perms) [MVersion ours, MVerAck])++zero :: NetworkAddress+zero = NetworkAddress 0 (sockToHostAddress (SockAddrInet 0 0))++ours :: Version+ours = buildVersion btc 1 0 zero zero 0++theirs :: Word64 -> Version+theirs services = (buildVersion btc 2 0 zero zero 0) {services = services, relay = True}
test/unit/Haskoin/Node/Peer/RequestSpec.hs view
@@ -1,5 +1,6 @@ module Haskoin.Node.Peer.RequestSpec (spec) where +import Data.Word (Word64) import Haskoin import Haskoin.Node.Peer.Request import Haskoin.Node.Test (mkBlocks)@@ -18,11 +19,21 @@  -- | Feed messages to a request for the given items. feed :: [InvVector] -> [Message] -> RequestStep-feed ivs = foldl' step (newRequest 42 ivs)+feed ivs = feedInputs Nothing ivs . map Received++-- | Feed inputs to a request for the given items, which waits first for the+-- pong of an earlier request if it is given a nonce.+feedInputs :: Maybe Word64 -> [InvVector] -> [RequestInput] -> RequestStep+feedInputs stale ivs = foldl' step (newRequest stale 42 ivs)   where-    step (Continue r) m = stepRequest r m+    step (Continue r) i = stepRequest r i     step done _ = done +isContinue :: RequestStep -> Bool+isContinue = \case+  Continue _ -> True+  _ -> False+ -- | Messages that have nothing to do with the request. noise :: Gen Message noise =@@ -50,7 +61,7 @@     feed ivs (map MBlock want) `shouldBe` done    it "completes immediately when nothing is requested" $-    newRequest 42 [] `shouldBe` Complete []+    newRequest Nothing 42 [] `shouldBe` Complete []    it "receives transactions" $ do     let txs = map coinbaseOf want@@ -79,6 +90,43 @@     case feed ivs [MTx (coinbaseOf (head' want))] of       Continue _ -> return ()       other -> expectationFailure ("Expected to continue, got " <> show other)++  it "fails at once when the peer disconnects" $+    feedInputs Nothing ivs [Received (MBlock (head' want)), Disconnected]+      `shouldBe` Failed "peer disconnected"++  it "ignores a block that it did not ask for" $+    feed ivs [MBlock (blocks !! 4)] `shouldSatisfy` isContinue++  it "ignores a notfound for an item that it did not ask for" $+    feed ivs [MNotFound (NotFound [blockInv (blocks !! 4)])] `shouldSatisfy` isContinue++  describe "after a request that is still owed its pong" $ do+    let stale = Just 7++    it "ignores the answers to the earlier request until its pong" $+      -- the earlier request asked for the same blocks, which come late, out+      -- of order and incomplete+      let late = [MBlock (want !! 1), MNotFound (NotFound ivs), MPong (Pong 7)]+       in feedInputs stale ivs (map Received (late <> map MBlock want))+            `shouldBe` done++    it "fails when its own pong comes before the earlier one" $+      feedInputs stale ivs [Received (MPong (Pong 42))] `shouldBe` Failed "incomplete response"++    it "fails at once when the peer disconnects" $+      feedInputs stale ivs [Disconnected] `shouldBe` Failed "peer disconnected"++    prop "never ends before the earlier pong but by a disconnection or its own pong" $+      forAll (listOf (oneof [noise, MBlock <$> elements want, pure (MNotFound (NotFound ivs))])) $ \msgs ->+        let early = filter (`notElem` [MPong (Pong 7), MPong (Pong 42)]) msgs+         in isContinue (feedInputs stale ivs (map Received early))++  prop "completes only with the items asked for, in order" $+    forAll (listOf (oneof [noise, MBlock <$> elements blocks, pure (MPong (Pong 42))])) $ \msgs ->+      case feed ivs msgs of+        Complete items -> items === map Right want+        _ -> property True    prop "ignores unrelated messages between items" $     forAll (vectorOf 3 (listOf noise)) $ \gaps ->
test/unit/Haskoin/Node/PeerMgr/AddressesSpec.hs view
@@ -111,9 +111,35 @@   it "bans a discovered address that misbehaved" $     retryAt 1 (cycleWith Misbehaved 1 (book [1])) `shouldBe` Just (later banTime) -  it "never bans a configured address" $ do+  it "never bans a configured address, and tries it again within seconds" $ do     let b = addAddress Configured 1 (book [1])-    retryAt 1 (cycleWith Misbehaved 1 b) `shouldBe` Just (later maxBackoff)+    retryAt 1 (cycleWith Misbehaved 1 b) `shouldBe` Just (later configuredBackoff)++  it "tries a configured address that fails again every ten seconds at most, for ever" $ do+    let own = addAddress Configured 1 emptyBook+        waits = map (retryAt 1) (drop 1 (iterate (cycleFailed 1) own))+        cycleFailed a b = finishAddress t0 Failed a (snd (taken (later 1000000) b))+    take 4 waits `shouldBe` map (Just . later) [2, 4, 8, configuredBackoff]+    waits !! 200 `shouldBe` Just (later configuredBackoff)++  describe "the slots kept for configured peers" $ do+    it "lets others in while every configured peer is connected" $ do+      roomForOthers 3 [[1 :: Int], [2]] [1, 2] `shouldBe` True+      roomForOthers 3 [[1 :: Int], [2]] [1, 2, 9] `shouldBe` False+    it "keeps a slot for each configured peer that has no connection" $ do+      roomForOthers 3 [[1 :: Int], [2]] [1] `shouldBe` True+      roomForOthers 3 [[1 :: Int], [2]] [1, 9] `shouldBe` False+      roomForOthers 3 [[1 :: Int], [2]] [9] `shouldBe` False+      roomForOthers 2 [[1 :: Int], [2]] [] `shouldBe` False+    it "takes a name with two addresses for one peer" $ do+      roomForOthers 2 [[1 :: Int, 2]] [2] `shouldBe` True+      roomForOthers 2 [[1 :: Int, 2]] [9] `shouldBe` False+    it "keeps a slot for a name that resolved to nothing" $+      roomForOthers 2 [[] :: [Int]] [9] `shouldBe` False+    it "never lets the others and the configured peers that are away fill more than there is" $+      property $ \(most :: Int) (names :: [[Int]]) (open :: [Int]) ->+        let away = length [() | n <- names, not (any (`elem` open) n)]+         in roomForOthers most names open == (length open + away < most)    it "keeps a bounded number of discovered addresses" $ do     let b = book [1 .. maxDiscovered + 10]
test/unit/Haskoin/Node/PeerMgr/LifecycleSpec.hs view
@@ -23,7 +23,7 @@  -- | A ten second timeout and a hundred second maximum life. limits :: Limits-limits = Limits {timeout = 10, maxLife = 100}+limits = Limits {timeout = 10, maxLife = Just 100}  -- | Feed inputs to a new connection, collecting the actions. run :: [PeerInput] -> (PeerState, [PeerAction])@@ -37,7 +37,7 @@  -- | A connection that completed the handshake. online :: [PeerInput]-online = [GotHandshake (GotVersion version), GotHandshake GotVerAck]+online = [GotHandshake t0 (GotVersion version), GotHandshake t0 GotVerAck]  -- | A random input. newtype Input = Input PeerInput@@ -48,8 +48,8 @@     Input       <$> oneof         [ Heard <$> time,-          GotHandshake <$> elements [GotVersion version, GotVerAck],-          Refused <$> elements [NotFullNode, NotWitnessNode, ConnectedToSelf],+          GotHandshake <$> time <*> elements [GotVersion version, GotVerAck],+          Refused <$> time <*> elements [NotFullNode, NotWitnessNode, ConnectedToSelf],           GotPong <$> time <*> nonce,           Tick <$> time <*> nonce         ]@@ -68,21 +68,21 @@       actions `shouldBe` [ReplyVerAck, Announce]      it "accepts the verack first" $-      snd (run [GotHandshake GotVerAck, GotHandshake (GotVersion version)])+      snd (run [GotHandshake t0 GotVerAck, GotHandshake t0 (GotVersion version)])         `shouldBe` [ReplyVerAck, Announce]      it "disconnects a peer that repeats a handshake message once online" $-      snd (run (online <> [GotHandshake GotVerAck]))+      snd (run (online <> [GotHandshake t0 GotVerAck]))         `shouldBe` [ReplyVerAck, Announce, Disconnect (Rejected DuplicateVerAck)]      it "disconnects a peer whose version was refused" $ do-      let (st, actions) = run [Refused ConnectedToSelf]+      let (st, actions) = run [Refused t0 ConnectedToSelf]       actions `shouldBe` [Disconnect (Rejected ConnectedToSelf)]-      st.stage `shouldBe` Disconnecting (Rejected ConnectedToSelf)+      st.stage `shouldBe` Disconnecting (Rejected ConnectedToSelf) t0      it "disconnects a peer that does not complete the handshake in time" $       -- chatter keeps the peer from being silent, but not from timing out-      snd (run [GotHandshake GotVerAck, Heard (at 9), Tick (at 11) 1])+      snd (run [GotHandshake t0 GotVerAck, Heard (at 9), Tick (at 11) 1])         `shouldBe` [Disconnect HandshakeTimeout]    describe "pings" $ do@@ -131,15 +131,57 @@       drop 2 (snd (run (online <> [Heard (at 100), Tick (at 100) 1])))         `shouldBe` [SendPing 1] +    it "never rotates a peer that has no longest life, as a configured one" $ do+      let kept = limits {maxLife = Nothing}+          go (st, acc) i = let (st', as) = stepPeer kept i st in (st', acc <> as)+          actions = snd (foldl' go (newPeerState t0, []) (online <> [Heard (at 100000), Tick (at 100001) 1]))+      drop 2 actions `shouldBe` [SendPing 1]+     it "rotates before checking anything else" $       snd (run [Tick (at 101) 1]) `shouldBe` [Disconnect TooOld] +  describe "disconnection" $ do+    it "waits a timeout for the peer process to stop" $+      snd (run [Refused (at 1) NotFullNode, Tick (at 5) 1, Tick (at 11) 2])+        `shouldBe` [Disconnect (Rejected NotFullNode)]++    it "aborts a peer process that has not stopped a timeout after it was told to" $ do+      -- a peer that stopped reading leaves its writer blocked, and the+      -- process never sees that it was told to disconnect+      let (st, actions) = run [Refused (at 1) NotFullNode, Tick (at 12) 2]+      actions `shouldBe` [Disconnect (Rejected NotFullNode), Abort (Rejected NotFullNode)]+      st.stage `shouldBe` Disconnecting (Rejected NotFullNode) (at 12)++    it "aborts again after each further timeout" $+      drop 1 (snd (run [Refused (at 1) NotFullNode, Tick (at 12) 2, Tick (at 20) 3, Tick (at 23) 4]))+        `shouldBe` [Abort (Rejected NotFullNode), Abort (Rejected NotFullNode)]++    it "stamps a disconnection by the clock with the time of the tick" $+      fst (run (online <> [Tick (at 11) 1])) `shouldSatisfy` \st ->+        st.stage == Disconnecting Silent (at 11)+   describe "properties" $ do-    prop "ignores everything once disconnecting" $ \(ins :: [Input]) ->+    prop "only aborts once disconnecting" $ \(ins :: [Input]) ->       let inputs = [i | Input i <- ins]-       in let (st, _) = run [Refused NotFullNode]-           in snd (feed st inputs) === []+       in let (st, _) = run [Refused t0 NotFullNode]+           in all (== Abort (Rejected NotFullNode)) (snd (feed st inputs)) +    prop "aborts a disconnection that has not ended a timeout after it began" $ \(ins :: [Input]) ->+      let inputs = [i | Input i <- ins]+       in case (run inputs) of+            (st@PeerState {stage = Disconnecting r began}, _) ->+              snd (stepPeer limits (Tick (11 `addUTCTime` began) 1) st) === [Abort r]+            _ -> property True++    prop "aborts only after telling the peer to disconnect, for the same reason" $ \(ins :: [Input]) ->+      let inputs = [i | Input i <- ins]+          ok told = \case+            [] -> True+            Disconnect r : rest -> ok (Just r) rest+            Abort r : rest -> told == Just r && ok told rest+            _ : rest -> ok told rest+       in ok Nothing (snd (run inputs))+     prop "announces a peer at most once, and remembers it" $ \(ins :: [Input]) ->       let inputs = [i | Input i <- ins]        in let (st, actions) = run inputs@@ -157,6 +199,6 @@       let inputs = [i | Input i <- ins]        in let (st, _) = run inputs               disconnecting = case st.stage of-                Disconnecting _ -> True+                Disconnecting _ _ -> True                 _ -> False            in isOnline st === (st.announced && not disconnecting)
test/unit/Haskoin/Node/PeerMgrSpec.hs view
@@ -5,7 +5,6 @@ import Control.Concurrent.MVar import Control.Concurrent.STM import Control.Monad (forever, void, when)-import Data.Time.Clock (diffUTCTime, getCurrentTime) import Haskoin import Haskoin.Node import Haskoin.Node.Test@@ -27,7 +26,9 @@       connect _ g = do         n <- atomically $ stateTVar attempts (\n -> (n + 1, n + 1))         memoryConnection net (script n) g-  withTestNode net ["127.0.0.1:1"] connect modify f+  -- the remote lives in memory; its name is a Unix socket, so that no+  -- address or port of the machine is named+  withTestNode net ["unix:scripted-peer"] connect modify f  -- | Remote that sends the version and then runs the handler on each -- message.@@ -49,24 +50,8 @@ spec :: Spec spec = do   let net = bchRegTest-  t0 <- runIO $ subtract 3000 <$> nowTimestamp-  let main = mkBlocks net 0 net.genesisHeader t0 2500    describe "node handshake" $ do-    it "connects to a full node" $ do-      blocks <- newTVarIO []-      withScriptedNode net id (const (honestRemote blocks)) $ \t -> do-        p <- waitForPeer t-        Just o <- getOnlinePeer t.node.peerMgr p-        fmap (.version) o.version `shouldBe` Just (fromIntegral myVersion)-        o.online `shouldBe` True-        map (.mailbox) <$> getPeers t.node.peerMgr `shouldReturn` [p]--    it "rejects a peer that is not a full node" $ do-      v <- remoteVersion net 0 =<< randomIO-      withScriptedNode net id (\_ -> handshakeThen v (const (return ()))) $-        noPeerConnectedWithin 2-     it "rejects a connection to itself" $ do       -- reply with the nonce from our own version message       let script _ r =@@ -112,123 +97,3 @@         r <- within 10 "connection" (readMVar remotes)         eventually 10 "connection closed" (readTVarIO r.closed)         noPeerConnectedWithin 0.5 t--    it "waits before retrying a peer that failed" $ do-      times <- newTVarIO []-      let script _ _ = getCurrentTime >>= \now -> atomically (modifyTVar' times (now :))-      withScriptedNode net id script $ \_ -> do-        eventually 20 "two attempts" $ (>= 2) . length <$> readTVarIO times-        -- the first failure waits two seconds; the connect loop alone could-        -- retry within a tenth of a second-        oldestFirst <- reverse <$> readTVarIO times-        case oldestFirst of-          first : second : _ ->-            (second `diffUTCTime` first) `shouldSatisfy` (>= 1.9)-          _ -> expectationFailure "fewer than two attempts"--  describe "node peer maintenance" $ do-    it "answers pings" $ do-      blocks <- newTVarIO []-      pongs <- newEmptyMVar-      let script _ r = do-            v <- remoteVersion net nodeNetwork =<< randomIO-            remoteSend r (MVersion v)-            remoteSend r (MPing (Ping 1234))-            let go =-                  remoteReceive r >>= \case-                    Nothing -> return ()-                    Just (MPong (Pong n)) -> putMVar pongs n >> go-                    Just m -> respondHonestly r blocks m >> go-            go-      withScriptedNode net id script $ \_ ->-        within 10 "pong" (takeMVar pongs) `shouldReturn` 1234--    it "disconnects a peer that stops responding" $ do-      v <- remoteVersion net nodeNetwork =<< randomIO-      let react r = \case-            MVersion _ -> remoteSend r MVerAck-            _ -> return () -- never answers pings-          script _ r = handshakeThen v (react r) r-      withScriptedNode net (setTimeout 2) script $ \t -> do-        p <- waitForPeer t-        waitForDisconnect t p--    it "disconnects a peer that has been connected for too long" $ do-      blocks <- newTVarIO []-      withScriptedNode-        net-        (setMaxPeerLife 1 . setTimeout 2)-        (const (honestRemote blocks))-        $ \t -> do-          p <- waitForPeer t-          waitForDisconnect t p--    it "reconnects after a peer disconnects" $ do-      blocks <- newTVarIO []-      let script n r-            | n == 1 = do-                v <- remoteVersion net nodeNetwork =<< randomIO-                remoteSend r (MVersion v)-                Just (MVersion _) <- remoteReceive r-                remoteSend r MVerAck-                Just MVerAck <- remoteReceive r-                -- The chain asks for headers once the peer is announced, so-                -- closing after that request cannot beat the announcement.-                remoteReceiveMatch 10 "header request" r $ \case-                  MGetHeaders _ -> Just ()-                  _ -> Nothing-                return () -- close the connection-            | otherwise = honestRemote blocks r-      withScriptedNode net id script $ \t -> do-        p1 <- waitForPeer t-        waitForDisconnect t p1-        p2 <- waitForPeer t-        p2 `shouldNotBe` p1--  describe "node header sync" $ do-    it "syncs headers from a peer" $ do-      blocks <- newTVarIO main-      withScriptedNode net id (const (honestRemote blocks)) $ \t -> do-        bn <- receiveWithin 30 "synced" t.events $ \case-          ChainEvent (ChainSynced bn) -> Just bn-          _ -> Nothing-        headerHash bn.header `shouldBe` headerHash (last main).header--    it "follows blocks announced by inventory" $ do-      blocks <- newTVarIO (take 10 main)-      remotes <- newEmptyMVar-      let script _ r = putMVar remotes r >> honestRemote blocks r-      withScriptedNode net id script $ \t -> do-        r <- within 10 "remote" (readMVar remotes)-        _ <- waitForBest 30 t ((== 10) . (.height))-        atomically $ writeTVar blocks (take 109 main)-        let tip = headerHash (main !! 108).header-        remoteSend r (MInv (Inv [InvVector InvBlock tip.get]))-        void $ waitForBest 30 t ((== 109) . (.height))--    it "follows blocks announced by headers that do not connect" $ do-      blocks <- newTVarIO (take 10 main)-      remotes <- newEmptyMVar-      let script _ r = putMVar remotes r >> honestRemote blocks r-      withScriptedNode net id script $ \t -> do-        r <- within 10 "remote" (readMVar remotes)-        p <- waitForPeer t-        _ <- waitForBest 30 t ((== 10) . (.height))-        atomically $ writeTVar blocks (take 60 main)-        remoteSend r (headersMessage [(main !! 59).header])-        _ <- waitForBest 30 t ((== 60) . (.height))-        expectNothingWithin 0.5 "disconnection" t.events $ \case-          PeerEvent (PeerDisconnected p') | p == p' -> Just ()-          _ -> Nothing--    it "downloads blocks from a peer" $ do-      blocks <- newTVarIO main-      withScriptedNode net id (const (honestRemote blocks)) $ \t -> do-        p <- waitForPeer t-        let want = take 3 (drop 100 main)-        getBlocks net 10 p (map (headerHash . (.header)) want)-          `shouldReturn` Just want-        let unknown = case mkBlocks net 7 net.genesisHeader t0 1 of-              b : _ -> headerHash b.header-              [] -> error "no block"-        getBlocks net 10 p [unknown] `shouldReturn` Nothing
test/unit/Haskoin/Node/PeerSpec.hs view
@@ -1,13 +1,13 @@ -- | Peer process talking to a scripted remote over an in-memory connection. module Haskoin.Node.PeerSpec (spec) where -import Conduit (sinkNull, yieldMany)+import Conduit (await, sinkNull, yieldMany) import Control.Concurrent (threadDelay) import Control.Concurrent.Async import Control.Concurrent.MVar import Control.Concurrent.STM import Control.Exception (evaluate, fromException)-import Control.Monad (forM_, forever)+import Control.Monad (forM_, forever, when) import Control.Monad.IO.Class (liftIO) import Data.ByteString qualified as B import Data.Int (Int64)@@ -15,7 +15,6 @@ import Data.Word (Word32) import Haskoin import Haskoin.Node-import Haskoin.Node.Peer.Lock (Lock (..)) import Haskoin.Node.Test import NQE import System.Mem (getAllocationCounter)@@ -57,8 +56,6 @@     withPublisher $ \pub ->       withSubscription pub $ \events -> do         (inbox, mailbox) <- newMailbox-        busy <- newTVarIO Free-        pending <- newTVarIO 0         let cfg =               PeerConfig                 { pub = pub,@@ -66,9 +63,11 @@                   label = "remote",                   connect = memoryConnection net script,                   logger = logger,-                  lookupBlock = lookup_block+                  lookupBlock = lookup_block,+                  bestBlock = return (genesisNode net),+                  remote = testRemote net                 }-            p = wrapPeer cfg busy pending mailbox+        p <- newPeer cfg mailbox         withAsync (peer cfg p inbox) $ \thread -> do           remote <- within 5 "connection" (readMVar rv)           f PeerTest {peer = p, events, remote, thread}@@ -126,8 +125,6 @@         liftIO (forever (threadDelay maxBound))   withTestLogger $ \logger -> withPublisher $ \pub -> do     (inbox, mailbox) <- newMailbox-    busy <- newTVarIO Free-    pending <- newTVarIO 0     let cfg =           PeerConfig             { pub = pub,@@ -135,9 +132,12 @@               label = "remote",               connect = \f -> f (Conduits src sinkNull),               logger = logger,-              lookupBlock = \_ -> return Nothing+              lookupBlock = \_ -> return Nothing,+              bestBlock = return (genesisNode btc),+              remote = testRemote btc             }-    withAsync (peer cfg (wrapPeer cfg busy pending mailbox) inbox) $ \_ -> do+    p <- newPeer cfg mailbox+    withAsync (peer cfg p inbox) $ \_ -> do       counter0 <- within 30 "first piece" (readMVar start)       counter1 <- within 30 "message read" (readMVar end)       -- the counter goes down as the thread allocates@@ -333,6 +333,35 @@       expectStopped t       eventually 5 "connection closed" (readTVarIO t.remote.closed) +    it "disconnects when told to while blocked writing to a peer that stopped reading" $+      withTestLogger $ \logger -> withPublisher $ \pub -> do+        (inbox, mailbox) <- newMailbox+        writing <- newEmptyMVar+        let stuck = do+              -- the first write never returns, as on a full socket+              _ <- await+              liftIO (putMVar writing () >> forever (threadDelay maxBound))+            silent = liftIO (forever (threadDelay maxBound))+            cfg =+              PeerConfig+                { pub = pub,+                  net = net,+                  label = "remote",+                  connect = \f -> f (Conduits silent stuck),+                  logger = logger,+                  lookupBlock = \_ -> return Nothing,+                  bestBlock = return (genesisNode net),+                  remote = testRemote net+                }+        p <- newPeer cfg mailbox+        withAsync (peer cfg p inbox) $ \thread -> do+          MPing (Ping 1) `sendMessage` p+          within 5 "writer to block" (readMVar writing)+          killPeer p+          within 5 "peer process to stop" (waitCatch thread) >>= \case+            Right () -> return ()+            Left e -> assertFailure ("Unexpected error: " <> show e)+   describe "peer data requests" $ do     let serve :: PeerTest -> (Message -> [Message]) -> IO a -> IO a         serve t f =@@ -344,41 +373,65 @@             Just m -> mapM_ (remoteSend t.remote) (f m) >> remote_loop t f         pong (MPing (Ping n)) = [MPong (Pong n)]         pong _ = []-        honest = \case-          MGetData (GetData ivs) ->-            [MBlock b | iv <- ivs, b <- blocks, block_iv b == iv]-          m -> pong m -    it "downloads blocks" $ withPeerTest net $ \t -> serve t honest $ do-      r <- getBlocks net 5 t.peer (map bhash (take 3 blocks))-      r `shouldBe` Just (take 3 blocks)+    it "gives nothing at once when the peer disconnects during a request" $+      -- the remote never answers+      withPeerTest net $ \t ->+        withAsync (getBlocks net 30 t.peer [bhash b0]) $ \request -> do+          _ <- remoteReceiveMatch 5 "request" t.remote $ \case+            MGetData _ -> Just ()+            _ -> Nothing+          publish (PeerDisconnected t.peer) t.peer.pub+          within 5 "request to end" (wait request) `shouldReturn` Nothing -    it "ignores unrelated messages while downloading" $+    it "gives nothing at once for a ping when the peer disconnects" $+      withPeerTest net $ \t ->+        withAsync (pingPeer 30 t.peer) $ \ping -> do+          _ <- remoteReceiveMatch 5 "ping" t.remote $ \case+            MPing _ -> Just ()+            _ -> Nothing+          publish (PeerDisconnected t.peer) t.peer.pub+          within 5 "ping to end" (wait ping) `shouldReturn` False++    it "gives nothing at once for a request to a peer that was told to disconnect" $       withPeerTest net $ \t -> do-        let noisy = \case-              MGetData (GetData ivs) ->-                concat-                  [ [MBlock b, MPing (Ping 5), MInv (Inv [block_iv b])]-                  | iv <- ivs,-                    b <- blocks,-                    block_iv b == iv-                  ]-              m -> pong m-        serve t noisy $ do-          r <- getBlocks net 5 t.peer (map bhash (take 3 blocks))-          r `shouldBe` Just (take 3 blocks)+        killPeer t.peer+        within 5 "request to end" (getBlocks net 30 t.peer [bhash b0]) `shouldReturn` Nothing -    it "fails when a requested block is not found" $+    it "runs overlapping requests on one peer without mixing their answers" $       withPeerTest net $ \t -> do+        -- answered in turn, the second request would see the block of the+        -- first one ahead of its own first block, and fail         let f = \case-              MGetData (GetData (iv : _)) -> [MNotFound (NotFound [iv])]+              MGetData (GetData ivs) -> [MBlock b | iv <- ivs, b <- blocks, block_iv b == iv]               m -> pong m         serve t f $-          getBlocks net 5 t.peer [bhash b0] `shouldReturn` Nothing+          withAsync (getBlocks net 10 t.peer [bhash (blocks !! 1)]) $ \first ->+            withAsync (getBlocks net 10 t.peer [bhash b0, bhash (blocks !! 1)]) $ \second -> do+              within 15 "first request" (wait first) `shouldReturn` Just [blocks !! 1]+              within 15 "second request" (wait second) `shouldReturn` Just [b0, blocks !! 1] -    it "times out when the peer does not answer" $-      withPeerTest net $ \t ->-        getBlocks net 1 t.peer [bhash b0] `shouldReturn` Nothing+    it "ignores the late answers of a request that timed out" $+      withPeerTest net $ \t -> do+        -- the first request times out before the peer answers it; the+        -- answers come then, ahead of those of the second request, which+        -- asks for the same blocks in another order+        slow <- newMVar True+        let answer m = do+              late <- modifyMVar slow (\x -> return (False, x))+              case m of+                MGetData (GetData ivs) -> do+                  when late (threadDelay 1500000)+                  return [MBlock b | iv <- ivs, b <- blocks, block_iv b == iv]+                _ -> return (pong m)+            loop =+              remoteReceive t.remote >>= \case+                Nothing -> return ()+                Just m -> answer m >>= mapM_ (remoteSend t.remote) >> loop+        withAsync loop $ \_ -> do+          getBlocks net 1 t.peer [bhash b0, bhash (blocks !! 1)] `shouldReturn` Nothing+          getBlocks net 10 t.peer [bhash (blocks !! 1), bhash b0]+            `shouldReturn` Just [blocks !! 1, b0]      it "gives nothing and drops a peer whose block does not match its header" $       withPeerTest net $ \t -> do@@ -391,15 +444,6 @@           MutatedBlock h BadMerkleRoot -> h == bhash b0           _ -> False -    it "returns a SegWit block that Bitcoin Core mined, with its witness" $-      withPeerTestKnowing net [(parent302, 301)] $ \t -> do-        let f = \case-              MGetData _ -> [MBlock coreSegWitBlock]-              m -> pong m-        serve t f $-          getBlocks net 5 t.peer [bhash coreSegWitBlock]-            `shouldReturn` Just [coreSegWitBlock]-     it "gives nothing and drops a peer that stripped the witness of a SegWit block" $       withPeerTestKnowing net [(parent302, 301)] $ \t -> do         let f = \case@@ -432,20 +476,3 @@         serve t f $           getBlocks net 5 t.peer [bhash coreSegWitBlock]             `shouldReturn` Just [stripped coreSegWitBlock]--    it "downloads transactions" $ withPeerTest net $ \t -> do-      let txs = concatMap (.txs) blocks-          tx_iv tx = InvVector InvWitnessTx (txHash tx).get-          f = \case-            MGetData (GetData ivs) ->-              [MTx tx | iv <- ivs, tx <- txs, tx_iv tx == iv]-            m -> pong m-      serve t f $-        getTxs net 5 t.peer (map txHash (take 2 txs))-          `shouldReturn` Just (take 2 txs)--    it "pings the peer" $ withPeerTest net $ \t -> do-      serve t pong $ pingPeer 5 t.peer `shouldReturn` True--    it "reports an unanswered ping" $ withPeerTest net $ \t ->-      pingPeer 1 t.peer `shouldReturn` False
+ test/unit/Haskoin/Node/RegtestSpec.hs view
@@ -0,0 +1,482 @@+-- | Test the library against Bitcoin Core and Bitcoin Cash Node in regtest+-- mode. Nodes run in Podman containers built from @test/regtest/Containerfile@,+-- through podman-test ("Regtest.Podman"), and the node under test reaches+-- them through Unix sockets, as the peers @unix:PATH@. The tests are+-- skipped when Podman cannot run, or when @HASKOIN_NODE_SKIP_REGTEST@ or+-- @PODMAN_TEST_SKIP@ is set.+--+-- They are part of the @spec@ suite, so that @stack test@ and @haskell-dev+-- test@ run every test. Each node implementation has two groups at the top+-- of the module, its chain and its one peer, which @haskell-dev@ (of+-- jprupp/tools) runs each in a process of its own, at the same time as the+-- others (@haskell-dev.toml@): each container is in a pod of its own with+-- its own sockets, so they never meet. The image is built by the first test+-- that needs it, once for every process of the machine.+--+-- These tests replace the mock peers that once stood in for an honest+-- node: what a node does, a real one shows. A peer that hangs is a node+-- stopped with @SIGSTOP@ ('freezeNode'). The tests of peers that break the+-- rules, which no real node does, keep their scripted peers in memory.+module Haskoin.Node.RegtestSpec (spec) where++import Control.Concurrent (threadDelay)+import Control.Concurrent.STM (atomically, modifyTVar', newTVarIO, readTVarIO)+import Control.Exception (finally)+import Control.Monad (forM_, replicateM_, void, when)+import Data.ByteString.Char8 qualified as C8+import Data.List (intercalate, isInfixOf, isPrefixOf, tails)+import Data.Maybe (isJust, mapMaybe)+import Data.Serialize (encode)+import Data.Set qualified as Set+import Data.String (fromString)+import Data.Text qualified as T+import Data.Time.Clock (diffUTCTime, getCurrentTime)+import Haskoin+import Haskoin.Network.Protocol qualified as P+import Haskoin.Node+import Haskoin.Node qualified as NC (NodeConfig (..))+import Haskoin.Node.Peer.Remote (Facts (..), newRemote, predict)+import Haskoin.Node.Test+import Network.Socket (SockAddr (..))+import Regtest.Podman+import System.Environment (lookupEnv)+import Test.Hspec++spec :: Spec+spec = do+  skip <- runIO (isJust <$> lookupEnv "HASKOIN_NODE_SKIP_REGTEST")+  usable <- if skip then return (Left "HASKOIN_NODE_SKIP_REGTEST set") else runIO podmanUsable+  case usable of+    Left why -> skipped why+    Right () -> regtests+  where+    skipped why = describe "Regtest" $ it "runs the nodes in Podman" $ pendingWith why++-- | Node connected to the given nodes in the container. The timeout is long+-- so that the stall recovery poll does not hide announcement handling bugs.+withRegtestNode :: Container -> [Int] -> (TestNode -> IO a) -> IO a+withRegtestNode c is f = do+  addrs <- mapM (hostAddress c) is+  withTestNode+    (implNet c.impl)+    addrs+    withConnection+    (setTimeout 600)+    f++-- | Wait until our best header is the tip of node number @i@.+waitForTip :: Container -> Int -> TestNode -> IO BlockNode+waitForTip c i t = do+  tip <- fromString <$> cli c i ["getbestblockhash"]+  waitForBest 60 t ((== tip) . headerHash . (.header))++blockHashAt :: Container -> Int -> Int -> IO BlockHash+blockHashAt c i h = fromString <$> cli c i ["getblockhash", show h]++-- | Node 0 with blocks mined so that it leaves initial block download.+withMinedNode :: Impl -> Int -> (Container -> IO a) -> IO a+withMinedNode impl n f =+  withContainer impl $ \c -> do+    startNode c 0 []+    _ <- mine c 0 n+    f c++-- | The tests of each node implementation, two groups at the top of the+-- module.+regtests :: Spec+regtests = forM_ [BitcoinCore, BitcoinCashNode] $ \impl -> do+  describe (implName impl) (chainTests impl)+  describe (implName impl <> ", one peer") (peerTests impl)++-- | How the node under test follows the chain of the nodes.+chainTests :: Impl -> Spec+chainTests impl = do+  let net = implNet impl++  it "completes the handshake" $ withMinedNode impl 1 $ \c ->+    withRegtestNode c [0] $ \t -> do+      p <- waitForPeer t+      Just o <- getOnlinePeer t.node.peerMgr p+      Just v <- return o.version+      v.version `shouldSatisfy` (>= 70012)+      let VarString ua = v.userAgent+          expected = case impl of+            BitcoinCore -> "Satoshi"+            BitcoinCashNode -> "Bitcoin Cash Node"+      show ua `shouldSatisfy` (expected `isInfixOf`)++  it "syncs a chain longer than one header batch" $+    withMinedNode impl 2100 $ \c ->+      withRegtestNode c [0] $ \t -> do+        bn <- receiveWithin 120 "synced" t.events $ \case+          ChainEvent (ChainSynced bn) -> Just bn+          _ -> Nothing+        bn.height `shouldBe` 2100+        void $ waitForTip c 0 t++  it "follows blocks mined one at a time" $ withMinedNode impl 1 $ \c ->+    withRegtestNode c [0] $ \t -> do+      _ <- waitForTip c 0 t+      replicateM_ 5 $ mine c 0 1 >> waitForTip c 0 t++  it "follows bursts of blocks without stalling" $+    withMinedNode impl 1 $ \c ->+      withRegtestNode c [0] $ \t -> do+        _ <- waitForTip c 0 t+        replicateM_ 3 $ mine c 0 99 >> waitForTip c 0 t++  it "follows a burst longer than a header batch" $+    withMinedNode impl 1 $ \c ->+      withRegtestNode c [0] $ \t -> do+        _ <- waitForTip c 0 t+        _ <- mine c 0 2500+        bn <- waitForTip c 0 t+        bn.height `shouldBe` 2501++  it "follows a reorganization" $ withMinedNode impl 10 $ \c ->+    withRegtestNode c [0] $ \t -> do+      old <- waitForTip c 0 t+      h8 <- cli c 0 ["getblockhash", "8"]+      void $ cli c 0 ["invalidateblock", h8]+      _ <- mineTo c 0 5 otherAddress+      new <- waitForTip c 0 t+      new.height `shouldBe` 12+      chainBlockMain t.node.chain (headerHash old.header) `shouldReturn` False+      split <- chainGetSplitBlock t.node.chain old new+      split.height `shouldBe` 7++  it "follows a reorganization found in a burst" $+    withMinedNode impl 120 $ \c ->+      withRegtestNode c [0] $ \t -> do+        _ <- waitForTip c 0 t+        h <- cli c 0 ["getblockhash", "70"]+        void $ cli c 0 ["invalidateblock", h]+        _ <- mineTo c 0 99 otherAddress+        new <- waitForTip c 0 t+        new.height `shouldBe` 168++  it "downloads blocks" $ withMinedNode impl 5 $ \c ->+    withRegtestNode c [0] $ \t -> do+      p <- waitForPeer t+      _ <- waitForTip c 0 t+      hs <- mapM (blockHashAt c 0) [1 .. 5]+      Just bs <- getBlocks net 10 p hs+      map (headerHash . (.header)) bs `shouldBe` hs+      forM_ bs $ \b ->+        buildMerkleRoot (map txHash b.txs) `shouldBe` Right b.header.merkle+      let unknown = headerHash (mkHeaders net 9 net.genesisHeader 0 1 !! 0)+      getBlocks net 10 p [unknown] `shouldReturn` Nothing++  it "downloads announced transactions" $ withContainer impl $ \c -> do+    startNode c 0 []+    -- Bitcoin Cash Node also loads a default wallet, so name ours+    let wallet args = cli c 0 ("-rpcwallet=w" : args)+    void $ cli c 0 ["createwallet", "w"]+    addr <- wallet ["getnewaddress"]+    void $ mineTo c 0 101 addr+    withRegtestNode c [0] $ \t -> do+      p <- waitForPeer t+      _ <- waitForTip c 0 t+      txid <- fromString <$> wallet ["sendtoaddress", mineAddress, "1"]+      receiveWithin 60 "transaction announcement" t.events $ \case+        PeerEvent (PeerMessage p' (MInv (Inv ivs)))+          | p == p' && any ((== txid) . TxHash . (.invHash)) ivs -> Just ()+        _ -> Nothing+      Just [tx] <- getTxs net 10 p [txid]+      txHash tx `shouldBe` txid++  it "pings a peer" $ withMinedNode impl 1 $ \c ->+    withRegtestNode c [0] $ \t -> do+      p <- waitForPeer t+      pingPeer 10 p `shouldReturn` True++  it "reconnects to a restarted peer and catches up" $+    withMinedNode impl 5 $ \c ->+      withRegtestNode c [0] $ \t -> do+        p <- waitForPeer t+        _ <- waitForTip c 0 t+        stopNode c 0+        waitForDisconnect t p+        startNode c 0 []+        _ <- mine c 0 3+        _ <- waitForPeer t+        bn <- waitForTip c 0 t+        bn.height `shouldBe` 8++  it "keeps following the chain when a peer goes away" $+    withMinedNode impl 5 $ \c -> do+      startNode c 1 ["-addnode=" <> nodeAddress c 0]+      eventually 60 "nodes in sync" $+        (== "5") <$> cli c 1 ["getblockcount"]+      withRegtestNode c [0, 1] $ \t -> do+        _ <- waitForPeer t+        _ <- waitForPeer t+        _ <- waitForTip c 0 t+        stopNode c 0+        _ <- mine c 1 5+        bn <- waitForTip c 1 t+        bn.height `shouldBe` 10++  it "follows bursts announced by several peers" $+    withMinedNode impl 1 $ \c -> do+      startNode c 1 ["-addnode=" <> nodeAddress c 0]+      withRegtestNode c [0, 1] $ \t -> do+        _ <- waitForPeer t+        _ <- waitForPeer t+        _ <- waitForTip c 0 t+        replicateM_ 3 $ mine c 0 99 >> waitForTip c 0 t+        eventually 60 "nodes in sync" $+          (== "298") <$> cli c 1 ["getblockcount"]+        expectNothingWithin 1 "peer disconnection" t.events $ \case+          PeerEvent (PeerDisconnected _) -> Just ()+          _ -> Nothing++-- | The commands of the messages that the first peer sent, up to its+-- verack, as the node heard them.+handshakeHeard :: TestNode -> IO [MessageCommand]+handshakeHeard t = go []+  where+    go acc =+      receiveWithin 30 "the handshake of the peer" t.events Just >>= \case+        PeerEvent (PeerMessage _ m)+          | MVerAck <- m -> return (reverse (msgType m : acc))+          | otherwise -> go (msgType m : acc)+        _ -> go acc++-- | The commands up to the first verack.+upToVerAck :: [MessageCommand] -> [MessageCommand]+upToVerAck cmds = case break (== MCVerAck) cmds of+  (early, v : _) -> early <> [v]+  (early, []) -> early++isRefused :: Judgement -> Bool+isRefused = \case+  Refused _ _ -> True+  _ -> False++-- | The bytes of @getheaders@ messages that node 0 has had from its peers,+-- from what @getpeerinfo@ says it received. A count that does not grow+-- means no new request.+headerRequests :: Container -> IO Int+headerRequests c = do+  info <- cli c 0 ["getpeerinfo"]+  let received = drop 1 (splitOn "\"bytesrecv_per_msg\"" info)+      counts = [count r | r <- received]+  return (sum counts)+  where+    count section = case [rest | rest <- tails section, "\"getheaders\":" `isPrefixOf` rest] of+      rest : _ -> read (takeWhile (`elem` ['0' .. '9']) (dropWhile (== ' ') (drop 13 rest)))+      [] -> 0+    splitOn sep s = case breakOn sep s of+      (first, Just rest) -> first : splitOn sep rest+      (first, Nothing) -> [first]+    breakOn sep s = go "" s+      where+        go acc rest+          | sep `isPrefixOf` rest = (reverse acc, Just (drop (length sep) rest))+          | otherwise = case rest of+              x : xs -> go (x : acc) xs+              [] -> (reverse acc, Nothing)++-- | Outputs of 1000 satoshis to so many addresses, as @sendmany@ takes them:+-- a JSON object from address to amount. The addresses hash numbers that+-- differ from one transaction to the next, so no two are alike; nobody can+-- spend them, which a test does not need.+manyOutputs :: Network -> Int -> Int -> String+manyOutputs net k n =+  "{" <> intercalate "," [show (addressOf i) <> ":0.00001" | i <- [1 .. n]] <> "}"+  where+    addressOf i =+      maybe (error "No address") T.unpack $+        addrToText net (PubKeyAddress (ripemd160 (C8.pack (show (k, i)))))++-- | Mine one block on node 0, and give its hash.+lastMined :: Container -> IO String+lastMined c =+  mine c 0 1 >>= \case+    [h] -> return h+    hs -> fail ("Mined " <> show (length hs) <> " blocks, not one")++-- | How the node under test treats one peer, and how the model of the+-- peer agrees with it ("Haskoin.Node.Peer.Remote"). A group of its own,+-- so that it runs at the same time as the chain tests.+peerTests :: Impl -> Spec+peerTests impl = do+  let net = implNet impl++  -- The model of the node ("Haskoin.Node.Peer.Remote") is read from the+  -- upstream source; these tests check it against the node itself.+  it "hears the handshake that the model predicts" $ withMinedNode impl 1 $ \c ->+    withRegtestNode c [0] $ \t -> do+      heard <- handshakeHeard t+      let zero = NetworkAddress 0 (sockToHostAddress (SockAddrInet 0 0))+          ours = buildVersion net 0 0 zero zero 0+          facts = Facts {now = 0, best = genesisNode net, known = mempty}+          model = newRemote net Set.empty AddrIPv4 True 0 0+          predicted = mapMaybe sent (fst (predict facts (MVersion ours) model))+          sent e = case e.action of+            P.Send m -> Just (msgType m)+            _ -> Nothing+      heard `shouldBe` upToVerAck predicted++  it "asks for the mempool only where the node allows it" $+    withMinedNode impl 1 $ \c ->+      withRegtestNode c [0] $ \t -> do+        p <- waitForPeer t+        j <- judgeMessage p MMempool+        -- Bitcoin Core offers no Bloom filters by default, and closes the+        -- connection of a peer that asks for its mempool without them;+        -- Bitcoin Cash Node offers them+        case impl of+          BitcoinCore -> j `shouldSatisfy` isRefused+          BitcoinCashNode -> j `shouldBe` Allowed+        MMempool `sendMessage` p+        pingPeer 10 p `shouldReturn` True++  it "asks a node that whitelisted it for its mempool" $ withContainer impl $ \c -> do+    startNode c 0 ["-whitelist=mempool@0.0.0.0/0"]+    _ <- mine c 0 1+    addr <- hostAddress c 0+    let granted cfg = cfg {NC.permissions = Set.singleton PermMempool}+    withTestNode net [addr] withConnection (granted . setTimeout 600) $ \t -> do+      p <- waitForPeer t+      judgeMessage p MMempool `shouldReturn` Allowed+      MMempool `sendMessage` p+      pingPeer 10 p `shouldReturn` True++  it "downloads a block as the node keeps it, witness and all" $ withContainer impl $ \c -> do+    startNode c 0 []+    let wallet args = cli c 0 ("-rpcwallet=w" : args)+    void $ cli c 0 ["createwallet", "w"]+    -- on Bitcoin Core a new address of the wallet is a SegWit one, so the+    -- payment to it is spent with a witness later; here it is the input+    -- of the payment that has one, from a coinbase paid to such an address+    addr <- wallet ["getnewaddress"]+    void $ mineTo c 0 101 addr+    void $ wallet ["sendtoaddress", addr, "1"]+    h <- lastMined c+    raw <- cli c 0 ["getblock", h, "0"]+    withRegtestNode c [0] $ \t -> do+      p <- waitForPeer t+      _ <- waitForTip c 0 t+      Just [b] <- getBlocks net 10 p [fromString h]+      encodeHex (encode b) `shouldBe` T.strip (T.pack raw)+      length b.txs `shouldBe` 2+      when (impl == BitcoinCore) $+        any (any (not . null) . (.witness)) b.txs `shouldBe` True++  it "gives nothing for blocks or pings that a frozen peer leaves unanswered" $+    withMinedNode impl 1 $ \c ->+      withRegtestNode c [0] $ \t -> do+        p <- waitForPeer t+        _ <- waitForTip c 0 t+        h <- blockHashAt c 0 1+        freezeNode c 0+        flip finally (thawNode c 0) $ do+          getBlocks net 2 p [h] `shouldReturn` Nothing+          pingPeer 2 p `shouldReturn` False++  it "drops a peer that stops answering" $ withMinedNode impl 1 $ \c -> do+    addr <- hostAddress c 0+    withTestNode net [addr] withConnection (setTimeout 3) $ \t -> do+      p <- waitForPeer t+      freezeNode c 0+      waitForDisconnect t p `finally` thawNode c 0++  -- Rotation is for peers that nobody chose ("Haskoin.Node.PeerMgr"). This+  -- test once said that the peer was dropped after two seconds, and it was.+  it "keeps a configured peer past the longest life that it allows a connection" $+    withMinedNode impl 1 $ \c -> do+      addr <- hostAddress c 0+      withTestNode net [addr] withConnection (setMaxPeerLife 2 . setTimeout 4) $ \t -> do+        p <- waitForPeer t+        expectNothingWithin 8 "the disconnection of a configured peer" t.events $ \case+          PeerEvent (PeerDisconnected p') | p == p' -> Just ()+          _ -> Nothing++  it "answers the pings of the node" $ withMinedNode impl 1 $ \c ->+    withRegtestNode c [0] $ \t -> do+      _ <- waitForPeer t+      void $ cli c 0 ["ping"]+      -- the node shows the time of a ping only once it has its pong+      eventually 30 "the time of a ping of the node" $+        ("\"pingtime\"" `isInfixOf`) <$> cli c 0 ["getpeerinfo"]++  it "refuses a node that does not keep the whole chain" $ withContainer impl $ \c -> do+    -- a pruned node offers NODE_NETWORK_LIMITED and not NODE_NETWORK+    startNode c 0 ["-prune=550"]+    _ <- mine c 0 1+    addr <- hostAddress c 0+    attempts <- newTVarIO (0 :: Int)+    let counted sa g = atomically (modifyTVar' attempts (+ 1)) >> withConnection sa g+    withTestNode net [addr] counted (setTimeout 600) $ \t -> do+      eventually 30 "a connection" $ (>= 1) <$> readTVarIO attempts+      expectNothingWithin 5 "peer connection" t.events $ \case+        PeerEvent (PeerConnected _) -> Just ()+        _ -> Nothing++  it "waits before trying again a peer that failed" $ withContainer impl $ \c -> do+    -- node 0 is not started: its socket is there, and nothing answers+    -- behind it+    addr <- hostAddress c 0+    times <- newTVarIO []+    let timed sa g = do+          now <- getCurrentTime+          atomically (modifyTVar' times (now :))+          withConnection sa g+    withTestNode net [addr] timed id $ \_ -> do+      eventually 20 "two attempts" $ (>= 2) . length <$> readTVarIO times+      -- the first failure waits two seconds; the connect loop alone could+      -- try again within a tenth of a second+      newestFirst <- readTVarIO times+      case reverse newestFirst of+        first : second : _ -> (second `diffUTCTime` first) `shouldSatisfy` (>= 1.9)+        _ -> expectationFailure "fewer than two attempts"++  it "says the headers are synced only with the minimum chain work" $+    -- every regtest header has a work of 2: genesis and the block on top+    -- of it have 4+    withMinedNode impl 1 $ \c -> do+      addr <- hostAddress c 0+      forM_ [(4, True), (5, False)] $ \(least, synced) ->+        withTestNode net {minimumChainWork = least} [addr] withConnection (setTimeout 600) $ \t -> do+          _ <- waitForTip c 0 t+          chainSync t.node.chain+          chainIsSynced t.node.chain `shouldReturn` synced++  it "gives the parents of a block" $ withMinedNode impl 15 $ \c ->+    withRegtestNode c [0] $ \t -> do+      bn <- waitForTip c 0 t+      ps <- chainGetParents t.node.chain 12 bn+      hs <- mapM (blockHashAt c 0) [12, 13, 14]+      map (headerHash . (.header)) ps `shouldBe` hs++  it "stops asking for headers once it has them all" $ withMinedNode impl 5 $ \c ->+    withRegtestNode c [0] $ \t -> do+      _ <- waitForTip c 0 t+      threadDelay 1000000+      asked <- headerRequests c+      threadDelay 3000000+      headerRequests c `shouldReturn` asked++  when (impl == BitcoinCashNode) $+    it "downloads a block larger than 2 MiB" $+      withContainer impl $ \c -> do+        -- on Bitcoin Cash a block message may be up to twice the block size,+        -- while every other message is limited to 2 MiB (2097152 bytes)+        startNode c 0 []+        let wallet args = cli c 0 ("-rpcwallet=w" : args)+        void $ cli c 0 ["createwallet", "w"]+        addr <- wallet ["getnewaddress"]+        void $ mineTo c 0 140 addr+        -- 40 transactions of 1800 outputs each, about 61 kB each, under the+        -- largest standard transaction and the largest argument of a command+        forM_ [1 .. 40 :: Int] $ \k ->+          void $ wallet ["sendmany", "", manyOutputs net k 1800]+        h <- lastMined c+        withRegtestNode c [0] $ \t -> do+          p <- waitForPeer t+          _ <- waitForTip c 0 t+          Just [b] <- getBlocks net 30 p [fromString h]+          C8.length (encode b) `shouldSatisfy` (> 2097152)+          length b.txs `shouldBe` 41
+ test/unit/Haskoin/Node/RouterSpec.hs view
@@ -0,0 +1,208 @@+-- | The order in which the router passes on the events of each peer,+-- driven through arbitrary interleavings of the events of several peers.+module Haskoin.Node.RouterSpec (spec) where++import Data.List (nub, sort)+import Haskoin.Node.Router+import Test.Hspec+import Test.Hspec.QuickCheck (prop)+import Test.QuickCheck hiding (Discard)++-- | A peer, and a message, numbered in the order it arrived.+type Key = Int++type Msg = Int++-- | What happens to one peer, in its own order.+data Ev+  = -- | the peer sends a message+    Msg+  | -- | the peer manager completed the handshake and announced the peer+    Done+  | -- | the announcement comes through the queue+    Conn+  | -- | the announcement of its disconnection comes through the queue+    Disc+  deriving stock (Eq, Show)++-- | What may happen to a peer, in an order that the node allows: messages+-- before the handshake, the end of the handshake, more messages, the+-- announcement, more messages, the disconnection. Any part may be missing,+-- as when a peer dies in its handshake, or the router does not hear from the+-- peer manager that the handshake completed because the peer was already+-- gone.+script :: Gen [Ev]+script = do+  early <- msgs+  done <- arbitrary+  held <- msgs+  late <- msgs+  stage <- chooseInt (0, 2)+  let afterDone = held <> [Conn | stage >= 1] <> (if stage >= 1 then late else []) <> [Disc | stage == 2]+  return (early <> [Done | done] <> afterDone)+  where+    msgs = do+      n <- chooseInt (0, 20)+      return (replicate n Msg)++-- | Merge the scripts of several peers in a random order that keeps the+-- order of each.+interleave :: [[a]] -> Gen [a]+interleave xss = case filter (not . null) xss of+  [] -> return []+  live -> do+    i <- chooseInt (0, length live - 1)+    let (front, chosen, back) = (take i live, live !! i, drop (i + 1) live)+    case chosen of+      x : rest -> (x :) <$> interleave (front <> [rest] <> back)+      [] -> interleave (front <> back)++-- | Number the messages and make inputs.+inputs :: [(Key, Ev)] -> [RouterInput Key Msg]+inputs = go 0+  where+    go _ [] = []+    go n ((k, e) : rest) = case e of+      Msg -> Arrived k n : go (n + 1) rest+      Done -> HandshakeDone k : go n rest+      Conn -> Connected k : go n rest+      Disc -> Disconnected k : go n rest++-- | The events of three peers, in an order the node allows.+newtype Allowed = Allowed [RouterInput Key Msg]+  deriving stock (Show)++instance Arbitrary Allowed where+  arbitrary = do+    scripts <- vectorOf 3 script+    Allowed . inputs <$> interleave [map (k,) s | (k, s) <- zip [1 ..] scripts]++-- | Any events at all of two peers, including orders the node rules out.+newtype Any = Any [RouterInput Key Msg]+  deriving stock (Show)++instance Arbitrary Any where+  arbitrary = do+    evs <- listOf ((,) <$> chooseInt (1, 2) <*> elements [Msg, Msg, Msg, Done, Conn, Disc])+    return (Any (inputs evs))++-- | Run the router, giving its last state and every action.+run :: [RouterInput Key Msg] -> (Router Key Msg, [RouterAction Key Msg])+run = foldl' go (newRouter, [])+  where+    go (r, acc) i = let (r', as) = stepRouter i r in (r', acc <> as)++keyOf :: RouterAction Key Msg -> Key+keyOf = \case+  Early k _ -> k+  Deliver k _ -> k+  Discard k _ -> k+  Announce k -> k+  Retire k -> k++-- | The message that an action disposes of, if any.+disposed :: RouterAction Key Msg -> Maybe Msg+disposed = \case+  Early _ m -> Just m+  Deliver _ m -> Just m+  Discard _ m -> Just m+  _ -> Nothing++delivered :: RouterAction Key Msg -> Maybe Msg+delivered = \case+  Deliver _ m -> Just m+  _ -> Nothing++arrived :: [RouterInput Key Msg] -> [Msg]+arrived is = [m | Arrived _ m <- is]++-- | Messages held at the end.+heldAtEnd :: Router Key Msg -> [Msg]+heldAtEnd r = concat [toList' q | k <- [1 .. 3], Just (Awaiting q) <- [routeOf k r]]+  where+    toList' = foldr (:) []++-- | No message of a peer is delivered unless the peer was announced since it+-- was last retired.+deliversOnlyAnnounced :: [RouterAction Key Msg] -> Bool+deliversOnlyAnnounced = go []+  where+    go _ [] = True+    go live (a : rest) = case a of+      Announce k -> go (k : live) rest+      Retire k -> k `elem` live && go (filter (/= k) live) rest+      Deliver k _ -> k `elem` live && go live rest+      _ -> go live rest++spec :: Spec+spec = describe "router" $ do+  it "handles the messages of a peer before its handshake at once" $+    snd (run [Arrived 1 0, Arrived 1 1]) `shouldBe` [Early 1 0, Early (1 :: Key) (1 :: Msg)]++  it "holds the messages that come between the handshake and the announcement" $ do+    let (r, actions) = run [HandshakeDone 1, Arrived 1 0, Arrived 1 1]+    actions `shouldBe` []+    heldAtEnd r `shouldBe` [0, 1]++  it "passes on the announcement, then the held messages in order" $+    snd (run [HandshakeDone 1, Arrived 1 0, Arrived 1 1, Connected 1, Arrived 1 2])+      `shouldBe` [Announce 1, Deliver 1 0, Deliver 1 1, Deliver 1 2]++  it "passes on the disconnection after every message" $+    snd (run [Connected 1, Arrived 1 0, Disconnected 1])+      `shouldBe` [Announce 1, Deliver 1 0, Retire 1]++  it "forgets a peer once it is gone" $+    fst (run [HandshakeDone 1, Connected 1, Disconnected (1 :: Key)]) `shouldBe` (newRouter :: Router Key Msg)++  it "announces a peer whose handshake it did not see end" $+    snd (run [Arrived 1 0, Connected 1, Arrived 1 1])+      `shouldBe` [Early 1 0, Announce 1, Deliver (1 :: Key) (1 :: Msg)]++  it "keeps peers apart" $+    snd (run [HandshakeDone 1, Arrived 1 0, Arrived 2 1, Connected 1])+      `shouldBe` [Early 2 1, Announce 1, Deliver (1 :: Key) (0 :: Msg)]++  describe "in any order that the node allows" $ do+    prop "announces a peer before any of its messages past the handshake, and retires it after" $+      \(Allowed is) ->+        let actions = snd (run is)+         in deliversOnlyAnnounced actions+              .&&. conjoin+                [ notElem (Announce k) (dropWhile (/= Retire k) actions)+                    .&&. all ((/= k) . keyOf) (drop 1 (dropWhile (/= Retire k) actions))+                | k <- [1 .. 3]+                ]++    prop "disposes of every message exactly once, or holds it" $+      \(Allowed is) ->+        let (r, actions) = run is+            done = [m | Just m <- map disposed actions]+         in sort (done <> heldAtEnd r) === arrived is+              .&&. length (nub done) === length done++    prop "delivers the messages of a peer in the order they came" $+      \(Allowed is) ->+        let actions = snd (run is)+         in conjoin+              [ let ms = [m | a <- actions, keyOf a == k, Just m <- [delivered a]]+                 in ms === sort ms+              | k <- [1 .. 3]+              ]++    prop "drops no message that comes after the handshake" $+      \(Allowed is) ->+        let actions = snd (run is)+            afterDone k = dropWhile (/= HandshakeDone k) is+            late k = [m | Arrived k' m <- afterDone k, k' == k]+            early = [m | Early _ m <- actions] <> [m | Discard _ m <- actions]+         in conjoin [all (`notElem` early) (late k) | k <- [1 .. 3]]++  describe "in any order at all" $ do+    prop "delivers nothing of a peer that is not announced" $+      \(Any is) -> deliversOnlyAnnounced (snd (run is))++    prop "disposes of no message twice" $+      \(Any is) ->+        let done = [m | Just m <- map disposed (snd (run is))]+         in length (nub done) === length done
test/unit/Haskoin/NodeSpec.hs view
@@ -15,7 +15,7 @@ import Control.Concurrent (threadDelay) import Control.Concurrent.Async import Control.Concurrent.STM-import Control.Monad (forM_, forever, replicateM)+import Control.Monad (forM_, forever) import Data.ByteString (ByteString) import Data.ByteString qualified as B import Data.ByteString.Base64 (decodeBase64Lenient)@@ -30,6 +30,7 @@ import Database.RocksDB qualified as R import Haskoin import Haskoin.Node+import Haskoin.Node.Address (peerHostAddress) import Haskoin.Node.Test (eventually) import NQE import Network.Socket (PortNumber, SockAddr (..), tupleToHostAddress, tupleToHostAddress6)@@ -72,8 +73,9 @@       setup = \_ -> return (),       timeout = 120,       discover = False,-      -- IPv4, so that the mock peer is reachable without IPv6-      staticPeers = ["127.0.0.1:17486"]+      -- a name for the mock peer, which lives in memory ('dummyPeerConnect'):+      -- a Unix socket, so that no address or port of the machine is named+      staticPeers = ["unix:mock-peer"]     }  -- | Connect to a mock peer that reacts to messages like this.@@ -97,7 +99,7 @@     go r s = do       nonce <- randomIO       now <- round <$> getPOSIXTime-      let rmt = NetworkAddress 0 (sockToHostAddress sa)+      let rmt = NetworkAddress 0 (peerHostAddress sa)           ver = buildVersion net nonce 0 ad rmt now       runPut (putMessage net (MVersion ver)) `send` s       runConduit $@@ -142,45 +144,6 @@ spec = do   let net = bchRegTest   describe "peer manager on test network" $ do-    it "connects to a peer" $-      withTestNode net "connect-one-peer" $ \TestNode {..} -> do-        p <- waitForPeer nodeEvents-        Just o <- getOnlinePeer testMgr p-        fmap (.version) o.version `shouldSatisfy` maybe False (>= 70002)-    it "downloads some blocks" $-      withTestNode net "get-blocks" $ \TestNode {..} -> do-        let h1 =-              "3094ed3592a06f3d8e099eed2d9c1192329944f5df4a48acb29e08f12cfbb660"-            h2 =-              "0c89955fc5c9f98ecc71954f167b938138c90c6a094c4737f2e901669d26763f"-        p <- waitForPeer nodeEvents-        pbs <- getBlocks net 10 p [h1, h2]-        (b1, b2) <- case pbs of-          Just [b1, b2] -> return (b1, b2)-          _ -> fail ("Expected two blocks, got " <> show pbs)-        headerHash b1.header `shouldBe` h1-        headerHash b2.header `shouldBe` h2-        let ths b = map txHash b.txs-            testMerkle b = buildMerkleRoot (ths b) `shouldBe` Right b.header.merkle-        testMerkle b1-        testMerkle b2-    it "downloads a block larger than 2 MiB" $ do-      -- On Bitcoin Cash a block message may be up to twice the block size,-      -- while every other message is limited to 2 MiB (2097152 bytes).-      let script = B.replicate 3000000 0x6a-          tx = Tx 1 [TxIn nullOutPoint B.empty maxBound] [TxOut 0 script] [] 0-          -- a header that commits to the transaction, or the node would-          -- refuse the block as not the one its header names-          root = either error id (buildMerkleRoot [txHash tx])-          big = case allBlocks of-            firstBlock : _ -> Block firstBlock.header {merkle = root} [tx]-            [] -> error "no test blocks"-      withTestNodeBlocks [big] net "big-block" $ \TestNode {..} -> do-        p <- waitForPeer nodeEvents-        pbs <- getBlocks net 10 p [headerHash big.header]-        let scriptSizes =-              [[B.length o.script | o <- t.outputs] | b <- concat pbs, t <- b.txs]-        scriptSizes `shouldBe` [[3000000]]     it "builds a version message with the given height and time" $ do       let local = NetworkAddress nodeNetwork (sockToHostAddress (SockAddrInet 0 0))           remote = NetworkAddress 0 (sockToHostAddress (SockAddrInet 8333 0x08080808))@@ -188,18 +151,30 @@       v.version `shouldBe` 70012       v.startHeight `shouldBe` 650000       v.timestamp `shouldBe` 1700000000+  describe "order of peer events" $ do+    it "publishes a peer as connected before the messages it sends right after its handshake" $ do+      -- the mock peer sends a burst right behind its verack, which used to+      -- reach the application ahead of the announcement of the peer+      let burst = [Right (MOther "zz" (B.singleton i)) | i <- [1 .. 12]]+          react = \case+            MVersion _ -> Right MVerAck : burst+            MPing (Ping n) -> [Right (MPong (Pong n))]+            _ -> []+          early = \case+            MVersion _ -> True+            MVerAck -> True+            _ -> False+      withTestNodeOpts (defOpts allBlocks) {react = react} net "burst-after-handshake" $+        \TestNode {..} -> do+          let next = receive nodeEvents >>= judgeEvent+              judgeEvent = \case+                PeerEvent (PeerConnected _) -> return Nothing+                PeerEvent (PeerMessage _ m) | not (early m) -> return (Just (msgType m))+                _ -> next+          timeout (10 * 1000 * 1000) next `shouldReturn` Just Nothing+          payloads <- timeout (10 * 1000 * 1000) . mapM (const (otherPayload nodeEvents)) $ burst+          payloads `shouldBe` Just [B.singleton i | i <- [1 .. 12]]   describe "untrusted peers" $ do-    it "imports a full batch of 2000 headers"-      $ withTestNodeOpts-        (defOpts allBlocks) {react = reactWhenOnline [Right (manyHeaders net 2000)]}-        net-        "full-batch"-      $ \TestNode {..} -> do-        bn <--          receiveMatch nodeEvents $ \case-            ChainEvent (ChainBestBlock bn) | bn.height > 0 -> Just bn-            _ -> Nothing-        bn.height `shouldBe` 2000     it "disconnects a peer that sends more than 2000 headers"       $ withTestNodeOpts         (defOpts allBlocks) {react = reactWhenOnline [Right (manyHeaders net 2001)]}@@ -373,74 +348,6 @@       withTestNodeOpts (defOpts allBlocks) {setup = setup} net "purge-cf" $         \TestNode {..} -> do           R.get testDB k `shouldReturn` Just "keep"-  describe "chain on test network" $ do-    it "stops asking a peer that has no more headers" $-      -- The peer answers getheaders with an empty headers message, as a-      -- peer does when the node already has its whole chain. The node must-      -- take that as the end of the sync instead of asking again.-      withTestNodeBlocks [] net "no-headers" $ \TestNode {..} -> do-        _ <- waitForPeer nodeEvents-        atomically $ readTVar getHeadersCount >>= check . (>= 1)-        threadDelay (1000 * 1000)-        readTVarIO getHeadersCount `shouldReturn` 1-    it "reports the headers as synced when the best header has the minimum chain work" $ do-      -- Every regtest header has a work of 2. Genesis and one header on top-      -- of it have 2 + 2 = 4, which is the minimum here.-      fresh <- freshHeader net-      let net4 = net {minimumChainWork = 4}-      withTestNodeBlocks [Block fresh []] net4 "min-work-reached" $-        \TestNode {..} -> do-          receiveMatch nodeEvents $ \case-            ChainEvent (ChainBestBlock bn) | bn.height == 1 -> Just ()-            _ -> Nothing-          chainSync testChain-          chainIsSynced testChain `shouldReturn` True-    it "does not report the headers as synced below the minimum chain work" $ do-      -- Same chain with a work of 2 + 2 = 4, one short of a minimum of 5.-      fresh <- freshHeader net-      let net5 = net {minimumChainWork = 5}-      withTestNodeBlocks [Block fresh []] net5 "min-work-missing" $-        \TestNode {..} -> do-          receiveMatch nodeEvents $ \case-            ChainEvent (ChainBestBlock bn) | bn.height == 1 -> Just ()-            _ -> Nothing-          chainSync testChain-          chainIsSynced testChain `shouldReturn` False-    it "syncs some headers" $-      withTestNode net "connect-sync" $ \TestNode {..} -> do-        let bh =-              "3bfa0c6da615fc45aa44ddea6854ac19d16f3ca167e0e21ac2cc262a49c9b002"-            ah =-              "7dc835a78a55fa76f9184dc4f6663a73e418c7afec789c5ae25e432fd7fc8467"-        bn <--          receiveMatch nodeEvents $ \case-            ChainEvent (ChainBestBlock bn)-              | bn.height > 0 -> Just bn-            _ -> Nothing-        bb <- chainGetBest testChain-        bb.height `shouldSatisfy` (== 15)-        an <--          maybe (error "No ancestor found") return-            =<< chainGetAncestor testChain 10 bn-        headerHash bn.header `shouldBe` bh-        headerHash an.header `shouldBe` ah-    it "downloads some block parents" $-      withTestNode net "parents" $ \TestNode {..} -> do-        let hs =-              [ "52e886df7b166d961ac2d3d2d561d806325d51a609dc0a5d9d5fcb65d47906d7",-                "2537a081b9e2b24d217fac2886f387758cb3aa4e4956b3be7ed229bafbb71b0f",-                "7c72f306215a296f9714320a497b1f2cb5f9b99f162d7e04333c243fac9a54d8"-              ]-        [_, bn] <--          replicateM 2 $-            receiveMatch nodeEvents $ \case-              ChainEvent (ChainBestBlock bn) -> Just bn-              _ -> Nothing-        bn.height `shouldBe` 15-        ps <- chainGetParents testChain 12 bn-        length ps `shouldBe` 3-        forM_ (zip ps hs) $ \(p, h) ->-          headerHash p.header `shouldBe` h  -- | An IPv4 socket address. v4At :: (Word8, Word8, Word8, Word8) -> PortNumber -> SockAddr@@ -482,18 +389,12 @@   MHeaders . Headers $     map (,VarInt 0) (appendBlocks net 0 net.genesisHeader n) --- | Valid header on top of genesis that is dated now. The node only counts--- its headers as synced when the best one is less than two hours old, and--- the headers of the other fixtures are years old.-freshHeader :: Network -> IO BlockHeader-freshHeader net = do-  now <- round <$> getPOSIXTime-  let genesis = net.genesisHeader-  return $-    mineBlock-      net-      0-      genesis {version = 4, prev = headerHash genesis, timestamp = now}+-- | The payload of the next unknown message that the node publishes.+otherPayload :: Inbox NodeEvent -> IO ByteString+otherPayload events =+  receive events >>= \case+    PeerEvent (PeerMessage _ (MOther "zz" payload)) -> return payload+    _ -> otherPayload events  -- | Wait for a peer to be announced, failing after a while. waitForPeer :: Inbox NodeEvent -> IO Peer@@ -510,15 +411,6 @@ withLifted :: ((a -> IO b) -> IO b) -> (a -> IO b) -> IO b withLifted w m = withRunInIO $ \io -> w (io . m) -withTestNode ::-  Network -> String -> (TestNode -> IO a) -> IO a-withTestNode = withTestNodeBlocks allBlocks---- | Like 'withTestNode', with the mock peer serving these blocks.-withTestNodeBlocks ::-  [Block] -> Network -> String -> (TestNode -> IO a) -> IO a-withTestNodeBlocks blocks = withTestNodeOpts (defOpts blocks)- withTestNodeOpts ::   TestOpts -> Network -> String -> (TestNode -> IO a) -> IO a withTestNodeOpts opts net str f =@@ -561,7 +453,8 @@               (NetworkAddress nodeNetwork anywhere)               sa               conn,-          logger = Logger {level = LevelError, source = "", push = \_ -> return ()}+          logger = Logger {level = LevelError, source = "", push = \_ -> return ()},+          permissions = mempty         }     anywhere = sockToHostAddress (SockAddrInet 0 0)     cfg = def {R.createIfMissing = True, R.errorIfExists = True}