/
abci.go
1917 lines (1678 loc) · 59.3 KB
/
abci.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
// Copyright (c) 2022 Gobalsky Labs Limited
//
// Use of this software is governed by the Business Source License included
// in the LICENSE.ZETA file and at https://www.mariadb.com/bsl11.
//
// Change Date: 18 months from the later of the date of the first publicly
// available Distribution of this version of the repository, and 25 June 2022.
//
// On the date above, in accordance with the Business Source License, use
// of this software will be governed by version 3 or later of the GNU General
// Public License.
package processor
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"sync/atomic"
"time"
protoapi "github.com/zeta-protocol/zeta/protos/zeta/api/v1"
"github.com/zeta-protocol/zeta/commands"
"github.com/zeta-protocol/zeta/core/api"
"github.com/zeta-protocol/zeta/core/blockchain"
"github.com/zeta-protocol/zeta/core/blockchain/abci"
"github.com/zeta-protocol/zeta/core/events"
"github.com/zeta-protocol/zeta/core/genesis"
"github.com/zeta-protocol/zeta/core/idgeneration"
"github.com/zeta-protocol/zeta/core/processor/ratelimit"
"github.com/zeta-protocol/zeta/core/txn"
"github.com/zeta-protocol/zeta/core/types"
"github.com/zeta-protocol/zeta/core/types/statevar"
"github.com/zeta-protocol/zeta/core/zetatime"
vgcontext "github.com/zeta-protocol/zeta/libs/context"
vgcrypto "github.com/zeta-protocol/zeta/libs/crypto"
signatures "github.com/zeta-protocol/zeta/libs/crypto/signature"
vgfs "github.com/zeta-protocol/zeta/libs/fs"
"github.com/zeta-protocol/zeta/libs/num"
"github.com/zeta-protocol/zeta/logging"
"github.com/zeta-protocol/zeta/paths"
commandspb "github.com/zeta-protocol/zeta/protos/zeta/commands/v1"
eventspb "github.com/zeta-protocol/zeta/protos/zeta/events/v1"
tmtypes "github.com/tendermint/tendermint/abci/types"
tmtypes1 "github.com/tendermint/tendermint/proto/tendermint/types"
tmtypesint "github.com/tendermint/tendermint/types"
)
const AppVersion = 1
var (
ErrPublicKeyCannotSubmitTransactionWithNoBalance = errors.New("public key cannot submit transaction without balance")
ErrUnexpectedTxPubKey = errors.New("no one listens to the public keys that signed this oracle data")
ErrTradingDisabled = errors.New("trading disabled")
ErrMarketProposalDisabled = errors.New("market proposal disabled")
ErrAssetProposalDisabled = errors.New("asset proposal disabled")
ErrAwaitingCheckpointRestore = errors.New("transactions not allowed while waiting for checkpoint restore")
ErrOracleNoSubscribers = errors.New("there are no subscribes to the oracle data")
ErrOracleDataNormalization = func(err error) error {
return fmt.Errorf("error normalizing incoming oracle data: %w", err)
}
)
type Checkpoint interface {
BalanceCheckpoint(ctx context.Context) (*types.CheckpointState, error)
Checkpoint(ctx context.Context, now time.Time) (*types.CheckpointState, error)
}
type SpamEngine interface {
EndOfBlock(blockHeight uint64, now time.Time)
PreBlockAccept(tx abci.Tx) (bool, error)
PostBlockAccept(tx abci.Tx) (bool, error)
}
type PoWEngine interface {
api.ProofOfWorkParams
BeginBlock(blockHeight uint64, blockHash string)
EndOfBlock()
CheckTx(tx abci.Tx) error
DeliverTx(tx abci.Tx) error
Commit()
GetSpamStatistics(partyID string) *protoapi.PoWStatistic
}
//nolint:interfacebloat
type Snapshot interface {
Info() ([]byte, int64, string)
Snapshot(ctx context.Context) ([]byte, error)
SnapshotNow(ctx context.Context) (b []byte, errlol error)
AddProviders(provs ...types.StateProvider)
CheckLoaded() (bool, error)
ClearAndInitialise() error
// Calls related to statesync
ListMeta() ([]*tmtypes.Snapshot, error)
ReceiveSnapshot(snap *types.Snapshot) error
RejectSnapshot() error
ApplySnapshotChunk(chunk *types.RawChunk) (bool, error)
GetMissingChunks() []uint32
ApplySnapshot(ctx context.Context) error
LoadSnapshotChunk(height uint64, format, chunk uint32) (*types.RawChunk, error)
}
type StateVarEngine interface {
ProposedValueReceived(ctx context.Context, ID, nodeID, eventID string, bundle *statevar.KeyValueBundle) error
OnBlockEnd(ctx context.Context)
}
type BlockchainClient interface {
Validators(height *int64) ([]*tmtypesint.Validator, error)
}
type ProtocolUpgradeService interface {
BeginBlock(ctx context.Context, blockHeight uint64)
UpgradeProposal(ctx context.Context, pk string, upgradeBlockHeight uint64, zetaReleaseTag string) error
TimeForUpgrade() bool
GetUpgradeStatus() types.UpgradeStatus
SetReadyForUpgrade()
CoreReadyForUpgrade() bool
SetCoreReadyForUpgrade()
Cleanup(ctx context.Context)
IsValidProposal(ctx context.Context, pk string, upgradeBlockHeight uint64, zetaReleaseTag string) error
}
type App struct {
abci *abci.App
currentTimestamp time.Time
previousTimestamp time.Time
txTotals []uint64
txSizes []int
cBlock string
chainCtx context.Context // use this to have access to chain ID
blockCtx context.Context // use this to have access to block hash + height in commit call
lastBlockAppHash []byte
version string
blockchainClient BlockchainClient
zetaPaths paths.Paths
cfg Config
log *logging.Logger
cancelFn func()
stopBlockchain func() error
rates *ratelimit.Rates
// service injection
assets Assets
banking Banking
broker Broker
witness Witness
evtfwd EvtForwarder
exec ExecutionEngine
ghandler *genesis.Handler
gov GovernanceEngine
notary Notary
stats Stats
time TimeService
top ValidatorTopology
netp NetworkParameters
oracles *Oracle
delegation DelegationEngine
limits Limits
stake StakeVerifier
stakingAccounts StakingAccounts
checkpoint Checkpoint
spam SpamEngine
pow PoWEngine
epoch EpochService
snapshot Snapshot
stateVar StateVarEngine
protocolUpgradeService ProtocolUpgradeService
erc20MultiSigTopology ERC20MultiSigTopology
gastimator *Gastimator
nilPow bool
nilSpam bool
maxBatchSize atomic.Uint64
}
func NewApp(
log *logging.Logger,
zetaPaths paths.Paths,
config Config,
cancelFn func(),
stopBlockchain func() error,
assets Assets,
banking Banking,
broker Broker,
witness Witness,
evtfwd EvtForwarder,
exec ExecutionEngine,
ghandler *genesis.Handler,
gov GovernanceEngine,
notary Notary,
stats Stats,
time TimeService,
epoch EpochService,
top ValidatorTopology,
netp NetworkParameters,
oracles *Oracle,
delegation DelegationEngine,
limits Limits,
stake StakeVerifier,
checkpoint Checkpoint,
spam SpamEngine,
pow PoWEngine,
stakingAccounts StakingAccounts,
snapshot Snapshot,
stateVarEngine StateVarEngine,
blockchainClient BlockchainClient,
erc20MultiSigTopology ERC20MultiSigTopology,
version string, // we need the version for snapshot reload
protocolUpgradeService ProtocolUpgradeService,
codec abci.Codec,
gastimator *Gastimator,
) *App {
log = log.Named(namedLogger)
log.SetLevel(config.Level.Get())
app := &App{
abci: abci.New(codec),
log: log,
zetaPaths: zetaPaths,
cfg: config,
cancelFn: cancelFn,
stopBlockchain: stopBlockchain,
rates: ratelimit.New(
config.Ratelimit.Requests,
config.Ratelimit.PerNBlocks,
),
assets: assets,
banking: banking,
broker: broker,
witness: witness,
evtfwd: evtfwd,
exec: exec,
ghandler: ghandler,
gov: gov,
notary: notary,
stats: stats,
time: time,
top: top,
netp: netp,
oracles: oracles,
delegation: delegation,
limits: limits,
stake: stake,
checkpoint: checkpoint,
spam: spam,
pow: pow,
stakingAccounts: stakingAccounts,
epoch: epoch,
snapshot: snapshot,
stateVar: stateVarEngine,
version: version,
blockchainClient: blockchainClient,
erc20MultiSigTopology: erc20MultiSigTopology,
protocolUpgradeService: protocolUpgradeService,
gastimator: gastimator,
}
// setup handlers
app.abci.OnInitChain = app.OnInitChain
app.abci.OnBeginBlock = app.OnBeginBlock
app.abci.OnEndBlock = app.OnEndBlock
app.abci.OnCommit = app.OnCommit
app.abci.OnCheckTx = app.OnCheckTx
app.abci.OnCheckTxSpam = app.OnCheckTxSpam
app.abci.OnDeliverTx = app.OnDeliverTx
app.abci.OnDeliverTxSpam = app.OnDeliverTXSpam
app.abci.OnInfo = app.Info
// snapshot specific handlers.
app.abci.OnListSnapshots = app.ListSnapshots
app.abci.OnOfferSnapshot = app.OfferSnapshot
app.abci.OnApplySnapshotChunk = app.ApplySnapshotChunk
app.abci.OnLoadSnapshotChunk = app.LoadSnapshotChunk
app.abci.
HandleCheckTx(txn.NodeSignatureCommand, app.RequireValidatorPubKey).
HandleCheckTx(txn.NodeVoteCommand, app.RequireValidatorPubKey).
HandleCheckTx(txn.ChainEventCommand, app.RequireValidatorPubKey).
HandleCheckTx(txn.SubmitOracleDataCommand, app.CheckSubmitOracleData).
HandleCheckTx(txn.RotateKeySubmissionCommand, app.RequireValidatorMasterPubKey).
HandleCheckTx(txn.StateVariableProposalCommand, app.RequireValidatorPubKey).
HandleCheckTx(txn.ValidatorHeartbeatCommand, app.RequireValidatorPubKey).
HandleCheckTx(txn.RotateEthereumKeySubmissionCommand, app.RequireValidatorPubKey).
HandleCheckTx(txn.ProtocolUpgradeCommand, app.CheckProtocolUpgradeProposal).
HandleCheckTx(txn.BatchMarketInstructions, app.CheckBatchMarketInstructions).
HandleCheckTx(txn.ProposeCommand, app.CheckPropose).
HandleCheckTx(txn.TransferFundsCommand, app.CheckTransferCommand)
app.abci.
// node commands
HandleDeliverTx(txn.NodeSignatureCommand,
app.RequireValidatorPubKeyW(app.DeliverNodeSignature)).
HandleDeliverTx(txn.NodeVoteCommand,
app.RequireValidatorPubKeyW(app.DeliverNodeVote)).
HandleDeliverTx(txn.ChainEventCommand,
app.RequireValidatorPubKeyW(addDeterministicID(app.DeliverChainEvent))).
HandleDeliverTx(txn.StateVariableProposalCommand,
app.RequireValidatorPubKeyW(app.DeliverStateVarProposal)).
HandleDeliverTx(txn.ValidatorHeartbeatCommand,
app.DeliverValidatorHeartbeat).
// validators commands
HandleDeliverTx(txn.IssueSignatures,
app.SendTransactionResult(app.DeliverIssueSignatures)).
HandleDeliverTx(txn.ProtocolUpgradeCommand,
app.SendTransactionResult(app.DeliverProtocolUpgradeCommand)).
HandleDeliverTx(txn.RotateKeySubmissionCommand,
app.SendTransactionResult(
app.RequireValidatorMasterPubKeyW(app.DeliverKeyRotateSubmission),
),
).
HandleDeliverTx(txn.RotateEthereumKeySubmissionCommand,
app.SendTransactionResult(
app.RequireValidatorPubKeyW(app.DeliverEthereumKeyRotateSubmission),
),
).
// user commands
HandleDeliverTx(txn.AnnounceNodeCommand,
app.SendTransactionResult(app.DeliverAnnounceNode),
).
HandleDeliverTx(txn.CancelTransferFundsCommand,
app.SendTransactionResult(app.DeliverCancelTransferFunds),
).
HandleDeliverTx(txn.TransferFundsCommand,
app.SendTransactionResult(
addDeterministicID(app.DeliverTransferFunds),
),
).
HandleDeliverTx(txn.SubmitOrderCommand,
app.SendTransactionResult(
addDeterministicID(app.DeliverSubmitOrder),
),
).
HandleDeliverTx(txn.CancelOrderCommand,
app.SendTransactionResult(
addDeterministicID(app.DeliverCancelOrder),
),
).
HandleDeliverTx(txn.AmendOrderCommand,
app.SendTransactionResult(
addDeterministicID(app.DeliverAmendOrder),
),
).
HandleDeliverTx(txn.WithdrawCommand,
app.SendTransactionResult(
addDeterministicID(app.DeliverWithdraw))).
HandleDeliverTx(txn.ProposeCommand,
app.SendTransactionResult(
app.CheckProposeW(
addDeterministicID(app.DeliverPropose),
),
),
).
HandleDeliverTx(txn.VoteCommand,
app.SendTransactionResult(app.DeliverVote),
).
HandleDeliverTx(txn.LiquidityProvisionCommand,
app.SendTransactionResult(
addDeterministicID(app.DeliverLiquidityProvision),
),
).
HandleDeliverTx(txn.CancelLiquidityProvisionCommand,
app.SendTransactionResult(app.DeliverCancelLiquidityProvision),
).
HandleDeliverTx(txn.AmendLiquidityProvisionCommand,
app.SendTransactionResult(
addDeterministicID(app.DeliverAmendLiquidityProvision),
),
).
HandleDeliverTx(txn.SubmitOracleDataCommand,
app.SendTransactionResult(app.DeliverSubmitOracleData),
).
HandleDeliverTx(txn.DelegateCommand,
app.SendTransactionResult(app.DeliverDelegate),
).
HandleDeliverTx(txn.UndelegateCommand,
app.SendTransactionResult(app.DeliverUndelegate),
).
HandleDeliverTx(txn.BatchMarketInstructions,
app.SendTransactionResult(
app.CheckBatchMarketInstructionsW(
addDeterministicID(app.DeliverBatchMarketInstructions),
),
),
)
app.time.NotifyOnTick(app.onTick)
app.nilPow = app.pow == nil || reflect.ValueOf(app.pow).IsNil()
app.nilSpam = app.spam == nil || reflect.ValueOf(app.spam).IsNil()
app.ensureConfig()
return app
}
func (app *App) OnSpamProtectionMaxBatchSizeUpdate(ctx context.Context, u *num.Uint) error {
app.maxBatchSize.Store(u.Uint64())
return nil
}
// addDeterministicID will build the command ID
// the command ID is built using the signature of the proposer of the command
// the signature is then hashed with sha3_256
// the hash is the hex string encoded.
func addDeterministicID(
f func(context.Context, abci.Tx, string) error,
) func(context.Context, abci.Tx) error {
return func(ctx context.Context, tx abci.Tx) error {
return f(ctx, tx, hex.EncodeToString(vgcrypto.Hash(tx.Signature())))
}
}
func (app *App) CheckProposeW(
f func(context.Context, abci.Tx) error,
) func(context.Context, abci.Tx) error {
return func(ctx context.Context, tx abci.Tx) error {
if err := app.CheckPropose(ctx, tx); err != nil {
return err
}
return f(ctx, tx)
}
}
func (app *App) CheckBatchMarketInstructionsW(
f func(context.Context, abci.Tx) error,
) func(context.Context, abci.Tx) error {
return func(ctx context.Context, tx abci.Tx) error {
if err := app.CheckBatchMarketInstructions(ctx, tx); err != nil {
return err
}
return f(ctx, tx)
}
}
func (app *App) RequireValidatorPubKeyW(
f func(context.Context, abci.Tx) error,
) func(context.Context, abci.Tx) error {
return func(ctx context.Context, tx abci.Tx) error {
if err := app.RequireValidatorPubKey(ctx, tx); err != nil {
return err
}
return f(ctx, tx)
}
}
func (app *App) RequireValidatorMasterPubKeyW(
f func(context.Context, abci.Tx) error,
) func(context.Context, abci.Tx) error {
return func(ctx context.Context, tx abci.Tx) error {
if err := app.RequireValidatorMasterPubKey(ctx, tx); err != nil {
return err
}
return f(ctx, tx)
}
}
func (app *App) SendTransactionResult(
f func(context.Context, abci.Tx) error,
) func(context.Context, abci.Tx) error {
return func(ctx context.Context, tx abci.Tx) error {
if err := f(ctx, tx); err != nil {
// Send and error event
app.broker.Send(events.NewTransactionResultEventFailure(
ctx, hex.EncodeToString(tx.Hash()), tx.Party(), err, tx.GetCmd(),
))
// FIXME(j): remove this once anyone have stopped using the event
app.broker.Send(events.NewTxErrEvent(ctx, err, tx.Party(), tx.GetCmd(), tx.Command().String()))
return err
}
// Send and error event
app.broker.Send(events.NewTransactionResultEventSuccess(
ctx, hex.EncodeToString(tx.Hash()), tx.Party(), tx.GetCmd(),
))
return nil
}
}
func (app *App) ensureConfig() {
if app.cfg.KeepCheckpointsMax < 1 {
app.cfg.KeepCheckpointsMax = 1
}
}
// ReloadConf updates the internal configuration.
func (app *App) ReloadConf(cfg Config) {
app.log.Info("reloading configuration")
if app.log.GetLevel() != cfg.Level.Get() {
app.log.Info("updating log level",
logging.String("old", app.log.GetLevel().String()),
logging.String("new", cfg.Level.String()),
)
app.log.SetLevel(cfg.Level.Get())
}
app.cfg = cfg
app.ensureConfig()
}
func (app *App) Abci() *abci.App {
return app.abci
}
func (app *App) cancel() {
if fn := app.cancelFn; fn != nil {
fn()
}
}
func (app *App) Info(_ tmtypes.RequestInfo) tmtypes.ResponseInfo {
if len(app.lastBlockAppHash) != 0 {
// we must've lost connection to tendermint for a bit, tell it where we got up to
height, _ := vgcontext.BlockHeightFromContext(app.blockCtx)
app.log.Info("ABCI service INFO requested after reconnect",
logging.Int64("height", height),
logging.String("hash", hex.EncodeToString(app.lastBlockAppHash)),
)
return tmtypes.ResponseInfo{
AppVersion: AppVersion,
Version: app.version,
LastBlockHeight: height,
LastBlockAppHash: app.lastBlockAppHash,
}
}
// returns whether or not we have loaded from a snapshot (and may even do the loading)
old := app.broker.SetStreaming(false)
defer app.broker.SetStreaming(old)
loaded, err := app.snapshot.CheckLoaded()
if err != nil {
app.log.Panic("failed to check if snapshot has been loaded", logging.Error(err))
}
resp := tmtypes.ResponseInfo{
AppVersion: AppVersion,
Version: app.version,
}
if loaded {
hash, height, chainID := app.snapshot.Info()
resp.LastBlockHeight = height
resp.LastBlockAppHash = hash
app.abci.SetChainID(chainID)
app.chainCtx = vgcontext.WithChainID(context.Background(), chainID)
}
app.log.Info("ABCI service INFO requested",
logging.String("version", resp.Version),
logging.Uint64("app-version", resp.AppVersion),
logging.Int64("height", resp.LastBlockHeight),
logging.String("hash", hex.EncodeToString(resp.LastBlockAppHash)),
)
return resp
}
func (app *App) ListSnapshots(_ tmtypes.RequestListSnapshots) tmtypes.ResponseListSnapshots {
app.log.Debug("ABCI service ListSnapshots requested")
snapshots, err := app.snapshot.ListMeta()
resp := tmtypes.ResponseListSnapshots{}
if err != nil {
app.log.Error("Could not list snapshots", logging.Error(err))
return resp
}
resp.Snapshots = snapshots
return resp
}
func (app *App) OfferSnapshot(req tmtypes.RequestOfferSnapshot) tmtypes.ResponseOfferSnapshot {
app.log.Debug("ABCI service OfferSnapshot start")
snap, err := types.SnapshotFromTM(req.Snapshot)
if err != nil {
app.log.Error("failed to convert snapshot", logging.Error(err))
return tmtypes.ResponseOfferSnapshot{
Result: tmtypes.ResponseOfferSnapshot_REJECT_SENDER,
}
}
// check that our unpacked snapshot's hash matches that which tendermint thinks it sent
if !bytes.Equal(snap.Hash, req.AppHash) {
app.log.Error("hash mismatch",
logging.String("snap.Hash", hex.EncodeToString(snap.Hash)),
logging.String("rep.AppHash", hex.EncodeToString(req.AppHash)))
return tmtypes.ResponseOfferSnapshot{
Result: tmtypes.ResponseOfferSnapshot_REJECT,
}
}
// see what the snapshot engine thinks
if err := app.snapshot.ReceiveSnapshot(snap); err != nil {
ret := tmtypes.ResponseOfferSnapshot{
Result: tmtypes.ResponseOfferSnapshot_REJECT,
}
if err == types.ErrSnapshotMetaMismatch {
// hashes match, but the meta doesn't, do not trust
ret.Result = tmtypes.ResponseOfferSnapshot_REJECT_SENDER
}
app.log.Error("snapshot rejected", logging.Error(err))
return ret
}
return tmtypes.ResponseOfferSnapshot{
Result: tmtypes.ResponseOfferSnapshot_ACCEPT,
}
}
func (app *App) ApplySnapshotChunk(ctx context.Context, req tmtypes.RequestApplySnapshotChunk) tmtypes.ResponseApplySnapshotChunk {
app.log.Debug("ABCI service ApplySnapshotChunk start")
chunk := types.RawChunk{
Nr: req.Index,
Data: req.Chunk,
}
resp := tmtypes.ResponseApplySnapshotChunk{}
ready, err := app.snapshot.ApplySnapshotChunk(&chunk)
if err != nil {
app.log.Error("could not apply snapshot chunk", logging.Error(err))
switch err {
case types.ErrUnknownSnapshot:
resp.Result = tmtypes.ResponseApplySnapshotChunk_RETRY_SNAPSHOT // we weren't ready?
case types.ErrChunkOutOfRange:
resp.Result = tmtypes.ResponseApplySnapshotChunk_REJECT_SNAPSHOT // try another snapshot
case types.ErrSnapshotMetaMismatch:
// refetch the chunk from someone else
resp.Result = tmtypes.ResponseApplySnapshotChunk_RETRY
resp.RejectSenders = []string{req.Sender}
case types.ErrMissingChunks:
resp.Result = tmtypes.ResponseApplySnapshotChunk_RETRY
resp.RefetchChunks = app.snapshot.GetMissingChunks()
default:
resp.Result = tmtypes.ResponseApplySnapshotChunk_ABORT
// @TODO panic?
}
if resp.Result == tmtypes.ResponseApplySnapshotChunk_RETRY || resp.Result == tmtypes.ResponseApplySnapshotChunk_REJECT_SNAPSHOT {
if err := app.snapshot.RejectSnapshot(); err == types.ErrSnapshotRetryLimit {
app.log.Error("Applying snapshot chunk has reaching the retry limit, aborting")
resp.Result = tmtypes.ResponseApplySnapshotChunk_ABORT
defer app.log.Panic("Failed to load snapshot, max retry limit reached", logging.Error(err))
}
}
return resp
}
resp.Result = tmtypes.ResponseApplySnapshotChunk_ACCEPT
if ready {
err = app.snapshot.ApplySnapshot(ctx)
if err != nil {
app.log.Error("failed to apply snapshot", logging.Error(err))
resp.Result = tmtypes.ResponseApplySnapshotChunk_ABORT
}
}
return resp
}
func (app *App) LoadSnapshotChunk(req tmtypes.RequestLoadSnapshotChunk) tmtypes.ResponseLoadSnapshotChunk {
app.log.Debug("ABCI service LoadSnapshotChunk start")
raw, err := app.snapshot.LoadSnapshotChunk(req.Height, req.Format, req.Chunk)
if err != nil {
app.log.Error("failed to load snapshot chunk", logging.Error(err), logging.Uint64("height", req.Height))
return tmtypes.ResponseLoadSnapshotChunk{}
}
return tmtypes.ResponseLoadSnapshotChunk{
Chunk: raw.Data,
}
}
func (app *App) OnInitChain(req tmtypes.RequestInitChain) tmtypes.ResponseInitChain {
app.log.Debug("ABCI service InitChain start")
hash := hex.EncodeToString(vgcrypto.Hash(req.AppStateBytes))
app.abci.SetChainID(req.ChainId)
app.chainCtx = vgcontext.WithChainID(context.Background(), req.ChainId)
ctx := vgcontext.WithBlockHeight(app.chainCtx, req.InitialHeight)
ctx = vgcontext.WithTraceID(ctx, hash)
app.blockCtx = ctx
app.broker.Send(
events.NewBeginBlock(ctx, eventspb.BeginBlock{
Height: uint64(req.InitialHeight),
Timestamp: req.Time.UnixNano(),
Hash: hash,
}),
)
if err := app.ghandler.OnGenesis(ctx, req.Time, req.AppStateBytes); err != nil {
app.cancel()
app.log.Fatal("couldn't initialise zeta with the genesis block", logging.Error(err))
}
app.broker.Send(
events.NewEndBlock(ctx, eventspb.EndBlock{
Height: uint64(req.InitialHeight),
}),
)
return tmtypes.ResponseInitChain{
Validators: app.top.GetValidatorPowerUpdates(),
}
}
func (app *App) OnEndBlock(req tmtypes.RequestEndBlock) (ctx context.Context, resp tmtypes.ResponseEndBlock) {
app.log.Debug("entering end block", logging.Time("at", time.Now()))
defer func() { app.log.Debug("leaving end block", logging.Time("at", time.Now())) }()
app.log.Debug("ABCI service END block completed",
logging.Int64("current-timestamp", app.currentTimestamp.UnixNano()),
logging.Int64("previous-timestamp", app.previousTimestamp.UnixNano()),
logging.String("current-datetime", zetatime.Format(app.currentTimestamp)),
logging.String("previous-datetime", zetatime.Format(app.previousTimestamp)),
)
app.epoch.OnBlockEnd(app.blockCtx)
if !app.nilPow {
app.pow.EndOfBlock()
}
if !app.nilSpam {
app.spam.EndOfBlock(uint64(req.Height), app.time.GetTimeNow())
}
app.stateVar.OnBlockEnd(app.blockCtx)
powerUpdates := app.top.GetValidatorPowerUpdates()
resp = tmtypes.ResponseEndBlock{}
if len(powerUpdates) > 0 {
resp.ValidatorUpdates = powerUpdates
}
// update max gas based on the network parameter
resp.ConsensusParamUpdates = &tmtypes.ConsensusParams{
Block: &tmtypes.BlockParams{
MaxGas: int64(app.gastimator.OnBlockEnd()),
MaxBytes: tmtypesint.DefaultBlockParams().MaxBytes,
},
Version: &tmtypes1.VersionParams{
AppVersion: AppVersion,
},
}
app.exec.BlockEnd(app.blockCtx)
return ctx, resp
}
// OnBeginBlock updates the internal lastBlockTime value with each new block.
func (app *App) OnBeginBlock(
req tmtypes.RequestBeginBlock,
) (ctx context.Context, resp tmtypes.ResponseBeginBlock) {
app.log.Debug("entering begin block", logging.Time("at", time.Now()), logging.Uint64("height", uint64(req.Header.Height)))
defer func() { app.log.Debug("leaving begin block", logging.Time("at", time.Now())) }()
hash := hex.EncodeToString(req.Hash)
ctx = vgcontext.WithBlockHeight(vgcontext.WithTraceID(app.chainCtx, hash), req.Header.Height)
if app.protocolUpgradeService.CoreReadyForUpgrade() {
app.startProtocolUpgrade(ctx)
}
app.broker.Send(
events.NewBeginBlock(ctx, eventspb.BeginBlock{
Height: uint64(req.Header.Height),
Timestamp: req.Header.Time.UnixNano(),
Hash: hash,
}),
)
app.cBlock = hash
// update pow engine on a new block
if !app.nilPow {
app.pow.BeginBlock(uint64(req.Header.Height), hash)
}
app.stats.SetHash(hash)
app.stats.SetHeight(uint64(req.Header.Height))
app.blockCtx = ctx
now := req.Header.Time
app.time.SetTimeNow(ctx, now)
app.rates.NextBlock()
app.currentTimestamp = app.time.GetTimeNow()
app.previousTimestamp = app.time.GetTimeLastBatch()
app.log.Debug("ABCI service BEGIN completed",
logging.Int64("current-timestamp", app.currentTimestamp.UnixNano()),
logging.Int64("previous-timestamp", app.previousTimestamp.UnixNano()),
logging.String("current-datetime", zetatime.Format(app.currentTimestamp)),
logging.String("previous-datetime", zetatime.Format(app.previousTimestamp)),
logging.Int64("height", req.Header.GetHeight()),
)
app.protocolUpgradeService.BeginBlock(ctx, uint64(req.Header.Height))
app.top.BeginBlock(ctx, req)
return ctx, resp
}
func (app *App) startProtocolUpgrade(ctx context.Context) {
// Stop blockchain server so it doesn't acceptc transactions and it doesn't times out.
go func() { app.stopBlockchain() }()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var eventsCh <-chan events.Event
var errsCh <-chan error
if app.broker.StreamingEnabled() {
// wait here for data node send back the confirmation
eventsCh, errsCh = app.broker.SocketClient().Receive(ctx)
}
app.broker.Send(
events.NewProtocolUpgradeStarted(ctx, eventspb.ProtocolUpgradeStarted{
LastBlockHeight: app.stats.Height(),
}),
)
if eventsCh != nil {
app.log.Info("waiting for data node to get ready for upgrade")
Loop:
for {
select {
case e := <-eventsCh:
if e.Type() != events.ProtocolUpgradeDataNodeReadyEvent {
continue
}
if e.StreamMessage().GetProtocolUpgradeDataNodeReady().GetLastBlockHeight() == app.stats.Height() {
cancel()
break Loop
}
case err := <-errsCh:
app.log.Fatal("failed to wait for data node to get ready for upgrade", logging.Error(err))
}
}
}
app.protocolUpgradeService.SetReadyForUpgrade()
// wait until killed
for {
time.Sleep(1 * time.Second)
app.log.Info("application is ready for shutdown")
}
}
func (app *App) OnCommit() (resp tmtypes.ResponseCommit) {
app.log.Debug("entering commit", logging.Time("at", time.Now()))
defer func() { app.log.Debug("leaving commit", logging.Time("at", time.Now())) }()
if !app.nilPow {
app.pow.Commit()
}
// call checkpoint _first_ so the snapshot contains the correct checkpoint state.
cpt, _ := app.checkpoint.Checkpoint(app.blockCtx, app.currentTimestamp)
t0 := time.Now()
var snapHash []byte
var err error
// if there is an approved protocol upgrade proposal and the current block height is later than the proposal's block height then take a snapshot and wait to be killed by the process manager
if app.protocolUpgradeService.TimeForUpgrade() {
app.protocolUpgradeService.Cleanup(app.blockCtx)
snapHash, err = app.snapshot.SnapshotNow(app.blockCtx)
if err == nil {
app.protocolUpgradeService.SetCoreReadyForUpgrade()
}
} else {
snapHash, err = app.snapshot.Snapshot(app.blockCtx)
}
if err != nil {
app.log.Panic("Failed to create snapshot",
logging.Error(err))
}
t1 := time.Now()
if len(snapHash) > 0 {
app.log.Info("#### snapshot took ", logging.Float64("time", t1.Sub(t0).Seconds()))
}
resp.Data = snapHash
if len(snapHash) == 0 {
resp.Data = vgcrypto.Hash([]byte(app.version))
resp.Data = append(resp.Data, app.exec.Hash()...)
resp.Data = append(resp.Data, app.delegation.Hash()...)
resp.Data = append(resp.Data, app.gov.Hash()...)
resp.Data = append(resp.Data, app.stakingAccounts.Hash()...)
}
if cpt != nil {
if len(snapHash) == 0 {
// only append to commit hash if we aren't using the snapshot hash
// otherwise restoring a checkpoint would restore an incomplete/wrong hash
resp.Data = append(resp.Data, cpt.Hash...)
app.log.Debug("checkpoint hash", logging.String("response-data", hex.EncodeToString(cpt.Hash)))
}
_ = app.handleCheckpoint(cpt)
}
// the snapshot produce an actual hash, so no need
// to rehash if we have a snapshot hash.
// otherwise, it's a concatenation of hash that we get,
// so we just re-hash to have an output which is actually an
// hash and is consistent over all calls to Commit
if len(snapHash) <= 0 {
resp.Data = vgcrypto.Hash(resp.Data)
} else {
app.broker.Send(events.NewSnapshotEventEvent(app.blockCtx, app.stats.Height(), app.cBlock, app.protocolUpgradeService.TimeForUpgrade()))
}
// Update response and save the apphash incase we lose connection with tendermint and need to verify our
// current state
app.lastBlockAppHash = resp.Data
app.log.Debug("apphash calculated", logging.String("response-data", hex.EncodeToString(resp.Data)))
app.updateStats()
app.setBatchStats()
app.broker.Send(
events.NewEndBlock(app.blockCtx, eventspb.EndBlock{
Height: app.stats.Height(),
}),
)
return resp
}
func (app *App) handleCheckpoint(cpt *types.CheckpointState) error {
now := app.currentTimestamp
height, _ := vgcontext.BlockHeightFromContext(app.blockCtx)
cpFileName := fmt.Sprintf("%s-%d-%s.cp", now.Format("20060102150405"), height, hex.EncodeToString(cpt.Hash))
cpFilePath, err := app.zetaPaths.CreateStatePathFor(paths.StatePath(filepath.Join(paths.CheckpointStateHome.String(), cpFileName)))
if err != nil {
return fmt.Errorf("couldn't get path for checkpoint file: %w", err)
}
if err := vgfs.WriteFile(cpFilePath, cpt.State); err != nil {
return fmt.Errorf("couldn't write checkpoint file at %s: %w", cpFilePath, err)
}
// emit the event indicating a new checkpoint was created
// this function is called both for interval checkpoints and withdrawal checkpoints
event := events.NewCheckpointEvent(app.blockCtx, cpt)
app.broker.Send(event)
return app.removeOldCheckpoints()
}
func (app *App) removeOldCheckpoints() error {
cpDirPath, err := app.zetaPaths.CreateStatePathFor(paths.StatePath(paths.CheckpointStateHome.String()))
if err != nil {
return fmt.Errorf("couldn't get checkpoints directory: %w", err)
}
files, err := ioutil.ReadDir(cpDirPath)
if err != nil {
return fmt.Errorf("could not open the checkpoint directory: %w", err)
}
// we assume that the files in this directory are only
// from the checkpoints
// and always keep the last 20, so return if we have less than that
if len(files) <= int(app.cfg.KeepCheckpointsMax) {
return nil
}
oldest := app.stats.Height()
toRemove := ""
for _, file := range files {
// checkpoint have the following format:
// 20230322173929-12140156-d833359cb648eb315b4d3f9ccaa5092bd175b2f72a9d44783377ca5d7a2ec965.cp
// which is:
// time-block-hash.cp
// we split and should have the block in splitted[1]
splitted := strings.Split(file.Name(), "-")
if len(splitted) != 3 {
app.log.Error("weird checkpoint file name", logging.String("checkpoint-file", file.Name()))
// weird file, keep going
continue
}
block, err := strconv.ParseInt(splitted[1], 10, 64)
if err != nil {
app.log.Error("could not parse block number", logging.Error(err), logging.String("checkpoint-file", file.Name()))
continue
}
if uint64(block) < oldest {
oldest = uint64(block)
toRemove = file.Name()
}