summaryrefslogtreecommitdiff
path: root/src/Network/Haskoin/Node/Peer.hs
blob: a0ef82b83bbe7519dcf5f622b63342e2dbe55e6b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
{-# LANGUAGE ConstraintKinds       #-}
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE LambdaCase            #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE TupleSections         #-}
{-# LANGUAGE TypeFamilies          #-}
module Network.Haskoin.Node.Peer
    ( peer
    ) where

import           Control.Monad
import           Control.Monad.Logger
import           Control.Monad.Reader
import           Data.Bits
import           Data.ByteString             (ByteString)
import qualified Data.ByteString             as BS
import qualified Data.ByteString.Char8       as C8
import qualified Data.ByteString.Lazy        as BL
import           Data.Conduit
import qualified Data.Conduit.Binary         as CB
import           Data.Conduit.Network
import           Data.Maybe
import           Data.Serialize
import           Data.String
import           Data.String.Conversions
import           Data.Time.Clock
import           Data.Word
import           Network.Haskoin.Block
import           Network.Haskoin.Constants
import           Network.Haskoin.Network
import           Network.Haskoin.Node.Common
import           Network.Haskoin.Transaction
import           Network.Socket              (SockAddr)
import           NQE
import           System.Random
import           UnliftIO

type MonadPeer m = (MonadUnliftIO m, MonadLoggerIO m, MonadReader PeerReader m)

data Pending
    = PendingTx !TxHash
    | PendingBlock !BlockHash
    | PendingMerkle !BlockHash
    | PendingHeaders
    deriving (Show, Eq)

data PeerReader = PeerReader
    { mySelf     :: !Peer
    , myConfig   :: !PeerConfig
    , mySockAddr :: !SockAddr
    , myHostPort :: !(Host, Port)
    , myPending  :: !(TVar [(Pending, Word32)])
    }

time :: Int
time = 15 * 1000 * 1000

logMsg :: IsString a => Message -> a
logMsg = fromString . cs . commandToString . msgType

logPeer ::
       (ConvertibleStrings String a, Semigroup a, IsString a) => SockAddr -> a
logPeer sa = "Peer<" <> cs (show sa) <> ">"

peer :: (MonadUnliftIO m, MonadLoggerIO m) => PeerConfig -> Peer -> m ()
peer pc p =
    fromSockAddr na >>= \case
        Nothing -> do
            $(logErrorS) (logPeer na) "Invalid network address"
            throwIO PeerAddressInvalid
        Just (host, port) -> do
            let cset = clientSettings port (C8.pack host)
            runGeneralTCPClient cset (peerSession (host, port))
  where
    na = naAddress (peerConfConnect pc)
    go = handshake >> exchangePing >> peerLoop
    net = peerConfNetwork pc
    peerSession hp ad = do
        let src =
                runConduit $
                appSource ad .| inPeerConduit net .| conduitMailbox p
            snk = outPeerConduit net .| appSink ad
        withAsync src $ \as -> do
            link as
            pbox <- newTVarIO []
            let rd =
                    PeerReader
                        { myConfig = pc
                        , mySelf = p
                        , myHostPort = hp
                        , mySockAddr = na
                        , myPending = pbox
                        }
            runReaderT (runConduit (go .| snk)) rd

handshake :: MonadPeer m => ConduitT () Message m ()
handshake = do
    p <- asks mySelf
    ch <- peerConfChain <$> asks myConfig
    rmt <- peerConfConnect <$> asks myConfig
    loc <- peerConfLocal <$> asks myConfig
    net <- peerConfNetwork <$> asks myConfig
    nonce <- peerConfNonce <$> asks myConfig
    bb <- chainGetBest ch
    ver <- buildVersion net nonce (nodeHeight bb) loc rmt
    yield $ MVersion ver
    lift (remoteVer p) >>= \case
        v
            | testSegWit net v -> do
                yield MVerAck
                lift (remoteVerAck p)
                mgr <- peerConfManager <$> asks myConfig
                managerSetPeerVersion p v mgr
            | otherwise -> do
                yield . MReject $
                    reject MCVersion RejectObsolete "No SegWit support"
                throwIO PeerNoSegWit
  where
    testSegWit net v
        | getSegWit net = services v `testBit` 3
        | otherwise = True
    remoteVer p = do
        m <-
            timeout time . receiveMatch p $ \case
                PeerIncoming (MVersion v) -> Just v
                _ -> Nothing
        case m of
            Just v  -> return v
            Nothing -> throwIO PeerTimeout
    remoteVerAck p = do
        m <-
            timeout time . receiveMatch p $ \case
                PeerIncoming MVerAck -> Just ()
                _ -> Nothing
        when (isNothing m) $ throwIO PeerTimeout

peerLoop :: MonadPeer m => ConduitT () Message m ()
peerLoop =
    forever $ do
        me <- asks mySelf
        m <- lift $ timeout (2 * 60 * 1000 * 1000) (receive me)
        case m of
            Nothing  -> exchangePing
            Just msg -> processMessage msg

exchangePing :: MonadPeer m => ConduitT () Message m ()
exchangePing = do
    lp <- logMe
    i <- liftIO randomIO
    yield $ MPing (Ping i)
    me <- asks mySelf
    mgr <- peerConfManager <$> asks myConfig
    t1 <- liftIO getCurrentTime
    m <-
        lift . timeout time . receiveMatch me $ \case
            PeerIncoming (MPong (Pong j))
                | i == j -> Just ()
            _ -> Nothing
    case m of
        Nothing -> do
            $(logErrorS) lp "Timeout while waiting for pong"
            throwIO PeerTimeout
        Just () -> do
            t2 <- liftIO getCurrentTime
            let d = t2 `diffUTCTime` t1
            $(logDebugS) lp $
                "Roundtrip: " <> cs (show (d * 1000)) <> " ms"
            ManagerPeerPing me d `send` mgr

checkStale :: MonadPeer m => ConduitM () Message m ()
checkStale = do
    pbox <- asks myPending
    ps <- readTVarIO pbox
    case ps of
        [] -> return ()
        (_, ts):_ -> do
            cur <- computeTime
            when (cur > ts + 30) $ throwIO PeerTimeout

registerOutgoing :: MonadPeer m => Message -> m ()
registerOutgoing (MGetData (GetData ivs)) = do
    pbox <- asks myPending
    cur <- computeTime
    ms <-
        fmap catMaybes . forM ivs $ \iv ->
            case toPending iv of
                Nothing -> return Nothing
                Just p  -> return $ Just (p, cur)
    atomically (modifyTVar pbox (++ ms))
  where
    toPending InvVector {invType = InvTx, invHash = hash} =
        Just (PendingTx (TxHash hash))
    toPending InvVector {invType = InvWitnessTx, invHash = hash} =
        Just (PendingTx (TxHash hash))
    toPending InvVector {invType = InvBlock, invHash = hash} =
        Just (PendingBlock (BlockHash hash))
    toPending InvVector {invType = InvWitnessBlock, invHash = hash} =
        Just (PendingBlock (BlockHash hash))
    toPending InvVector {invType = InvMerkleBlock, invHash = hash} =
        Just (PendingMerkle (BlockHash hash))
    toPending InvVector {invType = InvWitnessMerkleBlock, invHash = hash} =
        Just (PendingMerkle (BlockHash hash))
    toPending _ = Nothing
registerOutgoing MGetHeaders {} = do
    pbox <- asks myPending
    cur <- computeTime
    atomically (modifyTVar pbox (reverse . ((PendingHeaders, cur) :) . reverse))
registerOutgoing _ = return ()

registerIncoming :: MonadPeer m => Message -> m ()
registerIncoming (MNotFound (NotFound ivs)) =
    asks myPending >>= \pbox ->
        atomically (modifyTVar pbox (filter (matchNotFound . fst)))
  where
    matchNotFound (PendingTx (TxHash hash)) =
        InvVector InvTx hash `notElem` ivs &&
        InvVector InvWitnessTx hash `notElem` ivs
    matchNotFound (PendingBlock (BlockHash hash)) =
        InvVector InvBlock hash `notElem` ivs &&
        InvVector InvWitnessBlock hash `notElem` ivs
    matchNotFound (PendingMerkle (BlockHash hash)) =
        InvVector InvBlock hash `notElem` ivs &&
        InvVector InvMerkleBlock hash `notElem` ivs &&
        InvVector InvWitnessMerkleBlock hash `notElem` ivs
    matchNotFound _ = False
registerIncoming (MTx t) =
    asks myPending >>= \pbox ->
        atomically (modifyTVar pbox (filter ((/= PendingTx (txHash t)) . fst)))
registerIncoming (MBlock b) =
    asks myPending >>= \pbox ->
        atomically $
        modifyTVar
            pbox
            (filter ((/= PendingBlock (headerHash (blockHeader b))) . fst))
registerIncoming (MMerkleBlock b) =
    asks myPending >>= \pbox ->
        atomically $
        modifyTVar
            pbox
            (filter ((/= PendingMerkle (headerHash (merkleHeader b))) . fst))
registerIncoming MHeaders {} =
    asks myPending >>= \pbox ->
        atomically $ modifyTVar pbox (filter ((/= PendingHeaders) . fst))
registerIncoming _ = return ()

processMessage :: MonadPeer m => PeerMessage -> ConduitM () Message m ()
processMessage m = do
    checkStale
    case m of
        PeerOutgoing msg -> do
            lift (registerOutgoing msg)
            yield msg
        PeerIncoming msg -> do
            lift (registerIncoming msg)
            incoming msg

logMe ::
       ( ConvertibleStrings String a
       , Semigroup a
       , IsString a
       , MonadReader PeerReader m
       )
    => m a
logMe = logPeer <$> asks mySockAddr

incoming :: MonadPeer m => Message -> ConduitT () Message m ()
incoming m = do
    lp <- lift logMe
    p <- asks mySelf
    l <- peerConfListener <$> asks myConfig
    mgr <- peerConfManager <$> asks myConfig
    ch <- peerConfChain <$> asks myConfig
    case m of
        MVersion _ -> do
            $(logErrorS) lp $ "Received duplicate " <> logMsg m
            yield $
                MReject
                    Reject
                    { rejectMessage = MCVersion
                    , rejectCode = RejectDuplicate
                    , rejectReason = VarString BS.empty
                    , rejectData = BS.empty
                    }
        MPing (Ping n) -> yield $ MPong (Pong n)
        MPong (Pong n) -> atomically (l (p, GotPong n))
        MSendHeaders {} -> ChainSendHeaders p `send` ch
        MAlert {} -> $(logWarnS) lp $ "Deprecated " <> logMsg m
        MAddr (Addr as) -> managerNewPeers p as mgr
        MInv (Inv is) -> do
            let ts = [TxHash (invHash i) | i <- is, invType i == InvTx]
                bs =
                    [ BlockHash (invHash i)
                    | i <- is
                    , invType i == InvBlock || invType i == InvMerkleBlock
                    ]
            unless (null ts) $ atomically $ l (p, TxAvail ts)
            unless (null bs) $ ChainNewBlocks p bs `send` ch
        MTx tx -> atomically (l (p, GotTx tx))
        MBlock b -> atomically (l (p, GotBlock b))
        MMerkleBlock b -> atomically (l (p, GotMerkleBlock b))
        MHeaders (Headers hcs) -> ChainNewHeaders p hcs `send` ch
        MGetData (GetData d) -> atomically (l (p, SendData d))
        MNotFound (NotFound ns) -> do
            let f (InvVector InvTx hash) = Just (TxNotFound (TxHash hash))
                f (InvVector InvWitnessTx hash) =
                    Just (TxNotFound (TxHash hash))
                f (InvVector InvBlock hash) =
                    Just (BlockNotFound (BlockHash hash))
                f (InvVector InvWitnessBlock hash) =
                    Just (BlockNotFound (BlockHash hash))
                f (InvVector InvMerkleBlock hash) =
                    Just (BlockNotFound (BlockHash hash))
                f (InvVector InvWitnessMerkleBlock hash) =
                    Just (BlockNotFound (BlockHash hash))
                f _ = Nothing
                events = mapMaybe f ns
            atomically (mapM_ (l . (p, )) events)
        MGetBlocks g -> atomically (l (p, SendBlocks g))
        MGetHeaders h -> atomically (l (p, SendHeaders h))
        MReject r -> atomically (l (p, Rejected r))
        MMempool -> atomically (l (p, WantMempool))
        MGetAddr -> managerGetAddr p mgr
        _ -> $(logWarnS) lp $ "Ignoring message: " <> logMsg m

inPeerConduit :: MonadIO m => Network -> ConduitT ByteString PeerMessage m ()
inPeerConduit net = do
    headerBytes <- CB.take 24
    case decodeLazy headerBytes of
        Left e -> throwIO $ DecodeMessageError e
        Right (MessageHeader _ _cmd len _) -> do
            when (len > 32 * 2 ^ (20 :: Int)) . throwIO $ PayloadTooLarge len
            payloadBytes <- CB.take (fromIntegral len)
            case runGetLazy (getMessage net) $ headerBytes `BL.append` payloadBytes of
                Left e    -> throwIO $ CannotDecodePayload e
                Right msg -> yield $ PeerIncoming msg
            inPeerConduit net

outPeerConduit :: Monad m => Network -> ConduitT Message ByteString m ()
outPeerConduit net = awaitForever $ yield . runPut . putMessage net