-
Notifications
You must be signed in to change notification settings - Fork 149
/
mod.rs
1968 lines (1858 loc) · 69.5 KB
/
mod.rs
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
pub mod gk;
mod master_key;
use crate::{
benchmark,
contracts::{ContractsKeeper, ExecuteEnv, SidevmCode},
pink::{Cluster, ClusterContainer},
secret_channel::{ecdh_serde, SecretReceiver},
types::{deopaque_query, BlockInfo, OpaqueError, OpaqueQuery},
ChainStorage,
};
use anyhow::{anyhow, Result};
use core::fmt;
use phactory_api::contracts::{Query, QueryError, QueryType, Response};
use phala_scheduler::RequestScheduler;
use pink_loader::{
capi::v1::ecall::{ClusterSetupConfig, ECalls},
local_cache,
types::{
AccountId, ExecSideEffects, ExecutionMode, HookPoint, PinkEvent, TransactionArguments,
},
};
use runtime::BlockNumber;
use crate::contracts;
use crate::pal;
use chain::pallet_phat::ContractRegistryEvent;
use chain::pallet_registry::RegistryEvent;
pub use master_key::{gk_master_key_exists, RotatedMasterKey};
use parity_scale_codec::{Decode, Encode};
pub use phactory_api::prpc::{GatekeeperRole, GatekeeperStatus, SystemInfo};
use phala_crypto::{
ecdh::EcdhKey,
key_share,
sr25519::{Persistence, KDF},
};
use phala_mq::{
traits::MessageChannel, BadOrigin, ContractId, MessageDispatcher, MessageOrigin,
MessageSendQueue, SignedMessageChannel, TypedReceiver,
};
use phala_serde_more as more;
use phala_types::{
contract::{
self,
messaging::{
BatchDispatchClusterKeyEvent, ClusterOperation, ContractOperation, ResourceType,
WorkerClusterReport,
},
CodeIndex, ConvertTo,
},
messaging::{
AeadIV, BatchRotateMasterKeyEvent, DispatchMasterKeyEvent, DispatchMasterKeyHistoryEvent,
GatekeeperChange, GatekeeperLaunch, HeartbeatChallenge, KeyDistribution,
NewGatekeeperEvent, RemoveGatekeeperEvent, RotateMasterKeyEvent, SystemEvent, WorkerEvent,
WorkingReportEvent,
},
wrap_content_to_sign, AttestationProvider, EcdhPublicKey, SignedContentType, WorkerPublicKey,
};
use serde::{Deserialize, Serialize};
use sidevm::{
service::{Command as SidevmCommand, CommandSender, Spawner, SystemMessage},
OutgoingRequestChannel,
};
use sp_core::{hashing::blake2_256, sr25519, Pair, U256};
use pink::{SidevmOperation, Workers};
use std::convert::TryFrom;
use std::future::Future;
use tracing::{error, info};
pub type TransactionResult = Result<Option<ExecSideEffects>, TransactionError>;
pub(crate) const MAX_SUPPORTED_CONSENSUS_VERSION: u32 = 0;
#[derive(Encode, Decode, Debug, Clone, thiserror::Error)]
#[error("TransactionError: {:?}", self)]
pub enum TransactionError {
BadInput,
BadOrigin,
Other(String),
// general
InsufficientBalance,
NoBalance,
UnknownError,
BadContractId,
BadCommand,
SymbolExist,
AssetIdNotFound,
NotAssetOwner,
BadSecret,
BadMachineId,
FailedToSign,
BadDecimal,
DestroyNotAllowed,
ChannelError,
// for gatekeeper
NotGatekeeper,
MasterKeyLeakage,
BadSenderSignature,
// for pdiem
BadAccountInfo,
BadLedgerInfo,
BadTrustedStateData,
BadEpochChangedProofData,
BadTrustedState,
InvalidAccount,
BadTransactionWithProof,
FailedToVerify,
FailedToGetTransaction,
FailedToCalculateBalance,
BadChainId,
TransferringNotAllowed,
// for contract
CodeNotFound,
DuplicatedClusterDeploy,
FailedToUploadResourceToCluster,
NoClusterOnGatekeeper,
NoPinkSystemCode,
BadPinkSystemVersion,
}
impl From<BadOrigin> for TransactionError {
fn from(_: BadOrigin) -> TransactionError {
TransactionError::BadOrigin
}
}
impl From<String> for TransactionError {
fn from(s: String) -> TransactionError {
TransactionError::Other(s)
}
}
#[derive(Debug, Serialize, Deserialize, Clone, ::scale_info::TypeInfo)]
struct BenchState {
start_block: chain::BlockNumber,
start_time: u64,
start_iter: u64,
duration: u32,
}
#[derive(Debug, Serialize, Deserialize, Clone, ::scale_info::TypeInfo)]
enum WorkingState {
Computing,
Paused,
}
#[derive(Debug, Serialize, Deserialize, Clone, ::scale_info::TypeInfo)]
struct WorkingInfo {
session_id: u32,
state: WorkingState,
start_time: u64,
start_iter: u64,
}
// Minimum worker state machine can be reused to replay in GK.
#[derive(Debug, Serialize, Deserialize, Clone, ::scale_info::TypeInfo)]
struct WorkerState {
#[codec(skip)]
#[serde(with = "more::pubkey_bytes")]
pubkey: WorkerPublicKey,
hashed_id: U256,
registered: bool,
bench_state: Option<BenchState>,
working_state: Option<WorkingInfo>,
}
impl WorkerState {
pub fn new(pubkey: WorkerPublicKey) -> Self {
let raw_pubkey: &[u8] = pubkey.as_ref();
let pkh = blake2_256(raw_pubkey);
let hashed_id: U256 = pkh.into();
Self {
pubkey,
hashed_id,
registered: false,
bench_state: None,
working_state: None,
}
}
pub fn process_event(
&mut self,
block: &crate::BaseBlockInfo,
event: &SystemEvent,
callback: &mut impl WorkerStateMachineCallback,
log_on: bool,
) {
match event {
SystemEvent::WorkerEvent(evt) => {
if evt.pubkey != self.pubkey {
return;
}
use WorkerEvent::*;
use WorkingState::*;
if log_on {
info!("System::handle_event: {:?}", evt.event);
}
match evt.event {
Registered(_) => {
self.registered = true;
}
BenchStart { duration } => {
self.bench_state = Some(BenchState {
start_block: block.block_number,
start_time: block.now_ms,
start_iter: callback.bench_iterations(),
duration,
});
callback.bench_resume();
}
BenchScore(score) => {
if log_on {
info!("My benchmark score is {}", score);
}
}
Started { session_id, .. } => {
self.working_state = Some(WorkingInfo {
session_id,
state: Computing,
start_time: block.now_ms,
start_iter: callback.bench_iterations(),
});
callback.bench_resume();
}
Stopped => {
self.working_state = None;
if self.need_pause() {
callback.bench_pause();
}
}
EnterUnresponsive => {
if let Some(info) = &mut self.working_state {
if let Computing = info.state {
if log_on {
info!("Enter paused");
}
info.state = Paused;
return;
}
}
if log_on {
error!(
"Unexpected event received: {:?}, working_state= {:?}",
evt.event, self.working_state
);
}
}
ExitUnresponsive => {
if let Some(info) = &mut self.working_state {
if let Paused = info.state {
if log_on {
info!("Exit paused");
}
info.state = Computing;
return;
}
}
if log_on {
error!(
"Unexpected event received: {:?}, working_state= {:?}",
evt.event, self.working_state
);
}
}
}
}
SystemEvent::HeartbeatChallenge(seed_info) => {
self.handle_heartbeat_challenge(block, seed_info, callback, log_on);
}
};
}
fn handle_heartbeat_challenge(
&mut self,
block: &crate::BaseBlockInfo,
seed_info: &HeartbeatChallenge,
callback: &mut impl WorkerStateMachineCallback,
log_on: bool,
) {
if log_on {
debug!(
"System::handle_heartbeat_challenge({}, {:?}), registered={:?}, working_state={:?}",
block.block_number, seed_info, self.registered, self.working_state
);
}
if !self.registered {
return;
}
let working_state = if let Some(state) = &mut self.working_state {
state
} else {
return;
};
if matches!(working_state.state, WorkingState::Paused) {
return;
}
let x = self.hashed_id ^ seed_info.seed;
let online_hit = x <= seed_info.online_target;
// Push queue when necessary
if online_hit {
let iterations = callback.bench_iterations() - working_state.start_iter;
callback.heartbeat(
working_state.session_id,
block.block_number,
block.now_ms,
iterations,
);
}
}
fn need_pause(&self) -> bool {
self.bench_state.is_none() && self.working_state.is_none()
}
fn on_block_processed(
&mut self,
block: &crate::BaseBlockInfo,
callback: &mut impl WorkerStateMachineCallback,
) {
// Handle registering benchmark report
if let Some(BenchState {
start_block,
start_time,
start_iter,
duration,
}) = self.bench_state
{
if block.block_number - start_block >= duration {
self.bench_state = None;
let iterations = callback.bench_iterations() - start_iter;
callback.bench_report(start_time, iterations);
if self.need_pause() {
callback.bench_pause();
}
}
}
}
}
trait WorkerStateMachineCallback {
fn bench_iterations(&self) -> u64 {
0
}
fn bench_resume(&mut self) {}
fn bench_pause(&mut self) {}
fn bench_report(&mut self, _start_time: u64, _iterations: u64) {}
fn heartbeat(
&mut self,
_session_id: u32,
_block_num: chain::BlockNumber,
_block_time: u64,
_iterations: u64,
) {
}
}
struct WorkerSMDelegate<'a> {
egress: &'a SignedMessageChannel,
n_clusters: u32,
n_contracts: u32,
}
impl WorkerStateMachineCallback for WorkerSMDelegate<'_> {
fn bench_iterations(&self) -> u64 {
benchmark::iteration_counter()
}
fn bench_resume(&mut self) {
benchmark::resume();
}
fn bench_pause(&mut self) {
benchmark::pause();
}
fn bench_report(&mut self, start_time: u64, iterations: u64) {
let report = RegistryEvent::BenchReport {
start_time,
iterations,
};
info!("Reporting benchmark: {:?}", report);
self.egress.push_message(&report);
}
fn heartbeat(
&mut self,
session_id: u32,
challenge_block: chain::BlockNumber,
challenge_time: u64,
iterations: u64,
) {
let event = WorkingReportEvent::HeartbeatV2 {
session_id,
challenge_block,
challenge_time,
iterations,
n_clusters: self.n_clusters,
n_contracts: self.n_contracts,
};
info!("System: sending {:?}", event);
self.egress.push_message(&event);
}
}
#[derive(
Serialize, Deserialize, Clone, derive_more::Deref, derive_more::DerefMut, derive_more::From,
)]
#[serde(transparent)]
pub struct WorkerIdentityKey(#[serde(with = "more::key_bytes")] sr25519::Pair);
// By mocking the public key of the identity key pair, we can pretend to be the first Gatekeeper on Khala
// for "shadow-gk" simulation.
#[cfg(feature = "shadow-gk")]
impl WorkerIdentityKey {
pub(crate) fn public(&self) -> sr25519::Public {
// The pubkey of the first GK on khala
sr25519::Public(hex_literal::hex!(
"60067697c486c809737e50d30a67480c5f0cede44be181b96f7d59bc2116a850"
))
}
}
#[derive(
Serialize, Deserialize, Clone, derive_more::Deref, derive_more::DerefMut, derive_more::From,
)]
#[serde(transparent)]
pub(crate) struct ContractKey(#[serde(with = "more::key_bytes")] sr25519::Pair);
fn get_contract_key(cluster_key: &sr25519::Pair, contract_id: &ContractId) -> sr25519::Pair {
// Introduce deployer in key generation to prevent Replay Attacks
cluster_key
.derive_sr25519_pair(&[b"contract_key", contract_id.as_ref()])
.expect("should not fail with valid info")
}
#[derive(Serialize, Deserialize, Clone, ::scale_info::TypeInfo)]
pub struct System<Platform> {
platform: Platform,
// Configuration
dev_mode: bool,
pub(crate) sealing_path: String,
pub(crate) storage_path: String,
// Messageing
egress: SignedMessageChannel,
system_events: TypedReceiver<SystemEvent>,
gatekeeper_launch_events: TypedReceiver<GatekeeperLaunch>,
gatekeeper_change_events: TypedReceiver<GatekeeperChange>,
key_distribution_events: TypedReceiver<KeyDistribution<chain::BlockNumber>>,
cluster_key_distribution_events: TypedReceiver<ClusterOperation<chain::AccountId>>,
contract_operation_events: TypedReceiver<ContractOperation<chain::Hash, chain::AccountId>>,
// Worker
#[codec(skip)]
pub(crate) identity_key: WorkerIdentityKey,
#[codec(skip)]
#[serde(with = "ecdh_serde")]
pub(crate) ecdh_key: EcdhKey,
/// Be careful to use this field, as it is not updated in safe mode.
worker_state: WorkerState,
// Gatekeeper
pub(crate) gatekeeper: Option<gk::Gatekeeper<SignedMessageChannel>>,
pub(crate) contracts: ContractsKeeper,
pub(crate) contract_cluster: Option<Cluster>,
// Cached for query
/// The block number of the last block that the worker has synced.
/// Be careful to use this field, as it is not updated in safe mode.
pub(crate) block_number: BlockNumber,
/// The timestamp of the last block that the worker has synced.
/// Be careful to use this field, as it is not updated in safe mode.
pub(crate) now_ms: u64,
// If non-zero indicates the block which this worker loaded the chain state from.
pub(crate) genesis_block: BlockNumber,
}
impl<Platform: pal::Platform> System<Platform> {
#[allow(clippy::too_many_arguments)]
pub fn new(
platform: Platform,
dev_mode: bool,
sealing_path: String,
storage_path: String,
identity_key: sr25519::Pair,
ecdh_key: EcdhKey,
send_mq: &MessageSendQueue,
recv_mq: &mut MessageDispatcher,
) -> Self {
// Trigger panic early if platform is not properly implemented.
let _ = Platform::app_version();
let identity_key = WorkerIdentityKey(identity_key);
let pubkey = identity_key.public();
let sender = MessageOrigin::Worker(pubkey);
System {
platform,
dev_mode,
sealing_path,
storage_path,
egress: send_mq.channel(sender, identity_key.clone().0.into()),
system_events: recv_mq.subscribe_bound(),
gatekeeper_launch_events: recv_mq.subscribe_bound(),
gatekeeper_change_events: recv_mq.subscribe_bound(),
key_distribution_events: recv_mq.subscribe_bound(),
cluster_key_distribution_events: recv_mq.subscribe_bound(),
contract_operation_events: recv_mq.subscribe_bound(),
identity_key,
ecdh_key,
worker_state: WorkerState::new(pubkey),
gatekeeper: None,
contracts: Default::default(),
contract_cluster: None,
block_number: 0,
now_ms: 0,
genesis_block: 0,
}
}
pub fn get_system_message_handler(&self) -> Option<CommandSender> {
let handler_contract_id = self
.contract_cluster
.as_ref()?
.config
.log_handler
.as_ref()?;
self.contracts
.get(handler_contract_id)?
.get_system_message_handler()
}
pub fn registered(&self) -> bool {
self.worker_state.registered
}
#[allow(clippy::too_many_arguments)]
pub fn make_query(
&self,
req_id: u64,
contract_id: &AccountId,
origin: Option<&chain::AccountId>,
query: OpaqueQuery,
query_scheduler: RequestScheduler<AccountId>,
chain_storage: &ChainStorage,
sidevm_event_tx: OutgoingRequestChannel,
attestation_provider: Option<AttestationProvider>,
) -> Result<
impl Future<
Output = Result<
(
QueryType,
Result<Response, QueryError>,
Option<ExecSideEffects>,
),
OpaqueError,
>,
>,
OpaqueError,
> {
let contract = self
.contracts
.get(contract_id)
.ok_or(OpaqueError::ContractNotFound)?;
let cluster = self
.contract_cluster
.as_ref()
.expect("BUG: contract cluster should always exists")
.snapshot();
let sidevm_handle = contract.sidevm_handle();
let weight = contract.weight();
let context = contracts::QueryContext {
block_number: self.block_number,
now_ms: self.now_ms,
sidevm_handle,
log_handler: self.get_system_message_handler(),
query_scheduler,
weight,
worker_identity_key: self.identity_key.clone(),
chain_storage: chain_storage.snapshot(),
req_id,
sidevm_event_tx,
attestation_provider,
};
let origin = origin.cloned();
let query = deopaque_query::<Query>(&query)?;
let contract_id = contract_id.clone();
let contracts = self.contracts.clone();
Ok(async move {
let query_type = query.query_type();
let result = cluster
.handle_query(&contract_id, origin.as_ref(), query, context, contracts)
.await;
let (result, effects) = match result {
Ok((reply, effects)) => (Ok(reply), effects),
Err(err) => {
log::error!("Contract query error: {:?}", err);
(Err(err), None)
}
};
Ok((query_type, result, effects))
})
}
pub fn process_next_message(&mut self, block: &mut BlockInfo) -> anyhow::Result<bool> {
let ok = phala_mq::select_ignore_errors! {
(event, origin) = self.system_events => {
if !origin.is_pallet() {
anyhow::bail!("Invalid SystemEvent sender: {}", origin);
}
self.process_system_event(block, &event);
},
(event, origin) = self.gatekeeper_launch_events => {
self.process_gatekeeper_launch_event(block, origin, event);
},
(event, origin) = self.gatekeeper_change_events => {
self.process_gatekeeper_change_event(block, origin, event);
},
(event, origin) = self.key_distribution_events => {
self.process_key_distribution_event(block, origin, event);
},
(event, origin) = self.cluster_key_distribution_events => {
self.process_cluster_operation_event(block, origin, event)?;
},
(event, origin) = self.contract_operation_events => {
self.process_contract_operation_event(block, origin, event)?
},
};
Ok(ok.is_none())
}
pub fn will_process_block(&mut self, block: &mut BlockInfo) {
self.block_number = block.block_number;
self.now_ms = block.now_ms;
if let Some(gatekeeper) = &mut self.gatekeeper {
gatekeeper.will_process_block(block);
}
}
pub fn process_messages(&mut self, block: &mut BlockInfo) {
loop {
match self.process_next_message(block) {
Err(err) => {
error!("Error processing message: {:?}", err);
}
Ok(no_more) => {
if no_more {
break;
}
}
}
}
self.process_contract_messages(block);
if let Some(gatekeeper) = &mut self.gatekeeper {
gatekeeper.process_messages(block);
}
}
fn process_contract_messages(&mut self, block: &mut BlockInfo) {
// Iterate over all contracts to handle their incoming commands.
//
// Since the wasm contracts can instantiate new contracts, it means that it will mutate the `self.contracts`.
// So we can not directly iterate over the self.contracts.values_mut() which would keep borrowing on `self.contracts`
// in the scope of entire `for loop` body.
let contract_ids: Vec<_> = self.contracts.keys().cloned().collect();
'next_contract: for key in contract_ids {
// Inner loop to handle commands. One command per iteration and apply the command side-effects to make it
// availabe for next command.
loop {
let log_handler = self.get_system_message_handler();
let Some(cluster) = &mut self.contract_cluster else {
return;
};
let contract = match self.contracts.get_mut(&key) {
None => continue 'next_contract,
Some(v) => v,
};
let mut env = ExecuteEnv {
block,
contract_cluster: cluster,
log_handler: log_handler.clone(),
};
let result = match contract.process_next_message(&mut env) {
Some(result) => result,
None => break,
};
handle_contract_command_result(
self.identity_key.public(),
result,
&mut self.contracts,
cluster,
block,
&self.egress,
log_handler,
block.storage,
);
}
}
if let Some(cluster) = &mut self.contract_cluster {
cluster.on_idle(block.block_number);
};
}
pub fn did_process_block(&mut self, block: &mut BlockInfo) {
if let Some(gatekeeper) = &mut self.gatekeeper {
gatekeeper.did_process_block(block);
}
self.worker_state.on_block_processed(
block,
&mut WorkerSMDelegate {
egress: &self.egress,
n_clusters: self.contract_cluster.len() as _,
n_contracts: self.contracts.len() as _,
},
);
let log_handler = self.get_system_message_handler();
if let Some(cluster) = self.contract_cluster.as_mut() {
let contract_ids: Vec<_> = self.contracts.keys().cloned().collect();
'next_contract: for key in contract_ids {
let contract = match self.contracts.get_mut(&key) {
None => continue 'next_contract,
Some(v) => v,
};
let mut env = ExecuteEnv {
block,
contract_cluster: cluster,
log_handler: log_handler.clone(),
};
let result = contract.on_block_end(&mut env);
handle_contract_command_result(
self.identity_key.public(),
result,
&mut self.contracts,
cluster,
block,
&self.egress,
log_handler.clone(),
block.storage,
);
}
}
if self.contracts.weight_changed {
self.contracts.weight_changed = false;
self.contracts.apply_local_cache_quotas();
}
self.contracts
.try_restart_sidevms(block.sidevm_spawner, self.block_number);
let contract_running = self.contract_cluster.is_some();
benchmark::set_flag(benchmark::Flags::CONTRACT_RUNNING, contract_running);
}
fn process_system_event(&mut self, block: &BlockInfo, event: &SystemEvent) {
self.worker_state.process_event(
block,
event,
&mut WorkerSMDelegate {
egress: &self.egress,
n_clusters: self.contract_cluster.len() as _,
n_contracts: self.contracts.len() as _,
},
true,
);
}
/// Update local sealed master keys if the received history is longer than existing one.
///
/// Panic if `self.gatekeeper` is None since it implies a need for resync from the start as gk
fn set_master_key_history(&mut self, master_key_history: Vec<RotatedMasterKey>) {
if self.gatekeeper.is_none() {
master_key::seal(
self.sealing_path.clone(),
&master_key_history,
&self.identity_key,
&self.platform,
);
crate::maybe_remove_checkpoints(&self.storage_path);
panic!("Received master key, please restart pRuntime and pherry to sync as Gatekeeper");
}
if self
.gatekeeper
.as_mut()
.expect("checked; qed.")
.set_master_key_history(&master_key_history)
{
master_key::seal(
self.sealing_path.clone(),
&master_key_history,
&self.identity_key,
&self.platform,
);
}
}
fn init_gatekeeper(
&mut self,
block: &mut BlockInfo,
master_key_history: Vec<RotatedMasterKey>,
) {
assert!(
self.gatekeeper.is_none(),
"Duplicated gatekeeper initialization"
);
assert!(
!master_key_history.is_empty(),
"Init gatekeeper with no master key"
);
if self.genesis_block != 0 {
panic!("Gatekeeper must be synced start from the first block");
}
let master_key = sr25519::Pair::restore_from_secret_key(
&master_key_history
.first()
.expect("empty master key history")
.secret,
);
let block = &mut block.base;
let mut gatekeeper = gk::Gatekeeper::new(
master_key_history,
block.recv_mq,
block
.send_mq
.channel(MessageOrigin::Gatekeeper, master_key.into()),
);
if let Some(params) = block.storage.tokenomic_parameters() {
gatekeeper
.computing_economics
.update_tokenomic_parameters(params);
}
self.gatekeeper = Some(gatekeeper);
// TODO: clear up existing clusters
}
fn process_gatekeeper_launch_event(
&mut self,
block: &mut BlockInfo,
origin: MessageOrigin,
event: GatekeeperLaunch,
) {
if !origin.is_pallet() {
error!("Invalid origin {:?} sent a {:?}", origin, event);
return;
}
info!("Incoming gatekeeper launch event: {:?}", event);
match event {
GatekeeperLaunch::FirstGatekeeper(event) => {
self.process_first_gatekeeper_event(block, origin, event)
}
GatekeeperLaunch::MasterPubkeyOnChain(event) => {
info!(
"Gatekeeper launches on chain in block {}",
block.block_number
);
if let Some(gatekeeper) = &mut self.gatekeeper {
gatekeeper.master_pubkey_uploaded(event.master_pubkey);
}
}
GatekeeperLaunch::RotateMasterKey(event) => {
info!(
"Master key rotation req round {} in block {}",
event.rotation_id, block.block_number
);
self.process_master_key_rotation_request(block, origin, event);
}
GatekeeperLaunch::MasterPubkeyRotated(event) => {
info!(
"Rotated Master Pubkey {} on chain in block {}",
hex::encode(event.master_pubkey),
block.block_number
);
}
}
}
/// Generate the master key if this is the first gatekeeper
fn process_first_gatekeeper_event(
&mut self,
block: &mut BlockInfo,
_origin: MessageOrigin,
event: NewGatekeeperEvent,
) {
// ATTENTION: the first gk cannot resume if its original master_key.seal is lost,
// since there is no tx recorded on-chain that shares the key to itself
//
// Solution: always unregister the first gk after the second gk receives the key,
// thank god we only need to do this once for each blockchain
// double check the first gatekeeper is valid on chain
if !chain_state::is_gatekeeper(&event.pubkey, block.storage) {
error!(
"Fatal error: Invalid first gatekeeper registration {:?}",
event
);
panic!("System state poisoned");
}
let mut master_key_history = master_key::try_unseal(
self.sealing_path.clone(),
&self.identity_key.0,
&self.platform,
);
let my_pubkey = self.identity_key.public();
if my_pubkey == event.pubkey {
// if the first gatekeeper reboots, it will possess the master key, and should not re-generate it
if master_key_history.is_empty() {
info!("Gatekeeper: generate master key as the first gatekeeper");
// generate master key as the first gatekeeper, no need to restart
let master_key = crate::new_sr25519_key();
master_key_history.push(RotatedMasterKey {
rotation_id: 0,
block_height: 0,
secret: master_key.dump_secret_key(),
});
// manually seal the first master key for the first gk
master_key::seal(
self.sealing_path.clone(),
&master_key_history,
&self.identity_key,
&self.platform,
);
}
let master_key = sr25519::Pair::restore_from_secret_key(
&master_key_history.first().expect("checked; qed.").secret,
);
// upload the master key on chain via worker egress
info!(
"Gatekeeper: upload master key {} on chain",
hex::encode(master_key.public())
);
let master_pubkey = RegistryEvent::MasterPubkey {
master_pubkey: master_key.public(),
};
self.egress.push_message(&master_pubkey);
}
// other gatekeepers will has keys after key sharing and reboot
// init the gatekeeper if there is any master key to start slient syncing
if !master_key_history.is_empty() {
info!("Init gatekeeper in block {}", block.block_number);
self.init_gatekeeper(block, master_key_history);
}
if my_pubkey == event.pubkey {
self.gatekeeper
.as_mut()
.expect("gatekeeper must be initializaed; qed.")
.register_on_chain();
}
}
/// Rotate the master key
///
/// All the gatekeepers will generate the key, and only one will get published due to the nature of message queue.
///
/// The generated master key will be shared to all the gatekeepers (include this one), and only then will they really
/// update the master key on-chain.
fn process_master_key_rotation_request(
&mut self,
block: &mut BlockInfo,
_origin: MessageOrigin,
event: RotateMasterKeyEvent,
) {
if let Some(gatekeeper) = &mut self.gatekeeper {
info!("Gatekeeper:Rotate master key");
gatekeeper.process_master_key_rotation_request(
block,
event,
self.identity_key.0.clone(),
);
}
}
fn process_gatekeeper_change_event(
&mut self,
block: &mut BlockInfo,
origin: MessageOrigin,
event: GatekeeperChange,
) {
info!("Incoming gatekeeper change event: {:?}", event);
match event {
GatekeeperChange::Registered(event) => {
self.process_new_gatekeeper_event(block, origin, event)
}
GatekeeperChange::Unregistered(event) => {
self.process_remove_gatekeeper_event(block, origin, event)
}
}
}