forked from Concordium/concordium-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExternal.hs
1310 lines (1209 loc) · 61.2 KB
/
External.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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Concordium.External where
import Control.Exception
import Control.Monad
import qualified Data.Aeson as AE
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Unsafe as BS
import Data.Int
import qualified Data.Serialize as S
import Data.Word
import Foreign
import Foreign.C
import System.Directory
import System.FilePath
import Text.Read (readMaybe)
import qualified Concordium.Crypto.SHA256 as SHA256
import Concordium.ID.Types
import Concordium.Logger
import Concordium.Types
import qualified Data.FixedByteString as FBS
import Concordium.Afgjort.Finalize.Types (FinalizationInstance (FinalizationInstance))
import Concordium.Birk.Bake
import Concordium.Constants.Time (defaultEarlyBlockThreshold, defaultMaxBakingDelay)
import Concordium.Crypto.ByteStringHelpers
import Concordium.GlobalState
import Concordium.GlobalState.Persistent.LMDB (addDatabaseVersion)
import Concordium.GlobalState.Persistent.TreeState (InitException (..))
import Concordium.MultiVersion (
Callbacks (..),
CatchUpConfiguration (..),
DiskStateConfig (..),
MVR (..),
MultiVersionConfiguration (..),
MultiVersionRunner (..),
TransactionDBConfig (..),
makeMultiVersionRunner,
)
import qualified Concordium.MultiVersion as MV
import Concordium.Queries (BakerStatus (..))
import qualified Concordium.Queries as Q
import Concordium.Scheduler.Types
import Concordium.Skov (
BufferedFinalization (..),
MessageType (..),
NoFinalization (..),
UpdateResult (..),
)
import Concordium.TimerMonad (ThreadTimer)
-- |A 'PeerID' identifies peer at the p2p layer.
type PeerID = Word64
-- * Callbacks
-- ** Logging
-- | External function that logs in Rust a message using standard Rust log output
--
-- The first argument represents the Identifier which shows in which module the message has been
-- emitted.
-- The current mapping is as follows:
--
-- +----------+-----------+
-- |Identifier|Module |
-- +==========+===========+
-- |0 |Runner |
-- +----------+-----------+
-- |1 |Afgjort |
-- +----------+-----------+
-- |2 |Birk |
-- +----------+-----------+
-- |3 |Crypto |
-- +----------+-----------+
-- |4 |Kontrol |
-- +----------+-----------+
-- |5 |Skov |
-- +----------+-----------+
-- |6 |Baker |
-- +----------+-----------+
-- |7 |External |
-- +----------+-----------+
-- |8 |GlobalState|
-- +----------+-----------+
-- |9 |BlockState |
-- +----------+-----------+
-- |10 |TreeState |
-- +----------+-----------+
-- |11 |LMDB |
-- +----------+-----------+
-- |12 |Scheduler |
-- +----------+-----------+
--
-- The second argument represents the Log Level which is interpreted as follows:
--
-- +-----+--------+
-- |Value|LogLevel|
-- +=====+========+
-- |1 |Error |
-- +-----+--------+
-- |2 |Warning |
-- +-----+--------+
-- |3 |Info |
-- +-----+--------+
-- |4 |Debug |
-- +-----+--------+
-- |Other|Trace |
-- +-----+--------+
--
-- The third argument is the log message that is emitted.
type LogCallback = Word8 -> Word8 -> CString -> IO ()
-- |FFI wrapper for calling a 'LogCallback' function.
foreign import ccall "dynamic" callLogCallback :: FunPtr LogCallback -> LogCallback
-- |Wrap a log callback as a log method, only logging events with loglevel <= given log level.
toLogMethod :: Word8 -> FunPtr LogCallback -> LogMethod IO
toLogMethod maxLogLevel logCallbackPtr = le
where
logCallback = callLogCallback logCallbackPtr
le src lvl =
if logLevelId lvl <= maxLogLevel -- only log if log level less than maximum requested
then \msg ->
BS.useAsCString (BS.pack msg) $
logCallback (logSourceId src) (logLevelId lvl)
else \_ -> return ()
-- ** Broadcast
-- |Callback for broadcasting a message to the network.
-- The first argument indicates the message type.
-- The second argument is the genesis index.
-- The third argument is a pointer to the data to broadcast.
-- The fourth argument is the length of the data in bytes.
type BroadcastCallback = Int64 -> GenesisIndex -> CString -> Int64 -> IO ()
-- |FFI wrapper for invoking a 'BroadcastCallback' function.
foreign import ccall "dynamic" invokeBroadcastCallback :: FunPtr BroadcastCallback -> BroadcastCallback
-- |Helper for invoking a 'BroadcastCallback' function.
callBroadcastCallback :: FunPtr BroadcastCallback -> MessageType -> GenesisIndex -> BS.ByteString -> IO ()
callBroadcastCallback cbk mt gi bs = BS.useAsCStringLen bs $ \(cdata, clen) ->
invokeBroadcastCallback cbk mti gi cdata (fromIntegral clen)
where
mti = case mt of
MessageBlock -> 0
MessageFinalization -> 1
MessageFinalizationRecord -> 2
MessageCatchUpStatus -> 3
-- ** Direct-to-peer message
-- |Callback for sending a message to a peer.
-- The first argument is the peer to send to.
-- The second argument indicates the message type.
-- The third argument is a pointer to the data to broadcast.
-- The fourth argument is the length of the data in bytes.
type DirectMessageCallback = PeerID -> Int64 -> GenesisIndex -> CString -> Int64 -> IO ()
-- |FFI wrapper for invoking a 'DirectMessageCallback' function.
foreign import ccall "dynamic" invokeDirectMessageCallback :: FunPtr DirectMessageCallback -> DirectMessageCallback
-- |Helper for invoking a 'DirectMessageCallback' function.
callDirectMessageCallback :: FunPtr DirectMessageCallback -> PeerID -> MessageType -> GenesisIndex -> BS.ByteString -> IO ()
callDirectMessageCallback cbk peer mt genIndex bs = BS.useAsCStringLen bs $ \(cdata, clen) ->
invokeDirectMessageCallback cbk peer mti genIndex cdata (fromIntegral clen)
where
mti = case mt of
MessageBlock -> 0
MessageFinalization -> 1
MessageFinalizationRecord -> 2
MessageCatchUpStatus -> 3
-- ** Catch-up status
-- |Callback for direct-sending a catch-up status message to all (non-pending) peers.
-- The first argument is the genesis index.
-- The first argument is a pointer to the data, which must be a catch-up
-- status message. The second argument is the length of the data in bytes.
type CatchUpStatusCallback = GenesisIndex -> CString -> Int64 -> IO ()
-- |FFI wrapper for invoking a 'CatchUpStatusCallback' function.
foreign import ccall "dynamic" invokeCatchUpStatusCallback :: FunPtr CatchUpStatusCallback -> CatchUpStatusCallback
-- |Helper for invoking a 'CatchUpStatusCallback' function.
callCatchUpStatusCallback :: FunPtr CatchUpStatusCallback -> GenesisIndex -> BS.ByteString -> IO ()
callCatchUpStatusCallback cbk gi bs = BS.useAsCStringLen bs $ \(cdata, clen) ->
invokeCatchUpStatusCallback cbk gi cdata (fromIntegral clen)
-- ** Regenesis
-- |Callback to signal that a new genesis block has occurred.
-- The argument is the block hash as a 32-byte string.
type RegenesisCallback = Ptr RegenesisArc -> Ptr Word8 -> IO ()
-- |FFI wrapper for invoking a 'RegenesisCallback' function.
foreign import ccall "dynamic" invokeRegenesisCallback :: FunPtr RegenesisCallback -> RegenesisCallback
-- |Helper for invoking a 'RegenesisCallback' function.
callRegenesisCallback :: FunPtr RegenesisCallback -> RegenesisRef -> Maybe BlockHash -> IO ()
callRegenesisCallback cb rgRef (Just (BlockHash (SHA256.Hash bh))) = withForeignPtr rgRef $ \rg ->
FBS.withPtrReadOnly bh $ \ptr ->
invokeRegenesisCallback cb rg ptr
callRegenesisCallback cb rgRef Nothing = withForeignPtr rgRef $ \rg ->
invokeRegenesisCallback cb rg nullPtr
-- |Abstract type representing the rust Arc object used for tracking genesis blocks.
-- A pointer of this type is passed to consensus at start up and must be passed to each call of
-- the regenesis callback.
data RegenesisArc
-- |A reference that must be passed when calling the regenesis callback.
-- This is a 'ForeignPtr', so a finalizer that disposes of the pointer is attached.
type RegenesisRef = ForeignPtr RegenesisArc
-- |A function pointer used for freeing the regenesis reference.
type RegenesisFree = FinalizerPtr RegenesisArc
-- |Construct a 'RegenesisRef' from a finalizer and a raw pointer.
makeRegenesisRef :: RegenesisFree -> Ptr RegenesisArc -> IO RegenesisRef
makeRegenesisRef = newForeignPtr
-- * Consensus operations
-- |A 'ConsensusRunner' is a 'MultiVersionRunner' with an existentially quantified global state
-- and finalization configuration. A 'StablePtr' to a consensus runner is used as the reference
-- to the consensus that is passed over the FFI.
--
-- The use of the existential type is convenient, since it avoids or defers case analysis, while
-- allowing for multiple possible configurations.
data ConsensusRunner = forall gsconf finconf. ConsensusRunner (MultiVersionRunner gsconf finconf)
-- |Result of starting consensus
data StartResult
= StartSuccess
| StartGenesisFailure
| StartBakerIdentityFailure
| StartIOException
| StartInitException InitException
-- |Convert a 'StartResult' to an 'Int64'.
toStartResult :: StartResult -> Int64
toStartResult =
\case
StartSuccess -> 0
StartGenesisFailure -> 1
StartBakerIdentityFailure -> 2
StartIOException -> 3
StartInitException ie ->
case ie of
BlockStatePathDir -> 4
BlockStatePermissionError -> 5
TreeStatePermissionError -> 6
DatabaseOpeningError _ -> 7
GenesisBlockNotInDataBaseError -> 8
GenesisBlockIncorrect _ -> 9
DatabaseInvariantViolation _ -> 10
IncorrectDatabaseVersion _ -> 11
-- |Catch exceptions which may occur at start up and return an appropriate exit code.
handleStartExceptions :: LogMethod IO -> IO StartResult -> IO Int64
handleStartExceptions logM c =
toStartResult
<$> c
`catches` [ Handler handleIOError,
Handler handleInitException,
Handler handleGlobalStateInitException
]
where
handleIOError (ex :: IOError) = StartIOException <$ logM External LLError (displayException ex)
handleInitException ex = StartInitException ex <$ logM External LLError (displayException ex)
handleGlobalStateInitException (InvalidGenesisData _) = return StartGenesisFailure
-- |Migrate a legacy global state, if necessary.
migrateGlobalState :: FilePath -> LogMethod IO -> IO ()
migrateGlobalState dbPath logM = do
blockStateExists <- doesPathExist $ dbPath </> "blockstate-0" <.> "dat"
treeStateExists <- doesPathExist $ dbPath </> "treestate-0"
-- Only attempt migration when neither state exists
unless (blockStateExists || treeStateExists) $ do
oldBlockStateExists <- doesFileExist $ dbPath </> "blockstate" <.> "dat"
oldTreeStateExists <- doesDirectoryExist $ dbPath </> "treestate"
case (oldBlockStateExists, oldTreeStateExists) of
(True, True) -> do
logM GlobalState LLInfo "Migrating global state from legacy version."
renameFile (dbPath </> "blockstate" <.> "dat") (dbPath </> "blockstate-0" <.> "dat")
renameDirectory (dbPath </> "treestate") (dbPath </> "treestate-0")
runLoggerT (addDatabaseVersion (dbPath </> "treestate-0")) logM
logM GlobalState LLInfo "Migration complete."
(True, False) -> logM GlobalState LLWarning "Cannot migrate legacy database as 'treestate' is absent."
(False, True) -> logM GlobalState LLWarning "Cannot migrate legacy database as 'blockstate.dat' is absent."
_ -> return ()
-- |Start up an instance of Skov without starting the baker thread.
-- If an error occurs starting Skov, the error will be logged and
-- a null pointer will be returned.
startConsensus ::
-- |Maximum block size.
Word64 ->
-- |Block construction timeout in milliseconds
Word64 ->
-- |The amount of time in the future a transaction's expiry can be. In seconds.
Word64 ->
-- |Insertions before purging of transactions
Word64 ->
-- |Time in seconds during which a transaction can't be purged
Word64 ->
-- |Number of seconds between transaction table purging runs
Word64 ->
-- |Serialized genesis data (c string + len)
CString ->
Int64 ->
-- |Serialized baker identity (c string + len)
CString ->
Int64 ->
-- |Handler for generated messages
FunPtr BroadcastCallback ->
-- |Handler for sending catch-up status to peers
FunPtr CatchUpStatusCallback ->
-- |Regenesis object
Ptr RegenesisArc ->
-- |Finalizer for the regenesis object
RegenesisFree ->
-- |Handler for notifying the node of new regenesis blocks
FunPtr RegenesisCallback ->
-- |Maximum log level (inclusive) (0 to disable logging).
Word8 ->
-- |Handler for log events
FunPtr LogCallback ->
-- |FilePath for the AppData directory
CString ->
-- |Length of AppData path
Int64 ->
-- |Database connection string. If length is 0 don't do logging.
CString ->
-- |Length of database connection string.
Int64 ->
-- |Pointer to receive the pointer to the 'ConsensusRunner'.
Ptr (StablePtr ConsensusRunner) ->
IO Int64
startConsensus
maxBlock
blockConstructionTimeout
maxTimeToExpiry
insertionsBeforePurge
transactionsKeepAlive
transactionsPurgingDelay
gdataC
gdataLenC
bidC
bidLenC
bcbk
cucbk
regenesisPtr
regenesisFree
regenesisCB
maxLogLevel
lcbk
appDataC
appDataLenC
connStringPtr
connStringLen
runnerPtrPtr = handleStartExceptions logM $
decodeGenesis $ \genesisData -> decodeBakerIdentity $ \bakerIdentity -> do
-- Get the data directory
appDataPath <- peekCStringLen (appDataC, fromIntegral appDataLenC)
-- Do globalstate migration if necessary
migrateGlobalState appDataPath logM
let mvcStateConfig = DiskStateConfig appDataPath
let mvcFinalizationConfig =
BufferedFinalization
( FinalizationInstance
(bakerSignKey bakerIdentity)
(bakerElectionKey bakerIdentity)
(bakerAggregationKey bakerIdentity)
)
regenesisRef <- makeRegenesisRef regenesisFree regenesisPtr
-- Callbacks
let callbacks =
Callbacks
{ broadcastBlock = callBroadcastCallback bcbk MessageBlock,
broadcastFinalizationMessage = callBroadcastCallback bcbk MessageFinalization,
broadcastFinalizationRecord = callBroadcastCallback bcbk MessageFinalizationRecord,
notifyCatchUpStatus = callCatchUpStatusCallback cucbk,
notifyRegenesis = callRegenesisCallback regenesisCB regenesisRef
}
runner <-
if connStringLen /= 0
then do
mvcTXLogConfig <-
TransactionDBConfig
<$> BS.packCStringLen (connStringPtr, fromIntegral connStringLen)
let config ::
MultiVersionConfiguration
DiskTreeDiskBlockWithLogConfig
(BufferedFinalization ThreadTimer)
config = MultiVersionConfiguration{..}
ConsensusRunner
<$> makeMultiVersionRunner config callbacks (Just bakerIdentity) logM genesisData
else do
let config ::
MultiVersionConfiguration
DiskTreeDiskBlockConfig
(BufferedFinalization ThreadTimer)
config = MultiVersionConfiguration{mvcTXLogConfig = (), ..}
ConsensusRunner
<$> makeMultiVersionRunner config callbacks (Just bakerIdentity) logM genesisData
poke runnerPtrPtr =<< newStablePtr runner
return StartSuccess
where
-- Decode genesis data
decodeGenesis cont = do
genesisBS <- BS.packCStringLen (gdataC, fromIntegral gdataLenC)
case S.runGet getPVGenesisData genesisBS of
Left err -> do
logM External LLError $ "Failed to decode genesis data: " ++ err
return StartGenesisFailure
Right genData -> cont genData
-- Decode the baker identity
decodeBakerIdentity cont = do
bakerInfoBS <- BS.packCStringLen (bidC, fromIntegral bidLenC)
case AE.eitherDecodeStrict bakerInfoBS of
Left err -> do
logM External LLError $ "Failed to decode baker identity data: " ++ err
return StartBakerIdentityFailure
Right bakerIdentity -> cont (bakerIdentity :: BakerIdentity)
-- Log method
logM = toLogMethod maxLogLevel lcbk
-- Runtime parameters
mvcRuntimeParameters =
RuntimeParameters
{ rpBlockSize = fromIntegral maxBlock,
rpBlockTimeout = fromIntegral blockConstructionTimeout,
rpEarlyBlockThreshold = defaultEarlyBlockThreshold,
rpMaxBakingDelay = defaultMaxBakingDelay,
rpInsertionsBeforeTransactionPurge = fromIntegral insertionsBeforePurge,
rpTransactionsKeepAliveTime = TransactionTime transactionsKeepAlive,
rpTransactionsPurgingDelay = fromIntegral transactionsPurgingDelay,
rpMaxTimeToExpiry = fromIntegral maxTimeToExpiry
}
-- |Start up an instance of Skov without starting the baker thread.
-- If an error occurs starting Skov, the error will be logged and
-- a null pointer will be returned.
startConsensusPassive ::
-- |Maximum block size.
Word64 ->
-- |Block construction timeout in milliseconds
Word64 ->
-- |The amount of time in the future a transaction's expiry can be. In seconds.
Word64 ->
-- |Insertions before purging of transactions
Word64 ->
-- |Time in seconds during which a transaction can't be purged
Word64 ->
-- |Number of seconds between transaction table purging runs
Word64 ->
-- |Serialized genesis data (c string + len)
CString ->
Int64 ->
-- |Handler for sending catch-up status to peers
FunPtr CatchUpStatusCallback ->
-- |Regenesis object
Ptr RegenesisArc ->
-- |Finalizer for the regenesis object
RegenesisFree ->
-- |Handler for notifying the node of new regenesis blocks
FunPtr RegenesisCallback ->
-- |Maximum log level (inclusive) (0 to disable logging).
Word8 ->
-- |Handler for log events
FunPtr LogCallback ->
-- |FilePath for the AppData directory
CString ->
-- |Length of AppData path
Int64 ->
-- |Database connection string. If length is 0 don't do logging.
CString ->
-- |Length of database connection string.
Int64 ->
-- |Pointer to receive the pointer to the 'ConsensusRunner'.
Ptr (StablePtr ConsensusRunner) ->
IO Int64
startConsensusPassive
maxBlock
blockConstructionTimeout
maxTimeToExpiry
insertionsBeforePurge
transactionsKeepAlive
transactionsPurgingDelay
gdataC
gdataLenC
cucbk
regenesisPtr
regenesisFree
regenesisCB
maxLogLevel
lcbk
appDataC
appDataLenC
connStringPtr
connStringLen
runnerPtrPtr = handleStartExceptions logM $
decodeGenesis $ \genesisData -> do
-- Get the data directory
appDataPath <- peekCStringLen (appDataC, fromIntegral appDataLenC)
-- Do globalstate migration if necessary
migrateGlobalState appDataPath logM
let mvcStateConfig = DiskStateConfig appDataPath
let mvcFinalizationConfig = NoFinalization
-- Callbacks
regenesisRef <- makeRegenesisRef regenesisFree regenesisPtr
let callbacks =
Callbacks
{ broadcastBlock = \_ _ -> return (),
broadcastFinalizationMessage = \_ _ -> return (),
broadcastFinalizationRecord = \_ _ -> return (),
notifyCatchUpStatus = callCatchUpStatusCallback cucbk,
notifyRegenesis = callRegenesisCallback regenesisCB regenesisRef
}
runner <-
if connStringLen /= 0
then do
mvcTXLogConfig <-
TransactionDBConfig
<$> BS.packCStringLen (connStringPtr, fromIntegral connStringLen)
let config ::
MultiVersionConfiguration
DiskTreeDiskBlockWithLogConfig
(NoFinalization ThreadTimer)
config = MultiVersionConfiguration{..}
ConsensusRunner
<$> makeMultiVersionRunner config callbacks Nothing logM genesisData
else do
let config ::
MultiVersionConfiguration
DiskTreeDiskBlockConfig
(NoFinalization ThreadTimer)
config = MultiVersionConfiguration{mvcTXLogConfig = (), ..}
ConsensusRunner
<$> makeMultiVersionRunner config callbacks Nothing logM genesisData
poke runnerPtrPtr =<< newStablePtr runner
return StartSuccess
where
-- Decode genesis data
decodeGenesis cont = do
genesisBS <- BS.packCStringLen (gdataC, fromIntegral gdataLenC)
case S.runGet getPVGenesisData genesisBS of
Left err -> do
logM External LLError $ "Failed to decode genesis data: " ++ err
return StartGenesisFailure
Right genData -> cont genData
-- Log method
logM = toLogMethod maxLogLevel lcbk
-- Runtime parameters
mvcRuntimeParameters =
RuntimeParameters
{ rpBlockSize = fromIntegral maxBlock,
rpBlockTimeout = fromIntegral blockConstructionTimeout,
rpEarlyBlockThreshold = defaultEarlyBlockThreshold,
rpMaxBakingDelay = defaultMaxBakingDelay,
rpInsertionsBeforeTransactionPurge = fromIntegral insertionsBeforePurge,
rpTransactionsKeepAliveTime = TransactionTime transactionsKeepAlive,
rpTransactionsPurgingDelay = fromIntegral transactionsPurgingDelay,
rpMaxTimeToExpiry = fromIntegral maxTimeToExpiry
}
-- |Shut down consensus, stopping any baker thread if necessary.
-- The pointer is not valid after this function returns.
stopConsensus :: StablePtr ConsensusRunner -> IO ()
stopConsensus cptr = mask_ $ do
ConsensusRunner mvr <- deRefStablePtr cptr
MV.shutdownMultiVersionRunner mvr
freeStablePtr cptr
-- |Start the baker thread. Calling this mare than once does not start additional baker threads.
startBaker :: StablePtr ConsensusRunner -> IO ()
startBaker cptr = mask_ $ do
ConsensusRunner mvr <- deRefStablePtr cptr
MV.startBaker mvr
-- |Stop a baker thread. The baker thread may be restarted by calling 'startBaker'.
-- This does not otherwise affect the consensus.
stopBaker :: StablePtr ConsensusRunner -> IO ()
stopBaker cptr = mask_ $ do
ConsensusRunner mvr <- deRefStablePtr cptr
MV.stopBaker mvr
-- * Receive functions
-- | Result values for receive functions.
--
-- +=======+====================================+========================================================================================+==========+
-- | Value | Name | Description | Forward? |
-- +=======+====================================+========================================================================================+==========+
-- | 0 | ResultSuccess | Message received, validated and processed | Yes |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 1 | ResultSerializationFail | Message deserialization failed | No |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 2 | ResultInvalid | The message was determined to be invalid | No |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 3 | ResultPendingBlock | The message was received, but is awaiting a block to complete processing | Yes |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 4 | ResultPendingFinalization | The message was received, but is awaiting a finalization record to complete processing | Yes |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 5 | ResultAsync | The message was received, but is being processed asynchronously | Yes |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 6 | ResultDuplicate | The message duplicates a previously received message | No |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 7 | ResultStale | The message may have been valid in the past, but is no longer relevant | No |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 8 | ResultIncorrectFinalizationSession | The message refers to a different/unknown finalization session | No(?) |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 9 | ResultUnverifiable | The message could not be verified in the current state (initiate catch-up with peer) | No |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 10 | ResultContinueCatchUp | The peer should be marked pending catch-up if it is currently up-to-date | N/A |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 11 | ResultEarlyBlock | The block has a slot number exceeding our current + the early block threshold | No |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 12 | ResultMissingImportFile | The file provided for importing doesn't exist | N/A |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 13 | ResultConsensusShutDown | Consensus has been shut down and the message was ignored | No |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 14 | ResultExpiryTooLate | The transaction expiry time is too far in the future | No |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 15 | ResultVerificationFailed | The transaction signature verification failed | No |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 16 | ResultNonexistingSenderAccount | The transaction's sender account does not exist according to the focus block | No |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 17 | ResultDuplicateNonce | The sequence number for this account or udpate type was already used | No |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 18 | ResultNonceTooLarge | The transaction seq. number is larger than the next one for this account/update type | No |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 19 | ResultTooLowEnergy | The stated transaction energy is lower than the minimum amount necessary to execute it | No |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
-- | 20 | ResultInvalidGenesisIndex | The message is for an unknown genesis index | No |
-- +-------+------------------------------------+----------------------------------------------------------------------------------------+----------+
type ReceiveResult = Int64
-- |Convert an 'UpdateResult' to the corresponding 'ReceiveResult' value.
toReceiveResult :: UpdateResult -> ReceiveResult
toReceiveResult ResultSuccess = 0
toReceiveResult ResultSerializationFail = 1
toReceiveResult ResultInvalid = 2
toReceiveResult ResultPendingBlock = 3
toReceiveResult ResultPendingFinalization = 4
toReceiveResult ResultAsync = 5
toReceiveResult ResultDuplicate = 6
toReceiveResult ResultStale = 7
toReceiveResult ResultIncorrectFinalizationSession = 8
toReceiveResult ResultUnverifiable = 9
toReceiveResult ResultContinueCatchUp = 10
toReceiveResult ResultEarlyBlock = 11
toReceiveResult ResultMissingImportFile = 12
toReceiveResult ResultConsensusShutDown = 13
toReceiveResult ResultExpiryTooLate = 14
toReceiveResult ResultVerificationFailed = 15
toReceiveResult ResultNonexistingSenderAccount = 16
toReceiveResult ResultDuplicateNonce = 17
toReceiveResult ResultNonceTooLarge = 18
toReceiveResult ResultTooLowEnergy = 19
toReceiveResult ResultInvalidGenesisIndex = 20
-- |Handle receipt of a block.
-- The possible return codes are @ResultSuccess@, @ResultSerializationFail@, @ResultInvalid@,
-- @ResultPendingBlock@, @ResultPendingFinalization@, @ResultAsync@, @ResultDuplicate@,
-- @ResultStale@, @ResultConsensusShutDown@, and @ResultInvalidGenesisIndex@.
-- 'receiveBlock' may invoke the callbacks for new finalization messages.
receiveBlock :: StablePtr ConsensusRunner -> GenesisIndex -> CString -> Int64 -> IO ReceiveResult
receiveBlock bptr genIndex msg msgLen = do
(ConsensusRunner mvr) <- deRefStablePtr bptr
mvLog mvr External LLTrace $ "Received block data, size = " ++ show msgLen ++ "."
blockBS <- BS.packCStringLen (msg, fromIntegral msgLen)
toReceiveResult <$> runMVR (MV.receiveBlock genIndex blockBS) mvr
-- |Handle receipt of a finalization message.
-- The possible return codes are @ResultSuccess@, @ResultSerializationFail@, @ResultInvalid@,
-- @ResultPendingFinalization@, @ResultDuplicate@, @ResultStale@, @ResultIncorrectFinalizationSession@,
-- @ResultUnverifiable@, @ResultConsensusShutDown@, and @ResultInvalidGenesisIndex@.
-- 'receiveFinalization' may invoke the callbacks for new finalization messages.
receiveFinalizationMessage ::
StablePtr ConsensusRunner ->
GenesisIndex ->
CString ->
Int64 ->
IO ReceiveResult
receiveFinalizationMessage bptr genIndex msg msgLen = do
(ConsensusRunner mvr) <- deRefStablePtr bptr
mvLog mvr External LLTrace $ "Received finalization message, size = " ++ show msgLen ++ "."
finMsgBS <- BS.packCStringLen (msg, fromIntegral msgLen)
toReceiveResult <$> runMVR (MV.receiveFinalizationMessage genIndex finMsgBS) mvr
-- |Handle receipt of a finalization record.
-- The possible return codes are @ResultSuccess@, @ResultSerializationFail@, @ResultInvalid@,
-- @ResultPendingBlock@, @ResultPendingFinalization@, @ResultDuplicate@, @ResultStale@,
-- @ResultConsensusShutDown@ and @ResultInvalidGenesisIndex@.
-- 'receiveFinalizationRecord' may invoke the callbacks for new finalization messages.
receiveFinalizationRecord ::
StablePtr ConsensusRunner ->
GenesisIndex ->
CString ->
Int64 ->
IO ReceiveResult
receiveFinalizationRecord bptr genIndex msg msgLen = do
(ConsensusRunner mvr) <- deRefStablePtr bptr
mvLog mvr External LLTrace $ "Received finalization record, size = " ++ show msgLen ++ "."
finRecBS <- BS.packCStringLen (msg, fromIntegral msgLen)
toReceiveResult <$> runMVR (MV.receiveFinalizationRecord genIndex finRecBS) mvr
-- |Handle receipt of a transaction.
-- The possible return codes are @ResultSuccess@, @ResultSerializationFail@, @ResultDuplicate@,
-- @ResultStale@, @ResultInvalid@, @ResultConsensusShutDown@, @ResultExpiryTooLate@, @ResultVerificationFailed@,
-- @ResultNonexistingSenderAccount@, @ResultDuplicateNonce@, @ResultNonceTooLarge@, @ResultTooLowEnergy@.
receiveTransaction :: StablePtr ConsensusRunner -> CString -> Int64 -> IO ReceiveResult
receiveTransaction bptr transactionData transactionLen = do
(ConsensusRunner mvr) <- deRefStablePtr bptr
mvLog mvr External LLTrace $ "Received transaction, size = " ++ show transactionLen ++ "."
transactionBS <- BS.packCStringLen (transactionData, fromIntegral transactionLen)
toReceiveResult <$> runMVR (MV.receiveTransaction transactionBS) mvr
-- |Handle receiving a catch-up status message.
-- If the message is a request, then the supplied callback will be used to
-- send the requested data for the peer.
-- The response code can be:
-- * @ResultSerializationFail@
-- * @ResultInvalid@ -- the catch-up message is inconsistent with the skov
-- * @ResultPendingBlock@ -- the sender has some data I am missing, and should be marked pending
-- * @ResultSuccess@ -- I do not require additional data from the sender, so mark it as up-to-date
-- * @ResultContinueCatchUp@ -- The sender should be marked pending if it is currently up-to-date (no change otherwise)
receiveCatchUpStatus ::
-- |Consensus pointer
StablePtr ConsensusRunner ->
-- |Identifier of peer (passed to callback)
PeerID ->
-- |Genesis index
GenesisIndex ->
-- |Serialised catch-up message
CString ->
-- |Length of message
Int64 ->
-- |Limit to number of responses. Limit <= 0 means no messages will be sent.
Int64 ->
-- |Callback to receive messages
FunPtr DirectMessageCallback ->
IO ReceiveResult
receiveCatchUpStatus cptr src genIndex cstr len limit cbk =
toReceiveResult <$> do
let catchUpMessageLimit = fromIntegral limit
(ConsensusRunner mvr) <- deRefStablePtr cptr
if catchUpMessageLimit <= 0
then do
mvLog mvr External LLWarning "Requesting catchup with limit <= 0."
return ResultSuccess
else do
bs <- BS.packCStringLen (cstr, fromIntegral len)
let catchUpCallback mt = callDirectMessageCallback cbk src mt genIndex
runMVR (MV.receiveCatchUpStatus genIndex bs CatchUpConfiguration{..}) mvr
-- |Get a catch-up status message for requesting catch-up with peers.
-- The genesis index and string pointer are loaded into the given pointers.
-- The return value is the length of the string.
-- The string should be freed by calling 'freeCStr'.
getCatchUpStatus ::
-- |Consensus pointer
StablePtr ConsensusRunner ->
-- |Pointer to receive the genesis index
Ptr GenesisIndex ->
-- |Pointer to receive the string pointer
Ptr CString ->
IO Int64
getCatchUpStatus cptr genIndexPtr resPtr = do
(ConsensusRunner mvr) <- deRefStablePtr cptr
(genIndex, resBS) <- runMVR MV.getCatchUpRequest mvr
poke genIndexPtr genIndex
poke resPtr =<< toCString resBS
return (LBS.length resBS)
-- |Import a file consisting of a set of blocks and finalization records for the purposes of
-- out-of-band catch-up.
importBlocks ::
-- |Consensus runner
StablePtr ConsensusRunner ->
-- |File path to import blocks from
CString ->
-- |Length of filename
Int64 ->
IO Int64
importBlocks cptr fname fnameLen =
toReceiveResult <$> do
(ConsensusRunner mvr) <- deRefStablePtr cptr
theFile <- peekCStringLen (fname, fromIntegral fnameLen)
runMVR (MV.importBlocks theFile) mvr
-- * Queries
-- |Converts a lazy 'LBS.ByteString' to a null-terminated 'CString'.
-- The string must be freed after use by calling 'free'.
toCString :: LBS.ByteString -> IO CString
toCString lbs = do
let len = LBS.length lbs
buf <- mallocBytes (fromIntegral len + 1)
let copyChunk px bs = BS.unsafeUseAsCStringLen bs $ \(bsp, bspLen) -> do
copyBytes px bsp bspLen
return $ plusPtr px bspLen
end <- foldM copyChunk buf (LBS.toChunks lbs)
poke end (0 :: CChar)
return buf
-- |Encode a value as JSON in a CString. The allocated string must be explicitly freed to avoid
-- memory leaks.
jsonCString :: AE.ToJSON a => a -> IO CString
jsonCString = toCString . AE.encode
-- |Converts a 'BS.ByteString' to a 'CString' that encodes the length of the
-- string in big-endian in the first four bytes (not including the length).
-- This string should be freed after use by calling 'free'.
byteStringToCString :: BS.ByteString -> IO CString
byteStringToCString bs = do
let bsp = BS.concat [S.runPut (S.putWord32be (fromIntegral (BS.length bs))), bs]
-- This use of unsafe is fine because bsp is a non-null string.
BS.unsafeUseAsCStringLen bsp $ \(cstr, len) -> do
dest <- mallocBytes len
copyBytes dest cstr len
return dest
-- |Free a 'CString'. This should be called to dispose of any 'CString' values that are returned by
-- queries.
freeCStr :: CString -> IO ()
freeCStr = free
-- |Convenience wrapper for queries that return JSON values.
jsonQuery ::
AE.ToJSON a =>
-- |Consensus pointer
StablePtr ConsensusRunner ->
-- |Configuration-independent query operation
(forall gsconf finconf. MVR gsconf finconf a) ->
IO CString
jsonQuery cptr a = do
(ConsensusRunner mvr) <- deRefStablePtr cptr
res <- runMVR a mvr
jsonCString res
-- |Decode a block hash from a null-terminated base-16 string.
decodeBlockHash :: CString -> IO (Maybe BlockHash)
decodeBlockHash blockcstr = readMaybe <$> peekCString blockcstr
-- |Decode an account address from a null-terminated base-58 string.
decodeAccountAddress :: CString -> IO (Either String AccountAddress)
decodeAccountAddress acctstr = addressFromBytes <$> BS.packCString acctstr
-- |Decode a null-terminated string as either an account address (base-58) or a
-- credential registration ID (base-16).
decodeAccountAddressOrCredId :: CString -> IO (Maybe (Either CredentialRegistrationID AccountAddress))
decodeAccountAddressOrCredId str = do
bs <- BS.packCString str
return $ case addressFromBytes bs of
Left _ -> Left <$> bsDeserializeBase16 bs
Right acc -> Just $ Right acc
-- |Decode an instance address from a null-terminated JSON-encoded string.
decodeInstanceAddress :: CString -> IO (Maybe ContractAddress)
decodeInstanceAddress inststr = AE.decodeStrict <$> BS.packCString inststr
-- |Decode a module reference from a null-terminated base-16 string.
decodeModuleRef :: CString -> IO (Maybe ModuleRef)
decodeModuleRef modstr = readMaybe <$> peekCString modstr
-- |Decode a transaction hash from a null-terminated base-16 string.
decodeTransactionHash :: CString -> IO (Maybe TransactionHash)
decodeTransactionHash trHashStr = readMaybe <$> peekCString trHashStr
-- ** General queries
-- |Returns a null-terminated string with a JSON representation of the current status of Consensus.
getConsensusStatus :: StablePtr ConsensusRunner -> IO CString
getConsensusStatus cptr = jsonQuery cptr Q.getConsensusStatus
-- ** Queries against latest tree
-- |Returns a null-terminated string with a JSON representation of the current branches from the
-- last finalized block (inclusive).
getBranches :: StablePtr ConsensusRunner -> IO CString
getBranches cptr = jsonQuery cptr Q.getBranches
-- |Get the list of live blocks at a given height.
-- The height is interpreted relative to the genesis block at the specified index.
-- The last parameter indicates whether to restrict to a single genesis (if it is a non-zero value).
-- Returns a null-terminated string encoding a JSON list.
getBlocksAtHeight ::
StablePtr ConsensusRunner ->
-- |Block height to query
Word64 ->
-- |Genesis index that block height is based on
Word32 ->
-- |Non-zero to restrict to blocks at specified genesis index
Word8 ->
IO CString
getBlocksAtHeight cptr height genIndex restrict =
jsonQuery cptr $
Q.getBlocksAtHeight
(BlockHeight height)
(GenesisIndex genIndex)
(restrict /= 0)
-- ** Block-indexed queries
-- |Given a null-terminated string that represents a block hash (base 16), returns a null-terminated
-- string containing a JSON representation of the block.
-- If the block hash is invalid or unknown, this returns the JSON null value.
-- For details of the value returned, see 'Concordium.Queries.Types.BlockInfo'.
getBlockInfo :: StablePtr ConsensusRunner -> CString -> IO CString
getBlockInfo cptr blockcstr =
decodeBlockHash blockcstr >>= \case
Nothing -> jsonCString AE.Null
Just bh -> jsonQuery cptr (Q.getBlockInfo bh)
-- |Get the list of transactions in a block with short summaries of their effects.
-- Returns a null-terminated string encoding a JSON value.
-- If the block hash is invalid or unknown, this returns the JSON null value.
-- For details of the value returned, see 'Concordium.Queries.Types.BlockSummary'.
getBlockSummary :: StablePtr ConsensusRunner -> CString -> IO CString
getBlockSummary cptr blockcstr =
decodeBlockHash blockcstr >>= \case
Nothing -> jsonCString AE.Null
Just bh -> jsonQuery cptr (Q.getBlockSummary bh)
-- |Get the status of the rewards parameters for the given block. The block must
-- be given as a null-terminated base16 encoding of the block hash.
-- The return value is a null-terminated, JSON encoded value.
-- The returned string should be freed by calling 'freeCStr'.
getRewardStatus :: StablePtr ConsensusRunner -> CString -> IO CString
getRewardStatus cptr blockcstr =
decodeBlockHash blockcstr >>= \case
Nothing -> jsonCString AE.Null
Just bh -> jsonQuery cptr (Q.getRewardStatus bh)
-- |Get birk parameters for the given block. The block must be given as a
-- null-terminated base16 encoding of the block hash.
-- The return value is a null-terminated JSON-encoded value.
-- The returned string should be freed by calling 'freeCStr'.
getBirkParameters :: StablePtr ConsensusRunner -> CString -> IO CString
getBirkParameters cptr blockcstr =
decodeBlockHash blockcstr >>= \case
Nothing -> jsonCString AE.Null
Just bh -> jsonQuery cptr (Q.getBlockBirkParameters bh)
-- |Get the cryptographic parameters in a given block. The block must be given as a
-- null-terminated base16 encoding of the block hash.
-- The return value is a null-terminated JSON-encoded object.
-- The returned string should be freed by calling 'freeCStr'.
getCryptographicParameters :: StablePtr ConsensusRunner -> CString -> IO CString
getCryptographicParameters cptr blockcstr =
decodeBlockHash blockcstr >>= \case
Nothing -> jsonCString AE.Null
Just bh -> jsonQuery cptr (Q.getCryptographicParameters bh)
-- |Get all of the identity providers registered in the system as of a given block.
-- The block must be given as a null-terminated base16 encoding of the block hash.
-- The return value is a null-terminated JSON-encoded list. (Or null for an invalid block.)
-- The returned string should be freed by calling 'freeCStr'.
getAllIdentityProviders :: StablePtr ConsensusRunner -> CString -> IO CString
getAllIdentityProviders cptr blockcstr =
decodeBlockHash blockcstr >>= \case
Nothing -> jsonCString AE.Null
Just bh -> jsonQuery cptr (Q.getAllIdentityProviders bh)
-- |Get all of the identity providers registered in the system as of a given block.
-- The block must be given as a null-terminated base16 encoding of the block hash.
-- The return value is a null-terminated JSON-encoded list. (Or null for an invalid block.)
-- The returned string should be freed by calling 'freeCStr'.
getAllAnonymityRevokers :: StablePtr ConsensusRunner -> CString -> IO CString
getAllAnonymityRevokers cptr blockcstr =
decodeBlockHash blockcstr >>= \case
Nothing -> jsonCString AE.Null
Just bh -> jsonQuery cptr (Q.getAllAnonymityRevokers bh)
-- |Given a null-terminated string that represents a block hash (base 16), and a number of blocks,
-- returns a null-terminated string containing a JSON list of the ancestors of the node (up to the
-- given number, including the block itself).
-- If the block hash is invalid or unknown, this returns the JSON null value.
getAncestors :: StablePtr ConsensusRunner -> CString -> Word64 -> IO CString
getAncestors cptr blockcstr depth =
decodeBlockHash blockcstr >>= \case
Nothing -> jsonCString AE.Null
Just bh -> jsonQuery cptr (Q.getAncestors bh (BlockHeight depth))
-- |Get the list of account addresses in the given block. The block must be
-- given as a null-terminated base16 encoding of the block hash. The return
-- value is a null-terminated JSON-encoded list of addresses.
-- The returned string should be freed by calling 'freeCStr'.
getAccountList :: StablePtr ConsensusRunner -> CString -> IO CString
getAccountList cptr blockcstr =