-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRPC.hs
447 lines (422 loc) · 11.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
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
module LndClient.RPC
( unlockWallet,
lazyUnlockWallet,
lazyInitWallet,
newAddress,
addInvoice,
initWallet,
openChannelSync,
listChannels,
closeChannel,
listPeers,
connectPeer,
sendPayment,
getInfo,
subscribeInvoices,
subscribeChannelEvents,
grpcSync,
grpcSubscribe,
)
where
import qualified Control.Exception as CE (catch, throw)
import LndClient.Data.AddInvoice as AddInvoice
( AddInvoiceRequest (..),
AddInvoiceResponse (..),
)
import LndClient.Data.CloseChannel (CloseChannelRequest (..), CloseStatusUpdate (..))
import LndClient.Data.GetInfo
import LndClient.Data.InitWallet (InitWalletRequest (..))
import LndClient.Data.Invoice (Invoice (..))
import LndClient.Data.ListChannels (ListChannelsRequest (..), ListChannelsResponse (..))
import LndClient.Data.NewAddress (NewAddressResponse (..))
import LndClient.Data.OpenChannel (ChannelPoint (..), OpenChannelRequest (..))
import LndClient.Data.Peer (ConnectPeerRequest (..), Peer (..))
import LndClient.Data.SendPayment as SendPayment
( SendPaymentRequest (..),
SendPaymentResponse (..),
)
import LndClient.Data.SubscribeChannelEvents (ChannelEventUpdate (..))
import LndClient.Data.SubscribeInvoices as SubscribeInvoices
( SubscribeInvoicesRequest (..),
)
import LndClient.Data.UnlockWallet (UnlockWalletRequest (..))
import LndClient.Import
import qualified LndGrpc as GRPC
import Network.GRPC.HighLevel.Generated
import Network.GRPC.LowLevel
import qualified WalletUnlockerGrpc as GRPC
data RpcName
= UnlockWallet
| InitWallet
| LazyUnlockWallet
| LazyInitWallet
| NewAddress
| AddInvoice
| SubscribeInvoices
| SubscribeChannelEvents
| OpenChannelSync
| ListChannels
| CloseChannel
| ListPeers
| ConnectPeer
| GetInfo
| SendPayment
deriving (Generic)
instance ToJSON RpcName
grpcMeta :: LndEnv -> MetadataMap
grpcMeta env =
[("macaroon", encodeUtf8 (coerce (envLndHexMacaroon env) :: Text))]
grpcDefaultTimeout :: Int
grpcDefaultTimeout = 5
initWallet ::
(KatipContext m) =>
LndEnv ->
m (Either LndError ())
initWallet env = do
res <-
grpcSync
InitWallet
GRPC.walletUnlockerClient
GRPC.walletUnlockerInitWallet
grpcDefaultTimeout
env
InitWalletRequest
{ walletPassword = coerce $ envLndWalletPassword env,
cipherSeedMnemonic = coerce $ envLndCipherSeedMnemonic env,
aezeedPassphrase = coerce $ envLndAezeedPassphrase env
}
--
-- NOTE : some LND bullshit - it crashes if other RPC performed after that too soon
--
_ <- liftIO $ delay 10000000
return res
--
-- TODO : implement recovery_window and channel_backups
--
unlockWallet ::
(KatipContext m) =>
LndEnv ->
m (Either LndError ())
unlockWallet env =
grpcSync
UnlockWallet
GRPC.walletUnlockerClient
GRPC.walletUnlockerUnlockWallet
grpcDefaultTimeout
env
UnlockWalletRequest
{ walletPassword = coerce $ envLndWalletPassword env,
recoveryWindow = 0
}
lazyUnlockWallet ::
(KatipContext m) =>
LndEnv ->
m (Either LndError ())
lazyUnlockWallet env =
katipAddContext (sl "RpcName" LazyUnlockWallet) $ do
$(logTM) InfoS "RPC is running..."
unlocked <- isRight <$> getInfo (env {envLndLogErrors = False})
if unlocked
then do
$(logTM) InfoS "Wallet is already unlocked, doing nothing"
return $ Right ()
else unlockWallet env
lazyInitWallet ::
(KatipContext m) =>
LndEnv ->
m (Either LndError ())
lazyInitWallet env =
katipAddContext (sl "RpcName" LazyInitWallet) $ do
$(logTM) InfoS "RPC is running..."
unlockRes <- lazyUnlockWallet $ env {envLndLogErrors = False}
if isRight unlockRes
then return unlockRes
else do
initRes <- initWallet env
if isRight initRes
then lazyUnlockWallet env
else do
$(logTM) ErrorS "Wallet initialization fiasco"
return initRes
newAddress ::
(KatipContext m) =>
LndEnv ->
GRPC.AddressType ->
m (Either LndError NewAddressResponse)
newAddress env req =
grpcSync
NewAddress
GRPC.lightningClient
GRPC.lightningNewAddress
grpcDefaultTimeout
env
(GRPC.NewAddressRequest $ Enumerated $ Right req)
--
-- TODO
--
-- handle exceptions
-- fix RHash type
-- fix PaymentRequest type
-- rm RPCResponse (we don't have HTTP-related low level details anymore)
--
addInvoice ::
(KatipContext m) =>
LndEnv ->
AddInvoiceRequest ->
m (Either LndError AddInvoiceResponse)
addInvoice =
grpcSync
AddInvoice
GRPC.lightningClient
GRPC.lightningAddInvoice
grpcDefaultTimeout
subscribeInvoices ::
(KatipContext m) =>
--
-- TODO : replace IO with m if possible
--
(Invoice -> IO ()) ->
LndEnv ->
SubscribeInvoicesRequest ->
m (Either LndError ())
subscribeInvoices =
grpcSubscribe
SubscribeInvoices
GRPC.lightningSubscribeInvoices
3600
subscribeChannelEvents ::
(KatipContext m) =>
--
-- TODO : replace IO with m if possible
--
(ChannelEventUpdate -> IO ()) ->
LndEnv ->
m (Either LndError ())
subscribeChannelEvents handler env =
grpcSubscribe
SubscribeChannelEvents
GRPC.lightningSubscribeChannelEvents
3600
handler
env
GRPC.ChannelEventSubscription {}
openChannelSync ::
(KatipContext m) =>
LndEnv ->
OpenChannelRequest ->
m (Either LndError ChannelPoint)
openChannelSync =
grpcSync
OpenChannelSync
GRPC.lightningClient
GRPC.lightningOpenChannelSync
grpcDefaultTimeout
listChannels ::
(KatipContext m) =>
LndEnv ->
ListChannelsRequest ->
m (Either LndError ListChannelsResponse)
listChannels =
grpcSync
ListChannels
GRPC.lightningClient
GRPC.lightningListChannels
1
closeChannel ::
(KatipContext m) =>
(CloseStatusUpdate -> IO ()) ->
LndEnv ->
CloseChannelRequest ->
m (Either LndError ())
closeChannel =
grpcSubscribe
CloseChannel
GRPC.lightningCloseChannel
3600
listPeers ::
(KatipContext m) =>
LndEnv ->
m (Either LndError [Peer])
listPeers env =
grpcSync
ListPeers
GRPC.lightningClient
GRPC.lightningListPeers
grpcDefaultTimeout
env
(def :: GRPC.ListPeersRequest)
connectPeer ::
(KatipContext m) =>
LndEnv ->
ConnectPeerRequest ->
m (Either LndError ())
connectPeer =
grpcSync
ConnectPeer
GRPC.lightningClient
GRPC.lightningConnectPeer
grpcDefaultTimeout
getInfo ::
(KatipContext m) =>
LndEnv ->
m (Either LndError GetInfoResponse)
getInfo env =
grpcSync
GetInfo
GRPC.lightningClient
GRPC.lightningGetInfo
grpcDefaultTimeout
env
GRPC.GetInfoRequest
sendPayment ::
(KatipContext m) =>
LndEnv ->
SendPaymentRequest ->
m (Either LndError SendPaymentResponse)
sendPayment =
grpcSync
SendPayment
GRPC.lightningClient
GRPC.lightningSendPaymentSync
grpcDefaultTimeout
--
-- TODO : add logging and elapsed time logs
--
grpcSubscribe ::
( MonadIO m,
KatipContext m,
ToGrpc a gA,
FromGrpc b gB
) =>
RpcName ->
( GRPC.Lightning ClientRequest ClientResult ->
ClientRequest 'ServerStreaming gA gB ->
IO (ClientResult streamType streamResult)
) ->
--
-- TODO : newtype for timeout
--
Int ->
(b -> IO ()) ->
LndEnv ->
a ->
m (Either LndError ())
grpcSubscribe rpcName method timeout handler env req =
katipAddContext (sl "RpcName" rpcName) $ katipAddLndContext env $ do
$(logTM) InfoS "RPC is running..."
(ts, res) <- liftIO $ stopwatch $ case toGrpc req of
Left e -> return $ Left e
Right grpcReq ->
withGRPCClient (envLndGrpcConfig env) $ \client -> do
method' <- method <$> GRPC.lightningClient client
let greq =
ClientReaderRequest
grpcReq
timeout
(grpcMeta env)
(\_ _ s -> genStreamHandler s handler)
rawGrpc <- CE.catch (Right <$> method' greq) $ return . Left
return $ case rawGrpc of
Right ClientNormalResponse {} ->
Left $ GrpcUnexpectedResult "ClientNormalResponse"
Right (ClientErrorResponse err) ->
Left $ GrpcError err
Right ClientWriterResponse {} ->
Left $ GrpcUnexpectedResult "ClientWriterResponse"
Right ClientReaderResponse {} ->
Right ()
Right ClientBiDiResponse {} ->
Left $ GrpcUnexpectedResult "ClientBiDiResponse"
Left e ->
Left e
--
-- TODO : better logs?
--
katipAddContext (sl "ElapsedSeconds" (showElapsedSeconds ts)) $ do
case res of
Left e -> do
let logMsg = logStr ("RPC exited with message " <> show e :: Text)
if envLndLogErrors env
then $(logTM) ErrorS logMsg
else $(logTM) InfoS logMsg
Right _ ->
$(logTM) InfoS "RPC succeeded"
return res
grpcSync ::
( MonadIO m,
KatipContext m,
ToGrpc a gA,
FromGrpc b gB
) =>
RpcName ->
(Client -> IO client) ->
( client ->
ClientRequest 'Normal gA response2 ->
IO (ClientResult streamType gB)
) ->
--
-- TODO : newtype for timeout
--
Int ->
LndEnv ->
a ->
m (Either LndError b)
grpcSync rpcName service method timeout env req =
katipAddContext (sl "RpcName" rpcName) $ katipAddLndContext env $ do
$(logTM) InfoS "RPC is running..."
(ts, res) <- liftIO $ stopwatch $ case toGrpc req of
Left e -> return $ Left e
Right grpcReq ->
withGRPCClient (envLndGrpcConfig env) $ \client -> do
method' <- method <$> service client
rawGrpc <- method' $ ClientNormalRequest grpcReq timeout $ grpcMeta env
return $ case rawGrpc of
ClientNormalResponse grpcRes _ _ _ _ ->
fromGrpc grpcRes
ClientErrorResponse err ->
Left $ GrpcError err
ClientWriterResponse {} ->
Left $ GrpcUnexpectedResult "ClientWriterResponse"
ClientReaderResponse {} ->
Left $ GrpcUnexpectedResult "ClientReaderResponse"
ClientBiDiResponse {} ->
Left $ GrpcUnexpectedResult "ClientBiDiResponse"
--
-- TODO : better logs?
--
katipAddContext (sl "ElapsedSeconds" (showElapsedSeconds ts)) $ do
case res of
Left e -> do
let logMsg = logStr ("RPC exited with message " <> show e :: Text)
if envLndLogErrors env
then $(logTM) ErrorS logMsg
else $(logTM) InfoS logMsg
Right _ ->
$(logTM) InfoS "RPC succeeded"
return res
showElapsedSeconds :: Timespan -> Text
showElapsedSeconds = fromStrict . encodeTimespan SubsecondPrecisionAuto
genStreamHandler ::
(FromGrpc a b) =>
IO (Either GRPCIOError (Maybe b)) ->
(a -> IO ()) ->
IO ()
genStreamHandler stream handler = do
msg <- stream
case msg of
Left e -> CE.throw $ GrpcError $ ClientIOError e
Right Nothing -> CE.throw GrpcEmptyResult
Right (Just gi) -> do
case fromGrpc gi of
Right i -> handler i
Left e -> CE.throw e
genStreamHandler stream handler