-
Notifications
You must be signed in to change notification settings - Fork 213
/
DB.hs
306 lines (272 loc) · 10.1 KB
/
DB.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
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE RankNTypes #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- Database / Persistence layer for the pool production.
module Cardano.Pool.DB
( -- * Interface
DBLayer (..)
-- * Utilities
, determinePoolLifeCycleStatus
-- * Errors
, ErrPointAlreadyExists (..)
) where
import Prelude
import Cardano.Wallet.Primitive.Types
( BlockHeader
, CertificatePublicationTime (..)
, EpochNo (..)
, PoolId
, PoolLifeCycleStatus (..)
, PoolRegistrationCertificate
, PoolRetirementCertificate
, SlotNo (..)
, StakePoolMetadata
, StakePoolMetadataHash
, StakePoolMetadataUrl
)
import Control.Monad.Fail
( MonadFail )
import Control.Monad.IO.Class
( MonadIO )
import Control.Monad.Trans.Except
( ExceptT )
import Data.Generics.Internal.VL.Lens
( view )
import Data.Map.Strict
( Map )
import Data.Quantity
( Quantity (..) )
import Data.Word
( Word64 )
import System.Random
( StdGen )
-- | A Database interface for storing pool production in DB.
--
-- To use it, you will need the NamedFieldPuns extension and wrap operations
-- with @atomically@:
--
-- Example:
--
-- >>> :set -XNamedFieldPuns
-- >>> DBLayer{atomically,putPoolProduction} = db
-- >>> atomically $ putPoolProduction blockHeader pool
--
-- This gives you the power to also run /multiple/ operations atomically.
--
-- FIXME: Allowing 'MonadIO' to enable logging also within db transactions.
-- Ideally, we should lower than constraint to only allow logging effects and
-- not any dragons in IO.
data DBLayer m = forall stm. (MonadFail stm, MonadIO stm) => DBLayer
{ putPoolProduction
:: BlockHeader
-> PoolId
-> ExceptT ErrPointAlreadyExists stm ()
-- ^ Write for a given slot id the id of stake pool that produced a
-- a corresponding block
, readPoolProduction
:: EpochNo
-> stm (Map PoolId [BlockHeader])
-- ^ Read the all stake pools together with corresponding slot ids
-- for a given epoch.
, readTotalProduction
:: stm (Map PoolId (Quantity "block" Word64))
-- ^ Read the total pool production since the pool was first registered.
, putStakeDistribution
:: EpochNo
-> [(PoolId, Quantity "lovelace" Word64)]
-> stm ()
-- ^ Replace an existing distribution for the given epoch by the one
-- given as argument.
--
-- If there's no existing distribution, simply inserts it.
, readStakeDistribution
:: EpochNo
-> stm [(PoolId, Quantity "lovelace" Word64)]
, readPoolProductionCursor
:: Int
-> stm [BlockHeader]
-- ^ Read the latest @k@ blockheaders in ascending order. The tip will
-- be the last element in the list.
--
-- This is useful for the @NetworkLayer@ to know how far we have synced.
, readPoolLifeCycleStatus
:: PoolId
-> stm PoolLifeCycleStatus
-- ^ Read the current life cycle status of the given pool.
, putPoolRegistration
:: CertificatePublicationTime
-> PoolRegistrationCertificate
-> stm ()
-- ^ Add a mapping between stake pools and their corresponding
-- certificate. If the mapping already exists, data are replaced with
-- the latest version.
, readPoolRegistration
:: PoolId
-> stm (Maybe (CertificatePublicationTime, PoolRegistrationCertificate))
-- ^ Find the /latest/ registration certificate for the given pool,
-- together with the point in time that the certificate was added.
--
-- Note that a pool may also have other certificates associated with it
-- that affect its current lifecycle status.
--
-- See 'readPoolLifeCycleStatus' for a complete picture.
, putPoolRetirement
:: CertificatePublicationTime
-> PoolRetirementCertificate
-> stm ()
-- ^ Add a retirement certificate for a particular pool.
, readPoolRetirement
:: PoolId
-> stm (Maybe (CertificatePublicationTime, PoolRetirementCertificate))
-- ^ Find the /latest/ retirement certificate for the given pool,
-- together with the point in time that the certificate was added.
--
-- Note that a pool may also have other certificates associated with it
-- that affect its current lifecycle status.
--
-- See 'readPoolLifeCycleStatus' for a complete picture.
, unfetchedPoolMetadataRefs
:: Int
-> stm [(PoolId, StakePoolMetadataUrl, StakePoolMetadataHash)]
-- ^ Read the list of metadata remaining to fetch from remote server,
-- possibly empty if every pool already has an associated metadata
-- cached.
--
-- It returns at most `n` results, where `n` is the first argument.
, putFetchAttempt
:: (StakePoolMetadataUrl, StakePoolMetadataHash)
-> stm ()
-- ^ Store a fetch attempt for a given hash, so that it isn't retried
-- too often.
, listRegisteredPools
:: stm [PoolId]
-- ^ List the list of known pools, based on their registration
-- certificate. This list doesn't necessarily match the keys of the
-- map we would get from 'readPoolProduction' because not all registered
-- pools have necessarily produced any block yet!
, listRetiredPools
:: EpochNo
-> stm [PoolRetirementCertificate]
-- ^ List all pools with an active retirement epoch that is earlier
-- than or equal to the specified epoch.
, listPoolLifeCycleData
:: EpochNo
-> stm [PoolLifeCycleStatus]
-- ^ List the lifecycle data of all non-retired pools: pools that
-- either don't have an active retirement epoch or pools that have
-- an active retirement epoch that is later than the given epoch.
, putPoolMetadata
:: StakePoolMetadataHash
-> StakePoolMetadata
-> stm ()
-- ^ Store metadata fetched from a remote server.
, readPoolMetadata
:: stm (Map StakePoolMetadataHash StakePoolMetadata)
, readSystemSeed
:: stm StdGen
-- ^ Read the seed assigned to this particular database. The seed is
-- created with the database and is "unique" for each database. This
-- however allow to have a seed that can be used to produce consistent
-- results across requests.
, rollbackTo
:: SlotNo
-> stm ()
-- ^ Remove all entries of slot ids newer than the argument
, removePools
:: [PoolId]
-> stm ()
-- ^ Remove all data relating to the specified pools.
, removeRetiredPools
:: EpochNo
-> stm [PoolRetirementCertificate]
-- ^ Remove all pools with an active retirement epoch that is earlier
-- than or equal to the specified epoch.
--
-- Returns the retirement certificates of the pools that were removed.
--
-- See also:
--
-- - 'listRetiredPools'.
-- - 'removePools'.
, cleanDB
:: stm ()
-- ^ Clean a database
, atomically
:: forall a. stm a -> m a
-- ^ Run an operation.
--
-- For a Sqlite DB, this would be "run a query inside a transaction".
}
-- | Given the /latest/ registration and retirement certificates for a pool,
-- determine the pool's current life cycle status, based on the relative
-- order in which the certificates were published.
--
-- If two certificates are supplied, then:
--
-- * the certificates must be from the same pool.
-- * the publication times must be non-equal.
--
-- Violating either of the above pre-conditions is a programming error.
--
-- This function determines order of precedence according to the "pool
-- inference rule", as described in "A Formal Specification of the Cardano
-- Ledger":
--
-- https://hydra.iohk.io/build/3202141/download/1/ledger-spec.pdf
--
determinePoolLifeCycleStatus
:: (Ord publicationTime, Show publicationTime)
=> Maybe (publicationTime, PoolRegistrationCertificate)
-> Maybe (publicationTime, PoolRetirementCertificate)
-> PoolLifeCycleStatus
determinePoolLifeCycleStatus mReg mRet = case (mReg, mRet) of
(Nothing, _) ->
PoolNotRegistered
(Just (_, regCert), Nothing) ->
PoolRegistered regCert
(Just (regTime, regCert), Just (retTime, retCert))
| regPoolId /= retPoolId ->
differentPoolsError
| regTime > retTime ->
-- A re-registration always /supercedes/ a prior retirement.
PoolRegistered regCert
| regTime < retTime ->
-- A retirement always /augments/ the latest known registration.
PoolRegisteredAndRetired regCert retCert
| otherwise ->
timeCollisionError
where
regPoolId = view #poolId regCert
retPoolId = view #poolId retCert
differentPoolsError = error $ mconcat
[ "programming error:"
, " determinePoolLifeCycleStatus:"
, " called with certificates for different pools:"
, " pool id of registration certificate: "
, show regPoolId
, " pool id of retirement certificate: "
, show retPoolId
]
timeCollisionError = error $ mconcat
[ "programming error:"
, " determinePoolLifeCycleStatus:"
, " called with identical certificate publication times:"
, " pool id of registration certificate: "
, show regPoolId
, " pool id of retirement certificate: "
, show retPoolId
, " publication time of registration certificate: "
, show regTime
, " publication time of retirement certificate: "
, show retTime
]
-- | Forbidden operation was executed on an already existing slot
newtype ErrPointAlreadyExists
= ErrPointAlreadyExists BlockHeader -- Point already exists in db
deriving (Eq, Show)