forked from dymensionxyz/dymint
/
executor.go
441 lines (386 loc) · 13.8 KB
/
executor.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
package state
import (
"bytes"
"context"
"errors"
"time"
abci "github.com/tendermint/tendermint/abci/types"
abcitypes "github.com/tendermint/tendermint/abci/types"
tmcrypto "github.com/tendermint/tendermint/crypto/encoding"
tmstate "github.com/tendermint/tendermint/proto/tendermint/state"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
"github.com/tendermint/tendermint/proxy"
tmtypes "github.com/tendermint/tendermint/types"
"go.uber.org/multierr"
abciconv "github.com/furyaxyz/furyint/conv/abci"
"github.com/furyaxyz/furyint/log"
"github.com/furyaxyz/furyint/mempool"
"github.com/furyaxyz/furyint/types"
)
// BlockExecutor creates and applies blocks and maintains state.
type BlockExecutor struct {
proposerAddress []byte
namespaceID [8]byte
chainID string
proxyAppConsensusConn proxy.AppConnConsensus
proxyAppQueryConn proxy.AppConnQuery
mempool mempool.Mempool
eventBus *tmtypes.EventBus
logger log.Logger
}
// NewBlockExecutor creates new instance of BlockExecutor.
// Proposer address and namespace ID will be used in all newly created blocks.
func NewBlockExecutor(proposerAddress []byte, namespaceID [8]byte, chainID string, mempool mempool.Mempool, proxyApp proxy.AppConns, eventBus *tmtypes.EventBus, logger log.Logger) *BlockExecutor {
return &BlockExecutor{
proposerAddress: proposerAddress,
namespaceID: namespaceID,
chainID: chainID,
proxyAppConsensusConn: proxyApp.Consensus(),
proxyAppQueryConn: proxyApp.Query(),
mempool: mempool,
eventBus: eventBus,
logger: logger,
}
}
// InitChain calls InitChainSync using consensus connection to app.
func (e *BlockExecutor) InitChain(genesis *tmtypes.GenesisDoc, validators []*tmtypes.Validator) (*abci.ResponseInitChain, error) {
params := genesis.ConsensusParams
valUpates := abcitypes.ValidatorUpdates{}
for _, validator := range validators {
tmkey, err := tmcrypto.PubKeyToProto(validator.PubKey)
if err != nil {
return nil, err
}
valUpates = append(valUpates, abcitypes.ValidatorUpdate{
PubKey: tmkey,
Power: validator.VotingPower,
})
}
return e.proxyAppConsensusConn.InitChainSync(abci.RequestInitChain{
Time: genesis.GenesisTime,
ChainId: genesis.ChainID,
ConsensusParams: &abci.ConsensusParams{
Block: &abci.BlockParams{
MaxBytes: params.Block.MaxBytes,
MaxGas: params.Block.MaxGas,
},
Evidence: &tmproto.EvidenceParams{
MaxAgeNumBlocks: params.Evidence.MaxAgeNumBlocks,
MaxAgeDuration: params.Evidence.MaxAgeDuration,
MaxBytes: params.Evidence.MaxBytes,
},
Validator: &tmproto.ValidatorParams{
PubKeyTypes: params.Validator.PubKeyTypes,
},
Version: &tmproto.VersionParams{
AppVersion: params.Version.AppVersion,
},
},
Validators: valUpates,
AppStateBytes: genesis.AppState,
InitialHeight: genesis.InitialHeight,
})
}
// CreateBlock reaps transactions from mempool and builds a block.
func (e *BlockExecutor) CreateBlock(height uint64, lastCommit *types.Commit, lastHeaderHash [32]byte, state types.State) *types.Block {
maxBytes := state.ConsensusParams.Block.MaxBytes
maxGas := state.ConsensusParams.Block.MaxGas
mempoolTxs := e.mempool.ReapMaxBytesMaxGas(maxBytes, maxGas)
block := &types.Block{
Header: types.Header{
Version: types.Version{
Block: state.Version.Consensus.Block,
App: state.Version.Consensus.App,
},
ChainID: e.chainID,
NamespaceID: e.namespaceID,
Height: height,
Time: uint64(time.Now().UTC().UnixNano()),
LastHeaderHash: lastHeaderHash,
DataHash: [32]byte{},
ConsensusHash: [32]byte{},
AppHash: state.AppHash,
LastResultsHash: state.LastResultsHash,
ProposerAddress: e.proposerAddress,
},
Data: types.Data{
Txs: toFuryintTxs(mempoolTxs),
IntermediateStateRoots: types.IntermediateStateRoots{RawRootsList: nil},
Evidence: types.EvidenceData{Evidence: nil},
},
LastCommit: *lastCommit,
}
copy(block.Header.LastCommitHash[:], e.getLastCommitHash(lastCommit, &block.Header))
copy(block.Header.DataHash[:], e.getDataHash(block))
copy(block.Header.AggregatorsHash[:], state.Validators.Hash())
return block
}
// Validate validates block and commit.
func (e *BlockExecutor) Validate(state types.State, block *types.Block, commit *types.Commit, proposer *types.Sequencer) error {
if err := e.validateBlock(state, block); err != nil {
return err
}
if err := e.validateCommit(proposer, commit, &block.Header); err != nil {
return err
}
return nil
}
// UpdateStateFromResponses updates state based on the ABCIResponses.
func (e *BlockExecutor) UpdateStateFromResponses(resp *tmstate.ABCIResponses, state types.State, block *types.Block) (types.State, error) {
//Furyint ignores any setValidator responses from the app, as it is manages the validator set based on the settlement consensus
//TODO: this will be changed when supporting multiple sequencers from the hub
validatorUpdates := []*tmtypes.Validator{}
if state.ConsensusParams.Block.MaxBytes == 0 {
e.logger.Error("maxBytes=0", "state.ConsensusParams.Block", state.ConsensusParams.Block)
}
state, err := e.updateState(state, block, resp, validatorUpdates)
if err != nil {
return types.State{}, err
}
return state, nil
}
// Commit commits the block
func (e *BlockExecutor) Commit(ctx context.Context, state *types.State, block *types.Block, resp *tmstate.ABCIResponses) error {
appHash, err := e.commit(ctx, state, block, resp.DeliverTxs)
if err != nil {
return err
}
copy(state.AppHash[:], appHash[:])
err = e.publishEvents(resp, block, *state)
if err != nil {
e.logger.Error("failed to fire block events", "error", err)
}
return nil
}
func (e *BlockExecutor) updateState(state types.State, block *types.Block, abciResponses *tmstate.ABCIResponses, validatorUpdates []*tmtypes.Validator) (types.State, error) {
nValSet := state.NextValidators.Copy()
lastHeightValSetChanged := state.LastHeightValidatorsChanged
// Furyint can work without validators
if len(nValSet.Validators) > 0 {
if len(validatorUpdates) > 0 {
err := nValSet.UpdateWithChangeSet(validatorUpdates)
if err != nil {
return state, nil
}
// Change results from this height but only applies to the next next height.
lastHeightValSetChanged = int64(block.Header.Height + 1 + 1)
}
// TODO(tzdybal): right now, it's for backward compatibility, may need to change this
nValSet.IncrementProposerPriority(1)
}
hash := block.Header.Hash()
s := types.State{
Version: state.Version,
ChainID: state.ChainID,
InitialHeight: state.InitialHeight,
SLStateIndex: state.SLStateIndex,
LastBlockHeight: int64(block.Header.Height),
LastBlockTime: time.Unix(0, int64(block.Header.Time)),
LastBlockID: tmtypes.BlockID{
Hash: hash[:],
// for now, we don't care about part set headers
},
NextValidators: nValSet,
Validators: state.NextValidators.Copy(),
LastHeightValidatorsChanged: lastHeightValSetChanged,
ConsensusParams: state.ConsensusParams,
LastHeightConsensusParamsChanged: state.LastHeightConsensusParamsChanged,
// We're gonna update those fields only after we commit the blocks
AppHash: state.AppHash,
LastValidators: state.LastValidators.Copy(),
LastStoreHeight: state.LastStoreHeight,
}
copy(s.LastResultsHash[:], tmtypes.NewResults(abciResponses.DeliverTxs).Hash())
return s, nil
}
// GetAppInfo returns the latest AppInfo from the proxyApp.
func (e *BlockExecutor) GetAppInfo() (*abcitypes.ResponseInfo, error) {
return e.proxyAppQueryConn.InfoSync(abcitypes.RequestInfo{})
}
func (e *BlockExecutor) commit(ctx context.Context, state *types.State, block *types.Block, deliverTxs []*abci.ResponseDeliverTx) ([]byte, error) {
e.mempool.Lock()
defer e.mempool.Unlock()
err := e.mempool.FlushAppConn()
if err != nil {
return nil, err
}
resp, err := e.proxyAppConsensusConn.CommitSync()
if err != nil {
return nil, err
}
maxBytes := state.ConsensusParams.Block.MaxBytes
maxGas := state.ConsensusParams.Block.MaxGas
err = e.mempool.Update(int64(block.Header.Height), fromFuryintTxs(block.Data.Txs), deliverTxs, mempool.PreCheckMaxBytes(maxBytes), mempool.PostCheckMaxGas(maxGas))
if err != nil {
return nil, err
}
return resp.Data, err
}
func (e *BlockExecutor) validateBlock(state types.State, block *types.Block) error {
err := block.ValidateBasic()
if err != nil {
return err
}
if block.Header.Version.App != state.Version.Consensus.App ||
block.Header.Version.Block != state.Version.Consensus.Block {
return errors.New("block version mismatch")
}
if state.LastBlockHeight <= 0 && block.Header.Height != uint64(state.InitialHeight) {
return errors.New("initial block height mismatch")
}
if state.LastBlockHeight > 0 && block.Header.Height != uint64(state.LastStoreHeight)+1 {
return errors.New("block height mismatch")
}
if !bytes.Equal(block.Header.AppHash[:], state.AppHash[:]) {
return errors.New("AppHash mismatch")
}
if !bytes.Equal(block.Header.LastResultsHash[:], state.LastResultsHash[:]) {
return errors.New("LastResultsHash mismatch")
}
return nil
}
func (e *BlockExecutor) validateCommit(proposer *types.Sequencer, commit *types.Commit, header *types.Header) error {
abciHeaderPb := abciconv.ToABCIHeaderPB(header)
abciHeaderBytes, err := abciHeaderPb.Marshal()
if err != nil {
return err
}
if err = commit.Validate(proposer, abciHeaderBytes); err != nil {
return err
}
return nil
}
// Execute executes the block and returns the ABCIResponses.
func (e *BlockExecutor) Execute(ctx context.Context, state types.State, block *types.Block) (*tmstate.ABCIResponses, error) {
abciResponses := new(tmstate.ABCIResponses)
abciResponses.DeliverTxs = make([]*abci.ResponseDeliverTx, len(block.Data.Txs))
txIdx := 0
validTxs := 0
invalidTxs := 0
var err error
e.proxyAppConsensusConn.SetResponseCallback(func(req *abci.Request, res *abci.Response) {
if r, ok := res.Value.(*abci.Response_DeliverTx); ok {
txRes := r.DeliverTx
if txRes.Code == abci.CodeTypeOK {
validTxs++
} else {
e.logger.Debug("Invalid tx", "code", txRes.Code, "log", txRes.Log)
invalidTxs++
}
abciResponses.DeliverTxs[txIdx] = txRes
txIdx++
}
})
hash := block.Hash()
abciHeader := abciconv.ToABCIHeaderPB(&block.Header)
abciHeader.ChainID = e.chainID
abciHeader.ValidatorsHash = state.Validators.Hash()
abciResponses.BeginBlock, err = e.proxyAppConsensusConn.BeginBlockSync(
abci.RequestBeginBlock{
Hash: hash[:],
Header: abciHeader,
LastCommitInfo: abci.LastCommitInfo{
Round: 0,
Votes: nil,
},
ByzantineValidators: nil,
})
if err != nil {
return nil, err
}
for _, tx := range block.Data.Txs {
res := e.proxyAppConsensusConn.DeliverTxAsync(abci.RequestDeliverTx{Tx: tx})
if res.GetException() != nil {
return nil, errors.New(res.GetException().GetError())
}
}
abciResponses.EndBlock, err = e.proxyAppConsensusConn.EndBlockSync(abci.RequestEndBlock{Height: int64(block.Header.Height)})
if err != nil {
return nil, err
}
return abciResponses, nil
}
func (e *BlockExecutor) getLastCommitHash(lastCommit *types.Commit, header *types.Header) []byte {
lastABCICommit := abciconv.ToABCICommit(lastCommit, header)
return lastABCICommit.Hash()
}
func (e *BlockExecutor) getDataHash(block *types.Block) []byte {
abciData := tmtypes.Data{
Txs: abciconv.ToABCIBlockDataTxs(&block.Data),
}
return abciData.Hash()
}
func (e *BlockExecutor) publishEvents(resp *tmstate.ABCIResponses, block *types.Block, state types.State) error {
if e.eventBus == nil {
return nil
}
abciBlock, err := abciconv.ToABCIBlock(block)
abciBlock.Header.ValidatorsHash = state.Validators.Hash()
if err != nil {
return err
}
err = multierr.Append(err, e.eventBus.PublishEventNewBlock(tmtypes.EventDataNewBlock{
Block: abciBlock,
ResultBeginBlock: *resp.BeginBlock,
ResultEndBlock: *resp.EndBlock,
}))
err = multierr.Append(err, e.eventBus.PublishEventNewBlockHeader(tmtypes.EventDataNewBlockHeader{
Header: abciBlock.Header,
NumTxs: int64(len(abciBlock.Txs)),
ResultBeginBlock: *resp.BeginBlock,
ResultEndBlock: *resp.EndBlock,
}))
for _, ev := range abciBlock.Evidence.Evidence {
err = multierr.Append(err, e.eventBus.PublishEventNewEvidence(tmtypes.EventDataNewEvidence{
Evidence: ev,
Height: int64(block.Header.Height),
}))
}
for i, dtx := range resp.DeliverTxs {
err = multierr.Append(err, e.eventBus.PublishEventTx(tmtypes.EventDataTx{
TxResult: abci.TxResult{
Height: int64(block.Header.Height),
Index: uint32(i),
Tx: abciBlock.Data.Txs[i],
Result: *dtx,
},
}))
}
return err
}
func toFuryintTxs(txs tmtypes.Txs) types.Txs {
optiTxs := make(types.Txs, len(txs))
for i := range txs {
optiTxs[i] = []byte(txs[i])
}
return optiTxs
}
func fromFuryintTxs(optiTxs types.Txs) tmtypes.Txs {
txs := make(tmtypes.Txs, len(optiTxs))
for i := range optiTxs {
txs[i] = []byte(optiTxs[i])
}
return txs
}
// func validateValidatorUpdates(abciUpdates []abci.ValidatorUpdate,
// params tmproto.ValidatorParams) error {
// for _, valUpdate := range abciUpdates {
// if valUpdate.GetPower() < 0 {
// return fmt.Errorf("voting power can't be negative %v", valUpdate)
// } else if valUpdate.GetPower() == 0 {
// // continue, since this is deleting the validator, and thus there is no
// // pubkey to check
// continue
// }
// // Check if validator's pubkey matches an ABCI type in the consensus params
// pk, err := cryptoenc.PubKeyFromProto(valUpdate.PubKey)
// if err != nil {
// return err
// }
// if !tmtypes.IsValidPubkeyType(params, pk.Type()) {
// return fmt.Errorf("validator %v is using pubkey %s, which is unsupported for consensus",
// valUpdate, pk.Type())
// }
// }
// return nil
// }