arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/eth/rollup.go
eth/rollup.goRaw
  1package eth
  2
  3import (
  4	"math/big"
  5
  6	ethCommon "github.com/ethereum/go-ethereum/common"
  7	"github.com/ethereum/go-ethereum/core/types"
  8	"github.com/ethereum/go-ethereum/ethclient"
  9	"github.com/hermeznetwork/hermez-node/common"
 10	Hermez "github.com/hermeznetwork/hermez-node/eth/contracts/hermez"
 11	"github.com/hermeznetwork/hermez-node/log"
 12	"github.com/iden3/go-iden3-crypto/babyjub"
 13)
 14
 15const (
 16	// FeeIdxCoordinatorLen is the number of tokens the coordinator can use
 17	// to collect fees (determines the number of tokens that the
 18	// coordinator can collect fees from).  This value is determined by the
 19	// circuit.
 20	FeeIdxCoordinatorLen = 64
 21)
 22
 23// RollupConstants are the constants of the Rollup Smart Contract
 24type RollupConstants struct {
 25	// Maxim Deposit allowed
 26	MaxAmountDeposit *big.Int
 27	MaxAmountL2      *big.Int
 28	MaxTokens        int64
 29	// maximum L1 transactions allowed to be queued for a batch
 30	MaxL1Tx int
 31	// maximum L1 user transactions allowed to be queued for a batch
 32	MaxL1UserTx        int
 33	Rfield             *big.Int
 34	L1CoordinatorBytes int
 35	L1UserBytes        int
 36	L2Bytes            int
 37	MaxTxVerifiers     []int
 38	TokenHEZ           ethCommon.Address
 39	// Only test
 40	GovernanceAddress ethCommon.Address
 41	// Only test
 42	SafetyBot ethCommon.Address
 43	// Only test
 44	ConsensusContract ethCommon.Address
 45	// Only test
 46	WithdrawalContract ethCommon.Address
 47	ReservedIDx        uint32
 48	LastIDx            uint32
 49	ExitIDx            uint32
 50	NoLimitToken       int
 51	NumBuckets         int
 52	MaxWDelay          int64
 53}
 54
 55// RollupVariables are the variables of the Rollup Smart Contract
 56type RollupVariables struct {
 57	FeeAddToken    *big.Int
 58	ForgeL1Timeout int64
 59}
 60
 61// QueueStruct is the queue of L1Txs for a batch
 62//nolint:structcheck
 63type QueueStruct struct {
 64	L1TxQueue    []common.L1Tx
 65	TotalL1TxFee *big.Int
 66}
 67
 68// NewQueueStruct creates a new clear QueueStruct.
 69func NewQueueStruct() *QueueStruct {
 70	return &QueueStruct{
 71		L1TxQueue:    make([]common.L1Tx, 0),
 72		TotalL1TxFee: big.NewInt(0),
 73	}
 74}
 75
 76// RollupState represents the state of the Rollup in the Smart Contract
 77//nolint:structcheck,unused
 78type RollupState struct {
 79	StateRoot              *big.Int
 80	ExitRoots              []*big.Int
 81	ExitNullifierMap       map[[256 / 8]byte]bool
 82	TokenList              []ethCommon.Address
 83	TokenMap               map[ethCommon.Address]bool
 84	MapL1TxQueue           map[int64]*QueueStruct
 85	LastL1L2Batch          int64
 86	CurrentToForgeL1TxsNum int64
 87	LastToForgeL1TxsNum    int64
 88	CurrentIdx             int64
 89}
 90
 91// RollupEventL1UserTx is an event of the Rollup Smart Contract
 92type RollupEventL1UserTx struct {
 93	L1Tx            common.L1Tx
 94	ToForgeL1TxsNum int64 // QueueIndex       *big.Int
 95	Position        int   // TransactionIndex *big.Int
 96}
 97
 98// RollupEventAddToken is an event of the Rollup Smart Contract
 99type RollupEventAddToken struct {
100	Address ethCommon.Address
101	TokenID uint32
102}
103
104// RollupEventForgeBatch is an event of the Rollup Smart Contract
105type RollupEventForgeBatch struct {
106	BatchNum  int64
107	EthTxHash ethCommon.Hash
108}
109
110// RollupEventUpdateForgeL1L2BatchTimeout is an event of the Rollup Smart Contract
111type RollupEventUpdateForgeL1L2BatchTimeout struct {
112	ForgeL1Timeout *big.Int
113}
114
115// RollupEventUpdateFeeAddToken is an event of the Rollup Smart Contract
116type RollupEventUpdateFeeAddToken struct {
117	FeeAddToken *big.Int
118}
119
120// RollupEventWithdrawEvent is an event of the Rollup Smart Contract
121type RollupEventWithdrawEvent struct {
122	Idx             *big.Int
123	NumExitRoot     *big.Int
124	InstantWithdraw bool
125}
126
127// RollupEvents is the list of events in a block of the Rollup Smart Contract
128type RollupEvents struct { //nolint:structcheck
129	L1UserTx                    []RollupEventL1UserTx
130	AddToken                    []RollupEventAddToken
131	ForgeBatch                  []RollupEventForgeBatch
132	UpdateForgeL1L2BatchTimeout []RollupEventUpdateForgeL1L2BatchTimeout
133	UpdateFeeAddToken           []RollupEventUpdateFeeAddToken
134	WithdrawEvent               []RollupEventWithdrawEvent
135}
136
137// NewRollupEvents creates an empty RollupEvents with the slices initialized.
138func NewRollupEvents() RollupEvents {
139	return RollupEvents{
140		L1UserTx:                    make([]RollupEventL1UserTx, 0),
141		AddToken:                    make([]RollupEventAddToken, 0),
142		ForgeBatch:                  make([]RollupEventForgeBatch, 0),
143		UpdateForgeL1L2BatchTimeout: make([]RollupEventUpdateForgeL1L2BatchTimeout, 0),
144		UpdateFeeAddToken:           make([]RollupEventUpdateFeeAddToken, 0),
145		WithdrawEvent:               make([]RollupEventWithdrawEvent, 0),
146	}
147}
148
149// RollupForgeBatchArgs are the arguments to the ForgeBatch function in the Rollup Smart Contract
150//nolint:structcheck,unused
151type RollupForgeBatchArgs struct {
152	ProofA                [2]*big.Int
153	ProofB                [2][2]*big.Int
154	ProofC                [2]*big.Int
155	NewLastIdx            int64
156	NewStRoot             *big.Int
157	NewExitRoot           *big.Int
158	L1CoordinatorTxs      []*common.L1Tx
159	L1CoordinatorTxsAuths [][]byte // Authorization for accountCreations for each L1CoordinatorTxs
160	L2Txs                 []*common.L2Tx
161	FeeIdxCoordinator     []common.Idx
162	// Circuit selector
163	VerifierIdx int64
164	L1Batch     bool
165}
166
167// RollupInterface is the inteface to to Rollup Smart Contract
168type RollupInterface interface {
169	//
170	// Smart Contract Methods
171	//
172
173	// Public Functions
174
175	RollupForgeBatch(*RollupForgeBatchArgs) (*types.Transaction, error)
176	RollupAddToken(tokenAddress ethCommon.Address) (*types.Transaction, error)
177	RollupWithdraw(tokenID int64, balance *big.Int, babyPubKey *babyjub.PublicKey,
178		numExitRoot int64, siblings []*big.Int, idx int64, instantWithdraw bool) (*types.Transaction, error)
179	RollupForceExit(fromIdx int64, amountF common.Float16, tokenID int64) (*types.Transaction, error)
180	RollupForceTransfer(fromIdx int64, amountF common.Float16, tokenID, toIdx int64) (*types.Transaction, error)
181	RollupCreateAccountDepositTransfer(babyPubKey babyjub.PublicKey,
182		loadAmountF, amountF common.Float16, tokenID int64, toIdx int64) (*types.Transaction, error)
183	RollupDepositTransfer(fromIdx int64, loadAmountF, amountF common.Float16,
184		tokenID int64, toIdx int64) (*types.Transaction, error)
185	RollupDeposit(fromIdx int64, loadAmountF common.Float16, tokenID int64) (*types.Transaction, error)
186	RollupCreateAccountDepositFromRelayer(accountCreationAuthSig []byte,
187		babyPubKey babyjub.PublicKey, loadAmountF common.Float16) (*types.Transaction, error)
188	RollupCreateAccountDeposit(babyPubKey babyjub.PublicKey, loadAmountF common.Float16,
189		tokenID int64) (*types.Transaction, error)
190
191	RollupGetCurrentTokens() (*big.Int, error)
192	// RollupGetTokenAddress(tokenID int64) (*ethCommon.Address, error)
193	// RollupGetL1TxFromQueue(queue int64, position int64) ([]byte, error)
194	// RollupGetQueue(queue int64) ([]byte, error)
195
196	// Governance Public Functions
197	RollupUpdateForgeL1L2BatchTimeout(newForgeL1Timeout int64) (*types.Transaction, error)
198	RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (*types.Transaction, error)
199
200	//
201	// Smart Contract Status
202	//
203
204	RollupConstants() (*RollupConstants, error)
205	RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error)
206	RollupForgeBatchArgs(ethCommon.Hash) (*RollupForgeBatchArgs, error)
207}
208
209//
210// Implementation
211//
212
213// RollupClient is the implementation of the interface to the Rollup Smart Contract in ethereum.
214type RollupClient struct {
215	client  *EthereumClient
216	address ethCommon.Address
217}
218
219// NewRollupClient creates a new RollupClient
220func NewRollupClient(client *EthereumClient, address ethCommon.Address) *RollupClient {
221	return &RollupClient{
222		client:  client,
223		address: address,
224	}
225}
226
227// RollupForgeBatch is the interface to call the smart contract function
228func (c *RollupClient) RollupForgeBatch(args *RollupForgeBatchArgs) (*types.Transaction, error) {
229	log.Error("TODO")
230	return nil, errTODO
231}
232
233// RollupAddToken is the interface to call the smart contract function
234func (c *RollupClient) RollupAddToken(tokenAddress ethCommon.Address) (*types.Transaction, error) {
235	log.Error("TODO")
236	return nil, errTODO
237}
238
239// RollupWithdrawSNARK is the interface to call the smart contract function
240// func (c *RollupClient) RollupWithdrawSNARK() (*types.Transaction, error) { // TODO (Not defined in Hermez.sol)
241// 	return nil, errTODO
242// }
243
244// RollupWithdraw is the interface to call the smart contract function
245func (c *RollupClient) RollupWithdraw(tokenID int64, balance *big.Int, babyPubKey *babyjub.PublicKey, numExitRoot int64, siblings []*big.Int, idx int64, instantWithdraw bool) (*types.Transaction, error) {
246	log.Error("TODO")
247	return nil, errTODO
248}
249
250// RollupForceExit is the interface to call the smart contract function
251func (c *RollupClient) RollupForceExit(fromIdx int64, amountF common.Float16, tokenID int64) (*types.Transaction, error) {
252	log.Error("TODO")
253	return nil, errTODO
254}
255
256// RollupForceTransfer is the interface to call the smart contract function
257func (c *RollupClient) RollupForceTransfer(fromIdx int64, amountF common.Float16, tokenID, toIdx int64) (*types.Transaction, error) {
258	log.Error("TODO")
259	return nil, errTODO
260}
261
262// RollupCreateAccountDepositTransfer is the interface to call the smart contract function
263func (c *RollupClient) RollupCreateAccountDepositTransfer(babyPubKey babyjub.PublicKey, loadAmountF, amountF common.Float16, tokenID int64, toIdx int64) (*types.Transaction, error) {
264	log.Error("TODO")
265	return nil, errTODO
266}
267
268// RollupDepositTransfer is the interface to call the smart contract function
269func (c *RollupClient) RollupDepositTransfer(fromIdx int64, loadAmountF, amountF common.Float16, tokenID int64, toIdx int64) (*types.Transaction, error) {
270	log.Error("TODO")
271	return nil, errTODO
272}
273
274// RollupDeposit is the interface to call the smart contract function
275func (c *RollupClient) RollupDeposit(fromIdx int64, loadAmountF common.Float16, tokenID int64) (*types.Transaction, error) {
276	log.Error("TODO")
277	return nil, errTODO
278}
279
280// RollupCreateAccountDepositFromRelayer is the interface to call the smart contract function
281func (c *RollupClient) RollupCreateAccountDepositFromRelayer(accountCreationAuthSig []byte, babyPubKey babyjub.PublicKey, loadAmountF common.Float16) (*types.Transaction, error) {
282	log.Error("TODO")
283	return nil, errTODO
284}
285
286// RollupCreateAccountDeposit is the interface to call the smart contract function
287func (c *RollupClient) RollupCreateAccountDeposit(babyPubKey babyjub.PublicKey, loadAmountF common.Float16, tokenID int64) (*types.Transaction, error) {
288	log.Error("TODO")
289	return nil, errTODO
290}
291
292// RollupGetTokenAddress is the interface to call the smart contract function
293/* func (c *RollupClient) RollupGetTokenAddress(tokenID int64) (*ethCommon.Address, error) {
294	return nil, errTODO
295} */
296
297// RollupGetCurrentTokens is the interface to call the smart contract function
298func (c *RollupClient) RollupGetCurrentTokens() (*big.Int, error) {
299	log.Error("TODO")
300	return nil, errTODO
301}
302
303// RollupGetL1TxFromQueue is the interface to call the smart contract function
304/* func (c *RollupClient) RollupGetL1TxFromQueue(queue int64, position int64) ([]byte, error) {
305	return nil, errTODO
306} */
307
308// RollupGetQueue is the interface to call the smart contract function
309/* func (c *RollupClient) RollupGetQueue(queue int64) ([]byte, error) {
310	return nil, errTODO
311}*/
312
313// RollupUpdateForgeL1L2BatchTimeout is the interface to call the smart contract function
314func (c *RollupClient) RollupUpdateForgeL1L2BatchTimeout(newForgeL1Timeout int64) (*types.Transaction, error) {
315	log.Error("TODO")
316	return nil, errTODO
317}
318
319// RollupUpdateFeeAddToken is the interface to call the smart contract function
320func (c *RollupClient) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (*types.Transaction, error) {
321	log.Error("TODO")
322	return nil, errTODO
323}
324
325// RollupConstants returns the Constants of the Rollup Smart Contract
326func (c *RollupClient) RollupConstants() (*RollupConstants, error) {
327	rollupConstants := new(RollupConstants)
328	if err := c.client.Call(func(ec *ethclient.Client) error {
329		rollup, err := Hermez.NewHermez(c.address, ec)
330		if err != nil {
331			return err
332		}
333		// rollupConstants.GovernanceAddress :=
334		l1CoordinatorBytes, err := rollup.L1COORDINATORBYTES(nil)
335		if err != nil {
336			return err
337		}
338		rollupConstants.L1CoordinatorBytes = int(l1CoordinatorBytes.Int64())
339		l1UserBytes, err := rollup.L1USERBYTES(nil)
340		if err != nil {
341			return err
342		}
343		rollupConstants.L1UserBytes = int(l1UserBytes.Int64())
344		l2Bytes, err := rollup.L2BYTES(nil)
345		if err != nil {
346			return err
347		}
348		rollupConstants.L2Bytes = int(l2Bytes.Int64())
349		rollupConstants.LastIDx, err = rollup.LASTIDX(nil)
350		if err != nil {
351			return err
352		}
353		rollupConstants.MaxAmountDeposit, err = rollup.MAXLOADAMOUNT(nil)
354		if err != nil {
355			return err
356		}
357		rollupConstants.MaxAmountL2, err = rollup.MAXAMOUNT(nil)
358		if err != nil {
359			return err
360		}
361		maxL1Tx, err := rollup.MAXL1TX(nil)
362		if err != nil {
363			return err
364		}
365		rollupConstants.MaxL1Tx = int(maxL1Tx.Int64())
366		maxL1UserTx, err := rollup.MAXL1USERTX(nil)
367		if err != nil {
368			return err
369		}
370		rollupConstants.MaxL1UserTx = int(maxL1UserTx.Int64())
371		maxTokens, err := rollup.MAXTOKENS(nil)
372		if err != nil {
373			return err
374		}
375		rollupConstants.MaxTokens = maxTokens.Int64()
376		maxWDelay, err := rollup.MAXWITHDRAWALDELAY(nil)
377		if err != nil {
378			return err
379		}
380		rollupConstants.MaxWDelay = maxWDelay.Int64()
381		noLimitToken, err := rollup.NOLIMIT(nil)
382		if err != nil {
383			return err
384		}
385		rollupConstants.NoLimitToken = int(noLimitToken.Int64())
386		numBuckets, err := rollup.NUMBUCKETS(nil)
387		if err != nil {
388			return err
389		}
390		rollupConstants.NumBuckets = int(numBuckets.Int64())
391		// rollupConstants.ReservedIDx =
392		rollupConstants.Rfield, err = rollup.RFIELD(nil)
393		if err != nil {
394			return err
395		}
396		// rollupConstants.SafetyBot =
397		// rollupConstants.TokenHEZ =
398		// rollupConstants.WithdrawalContract =
399		return nil
400	}); err != nil {
401		return nil, err
402	}
403	return rollupConstants, nil
404}
405
406// RollupEventsByBlock returns the events in a block that happened in the Rollup Smart Contract
407func (c *RollupClient) RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error) {
408	log.Error("TODO")
409	return nil, nil, errTODO
410}
411
412// RollupForgeBatchArgs returns the arguments used in a ForgeBatch call in the Rollup Smart Contract in the given transaction
413func (c *RollupClient) RollupForgeBatchArgs(ethTxHash ethCommon.Hash) (*RollupForgeBatchArgs, error) {
414	// tx := client.TransactionByHash(ethTxHash) -> types.Transaction
415	// txData := types.Transaction -> Data()
416	// m := abi.MethodById(txData) -> Method
417	// m.Inputs.Unpack(txData) -> Args
418	// client.TransactionReceipt()?
419	log.Error("TODO")
420	return nil, errTODO
421}