-
Notifications
You must be signed in to change notification settings - Fork 35
/
enclave.go
1624 lines (1392 loc) · 59.4 KB
/
enclave.go
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
package enclave
import (
"context"
"crypto/ecdsa"
"encoding/json"
"errors"
"fmt"
"math/big"
"sync"
"time"
"github.com/obscuronet/go-obscuro/go/common/measure"
"github.com/obscuronet/go-obscuro/go/enclave/gas"
"github.com/obscuronet/go-obscuro/go/enclave/storage"
"github.com/obscuronet/go-obscuro/go/enclave/vkhandler"
"github.com/obscuronet/go-obscuro/go/common/compression"
"github.com/obscuronet/go-obscuro/go/enclave/components"
"github.com/obscuronet/go-obscuro/go/enclave/nodetype"
"github.com/obscuronet/go-obscuro/go/enclave/l2chain"
"github.com/obscuronet/go-obscuro/go/responses"
"github.com/obscuronet/go-obscuro/go/enclave/genesis"
"github.com/obscuronet/go-obscuro/go/enclave/core"
"github.com/obscuronet/go-obscuro/go/common/errutil"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto/ecies"
"github.com/ethereum/go-ethereum/eth/filters"
"github.com/ethereum/go-ethereum/params"
"github.com/obscuronet/go-obscuro/go/common"
"github.com/obscuronet/go-obscuro/go/common/gethapi"
"github.com/obscuronet/go-obscuro/go/common/gethencoding"
"github.com/obscuronet/go-obscuro/go/common/log"
"github.com/obscuronet/go-obscuro/go/common/profiler"
"github.com/obscuronet/go-obscuro/go/common/stopcontrol"
"github.com/obscuronet/go-obscuro/go/common/syserr"
"github.com/obscuronet/go-obscuro/go/common/tracers"
"github.com/obscuronet/go-obscuro/go/config"
"github.com/obscuronet/go-obscuro/go/enclave/crosschain"
"github.com/obscuronet/go-obscuro/go/enclave/crypto"
"github.com/obscuronet/go-obscuro/go/enclave/debugger"
"github.com/obscuronet/go-obscuro/go/enclave/events"
"github.com/obscuronet/go-obscuro/go/enclave/mempool"
"github.com/obscuronet/go-obscuro/go/enclave/rpc"
"github.com/obscuronet/go-obscuro/go/ethadapter/mgmtcontractlib"
_ "github.com/obscuronet/go-obscuro/go/common/tracers/native" // make sure the tracers are loaded
gethcommon "github.com/ethereum/go-ethereum/common"
gethcore "github.com/ethereum/go-ethereum/core"
gethcrypto "github.com/ethereum/go-ethereum/crypto"
gethlog "github.com/ethereum/go-ethereum/log"
gethrpc "github.com/ethereum/go-ethereum/rpc"
)
var _noHeadBatch = big.NewInt(0)
type enclaveImpl struct {
config *config.EnclaveConfig
storage storage.Storage
blockResolver storage.BlockResolver
l1BlockProcessor components.L1BlockProcessor
rollupConsumer components.RollupConsumer
l1Blockchain *gethcore.BlockChain
rpcEncryptionManager rpc.EncryptionManager
subscriptionManager *events.SubscriptionManager
crossChainProcessors *crosschain.Processors
sharedSecretProcessor *components.SharedSecretProcessor
chain l2chain.ObscuroChain
service nodetype.NodeType
registry components.BatchRegistry
// todo (#627) - use the ethconfig.Config instead
GlobalGasCap uint64 // 5_000_000_000, // todo (#627) - make config
BaseFee *big.Int // gethcommon.Big0,
mgmtContractLib mgmtcontractlib.MgmtContractLib
attestationProvider components.AttestationProvider // interface for producing attestation reports and verifying them
enclaveKey *ecdsa.PrivateKey // this is a key specific to this enclave, which is included in the Attestation. Used for signing rollups and for encryption of the shared secret.
enclavePubKey []byte // the public key of the above
dataEncryptionService crypto.DataEncryptionService
dataCompressionService compression.DataCompressionService
profiler *profiler.Profiler
debugger *debugger.Debugger
logger gethlog.Logger
stopControl *stopcontrol.StopControl
mainMutex sync.Mutex // serialises all data ingestion or creation to avoid weird races
}
// NewEnclave creates a new enclave.
// `genesisJSON` is the configuration for the corresponding L1's genesis block. This is used to validate the blocks
// received from the L1 node if `validateBlocks` is set to true.
func NewEnclave(
config *config.EnclaveConfig,
genesis *genesis.Genesis,
mgmtContractLib mgmtcontractlib.MgmtContractLib,
logger gethlog.Logger,
) common.Enclave {
jsonConfig, _ := json.MarshalIndent(config, "", " ")
logger.Info("Creating enclave service with following config", log.CfgKey, string(jsonConfig))
// todo (#1053) - add the delay: N hashes
var prof *profiler.Profiler
// don't run a profiler on an attested enclave
if !config.WillAttest && config.ProfilerEnabled {
prof = profiler.NewProfiler(profiler.DefaultEnclavePort, logger)
err := prof.Start()
if err != nil {
logger.Crit("unable to start the profiler", log.ErrKey, err)
}
}
zeroTimestamp := uint64(0)
// Initialise the database
chainConfig := params.ChainConfig{
ChainID: big.NewInt(config.ObscuroChainID),
HomesteadBlock: gethcommon.Big0,
DAOForkBlock: gethcommon.Big0,
EIP150Block: gethcommon.Big0,
EIP155Block: gethcommon.Big0,
EIP158Block: gethcommon.Big0,
ByzantiumBlock: gethcommon.Big0,
ConstantinopleBlock: gethcommon.Big0,
PetersburgBlock: gethcommon.Big0,
IstanbulBlock: gethcommon.Big0,
MuirGlacierBlock: gethcommon.Big0,
BerlinBlock: gethcommon.Big0,
LondonBlock: gethcommon.Big0,
CancunTime: &zeroTimestamp,
ShanghaiTime: &zeroTimestamp,
PragueTime: &zeroTimestamp,
VerkleTime: &zeroTimestamp,
}
storage := storage.NewStorageFromConfig(config, &chainConfig, logger)
// Initialise the Ethereum "Blockchain" structure that will allow us to validate incoming blocks
// todo (#1056) - valid block
var l1Blockchain *gethcore.BlockChain
if config.ValidateL1Blocks {
if config.GenesisJSON == nil {
logger.Crit("enclave is configured to validate blocks, but genesis JSON is nil")
}
l1Blockchain = l2chain.NewL1Blockchain(config.GenesisJSON, logger)
} else {
logger.Info("validateBlocks is set to false. L1 blocks will not be validated.")
}
// todo (#1474) - make sure the enclave cannot be started in production with WillAttest=false
var attestationProvider components.AttestationProvider
if config.WillAttest {
attestationProvider = &components.EgoAttestationProvider{}
} else {
logger.Info("WARNING - Attestation is not enabled, enclave will not create a verified attestation report.")
attestationProvider = &components.DummyAttestationProvider{}
}
// attempt to fetch the enclave key from the database
enclaveKey, err := storage.GetEnclaveKey()
if err != nil {
if !errors.Is(err, errutil.ErrNotFound) {
logger.Crit("Failed to fetch enclave key", log.ErrKey, err)
}
// enclave key not found - new key should be generated
// todo (#1053) - revisit the crypto for this key generation/lifecycle before production
logger.Info("Generating the Obscuro key")
enclaveKey, err = gethcrypto.GenerateKey()
if err != nil {
logger.Crit("Failed to generate enclave key.", log.ErrKey, err)
}
err = storage.StoreEnclaveKey(enclaveKey)
if err != nil {
logger.Crit("Failed to store enclave key.", log.ErrKey, err)
}
}
serializedEnclavePubKey := gethcrypto.CompressPubkey(&enclaveKey.PublicKey)
logger.Info(fmt.Sprintf("Generated public key %s", gethcommon.Bytes2Hex(serializedEnclavePubKey)))
obscuroKey := crypto.GetObscuroKey(logger)
rpcEncryptionManager := rpc.NewEncryptionManager(ecies.ImportECDSA(obscuroKey))
dataEncryptionService := crypto.NewDataEncryptionService(logger)
dataCompressionService := compression.NewBrotliDataCompressionService()
memp := mempool.New(config.ObscuroChainID, logger)
crossChainProcessors := crosschain.New(&config.MessageBusAddress, storage, big.NewInt(config.ObscuroChainID), logger)
subscriptionManager := events.NewSubscriptionManager(&rpcEncryptionManager, storage, logger)
gasOracle := gas.NewGasOracle()
blockProcessor := components.NewBlockProcessor(storage, crossChainProcessors, gasOracle, logger)
batchExecutor := components.NewBatchExecutor(storage, crossChainProcessors, genesis, gasOracle, &chainConfig, logger)
sigVerifier, err := components.NewSignatureValidator(config.SequencerID, storage)
registry := components.NewBatchRegistry(storage, logger)
rProducer := components.NewRollupProducer(config.SequencerID, storage, registry, logger)
if err != nil {
logger.Crit("Could not initialise the signature validator", log.ErrKey, err)
}
rollupCompression := components.NewRollupCompression(registry, batchExecutor, dataEncryptionService, dataCompressionService, storage, &chainConfig, logger)
rConsumer := components.NewRollupConsumer(mgmtContractLib, registry, rollupCompression, storage, logger, sigVerifier)
sharedSecretProcessor := components.NewSharedSecretProcessor(mgmtContractLib, attestationProvider, storage, logger)
var service nodetype.NodeType
if config.NodeType == common.Sequencer {
service = nodetype.NewSequencer(
blockProcessor,
batchExecutor,
registry,
rProducer,
rConsumer,
rollupCompression,
logger,
config.HostID,
&chainConfig,
enclaveKey,
memp,
storage,
dataEncryptionService,
dataCompressionService,
nodetype.SequencerSettings{
MaxBatchSize: config.MaxBatchSize,
MaxRollupSize: config.MaxRollupSize,
GasPaymentAddress: config.GasPaymentAddress,
BatchGasLimit: config.GasLimit,
BaseFee: config.BaseFee,
},
)
} else {
service = nodetype.NewValidator(blockProcessor, batchExecutor, registry, rConsumer, &chainConfig, config.SequencerID, storage, sigVerifier, logger)
}
chain := l2chain.NewChain(
storage,
&chainConfig,
genesis,
logger,
registry,
)
// ensure cached chain state data is up-to-date using the persisted batch data
err = restoreStateDBCache(storage, registry, batchExecutor, genesis, logger)
if err != nil {
logger.Crit("failed to resync L2 chain state DB after restart", log.ErrKey, err)
}
// TODO ensure debug is allowed/disallowed
debug := debugger.New(chain, storage, &chainConfig)
logger.Info("Enclave service created with following config", log.CfgKey, config.HostID)
return &enclaveImpl{
config: config,
storage: storage,
blockResolver: storage,
l1BlockProcessor: blockProcessor,
rollupConsumer: rConsumer,
l1Blockchain: l1Blockchain,
rpcEncryptionManager: rpcEncryptionManager,
subscriptionManager: subscriptionManager,
crossChainProcessors: crossChainProcessors,
mgmtContractLib: mgmtContractLib,
attestationProvider: attestationProvider,
sharedSecretProcessor: sharedSecretProcessor,
enclaveKey: enclaveKey,
enclavePubKey: serializedEnclavePubKey,
dataEncryptionService: dataEncryptionService,
dataCompressionService: dataCompressionService,
profiler: prof,
logger: logger,
debugger: debug,
stopControl: stopcontrol.New(),
chain: chain,
registry: registry,
service: service,
GlobalGasCap: 5_000_000_000, // todo (#627) - make config
BaseFee: gethcommon.Big0,
mainMutex: sync.Mutex{},
}
}
func (e *enclaveImpl) GetBatch(hash common.L2BatchHash) (*common.ExtBatch, common.SystemError) {
batch, err := e.storage.FetchBatch(hash)
if err != nil {
return nil, responses.ToInternalError(fmt.Errorf("failed getting batch. Cause: %w", err))
}
b, err := batch.ToExtBatch(e.dataEncryptionService, e.dataCompressionService)
if err != nil {
return nil, responses.ToInternalError(err)
}
return b, nil
}
func (e *enclaveImpl) GetBatchBySeqNo(seqNo uint64) (*common.ExtBatch, common.SystemError) {
batch, err := e.storage.FetchBatchBySeqNo(seqNo)
if err != nil {
return nil, responses.ToInternalError(fmt.Errorf("failed getting batch. Cause: %w", err))
}
b, err := batch.ToExtBatch(e.dataEncryptionService, e.dataCompressionService)
if err != nil {
return nil, responses.ToInternalError(err)
}
return b, nil
}
// Status is only implemented by the RPC wrapper
func (e *enclaveImpl) Status() (common.Status, common.SystemError) {
if e.stopControl.IsStopping() {
return common.Status{StatusCode: common.Unavailable}, responses.ToInternalError(fmt.Errorf("requested Status with the enclave stopping"))
}
_, err := e.storage.FetchSecret()
if err != nil {
if errors.Is(err, errutil.ErrNotFound) {
return common.Status{StatusCode: common.AwaitingSecret, L2Head: _noHeadBatch}, nil
}
return common.Status{StatusCode: common.Unavailable}, responses.ToInternalError(err)
}
var l1HeadHash gethcommon.Hash
l1Head, err := e.storage.FetchHeadBlock()
if err != nil {
// this might be normal while enclave is starting up, just send empty hash
e.logger.Debug("failed to fetch L1 head block for status response", log.ErrKey, err)
} else {
l1HeadHash = l1Head.Hash()
}
// we use zero when there's no head batch yet, the first seq number is 1
l2HeadSeqNo := _noHeadBatch
// this is the highest seq number that has been received and stored on the enclave (it may not have been executed)
currSeqNo, err := e.storage.FetchCurrentSequencerNo()
if err != nil {
// this might be normal while enclave is starting up, just send empty hash
e.logger.Debug("failed to fetch L2 head batch for status response", log.ErrKey, err)
} else {
l2HeadSeqNo = currSeqNo
}
return common.Status{StatusCode: common.Running, L1Head: l1HeadHash, L2Head: l2HeadSeqNo}, nil
}
// StopClient is only implemented by the RPC wrapper
func (e *enclaveImpl) StopClient() common.SystemError {
return nil // The enclave is local so there is no client to stop
}
func (e *enclaveImpl) sendBatch(batch *core.Batch, outChannel chan common.StreamL2UpdatesResponse) {
e.logger.Info("Streaming batch to host", log.BatchHashKey, batch.Hash(), log.BatchSeqNoKey, batch.SeqNo())
extBatch, err := batch.ToExtBatch(e.dataEncryptionService, e.dataCompressionService)
if err != nil {
// this error is unrecoverable
e.logger.Crit("failed to convert batch", log.ErrKey, err)
}
resp := common.StreamL2UpdatesResponse{
Batch: extBatch,
}
outChannel <- resp
}
// this function is only called when the executed batch is the new head
func (e *enclaveImpl) streamEventsForNewHeadBatch(batch *core.Batch, receipts types.Receipts, outChannel chan common.StreamL2UpdatesResponse) {
logs, err := e.subscriptionManager.GetSubscribedLogsForBatch(batch, receipts)
e.logger.Debug("Stream Events for", log.BatchHashKey, batch.Hash(), "nr_events", len(logs))
if err != nil {
e.logger.Error("Error while getting subscription logs", log.ErrKey, err)
return
}
if logs != nil {
outChannel <- common.StreamL2UpdatesResponse{
Logs: logs,
}
}
}
func (e *enclaveImpl) StreamL2Updates() (chan common.StreamL2UpdatesResponse, func()) {
l2UpdatesChannel := make(chan common.StreamL2UpdatesResponse, 100)
if e.stopControl.IsStopping() {
close(l2UpdatesChannel)
return l2UpdatesChannel, func() {}
}
e.registry.SubscribeForExecutedBatches(func(batch *core.Batch, receipts types.Receipts) {
e.sendBatch(batch, l2UpdatesChannel)
if receipts != nil {
e.streamEventsForNewHeadBatch(batch, receipts, l2UpdatesChannel)
}
})
return l2UpdatesChannel, func() {
e.registry.UnsubscribeFromBatches()
}
}
// SubmitL1Block is used to update the enclave with an additional L1 block.
func (e *enclaveImpl) SubmitL1Block(block types.Block, receipts types.Receipts, _ bool) (*common.BlockSubmissionResponse, common.SystemError) {
if e.stopControl.IsStopping() {
return nil, responses.ToInternalError(fmt.Errorf("requested SubmitL1Block with the enclave stopping"))
}
e.mainMutex.Lock()
defer e.mainMutex.Unlock()
e.logger.Info("SubmitL1Block", log.BlockHeightKey, block.Number(), log.BlockHashKey, block.Hash())
// If the block and receipts do not match, reject the block.
br, err := common.ParseBlockAndReceipts(&block, &receipts)
if err != nil {
return nil, e.rejectBlockErr(fmt.Errorf("could not submit L1 block. Cause: %w", err))
}
result, err := e.ingestL1Block(br)
if err != nil {
return nil, e.rejectBlockErr(fmt.Errorf("could not submit L1 block. Cause: %w", err))
}
if result.IsFork() {
e.logger.Info(fmt.Sprintf("Detected fork at block %s with height %d", block.Hash(), block.Number()))
}
err = e.service.OnL1Block(block, result)
if err != nil {
return nil, e.rejectBlockErr(fmt.Errorf("could not submit L1 block. Cause: %w", err))
}
bsr := &common.BlockSubmissionResponse{ProducedSecretResponses: e.sharedSecretProcessor.ProcessNetworkSecretMsgs(br)}
return bsr, nil
}
func (e *enclaveImpl) ingestL1Block(br *common.BlockAndReceipts) (*components.BlockIngestionType, error) {
e.logger.Info("Start ingesting block", log.BlockHashKey, br.Block.Hash())
ingestion, err := e.l1BlockProcessor.Process(br)
if err != nil {
// only warn for unexpected errors
if errors.Is(err, errutil.ErrBlockAncestorNotFound) || errors.Is(err, errutil.ErrBlockAlreadyProcessed) {
e.logger.Debug("Did not ingest block", log.ErrKey, err, log.BlockHashKey, br.Block.Hash())
} else {
e.logger.Warn("Failed ingesting block", log.ErrKey, err, log.BlockHashKey, br.Block.Hash())
}
return nil, err
}
err = e.rollupConsumer.ProcessRollupsInBlock(br)
if err != nil && !errors.Is(err, components.ErrDuplicateRollup) {
e.logger.Error("Encountered error while processing l1 block", log.ErrKey, err)
// Unsure what to do here; block has been stored
}
if ingestion.IsFork() {
err := e.service.OnL1Fork(ingestion.ChainFork)
if err != nil {
return nil, err
}
}
return ingestion, nil
}
func (e *enclaveImpl) SubmitTx(tx common.EncryptedTx) (*responses.RawTx, common.SystemError) {
if e.stopControl.IsStopping() {
return nil, responses.ToInternalError(fmt.Errorf("requested SubmitTx with the enclave stopping"))
}
// decode the received request into a []interface
paramList, err := e.decodeRequest(tx)
if err != nil {
return responses.AsPlaintextError(fmt.Errorf("unable to decode eth_call params - %w", err)), nil
}
// Parameters are [ViewingKey, Transaction]
if len(paramList) != 2 {
return responses.AsPlaintextError(fmt.Errorf("unexpected number of parameters")), nil
}
decryptedTx, err := rpc.ExtractTx(paramList[1].(string))
if err != nil {
e.logger.Info("could not decrypt transaction. ", log.ErrKey, err)
return responses.AsPlaintextError(fmt.Errorf("could not decrypt transaction. Cause: %w", err)), nil
}
e.logger.Debug("Submitted transaction", log.TxKey, decryptedTx.Hash())
viewingKeyAddress, err := rpc.GetSender(decryptedTx)
if err != nil {
if errors.Is(err, types.ErrInvalidSig) {
return responses.AsPlaintextError(fmt.Errorf("transaction contains invalid signature")), nil
}
return responses.AsPlaintextError(fmt.Errorf("could not recover from address. Cause: %w", err)), nil
}
// extract, create and validate the VK encryption handler
vkHandler, err := createVKHandler(&viewingKeyAddress, paramList[0])
if err != nil {
return responses.AsPlaintextError(fmt.Errorf("unable to create VK encryptor - %w", err)), nil
}
if e.crossChainProcessors.Local.IsSyntheticTransaction(*decryptedTx) {
return responses.AsPlaintextError(responses.ToInternalError(fmt.Errorf("synthetic transaction coming from external rpc"))), nil
}
if err = e.checkGas(decryptedTx); err != nil {
e.logger.Info("gas check failed", log.ErrKey, err.Error())
return responses.AsEncryptedError(err, vkHandler), nil
}
if err = e.service.SubmitTransaction(decryptedTx); err != nil {
e.logger.Debug("Could not submit transaction", log.TxKey, decryptedTx.Hash(), log.ErrKey, err)
return responses.AsEncryptedError(err, vkHandler), nil
}
hash := decryptedTx.Hash().Hex()
return responses.AsEncryptedResponse(&hash, vkHandler), nil
}
func (e *enclaveImpl) Validator() nodetype.ObsValidator {
validator, ok := e.service.(nodetype.ObsValidator)
if !ok {
panic("enclave service is not a validator but validator was requested!")
}
return validator
}
func (e *enclaveImpl) Sequencer() nodetype.Sequencer {
sequencer, ok := e.service.(nodetype.Sequencer)
if !ok {
panic("enclave service is not a sequencer but sequencer was requested!")
}
return sequencer
}
func (e *enclaveImpl) SubmitBatch(extBatch *common.ExtBatch) common.SystemError {
if e.stopControl.IsStopping() {
return responses.ToInternalError(fmt.Errorf("requested SubmitBatch with the enclave stopping"))
}
core.LogMethodDuration(e.logger, measure.NewStopwatch(), "SubmitBatch call completed.", log.BatchHashKey, extBatch.Hash())
e.logger.Info("Received new p2p batch", log.BatchHeightKey, extBatch.Header.Number, log.BatchHashKey, extBatch.Hash(), "l1", extBatch.Header.L1Proof)
batch, err := core.ToBatch(extBatch, e.dataEncryptionService, e.dataCompressionService)
if err != nil {
return responses.ToInternalError(fmt.Errorf("could not convert batch. Cause: %w", err))
}
err = e.Validator().VerifySequencerSignature(batch)
if err != nil {
return responses.ToInternalError(fmt.Errorf("invalid batch received. Could not verify signature. Cause: %w", err))
}
e.mainMutex.Lock()
defer e.mainMutex.Unlock()
// if the signature is valid, then store the batch
err = e.storage.StoreBatch(batch)
if err != nil {
return responses.ToInternalError(fmt.Errorf("could not store batch. Cause: %w", err))
}
err = e.Validator().ExecuteStoredBatches()
if err != nil {
return responses.ToInternalError(fmt.Errorf("could not execute batches. Cause: %w", err))
}
return nil
}
func (e *enclaveImpl) CreateBatch(skipBatchIfEmpty bool) common.SystemError {
defer core.LogMethodDuration(e.logger, measure.NewStopwatch(), "CreateBatch call ended")
if e.stopControl.IsStopping() {
return responses.ToInternalError(fmt.Errorf("requested CreateBatch with the enclave stopping"))
}
e.mainMutex.Lock()
defer e.mainMutex.Unlock()
err := e.Sequencer().CreateBatch(skipBatchIfEmpty)
if err != nil {
return responses.ToInternalError(err)
}
return nil
}
func (e *enclaveImpl) CreateRollup(fromSeqNo uint64) (*common.ExtRollup, common.SystemError) {
defer core.LogMethodDuration(e.logger, measure.NewStopwatch(), "CreateRollup call ended")
if e.stopControl.IsStopping() {
return nil, responses.ToInternalError(fmt.Errorf("requested GenerateRollup with the enclave stopping"))
}
// todo - remove once the db operations are more atomic
e.mainMutex.Lock()
defer e.mainMutex.Unlock()
rollup, err := e.Sequencer().CreateRollup(fromSeqNo)
if err != nil {
return nil, responses.ToInternalError(err)
}
return rollup, nil
}
// ObsCall handles param decryption, validation and encryption
// and requests the Rollup chain to execute the payload (eth_call)
func (e *enclaveImpl) ObsCall(encryptedParams common.EncryptedParamsCall) (*responses.Call, common.SystemError) {
if e.stopControl.IsStopping() {
return nil, responses.ToInternalError(fmt.Errorf("requested ObsCall with the enclave stopping"))
}
// decode the received request into a []interface
paramList, err := e.decodeRequest(encryptedParams)
if err != nil {
return responses.AsPlaintextError(fmt.Errorf("unable to decode eth_call params - %w", err)), nil
}
// Parameters are [ViewingKey, TransactionArgs, BlockNumber]
if len(paramList) != 3 {
return responses.AsPlaintextError(fmt.Errorf("unexpected number of parameters")), nil
}
apiArgs, err := gethencoding.ExtractEthCall(paramList[1])
if err != nil {
err = fmt.Errorf("unable to decode EthCall Params - %w", err)
return responses.AsPlaintextError(err), nil
}
// encryption will fail if no From address is provided
if apiArgs.From == nil {
err = fmt.Errorf("no from address provided")
return responses.AsPlaintextError(err), nil
}
// extract, create and validate the VK encryption handler
vkHandler, err := createVKHandler(apiArgs.From, paramList[0])
if err != nil {
return responses.AsPlaintextError(fmt.Errorf("unable to create VK encryptor - %w", err)), nil
}
blkNumber, err := gethencoding.ExtractBlockNumber(paramList[2])
if err != nil {
err = fmt.Errorf("unable to extract requested block number - %w", err)
return responses.AsEncryptedError(err, vkHandler), nil
}
execResult, err := e.chain.ObsCall(apiArgs, blkNumber)
if err != nil {
e.logger.Debug("Failed eth_call.", log.ErrKey, err)
// make sure it's not some internal error
if errors.Is(err, syserr.InternalError{}) {
return nil, responses.ToInternalError(err)
}
// make sure to serialize any possible EVM error
evmErr, err := serializeEVMError(err)
if err == nil {
err = fmt.Errorf(string(evmErr))
}
return responses.AsEncryptedError(err, vkHandler), nil
}
// encrypt the result payload
var encodedResult string
if len(execResult.ReturnData) != 0 {
encodedResult = hexutil.Encode(execResult.ReturnData)
}
return responses.AsEncryptedResponse(&encodedResult, vkHandler), nil
}
func (e *enclaveImpl) GetTransactionCount(encryptedParams common.EncryptedParamsGetTxCount) (*responses.TxCount, common.SystemError) {
if e.stopControl.IsStopping() {
return nil, responses.ToInternalError(fmt.Errorf("requested GetTransactionCount with the enclave stopping"))
}
// decode the received request into a []interface
paramList, err := e.decodeRequest(encryptedParams)
if err != nil {
return responses.AsPlaintextError(fmt.Errorf("unable to decode eth_transactionCount params - %w", err)), nil
}
// Parameters are [ViewingKey, Address]
if len(paramList) < 2 {
return responses.AsPlaintextError(fmt.Errorf("unexpected number of parameters")), nil
}
addressStr, ok := paramList[1].(string)
if !ok {
return responses.AsPlaintextError(fmt.Errorf("unexpected address parameter")), nil
}
address := gethcommon.HexToAddress(addressStr)
// extract, create and validate the VK encryption handler
vkHandler, err := createVKHandler(&address, paramList[0])
if err != nil {
return responses.AsPlaintextError(fmt.Errorf("unable to create VK encryptor - %w", err)), nil
}
var nonce uint64
l2Head, err := e.storage.FetchBatchBySeqNo(e.registry.HeadBatchSeq().Uint64())
if err == nil {
// todo - we should return an error when head state is not available, but for current test situations with race
// conditions we allow it to return zero while head state is uninitialized
s, err := e.storage.CreateStateDB(l2Head.Hash())
if err != nil {
return nil, responses.ToInternalError(err)
}
nonce = s.GetNonce(address)
}
encoded := hexutil.EncodeUint64(nonce)
return responses.AsEncryptedResponse(&encoded, vkHandler), nil
}
func (e *enclaveImpl) GetTransaction(encryptedParams common.EncryptedParamsGetTxByHash) (*responses.TxByHash, common.SystemError) {
if e.stopControl.IsStopping() {
return nil, responses.ToInternalError(fmt.Errorf("requested GetTransaction with the enclave stopping"))
}
// decode the received request into a []interface
paramList, err := e.decodeRequest(encryptedParams)
if err != nil {
return responses.AsPlaintextError(fmt.Errorf("unable to decode eth_getTransaction params - %w", err)), nil
}
// Parameters are [ViewingKey, Hash]
if len(paramList) != 2 {
return responses.AsPlaintextError(fmt.Errorf("unexpected number of parameters")), nil
}
txHashStr, ok := paramList[1].(string)
if !ok {
return responses.AsPlaintextError(fmt.Errorf("unexpected tx hash parameter")), nil
}
txHash := gethcommon.HexToHash(txHashStr)
// Unlike in the Geth impl, we do not try and retrieve unconfirmed transactions from the mempool.
tx, blockHash, blockNumber, index, err := e.storage.GetTransaction(txHash)
if err != nil {
if errors.Is(err, errutil.ErrNotFound) {
// like geth, return an empty response when a not found tx is requested
return responses.AsEmptyResponse(), nil
}
return responses.AsPlaintextError(err), nil
}
viewingKeyAddress, err := rpc.GetSender(tx)
if err != nil {
err = fmt.Errorf("could not recover viewing key address to encrypt eth_getTransactionByHash response. Cause: %w", err)
return responses.AsPlaintextError(err), nil
}
// extract, create and validate the VK encryption handler
vkHandler, err := createVKHandler(&viewingKeyAddress, paramList[0])
if err != nil {
return responses.AsPlaintextError(fmt.Errorf("unable to create VK encryptor - %w", err)), nil
}
// Unlike in the Geth impl, we hardcode the use of a London signer.
// todo (#1553) - once the enclave's genesis.json is set, retrieve the signer type using `types.MakeSigner`
signer := types.NewLondonSigner(tx.ChainId())
rpcTx := newRPCTransaction(tx, blockHash, blockNumber, index, gethcommon.Big0, signer)
return responses.AsEncryptedResponse(rpcTx, vkHandler), nil
}
func (e *enclaveImpl) GetTransactionReceipt(encryptedParams common.EncryptedParamsGetTxReceipt) (*responses.TxReceipt, common.SystemError) {
if e.stopControl.IsStopping() {
return nil, responses.ToInternalError(fmt.Errorf("requested GetTransactionReceipt with the enclave stopping"))
}
// decode the received request into a []interface
paramList, err := e.decodeRequest(encryptedParams)
if err != nil {
return responses.AsPlaintextError(fmt.Errorf("unable to decode eth_getTransaction params - %w", err)), nil
}
// Parameters are [ViewingKey, Hash]
if len(paramList) != 2 {
return responses.AsPlaintextError(fmt.Errorf("unexpected number of parameters")), nil
}
txHashStr, ok := paramList[1].(string)
if !ok {
return responses.AsPlaintextError(fmt.Errorf("unable to parse the tx hash")), nil
}
txHash := gethcommon.HexToHash(txHashStr)
// todo - optimise these calls. This can be done with a single sql
e.logger.Trace("Get receipt for ", "txHash", txHash)
// We retrieve the transaction.
tx, _, _, _, err := e.storage.GetTransaction(txHash) //nolint:dogsled
if err != nil {
e.logger.Trace("error getting tx ", "txHash", txHash, log.ErrKey, err)
if errors.Is(err, errutil.ErrNotFound) {
// like geth return an empty response when a not-found tx is requested
return responses.AsEmptyResponse(), nil
}
return responses.AsPlaintextError(err), nil
}
// We retrieve the sender's address.
sender, err := rpc.GetSender(tx)
if err != nil {
e.logger.Trace("error getting sender tx ", "txHash", txHash, log.ErrKey, err)
return responses.AsPlaintextError(fmt.Errorf("could not recover viewing key address to encrypt eth_getTransactionReceipt response. Cause: %w", err)), nil
}
// extract, create and validate the VK encryption handler
vkHandler, err := createVKHandler(&sender, paramList[0])
if err != nil {
e.logger.Trace("error getting the vk ", "txHash", txHash, log.ErrKey, err)
return responses.AsPlaintextError(fmt.Errorf("unable to create VK encryptor - %w", err)), nil
}
// We retrieve the transaction receipt.
txReceipt, err := e.storage.GetTransactionReceipt(txHash)
if err != nil {
e.logger.Trace("error getting tx receipt", "txHash", txHash, log.ErrKey, err)
if errors.Is(err, errutil.ErrNotFound) {
// like geth return an empty response when a not-found tx is requested
return responses.AsEmptyResponse(), nil
}
err = fmt.Errorf("could not retrieve transaction receipt in eth_getTransactionReceipt request. Cause: %w", err)
return responses.AsEncryptedError(err, vkHandler), nil
}
// We filter out irrelevant logs.
txReceipt.Logs, err = e.subscriptionManager.FilterLogsForReceipt(txReceipt, &sender)
if err != nil {
e.logger.Trace("error filter logs ", "txHash", txHash, log.ErrKey, err)
return nil, responses.ToInternalError(err)
}
e.logger.Trace("Successfully retreived receipt for ", "txHash", txHash, "rec", txReceipt)
return responses.AsEncryptedResponse(txReceipt, vkHandler), nil
}
func (e *enclaveImpl) Attestation() (*common.AttestationReport, common.SystemError) {
if e.stopControl.IsStopping() {
return nil, responses.ToInternalError(fmt.Errorf("requested ObsCall with the enclave stopping"))
}
if e.enclavePubKey == nil {
return nil, responses.ToInternalError(fmt.Errorf("public key not initialized, we can't produce the attestation report"))
}
report, err := e.attestationProvider.GetReport(e.enclavePubKey, e.config.HostID, e.config.HostAddress)
if err != nil {
return nil, responses.ToInternalError(fmt.Errorf("could not produce remote report. Cause %w", err))
}
return report, nil
}
// GenerateSecret - the genesis enclave is responsible with generating the secret entropy
func (e *enclaveImpl) GenerateSecret() (common.EncryptedSharedEnclaveSecret, common.SystemError) {
if e.stopControl.IsStopping() {
return nil, responses.ToInternalError(fmt.Errorf("requested GenerateSecret with the enclave stopping"))
}
secret := crypto.GenerateEntropy(e.logger)
err := e.storage.StoreSecret(secret)
if err != nil {
return nil, responses.ToInternalError(fmt.Errorf("could not store secret. Cause: %w", err))
}
encSec, err := crypto.EncryptSecret(e.enclavePubKey, secret, e.logger)
if err != nil {
return nil, responses.ToInternalError(fmt.Errorf("failed to encrypt secret. Cause: %w", err))
}
return encSec, nil
}
// InitEnclave - initialise an enclave with a seed received by another enclave
func (e *enclaveImpl) InitEnclave(s common.EncryptedSharedEnclaveSecret) common.SystemError {
if e.stopControl.IsStopping() {
return responses.ToInternalError(fmt.Errorf("requested InitEnclave with the enclave stopping"))
}
secret, err := crypto.DecryptSecret(s, e.enclaveKey)
if err != nil {
return responses.ToInternalError(err)
}
err = e.storage.StoreSecret(*secret)
if err != nil {
return responses.ToInternalError(fmt.Errorf("could not store secret. Cause: %w", err))
}
e.logger.Trace(fmt.Sprintf("Secret decrypted and stored. Secret: %v", secret))
return nil
}
// GetBalance handles param decryption, validation and encryption
// and requests the Rollup chain to execute the payload (eth_getBalance)
func (e *enclaveImpl) GetBalance(encryptedParams common.EncryptedParamsGetBalance) (*responses.Balance, common.SystemError) {
if e.stopControl.IsStopping() {
return nil, responses.ToInternalError(fmt.Errorf("requested GetBalance with the enclave stopping"))
}
// decode the received request into a []interface
paramList, err := e.decodeRequest(encryptedParams)
if err != nil {
return responses.AsPlaintextError(fmt.Errorf("unable to decode eth_getBalance params - %w", err)), nil
}
// Parameters are [ViewingKey, Address, BlockNumber]
if len(paramList) != 3 {
return responses.AsPlaintextError(fmt.Errorf("unexpected number of parameters")), nil
}
requestedAddress, err := gethencoding.ExtractAddress(paramList[1])
if err != nil {
return responses.AsPlaintextError(fmt.Errorf("unable to extract requested address - %w", err)), nil
}
blockNumber, err := gethencoding.ExtractBlockNumber(paramList[2])
if err != nil {
return responses.AsPlaintextError(fmt.Errorf("unable to extract requested block number - %w", err)), nil
}
// params are correct, fetch the balance of the requested address
// If the accountAddress is a contract, encrypt with the address of the contract owner
encryptAddress, balance, err := e.chain.GetBalance(*requestedAddress, blockNumber)
if err != nil {
return responses.AsPlaintextError(fmt.Errorf("unable to get balance - %w", err)), nil
}
// extract, create and validate the VK encryption handler
vkHandler, err := createVKHandler(encryptAddress, paramList[0])
if err != nil {
return responses.AsPlaintextError(fmt.Errorf("unable to create VK encryptor - %w", err)), nil
}
return responses.AsEncryptedResponse(balance, vkHandler), nil
}
func (e *enclaveImpl) GetCode(address gethcommon.Address, batchHash *common.L2BatchHash) ([]byte, common.SystemError) {
if e.stopControl.IsStopping() {
return nil, responses.ToInternalError(fmt.Errorf("requested GetCode with the enclave stopping"))
}
stateDB, err := e.storage.CreateStateDB(*batchHash)
if err != nil {
return nil, responses.ToInternalError(fmt.Errorf("could not create stateDB. Cause: %w", err))
}
return stateDB.GetCode(address), nil
}
func (e *enclaveImpl) Subscribe(id gethrpc.ID, encryptedSubscription common.EncryptedParamsLogSubscription) common.SystemError {
if e.stopControl.IsStopping() {
return responses.ToInternalError(fmt.Errorf("requested SubscribeForExecutedBatches with the enclave stopping"))
}
return e.subscriptionManager.AddSubscription(id, encryptedSubscription)
}
func (e *enclaveImpl) Unsubscribe(id gethrpc.ID) common.SystemError {
if e.stopControl.IsStopping() {
return responses.ToInternalError(fmt.Errorf("requested Unsubscribe with the enclave stopping"))
}
e.subscriptionManager.RemoveSubscription(id)
return nil
}
func (e *enclaveImpl) Stop() common.SystemError {
// block all requests
e.stopControl.Stop()
if e.profiler != nil {
if err := e.profiler.Stop(); err != nil {
e.logger.Error("Could not stop profiler", log.ErrKey, err)
return err
}
}
if e.registry != nil {
e.registry.UnsubscribeFromBatches()
}
time.Sleep(time.Second)
err := e.storage.Close()
if err != nil {
e.logger.Error("Could not stop db", log.ErrKey, err)
return err
}
return nil
}