-
Notifications
You must be signed in to change notification settings - Fork 531
/
Copy pathtx_pre_checker.go
280 lines (257 loc) · 10.2 KB
/
tx_pre_checker.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
// Copyright 2021-2022, Offchain Labs, Inc.
// For license information, see https://github.com/nitro/blob/master/LICENSE
package gethexec
import (
"context"
"errors"
"fmt"
"time"
flag "github.com/spf13/pflag"
"github.com/ethereum/go-ethereum/arbitrum_types"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/metrics"
"github.com/ethereum/go-ethereum/params"
"github.com/offchainlabs/nitro/arbos/arbosState"
"github.com/offchainlabs/nitro/arbos/l1pricing"
"github.com/offchainlabs/nitro/timeboost"
"github.com/offchainlabs/nitro/util/arbmath"
"github.com/offchainlabs/nitro/util/headerreader"
)
var (
conditionalTxRejectedByTxPreCheckerCurrentStateCounter = metrics.NewRegisteredCounter("arb/txprechecker/conditionaltx/currentstate/rejected", nil)
conditionalTxAcceptedByTxPreCheckerCurrentStateCounter = metrics.NewRegisteredCounter("arb/txprechecker/conditionaltx/currentstate/accepted", nil)
conditionalTxRejectedByTxPreCheckerOldStateCounter = metrics.NewRegisteredCounter("arb/txprechecker/conditionaltx/oldstate/rejected", nil)
conditionalTxAcceptedByTxPreCheckerOldStateCounter = metrics.NewRegisteredCounter("arb/txprechecker/conditionaltx/oldstate/accepted", nil)
)
const TxPreCheckerStrictnessNone uint = 0
const TxPreCheckerStrictnessAlwaysCompatible uint = 10
const TxPreCheckerStrictnessLikelyCompatible uint = 20
const TxPreCheckerStrictnessFullValidation uint = 30
type TxPreCheckerConfig struct {
Strictness uint `koanf:"strictness" reload:"hot"`
RequiredStateAge int64 `koanf:"required-state-age" reload:"hot"`
RequiredStateMaxBlocks uint `koanf:"required-state-max-blocks" reload:"hot"`
}
type TxPreCheckerConfigFetcher func() *TxPreCheckerConfig
var DefaultTxPreCheckerConfig = TxPreCheckerConfig{
Strictness: TxPreCheckerStrictnessLikelyCompatible,
RequiredStateAge: 2,
RequiredStateMaxBlocks: 4,
}
func TxPreCheckerConfigAddOptions(prefix string, f *flag.FlagSet) {
f.Uint(prefix+".strictness", DefaultTxPreCheckerConfig.Strictness, "how strict to be when checking txs before forwarding them. 0 = accept anything, "+
"10 = should never reject anything that'd succeed, 20 = likely won't reject anything that'd succeed, "+
"30 = full validation which may reject txs that would succeed")
f.Int64(prefix+".required-state-age", DefaultTxPreCheckerConfig.RequiredStateAge, "how long ago should the storage conditions from eth_SendRawTransactionConditional be true, 0 = don't check old state")
f.Uint(prefix+".required-state-max-blocks", DefaultTxPreCheckerConfig.RequiredStateMaxBlocks, "maximum number of blocks to look back while looking for the <required-state-age> seconds old state, 0 = don't limit the search")
}
type TxPreChecker struct {
TransactionPublisher
bc *core.BlockChain
config TxPreCheckerConfigFetcher
expressLaneTracker *ExpressLaneTracker
}
func NewTxPreChecker(publisher TransactionPublisher, bc *core.BlockChain, config TxPreCheckerConfigFetcher) *TxPreChecker {
return &TxPreChecker{
TransactionPublisher: publisher,
bc: bc,
config: config,
}
}
type NonceError struct {
sender common.Address
txNonce uint64
stateNonce uint64
}
func (e NonceError) Error() string {
if e.txNonce < e.stateNonce {
return fmt.Sprintf("%v: address %v, tx: %d state: %d", core.ErrNonceTooLow, e.sender, e.txNonce, e.stateNonce)
}
if e.txNonce > e.stateNonce {
return fmt.Sprintf("%v: address %v, tx: %d state: %d", core.ErrNonceTooHigh, e.sender, e.txNonce, e.stateNonce)
}
// This should be unreachable
return fmt.Sprintf("invalid nonce error for address %v nonce %v", e.sender, e.txNonce)
}
func (e NonceError) Unwrap() error {
if e.txNonce < e.stateNonce {
return core.ErrNonceTooLow
}
if e.txNonce > e.stateNonce {
return core.ErrNonceTooHigh
}
// This should be unreachable
return nil
}
func MakeNonceError(sender common.Address, txNonce uint64, stateNonce uint64) error {
if txNonce == stateNonce {
return nil
}
return NonceError{
sender: sender,
txNonce: txNonce,
stateNonce: stateNonce,
}
}
func PreCheckTx(bc *core.BlockChain, chainConfig *params.ChainConfig, header *types.Header, statedb *state.StateDB, arbos *arbosState.ArbosState, tx *types.Transaction, options *arbitrum_types.ConditionalOptions, config *TxPreCheckerConfig) error {
if config.Strictness < TxPreCheckerStrictnessAlwaysCompatible {
return nil
}
if tx.Gas() < params.TxGas {
return core.ErrIntrinsicGas
}
if tx.Type() >= types.ArbitrumDepositTxType || tx.Type() == types.BlobTxType {
// Should be unreachable for Arbitrum types due to UnmarshalBinary not accepting Arbitrum internal txs
// and we want to disallow BlobTxType since Arbitrum doesn't support EIP-4844 txs yet.
return types.ErrTxTypeNotSupported
}
sender, err := types.Sender(types.MakeSigner(chainConfig, header.Number, header.Time, arbos.ArbOSVersion()), tx)
if err != nil {
return err
}
baseFee := header.BaseFee
if config.Strictness < TxPreCheckerStrictnessLikelyCompatible {
baseFee, err = arbos.L2PricingState().MinBaseFeeWei()
if err != nil {
return err
}
}
if arbmath.BigLessThan(tx.GasFeeCap(), baseFee) {
return fmt.Errorf("%w: address %v, maxFeePerGas: %s baseFee: %s", core.ErrFeeCapTooLow, sender, tx.GasFeeCap(), header.BaseFee)
}
stateNonce := statedb.GetNonce(sender)
if tx.Nonce() < stateNonce {
return MakeNonceError(sender, tx.Nonce(), stateNonce)
}
extraInfo := types.DeserializeHeaderExtraInformation(header)
intrinsic, err := core.IntrinsicGas(tx.Data(), tx.AccessList(), tx.SetCodeAuthorizations(), tx.To() == nil, chainConfig.IsHomestead(header.Number), chainConfig.IsIstanbul(header.Number), chainConfig.IsShanghai(header.Number, header.Time, extraInfo.ArbOSFormatVersion))
if err != nil {
return err
}
if tx.Gas() < intrinsic {
return core.ErrIntrinsicGas
}
if config.Strictness < TxPreCheckerStrictnessLikelyCompatible {
return nil
}
if options != nil {
if err := options.Check(extraInfo.L1BlockNumber, header.Time, statedb); err != nil {
conditionalTxRejectedByTxPreCheckerCurrentStateCounter.Inc(1)
return err
}
conditionalTxAcceptedByTxPreCheckerCurrentStateCounter.Inc(1)
if config.RequiredStateAge > 0 {
now := time.Now().Unix()
oldHeader := header
blocksTraversed := uint(0)
// find a block that's old enough
// #nosec G115
for now-int64(oldHeader.Time) < config.RequiredStateAge &&
(config.RequiredStateMaxBlocks <= 0 || blocksTraversed < config.RequiredStateMaxBlocks) &&
oldHeader.Number.Uint64() > 0 {
previousHeader := bc.GetHeader(oldHeader.ParentHash, oldHeader.Number.Uint64()-1)
if previousHeader == nil {
break
}
oldHeader = previousHeader
blocksTraversed++
}
if !headerreader.HeadersEqual(oldHeader, header) {
secondOldStatedb, err := bc.StateAt(oldHeader.Root)
if err != nil {
return fmt.Errorf("failed to get old state: %w", err)
}
oldExtraInfo := types.DeserializeHeaderExtraInformation(oldHeader)
if err := options.Check(oldExtraInfo.L1BlockNumber, oldHeader.Time, secondOldStatedb); err != nil {
conditionalTxRejectedByTxPreCheckerOldStateCounter.Inc(1)
return arbitrum_types.WrapOptionsCheckError(err, "conditions check failed for old state")
}
}
conditionalTxAcceptedByTxPreCheckerOldStateCounter.Inc(1)
}
}
balance := statedb.GetBalance(sender)
cost := tx.Cost()
if arbmath.BigLessThan(balance.ToBig(), cost) {
return fmt.Errorf("%w: address %v have %v want %v", core.ErrInsufficientFunds, sender, balance, cost)
}
if config.Strictness >= TxPreCheckerStrictnessFullValidation && tx.Nonce() > stateNonce {
return MakeNonceError(sender, tx.Nonce(), stateNonce)
}
brotliCompressionLevel, err := arbos.BrotliCompressionLevel()
if err != nil {
return fmt.Errorf("failed to get brotli compression level: %w", err)
}
dataCost, _ := arbos.L1PricingState().GetPosterInfo(tx, l1pricing.BatchPosterAddress, brotliCompressionLevel)
dataGas := arbmath.BigDiv(dataCost, header.BaseFee)
if tx.Gas() < intrinsic+dataGas.Uint64() {
return core.ErrIntrinsicGas
}
return nil
}
func (c *TxPreChecker) PublishTransaction(ctx context.Context, tx *types.Transaction, options *arbitrum_types.ConditionalOptions) error {
block := c.bc.CurrentBlock()
statedb, err := c.bc.StateAt(block.Root)
if err != nil {
return err
}
arbos, err := arbosState.OpenSystemArbosState(statedb, nil, true)
if err != nil {
return err
}
err = PreCheckTx(c.bc, c.bc.Config(), block, statedb, arbos, tx, options, c.config())
if err != nil {
return err
}
return c.TransactionPublisher.PublishTransaction(ctx, tx, options)
}
func (c *TxPreChecker) PublishExpressLaneTransaction(ctx context.Context, msg *timeboost.ExpressLaneSubmission) error {
if msg == nil || msg.Transaction == nil {
return timeboost.ErrMalformedData
}
if c.expressLaneTracker == nil {
log.Error("ExpressLaneTracker not properly initialized in TxPreChecker, rejecting transaction.", "msg", msg)
return errors.New("express lane server misconfiguration")
}
err := c.expressLaneTracker.ValidateExpressLaneTx(msg)
if err != nil {
return err
}
block := c.bc.CurrentBlock()
statedb, err := c.bc.StateAt(block.Root)
if err != nil {
return err
}
arbos, err := arbosState.OpenSystemArbosState(statedb, nil, true)
if err != nil {
return err
}
err = PreCheckTx(c.bc, c.bc.Config(), block, statedb, arbos, msg.Transaction, msg.Options, c.config())
if err != nil {
return err
}
return c.TransactionPublisher.PublishExpressLaneTransaction(ctx, msg)
}
func (c *TxPreChecker) PublishAuctionResolutionTransaction(ctx context.Context, tx *types.Transaction) error {
block := c.bc.CurrentBlock()
statedb, err := c.bc.StateAt(block.Root)
if err != nil {
return err
}
arbos, err := arbosState.OpenSystemArbosState(statedb, nil, true)
if err != nil {
return err
}
err = PreCheckTx(c.bc, c.bc.Config(), block, statedb, arbos, tx, nil, c.config())
if err != nil {
return err
}
return c.TransactionPublisher.PublishAuctionResolutionTransaction(ctx, tx)
}
func (c *TxPreChecker) SetExpressLaneTracker(tracker *ExpressLaneTracker) {
c.expressLaneTracker = tracker
}