/
DB.hs
251 lines (221 loc) · 8.09 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
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RankNTypes #-}
-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- Database / Persistence layer for the pool production.
module Cardano.Pool.DB
( -- * Interface
DBLayer (..)
, CertificatePublicationTime
, PoolRegistrationStatus (..)
, determinePoolRegistrationStatus
, readPoolRegistrationStatus
-- * Errors
, ErrPointAlreadyExists (..)
) where
import Prelude
import Cardano.Wallet.Primitive.Types
( BlockHeader
, EpochNo (..)
, PoolId
, PoolRegistrationCertificate
, PoolRetirementCertificate
, SlotId (..)
, SlotInternalIndex (..)
, StakePoolMetadata
, StakePoolMetadataHash
, StakePoolMetadataUrl
)
import Control.Monad.Fail
( MonadFail )
import Control.Monad.IO.Class
( MonadIO )
import Control.Monad.Trans.Except
( ExceptT )
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.
, 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,
-- along with the point in time that the certificate was added.
, 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,
-- along with the point in time that the certificate was added.
, unfetchedPoolMetadataRefs
:: Int
-> stm [(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!
, 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
:: SlotId
-> stm ()
-- ^ Remove all entries of slot ids newer than the argument
, 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".
}
-- | Represents an abstract notion of a certificate publication time.
--
-- Certificates published at later times take precedence over certificates
-- published at earlier times.
--
type CertificatePublicationTime = (SlotId, SlotInternalIndex)
-- | Indicates the current registration status of a pool.
--
-- Use the 'readPoolRegistrationStatus' function to query the registration
-- status for a particular pool and database backend.
--
data PoolRegistrationStatus
= PoolNotRegistered
-- ^ Indicates that a pool is not registered.
| PoolRegistered
PoolRegistrationCertificate
-- ^ Indicates that a pool is registered BUT NOT marked for retirement.
-- Records the latest registration certificate.
| PoolRegisteredAndRetired
PoolRegistrationCertificate
PoolRetirementCertificate
-- ^ Indicates that a pool is registered AND ALSO marked for retirement.
-- Records the latest registration and retirement certificates.
-- | Given the latest registration and retirement certificates for a pool,
-- determine the pool's current registration status based on the relative
-- order in which the certificates were published.
determinePoolRegistrationStatus
:: Maybe (CertificatePublicationTime, PoolRegistrationCertificate)
-> Maybe (CertificatePublicationTime, PoolRetirementCertificate)
-> PoolRegistrationStatus
determinePoolRegistrationStatus = f
where
f Nothing _ =
PoolNotRegistered
f (Just (_, regCert)) Nothing =
PoolRegistered regCert
f (Just (regTime, regCert)) (Just (retTime, retCert))
| regTime > retTime =
PoolRegistered regCert
| otherwise =
PoolRegisteredAndRetired regCert retCert
-- | Reads the current registration status of a pool.
--
-- See 'PoolRegistrationStatus' for more details.
--
readPoolRegistrationStatus
:: DBLayer m
-> PoolId
-> m PoolRegistrationStatus
readPoolRegistrationStatus
DBLayer {atomically, readPoolRegistration, readPoolRetirement} poolId =
atomically $ determinePoolRegistrationStatus
<$> readPoolRegistration poolId
<*> readPoolRetirement poolId
-- | Forbidden operation was executed on an already existing slot
newtype ErrPointAlreadyExists
= ErrPointAlreadyExists BlockHeader -- Point already exists in db
deriving (Eq, Show)