arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/common/zk.go
common/zk.goRaw
  1// Package common contains all the common data structures used at the
  2// hermez-node, zk.go contains the zkSnark inputs used to generate the proof
  3package common
  4
  5import (
  6	"crypto/sha256"
  7	"encoding/binary"
  8	"encoding/json"
  9	"fmt"
 10	"math/big"
 11
 12	"github.com/hermeznetwork/hermez-node/log"
 13	"github.com/hermeznetwork/tracerr"
 14	cryptoConstants "github.com/iden3/go-iden3-crypto/constants"
 15	"github.com/iden3/go-merkletree"
 16	"github.com/mitchellh/mapstructure"
 17)
 18
 19// ZKMetadata contains ZKInputs metadata that is not used directly in the
 20// ZKInputs result, but to calculate values for Hash check
 21type ZKMetadata struct {
 22	// Circuit parameters
 23	// absolute maximum of L1 or L2 transactions allowed
 24	MaxLevels uint32
 25	// merkle tree depth
 26	NLevels uint32
 27	// absolute maximum of L1 transaction allowed
 28	MaxL1Tx uint32
 29	// total txs allowed
 30	MaxTx uint32
 31	// Maximum number of Idxs where Fees can be send in a batch (currently
 32	// is constant for all circuits: 64)
 33	MaxFeeIdxs uint32
 34
 35	L1TxsData             [][]byte
 36	L1TxsDataAvailability [][]byte
 37	L2TxsData             [][]byte
 38	ChainID               uint16
 39
 40	NewLastIdxRaw   Idx
 41	NewStateRootRaw *merkletree.Hash
 42	NewExitRootRaw  *merkletree.Hash
 43}
 44
 45// ZKInputs represents the inputs that will be used to generate the zkSNARK
 46// proof
 47type ZKInputs struct {
 48	Metadata ZKMetadata `json:"-"`
 49
 50	//
 51	// General
 52	//
 53
 54	// CurrentNumBatch is the current batch number processed
 55	CurrentNumBatch *big.Int `json:"currentNumBatch"` // uint32
 56	// inputs for final `hashGlobalInputs`
 57	// OldLastIdx is the last index assigned to an account
 58	OldLastIdx *big.Int `json:"oldLastIdx"` // uint64 (max nLevels bits)
 59	// OldStateRoot is the current state merkle tree root
 60	OldStateRoot *big.Int `json:"oldStateRoot"` // Hash
 61	// GlobalChainID is the blockchain ID (0 for Ethereum mainnet). This
 62	// value can be get from the smart contract.
 63	GlobalChainID *big.Int `json:"globalChainID"` // uint16
 64	// FeeIdxs is an array of merkle tree indexes (Idxs) where the
 65	// coordinator will receive the accumulated fees
 66	FeeIdxs []*big.Int `json:"feeIdxs"` // uint64 (max nLevels bits), len: [maxFeeIdxs]
 67
 68	// accumulate fees
 69	// FeePlanTokens contains all the tokenIDs for which the fees are being
 70	// accumulated and those fees accoumulated will be paid to the FeeIdxs
 71	// array.  The order of FeeIdxs & FeePlanTokens & State3 must match.
 72	// Coordinator fees are processed correlated such as:
 73	// [FeePlanTokens[i], FeeIdxs[i]]
 74	FeePlanTokens []*big.Int `json:"feePlanTokens"` // uint32 (max nLevels bits), len: [maxFeeIdxs]
 75
 76	//
 77	// Txs (L1&L2)
 78	//
 79
 80	// transaction L1-L2
 81	// TxCompressedData
 82	TxCompressedData []*big.Int `json:"txCompressedData"` // big.Int (max 251 bits), len: [maxTx]
 83	// TxCompressedDataV2, only used in L2Txs, in L1Txs is set to 0
 84	TxCompressedDataV2 []*big.Int `json:"txCompressedDataV2"` // big.Int (max 193 bits), len: [maxTx]
 85	// MaxNumBatch is the maximum allowed batch number when the transaction
 86	// can be processed
 87	MaxNumBatch []*big.Int `json:"maxNumBatch"` // big.Int (max 32 bits), len: [maxTx]
 88
 89	// FromIdx
 90	FromIdx []*big.Int `json:"fromIdx"` // uint64 (max nLevels bits), len: [maxTx]
 91	// AuxFromIdx is the Idx of the new created account which is
 92	// consequence of a L1CreateAccountTx
 93	AuxFromIdx []*big.Int `json:"auxFromIdx"` // uint64 (max nLevels bits), len: [maxTx]
 94
 95	// ToIdx
 96	ToIdx []*big.Int `json:"toIdx"` // uint64 (max nLevels bits), len: [maxTx]
 97	// AuxToIdx is the Idx of the Tx that has 'toIdx==0', is the
 98	// coordinator who will find which Idx corresponds to the 'toBJJAy' or
 99	// 'toEthAddr'
100	AuxToIdx []*big.Int `json:"auxToIdx"` // uint64 (max nLevels bits), len: [maxTx]
101	// ToBJJAy
102	ToBJJAy []*big.Int `json:"toBjjAy"` // big.Int, len: [maxTx]
103	// ToEthAddr
104	ToEthAddr []*big.Int `json:"toEthAddr"` // ethCommon.Address, len: [maxTx]
105	// AmountF encoded as float40
106	AmountF []*big.Int `json:"amountF"` // uint40 len: [maxTx]
107
108	// OnChain determines if is L1 (1/true) or L2 (0/false)
109	OnChain []*big.Int `json:"onChain"` // bool, len: [maxTx]
110
111	//
112	// Txs/L1Txs
113	//
114	// NewAccount boolean (0/1) flag set 'true' when L1 tx creates a new
115	// account (fromIdx==0)
116	NewAccount []*big.Int `json:"newAccount"` // bool, len: [maxTx]
117	// DepositAmountF encoded as float40
118	DepositAmountF []*big.Int `json:"loadAmountF"` // uint40, len: [maxTx]
119	// FromEthAddr
120	FromEthAddr []*big.Int `json:"fromEthAddr"` // ethCommon.Address, len: [maxTx]
121	// FromBJJCompressed boolean encoded where each value is a *big.Int
122	FromBJJCompressed [][256]*big.Int `json:"fromBjjCompressed"` // bool array, len: [maxTx][256]
123
124	//
125	// Txs/L2Txs
126	//
127
128	// RqOffset relative transaction position to be linked. Used to perform
129	// atomic transactions.
130	RqOffset []*big.Int `json:"rqOffset"` // uint8 (max 3 bits), len: [maxTx]
131
132	// transaction L2 request data
133	// RqTxCompressedDataV2
134	RqTxCompressedDataV2 []*big.Int `json:"rqTxCompressedDataV2"` // big.Int (max 251 bits), len: [maxTx]
135	// RqToEthAddr
136	RqToEthAddr []*big.Int `json:"rqToEthAddr"` // ethCommon.Address, len: [maxTx]
137	// RqToBJJAy
138	RqToBJJAy []*big.Int `json:"rqToBjjAy"` // big.Int, len: [maxTx]
139
140	// transaction L2 signature
141	// S
142	S []*big.Int `json:"s"` // big.Int, len: [maxTx]
143	// R8x
144	R8x []*big.Int `json:"r8x"` // big.Int, len: [maxTx]
145	// R8y
146	R8y []*big.Int `json:"r8y"` // big.Int, len: [maxTx]
147
148	//
149	// State MerkleTree Leafs transitions
150	//
151
152	// state 1, value of the sender (from) account leaf. The values at the
153	// moment pre-smtprocessor of the update (before updating the Sender
154	// leaf).
155	TokenID1  []*big.Int   `json:"tokenID1"`  // uint32, len: [maxTx]
156	Nonce1    []*big.Int   `json:"nonce1"`    // uint64 (max 40 bits), len: [maxTx]
157	Sign1     []*big.Int   `json:"sign1"`     // bool, len: [maxTx]
158	Ay1       []*big.Int   `json:"ay1"`       // big.Int, len: [maxTx]
159	Balance1  []*big.Int   `json:"balance1"`  // big.Int (max 192 bits), len: [maxTx]
160	EthAddr1  []*big.Int   `json:"ethAddr1"`  // ethCommon.Address, len: [maxTx]
161	Siblings1 [][]*big.Int `json:"siblings1"` // big.Int, len: [maxTx][nLevels + 1]
162	// Required for inserts and deletes, values of the CircomProcessorProof
163	// (smt insert proof)
164	IsOld0_1  []*big.Int `json:"isOld0_1"`  // bool, len: [maxTx]
165	OldKey1   []*big.Int `json:"oldKey1"`   // uint64 (max 40 bits), len: [maxTx]
166	OldValue1 []*big.Int `json:"oldValue1"` // Hash, len: [maxTx]
167
168	// state 2, value of the receiver (to) account leaf. The values at the
169	// moment pre-smtprocessor of the update (before updating the Receiver
170	// leaf).
171	// If Tx is an Exit (tx.ToIdx=1), state 2 is used for the Exit Merkle
172	// Proof of the Exit MerkleTree.
173	TokenID2  []*big.Int   `json:"tokenID2"`  // uint32, len: [maxTx]
174	Nonce2    []*big.Int   `json:"nonce2"`    // uint64 (max 40 bits), len: [maxTx]
175	Sign2     []*big.Int   `json:"sign2"`     // bool, len: [maxTx]
176	Ay2       []*big.Int   `json:"ay2"`       // big.Int, len: [maxTx]
177	Balance2  []*big.Int   `json:"balance2"`  // big.Int (max 192 bits), len: [maxTx]
178	EthAddr2  []*big.Int   `json:"ethAddr2"`  // ethCommon.Address, len: [maxTx]
179	Siblings2 [][]*big.Int `json:"siblings2"` // big.Int, len: [maxTx][nLevels + 1]
180	// NewExit determines if an exit transaction has to create a new leaf
181	// in the exit tree. If already exists an exit leaf of an account in
182	// the ExitTree, there is no 'new leaf' creation and 'NewExit' for that
183	// tx is 0 (if is an 'insert' in the tree, NewExit=1, if is an 'update'
184	// of an existing leaf, NewExit=0).
185	NewExit []*big.Int `json:"newExit"` // bool, len: [maxTx]
186	// Required for inserts and deletes, values of the CircomProcessorProof
187	// (smt insert proof)
188	IsOld0_2  []*big.Int `json:"isOld0_2"`  // bool, len: [maxTx]
189	OldKey2   []*big.Int `json:"oldKey2"`   // uint64 (max 40 bits), len: [maxTx]
190	OldValue2 []*big.Int `json:"oldValue2"` // Hash, len: [maxTx]
191
192	// state 3, fee leafs states, value of the account leaf receiver of the
193	// Fees fee tx. The values at the moment pre-smtprocessor of the update
194	// (before updating the Receiver leaf).
195	// The order of FeeIdxs & FeePlanTokens & State3 must match.
196	TokenID3  []*big.Int   `json:"tokenID3"`  // uint32, len: [maxFeeIdxs]
197	Nonce3    []*big.Int   `json:"nonce3"`    // uint64 (max 40 bits), len: [maxFeeIdxs]
198	Sign3     []*big.Int   `json:"sign3"`     // bool, len: [maxFeeIdxs]
199	Ay3       []*big.Int   `json:"ay3"`       // big.Int, len: [maxFeeIdxs]
200	Balance3  []*big.Int   `json:"balance3"`  // big.Int (max 192 bits), len: [maxFeeIdxs]
201	EthAddr3  []*big.Int   `json:"ethAddr3"`  // ethCommon.Address, len: [maxFeeIdxs]
202	Siblings3 [][]*big.Int `json:"siblings3"` // Hash, len: [maxFeeIdxs][nLevels + 1]
203
204	//
205	// Intermediate States
206	//
207
208	// Intermediate States to parallelize witness computation
209	// Note: the Intermediate States (IS) of the last transaction does not
210	// exist. Meaning that transaction 3 (4th) will fill the parameters
211	// FromIdx[3] and ISOnChain[3], but last transaction (maxTx-1) will fill
212	// FromIdx[maxTx-1] but will not fill ISOnChain. That's why IS have
213	// length of maxTx-1, while the other parameters have length of maxTx.
214	// Last transaction does not need intermediate state since its output
215	// will not be used.
216
217	// decode-tx
218	// ISOnChain indicates if tx is L1 (true (1)) or L2 (false (0))
219	ISOnChain []*big.Int `json:"imOnChain"` // bool, len: [maxTx - 1]
220	// ISOutIdx current index account for each Tx
221	// Contains the index of the created account in case that the tx is of
222	// account creation type.
223	ISOutIdx []*big.Int `json:"imOutIdx"` // uint64 (max nLevels bits), len: [maxTx - 1]
224	// rollup-tx
225	// ISStateRoot root at the moment of the Tx (once processed), the state
226	// root value once the Tx is processed into the state tree
227	ISStateRoot []*big.Int `json:"imStateRoot"` // Hash, len: [maxTx - 1]
228	// ISExitTree root at the moment (once processed) of the Tx the value
229	// once the Tx is processed into the exit tree
230	ISExitRoot []*big.Int `json:"imExitRoot"` // Hash, len: [maxTx - 1]
231	// ISAccFeeOut accumulated fees once the Tx is processed.  Contains the
232	// array of FeeAccount Balances at each moment of each Tx processed.
233	ISAccFeeOut [][]*big.Int `json:"imAccFeeOut"` // big.Int, len: [maxTx - 1][maxFeeIdxs]
234	// fee-tx:
235	// ISStateRootFee root at the moment of the Tx (once processed), the
236	// state root value once the Tx is processed into the state tree
237	ISStateRootFee []*big.Int `json:"imStateRootFee"` // Hash, len: [maxFeeIdxs - 1]
238	// ISInitStateRootFee state root once all L1-L2 tx are processed
239	// (before computing the fees-tx)
240	ISInitStateRootFee *big.Int `json:"imInitStateRootFee"` // Hash
241	// ISFinalAccFee final accumulated fees (before computing the fees-tx).
242	// Contains the final values of the ISAccFeeOut parameter
243	ISFinalAccFee []*big.Int `json:"imFinalAccFee"` // big.Int, len: [maxFeeIdxs]
244}
245
246func bigIntsToStrings(v interface{}) interface{} {
247	switch c := v.(type) {
248	case *big.Int:
249		return c.String()
250	case []*big.Int:
251		r := make([]interface{}, len(c))
252		for i := range c {
253			r[i] = bigIntsToStrings(c[i])
254		}
255		return r
256	case [256]*big.Int:
257		r := make([]interface{}, len(c))
258		for i := range c {
259			r[i] = bigIntsToStrings(c[i])
260		}
261		return r
262	case [][]*big.Int:
263		r := make([]interface{}, len(c))
264		for i := range c {
265			r[i] = bigIntsToStrings(c[i])
266		}
267		return r
268	case [][256]*big.Int:
269		r := make([]interface{}, len(c))
270		for i := range c {
271			r[i] = bigIntsToStrings(c[i])
272		}
273		return r
274	case map[string]interface{}:
275		// avoid printing a warning when there is a struct type
276	default:
277		log.Warnf("bigIntsToStrings unexpected type: %T\n", v)
278	}
279	return nil
280}
281
282// MarshalJSON implements the json marshaler for ZKInputs
283func (z ZKInputs) MarshalJSON() ([]byte, error) {
284	var m map[string]interface{}
285	dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
286		TagName: "json",
287		Result:  &m,
288	})
289	if err != nil {
290		return nil, tracerr.Wrap(err)
291	}
292	err = dec.Decode(z)
293	if err != nil {
294		return nil, tracerr.Wrap(err)
295	}
296
297	for k, v := range m {
298		m[k] = bigIntsToStrings(v)
299	}
300	return json.Marshal(m)
301}
302
303// NewZKInputs returns a pointer to an initialized struct of ZKInputs
304func NewZKInputs(chainID uint16, maxTx, maxL1Tx, maxFeeIdxs, nLevels uint32, currentNumBatch *big.Int) *ZKInputs {
305	zki := &ZKInputs{}
306	zki.Metadata.MaxFeeIdxs = maxFeeIdxs
307	zki.Metadata.MaxLevels = uint32(48) //nolint:gomnd
308	zki.Metadata.NLevels = nLevels
309	zki.Metadata.MaxL1Tx = maxL1Tx
310	zki.Metadata.MaxTx = maxTx
311	zki.Metadata.ChainID = chainID
312
313	// General
314	zki.CurrentNumBatch = currentNumBatch
315	zki.OldLastIdx = big.NewInt(0)
316	zki.OldStateRoot = big.NewInt(0)
317	zki.GlobalChainID = big.NewInt(int64(chainID))
318	zki.FeeIdxs = newSlice(maxFeeIdxs)
319	zki.FeePlanTokens = newSlice(maxFeeIdxs)
320
321	// Txs
322	zki.TxCompressedData = newSlice(maxTx)
323	zki.TxCompressedDataV2 = newSlice(maxTx)
324	zki.MaxNumBatch = newSlice(maxTx)
325	zki.FromIdx = newSlice(maxTx)
326	zki.AuxFromIdx = newSlice(maxTx)
327	zki.ToIdx = newSlice(maxTx)
328	zki.AuxToIdx = newSlice(maxTx)
329	zki.ToBJJAy = newSlice(maxTx)
330	zki.ToEthAddr = newSlice(maxTx)
331	zki.AmountF = newSlice(maxTx)
332	zki.OnChain = newSlice(maxTx)
333	zki.NewAccount = newSlice(maxTx)
334
335	// L1
336	zki.DepositAmountF = newSlice(maxTx)
337	zki.FromEthAddr = newSlice(maxTx)
338	zki.FromBJJCompressed = make([][256]*big.Int, maxTx)
339	for i := 0; i < len(zki.FromBJJCompressed); i++ {
340		// zki.FromBJJCompressed[i] = newSlice(256)
341		for j := 0; j < 256; j++ {
342			zki.FromBJJCompressed[i][j] = big.NewInt(0)
343		}
344	}
345
346	// L2
347	zki.RqOffset = newSlice(maxTx)
348	zki.RqTxCompressedDataV2 = newSlice(maxTx)
349	zki.RqToEthAddr = newSlice(maxTx)
350	zki.RqToBJJAy = newSlice(maxTx)
351	zki.S = newSlice(maxTx)
352	zki.R8x = newSlice(maxTx)
353	zki.R8y = newSlice(maxTx)
354
355	// State MerkleTree Leafs transitions
356	zki.TokenID1 = newSlice(maxTx)
357	zki.Nonce1 = newSlice(maxTx)
358	zki.Sign1 = newSlice(maxTx)
359	zki.Ay1 = newSlice(maxTx)
360	zki.Balance1 = newSlice(maxTx)
361	zki.EthAddr1 = newSlice(maxTx)
362	zki.Siblings1 = make([][]*big.Int, maxTx)
363	for i := 0; i < len(zki.Siblings1); i++ {
364		zki.Siblings1[i] = newSlice(nLevels + 1)
365	}
366	zki.IsOld0_1 = newSlice(maxTx)
367	zki.OldKey1 = newSlice(maxTx)
368	zki.OldValue1 = newSlice(maxTx)
369
370	zki.TokenID2 = newSlice(maxTx)
371	zki.Nonce2 = newSlice(maxTx)
372	zki.Sign2 = newSlice(maxTx)
373	zki.Ay2 = newSlice(maxTx)
374	zki.Balance2 = newSlice(maxTx)
375	zki.EthAddr2 = newSlice(maxTx)
376	zki.Siblings2 = make([][]*big.Int, maxTx)
377	for i := 0; i < len(zki.Siblings2); i++ {
378		zki.Siblings2[i] = newSlice(nLevels + 1)
379	}
380	zki.NewExit = newSlice(maxTx)
381	zki.IsOld0_2 = newSlice(maxTx)
382	zki.OldKey2 = newSlice(maxTx)
383	zki.OldValue2 = newSlice(maxTx)
384
385	zki.TokenID3 = newSlice(maxFeeIdxs)
386	zki.Nonce3 = newSlice(maxFeeIdxs)
387	zki.Sign3 = newSlice(maxFeeIdxs)
388	zki.Ay3 = newSlice(maxFeeIdxs)
389	zki.Balance3 = newSlice(maxFeeIdxs)
390	zki.EthAddr3 = newSlice(maxFeeIdxs)
391	zki.Siblings3 = make([][]*big.Int, maxFeeIdxs)
392	for i := 0; i < len(zki.Siblings3); i++ {
393		zki.Siblings3[i] = newSlice(nLevels + 1)
394	}
395
396	// Intermediate States
397	zki.ISOnChain = newSlice(maxTx - 1)
398	zki.ISOutIdx = newSlice(maxTx - 1)
399	zki.ISStateRoot = newSlice(maxTx - 1)
400	zki.ISExitRoot = newSlice(maxTx - 1)
401	zki.ISAccFeeOut = make([][]*big.Int, maxTx-1)
402	for i := 0; i < len(zki.ISAccFeeOut); i++ {
403		zki.ISAccFeeOut[i] = newSlice(maxFeeIdxs)
404	}
405	zki.ISStateRootFee = newSlice(maxFeeIdxs - 1)
406	zki.ISInitStateRootFee = big.NewInt(0)
407	zki.ISFinalAccFee = newSlice(maxFeeIdxs)
408
409	return zki
410}
411
412// newSlice returns a []*big.Int slice of length n with values initialized at
413// 0.
414// Is used to initialize all *big.Ints of the ZKInputs data structure, so when
415// the transactions are processed and the ZKInputs filled, there is no need to
416// set all the elements, and if a transaction does not use a parameter, can be
417// leaved as it is in the ZKInputs, as will be 0, so later when using the
418// ZKInputs to generate the zkSnark proof there is no 'nil'/'null' values.
419func newSlice(n uint32) []*big.Int {
420	s := make([]*big.Int, n)
421	for i := 0; i < len(s); i++ {
422		s[i] = big.NewInt(0)
423	}
424	return s
425}
426
427// HashGlobalData returns the HashGlobalData
428func (z ZKInputs) HashGlobalData() (*big.Int, error) {
429	b, err := z.ToHashGlobalData()
430	if err != nil {
431		return nil, tracerr.Wrap(err)
432	}
433
434	h := sha256.New()
435	_, err = h.Write(b)
436	if err != nil {
437		return nil, tracerr.Wrap(err)
438	}
439
440	r := new(big.Int).SetBytes(h.Sum(nil))
441	v := r.Mod(r, cryptoConstants.Q)
442
443	return v, nil
444}
445
446// ToHashGlobalData returns the data to be hashed in the method HashGlobalData
447func (z ZKInputs) ToHashGlobalData() ([]byte, error) {
448	var b []byte
449	bytesMaxLevels := int(z.Metadata.MaxLevels / 8) //nolint:gomnd
450	bytesNLevels := int(z.Metadata.NLevels / 8)     //nolint:gomnd
451
452	// [MAX_NLEVELS bits] oldLastIdx
453	oldLastIdx := make([]byte, bytesMaxLevels)
454	oldLastIdxBytes := z.OldLastIdx.Bytes()
455	copy(oldLastIdx[len(oldLastIdx)-len(oldLastIdxBytes):], oldLastIdxBytes)
456	b = append(b, oldLastIdx...)
457
458	// [MAX_NLEVELS bits] newLastIdx
459	newLastIdx := make([]byte, bytesMaxLevels)
460	newLastIdxBytes, err := z.Metadata.NewLastIdxRaw.Bytes()
461	if err != nil {
462		return nil, tracerr.Wrap(err)
463	}
464	copy(newLastIdx, newLastIdxBytes[len(newLastIdxBytes)-bytesMaxLevels:])
465	b = append(b, newLastIdx...)
466
467	// [256 bits] oldStRoot
468	oldStateRoot := make([]byte, 32)
469	copy(oldStateRoot, z.OldStateRoot.Bytes())
470	b = append(b, oldStateRoot...)
471
472	// [256 bits] newStateRoot
473	newStateRoot := make([]byte, 32)
474	copy(newStateRoot, z.Metadata.NewStateRootRaw.Bytes())
475	b = append(b, newStateRoot...)
476
477	// [256 bits] newExitRoot
478	newExitRoot := make([]byte, 32)
479	copy(newExitRoot, z.Metadata.NewExitRootRaw.Bytes())
480	b = append(b, newExitRoot...)
481
482	// [MAX_L1_TX * (2 * MAX_NLEVELS + 528) bits] L1TxsData
483	l1TxDataLen := (2*z.Metadata.MaxLevels + 528)
484	l1TxsDataLen := (z.Metadata.MaxL1Tx * l1TxDataLen)
485	l1TxsData := make([]byte, l1TxsDataLen/8) //nolint:gomnd
486	for i := 0; i < len(z.Metadata.L1TxsData); i++ {
487		dataLen := int(l1TxDataLen) / 8 //nolint:gomnd
488		pos0 := i * dataLen
489		pos1 := i*dataLen + dataLen
490		copy(l1TxsData[pos0:pos1], z.Metadata.L1TxsData[i])
491	}
492	b = append(b, l1TxsData...)
493
494	var l1TxsDataAvailability []byte
495	for i := 0; i < len(z.Metadata.L1TxsDataAvailability); i++ {
496		l1TxsDataAvailability = append(l1TxsDataAvailability, z.Metadata.L1TxsDataAvailability[i]...)
497	}
498	b = append(b, l1TxsDataAvailability...)
499
500	// [MAX_TX*(2*NLevels + 48) bits] L2TxsData
501	var l2TxsData []byte
502	l2TxDataLen := 2*z.Metadata.NLevels + 48 //nolint:gomnd
503	l2TxsDataLen := (z.Metadata.MaxTx * l2TxDataLen)
504	expectedL2TxsDataLen := l2TxsDataLen / 8 //nolint:gomnd
505	for i := 0; i < len(z.Metadata.L2TxsData); i++ {
506		l2TxsData = append(l2TxsData, z.Metadata.L2TxsData[i]...)
507	}
508	if len(l2TxsData) > int(expectedL2TxsDataLen) {
509		return nil, tracerr.Wrap(fmt.Errorf("len(l2TxsData): %d, expected: %d", len(l2TxsData), expectedL2TxsDataLen))
510	}
511
512	b = append(b, l2TxsData...)
513	l2TxsPadding := make([]byte, (int(z.Metadata.MaxTx)-len(z.Metadata.L1TxsDataAvailability)-len(z.Metadata.L2TxsData))*int(l2TxDataLen)/8) //nolint:gomnd
514	b = append(b, l2TxsPadding...)
515
516	// [NLevels * MAX_TOKENS_FEE bits] feeTxsData
517	for i := 0; i < len(z.FeeIdxs); i++ {
518		feeIdx := make([]byte, bytesNLevels) //nolint:gomnd
519		feeIdxBytes := z.FeeIdxs[i].Bytes()
520		copy(feeIdx[len(feeIdx)-len(feeIdxBytes):], feeIdxBytes[:])
521		b = append(b, feeIdx...)
522	}
523
524	// [16 bits] chainID
525	var chainID [2]byte
526	binary.BigEndian.PutUint16(chainID[:], z.Metadata.ChainID)
527	b = append(b, chainID[:]...)
528
529	// [32 bits] currentNumBatch
530	currNumBatchBytes := z.CurrentNumBatch.Bytes()
531	var currNumBatch [4]byte
532	copy(currNumBatch[4-len(currNumBatchBytes):], currNumBatchBytes)
533	b = append(b, currNumBatch[:]...)
534
535	return b, nil
536}