-
Notifications
You must be signed in to change notification settings - Fork 86
/
PBFT.hs
483 lines (421 loc) · 18.2 KB
/
PBFT.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
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilyDependencies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module Ouroboros.Consensus.Protocol.PBFT (
PBft
, PBftLedgerView(..)
, PBftFields(..)
, PBftParams(..)
, PBftIsLeader(..)
, PBftIsLeaderOrNot(..)
, genesisKeyCoreNodeId
, nodeIdToGenesisKey
, pbftWindowSize
-- * Forging
, ConstructContextDSIGN(..)
, forgePBftFields
-- * Classes
, PBftCrypto(..)
, PBftMockCrypto
, PBftCardanoCrypto
, PBftValidateView(..)
, pbftValidateRegular
, pbftValidateBoundary
-- * Type instances
, NodeConfig(..)
-- * Exported for testing
, PBftValidationErr(..)
) where
import Codec.Serialise (Serialise (..))
import qualified Control.Exception as Exn
import Control.Monad.Except
import Crypto.Random (MonadRandom)
import Data.Bimap (Bimap)
import qualified Data.Bimap as Bimap
import Data.Proxy (Proxy (..))
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Typeable (Typeable)
import Data.Word (Word64)
import GHC.Generics (Generic)
import qualified Cardano.Chain.Common as CC.Common
import qualified Cardano.Chain.Genesis as CC.Genesis
import Cardano.Crypto.DSIGN.Class
import Cardano.Prelude (NoUnexpectedThunks)
import Ouroboros.Network.Block (BlockNo, pattern BlockPoint,
pattern GenesisPoint, HasHeader (..), HeaderHash, Point,
SlotNo (..))
import Ouroboros.Network.Point (WithOrigin (..))
import Ouroboros.Consensus.Block
import Ouroboros.Consensus.BlockchainTime
import Ouroboros.Consensus.Crypto.DSIGN.Cardano
import Ouroboros.Consensus.Ledger.Byron.Config
import Ouroboros.Consensus.Node.ProtocolInfo.Abstract
import Ouroboros.Consensus.NodeId (CoreNodeId (..))
import Ouroboros.Consensus.Protocol.Abstract
import Ouroboros.Consensus.Protocol.PBFT.ChainState (PBftChainState)
import qualified Ouroboros.Consensus.Protocol.PBFT.ChainState as CS
import Ouroboros.Consensus.Protocol.PBFT.ChainState.HeaderHashBytes
(HeaderHashBytes, headerHashBytes)
import Ouroboros.Consensus.Protocol.PBFT.Crypto
import Ouroboros.Consensus.Protocol.Signed
import Ouroboros.Consensus.Util.Condense
import Ouroboros.Consensus.Util.Orphans ()
{-------------------------------------------------------------------------------
Fields that PBFT requires present in a block
-------------------------------------------------------------------------------}
data PBftFields c toSign = PBftFields {
-- | The actual issuer of a block
pbftIssuer :: VerKeyDSIGN (PBftDSIGN c)
-- | The stakeholder on whose behalf the block is being issued
, pbftGenKey :: VerKeyDSIGN (PBftDSIGN c)
, pbftSignature :: SignedDSIGN (PBftDSIGN c) toSign
}
deriving (Generic)
deriving instance PBftCrypto c => Show (PBftFields c toSign)
deriving instance PBftCrypto c => Eq (PBftFields c toSign)
instance (PBftCrypto c, Typeable toSign) => NoUnexpectedThunks (PBftFields c toSign)
-- use generic instance
-- | Part of the header that we validate
data PBftValidateView c =
-- | Regular block
--
-- Regular blocks are signed, and so we need to validate them.
-- We also need to know the slot number of the block
forall signed. Signable (PBftDSIGN c) signed
=> PBftValidateRegular
SlotNo
(PBftFields c signed)
signed
(ContextDSIGN (PBftDSIGN c))
-- | Boundary block (EBB)
--
-- EBBs are not signed but do affect the chainstate.
| PBftValidateBoundary SlotNo HeaderHashBytes
-- | Convenience constructor for 'PBftValidateView' for regular blocks
pbftValidateRegular :: ( HasHeader hdr
, SignedHeader hdr
, Signable (PBftDSIGN c) (Signed hdr)
)
=> ContextDSIGN (PBftDSIGN c)
-> (hdr -> PBftFields c (Signed hdr))
-> (hdr -> PBftValidateView c)
pbftValidateRegular contextDSIGN getFields hdr =
PBftValidateRegular
(blockSlot hdr)
(getFields hdr)
(headerSigned hdr)
contextDSIGN
-- | Convenience constructor for 'PBftValidateView' for boundary blocks
pbftValidateBoundary :: forall hdr c. (
HasHeader hdr
, Serialise (HeaderHash hdr)
)
=> hdr -> PBftValidateView c
pbftValidateBoundary hdr =
PBftValidateBoundary
(blockSlot hdr)
(headerHashBytes (Proxy @hdr) (blockHash hdr))
-- | Part of the header required for chain selection
--
-- EBBs share a block number with regular blocks, and so for chain selection
-- we need to know if a block is an EBB or not (because a chain ending on an
-- EBB with a particular block number is longer than a chain on a regular
-- block with that same block number).
type PBftSelectView = (BlockNo, IsEBB)
{-------------------------------------------------------------------------------
Block forging
-------------------------------------------------------------------------------}
class ConstructContextDSIGN cfg c where
constructContextDSIGN :: proxy c
-> cfg
-> VerKeyDSIGN (PBftDSIGN c)
-> ContextDSIGN (PBftDSIGN c)
instance ConstructContextDSIGN ext PBftMockCrypto where
constructContextDSIGN _p _cfg _genKey = ()
instance ConstructContextDSIGN ByronConfig PBftCardanoCrypto where
constructContextDSIGN _p cfg genKey = (cfg, genKey)
forgePBftFields :: forall m c toSign. (
MonadRandom m
, PBftCrypto c
, Signable (PBftDSIGN c) toSign
)
=> (VerKeyDSIGN (PBftDSIGN c) -> ContextDSIGN (PBftDSIGN c))
-- ^ Construct DSIGN context
-- See 'constructContextDSIGN' for a suitable argument.
-> IsLeader (PBft c)
-> toSign
-> m (PBftFields c toSign)
forgePBftFields contextDSIGN PBftIsLeader{..} toSign = do
signature <- signedDSIGN ctxtDSIGN toSign pbftSignKey
return $ Exn.assert (issuer == deriveVerKeyDSIGN pbftSignKey) $ PBftFields {
pbftIssuer = issuer
, pbftGenKey = genKey
, pbftSignature = signature
}
where
issuer = dlgCertDlgVerKey pbftDlgCert
genKey = dlgCertGenVerKey pbftDlgCert
ctxtDSIGN = contextDSIGN genKey
{-------------------------------------------------------------------------------
Information PBFT requires from the ledger
-------------------------------------------------------------------------------}
data PBftLedgerView c = PBftLedgerView {
-- | ProtocolParameters: map from genesis to delegate keys.
pbftDelegates :: !(Bimap (PBftVerKeyHash c) (PBftVerKeyHash c))
}
deriving (Generic)
deriving instance PBftCrypto c => NoUnexpectedThunks (PBftLedgerView c)
-- use generic instance
deriving instance Eq (PBftVerKeyHash c) => Eq (PBftLedgerView c)
deriving instance Show (PBftVerKeyHash c) => Show (PBftLedgerView c)
instance (Serialise (PBftVerKeyHash c), Ord (PBftVerKeyHash c))
=> Serialise (PBftLedgerView c) where
encode (PBftLedgerView ds) = encode (Bimap.toList ds)
decode = PBftLedgerView . Bimap.fromList <$> decode
{-------------------------------------------------------------------------------
Protocol proper
-------------------------------------------------------------------------------}
-- | Permissive BFT
--
-- As defined in https://hydra.iohk.io/job/Cardano/cardano-ledger-specs/byronChainSpec/latest/download-by-type/doc-pdf/blockchain-spec
data PBft c
-- | Protocol parameters
data PBftParams = PBftParams {
-- | Security parameter
--
-- Although the protocol proper does not have such a security parameter,
-- we insist on it.
pbftSecurityParam :: !SecurityParam
-- | Number of core nodes
, pbftNumNodes :: !NumCoreNodes
-- | Signature threshold
--
-- This bounds the proportion of the latest 'pbftSecurityParam'-many
-- blocks which is allowed to be signed by any single key. The protocol
-- proper is parameterized over the size of this window of recent blocks,
-- but this implementation follows the specification by fixing that
-- parameter to the ambient security parameter @k@.
, pbftSignatureThreshold :: !Double
-- | Slot length
, pbftSlotLength :: !SlotLength
}
deriving (Generic, NoUnexpectedThunks, Show)
-- | If we are a core node (i.e. a block producing node) we know which core
-- node we are, and we have the operational key pair and delegation certificate.
--
data PBftIsLeader c = PBftIsLeader {
pbftCoreNodeId :: !CoreNodeId
, pbftSignKey :: !(SignKeyDSIGN (PBftDSIGN c))
, pbftDlgCert :: !(PBftDelegationCert c)
}
deriving (Generic)
instance PBftCrypto c => NoUnexpectedThunks (PBftIsLeader c)
-- use generic instance
data PBftIsLeaderOrNot c
= PBftIsALeader !(PBftIsLeader c)
| PBftIsNotALeader
deriving (Generic, NoUnexpectedThunks)
-- | (Static) node configuration
data instance NodeConfig (PBft c) = PBftNodeConfig {
pbftParams :: !PBftParams
, pbftIsLeader :: !(PBftIsLeaderOrNot c)
}
deriving (Generic, NoUnexpectedThunks)
instance PBftCrypto c => OuroborosTag (PBft c) where
type ValidationErr (PBft c) = PBftValidationErr c
type ValidateView (PBft c) = PBftValidateView c
type SelectView (PBft c) = PBftSelectView
type NodeState (PBft c) = ()
-- | We require two things from the ledger state:
--
-- - Protocol parameters, for the signature window and threshold.
-- - The delegation map.
type LedgerView (PBft c) = PBftLedgerView c
type IsLeader (PBft c) = PBftIsLeader c
type ChainState (PBft c) = PBftChainState c
protocolSecurityParam = pbftSecurityParam . pbftParams
protocolSlotLengths = singletonSlotLengths . pbftSlotLength . pbftParams
checkIsLeader PBftNodeConfig{pbftIsLeader, pbftParams} (SlotNo n) _l _cs =
case pbftIsLeader of
PBftIsNotALeader -> return Nothing
-- We are the slot leader based on our node index, and the current
-- slot number. Our node index depends which genesis key has delegated
-- to us, see 'genesisKeyCoreNodeId'.
PBftIsALeader credentials
| n `mod` numCoreNodes == fromIntegral i -> return (Just credentials)
| otherwise -> return Nothing
where
PBftIsLeader{pbftCoreNodeId = CoreNodeId i} = credentials
PBftParams{pbftNumNodes = NumCoreNodes numCoreNodes} = pbftParams
applyChainState cfg@PBftNodeConfig{..} lv@(PBftLedgerView dms) toValidate chainState =
case toValidate of
PBftValidateBoundary slot hash ->
return $! appendEBB cfg params slot hash chainState
PBftValidateRegular slot PBftFields{..} signed contextDSIGN -> do
-- Check that the issuer signature verifies, and that it's a delegate of a
-- genesis key, and that genesis key hasn't voted too many times.
case verifySignedDSIGN
contextDSIGN
pbftIssuer
signed
pbftSignature of
Right () -> return ()
Left err -> throwError $ PBftInvalidSignature (Text.pack err)
-- FIXME confirm that non-strict inequality is ok in general.
-- It's here because EBBs have the same slot as the first block of their
-- epoch.
unless (At slot >= CS.lastSignedSlot chainState)
$ throwError PBftInvalidSlot
case Bimap.lookupR (hashVerKey pbftIssuer) dms of
Nothing -> throwError $ PBftNotGenesisDelegate (hashVerKey pbftIssuer) lv
Just gk -> do
let chainState' = append cfg params (slot, gk) chainState
case exceedsThreshold params chainState' gk of
Nothing -> return $! chainState'
Just n -> throwError $ PBftExceededSignThreshold gk n
where
params = pbftWindowParams cfg
rewindChainState cfg = flip (rewind cfg params)
where
params = pbftWindowParams cfg
compareCandidates PBftNodeConfig{..} (lBlockNo, lIsEBB) (rBlockNo, rIsEBB) =
-- Prefer the highest block number, as it is a proxy for chain length
case lBlockNo `compare` rBlockNo of
LT -> LT
GT -> GT
-- If the block numbers are the same, check if one of them is an EBB.
-- An EBB has the same block number as the block before it, so the
-- chain ending with an EBB is actually longer than the one ending
-- with a regular block.
EQ -> score lIsEBB `compare` score rIsEBB
where
score :: IsEBB -> Int
score IsEBB = 1
score IsNotEBB = 0
{-------------------------------------------------------------------------------
Internal: thin wrapper on top of 'PBftChainState'
-------------------------------------------------------------------------------}
-- | Parameters for the window check
data PBftWindowParams = PBftWindowParams {
-- | Window size
windowSize :: CS.WindowSize
-- | Threshold (maximum number of slots anyone is allowed to sign)
, threshold :: Word64
}
-- | Compute window check parameters from the node config
pbftWindowParams :: NodeConfig (PBft c) -> PBftWindowParams
pbftWindowParams PBftNodeConfig{..} = PBftWindowParams {
windowSize = winSize
, threshold = floor $ pbftSignatureThreshold * fromIntegral winSize
}
where
PBftParams{..} = pbftParams
winSize = pbftWindowSize pbftSecurityParam
-- | Window size used by PBFT
--
-- We set the window size to be equal to k.
pbftWindowSize :: SecurityParam -> CS.WindowSize
pbftWindowSize (SecurityParam k) = CS.WindowSize k
-- | Does the number of blocks signed by this key exceed the threshold?
--
-- Returns @Just@ the number of blocks signed if exceeded.
exceedsThreshold :: PBftCrypto c
=> PBftWindowParams
-> PBftChainState c -> PBftVerKeyHash c -> Maybe Word64
exceedsThreshold PBftWindowParams{..} st gk =
if numSigned > threshold
then Just numSigned
else Nothing
where
numSigned = CS.countSignedBy st gk
append :: PBftCrypto c
=> NodeConfig (PBft c)
-> PBftWindowParams
-> (SlotNo, PBftVerKeyHash c)
-> PBftChainState c -> PBftChainState c
append PBftNodeConfig{..} PBftWindowParams{..} =
CS.append pbftSecurityParam windowSize . uncurry CS.PBftSigner
where
PBftParams{..} = pbftParams
appendEBB :: forall c. PBftCrypto c
=> NodeConfig (PBft c)
-> PBftWindowParams
-> SlotNo
-> HeaderHashBytes
-> PBftChainState c -> PBftChainState c
appendEBB PBftNodeConfig{..} PBftWindowParams{..} =
CS.appendEBB pbftSecurityParam windowSize
where
PBftParams{..} = pbftParams
rewind :: forall c hdr. (PBftCrypto c, Serialise (HeaderHash hdr))
=> NodeConfig (PBft c)
-> PBftWindowParams
-> Point hdr
-> PBftChainState c
-> Maybe (PBftChainState c)
rewind PBftNodeConfig{..} PBftWindowParams{..} p =
CS.rewind pbftSecurityParam windowSize p'
where
PBftParams{..} = pbftParams
p' = case p of
GenesisPoint -> Origin
BlockPoint s hh -> At (s, headerHashBytes (Proxy :: Proxy hdr) hh)
{-------------------------------------------------------------------------------
PBFT node order
-------------------------------------------------------------------------------}
-- | Determine the 'CoreNodeId' for a code node, based on the genesis key it
-- will sign blocks on behalf of.
--
-- In PBFT, the 'CoreNodeId' index is determined by the 0-based position in
-- the sort order of the genesis key hashes.
genesisKeyCoreNodeId :: CC.Genesis.Config
-> VerKeyDSIGN CardanoDSIGN
-- ^ The genesis verification key
-> Maybe CoreNodeId
genesisKeyCoreNodeId gc vkey =
CoreNodeId . fromIntegral <$>
Set.lookupIndex (hashVerKey vkey) (genesisKeyHashes gc)
-- | Inverse of 'genesisKeyCoreNodeId'
nodeIdToGenesisKey :: CC.Genesis.Config
-> CoreNodeId
-> Maybe CC.Common.KeyHash
nodeIdToGenesisKey gc (CoreNodeId nid) = do
guard $ nid < fromIntegral (Set.size (genesisKeyHashes gc))
return $ Set.elemAt (fromIntegral nid) (genesisKeyHashes gc)
genesisKeyHashes :: CC.Genesis.Config -> Set CC.Common.KeyHash
genesisKeyHashes = CC.Genesis.unGenesisKeyHashes
. CC.Genesis.configGenesisKeyHashes
{-------------------------------------------------------------------------------
PBFT specific types
-------------------------------------------------------------------------------}
-- | NOTE: this type is stored in the state, so it must be in normal form to
-- avoid space leaks.
data PBftValidationErr c
= PBftInvalidSignature !Text
| PBftNotGenesisDelegate !(PBftVerKeyHash c) !(PBftLedgerView c)
-- | We record how many slots this key signed
| PBftExceededSignThreshold !(PBftVerKeyHash c) !Word64
| PBftInvalidSlot
deriving (Generic, NoUnexpectedThunks)
deriving instance PBftCrypto c => Show (PBftValidationErr c)
deriving instance PBftCrypto c => Eq (PBftValidationErr c)
{-------------------------------------------------------------------------------
Condense
-------------------------------------------------------------------------------}
instance PBftCrypto c => Condense (PBftFields c toSign) where
condense PBftFields{..} = condense pbftSignature