-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestApp.hs
495 lines (468 loc) · 14.5 KB
/
TestApp.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
490
491
492
493
494
495
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralisedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module LndClient.TestApp
( Env (..),
liftLndResult,
customerNodeLocation,
merchantNodeLocation,
syncWallets,
mine6,
withEnv,
setupOneChannel,
liftMaybe,
receiveInvoice,
receiveClosedChannels,
)
where
import LndClient.Data.AddInvoice as AddInvoice
( AddInvoiceRequest (..),
AddInvoiceResponse (..),
)
import LndClient.Data.Channel as Channel (Channel (..))
import LndClient.Data.ChannelPoint as ChannelPoint (ChannelPoint (..))
import LndClient.Data.CloseChannel
( ChannelCloseSummary (..),
CloseChannelRequest (..),
)
import LndClient.Data.GetInfo (GetInfoResponse (..))
import LndClient.Data.Invoice as Invoice (Invoice (..))
import LndClient.Data.ListChannels as LC (ListChannelsRequest (..))
import LndClient.Data.LndEnv
import LndClient.Data.NewAddress (NewAddressResponse (..))
import LndClient.Data.OpenChannel (OpenChannelRequest (..))
import LndClient.Data.Peer
( ConnectPeerRequest (..),
LightningAddress (..),
)
import LndClient.Data.SendPayment (SendPaymentRequest (..))
import LndClient.Data.SubscribeChannelEvents
( ChannelEventUpdate (..),
ChannelEventUpdateChannel (..),
)
import LndClient.Data.SubscribeInvoices
( SubscribeInvoicesRequest (..),
)
import LndClient.Import
import LndClient.RPC.Silent
import qualified LndGrpc as GRPC
import Network.Bitcoin as BTC (Client, getClient)
import Network.Bitcoin.BlockChain (getBlockCount)
import Network.Bitcoin.Mining (generateToAddress)
import Network.GRPC.HighLevel.Generated
liftLndResult :: (MonadIO m) => Either LndError a -> m a
liftLndResult (Right x) =
pure x
liftLndResult (Left x) =
liftIO $ fail $ "liftLndResult failed " <> show x
customerNodeLocation :: NodeLocation
customerNodeLocation = NodeLocation "localhost:9734"
merchantNodeLocation :: NodeLocation
merchantNodeLocation = NodeLocation "localhost:9735"
data Env
= Env
{ envLndMerchant :: LndEnv,
envLndCustomer :: LndEnv,
envBtcClient :: BTC.Client,
envKatipNS :: Namespace,
envKatipCTX :: LogContexts,
envKatipLE :: LogEnv,
envMerchantCQ :: TChan ((), ChannelEventUpdate),
envCustomerCQ :: TChan ((), ChannelEventUpdate),
envMerchantIQ :: TChan (SubscribeInvoicesRequest, Invoice)
}
custEnv :: LndEnv -> LndEnv
custEnv x =
x
{ envLndGrpcConfig =
(envLndGrpcConfig x)
{ clientServerPort = 11009
},
envLndCipherSeedMnemonic =
CipherSeedMnemonic
[ "absent",
"betray",
"direct",
"scheme",
"sunset",
"mechanic",
"exhaust",
"suggest",
"boy",
"arena",
"sketch",
"bone",
"news",
"south",
"way",
"survey",
"clip",
"dutch",
"depart",
"green",
"furnace",
"wire",
"wave",
"fall"
],
envLndAezeedPassphrase = Nothing
}
readEnv :: IO Env
readEnv = do
handleScribe <-
mkHandleScribeWithFormatter
bracketFormat
ColorIfTerminal
stdout
(permitItem DebugS)
V2
le <-
registerScribe "stdout" handleScribe defaultScribeSettings
=<< initLogEnv "LndClient" "test"
lndEnv <- liftIO readLndEnv
bc <- liftIO newBtcClient
mcq <- atomically newBroadcastTChan
ccq <- atomically newBroadcastTChan
miq <- atomically newBroadcastTChan
return
Env
{ envLndMerchant = lndEnv,
envLndCustomer = custEnv lndEnv,
envBtcClient = bc,
envKatipLE = le,
envKatipCTX = mempty,
envKatipNS = mempty,
envMerchantCQ = mcq,
envCustomerCQ = ccq,
envMerchantIQ = miq
}
withEnv :: (Env -> AppM IO ()) -> IO ()
withEnv f = do
env <- readEnv
let merchantEnv = envLndMerchant env
let customerEnv = envLndCustomer env
let merchantCQ = envMerchantCQ env
let customerCQ = envCustomerCQ env
runApp env $ do
--
-- Init wallets
--
void $ liftLndResult =<< lazyInitWallet merchantEnv
void $ liftLndResult =<< lazyInitWallet customerEnv
lazyMineInitialCoins env
--
-- Connect Customer to Merchant
--
GetInfoResponse merchantPubKey _ _ <-
liftLndResult =<< getInfo merchantEnv
let connectPeerRequest =
ConnectPeerRequest
{ addr =
LightningAddress
{ pubkey = merchantPubKey,
host = merchantNodeLocation
},
perm = False
}
void $
liftLndResult
=<< lazyConnectPeer customerEnv connectPeerRequest
--
-- Subscribe to events
--
void . spawnLink $
liftLndResult
=<< subscribeChannelEventsChan (pure merchantCQ) merchantEnv
void . spawnLink $
liftLndResult
=<< subscribeChannelEventsChan (pure customerCQ) customerEnv
pid <-
spawnLink $
liftLndResult
=<< subscribeInvoicesChan
(pure $ envMerchantIQ env)
merchantEnv
--
-- TODO : this is related to LND bug
-- https://github.com/lightningnetwork/lnd/issues/2469
--
(SubscribeInvoicesRequest (Just $ AddIndex 1) Nothing)
f env
$(logTM) InfoS "GONNA_TO_CANCEL_SUBSCRIPTION"
liftIO $ cancel pid
--withSpawnLink
-- ( liftLndResult
-- =<< subscribeInvoicesChan
-- (pure $ envMerchantIQ env)
-- merchantEnv
-- --
-- -- TODO : this is related to LND bug
-- -- https://github.com/lightningnetwork/lnd/issues/2469
-- --
-- (SubscribeInvoicesRequest (Just $ AddIndex 1) Nothing)
-- )
-- ( const $ do
-- f env
-- $(logTM) InfoS "GONNA_TO_TERMINATE_SUBSCRIPTION"
-- )
$(logTM) InfoS "BOOOOOOOMMMMMMMMMMMMMMMM"
void . closeScribes $ envKatipLE env
newBtcClient :: IO BTC.Client
newBtcClient =
getClient
"http://localhost:18443"
"developer"
"developer"
mine :: KatipContext m => Int -> Text -> Env -> m ()
mine x btcAddr env = do
$(logTM) InfoS $ logStr $
"Mining " <> show x <> (" blocks ..." :: Text)
void . liftIO $
generateToAddress (envBtcClient env) x (toStrict btcAddr) Nothing
liftLndResult =<< syncWallets env
mine6 :: KatipContext m => Env -> m ()
mine6 env = do
btcAddr <- customerAddress env
mine 6 btcAddr env
mine1 :: KatipContext m => Env -> m ()
mine1 env = do
btcAddr <- customerAddress env
mine 1 btcAddr env
setupOneChannel :: (KatipContext m, MonadUnliftIO m) => Env -> m ()
setupOneChannel env = do
mq <- atomically . dupTChan $ envMerchantCQ env
cq <- atomically . dupTChan $ envCustomerCQ env
--
-- Initialize closing channels procedure
--
$(logTM) InfoS "SetupOneChannel - closing channels ..."
cs <-
liftLndResult
=<< listChannels
customerEnv
(ListChannelsRequest True False False False Nothing)
let cps = Channel.channelPoint <$> cs
mapM_
( \cp ->
spawnLink $
closeChannel
--
-- TODO : investigate why it throws empty gRPC
-- response error and as consequence
-- probably it's how subscription terminates
-- when channel is completely closed
--
-- but bad thing is that callback sometimes
-- is never called, that's why it's not used there
-- we are getting TChan events instead from
-- previous opened subscription
--
(const $ return ())
(envLndMerchant env)
(CloseChannelRequest cp False Nothing Nothing Nothing)
)
cps
liftLndResult =<< receiveClosedChannels env cps mq
liftLndResult =<< receiveClosedChannels env cps cq
--
-- Open channel from Customer to Merchant
--
$(logTM) InfoS "SetupOneChannel - opening channel ..."
GetInfoResponse merchantPubKey _ _ <-
liftLndResult =<< getInfo merchantEnv
let openChannelRequest =
OpenChannelRequest
{ nodePubkey = merchantPubKey,
localFundingAmount = MoneyAmount 20000,
pushSat = Just $ MoneyAmount 1000,
targetConf = Nothing,
satPerByte = Nothing,
private = Nothing,
minHtlcMsat = Nothing,
remoteCsvDelay = Nothing,
minConfs = Nothing,
spendUnconfirmed = Nothing,
closeAddress = Nothing
}
cp <-
liftLndResult
=<< openChannelSync (envLndCustomer env) openChannelRequest
liftLndResult =<< receiveActiveChannel env cp mq
liftLndResult =<< receiveActiveChannel env cp cq
--
-- TODO : this invoice is added and settled to
-- raise invoice index to 1 to be able to receive
-- notifications about all next invoices
-- remove when LND bug will be fixed
-- https://github.com/lightningnetwork/lnd/issues/2469
--
let addInvoiceRequest =
AddInvoiceRequest
{ memo = Just "HELLO",
value = MoneyAmount 1000,
expiry = Just $ Seconds 1000
}
invoice <-
liftLndResult =<< addInvoice merchantEnv addInvoiceRequest
let sendPaymentRequest =
SendPaymentRequest
{ paymentRequest = AddInvoice.paymentRequest invoice,
amt = MoneyAmount 1000
}
void $
liftLndResult =<< sendPayment customerEnv sendPaymentRequest
$(logTM) InfoS "SetupOneChannel - finished"
where
merchantEnv = envLndMerchant env
customerEnv = envLndCustomer env
newtype AppM m a
= AppM
{ unAppM :: ReaderT Env m a
}
deriving (Functor, Applicative, Monad, MonadIO, MonadReader Env)
instance (MonadUnliftIO m) => MonadUnliftIO (AppM m) where
askUnliftIO =
AppM (fmap (\(UnliftIO run) -> UnliftIO (run . unAppM)) askUnliftIO)
withRunInIO go = AppM (withRunInIO (\k -> go (k . unAppM)))
instance (MonadIO m) => Katip (AppM m) where
getLogEnv = asks envKatipLE
localLogEnv f (AppM m) =
AppM (local (\s -> s {envKatipLE = f (envKatipLE s)}) m)
instance (MonadIO m) => KatipContext (AppM m) where
getKatipContext = asks envKatipCTX
localKatipContext f (AppM m) =
AppM (local (\s -> s {envKatipCTX = f (envKatipCTX s)}) m)
getKatipNamespace = asks envKatipNS
localKatipNamespace f (AppM m) =
AppM (local (\s -> s {envKatipNS = f (envKatipNS s)}) m)
runApp :: Env -> AppM m a -> m a
runApp env app = runReaderT (unAppM app) env
liftMaybe :: MonadIO m => String -> Maybe a -> m a
liftMaybe msg mx =
case mx of
Just x -> pure x
Nothing -> liftIO $ fail msg
receiveActiveChannel ::
( MonadUnliftIO m,
KatipContext m
) =>
Env ->
ChannelPoint ->
TChan ((), ChannelEventUpdate) ->
m (Either LndError ())
receiveActiveChannel = this 0
where
this (attempt :: Integer) env cp cq =
if attempt > 30
then pure $ Left $ LndError "receiveActiveChannel - exceeded"
else do
x <- readTChanTimeout (MicroSecondsDelay 1000000) cq
case channelEvent . snd <$> x of
Just (ChannelEventUpdateChannelActiveChannel gcp) ->
if cp == gcp
then pure $ Right ()
else mine1 env >> this (attempt + 1) env cp cq
_ ->
mine1 env >> this (attempt + 1) env cp cq
receiveClosedChannels ::
( MonadUnliftIO m,
KatipContext m
) =>
Env ->
[ChannelPoint] ->
TChan ((), ChannelEventUpdate) ->
m (Either LndError ())
receiveClosedChannels = this 0
where
this _ _ [] _ =
pure $ Right ()
this 30 _ _ _ =
pure
$ Left
$ LndError "receiveClosedChannels - exceeded"
this (attempt :: Integer) env cps0 cq = do
x0 <- readTChanTimeout (MicroSecondsDelay 1000000) cq
let x = channelEvent . snd <$> x0
$(logTM) InfoS $ logStr $
"receiveClosedChannels - got " <> (show x :: Text)
case x of
Just (ChannelEventUpdateChannelClosedChannel res) ->
case filter (/= chPoint res) cps0 of
[] -> pure $ Right ()
cps -> mine1 env >> this (attempt + 1) env cps cq
_ ->
mine1 env >> this (attempt + 1) env cps0 cq
receiveInvoice ::
( MonadUnliftIO m,
KatipContext m
) =>
RHash ->
GRPC.Invoice_InvoiceState ->
TChan (SubscribeInvoicesRequest, Invoice) ->
m (Either LndError ())
receiveInvoice rh s q = do
mx0 <- readTChanTimeout (MicroSecondsDelay 30000000) q
let mx = snd <$> mx0
$(logTM) InfoS $ logStr $
"receiveInvoice - " <> (show $ mx :: Text)
case (\x -> Invoice.rHash x == rh && Invoice.state x == s) <$> mx of
Just True -> return $ Right ()
Just False -> receiveInvoice rh s q
Nothing -> return . Left $ TChanTimeout "receiveInvoice"
customerAddress :: KatipContext m => Env -> m Text
customerAddress env = do
NewAddressResponse btcAddress <-
liftLndResult
=<< newAddress
(envLndCustomer env)
GRPC.AddressTypeWITNESS_PUBKEY_HASH
pure btcAddress
merchantAddress :: KatipContext m => Env -> m Text
merchantAddress env = do
NewAddressResponse btcAddress <-
liftLndResult
=<< newAddress
(envLndMerchant env)
GRPC.AddressTypeWITNESS_PUBKEY_HASH
pure btcAddress
lazyMineInitialCoins :: KatipContext m => Env -> m ()
lazyMineInitialCoins env = do
h <- liftIO . getBlockCount $ envBtcClient env
when (h < 102) $ do
mercAddr <- merchantAddress env
custAddr <- customerAddress env
mine 1 mercAddr env
mine 1 custAddr env
-- reward coins are spendable only after 100 blocks
mine 100 custAddr env
syncWallets ::
(KatipContext m) =>
Env ->
m (Either LndError ())
syncWallets = this 30
where
this (x :: Int) env =
if x > 0
then do
$(logTM) InfoS "Wallet sync ..."
resMerchant <- getInfo (envLndMerchant env)
resCustomer <- getInfo (envLndCustomer env)
case (,) <$> resMerchant <*> resCustomer of
Left _ ->
liftIO (delay 1000000) >> this (x - 1) env
Right (mr, cr) ->
if syncedToChain mr && syncedToChain cr
then return $ Right ()
else liftIO (delay 1000000) >> this (x - 1) env
else do
let msg = "syncWallets attempt limit exceeded"
$(logTM) ErrorS $ logStr msg
return . Left $ LndError msg