-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRPC.hs
489 lines (469 loc) · 14.2 KB
/
RPC.hs
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
module LndClient.RPC
( unlockWallet,
newAddress,
addInvoice,
initWallet,
openChannel,
getPeers,
connectPeer,
getInfo,
subscribeInvoices,
RPCResponse (..),
coerceRPCResponse,
maybeRPCResponse,
)
where
import Chronos (SubsecondPrecision (SubsecondPrecisionAuto), encodeTimespan, stopwatch)
import Control.Concurrent.Thread.Delay (delay)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Aeson (FromJSON, ToJSON, eitherDecode, encode)
import Data.ByteString (ByteString)
import Data.Coerce (coerce)
import qualified Data.Conduit.List as CL
import Data.Either (isRight)
import Data.Maybe (fromMaybe)
import Data.Text as T (pack)
import Data.Text.Lazy as TL (fromStrict)
import Data.Word (Word64)
import GHC.Generics (Generic)
import Katip (KatipContext, Severity (..), katipAddContext, logStr, logTM, sl)
import LndClient.Data.AddInvoice as AddInvoice
( AddInvoiceRequest (..),
AddInvoiceResponse (..),
)
import LndClient.Data.GetInfo
import LndClient.Data.InitWallet (InitWalletRequest (..))
import LndClient.Data.Invoice (Invoice (..))
import LndClient.Data.LndEnv
( LndB64WalletPassword (..),
LndEnv (..),
LndHexMacaroon (..),
LndTlsManagerBuilder (..),
LndUrl (..),
)
import LndClient.Data.NewAddress (NewAddressResponse (..))
import LndClient.Data.Newtypes
import LndClient.Data.OpenChannel (ChannelPoint (..), OpenChannelRequest (..))
import LndClient.Data.Peer (ConnectPeerRequest (..), PeerList (..))
import LndClient.Data.SubscribeInvoices as SubscribeInvoices (SubscribeInvoicesRequest (..))
import LndClient.Data.Types
import LndClient.Data.UnlockWallet (UnlockWalletRequest (..))
import LndClient.Data.Void (VoidRequest (..), VoidResponse (..))
import LndClient.Utils (coerceLndResult, doExpBackOff)
import qualified LndGrpc as GRPC
import Network.GRPC.HighLevel.Generated
import Network.HTTP.Client
( RequestBody (RequestBodyLBS),
Response (..),
httpLbs,
method,
parseRequest,
queryString,
requestBody,
requestHeaders,
responseStatus,
responseTimeout,
responseTimeoutNone,
)
import Network.HTTP.Simple (httpSink, setRequestManager)
import Network.HTTP.Types.Method (StdMethod (..), renderStdMethod)
import Network.HTTP.Types.Status (ok200, status404, statusCode)
import Network.HTTP.Types.URI (Query, renderQuery)
import Proto3.Suite.Class
import UnliftIO
newtype RPCResponse a
= RPCResponse (Response (Either String a))
deriving (Show)
data RpcName
= UnlockWallet
| NewAddress
| AddInvoice
| InitWallet
| SubscribeInvoices
| OpenChannel
| GetPeers
| ConnectPeer
| GetInfo
deriving (Generic)
instance ToJSON RpcName
data RpcArgs a b m
= RpcArgs
{ rpcEnv :: LndEnv,
rpcMethod :: StdMethod,
rpcUrlPath :: String,
rpcUrlQuery :: Query,
rpcReqBody :: Maybe a,
rpcRetryAttempt :: Int,
rpcSuccessCond :: RPCResponse b -> Bool,
rpcName :: RpcName,
rpcSubHandler :: Maybe (ByteString -> m ())
}
maybeRPCResponse :: LndResult (RPCResponse a) -> Maybe a
maybeRPCResponse res0 =
case res0 of
LndSuccess _ (RPCResponse res1) ->
case responseBody res1 of
Right res2 -> Just res2
_ -> Nothing
_ -> Nothing
coerceRPCResponse :: (Show a, MonadIO m) => LndResult (RPCResponse a) -> m a
coerceRPCResponse x = do
RPCResponse y <- coerceLndResult x
case responseBody y of
Left e -> fail e
Right z -> return z
rpc ::
(ToJSON a, FromJSON b, KatipContext m, MonadUnliftIO m) =>
RpcArgs a b m ->
m (LndResult (RPCResponse b))
rpc
RpcArgs
{ rpcEnv,
rpcMethod,
rpcUrlPath,
rpcUrlQuery,
rpcReqBody,
rpcRetryAttempt,
rpcSuccessCond,
rpcName,
rpcSubHandler
} =
katipAddContext (sl "rpcName" rpcName) $ do
$(logTM) InfoS "is running..."
this <- doExpBackOff rpcRetryAttempt rpcSuccessCond expr
case this of
(LndSuccess et _) ->
$(logTM) InfoS
$ logStr
$ "succeeded, elapsed time = "
<> showElapsedTime et
<> " seconds"
(LndFail et (RPCResponse res)) ->
$(logTM) ErrorS
$ logStr
$ "failed with HTTP status "
<> (T.pack . show . statusCode . responseStatus $ res)
<> ", elapsed time = "
<> showElapsedTime et
<> " seconds"
(LndHttpException et e) ->
$(logTM) ErrorS
$ logStr
$ "failed with HttpException "
<> T.pack (show e)
<> ", elapsed time = "
<> showElapsedTime et
<> " seconds"
return this
where
showElapsedTime = encodeTimespan SubsecondPrecisionAuto
expr = do
req0 <- liftIO $ parseRequest $ coerce (envLndUrl rpcEnv) <> rpcUrlPath
let req1 =
req0
{ method = renderStdMethod rpcMethod,
queryString = renderQuery False rpcUrlQuery,
requestHeaders =
[ ("Content-Type", "application/json"),
( "Grpc-Metadata-macaroon",
coerce $ envLndHexMacaroon rpcEnv
)
]
}
let req2 =
maybe
req1
(\b -> req1 {requestBody = RequestBodyLBS $ encode b})
rpcReqBody
--liftIO $ print $ encode rpcReqBody
manager <- liftIO $ coerce $ envLndTlsManagerBuilder rpcEnv
case rpcSubHandler of
Nothing -> do
res <- liftIO $ httpLbs req2 manager
liftIO $ print res
return $ RPCResponse $ eitherDecode <$> res
Just subHandler -> do
let req3 = setRequestManager manager req2
let req4 = req3 {responseTimeout = responseTimeoutNone}
httpSink req4 $ \res -> do
CL.mapM_ subHandler
return
$ RPCResponse
$ Left "subscription don't have response body"
<$ res
grpcMeta :: LndEnv -> MetadataMap
grpcMeta env =
[("macaroon", coerce $ envLndHexMacaroon env)]
initWallet ::
(KatipContext m, MonadUnliftIO m) =>
LndEnv ->
InitWalletRequest ->
m (LndResult (RPCResponse VoidResponse))
initWallet env req = do
res <- rpc $ rpcArgs env
--
-- NOTE : some LND bullshit - it crashes if other RPC performed after that too soon
--
_ <- liftIO $ delay 5000000
return res
where
rpcArgs rpcEnv =
RpcArgs
{ rpcEnv,
rpcMethod = POST,
rpcUrlPath = "/v1/initwallet",
rpcUrlQuery = [],
rpcReqBody = Just req,
rpcRetryAttempt = 0,
rpcSuccessCond = stdRpcCond,
rpcName = InitWallet,
rpcSubHandler = Nothing
}
--
-- TODO : implement recovery_window and channel_backups
--
unlockWallet ::
(KatipContext m, MonadUnliftIO m) =>
LndEnv ->
m (LndResult (RPCResponse VoidResponse))
unlockWallet env =
rpc $ rpcArgs env
where
rpcReqBody rpcEnv =
Just
UnlockWalletRequest
{ walletPassword = coerce $ envLndB64WalletPassword rpcEnv,
recoveryWindow = 0
}
rpcSuccessCond (RPCResponse res) =
let ss = responseStatus res in ss == ok200 || ss == status404
rpcArgs rpcEnv =
RpcArgs
{ rpcEnv,
rpcMethod = POST,
rpcUrlPath = "/v1/unlockwallet",
rpcUrlQuery = [],
rpcReqBody = rpcReqBody rpcEnv,
rpcRetryAttempt = 5,
rpcSuccessCond,
rpcName = UnlockWallet,
rpcSubHandler = Nothing
}
stdRpcCond :: RPCResponse a -> Bool
stdRpcCond (RPCResponse res) =
(responseStatus res == ok200) && isRight (responseBody res)
newAddress ::
(KatipContext m, MonadUnliftIO m) =>
LndEnv ->
m (LndResult (RPCResponse NewAddressResponse))
newAddress env = rpc $ rpcArgs env
where
rpcArgs rpcEnv =
RpcArgs
{ rpcEnv,
rpcMethod = GET,
rpcUrlPath = "/v1/newaddress",
rpcUrlQuery = [("type", Just "1")],
rpcReqBody = Nothing :: Maybe VoidRequest,
rpcRetryAttempt = 0,
rpcSuccessCond = stdRpcCond,
rpcName = NewAddress,
rpcSubHandler = Nothing
}
--
-- TODO
-- better generic utils for request/parsing
-- handle exceptions
-- fix RHash type
-- fix PaymentRequest type
-- rm RPCResponse (we don't have HTTP-related low level details anymore)
--
addInvoice ::
(MonadIO m) =>
LndEnv ->
AddInvoiceRequest ->
m (LndResult AddInvoiceResponse)
addInvoice env req =
liftIO $ withGRPCClient (envLndGrpcConfig env) $ \client -> do
method <- GRPC.lightningAddInvoice <$> GRPC.lightningClient client
(ts, rawGrpc) <-
stopwatch . method $ ClientNormalRequest grpcReq 1 $ grpcMeta env
case rawGrpc of
--
-- TODO : patterns here are not exhaustive and compiler don't warn about it
-- for some reason. Investigate and/or fix
--
ClientNormalResponse grpcRes _ _ _ _ ->
return $ LndSuccess ts $
AddInvoiceResponse
{ rHash =
RHash $
GRPC.addInvoiceResponseRHash grpcRes,
paymentRequest =
PaymentRequest $
GRPC.addInvoiceResponsePaymentRequest grpcRes,
addIndex =
AddIndex $
GRPC.addInvoiceResponseAddIndex grpcRes
}
ClientErrorResponse err -> do
print err
fail "ClientErrorResponse"
where
grpcReq :: GRPC.Invoice
grpcReq =
--
-- TODO : handle invoiceValue overflow
--
def
{ GRPC.invoiceValue =
fromIntegral (coerce . AddInvoice.value $ req :: Word64),
GRPC.invoiceMemo =
maybe def TL.fromStrict $ AddInvoice.memo req,
GRPC.invoiceDescriptionHash =
fromMaybe def $ AddInvoice.descriptionHash req
}
subscribeInvoices ::
(MonadIO m) =>
LndEnv ->
SubscribeInvoicesRequest ->
--
-- TODO : replace IO with m if possible
--
(Invoice -> IO ()) ->
m (LndResult ())
subscribeInvoices env req invoiceHandler =
liftIO $ withGRPCClient (envLndGrpcConfig env) $ \client -> do
method <- GRPC.lightningSubscribeInvoices <$> GRPC.lightningClient client
(ts, rawGrpc) <-
stopwatch . method $
ClientReaderRequest grpcReq 3600 (grpcMeta env) (\_ _ s -> streamHandler s)
case rawGrpc of
ClientReaderResponse {} ->
return $ LndFail ts ()
ClientErrorResponse err -> do
print err
fail "ClientErrorResponse"
where
streamHandler stream = do
msg <- stream
case msg of
Left e -> fail $ "SubscribeInvoices error " <> show e
Right Nothing -> fail "SubscribeInvoices got Nothing"
Right (Just i) -> do
--
-- TODO : handle all fields and types overflow
--
invoiceHandler $
Invoice
{ rHash = RHash $ GRPC.invoiceRHash i,
amtPaidSat =
Just . MoneyAmount $ fromIntegral $ GRPC.invoiceAmtPaidSat i,
creationDate = Nothing,
settleDate = Nothing,
value = MoneyAmount $ fromIntegral $ GRPC.invoiceValue i,
expiry = Nothing,
settled = Nothing,
settleIndex = Nothing,
descriptionHash = Nothing,
memo = Nothing,
paymentRequest = Nothing,
fallbackAddr = Nothing,
cltvExpiry = Nothing,
private = Nothing,
addIndex = AddIndex $ GRPC.invoiceAddIndex i,
state = Nothing
}
streamHandler stream
grpcReq :: GRPC.InvoiceSubscription
grpcReq =
def
{ GRPC.invoiceSubscriptionAddIndex =
maybe def coerce $ SubscribeInvoices.addIndex req,
GRPC.invoiceSubscriptionSettleIndex =
maybe def coerce $ SubscribeInvoices.settleIndex req
}
openChannel ::
(KatipContext m, MonadUnliftIO m) =>
LndEnv ->
OpenChannelRequest ->
m (LndResult (RPCResponse ChannelPoint))
openChannel env req = rpc $ rpcArgs env
where
rpcArgs rpcEnv =
RpcArgs
{ rpcEnv,
rpcMethod = POST,
rpcUrlPath = "/v1/channels",
rpcUrlQuery = [],
rpcReqBody = Just req,
rpcRetryAttempt = 0,
rpcSuccessCond = stdRpcCond,
rpcName = OpenChannel,
rpcSubHandler = Nothing
}
getPeers ::
(KatipContext m, MonadUnliftIO m) =>
LndEnv ->
m (LndResult (RPCResponse PeerList))
getPeers env = rpc $ rpcArgs env
where
rpcArgs rpcEnv =
RpcArgs
{ rpcEnv,
rpcMethod = GET,
rpcUrlPath = "/v1/peers",
rpcUrlQuery = [],
rpcReqBody = Nothing :: Maybe VoidRequest,
rpcRetryAttempt = 0,
rpcSuccessCond = stdRpcCond,
rpcName = GetPeers,
rpcSubHandler = Nothing
}
connectPeer ::
(KatipContext m, MonadUnliftIO m) =>
LndEnv ->
ConnectPeerRequest ->
m (LndResult (RPCResponse VoidResponse))
connectPeer env req = rpc $ rpcArgs env
where
rpcArgs rpcEnv =
RpcArgs
{ rpcEnv,
rpcMethod = POST,
rpcUrlPath = "/v1/peers",
rpcUrlQuery = [],
rpcReqBody = Just req,
rpcRetryAttempt = 0,
rpcSuccessCond = stdRpcCond,
rpcName = ConnectPeer,
rpcSubHandler = Nothing
}
getInfo ::
(KatipContext m, MonadUnliftIO m) =>
LndEnv ->
m (LndResult (RPCResponse GetInfoResponse))
getInfo env = rpc $ rpcArgs env
where
rpcArgs rpcEnv =
RpcArgs
{ rpcEnv,
rpcMethod = GET,
rpcUrlPath = "/v1/getinfo",
rpcUrlQuery = [],
rpcReqBody = Nothing :: Maybe VoidRequest,
rpcRetryAttempt = 0,
rpcSuccessCond = stdRpcCond,
rpcName = GetInfo,
rpcSubHandler = Nothing
}