-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathtransaction.go
More file actions
479 lines (439 loc) · 14.8 KB
/
transaction.go
File metadata and controls
479 lines (439 loc) · 14.8 KB
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
// Copyright 2014 The go-ethereum Authors
// (original work)
// Copyright 2024 The Erigon Authors
// (modifications)
// This file is part of Erigon.
//
// Erigon is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Erigon is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Erigon. If not, see <http://www.gnu.org/licenses/>.
package types
import (
"bytes"
"errors"
"fmt"
"io"
"math/big"
"sync/atomic"
"github.com/holiman/uint256"
"github.com/erigontech/erigon/common"
libcrypto "github.com/erigontech/erigon/common/crypto"
"github.com/erigontech/erigon/common/log/v3"
"github.com/erigontech/erigon/common/math"
"github.com/erigontech/erigon/execution/chain"
"github.com/erigontech/erigon/execution/protocol/params"
"github.com/erigontech/erigon/execution/rlp"
"github.com/erigontech/erigon/execution/types/accounts"
)
var (
ErrInvalidSig = errors.New("invalid transaction v, r, s values")
ErrUnexpectedProtection = errors.New("transaction type does not supported EIP-155 protected signatures")
ErrInvalidTxType = errors.New("transaction type not valid in this context")
ErrTxTypeNotSupported = errors.New("transaction type not supported")
errTrailingBytes = errors.New("trailing bytes after rlp encoded transaction")
)
// Transaction types.
const (
LegacyTxType = iota
AccessListTxType
DynamicFeeTxType
BlobTxType
SetCodeTxType
AccountAbstractionTxType
)
// Transaction is an Ethereum transaction.
type Transaction interface {
Type() byte
GetChainID() *uint256.Int
GetNonce() uint64
GetTipCap() *uint256.Int // max_priority_fee_per_gas in EIP-1559
GetEffectiveGasTip(baseFee *uint256.Int) uint256.Int // priority_fee_per_gas in EIP-1559
GetFeeCap() *uint256.Int // max_fee_per_gas in EIP-1559
GetBlobHashes() []common.Hash
GetGasLimit() uint64
GetBlobGas() uint64
GetValue() *uint256.Int
GetTo() *common.Address
AsMessage(s Signer, baseFee *uint256.Int, rules *chain.Rules) (*Message, error)
WithSignature(signer Signer, sig []byte) (Transaction, error)
Hash() common.Hash
SigningHash(chainID *big.Int) common.Hash
GetData() []byte
GetAccessList() AccessList
GetAuthorizations() []Authorization // If this is a network wrapper, returns the unwrapped txn. Otherwise returns itself.
Protected() bool
RawSignatureValues() (*uint256.Int, *uint256.Int, *uint256.Int)
EncodingSize() int
EncodeRLP(w io.Writer) error
DecodeRLP(s *rlp.Stream) error
MarshalBinary(w io.Writer) error
// Sender returns the address derived from the signature (V, R, S) using secp256k1
// elliptic curve and an error if it failed deriving or upon an incorrect
// signature.
//
// Sender may cache the address, allowing it to be used regardless of
// signing method. The cache is invalidated if the cached signer does
// not match the signer used in the current call.
Sender(Signer) (accounts.Address, error)
cachedSender() (accounts.Address, bool)
GetSender() (accounts.Address, bool)
SetSender(accounts.Address)
IsContractDeploy() bool
Unwrap() Transaction // If this is a network wrapper, returns the unwrapped txn. Otherwise returns itself.
}
// TransactionMisc is collection of miscellaneous fields for transaction that is supposed to be embedded into concrete
// implementations of different transaction types
type TransactionMisc struct {
// caches
hash atomic.Pointer[common.Hash]
from accounts.Address
}
// CalcEffectiveGasTip computes the effective gas tip given a transaction's tip/fee caps and a base fee.
// Shared logic used by all transaction types that implement GetEffectiveGasTip.
func CalcEffectiveGasTip(baseFee *uint256.Int, getTipCap func() *uint256.Int, getFeeCap func() *uint256.Int) uint256.Int {
if baseFee == nil {
return *getTipCap()
}
gasFeeCap := getFeeCap()
if gasFeeCap.Lt(baseFee) {
var zero uint256.Int
return zero
}
var effectiveFee uint256.Int
effectiveFee.Sub(gasFeeCap, baseFee)
if getTipCap().Lt(&effectiveFee) {
return *getTipCap()
}
return effectiveFee
}
// RLP-marshalled legacy transactions and binary-marshalled (not wrapped into an RLP string) typed (EIP-2718) transactions
type BinaryTransactions [][]byte
func (t BinaryTransactions) Len() int {
return len(t)
}
func (t BinaryTransactions) EncodeIndex(i int, w *bytes.Buffer) {
w.Write(t[i])
}
func DecodeRLPTransaction(s *rlp.Stream, blobTxnsAreWrappedWithBlobs bool) (Transaction, error) {
// if the stream is in an enclosing RLP list (transactions list inside a block)
inBlock := s.MoreDataInList()
kind, _, err := s.Kind()
if err != nil {
return nil, err
}
var txn Transaction
switch kind {
case rlp.List:
legacy := &LegacyTx{}
if err := legacy.DecodeRLP(s); err != nil {
return nil, err
}
txn = legacy
case rlp.String:
// Decode the EIP-2718 typed txn envelope.
var b []byte
if b, err = s.Bytes(); err != nil {
return nil, err
}
if len(b) == 0 {
return nil, rlp.EOL
}
if txn, err = UnmarshalTransactionFromBinary(b, blobTxnsAreWrappedWithBlobs); err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("not an RLP encoded transaction. If this is a canonical encoded transaction, use UnmarshalTransactionFromBinary instead. Got %v for kind, expected String", kind)
}
if !inBlock {
if _, _, peekErr := s.Kind(); peekErr == nil {
return nil, errTrailingBytes
} else if !errors.Is(peekErr, io.EOF) && !errors.Is(peekErr, rlp.EOL) {
return nil, peekErr
}
}
return txn, nil
}
// DecodeWrappedTransaction as similar to DecodeTransaction,
// but type-3 (blob) transactions are expected to be wrapped with blobs/commitments/proofs.
// See https://eips.ethereum.org/EIPS/eip-4844#networking
func DecodeWrappedTransaction(data []byte) (Transaction, error) {
blobTxnsAreWrappedWithBlobs := true
if len(data) == 0 {
return nil, io.EOF
}
if data[0] < 0x80 { // the encoding is canonical, not RLP
return UnmarshalTransactionFromBinary(data, blobTxnsAreWrappedWithBlobs)
}
s, done := rlp.NewStreamFromPool(bytes.NewReader(data), uint64(len(data)))
defer done()
return DecodeRLPTransaction(s, blobTxnsAreWrappedWithBlobs)
}
// DecodeTransaction decodes a transaction either in RLP or canonical format
func DecodeTransaction(data []byte) (Transaction, error) {
blobTxnsAreWrappedWithBlobs := false
if len(data) == 0 {
return nil, io.EOF
}
if data[0] < 0x80 { // the encoding is canonical, not RLP
return UnmarshalTransactionFromBinary(data, blobTxnsAreWrappedWithBlobs)
}
s, done := rlp.NewStreamFromPool(bytes.NewReader(data), uint64(len(data)))
defer done()
tx, err := DecodeRLPTransaction(s, blobTxnsAreWrappedWithBlobs)
if err != nil {
return nil, err
}
return tx, nil
}
// Parse transaction without envelope.
func UnmarshalTransactionFromBinary(data []byte, blobTxnsAreWrappedWithBlobs bool) (Transaction, error) {
if len(data) <= 1 {
return nil, fmt.Errorf("short input: %v", len(data))
}
s, done := rlp.NewStreamFromPool(bytes.NewReader(data[1:]), uint64(len(data)-1))
defer done()
var t Transaction
switch data[0] {
case AccessListTxType:
t = &AccessListTx{}
case DynamicFeeTxType:
t = &DynamicFeeTransaction{}
case BlobTxType:
if blobTxnsAreWrappedWithBlobs {
t = &BlobTxWrapper{}
} else {
t = &BlobTx{}
}
case SetCodeTxType:
t = &SetCodeTransaction{}
case AccountAbstractionTxType:
t = &AccountAbstractionTransaction{}
default:
if data[0] >= 0x80 {
// txn is type legacy which is RLP encoded
return DecodeTransaction(data)
}
return nil, ErrTxTypeNotSupported
}
if err := t.DecodeRLP(s); err != nil {
return nil, err
}
if s.Remaining() != 0 {
return nil, errTrailingBytes
}
return t, nil
}
// Removes everything but the payload body from blob tx and prepends 0x3 at the beginning - no copy
// Doesn't change non-blob tx
func UnwrapTxPlayloadRlp(blobTxRlp []byte) ([]byte, error) {
if blobTxRlp[0] != BlobTxType {
return blobTxRlp, nil
}
dataposPrev, _, isList, err := rlp.Prefix(blobTxRlp[1:], 0)
if err != nil || dataposPrev < 1 {
return nil, err
}
if !isList { // This is clearly not wrapped txn then
return blobTxRlp, nil
}
blobTxRlp = blobTxRlp[1:]
// Get to the wrapper list
datapos, datalen, err := rlp.ParseList(blobTxRlp, dataposPrev)
if err != nil {
return nil, err
}
blobTxRlp = blobTxRlp[dataposPrev-1 : datapos+datalen] // seekInFiles left an extra-bit
blobTxRlp[0] = 0x3
// Include the prefix part of the rlp
return blobTxRlp, nil
}
func MarshalTransactionsBinary(txs Transactions) ([][]byte, error) {
var err error
var buf bytes.Buffer
result := make([][]byte, len(txs))
for i := range txs {
if txs[i] == nil {
result[i] = nil
continue
}
buf.Reset()
err = txs[i].MarshalBinary(&buf)
if err != nil {
return nil, err
}
result[i] = common.Copy(buf.Bytes())
}
return result, nil
}
func DecodeTransactions(txs [][]byte) ([]Transaction, error) {
result := make([]Transaction, len(txs))
var err error
for i := range txs {
result[i], err = UnmarshalTransactionFromBinary(txs[i], false /* blobTxnsAreWrappedWithBlobs*/)
if err != nil {
return nil, err
}
}
return result, nil
}
func TypedTransactionMarshalledAsRlpString(data []byte) bool {
// Unless it's a single byte, serialized RLP strings have their first byte in the [0x80, 0xc0) range
return len(data) > 0 && 0x80 <= data[0] && data[0] < 0xc0
}
func sanityCheckSignature(v *uint256.Int, r *uint256.Int, s *uint256.Int, maybeProtected bool) error {
if isProtectedV(v) && !maybeProtected {
return ErrUnexpectedProtection
}
var plainV byte
if isProtectedV(v) {
chainID := DeriveChainId(v).Uint64()
plainV = byte(v.Uint64() - 35 - 2*chainID)
} else if maybeProtected {
// Only EIP-155 signatures can be optionally protected. Since
// we determined this v value is not protected, it must be a
// raw 27 or 28.
plainV = byte(v.Uint64() - 27)
} else {
// If the signature is not optionally protected, we assume it
// must already be equal to the recovery id.
plainV = byte(v.Uint64())
}
if !libcrypto.TransactionSignatureIsValid(plainV, r, s, true /* allowPreEip2s */) {
return ErrInvalidSig
}
return nil
}
func isProtectedV(V *uint256.Int) bool {
if V.BitLen() <= 8 {
v := V.Uint64()
return v != 27 && v != 28 && v != 1 && v != 0
}
// anything not 27 or 28 is considered protected
return true
}
// Transactions implements DerivableList for transactions.
type Transactions []Transaction
// Len returns the length of s.
func (s Transactions) Len() int { return len(s) }
// EncodeIndex encodes the i'th transaction to w. Note that this does not check for errors
// because we assume that *Transaction will only ever contain valid txs that were either
// constructed by decoding or via public API in this package.
func (s Transactions) EncodeIndex(i int, w *bytes.Buffer) {
if err := s[i].MarshalBinary(w); err != nil {
panic(err)
}
}
// TransactionsGroupedBySender - lists of transactions grouped by sender
type TransactionsGroupedBySender []Transactions
// Message is a fully derived transaction and implements core.Message
type Message struct {
to accounts.Address
from accounts.Address
nonce uint64
amount uint256.Int
gasLimit uint64
gasPrice uint256.Int
feeCap uint256.Int
tipCap uint256.Int
maxFeePerBlobGas uint256.Int
data []byte
accessList AccessList
checkNonce bool
checkTransaction bool
checkGas bool
isFree bool
blobHashes []common.Hash
authorizations []Authorization
}
func NewMessage(from accounts.Address, to accounts.Address, nonce uint64, amount *uint256.Int, gasLimit uint64,
gasPrice *uint256.Int, feeCap, tipCap *uint256.Int, data []byte, accessList AccessList, checkNonce bool,
checkTransaction bool, checkGas bool, isFree bool, maxFeePerBlobGas *uint256.Int,
) *Message {
m := Message{
from: from,
to: to,
nonce: nonce,
amount: *amount,
gasLimit: gasLimit,
data: data,
accessList: accessList,
checkNonce: checkNonce,
checkTransaction: checkTransaction,
checkGas: checkGas,
isFree: isFree,
}
if gasPrice != nil {
m.gasPrice.Set(gasPrice)
}
if tipCap != nil {
m.tipCap.Set(tipCap)
}
if feeCap != nil {
m.feeCap.Set(feeCap)
}
if maxFeePerBlobGas != nil {
m.maxFeePerBlobGas.Set(maxFeePerBlobGas)
}
return &m
}
func (m *Message) From() accounts.Address { return m.from }
func (m *Message) To() accounts.Address { return m.to }
func (m *Message) GasPrice() *uint256.Int { return &m.gasPrice }
func (m *Message) FeeCap() *uint256.Int { return &m.feeCap }
func (m *Message) TipCap() *uint256.Int { return &m.tipCap }
func (m *Message) Value() *uint256.Int { return &m.amount }
func (m *Message) Gas() uint64 { return m.gasLimit }
func (m *Message) Nonce() uint64 { return m.nonce }
func (m *Message) Data() []byte { return m.data }
func (m *Message) AccessList() AccessList { return m.accessList }
func (m *Message) Authorizations() []Authorization { return m.authorizations }
func (m *Message) SetBlobVersionedHashes(blobHashes []common.Hash) {
m.blobHashes = blobHashes
}
func (m *Message) SetAuthorizations(authorizations []Authorization) {
m.authorizations = authorizations
}
func (m *Message) CheckNonce() bool { return m.checkNonce }
func (m *Message) SetCheckNonce(checkNonce bool) {
m.checkNonce = checkNonce
}
func (m *Message) CheckTransaction() bool { return m.checkTransaction }
func (m *Message) SetCheckTransaction(checkTransaction bool) {
m.checkTransaction = checkTransaction
}
func (m *Message) CheckGas() bool { return m.checkGas }
func (m *Message) SetCheckGas(checkGas bool) {
m.checkGas = checkGas
}
func (m *Message) IsFree() bool { return m.isFree }
func (m *Message) SetIsFree(isFree bool) {
m.isFree = isFree
}
func (m *Message) ChangeGas(globalGasCap, desiredGas uint64) {
gas := globalGasCap
if gas == 0 {
gas = uint64(math.MaxUint64 / 2)
}
if desiredGas > 0 {
gas = desiredGas
}
if globalGasCap != 0 && globalGasCap < gas {
log.Warn("Caller gas above allowance, capping", "requested", gas, "cap", globalGasCap)
gas = globalGasCap
}
m.gasLimit = gas
}
func (m *Message) BlobGas() uint64 { return params.GasPerBlob * uint64(len(m.blobHashes)) }
func (m *Message) MaxFeePerBlobGas() *uint256.Int {
return &m.maxFeePerBlobGas
}
func (m *Message) BlobHashes() []common.Hash { return m.blobHashes }