forked from dymensionxyz/dymint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
executor.go
306 lines (268 loc) · 9.05 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
package block
import (
"encoding/hex"
"errors"
"time"
abci "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"
"github.com/dymensionxyz/dymint/mempool"
"github.com/dymensionxyz/dymint/types"
)
// Executor creates and applies blocks and maintains state.
type Executor struct {
proposerAddress []byte
namespaceID [8]byte
chainID string
proxyAppConsensusConn proxy.AppConnConsensus
proxyAppQueryConn proxy.AppConnQuery
mempool mempool.Mempool
eventBus *tmtypes.EventBus
logger types.Logger
}
// NewExecutor creates new instance of BlockExecutor.
// Proposer address and namespace ID will be used in all newly created blocks.
func NewExecutor(proposerAddress []byte, namespaceID string, chainID string, mempool mempool.Mempool, proxyApp proxy.AppConns, eventBus *tmtypes.EventBus, logger types.Logger) (*Executor, error) {
bytes, err := hex.DecodeString(namespaceID)
if err != nil {
return nil, err
}
be := Executor{
proposerAddress: proposerAddress,
chainID: chainID,
proxyAppConsensusConn: proxyApp.Consensus(),
proxyAppQueryConn: proxyApp.Query(),
mempool: mempool,
eventBus: eventBus,
logger: logger,
}
copy(be.namespaceID[:], bytes)
return &be, nil
}
// InitChain calls InitChainSync using consensus connection to app.
func (e *Executor) InitChain(genesis *tmtypes.GenesisDoc, validators []*tmtypes.Validator) (*abci.ResponseInitChain, error) {
params := genesis.ConsensusParams
valUpates := abci.ValidatorUpdates{}
for _, validator := range validators {
tmkey, err := tmcrypto.PubKeyToProto(validator.PubKey)
if err != nil {
return nil, err
}
valUpates = append(valUpates, abci.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 *Executor) CreateBlock(height uint64, lastCommit *types.Commit, lastHeaderHash [32]byte, state *types.State, maxBlockDataSizeBytes uint64) *types.Block {
if state.ConsensusParams.Block.MaxBytes > 0 {
maxBlockDataSizeBytes = min(maxBlockDataSizeBytes, uint64(state.ConsensusParams.Block.MaxBytes))
}
mempoolTxs := e.mempool.ReapMaxBytesMaxGas(int64(maxBlockDataSizeBytes), state.ConsensusParams.Block.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, // TODO: used?????
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: toDymintTxs(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.SequencersHash[:], state.Validators.Hash())
return block
}
// Commit commits the block
func (e *Executor) Commit(state *types.State, block *types.Block, resp *tmstate.ABCIResponses) ([]byte, int64, error) {
appHash, retainHeight, err := e.commit(state, block, resp.DeliverTxs)
if err != nil {
return nil, 0, err
}
err = e.publishEvents(resp, block)
if err != nil {
e.logger.Error("fire block events", "error", err)
return nil, 0, err
}
return appHash, retainHeight, nil
}
// GetAppInfo returns the latest AppInfo from the proxyApp.
func (e *Executor) GetAppInfo() (*abci.ResponseInfo, error) {
return e.proxyAppQueryConn.InfoSync(abci.RequestInfo{})
}
func (e *Executor) commit(state *types.State, block *types.Block, deliverTxs []*abci.ResponseDeliverTx) ([]byte, int64, error) {
e.mempool.Lock()
defer e.mempool.Unlock()
err := e.mempool.FlushAppConn()
if err != nil {
return nil, 0, err
}
resp, err := e.proxyAppConsensusConn.CommitSync()
if err != nil {
return nil, 0, err
}
maxBytes := state.ConsensusParams.Block.MaxBytes
maxGas := state.ConsensusParams.Block.MaxGas
err = e.mempool.Update(int64(block.Header.Height), fromDymintTxs(block.Data.Txs), deliverTxs)
if err != nil {
return nil, 0, err
}
e.mempool.SetPreCheckFn(mempool.PreCheckMaxBytes(maxBytes))
e.mempool.SetPostCheckFn(mempool.PostCheckMaxGas(maxGas))
return resp.Data, resp.RetainHeight, err
}
// ExecuteBlock executes the block and returns the ABCIResponses. Block should be valid (passed validation checks).
func (e *Executor) ExecuteBlock(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 := types.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 *Executor) getLastCommitHash(lastCommit *types.Commit, header *types.Header) []byte {
lastABCICommit := types.ToABCICommit(lastCommit, header)
return lastABCICommit.Hash()
}
func (e *Executor) getDataHash(block *types.Block) []byte {
abciData := tmtypes.Data{
Txs: types.ToABCIBlockDataTxs(&block.Data),
}
return abciData.Hash()
}
func (e *Executor) publishEvents(resp *tmstate.ABCIResponses, block *types.Block) error {
if e.eventBus == nil {
return nil
}
abciBlock, err := types.ToABCIBlock(block)
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 toDymintTxs(txs tmtypes.Txs) types.Txs {
optiTxs := make(types.Txs, len(txs))
for i := range txs {
optiTxs[i] = []byte(txs[i])
}
return optiTxs
}
func fromDymintTxs(optiTxs types.Txs) tmtypes.Txs {
txs := make(tmtypes.Txs, len(optiTxs))
for i := range optiTxs {
txs[i] = []byte(optiTxs[i])
}
return txs
}