forked from OffchainLabs/nitro
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathparse_l2.go
396 lines (373 loc) · 11.8 KB
/
parse_l2.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
package arbos
import (
"bytes"
"errors"
"fmt"
"io"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log"
"github.com/offchainlabs/nitro/arbos/arbostypes"
"github.com/offchainlabs/nitro/arbos/util"
"github.com/offchainlabs/nitro/util/arbmath"
)
func ParseL2Transactions(msg *arbostypes.L1IncomingMessage, chainId *big.Int) (types.Transactions, error) {
if len(msg.L2msg) > arbostypes.MaxL2MessageSize {
// ignore the message if l2msg is too large
return nil, errors.New("message too large")
}
switch msg.Header.Kind {
case arbostypes.L1MessageType_L2Message:
return parseL2Message(bytes.NewReader(msg.L2msg), msg.Header.Poster, msg.Header.Timestamp, msg.Header.RequestId, chainId, 0)
case arbostypes.L1MessageType_Initialize:
return nil, errors.New("ParseL2Transactions encounted initialize message (should've been handled explicitly at genesis)")
case arbostypes.L1MessageType_EndOfBlock:
return nil, nil
case arbostypes.L1MessageType_L2FundedByL1:
if len(msg.L2msg) < 1 {
return nil, errors.New("L2FundedByL1 message has no data")
}
if msg.Header.RequestId == nil {
return nil, errors.New("cannot issue L2 funded by L1 tx without L1 request id")
}
kind := msg.L2msg[0]
depositRequestId := crypto.Keccak256Hash(msg.Header.RequestId[:], arbmath.U256Bytes(common.Big0))
unsignedRequestId := crypto.Keccak256Hash(msg.Header.RequestId[:], arbmath.U256Bytes(common.Big1))
tx, err := parseUnsignedTx(bytes.NewReader(msg.L2msg[1:]), msg.Header.Poster, &unsignedRequestId, chainId, kind)
if err != nil {
return nil, err
}
deposit := types.NewTx(&types.ArbitrumDepositTx{
ChainId: chainId,
L1RequestId: depositRequestId,
// Matches the From of parseUnsignedTx
To: msg.Header.Poster,
Value: tx.Value(),
})
return types.Transactions{deposit, tx}, nil
case arbostypes.L1MessageType_SubmitRetryable:
tx, err := parseSubmitRetryableMessage(bytes.NewReader(msg.L2msg), msg.Header, chainId)
if err != nil {
return nil, err
}
return types.Transactions{tx}, nil
case arbostypes.L1MessageType_BatchForGasEstimation:
return nil, errors.New("L1 message type BatchForGasEstimation is unimplemented")
case arbostypes.L1MessageType_EthDeposit:
tx, err := parseEthDepositMessage(bytes.NewReader(msg.L2msg), msg.Header, chainId)
if err != nil {
return nil, err
}
return types.Transactions{tx}, nil
case arbostypes.L1MessageType_RollupEvent:
log.Debug("ignoring rollup event message")
return types.Transactions{}, nil
case arbostypes.L1MessageType_BatchPostingReport:
tx, err := parseBatchPostingReportMessage(bytes.NewReader(msg.L2msg), chainId, msg.BatchGasCost)
if err != nil {
return nil, err
}
return types.Transactions{tx}, nil
case arbostypes.L1MessageType_Invalid:
// intentionally invalid message
return nil, errors.New("invalid message")
default:
// invalid message, just ignore it
return nil, fmt.Errorf("invalid message type %v", msg.Header.Kind)
}
}
const (
L2MessageKind_UnsignedUserTx = 0
L2MessageKind_ContractTx = 1
L2MessageKind_NonmutatingCall = 2
L2MessageKind_Batch = 3
L2MessageKind_SignedTx = 4
// 5 is reserved
L2MessageKind_Heartbeat = 6 // deprecated
L2MessageKind_SignedCompressedTx = 7
// 8 is reserved for BLS signed batch
)
// Warning: this does not validate the day of the week or if DST is being observed
func parseTimeOrPanic(format string, value string) time.Time {
t, err := time.Parse(format, value)
if err != nil {
panic(err)
}
return t
}
var HeartbeatsDisabledAt = uint64(parseTimeOrPanic(time.RFC1123, "Mon, 08 Aug 2022 16:00:00 GMT").Unix())
func parseL2Message(rd io.Reader, poster common.Address, timestamp uint64, requestId *common.Hash, chainId *big.Int, depth int) (types.Transactions, error) {
var l2KindBuf [1]byte
if _, err := rd.Read(l2KindBuf[:]); err != nil {
return nil, err
}
switch l2KindBuf[0] {
case L2MessageKind_UnsignedUserTx:
tx, err := parseUnsignedTx(rd, poster, requestId, chainId, L2MessageKind_UnsignedUserTx)
if err != nil {
return nil, err
}
return types.Transactions{tx}, nil
case L2MessageKind_ContractTx:
tx, err := parseUnsignedTx(rd, poster, requestId, chainId, L2MessageKind_ContractTx)
if err != nil {
return nil, err
}
return types.Transactions{tx}, nil
case L2MessageKind_NonmutatingCall:
return nil, errors.New("L2 message kind NonmutatingCall is unimplemented")
case L2MessageKind_Batch:
if depth >= 16 {
return nil, errors.New("L2 message batches have a max depth of 16")
}
segments := make(types.Transactions, 0)
index := big.NewInt(0)
for {
nextMsg, err := util.BytestringFromReader(rd, arbostypes.MaxL2MessageSize)
if err != nil {
// an error here means there are no further messages in the batch
// nolint:nilerr
return segments, nil
}
var nextRequestId *common.Hash
if requestId != nil {
subRequestId := crypto.Keccak256Hash(requestId[:], arbmath.U256Bytes(index))
nextRequestId = &subRequestId
}
nestedSegments, err := parseL2Message(bytes.NewReader(nextMsg), poster, timestamp, nextRequestId, chainId, depth+1)
if err != nil {
return nil, err
}
segments = append(segments, nestedSegments...)
index.Add(index, big.NewInt(1))
}
case L2MessageKind_SignedTx:
newTx := new(types.Transaction)
// Safe to read in its entirety, as all input readers are limited
readBytes, err := io.ReadAll(rd)
if err != nil {
return nil, err
}
if err := newTx.UnmarshalBinary(readBytes); err != nil {
return nil, err
}
if newTx.Type() >= types.ArbitrumDepositTxType || newTx.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 nil, types.ErrTxTypeNotSupported
}
return types.Transactions{newTx}, nil
case L2MessageKind_Heartbeat:
if timestamp >= HeartbeatsDisabledAt {
return nil, errors.New("heartbeat messages have been disabled")
}
// do nothing
return nil, nil
case L2MessageKind_SignedCompressedTx:
return nil, errors.New("L2 message kind SignedCompressedTx is unimplemented")
default:
// ignore invalid message kind
return nil, fmt.Errorf("unkown L2 message kind %v", l2KindBuf[0])
}
}
func parseUnsignedTx(rd io.Reader, poster common.Address, requestId *common.Hash, chainId *big.Int, txKind byte) (*types.Transaction, error) {
gasLimitHash, err := util.HashFromReader(rd)
if err != nil {
return nil, err
}
gasLimitBig := gasLimitHash.Big()
if !gasLimitBig.IsUint64() {
return nil, errors.New("unsigned user tx gas limit >= 2^64")
}
gasLimit := gasLimitBig.Uint64()
maxFeePerGas, err := util.HashFromReader(rd)
if err != nil {
return nil, err
}
var nonce uint64
if txKind == L2MessageKind_UnsignedUserTx {
nonceAsHash, err := util.HashFromReader(rd)
if err != nil {
return nil, err
}
nonceAsBig := nonceAsHash.Big()
if !nonceAsBig.IsUint64() {
return nil, errors.New("unsigned user tx nonce >= 2^64")
}
nonce = nonceAsBig.Uint64()
}
to, err := util.AddressFrom256FromReader(rd)
if err != nil {
return nil, err
}
var destination *common.Address
if to != (common.Address{}) {
destination = &to
}
value, err := util.HashFromReader(rd)
if err != nil {
return nil, err
}
calldata, err := io.ReadAll(rd)
if err != nil {
return nil, err
}
var inner types.TxData
switch txKind {
case L2MessageKind_UnsignedUserTx:
inner = &types.ArbitrumUnsignedTx{
ChainId: chainId,
From: poster,
Nonce: nonce,
GasFeeCap: maxFeePerGas.Big(),
Gas: gasLimit,
To: destination,
Value: value.Big(),
Data: calldata,
}
case L2MessageKind_ContractTx:
if requestId == nil {
return nil, errors.New("cannot issue contract tx without L1 request id")
}
inner = &types.ArbitrumContractTx{
ChainId: chainId,
RequestId: *requestId,
From: poster,
GasFeeCap: maxFeePerGas.Big(),
Gas: gasLimit,
To: destination,
Value: value.Big(),
Data: calldata,
}
default:
return nil, errors.New("invalid L2 tx type in parseUnsignedTx")
}
return types.NewTx(inner), nil
}
func parseEthDepositMessage(rd io.Reader, header *arbostypes.L1IncomingMessageHeader, chainId *big.Int) (*types.Transaction, error) {
to, err := util.AddressFromReader(rd)
if err != nil {
return nil, err
}
balance, err := util.HashFromReader(rd)
if err != nil {
return nil, err
}
if header.RequestId == nil {
return nil, errors.New("cannot issue deposit tx without L1 request id")
}
tx := &types.ArbitrumDepositTx{
ChainId: chainId,
L1RequestId: *header.RequestId,
From: header.Poster,
To: to,
Value: balance.Big(),
}
return types.NewTx(tx), nil
}
func parseSubmitRetryableMessage(rd io.Reader, header *arbostypes.L1IncomingMessageHeader, chainId *big.Int) (*types.Transaction, error) {
retryTo, err := util.AddressFrom256FromReader(rd)
if err != nil {
return nil, err
}
pRetryTo := &retryTo
if retryTo == (common.Address{}) {
pRetryTo = nil
}
callvalue, err := util.HashFromReader(rd)
if err != nil {
return nil, err
}
depositValue, err := util.HashFromReader(rd)
if err != nil {
return nil, err
}
maxSubmissionFee, err := util.HashFromReader(rd)
if err != nil {
return nil, err
}
feeRefundAddress, err := util.AddressFrom256FromReader(rd)
if err != nil {
return nil, err
}
callvalueRefundAddress, err := util.AddressFrom256FromReader(rd)
if err != nil {
return nil, err
}
gasLimit, err := util.HashFromReader(rd)
if err != nil {
return nil, err
}
gasLimitBig := gasLimit.Big()
if !gasLimitBig.IsUint64() {
return nil, errors.New("gas limit too large")
}
maxFeePerGas, err := util.HashFromReader(rd)
if err != nil {
return nil, err
}
dataLength256, err := util.HashFromReader(rd)
if err != nil {
return nil, err
}
dataLengthBig := dataLength256.Big()
if !dataLengthBig.IsUint64() {
return nil, errors.New("data length field too large")
}
dataLength := dataLengthBig.Uint64()
if dataLength > arbostypes.MaxL2MessageSize {
return nil, errors.New("retryable data too large")
}
retryData := make([]byte, dataLength)
if dataLength > 0 {
if _, err := rd.Read(retryData); err != nil {
return nil, err
}
}
if header.RequestId == nil {
return nil, errors.New("cannot issue submit retryable tx without L1 request id")
}
tx := &types.ArbitrumSubmitRetryableTx{
ChainId: chainId,
RequestId: *header.RequestId,
From: header.Poster,
L1BaseFee: header.L1BaseFee,
DepositValue: depositValue.Big(),
GasFeeCap: maxFeePerGas.Big(),
Gas: gasLimitBig.Uint64(),
RetryTo: pRetryTo,
RetryValue: callvalue.Big(),
Beneficiary: callvalueRefundAddress,
MaxSubmissionFee: maxSubmissionFee.Big(),
FeeRefundAddr: feeRefundAddress,
RetryData: retryData,
}
return types.NewTx(tx), err
}
func parseBatchPostingReportMessage(rd io.Reader, chainId *big.Int, msgBatchGasCost *uint64) (*types.Transaction, error) {
batchTimestamp, batchPosterAddr, _, batchNum, l1BaseFee, extraGas, err := arbostypes.ParseBatchPostingReportMessageFields(rd)
if err != nil {
return nil, err
}
var batchDataGas uint64
if msgBatchGasCost != nil {
batchDataGas = *msgBatchGasCost
} else {
return nil, errors.New("cannot compute batch gas cost")
}
batchDataGas = arbmath.SaturatingUAdd(batchDataGas, extraGas)
data, err := util.PackInternalTxDataBatchPostingReport(
batchTimestamp, batchPosterAddr, batchNum, batchDataGas, l1BaseFee,
)
if err != nil {
return nil, err
}
return types.NewTx(&types.ArbitrumInternalTx{
ChainId: chainId,
Data: data,
// don't need to fill in the other fields, since they exist only to ensure uniqueness, and batchNum is already unique
}), nil
}