/
Layer.hs
295 lines (248 loc) · 10.2 KB
/
Layer.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
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- Dummy implementation of the database-layer, using 'MVar'. This may be good
-- for testing to compare with an implementation on a real data store, or to use
-- when compiling the wallet for targets which don't have SQLite.
module Cardano.Wallet.DB.Pure.Layer
( newDBLayer
) where
import Prelude
import Cardano.Address.Derivation
( XPrv )
import Cardano.Wallet.DB
( DBLayer (..)
, ErrWalletAlreadyInitialized (..)
, ErrWalletNotInitialized (..)
)
import Cardano.Wallet.DB.Pure.Implementation
( Database
, Err (..)
, ModelOp
, emptyDatabase
, mCheckWallet
, mGetWalletId
, mInitializeWallet
, mIsStakeKeyRegistered
, mListCheckpoints
, mPutCheckpoint
, mPutDelegationCertificate
, mPutDelegationRewardBalance
, mPutPrivateKey
, mPutTxHistory
, mPutWalletMeta
, mReadCheckpoint
, mReadDelegationRewardBalance
, mReadGenesisParameters
, mReadPrivateKey
, mReadTxHistory
, mReadWalletMeta
, mRollbackTo
)
import Cardano.Wallet.Primitive.AddressDerivation
( Depth (..) )
import Cardano.Wallet.Primitive.Passphrase
( PassphraseHash )
import Cardano.Wallet.Primitive.Slotting
( TimeInterpreter )
import Cardano.Wallet.Primitive.Types
( SortOrder (..), WalletId, wholeRange )
import Cardano.Wallet.Primitive.Types.Coin
( Coin (..) )
import Cardano.Wallet.Primitive.Types.Tx
( TransactionInfo (..) )
import Control.Monad
( join, when )
import Control.Monad.IO.Unlift
( MonadUnliftIO (..) )
import Control.Monad.Trans.Except
( ExceptT (..), throwE )
import Data.Functor.Identity
( Identity (..) )
import Data.Maybe
( fromMaybe )
import UnliftIO.Exception
( Exception, throwIO )
import UnliftIO.MVar
( MVar, modifyMVar, newMVar, withMVar )
-- | Instantiate a new in-memory "database" layer that simply stores data in
-- a local MVar. Data vanishes if the software is shut down.
newDBLayer
:: forall m s k.
( MonadUnliftIO m
, MonadFail m )
=> TimeInterpreter Identity
-> m (DBLayer m s k)
newDBLayer timeInterpreter = do
lock <- newMVar ()
db <- newMVar (emptyDatabase :: Database WalletId s (k 'RootK XPrv, PassphraseHash))
let getWalletId' = ExceptT
$ alterDB errWalletNotInitialized db mGetWalletId
let
dbl = DBLayer
{-----------------------------------------------------------------------
Wallets
-----------------------------------------------------------------------}
{ initializeWallet = \pk cp meta txs gp -> ExceptT $
alterDB errWalletAlreadyExists db $
mInitializeWallet pk cp meta txs gp
, getWalletId = getWalletId'
{-----------------------------------------------------------------------
Checkpoints
-----------------------------------------------------------------------}
, walletsDB = error "MVar.walletsDB: not implemented"
, putCheckpoint = \_pk cp -> ExceptT $
alterDB errWalletNotInitialized db (mCheckWallet) >>= \case
Left err -> pure $ Left err
Right _ -> do
alterDB errWalletNotInitialized db $
mPutCheckpoint cp
, readCheckpoint = const $ join <$> readDBMaybe db mReadCheckpoint
, listCheckpoints = const
$ fromMaybe []
<$> readDBMaybe db mListCheckpoints
, rollbackTo = \_pk pt -> ExceptT $
alterDB errWalletNotInitialized db $
mRollbackTo pt
, prune = \_ _ -> error "MVar.prune: not implemented"
{-----------------------------------------------------------------------
Wallet Metadata
-----------------------------------------------------------------------}
, putWalletMeta = \_pk meta -> ExceptT $
alterDB errWalletNotInitialized db $
mPutWalletMeta meta
, readWalletMeta = const
$ fmap join
$ readDBMaybe db
$ mReadWalletMeta timeInterpreter
, putDelegationCertificate = \_pk cert sl -> ExceptT $
alterDB errWalletNotInitialized db $
mPutDelegationCertificate cert sl
, isStakeKeyRegistered =
const $ ExceptT . alterDB errWalletNotInitialized db $ mIsStakeKeyRegistered
{-----------------------------------------------------------------------
Tx History
-----------------------------------------------------------------------}
, putTxHistory = \_pk txh -> ExceptT $
alterDB errWalletNotInitialized db $
mPutTxHistory txh
, readTransactions = \_pk minWithdrawal order range mstatus _mlimit ->
fmap (fromMaybe []) $
readDBMaybe db $
mReadTxHistory
timeInterpreter
minWithdrawal
order
range
mstatus
-- TODO: shift implementation to mGetTx
, getTx = \pk tid -> do
pk' <- getWalletId'
when ( pk /= pk') $ throwE ErrWalletNotInitialized
ExceptT $ do
alterDB errWalletNotInitialized db (mCheckWallet) >>= \case
Left err -> pure $ Left err
Right _ -> do
txInfos <- fmap (fromMaybe [])
$ readDBMaybe db
$ mReadTxHistory
timeInterpreter
Nothing
Descending
wholeRange
Nothing
let txPresent (TransactionInfo{..}) = txInfoId == tid
case filter txPresent txInfos of
[] -> pure $ Right Nothing
t:_ -> pure $ Right $ Just t
{-----------------------------------------------------------------------
Keystore
-----------------------------------------------------------------------}
, putPrivateKey = \_pk prv -> ExceptT $
alterDB errWalletNotInitialized db $
mPutPrivateKey prv
, readPrivateKey = const $ join <$> readDBMaybe db mReadPrivateKey
{-----------------------------------------------------------------------
Pending Tx
-----------------------------------------------------------------------}
, addTxSubmission =
error "addTxSubmission not tested in State Machine tests"
, readLocalTxSubmissionPending =
error "readLocalTxSubmissionPending not tested in State Machine tests"
, resubmitTx =
error "resubmitTx not tested in State Machine tests"
, rollForwardTxSubmissions =
error "rollForwardTxSubmissions not tested in State Machine tests"
, removePendingOrExpiredTx = error
"removePendingOrExpiredTx not implemented in State Machine tests"
{-----------------------------------------------------------------------
Protocol Parameters
-----------------------------------------------------------------------}
, readGenesisParameters = const
$ join
<$> readDBMaybe db mReadGenesisParameters
{-----------------------------------------------------------------------
Delegation Rewards
-----------------------------------------------------------------------}
, putDelegationRewardBalance = \_pk amt -> ExceptT $
alterDB errWalletNotInitialized db (mPutDelegationRewardBalance amt)
, readDelegationRewardBalance =
const $ fromMaybe (Coin 0)
<$> readDBMaybe db mReadDelegationRewardBalance
{-----------------------------------------------------------------------
Execution
-----------------------------------------------------------------------}
, atomically = \action -> withMVar lock $ \() -> action
}
pure dbl
-- | Read the database, but return 'Nothing' if the operation fails.
readDBMaybe :: MonadUnliftIO f
=> MVar (Database WalletId s xprv)
-> ModelOp WalletId s xprv a
-> f (Maybe a)
readDBMaybe db = fmap (either (const Nothing) Just) . readDB db
-- | Apply an operation to the model database, then update the mutable variable.
-- Failures are converted to 'Err' using the provided function.
-- Failures that cannot be converted are rethrown as 'MVarDBError'.
alterDB
:: MonadUnliftIO m
=> (Err -> Maybe err)
-- ^ Error type converter
-> MVar (Database WalletId s xprv)
-- ^ The database variable
-> ModelOp WalletId s xprv a
-- ^ Operation to run on the database
-> m (Either err a)
alterDB convertErr db op = modifyMVar db (bubble . op)
where
bubble (Left e, !db') = case convertErr e of
Just e' -> pure (db', Left e')
Nothing -> throwIO $ MVarDBError e
bubble (Right a, !db') = pure (db', Right a)
-- | Run a query operation on the model database.
readDB
:: MonadUnliftIO m
=> MVar (Database WalletId s xprv)
-- ^ The database variable
-> ModelOp WalletId s xprv a
-- ^ Operation to run on the database
-> m (Either Err a)
readDB = alterDB Just -- >>= either (throwIO . MVarDBError) pure
errWalletNotInitialized :: Err -> Maybe ErrWalletNotInitialized
errWalletNotInitialized WalletNotInitialized = Just ErrWalletNotInitialized
errWalletNotInitialized _ = Nothing
errWalletAlreadyExists :: Err -> Maybe ErrWalletAlreadyInitialized
errWalletAlreadyExists WalletAlreadyInitialized
= Just ErrWalletAlreadyInitialized
errWalletAlreadyExists _ = Nothing
-- | Error which happens when model returns an unexpected value.
newtype MVarDBError = MVarDBError Err
deriving (Show)
instance Exception MVarDBError