-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathserialize.go
More file actions
312 lines (256 loc) · 8.27 KB
/
serialize.go
File metadata and controls
312 lines (256 loc) · 8.27 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
package transaction
import (
"encoding/hex"
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rlp"
"github.com/tempoxyz/tempo-go/pkg/signer"
)
// SerializeFormat specifies the serialization format for a transaction.
type SerializeFormat int
const (
// FormatNormal uses TempoTransaction prefix (0x76) for standard signing (default).
FormatNormal SerializeFormat = iota
// FormatFeePayer uses TempoTransaction fee payer prefix (0x78) for fee payer signing.
FormatFeePayer
)
// String returns a human-readable representation of the serialize format.
// Implements the fmt.Stringer interface.
func (f SerializeFormat) String() string {
switch f {
case FormatNormal:
return "normal"
case FormatFeePayer:
return "feePayer"
default:
return fmt.Sprintf("unknown(%d)", f)
}
}
// SerializeOptions contains options for serializing a transaction.
type SerializeOptions struct {
// Format specifies the serialization format.
// FormatNormal (default) uses TempoTransaction prefix (0x76) for standard signing.
// FormatFeePayer uses TempoTransaction fee payer prefix (0x78) for fee payer signing.
Format SerializeFormat
// Sender is the sender address, required when Format is FormatFeePayer.
Sender common.Address
}
// Serialize serializes a TempoTransaction to hex string.
// Returns a string starting with TempoTransaction prefix "0x76" or "0x78" (if fee payer format).
func Serialize(tx *Tx, opts *SerializeOptions) (string, error) {
if opts == nil {
opts = &SerializeOptions{Format: FormatNormal}
}
rlpList, err := buildRLPList(tx, opts)
if err != nil {
return "", err
}
return encodeWithPrefix(rlpList, opts.Format)
}
// buildRLPList constructs the RLP list for a transaction.
// This contains all 13-14 fields of a TempoTransaction.
func buildRLPList(tx *Tx, opts *SerializeOptions) ([]interface{}, error) {
rlpList := make([]interface{}, 0, 14)
// Fields 0-3: Core gas and fee fields
rlpList = append(rlpList,
bigIntToBytes(tx.ChainID),
bigIntToBytes(tx.MaxPriorityFeePerGas),
bigIntToBytes(tx.MaxFeePerGas),
uint64ToBytes(tx.Gas),
)
// Field 4: calls
callsRLP, err := encodeCalls(tx.Calls)
if err != nil {
return nil, fmt.Errorf("failed to encode calls: %w", err)
}
rlpList = append(rlpList, callsRLP)
// Field 5: accessList
rlpList = append(rlpList, encodeAccessList(tx.AccessList))
// Fields 6-10: Nonce, validity, and fee token
rlpList = append(rlpList,
bigIntToBytes(tx.NonceKey),
uint64ToBytes(tx.Nonce),
uint64ToBytes(tx.ValidBefore),
uint64ToBytes(tx.ValidAfter),
encodeFeeToken(tx.FeeToken),
)
// Field 11: feePayerSignatureOrSender
rlpList = append(rlpList, encodeFeePayerField(tx, opts))
// Field 12: authorizationList (empty for now)
rlpList = append(rlpList, []interface{}{})
// Field 13: signatureEnvelope (if present)
if tx.Signature != nil {
sigEnvelopeBytes, err := encodeSignatureEnvelope(tx.Signature)
if err != nil {
return nil, fmt.Errorf("failed to encode signature envelope: %w", err)
}
rlpList = append(rlpList, sigEnvelopeBytes)
}
return rlpList, nil
}
// encodeFeeToken encodes the fee token address.
// Returns empty bytes if the address is zero (native token).
func encodeFeeToken(token common.Address) []byte {
if token != (common.Address{}) {
return token.Bytes()
}
return []byte{}
}
// encodeFeePayerField encodes field 11 (feePayerSignatureOrSender).
// The encoding depends on the serialization format and whether a fee payer signature exists.
func encodeFeePayerField(tx *Tx, opts *SerializeOptions) interface{} {
// For fee payer signing format (0x78), include sender address
if opts.Format == FormatFeePayer {
return opts.Sender.Bytes()
}
// If transaction has fee payer signature, encode it as [yParity, r, s]
if tx.FeePayerSignature != nil {
var yParityBytes []byte
if tx.FeePayerSignature.YParity != 0 {
yParityBytes = []byte{tx.FeePayerSignature.YParity}
}
return []interface{}{
yParityBytes,
tx.FeePayerSignature.R.Bytes(),
tx.FeePayerSignature.S.Bytes(),
}
}
// If awaiting fee payer, use 0x00 marker
if tx.AwaitingFeePayer {
return []byte{0x00}
}
// No fee payer signature - use empty byte array
return []byte{}
}
// encodeWithPrefix encodes the RLP list and adds the appropriate TempoTransaction type prefix.
// Returns TempoTransaction prefix "0x76" for normal format, "0x78" for fee payer format.
func encodeWithPrefix(rlpList []interface{}, format SerializeFormat) (string, error) {
rlpBytes, err := rlp.EncodeToBytes(rlpList)
if err != nil {
return "", fmt.Errorf("failed to encode RLP: %w", err)
}
prefix := "76"
if format == FormatFeePayer {
prefix = "78"
}
return "0x" + prefix + hex.EncodeToString(rlpBytes), nil
}
// SerializeForSigning serializes a transaction for sender signing (without signatures).
func SerializeForSigning(tx *Tx) (string, error) {
// Create a copy without signatures
txCopy := *tx
txCopy.Signature = nil
txCopy.FeePayerSignature = nil
return Serialize(&txCopy, &SerializeOptions{Format: FormatNormal})
}
// SerializeForFeePayerSigning serializes a transaction for fee payer signing.
// This uses the 0x78 prefix and includes the sender address.
// IMPORTANT: Must remove BOTH sender and fee payer signatures (per tempo.ts reference).
func SerializeForFeePayerSigning(tx *Tx, sender common.Address) (string, error) {
// Create a copy without signatures
txCopy := *tx
txCopy.Signature = nil // Remove sender signature (required by tempo.ts)
txCopy.FeePayerSignature = nil // Remove fee payer signature
return Serialize(&txCopy, &SerializeOptions{
Format: FormatFeePayer,
Sender: sender,
})
}
// encodeCalls encodes the calls array to RLP.
// Each call is encoded as [to, value, data].
func encodeCalls(calls []Call) ([]interface{}, error) {
rlpCalls := make([]interface{}, 0, len(calls))
for _, call := range calls {
callTuple := make([]interface{}, 3)
// Field 0: to
if call.To != nil {
callTuple[0] = call.To.Bytes()
} else {
callTuple[0] = []byte{}
}
// Field 1: value
if call.Value != nil {
callTuple[1] = call.Value.Bytes()
} else {
callTuple[1] = []byte{}
}
// Field 2: data
if call.Data != nil {
callTuple[2] = call.Data
} else {
callTuple[2] = []byte{}
}
rlpCalls = append(rlpCalls, callTuple)
}
return rlpCalls, nil
}
// encodeAccessList encodes the access list to RLP.
// Each tuple is encoded as [address, [storageKeys]].
func encodeAccessList(accessList AccessList) []interface{} {
if len(accessList) == 0 {
return []interface{}{}
}
rlpAccessList := make([]interface{}, 0, len(accessList))
for _, tuple := range accessList {
// Encode storage keys
storageKeys := make([]interface{}, 0, len(tuple.StorageKeys))
for _, key := range tuple.StorageKeys {
storageKeys = append(storageKeys, key.Bytes())
}
// Create tuple [address, [storageKeys]]
rlpTuple := []interface{}{
tuple.Address.Bytes(),
storageKeys,
}
rlpAccessList = append(rlpAccessList, rlpTuple)
}
return rlpAccessList
}
// encodeSignature encodes a signature to RLP tuple [yParity, r, s].
func encodeSignature(sig *signer.Signature) []interface{} {
var yParityBytes []byte
if sig.YParity != 0 {
yParityBytes = []byte{sig.YParity}
}
return []interface{}{
yParityBytes,
sig.R.Bytes(),
sig.S.Bytes(),
}
}
// encodeSignatureEnvelope encodes a signature envelope to RLP.
func encodeSignatureEnvelope(envelope *signer.SignatureEnvelope) ([]byte, error) {
if envelope == nil || envelope.Signature == nil {
return []byte{}, nil
}
if envelope.Type == "secp256k1" {
result := make([]byte, 65)
rBytes := envelope.Signature.R.Bytes()
copy(result[32-len(rBytes):32], rBytes)
sBytes := envelope.Signature.S.Bytes()
copy(result[64-len(sBytes):64], sBytes)
result[64] = envelope.Signature.YParity
return result, nil
}
sigTuple := encodeSignature(envelope.Signature)
envelopeRLP := []interface{}{
[]byte(envelope.Type),
sigTuple,
}
return rlp.EncodeToBytes(envelopeRLP)
}
// bigIntToBytes converts a *big.Int to bytes, returning empty bytes for nil or 0.
func bigIntToBytes(n *big.Int) []byte {
if n == nil || n.Sign() == 0 {
return []byte{}
}
return n.Bytes()
}
// uint64ToBytes converts a uint64 to bytes, returning empty bytes for 0.
func uint64ToBytes(n uint64) []byte {
if n == 0 {
return []byte{}
}
return new(big.Int).SetUint64(n).Bytes()
}