Skip to content

Commit

Permalink
ouroboros-consensus: add newTestGuardedBlockchainTime
Browse files Browse the repository at this point in the history
  • Loading branch information
nfrisby committed Oct 13, 2019
1 parent e3a2401 commit bcdda1e
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions ouroboros-consensus/src/Ouroboros/Consensus/BlockchainTime.hs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ module Ouroboros.Consensus.BlockchainTime (
, NumSlots(..)
, TestBlockchainTime(..)
, newTestBlockchainTime
, newTestGuardedBlockchainTime
-- * Real blockchain time
, realBlockchainTime
-- * Time to slots and back again
Expand Down Expand Up @@ -178,7 +179,19 @@ newTestBlockchainTime
-> NumSlots -- ^ Number of slots
-> DiffTime -- ^ Slot duration
-> m (TestBlockchainTime m)
newTestBlockchainTime registry (NumSlots numSlots) slotLen = do
newTestBlockchainTime registry numSlots slotLen =
newTestGuardedBlockchainTime registry numSlots slotLen (\_ -> pure ())

-- | Like 'newTestBlockchainTime', but also allows other computations to delay
-- the end of each slot
newTestGuardedBlockchainTime
:: forall m. (IOLike m, HasCallStack)
=> ResourceRegistry m
-> NumSlots -- ^ Number of slots
-> DiffTime -- ^ Slot duration
-> (SlotNo -> m ()) -- ^ Blocks until slot is finished
-> m (TestBlockchainTime m)
newTestGuardedBlockchainTime registry (NumSlots numSlots) slotLen waitOn = do
slotVar <- newTVarM initVal
doneVar <- newEmptyMVar ()

Expand Down Expand Up @@ -207,10 +220,15 @@ newTestBlockchainTime registry (NumSlots numSlots) slotLen = do
loop slotVar doneVar = do
-- count off each requested slot
replicateM_ numSlots $ do
atomically $ modifyTVar slotVar $ Running . \case
Initializing -> SlotNo 0
Running slot -> succ slot
s' <- atomically $ do
st <- readTVar slotVar
let s' = case st of
Initializing -> SlotNo 0
Running s -> succ s
writeTVar slotVar (Running s')
pure s'
threadDelay slotLen
waitOn s'
-- signal the end of the final slot
putMVar doneVar ()

Expand Down

0 comments on commit bcdda1e

Please sign in to comment.