arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/eth/rollup.go
eth/rollup.goRaw
  1package eth
  2
  3import (
  4	"context"
  5	"fmt"
  6	"math/big"
  7	"strings"
  8
  9	"github.com/ethereum/go-ethereum"
 10	"github.com/ethereum/go-ethereum/accounts/abi"
 11	"github.com/ethereum/go-ethereum/accounts/abi/bind"
 12	ethCommon "github.com/ethereum/go-ethereum/common"
 13	"github.com/ethereum/go-ethereum/core/types"
 14	"github.com/ethereum/go-ethereum/crypto"
 15	"github.com/ethereum/go-ethereum/ethclient"
 16	"github.com/hermeznetwork/hermez-node/common"
 17	Hermez "github.com/hermeznetwork/hermez-node/eth/contracts/hermez"
 18	HEZ "github.com/hermeznetwork/hermez-node/eth/contracts/tokenHEZ"
 19	"github.com/hermeznetwork/hermez-node/log"
 20	"github.com/iden3/go-iden3-crypto/babyjub"
 21)
 22
 23const (
 24	// RollupConstMaxFeeIdxCoordinator is the maximum number of tokens the
 25	// coordinator can use to collect fees (determines the number of tokens
 26	// that the coordinator can collect fees from).  This value is
 27	// determined by the circuit.
 28	RollupConstMaxFeeIdxCoordinator = 64
 29	// RollupConstReservedIDx First 256 indexes reserved, first user index will be the 256
 30	RollupConstReservedIDx = 255
 31	// RollupConstExitIDx IDX 1 is reserved for exits
 32	RollupConstExitIDx = 1
 33	// RollupConstLimitLoadAmount Max load amount allowed (loadAmount: L1 --> L2)
 34	RollupConstLimitLoadAmount = (1 << 128)
 35	// RollupConstLimitL2TransferAmount Max amount allowed (amount L2 --> L2)
 36	RollupConstLimitL2TransferAmount = (1 << 192)
 37	// RollupConstLimitTokens Max number of tokens allowed to be registered inside the rollup
 38	RollupConstLimitTokens = (1 << 32)
 39	// RollupConstL1CoordinatorTotalBytes [4 bytes] token + [32 bytes] babyjub + [65 bytes] compressedSignature
 40	RollupConstL1CoordinatorTotalBytes = 101
 41	// RollupConstL1UserTotalBytes [20 bytes] fromEthAddr + [32 bytes] fromBjj-compressed + [6 bytes] fromIdx +
 42	// [2 bytes] loadAmountFloat16 + [2 bytes] amountFloat16 + [4 bytes] tokenId + [6 bytes] toIdx
 43	RollupConstL1UserTotalBytes = 72
 44	// RollupConstMaxL1UserTx Maximum L1-user transactions allowed to be queued in a batch
 45	RollupConstMaxL1UserTx = 128
 46	// RollupConstMaxL1Tx Maximum L1 transactions allowed to be queued in a batch
 47	RollupConstMaxL1Tx = 256
 48	// RollupConstInputSHAConstantBytes [6 bytes] lastIdx + [6 bytes] newLastIdx  + [32 bytes] stateRoot  + [32 bytes] newStRoot  + [32 bytes] newExitRoot +
 49	// [_MAX_L1_TX * _L1_USER_TOTALBYTES bytes] l1TxsData + totalL2TxsDataLength + feeIdxCoordinatorLength + [2 bytes] chainID =
 50	// 18542 bytes +  totalL2TxsDataLength + feeIdxCoordinatorLength
 51	RollupConstInputSHAConstantBytes = 18542
 52	// RollupConstNumBuckets Number of buckets
 53	RollupConstNumBuckets = 5
 54	// RollupConstMaxWithdrawalDelay max withdrawal delay in seconds
 55	RollupConstMaxWithdrawalDelay = 2 * 7 * 24 * 60 * 60
 56	// RollupConstExchangeMultiplier exchange multiplier
 57	RollupConstExchangeMultiplier = 1e14
 58	// LenVerifiers number of Rollup Smart Contract Verifiers
 59	LenVerifiers = 1
 60)
 61
 62var (
 63	// RollupConstEthAddressInternalOnly This ethereum address is used internally for rollup accounts that don't have ethereum address, only Babyjubjub
 64	// This non-ethereum accounts can be created by the coordinator and allow users to have a rollup
 65	// account without needing an ethereum address
 66	RollupConstEthAddressInternalOnly = ethCommon.HexToAddress("0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF")
 67	// RollupConstRfield Modulus zkSNARK
 68	RollupConstRfield, _ = new(big.Int).SetString(
 69		"21888242871839275222246405745257275088548364400416034343698204186575808495617", 10)
 70
 71	// RollupConstERC1820 ERC1820Registry address
 72	RollupConstERC1820 = ethCommon.HexToAddress("0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24")
 73
 74	// ERC777 tokens signatures
 75
 76	// RollupConstRecipientInterfaceHash ERC777 recipient interface hash
 77	RollupConstRecipientInterfaceHash = crypto.Keccak256([]byte("ERC777TokensRecipient"))
 78	// RollupConstPerformL1UserTxSignature the signature of the function that can be called thru an ERC777 `send`
 79	RollupConstPerformL1UserTxSignature = crypto.Keccak256([]byte("addL1Transaction(uint256,uint48,uint16,uint16,uint32,uint48)"))
 80	// RollupConstAddTokenSignature the signature of the function that can be called thru an ERC777 `send`
 81	RollupConstAddTokenSignature = crypto.Keccak256([]byte("addToken(address)"))
 82	// RollupConstSendSignature ERC777 Signature
 83	RollupConstSendSignature = crypto.Keccak256([]byte("send(address,uint256,bytes)"))
 84	// RollupConstERC777Granularity ERC777 Signature
 85	RollupConstERC777Granularity = crypto.Keccak256([]byte("granularity()"))
 86	// RollupConstWithdrawalDelayerDeposit  This constant are used to deposit tokens from ERC77 tokens into withdrawal delayer
 87	RollupConstWithdrawalDelayerDeposit = crypto.Keccak256([]byte("deposit(address,address,uint192)"))
 88
 89	// ERC20 signature
 90
 91	// RollupConstTransferSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
 92	RollupConstTransferSignature = crypto.Keccak256([]byte("transfer(address,uint256)"))
 93	// RollupConstTransferFromSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
 94	RollupConstTransferFromSignature = crypto.Keccak256([]byte("transferFrom(address,address,uint256)"))
 95	// RollupConstApproveSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
 96	RollupConstApproveSignature = crypto.Keccak256([]byte("approve(address,uint256)"))
 97	// RollupConstERC20Signature ERC20 decimals signature
 98	RollupConstERC20Signature = crypto.Keccak256([]byte("decimals()"))
 99)
100
101// RollupPublicConstants are the constants of the Rollup Smart Contract
102type RollupPublicConstants struct {
103	AbsoluteMaxL1L2BatchTimeout int64                  `json:"absoluteMaxL1L2BatchTimeout"`
104	TokenHEZ                    ethCommon.Address      `json:"tokenHEZ"`
105	Verifiers                   []RollupVerifierStruct `json:"verifiers"`
106	HermezAuctionContract       ethCommon.Address      `json:"hermezAuctionContract"`
107	HermezGovernanceDAOAddress  ethCommon.Address      `json:"hermezGovernanceDAOAddress"`
108	SafetyAddress               ethCommon.Address      `json:"safetyAddress"`
109	WithdrawDelayerContract     ethCommon.Address      `json:"withdrawDelayerContract"`
110}
111
112// RollupVariables are the variables of the Rollup Smart Contract
113type RollupVariables struct {
114	FeeAddToken           *big.Int
115	ForgeL1L2BatchTimeout int64
116	WithdrawalDelay       uint64
117}
118
119// QueueStruct is the queue of L1Txs for a batch
120type QueueStruct struct {
121	L1TxQueue    []common.L1Tx
122	TotalL1TxFee *big.Int
123}
124
125// NewQueueStruct creates a new clear QueueStruct.
126func NewQueueStruct() *QueueStruct {
127	return &QueueStruct{
128		L1TxQueue:    make([]common.L1Tx, 0),
129		TotalL1TxFee: big.NewInt(0),
130	}
131}
132
133// RollupVerifierStruct is the information about verifiers of the Rollup Smart Contract
134type RollupVerifierStruct struct {
135	MaxTx   int64 `json:"maxTx"`
136	NLevels int64 `json:"nlevels"`
137}
138
139// RollupState represents the state of the Rollup in the Smart Contract
140type RollupState struct {
141	StateRoot              *big.Int
142	ExitRoots              []*big.Int
143	ExitNullifierMap       map[[256 / 8]byte]bool
144	TokenList              []ethCommon.Address
145	TokenMap               map[ethCommon.Address]bool
146	MapL1TxQueue           map[int64]*QueueStruct
147	LastL1L2Batch          int64
148	CurrentToForgeL1TxsNum int64
149	LastToForgeL1TxsNum    int64
150	CurrentIdx             int64
151}
152
153// RollupEventL1UserTx is an event of the Rollup Smart Contract
154type RollupEventL1UserTx struct {
155	// ToForgeL1TxsNum int64 // QueueIndex       *big.Int
156	// Position        int   // TransactionIndex *big.Int
157	L1UserTx common.L1Tx
158}
159
160// RollupEventL1UserTxAux is an event of the Rollup Smart Contract
161type RollupEventL1UserTxAux struct {
162	ToForgeL1TxsNum uint64 // QueueIndex       *big.Int
163	Position        uint8  // TransactionIndex *big.Int
164	L1UserTx        []byte
165}
166
167// RollupEventAddToken is an event of the Rollup Smart Contract
168type RollupEventAddToken struct {
169	TokenAddress ethCommon.Address
170	TokenID      uint32
171}
172
173// RollupEventForgeBatch is an event of the Rollup Smart Contract
174type RollupEventForgeBatch struct {
175	BatchNum int64
176	// Sender    ethCommon.Address
177	EthTxHash ethCommon.Hash
178}
179
180// RollupEventUpdateForgeL1L2BatchTimeout is an event of the Rollup Smart Contract
181type RollupEventUpdateForgeL1L2BatchTimeout struct {
182	NewForgeL1L2BatchTimeout int64
183}
184
185// RollupEventUpdateFeeAddToken is an event of the Rollup Smart Contract
186type RollupEventUpdateFeeAddToken struct {
187	NewFeeAddToken *big.Int
188}
189
190// RollupEventWithdrawEvent is an event of the Rollup Smart Contract
191type RollupEventWithdrawEvent struct {
192	Idx             uint64
193	NumExitRoot     uint64
194	InstantWithdraw bool
195}
196
197// RollupEvents is the list of events in a block of the Rollup Smart Contract
198type RollupEvents struct {
199	L1UserTx                    []RollupEventL1UserTx
200	AddToken                    []RollupEventAddToken
201	ForgeBatch                  []RollupEventForgeBatch
202	UpdateForgeL1L2BatchTimeout []RollupEventUpdateForgeL1L2BatchTimeout
203	UpdateFeeAddToken           []RollupEventUpdateFeeAddToken
204	WithdrawEvent               []RollupEventWithdrawEvent
205}
206
207// NewRollupEvents creates an empty RollupEvents with the slices initialized.
208func NewRollupEvents() RollupEvents {
209	return RollupEvents{
210		L1UserTx:                    make([]RollupEventL1UserTx, 0),
211		AddToken:                    make([]RollupEventAddToken, 0),
212		ForgeBatch:                  make([]RollupEventForgeBatch, 0),
213		UpdateForgeL1L2BatchTimeout: make([]RollupEventUpdateForgeL1L2BatchTimeout, 0),
214		UpdateFeeAddToken:           make([]RollupEventUpdateFeeAddToken, 0),
215		WithdrawEvent:               make([]RollupEventWithdrawEvent, 0),
216	}
217}
218
219// RollupForgeBatchArgs are the arguments to the ForgeBatch function in the Rollup Smart Contract
220type RollupForgeBatchArgs struct {
221	NewLastIdx            int64
222	NewStRoot             *big.Int
223	NewExitRoot           *big.Int
224	L1CoordinatorTxs      []common.L1Tx
225	L1CoordinatorTxsAuths [][]byte // Authorization for accountCreations for each L1CoordinatorTx
226	L2TxsData             []common.L2Tx
227	FeeIdxCoordinator     []common.Idx
228	// Circuit selector
229	VerifierIdx uint8
230	L1Batch     bool
231	ProofA      [2]*big.Int
232	ProofB      [2][2]*big.Int
233	ProofC      [2]*big.Int
234}
235
236// RollupForgeBatchArgsAux are the arguments to the ForgeBatch function in the Rollup Smart Contract
237type RollupForgeBatchArgsAux struct {
238	NewLastIdx             *big.Int
239	NewStRoot              *big.Int
240	NewExitRoot            *big.Int
241	EncodedL1CoordinatorTx []byte
242	L2TxsData              []byte
243	FeeIdxCoordinator      []byte
244	// Circuit selector
245	VerifierIdx uint8
246	L1Batch     bool
247	ProofA      [2]*big.Int
248	ProofB      [2][2]*big.Int
249	ProofC      [2]*big.Int
250}
251
252// RollupInterface is the inteface to to Rollup Smart Contract
253type RollupInterface interface {
254	//
255	// Smart Contract Methods
256	//
257
258	// Public Functions
259
260	RollupForgeBatch(*RollupForgeBatchArgs) (*types.Transaction, error)
261	RollupAddToken(tokenAddress ethCommon.Address, feeAddToken, deadline *big.Int) (*types.Transaction, error)
262
263	RollupWithdrawMerkleProof(babyPubKey *babyjub.PublicKey, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (*types.Transaction, error)
264	RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]*big.Int, tokenID uint32, numExitRoot, idx int64, amount *big.Int, instantWithdraw bool) (*types.Transaction, error)
265
266	RollupL1UserTxERC20ETH(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error)
267	RollupL1UserTxERC20Permit(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error)
268
269	// Governance Public Functions
270	RollupUpdateForgeL1L2BatchTimeout(newForgeL1L2BatchTimeout int64) (*types.Transaction, error)
271	RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (*types.Transaction, error)
272
273	// Viewers
274	RollupRegisterTokensCount() (*big.Int, error)
275
276	//
277	// Smart Contract Status
278	//
279
280	RollupConstants() (*RollupPublicConstants, error)
281	RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error)
282	RollupForgeBatchArgs(ethCommon.Hash) (*RollupForgeBatchArgs, *ethCommon.Address, error)
283}
284
285//
286// Implementation
287//
288
289// RollupClient is the implementation of the interface to the Rollup Smart Contract in ethereum.
290type RollupClient struct {
291	client      *EthereumClient
292	address     ethCommon.Address
293	tokenHEZ    TokenConfig
294	hermez      *Hermez.Hermez
295	contractAbi abi.ABI
296}
297
298// NewRollupClient creates a new RollupClient
299func NewRollupClient(client *EthereumClient, address ethCommon.Address, tokenHEZ TokenConfig) (*RollupClient, error) {
300	contractAbi, err := abi.JSON(strings.NewReader(string(Hermez.HermezABI)))
301	if err != nil {
302		return nil, err
303	}
304	hermez, err := Hermez.NewHermez(address, client.Client())
305	if err != nil {
306		return nil, err
307	}
308	return &RollupClient{
309		client:      client,
310		address:     address,
311		tokenHEZ:    tokenHEZ,
312		hermez:      hermez,
313		contractAbi: contractAbi,
314	}, nil
315}
316
317// RollupForgeBatch is the interface to call the smart contract function
318func (c *RollupClient) RollupForgeBatch(args *RollupForgeBatchArgs) (tx *types.Transaction, err error) {
319	if tx, err = c.client.CallAuth(
320		1000000, //nolint:gomnd
321		func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
322			rollupConst, err := c.RollupConstants()
323			if err != nil {
324				return nil, err
325			}
326			nLevels := rollupConst.Verifiers[args.VerifierIdx].NLevels
327			lenBytes := nLevels / 8 //nolint:gomnd
328			newLastIdx := big.NewInt(int64(args.NewLastIdx))
329			var l1CoordinatorBytes []byte
330			for i := 0; i < len(args.L1CoordinatorTxs); i++ {
331				l1 := args.L1CoordinatorTxs[i]
332				bytesl1, err := l1.BytesCoordinatorTx(args.L1CoordinatorTxsAuths[i])
333				if err != nil {
334					return nil, err
335				}
336				l1CoordinatorBytes = append(l1CoordinatorBytes, bytesl1[:]...)
337			}
338			var l2DataBytes []byte
339			for i := 0; i < len(args.L2TxsData); i++ {
340				l2 := args.L2TxsData[i]
341				bytesl2, err := l2.Bytes(int(nLevels))
342				if err != nil {
343					return nil, err
344				}
345				l2DataBytes = append(l2DataBytes, bytesl2[:]...)
346			}
347			var feeIdxCoordinator []byte
348			if len(args.FeeIdxCoordinator) > RollupConstMaxFeeIdxCoordinator {
349				return nil, fmt.Errorf("len(args.FeeIdxCoordinator) > %v",
350					RollupConstMaxFeeIdxCoordinator)
351			}
352			for i := 0; i < RollupConstMaxFeeIdxCoordinator; i++ {
353				feeIdx := common.Idx(0)
354				if i < len(args.FeeIdxCoordinator) {
355					feeIdx = args.FeeIdxCoordinator[i]
356				}
357				bytesFeeIdx, err := feeIdx.Bytes()
358				if err != nil {
359					return nil, err
360				}
361				feeIdxCoordinator = append(feeIdxCoordinator, bytesFeeIdx[len(bytesFeeIdx)-int(lenBytes):]...)
362			}
363			return c.hermez.ForgeBatch(auth, newLastIdx, args.NewStRoot, args.NewExitRoot, l1CoordinatorBytes, l2DataBytes, feeIdxCoordinator, args.VerifierIdx, args.L1Batch, args.ProofA, args.ProofB, args.ProofC)
364		},
365	); err != nil {
366		return nil, fmt.Errorf("Failed forge batch: %w", err)
367	}
368	return tx, nil
369}
370
371// RollupAddToken is the interface to call the smart contract function.
372// `feeAddToken` is the amount of HEZ tokens that will be paid to add the
373// token.  `feeAddToken` must match the public value of the smart contract.
374func (c *RollupClient) RollupAddToken(tokenAddress ethCommon.Address, feeAddToken, deadline *big.Int) (tx *types.Transaction, err error) {
375	if tx, err = c.client.CallAuth(
376		0,
377		func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
378			tokenHEZcontract, err := HEZ.NewHEZ(c.tokenHEZ.Address, ec)
379			if err != nil {
380				return nil, err
381			}
382			owner := c.client.account.Address
383			spender := c.address
384			nonce, err := tokenHEZcontract.Nonces(nil, owner)
385			tokenname := c.tokenHEZ.Name
386			tokenAddr := c.tokenHEZ.Address
387			chainid, _ := c.client.client.ChainID(context.Background())
388			digest, _ := createPermitDigest(tokenAddr, owner, spender, chainid, feeAddToken, nonce, deadline, tokenname)
389			signature, _ := c.client.ks.SignHash(*c.client.account, digest)
390			permit := createPermit(owner, spender, feeAddToken, deadline, digest, signature)
391
392			return c.hermez.AddToken(auth, tokenAddress, permit)
393		},
394	); err != nil {
395		return nil, fmt.Errorf("Failed add Token %w", err)
396	}
397	return tx, nil
398}
399
400// RollupWithdrawMerkleProof is the interface to call the smart contract function
401func (c *RollupClient) RollupWithdrawMerkleProof(fromBJJ *babyjub.PublicKey, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (tx *types.Transaction, err error) {
402	if tx, err = c.client.CallAuth(
403		0,
404		func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
405			pkCompL := fromBJJ.Compress()
406			pkCompB := common.SwapEndianness(pkCompL[:])
407			babyPubKey := new(big.Int).SetBytes(pkCompB)
408			numExitRootB := big.NewInt(numExitRoot)
409			idxBig := big.NewInt(idx)
410			return c.hermez.WithdrawMerkleProof(auth, tokenID, amount, babyPubKey, numExitRootB, siblings, idxBig, instantWithdraw)
411		},
412	); err != nil {
413		return nil, fmt.Errorf("Failed update WithdrawMerkleProof: %w", err)
414	}
415	return tx, nil
416}
417
418// RollupWithdrawCircuit is the interface to call the smart contract function
419func (c *RollupClient) RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]*big.Int, tokenID uint32, numExitRoot, idx int64, amount *big.Int, instantWithdraw bool) (*types.Transaction, error) {
420	log.Error("TODO")
421	return nil, errTODO
422}
423
424// RollupL1UserTxERC20ETH is the interface to call the smart contract function
425func (c *RollupClient) RollupL1UserTxERC20ETH(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (tx *types.Transaction, err error) {
426	if tx, err = c.client.CallAuth(
427		0,
428		func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
429			pkCompL := fromBJJ.Compress()
430			pkCompB := common.SwapEndianness(pkCompL[:])
431			babyPubKey := new(big.Int).SetBytes(pkCompB)
432			fromIdxBig := big.NewInt(fromIdx)
433			toIdxBig := big.NewInt(toIdx)
434			tokenIDBig := uint32(tokenID)
435			loadAmountF, err := common.NewFloat16(loadAmount)
436			if err != nil {
437				return nil, err
438			}
439			amountF, err := common.NewFloat16(amount)
440			if err != nil {
441				return nil, err
442			}
443			if tokenID == 0 {
444				auth.Value = loadAmount
445			}
446			var permit []byte
447			return c.hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig, uint16(loadAmountF), uint16(amountF), tokenIDBig, toIdxBig, permit)
448		},
449	); err != nil {
450		return nil, fmt.Errorf("Failed add L1 Tx ERC20/ETH: %w", err)
451	}
452	return tx, nil
453}
454
455// RollupL1UserTxERC20Permit is the interface to call the smart contract function
456func (c *RollupClient) RollupL1UserTxERC20Permit(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error) {
457	if tx, err = c.client.CallAuth(
458		0,
459		func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
460			pkCompL := fromBJJ.Compress()
461			pkCompB := common.SwapEndianness(pkCompL[:])
462			babyPubKey := new(big.Int).SetBytes(pkCompB)
463			fromIdxBig := big.NewInt(fromIdx)
464			toIdxBig := big.NewInt(toIdx)
465			tokenIDBig := uint32(tokenID)
466			loadAmountF, err := common.NewFloat16(loadAmount)
467			if err != nil {
468				return nil, err
469			}
470			amountF, err := common.NewFloat16(amount)
471			if err != nil {
472				return nil, err
473			}
474			if tokenID == 0 {
475				auth.Value = loadAmount
476			}
477			tokenHEZcontract, err := HEZ.NewHEZ(c.tokenHEZ.Address, ec)
478			if err != nil {
479				return nil, err
480			}
481			owner := c.client.account.Address
482			spender := c.address
483			nonce, err := tokenHEZcontract.Nonces(nil, owner)
484			tokenname := c.tokenHEZ.Name
485			tokenAddr := c.tokenHEZ.Address
486			chainid, _ := c.client.client.ChainID(context.Background())
487			digest, _ := createPermitDigest(tokenAddr, owner, spender, chainid, amount, nonce, deadline, tokenname)
488			signature, _ := c.client.ks.SignHash(*c.client.account, digest)
489			permit := createPermit(owner, spender, amount, deadline, digest, signature)
490			return c.hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig, uint16(loadAmountF), uint16(amountF), tokenIDBig, toIdxBig, permit)
491		},
492	); err != nil {
493		return nil, fmt.Errorf("Failed add L1 Tx ERC20Permit: %w", err)
494	}
495	return tx, nil
496}
497
498// RollupRegisterTokensCount is the interface to call the smart contract function
499func (c *RollupClient) RollupRegisterTokensCount() (*big.Int, error) {
500	var registerTokensCount *big.Int
501	if err := c.client.Call(func(ec *ethclient.Client) error {
502		hermez, err := Hermez.NewHermez(c.address, ec)
503		if err != nil {
504			return err
505		}
506		registerTokensCount, err = hermez.RegisterTokensCount(nil)
507		return err
508	}); err != nil {
509		return nil, err
510	}
511	return registerTokensCount, nil
512}
513
514// RollupUpdateForgeL1L2BatchTimeout is the interface to call the smart contract function
515func (c *RollupClient) RollupUpdateForgeL1L2BatchTimeout(newForgeL1L2BatchTimeout int64) (tx *types.Transaction, err error) {
516	if tx, err = c.client.CallAuth(
517		0,
518		func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
519			return c.hermez.UpdateForgeL1L2BatchTimeout(auth, uint8(newForgeL1L2BatchTimeout))
520		},
521	); err != nil {
522		return nil, fmt.Errorf("Failed update ForgeL1L2BatchTimeout: %w", err)
523	}
524	return tx, nil
525}
526
527// RollupUpdateFeeAddToken is the interface to call the smart contract function
528func (c *RollupClient) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (tx *types.Transaction, err error) {
529	if tx, err = c.client.CallAuth(
530		0,
531		func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
532			return c.hermez.UpdateFeeAddToken(auth, newFeeAddToken)
533		},
534	); err != nil {
535		return nil, fmt.Errorf("Failed update FeeAddToken: %w", err)
536	}
537	return tx, nil
538}
539
540// RollupConstants returns the Constants of the Rollup Smart Contract
541func (c *RollupClient) RollupConstants() (rollupConstants *RollupPublicConstants, err error) {
542	rollupConstants = new(RollupPublicConstants)
543	if err := c.client.Call(func(ec *ethclient.Client) error {
544		absoluteMaxL1L2BatchTimeout, err := c.hermez.ABSOLUTEMAXL1L2BATCHTIMEOUT(nil)
545		if err != nil {
546			return err
547		}
548		rollupConstants.AbsoluteMaxL1L2BatchTimeout = int64(absoluteMaxL1L2BatchTimeout)
549		rollupConstants.TokenHEZ, err = c.hermez.TokenHEZ(nil)
550		if err != nil {
551			return err
552		}
553		for i := int64(0); i < int64(LenVerifiers); i++ {
554			var newRollupVerifier RollupVerifierStruct
555			rollupVerifier, err := c.hermez.RollupVerifiers(nil, big.NewInt(i))
556			if err != nil {
557				return err
558			}
559			newRollupVerifier.MaxTx = rollupVerifier.MaxTx.Int64()
560			newRollupVerifier.NLevels = rollupVerifier.NLevels.Int64()
561			rollupConstants.Verifiers = append(rollupConstants.Verifiers, newRollupVerifier)
562		}
563		rollupConstants.HermezAuctionContract, err = c.hermez.HermezAuctionContract(nil)
564		if err != nil {
565			return err
566		}
567		rollupConstants.HermezGovernanceDAOAddress, err = c.hermez.HermezGovernanceDAOAddress(nil)
568		if err != nil {
569			return err
570		}
571		rollupConstants.SafetyAddress, err = c.hermez.SafetyAddress(nil)
572		if err != nil {
573			return err
574		}
575		rollupConstants.WithdrawDelayerContract, err = c.hermez.WithdrawDelayerContract(nil)
576		return err
577	}); err != nil {
578		return nil, err
579	}
580	return rollupConstants, nil
581}
582
583var (
584	logHermezL1UserTxEvent               = crypto.Keccak256Hash([]byte("L1UserTxEvent(uint64,uint8,bytes)"))
585	logHermezAddToken                    = crypto.Keccak256Hash([]byte("AddToken(address,uint32)"))
586	logHermezForgeBatch                  = crypto.Keccak256Hash([]byte("ForgeBatch(uint64)"))
587	logHermezUpdateForgeL1L2BatchTimeout = crypto.Keccak256Hash([]byte("UpdateForgeL1L2BatchTimeout(uint8)"))
588	logHermezUpdateFeeAddToken           = crypto.Keccak256Hash([]byte("UpdateFeeAddToken(uint256)"))
589	logHermezWithdrawEvent               = crypto.Keccak256Hash([]byte("WithdrawEvent(uint48,uint48,bool)"))
590)
591
592// RollupEventsByBlock returns the events in a block that happened in the Rollup Smart Contract
593func (c *RollupClient) RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error) {
594	var rollupEvents RollupEvents
595	var blockHash ethCommon.Hash
596
597	query := ethereum.FilterQuery{
598		FromBlock: big.NewInt(blockNum),
599		ToBlock:   big.NewInt(blockNum),
600		Addresses: []ethCommon.Address{
601			c.address,
602		},
603		BlockHash: nil,
604		Topics:    [][]ethCommon.Hash{},
605	}
606	logs, err := c.client.client.FilterLogs(context.Background(), query)
607	if err != nil {
608		return nil, nil, err
609	}
610	if len(logs) > 0 {
611		blockHash = logs[0].BlockHash
612	}
613	for _, vLog := range logs {
614		if vLog.BlockHash != blockHash {
615			return nil, nil, ErrBlockHashMismatchEvent
616		}
617		switch vLog.Topics[0] {
618		case logHermezL1UserTxEvent:
619			var L1UserTxAux RollupEventL1UserTxAux
620			var L1UserTx RollupEventL1UserTx
621			err := c.contractAbi.Unpack(&L1UserTxAux, "L1UserTxEvent", vLog.Data)
622			if err != nil {
623				return nil, nil, err
624			}
625			L1Tx, err := common.L1UserTxFromBytes(L1UserTxAux.L1UserTx)
626			if err != nil {
627				return nil, nil, err
628			}
629			toForgeL1TxsNum := new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
630			L1Tx.ToForgeL1TxsNum = &toForgeL1TxsNum
631			L1Tx.Position = int(new(big.Int).SetBytes(vLog.Topics[2][:]).Int64())
632			L1Tx.UserOrigin = true
633			L1UserTx.L1UserTx = *L1Tx
634			rollupEvents.L1UserTx = append(rollupEvents.L1UserTx, L1UserTx)
635		case logHermezAddToken:
636			var addToken RollupEventAddToken
637			err := c.contractAbi.Unpack(&addToken, "AddToken", vLog.Data)
638			if err != nil {
639				return nil, nil, err
640			}
641			addToken.TokenAddress = ethCommon.BytesToAddress(vLog.Topics[1].Bytes())
642			rollupEvents.AddToken = append(rollupEvents.AddToken, addToken)
643		case logHermezForgeBatch:
644			var forgeBatch RollupEventForgeBatch
645			forgeBatch.BatchNum = new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
646			forgeBatch.EthTxHash = vLog.TxHash
647			// forgeBatch.Sender = vLog.Address
648			rollupEvents.ForgeBatch = append(rollupEvents.ForgeBatch, forgeBatch)
649		case logHermezUpdateForgeL1L2BatchTimeout:
650			var updateForgeL1L2BatchTimeout struct {
651				NewForgeL1L2BatchTimeout uint8
652			}
653			err := c.contractAbi.Unpack(&updateForgeL1L2BatchTimeout, "UpdateForgeL1L2BatchTimeout", vLog.Data)
654			if err != nil {
655				return nil, nil, err
656			}
657			rollupEvents.UpdateForgeL1L2BatchTimeout = append(rollupEvents.UpdateForgeL1L2BatchTimeout,
658				RollupEventUpdateForgeL1L2BatchTimeout{
659					NewForgeL1L2BatchTimeout: int64(updateForgeL1L2BatchTimeout.NewForgeL1L2BatchTimeout),
660				})
661		case logHermezUpdateFeeAddToken:
662			var updateFeeAddToken RollupEventUpdateFeeAddToken
663			err := c.contractAbi.Unpack(&updateFeeAddToken, "UpdateFeeAddToken", vLog.Data)
664			if err != nil {
665				return nil, nil, err
666			}
667			rollupEvents.UpdateFeeAddToken = append(rollupEvents.UpdateFeeAddToken, updateFeeAddToken)
668		case logHermezWithdrawEvent:
669			var withdraw RollupEventWithdrawEvent
670			withdraw.Idx = new(big.Int).SetBytes(vLog.Topics[1][:]).Uint64()
671			withdraw.NumExitRoot = new(big.Int).SetBytes(vLog.Topics[2][:]).Uint64()
672			instantWithdraw := new(big.Int).SetBytes(vLog.Topics[3][:]).Uint64()
673			if instantWithdraw == 1 {
674				withdraw.InstantWithdraw = true
675			}
676			rollupEvents.WithdrawEvent = append(rollupEvents.WithdrawEvent, withdraw)
677		}
678	}
679	return &rollupEvents, &blockHash, nil
680}
681
682// RollupForgeBatchArgs returns the arguments used in a ForgeBatch call in the
683// Rollup Smart Contract in the given transaction, and the sender address.
684func (c *RollupClient) RollupForgeBatchArgs(ethTxHash ethCommon.Hash) (*RollupForgeBatchArgs, *ethCommon.Address, error) {
685	tx, _, err := c.client.client.TransactionByHash(context.Background(), ethTxHash)
686	if err != nil {
687		return nil, nil, err
688	}
689	txData := tx.Data()
690	method, err := c.contractAbi.MethodById(txData[:4])
691	if err != nil {
692		return nil, nil, err
693	}
694	receipt, err := c.client.client.TransactionReceipt(context.Background(), ethTxHash)
695	if err != nil {
696		return nil, nil, err
697	}
698	sender, err := c.client.client.TransactionSender(context.Background(), tx, receipt.Logs[0].BlockHash, receipt.Logs[0].Index)
699	if err != nil {
700		return nil, nil, err
701	}
702	var aux RollupForgeBatchArgsAux
703	if err := method.Inputs.Unpack(&aux, txData[4:]); err != nil {
704		return nil, nil, err
705	}
706	rollupForgeBatchArgs := RollupForgeBatchArgs{
707		L1Batch:               aux.L1Batch,
708		NewExitRoot:           aux.NewExitRoot,
709		NewLastIdx:            aux.NewLastIdx.Int64(),
710		NewStRoot:             aux.NewStRoot,
711		ProofA:                aux.ProofA,
712		ProofB:                aux.ProofB,
713		ProofC:                aux.ProofC,
714		VerifierIdx:           aux.VerifierIdx,
715		L1CoordinatorTxs:      []common.L1Tx{},
716		L1CoordinatorTxsAuths: [][]byte{},
717		L2TxsData:             []common.L2Tx{},
718		FeeIdxCoordinator:     []common.Idx{},
719	}
720	numTxsL1 := len(aux.EncodedL1CoordinatorTx) / common.L1CoordinatorTxBytesLen
721	for i := 0; i < numTxsL1; i++ {
722		bytesL1Coordinator := aux.EncodedL1CoordinatorTx[i*common.L1CoordinatorTxBytesLen : (i+1)*common.L1CoordinatorTxBytesLen]
723		var signature []byte
724		v := bytesL1Coordinator[0]
725		s := bytesL1Coordinator[1:33]
726		r := bytesL1Coordinator[33:65]
727		signature = append(signature, r[:]...)
728		signature = append(signature, s[:]...)
729		signature = append(signature, v)
730		l1Tx, err := common.L1CoordinatorTxFromBytes(bytesL1Coordinator)
731		if err != nil {
732			return nil, nil, err
733		}
734		rollupForgeBatchArgs.L1CoordinatorTxs = append(rollupForgeBatchArgs.L1CoordinatorTxs, *l1Tx)
735		rollupForgeBatchArgs.L1CoordinatorTxsAuths = append(rollupForgeBatchArgs.L1CoordinatorTxsAuths, signature)
736	}
737	rollupConsts, err := c.RollupConstants()
738	if err != nil {
739		return nil, nil, err
740	}
741	nLevels := rollupConsts.Verifiers[rollupForgeBatchArgs.VerifierIdx].NLevels
742	lenL2TxsBytes := int((nLevels/8)*2 + 2 + 1)
743	numTxsL2 := len(aux.L2TxsData) / lenL2TxsBytes
744	for i := 0; i < numTxsL2; i++ {
745		l2Tx, err := common.L2TxFromBytes(aux.L2TxsData[i*lenL2TxsBytes:(i+1)*lenL2TxsBytes], int(nLevels))
746		if err != nil {
747			return nil, nil, err
748		}
749		rollupForgeBatchArgs.L2TxsData = append(rollupForgeBatchArgs.L2TxsData, *l2Tx)
750	}
751	lenFeeIdxCoordinatorBytes := int(nLevels / 8) //nolint:gomnd
752	numFeeIdxCoordinator := len(aux.FeeIdxCoordinator) / lenFeeIdxCoordinatorBytes
753	for i := 0; i < numFeeIdxCoordinator; i++ {
754		var paddedFeeIdx [6]byte
755		// TODO: This check is not necessary: the first case will always work.  Test it before removing the if.
756		if lenFeeIdxCoordinatorBytes < common.IdxBytesLen {
757			copy(paddedFeeIdx[6-lenFeeIdxCoordinatorBytes:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
758		} else {
759			copy(paddedFeeIdx[:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
760		}
761		feeIdxCoordinator, err := common.IdxFromBytes(paddedFeeIdx[:])
762		if err != nil {
763			return nil, nil, err
764		}
765		if feeIdxCoordinator != common.Idx(0) {
766			rollupForgeBatchArgs.FeeIdxCoordinator = append(rollupForgeBatchArgs.FeeIdxCoordinator, feeIdxCoordinator)
767		}
768	}
769	return &rollupForgeBatchArgs, &sender, nil
770}