diff --git a/common/bid.go b/common/bid.go index ea0c8f8..a661c37 100644 --- a/common/bid.go +++ b/common/bid.go @@ -9,7 +9,7 @@ import ( // Bid is a struct that represents one bid in the PoH type Bid struct { SlotNum SlotNum `meddler:"slot_num"` - ForgerAddr ethCommon.Address `meddler:"forger_addr"` // Coordinator reference BidValue *big.Int `meddler:"bid_value,bigint"` EthBlockNum int64 `meddler:"eth_block_num"` + Bidder ethCommon.Address `meddler:"bidder_addr"` // Coordinator reference } diff --git a/common/coordinator.go b/common/coordinator.go index c49051d..93cdb32 100644 --- a/common/coordinator.go +++ b/common/coordinator.go @@ -7,8 +7,8 @@ import ( // Coordinator represents a Hermez network coordinator who wins an auction for an specific slot // WARNING: this is strongly based on the previous implementation, once the new spec is done, this may change a lot. type Coordinator struct { - Forger ethCommon.Address `meddler:"forger_addr"` // address of the forger - EthBlockNum int64 `meddler:"eth_block_num"` // block in which the coordinator was registered - WithdrawAddr ethCommon.Address `meddler:"withdraw_addr"` // address of the withdraw - URL string `meddler:"url"` // URL of the coordinators API + Bidder ethCommon.Address `meddler:"bidder_addr"` // address of the bidder + Forger ethCommon.Address `meddler:"forger_addr"` // address of the forger + EthBlockNum int64 `meddler:"eth_block_num"` // block in which the coordinator was registered + URL string `meddler:"url"` // URL of the coordinators API } diff --git a/coordinator/coordinator_test.go b/coordinator/coordinator_test.go index 957a4c5..a4fa2ff 100644 --- a/coordinator/coordinator_test.go +++ b/coordinator/coordinator_test.go @@ -168,15 +168,16 @@ func TestCoordinator(t *testing.T) { var timer timer ethClientSetup := test.NewClientSetupExample() - addr := ethCommon.HexToAddress("0xc344E203a046Da13b0B4467EB7B3629D0C99F6E6") - ethClient := test.NewClient(true, &timer, &addr, ethClientSetup) + bidder := ethCommon.HexToAddress("0x6b175474e89094c44da98b954eedeac495271d0f") + forger := ethCommon.HexToAddress("0xc344E203a046Da13b0B4467EB7B3629D0C99F6E6") + ethClient := test.NewClient(true, &timer, &bidder, ethClientSetup) // Bid for slot 2 and 4 - _, err := ethClient.AuctionRegisterCoordinator(addr, "https://foo.bar") + _, err := ethClient.AuctionSetCoordinator(forger, "https://foo.bar") require.Nil(t, err) - _, err = ethClient.AuctionBid(2, big.NewInt(9999), addr) + _, err = ethClient.AuctionBid(2, big.NewInt(9999)) require.Nil(t, err) - _, err = ethClient.AuctionBid(4, big.NewInt(9999), addr) + _, err = ethClient.AuctionBid(4, big.NewInt(9999)) require.Nil(t, err) c := NewCoordinator(conf, hdb, txsel, bb, serverProofs, ethClient) diff --git a/db/historydb/historydb.go b/db/historydb/historydb.go index d0984ac..dd18ec3 100644 --- a/db/historydb/historydb.go +++ b/db/historydb/historydb.go @@ -195,7 +195,7 @@ func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error { // TODO: check the coordinator info return db.BulkInsert( d, - "INSERT INTO bid (slot_num, forger_addr, bid_value, eth_block_num) VALUES %s;", + "INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;", bids[:], ) } @@ -217,7 +217,7 @@ func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error { func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error { return db.BulkInsert( d, - "INSERT INTO coordinator (forger_addr, eth_block_num, withdraw_addr, url) VALUES %s;", + "INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;", coordinators[:], ) } diff --git a/db/migrations/0001.sql b/db/migrations/0001.sql index 5d020f1..af490d7 100644 --- a/db/migrations/0001.sql +++ b/db/migrations/0001.sql @@ -8,11 +8,11 @@ CREATE TABLE block ( ); CREATE TABLE coordinator ( + bidder_addr BYTEA NOT NULL, forger_addr BYTEA NOT NULL, eth_block_num BIGINT NOT NULL REFERENCES block (eth_block_num) ON DELETE CASCADE, - withdraw_addr BYTEA NOT NULL, url VARCHAR(200) NOT NULL, - PRIMARY KEY (forger_addr, eth_block_num) + PRIMARY KEY (bidder_addr, eth_block_num) ); CREATE TABLE batch ( @@ -43,7 +43,7 @@ CREATE TABLE bid ( slot_num BIGINT NOT NULL, bid_value BYTEA NOT NULL, eth_block_num BIGINT NOT NULL REFERENCES block (eth_block_num) ON DELETE CASCADE, - forger_addr BYTEA NOT NULL, -- fake foreign key for coordinator + bidder_addr BYTEA NOT NULL, -- fake foreign key for coordinator PRIMARY KEY (slot_num, bid_value) ); diff --git a/eth/auction_test.go b/eth/auction_test.go index 9e31d69..111abdb 100644 --- a/eth/auction_test.go +++ b/eth/auction_test.go @@ -23,7 +23,8 @@ var genesisBlock = 100 var minBidStr = "10000000000000000000" var URL = "http://localhost:3000" -var newURL = "http://localhost:3002" + +// var newURL = "http://localhost:3002" var BLOCKSPERSLOT = uint8(40) func TestAuctionGetCurrentSlotNumber(t *testing.T) { @@ -43,7 +44,7 @@ func TestAuctionConstants(t *testing.T) { assert.Equal(t, auctionConstants.GenesisBlockNum, int64(genesisBlock)) assert.Equal(t, auctionConstants.HermezRollup, hermezRollupAddressTestConst) assert.Equal(t, auctionConstants.InitialMinimalBidding, INITMINBID) - assert.Equal(t, auctionConstants.TokenHEZ, tokenERC777AddressConst) + assert.Equal(t, auctionConstants.TokenHEZ, tokenHEZAddressConst) } func TestAuctionVariables(t *testing.T) { @@ -244,22 +245,23 @@ func TestAuctionChangeDefaultSlotSetBid(t *testing.T) { } func TestAuctionGetClaimableHEZ(t *testing.T) { - forgerAddress := governanceAddressConst + bidderAddress := governanceAddressConst - claimableHEZ, err := auctionClientTest.AuctionGetClaimableHEZ(forgerAddress) + claimableHEZ, err := auctionClientTest.AuctionGetClaimableHEZ(bidderAddress) require.Nil(t, err) assert.Equal(t, claimableHEZ.Int64(), int64(0)) } func TestAuctionRegisterCoordinator(t *testing.T) { forgerAddress := governanceAddressConst + bidderAddress := governanceAddressConst _, err := auctionClientTest.AuctionSetCoordinator(forgerAddress, URL) require.Nil(t, err) currentBlockNum, _ := auctionClientTest.client.EthCurrentBlock() auctionEvents, _, _ := auctionClientTest.AuctionEventsByBlock(currentBlockNum) assert.Equal(t, forgerAddress, auctionEvents.SetCoordinator[0].ForgerAddress) - assert.Equal(t, forgerAddress, auctionEvents.SetCoordinator[0].BidderAddress) + assert.Equal(t, bidderAddress, auctionEvents.SetCoordinator[0].BidderAddress) assert.Equal(t, URL, auctionEvents.SetCoordinator[0].CoordinatorURL) } @@ -268,13 +270,13 @@ func TestAuctionBid(t *testing.T) { require.Nil(t, err) bidAmount := new(big.Int) bidAmount.SetString("12000000000000000000", 10) - forgerAddress := governanceAddressConst + bidderAddress := governanceAddressConst _, err = auctionClientTest.AuctionBid(currentSlot+4, bidAmount) require.Nil(t, err) currentBlockNum, _ := auctionClientTest.client.EthCurrentBlock() auctionEvents, _, _ := auctionClientTest.AuctionEventsByBlock(currentBlockNum) assert.Equal(t, bidAmount, auctionEvents.NewBid[0].BidAmount) - assert.Equal(t, forgerAddress, auctionEvents.NewBid[0].Bidder) + assert.Equal(t, bidderAddress, auctionEvents.NewBid[0].Bidder) assert.Equal(t, currentSlot+4, auctionEvents.NewBid[0].Slot) } @@ -306,27 +308,27 @@ func TestAuctionMultiBid(t *testing.T) { minBid.SetString("11000000000000000000", 10) budget := new(big.Int) budget.SetString("45200000000000000000", 10) - forgerAddress := governanceAddressConst + bidderAddress := governanceAddressConst _, err = auctionClientTest.AuctionMultiBid(currentSlot+4, currentSlot+10, slotSet, maxBid, minBid, budget) require.Nil(t, err) currentBlockNum, _ := auctionClientTest.client.EthCurrentBlock() auctionEvents, _, _ := auctionClientTest.AuctionEventsByBlock(currentBlockNum) - assert.Equal(t, forgerAddress, auctionEvents.NewBid[0].Bidder) + assert.Equal(t, bidderAddress, auctionEvents.NewBid[0].Bidder) assert.Equal(t, currentSlot+4, auctionEvents.NewBid[0].Slot) - assert.Equal(t, forgerAddress, auctionEvents.NewBid[1].Bidder) + assert.Equal(t, bidderAddress, auctionEvents.NewBid[1].Bidder) assert.Equal(t, currentSlot+6, auctionEvents.NewBid[1].Slot) - assert.Equal(t, forgerAddress, auctionEvents.NewBid[2].Bidder) + assert.Equal(t, bidderAddress, auctionEvents.NewBid[2].Bidder) assert.Equal(t, currentSlot+8, auctionEvents.NewBid[2].Slot) - assert.Equal(t, forgerAddress, auctionEvents.NewBid[3].Bidder) + assert.Equal(t, bidderAddress, auctionEvents.NewBid[3].Bidder) assert.Equal(t, currentSlot+10, auctionEvents.NewBid[3].Slot) } func TestAuctionGetClaimableHEZ2(t *testing.T) { - forgerAddress := governanceAddressConst + bidderAddress := governanceAddressConst amount := new(big.Int) amount.SetString("11000000000000000000", 10) - claimableHEZ, err := auctionClientTest.AuctionGetClaimableHEZ(forgerAddress) + claimableHEZ, err := auctionClientTest.AuctionGetClaimableHEZ(bidderAddress) require.Nil(t, err) assert.Equal(t, claimableHEZ, amount) } @@ -344,7 +346,7 @@ func TestAuctionClaimHEZ(t *testing.T) { } func TestAuctionForge(t *testing.T) { - auctionClientTestHermez, err := NewAuctionClient(ethereumClientHermez, auctionTestAddressConst, tokenERC777AddressConst) + auctionClientTestHermez, err := NewAuctionClient(ethereumClientHermez, auctionTestAddressConst, tokenHEZAddressConst) require.Nil(t, err) slotConst := 4 blockNum := int64(int(BLOCKSPERSLOT)*slotConst + genesisBlock) diff --git a/eth/main_test.go b/eth/main_test.go index 3cd74ce..d13fe19 100644 --- a/eth/main_test.go +++ b/eth/main_test.go @@ -35,8 +35,9 @@ var ( bootCoordinatorAddressConst = ethCommon.HexToAddress(bootCoordinatorAddressStr) tokenERC777AddressStr = "0xf784709d2317D872237C4bC22f867d1BAe2913AB" //nolint:gosec tokenERC777AddressConst = ethCommon.HexToAddress(tokenERC777AddressStr) - tokenERC20AddressStr = "0x3619DbE27d7c1e7E91aA738697Ae7Bc5FC3eACA5" + tokenERC20AddressStr = "0x3619DbE27d7c1e7E91aA738697Ae7Bc5FC3eACA5" //nolint:gosec tokenERC20AddressConst = ethCommon.HexToAddress(tokenERC20AddressStr) + tokenHEZAddressConst = tokenERC777AddressConst hermezRollupAddressStr = "0xEcc0a6dbC0bb4D51E4F84A315a9e5B0438cAD4f0" hermezRollupAddressConst = ethCommon.HexToAddress(hermezRollupAddressStr) wdelayerAddressStr = "0xD6C850aeBFDC46D7F4c207e445cC0d6B0919BDBe" @@ -132,7 +133,7 @@ func TestMain(m *testing.M) { // Controllable Governance Address ethereumClientGov := NewEthereumClient(ethClient, accountGov, ks, nil) - auctionClientTest, err = NewAuctionClient(ethereumClientGov, auctionTestAddressConst, tokenERC777AddressConst) + auctionClientTest, err = NewAuctionClient(ethereumClientGov, auctionTestAddressConst, tokenHEZAddressConst) if err != nil { panic(err) } diff --git a/eth/rollup.go b/eth/rollup.go index b24688c..e7541dd 100644 --- a/eth/rollup.go +++ b/eth/rollup.go @@ -5,16 +5,14 @@ import ( "math/big" "strings" - Hermez "github.com/hermeznetwork/hermez-node/eth/contracts/hermez" - "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethclient" - ethCommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethclient" "github.com/hermeznetwork/hermez-node/common" + Hermez "github.com/hermeznetwork/hermez-node/eth/contracts/hermez" "github.com/hermeznetwork/hermez-node/log" "github.com/iden3/go-iden3-crypto/babyjub" ) @@ -40,12 +38,10 @@ const ( // RollupConstL1UserTotalBytes [20 bytes] fromEthAddr + [32 bytes] fromBjj-compressed + [6 bytes] fromIdx + // [2 bytes] loadAmountFloat16 + [2 bytes] amountFloat16 + [4 bytes] tokenId + [6 bytes] toIdx RollupConstL1UserTotalBytes = 72 - // RollupConstMaxL1UserTX Maximum L1-user transactions allowed to be queued in a batch - RollupConstMaxL1UserTX = 128 - // RollupConstMaxL1TX Maximum L1 transactions allowed to be queued in a batch - RollupConstMaxL1TX = 256 - // RollupConstRfield Modulus zkSNARK - RollupConstRfield = 21888242871839275222246405745257275088548364400416034343698204186575808495617 + // RollupConstMaxL1UserTx Maximum L1-user transactions allowed to be queued in a batch + RollupConstMaxL1UserTx = 128 + // RollupConstMaxL1Tx Maximum L1 transactions allowed to be queued in a batch + RollupConstMaxL1Tx = 256 // RollupConstInputSHAConstantBytes [6 bytes] lastIdx + [6 bytes] newLastIdx + [32 bytes] stateRoot + [32 bytes] newStRoot + [32 bytes] newExitRoot + // [_MAX_L1_TX * _L1_USER_TOTALBYTES bytes] l1TxsData + totalL2TxsDataLength + feeIdxCoordinatorLength + [2 bytes] chainID = // 18542 bytes + totalL2TxsDataLength + feeIdxCoordinatorLength @@ -65,6 +61,9 @@ var ( // This non-ethereum accounts can be created by the coordinator and allow users to have a rollup // account without needing an ethereum address RollupConstEthAddressInternalOnly = ethCommon.HexToAddress("0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF") + // RollupConstRfield Modulus zkSNARK + RollupConstRfield, _ = new(big.Int).SetString( + "21888242871839275222246405745257275088548364400416034343698204186575808495617", 10) // RollupConstERC1820 ERC1820Registry address RollupConstERC1820 = ethCommon.HexToAddress("0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24") @@ -73,8 +72,8 @@ var ( // RollupConstRecipientInterfaceHash ERC777 recipient interface hash RollupConstRecipientInterfaceHash = crypto.Keccak256([]byte("ERC777TokensRecipient")) - // RollupConstPerformL1UserTXSignature the signature of the function that can be called thru an ERC777 `send` - RollupConstPerformL1UserTXSignature = crypto.Keccak256([]byte("addL1Transaction(uint256,uint48,uint16,uint16,uint32,uint48)")) + // RollupConstPerformL1UserTxSignature the signature of the function that can be called thru an ERC777 `send` + RollupConstPerformL1UserTxSignature = crypto.Keccak256([]byte("addL1Transaction(uint256,uint48,uint16,uint16,uint32,uint48)")) // RollupConstAddTokenSignature the signature of the function that can be called thru an ERC777 `send` RollupConstAddTokenSignature = crypto.Keccak256([]byte("addToken(address)")) // RollupConstSendSignature ERC777 Signature @@ -130,7 +129,7 @@ var ( // RollupPublicConstants are the constants of the Rollup Smart Contract type RollupPublicConstants struct { - AbsoluteMaxL1L2BatchTimeout uint8 + AbsoluteMaxL1L2BatchTimeout int64 TokenHEZ ethCommon.Address Verifiers []RollupVerifierStruct HermezAuctionContract ethCommon.Address @@ -163,8 +162,8 @@ func NewQueueStruct() *QueueStruct { // RollupVerifierStruct is the information about verifiers of the Rollup Smart Contract type RollupVerifierStruct struct { - MaxTx *big.Int - NLevels *big.Int + MaxTx int64 + NLevels int64 } // RollupState represents the state of the Rollup in the Smart Contract @@ -184,8 +183,8 @@ type RollupState struct { // RollupEventL1UserTx is an event of the Rollup Smart Contract type RollupEventL1UserTx struct { - ToForgeL1TxsNum uint64 // QueueIndex *big.Int - Position uint8 // TransactionIndex *big.Int + ToForgeL1TxsNum int64 // QueueIndex *big.Int + Position int // TransactionIndex *big.Int L1Tx common.L1Tx } @@ -250,7 +249,7 @@ func NewRollupEvents() RollupEvents { // RollupForgeBatchArgs are the arguments to the ForgeBatch function in the Rollup Smart Contract //nolint:structcheck,unused type RollupForgeBatchArgs struct { - NewLastIdx uint64 + NewLastIdx int64 NewStRoot *big.Int NewExitRoot *big.Int L1CoordinatorTxs []*common.L1Tx @@ -453,23 +452,24 @@ func (c *RollupClient) RollupConstants() (*RollupPublicConstants, error) { if err != nil { return err } - rollupConstants.AbsoluteMaxL1L2BatchTimeout, err = hermez.ABSOLUTEMAXL1L2BATCHTIMEOUT(nil) + absoluteMaxL1L2BatchTimeout, err := hermez.ABSOLUTEMAXL1L2BATCHTIMEOUT(nil) if err != nil { return err } + rollupConstants.AbsoluteMaxL1L2BatchTimeout = int64(absoluteMaxL1L2BatchTimeout) rollupConstants.TokenHEZ, err = hermez.TokenHEZ(nil) if err != nil { return err } for i := int64(0); i < int64(LenVerifiers); i++ { - newRollupVerifier := new(RollupVerifierStruct) + var newRollupVerifier RollupVerifierStruct rollupVerifier, err := hermez.RollupVerifiers(nil, big.NewInt(i)) if err != nil { return err } - newRollupVerifier.MaxTx = rollupVerifier.MaxTx - newRollupVerifier.NLevels = rollupVerifier.NLevels - rollupConstants.Verifiers = append(rollupConstants.Verifiers, *newRollupVerifier) + newRollupVerifier.MaxTx = rollupVerifier.MaxTx.Int64() + newRollupVerifier.NLevels = rollupVerifier.NLevels.Int64() + rollupConstants.Verifiers = append(rollupConstants.Verifiers, newRollupVerifier) } rollupConstants.HermezAuctionContract, err = hermez.HermezAuctionContract(nil) if err != nil { @@ -492,7 +492,7 @@ func (c *RollupClient) RollupConstants() (*RollupPublicConstants, error) { } var ( - logHermezL1UserTXEvent = crypto.Keccak256Hash([]byte("L1UserTxEvent(uint64,uint8,bytes)")) + logHermezL1UserTxEvent = crypto.Keccak256Hash([]byte("L1UserTxEvent(uint64,uint8,bytes)")) logHermezAddToken = crypto.Keccak256Hash([]byte("AddToken(address,uint32)")) logHermezForgeBatch = crypto.Keccak256Hash([]byte("ForgeBatch(uint64)")) logHermezUpdateForgeL1L2BatchTimeout = crypto.Keccak256Hash([]byte("UpdateForgeL1L2BatchTimeout(uint8)")) @@ -526,7 +526,7 @@ func (c *RollupClient) RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethC return nil, nil, ErrBlockHashMismatchEvent } switch vLog.Topics[0] { - case logHermezL1UserTXEvent: + case logHermezL1UserTxEvent: var L1UserTxAux RollupEventL1UserTxAux var L1UserTx RollupEventL1UserTx err := c.contractAbi.Unpack(&L1UserTxAux, "L1UserTxEvent", vLog.Data) @@ -537,8 +537,8 @@ func (c *RollupClient) RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethC if err != nil { return nil, nil, err } - L1UserTx.ToForgeL1TxsNum = new(big.Int).SetBytes(vLog.Topics[1][:]).Uint64() - L1UserTx.Position = uint8(new(big.Int).SetBytes(vLog.Topics[2][:]).Uint64()) + L1UserTx.ToForgeL1TxsNum = new(big.Int).SetBytes(vLog.Topics[1][:]).Int64() + L1UserTx.Position = int(new(big.Int).SetBytes(vLog.Topics[2][:]).Int64()) L1UserTx.L1Tx = *L1Tx rollupEvents.L1UserTx = append(rollupEvents.L1UserTx, L1UserTx) case logHermezAddToken: @@ -552,6 +552,7 @@ func (c *RollupClient) RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethC case logHermezForgeBatch: var forgeBatch RollupEventForgeBatch forgeBatch.BatchNum = new(big.Int).SetBytes(vLog.Topics[1][:]).Int64() + forgeBatch.EthTxHash = vLog.TxHash rollupEvents.ForgeBatch = append(rollupEvents.ForgeBatch, forgeBatch) case logHermezUpdateForgeL1L2BatchTimeout: var updateForgeL1L2BatchTimeout RollupEventUpdateForgeL1L2BatchTimeout @@ -592,12 +593,14 @@ func (c *RollupClient) RollupForgeBatchArgs(ethTxHash ethCommon.Hash) (*RollupFo if err != nil { return nil, err } - aux := new(RollupForgeBatchArgsAux) - method.Inputs.Unpack(aux, txData) - rollupForgeBatchArgs := new(RollupForgeBatchArgs) + var aux RollupForgeBatchArgsAux + if err := method.Inputs.Unpack(&aux, txData); err != nil { + return nil, err + } + var rollupForgeBatchArgs RollupForgeBatchArgs rollupForgeBatchArgs.L1Batch = aux.L1Batch rollupForgeBatchArgs.NewExitRoot = aux.NewExitRoot - rollupForgeBatchArgs.NewLastIdx = aux.NewLastIdx + rollupForgeBatchArgs.NewLastIdx = int64(aux.NewLastIdx) rollupForgeBatchArgs.NewStRoot = aux.NewStRoot rollupForgeBatchArgs.ProofA = aux.ProofA rollupForgeBatchArgs.ProofB = aux.ProofB @@ -606,30 +609,31 @@ func (c *RollupClient) RollupForgeBatchArgs(ethTxHash ethCommon.Hash) (*RollupFo numTxsL1 := len(aux.L1CoordinatorTxs) / common.L1TxBytesLen for i := 0; i < numTxsL1; i++ { - L1Tx, err := common.L1TxFromCoordinatorBytes(aux.L1CoordinatorTxs[i*common.L1CoordinatorTxBytesLen : (i+1)*common.L1CoordinatorTxBytesLen]) + l1Tx, err := common.L1TxFromCoordinatorBytes(aux.L1CoordinatorTxs[i*common.L1CoordinatorTxBytesLen : (i+1)*common.L1CoordinatorTxBytesLen]) if err != nil { return nil, err } - rollupForgeBatchArgs.L1CoordinatorTxs = append(rollupForgeBatchArgs.L1CoordinatorTxs, L1Tx) + rollupForgeBatchArgs.L1CoordinatorTxs = append(rollupForgeBatchArgs.L1CoordinatorTxs, l1Tx) } rollupConsts, err := c.RollupConstants() if err != nil { return nil, err } - nLevels := rollupConsts.Verifiers[rollupForgeBatchArgs.VerifierIdx].NLevels.Int64() + nLevels := rollupConsts.Verifiers[rollupForgeBatchArgs.VerifierIdx].NLevels lenL2TxsBytes := int((nLevels/8)*2 + 2 + 1) numTxsL2 := len(aux.L2TxsData) / lenL2TxsBytes for i := 0; i < numTxsL2; i++ { - L2Tx, err := common.L2TxFromBytes(aux.L2TxsData[i*lenL2TxsBytes:(i+1)*lenL2TxsBytes], int(nLevels)) + l2Tx, err := common.L2TxFromBytes(aux.L2TxsData[i*lenL2TxsBytes:(i+1)*lenL2TxsBytes], int(nLevels)) if err != nil { return nil, err } - rollupForgeBatchArgs.L2TxsData = append(rollupForgeBatchArgs.L2TxsData, L2Tx) + rollupForgeBatchArgs.L2TxsData = append(rollupForgeBatchArgs.L2TxsData, l2Tx) } - lenFeeIdxCoordinatorBytes := int(nLevels / 8) + lenFeeIdxCoordinatorBytes := int(nLevels / 8) //nolint:gomnd numFeeIdxCoordinator := len(aux.FeeIdxCoordinator) / lenFeeIdxCoordinatorBytes for i := 0; i < numFeeIdxCoordinator; i++ { var paddedFeeIdx [6]byte + // TODO: This check is not necessary: the first case will always work. Test it before removing the if. if lenFeeIdxCoordinatorBytes < common.IdxBytesLen { copy(paddedFeeIdx[6-lenFeeIdxCoordinatorBytes:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes]) } else { @@ -641,7 +645,7 @@ func (c *RollupClient) RollupForgeBatchArgs(ethTxHash ethCommon.Hash) (*RollupFo } rollupForgeBatchArgs.FeeIdxCoordinator = append(rollupForgeBatchArgs.FeeIdxCoordinator, FeeIdxCoordinator) } - return rollupForgeBatchArgs, nil + return &rollupForgeBatchArgs, nil // tx := client.TransactionByHash(ethTxHash) -> types.Transaction // txData := types.Transaction -> Data() // m := abi.MethodById(txData) -> Method diff --git a/synchronizer/synchronizer.go b/synchronizer/synchronizer.go index 0969ada..c570e5f 100644 --- a/synchronizer/synchronizer.go +++ b/synchronizer/synchronizer.go @@ -429,7 +429,7 @@ func (s *Synchronizer) rollupSync(blockNum int64) (*rollupData, error) { } // Get L2Txs - poolL2Txs := common.L2TxsToPoolL2Txs(forgeBatchArgs.L2Txs) // TODO: This is a big uggly, find a better way + poolL2Txs := common.L2TxsToPoolL2Txs(forgeBatchArgs.L2TxsData) // TODO: This is a big uggly, find a better way // Get exitTree // TODO: Get createdAccounts from ProcessTxs() @@ -502,18 +502,18 @@ func (s *Synchronizer) auctionSync(blockNum int64) (*auctionData, error) { bid := &common.Bid{ SlotNum: common.SlotNum(eNewBid.Slot), BidValue: eNewBid.BidAmount, - ForgerAddr: eNewBid.CoordinatorForger, + Bidder: eNewBid.Bidder, EthBlockNum: blockNum, } auctionData.bids = append(auctionData.bids, bid) } // Get Coordinators - for _, eNewCoordinator := range auctionEvents.NewCoordinator { + for _, eNewCoordinator := range auctionEvents.SetCoordinator { coordinator := &common.Coordinator{ - Forger: eNewCoordinator.ForgerAddress, - WithdrawAddr: eNewCoordinator.WithdrawalAddress, - URL: eNewCoordinator.CoordinatorURL, + Bidder: eNewCoordinator.BidderAddress, + Forger: eNewCoordinator.ForgerAddress, + URL: eNewCoordinator.CoordinatorURL, } auctionData.coordinators = append(auctionData.coordinators, coordinator) } @@ -530,18 +530,6 @@ func (s *Synchronizer) auctionSync(blockNum int64) (*auctionData, error) { // TODO: NewForge // TODO: HEZClaimed - // TODO: Think about separating new coordinaors from coordinator updated - - // Get Coordinators from updates - for _, eCoordinatorUpdated := range auctionEvents.CoordinatorUpdated { - coordinator := &common.Coordinator{ - Forger: eCoordinatorUpdated.ForgerAddress, - WithdrawAddr: eCoordinatorUpdated.WithdrawalAddress, - URL: eCoordinatorUpdated.CoordinatorURL, - } - auctionData.coordinators = append(auctionData.coordinators, coordinator) - } - // TODO: VARS // TODO: CONSTANTS diff --git a/test/ethclient.go b/test/ethclient.go index cb209b8..929e8bd 100644 --- a/test/ethclient.go +++ b/test/ethclient.go @@ -34,7 +34,7 @@ type RollupBlock struct { Vars eth.RollupVariables Events eth.RollupEvents Txs map[ethCommon.Hash]*types.Transaction - Constants *eth.RollupConstants + Constants *eth.RollupPublicConstants Eth *EthereumBlock } @@ -128,7 +128,7 @@ func (a *AuctionBlock) forge(forger ethCommon.Address) error { a.Events.NewForge = append(a.Events.NewForge, eth.AuctionEventNewForge{ Forger: forger, - CurrentSlot: slotToForge, + SlotToForge: slotToForge, }) return nil } @@ -159,7 +159,9 @@ func (a *AuctionBlock) canForge(forger ethCommon.Address, blockNum int64) (bool, if !slotState.Fulfilled && (relativeBlock >= int64(a.Vars.SlotDeadline)) { // if the relative block has exceeded the slotDeadline and no batch has been forged, anyone can forge return true, nil - } else if slotState.Forger == forger && slotState.BidAmount.Cmp(minBid) >= 0 { + // TODO, find the forger set by the Bidder + } else if coord, ok := a.State.Coordinators[slotState.Bidder]; ok && + coord.Forger == forger && slotState.BidAmount.Cmp(minBid) >= 0 { // if forger bidAmount has exceeded the minBid it can forge return true, nil } else if a.Vars.BootCoordinator == forger && slotState.BidAmount.Cmp(minBid) == -1 { @@ -214,7 +216,7 @@ func (b *Block) Next() *Block { // ClientSetup is used to initialize the constants of the Smart Contracts and // other details of the test Client type ClientSetup struct { - RollupConstants *eth.RollupConstants + RollupConstants *eth.RollupPublicConstants RollupVariables *eth.RollupVariables AuctionConstants *eth.AuctionConstants AuctionVariables *eth.AuctionVariables @@ -224,36 +226,33 @@ type ClientSetup struct { // NewClientSetupExample returns a ClientSetup example with hardcoded realistic values. //nolint:gomnd func NewClientSetupExample() *ClientSetup { - rfield, ok := new(big.Int).SetString("21888242871839275222246405745257275088548364400416034343698204186575808495617", 10) - if !ok { - panic("bad rfield") - } + // rfield, ok := new(big.Int).SetString("21888242871839275222246405745257275088548364400416034343698204186575808495617", 10) + // if !ok { + // panic("bad rfield") + // } initialMinimalBidding, ok := new(big.Int).SetString("10000000000000000000", 10) // 10 * (1e18) if !ok { panic("bad initialMinimalBidding") } tokenHEZ := ethCommon.HexToAddress("0x51D243D62852Bba334DD5cc33f242BAc8c698074") governanceAddress := ethCommon.HexToAddress("0x688EfD95BA4391f93717CF02A9aED9DBD2855cDd") - rollupConstants := ð.RollupConstants{ - MaxAmountDeposit: new(big.Int).Lsh(big.NewInt(1), 128), - MaxAmountL2: new(big.Int).Lsh(big.NewInt(1), 192), - MaxTokens: 0xffffffff, - MaxL1Tx: 256, - MaxL1UserTx: 128, - Rfield: rfield, - L1CoordinatorBytes: 101, - L1UserBytes: 68, - L2Bytes: 11, - MaxTxVerifiers: []int{512, 1024, 2048}, - TokenHEZ: tokenHEZ, - GovernanceAddress: governanceAddress, - SafetyBot: ethCommon.HexToAddress("0x84d8B79E84fe87B14ad61A554e740f6736bF4c20"), - ConsensusContract: ethCommon.HexToAddress("0x8E442975805fb1908f43050c9C1A522cB0e28D7b"), - WithdrawalContract: ethCommon.HexToAddress("0x5CB7979cBdbf65719BEE92e4D15b7b7Ed3D79114"), + rollupConstants := ð.RollupPublicConstants{ + Verifiers: []eth.RollupVerifierStruct{ + { + MaxTx: 2048, + NLevels: 32, + }, + }, + TokenHEZ: tokenHEZ, + HermezGovernanceDAOAddress: governanceAddress, + SafetyAddress: ethCommon.HexToAddress("0x84d8B79E84fe87B14ad61A554e740f6736bF4c20"), + HermezAuctionContract: ethCommon.HexToAddress("0x8E442975805fb1908f43050c9C1A522cB0e28D7b"), + WithdrawDelayerContract: ethCommon.HexToAddress("0x5CB7979cBdbf65719BEE92e4D15b7b7Ed3D79114"), } rollupVariables := ð.RollupVariables{ - FeeAddToken: big.NewInt(11), - ForgeL1Timeout: 9, + FeeAddToken: big.NewInt(11), + ForgeL1L2BatchTimeout: 9, + WithdrawalDelay: 80, } auctionConstants := ð.AuctionConstants{ BlocksPerSlot: 40, @@ -301,7 +300,7 @@ type Client struct { rw *sync.RWMutex log bool addr *ethCommon.Address - rollupConstants *eth.RollupConstants + rollupConstants *eth.RollupPublicConstants auctionConstants *eth.AuctionConstants blocks map[int64]*Block // state state @@ -431,6 +430,11 @@ func (c *Client) currentBlock() *Block { return c.blocks[c.blockNum] } +// CtlSetAddr sets the address of the client +func (c *Client) CtlSetAddr(addr ethCommon.Address) { + c.addr = &addr +} + // CtlMineBlock moves one block forward func (c *Client) CtlMineBlock() { c.rw.Lock() @@ -561,7 +565,7 @@ func (c *Client) CtlAddL1TxUser(l1Tx *common.L1Tx) { nextBlock := c.nextBlock() r := nextBlock.Rollup queue := r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] - if len(queue.L1TxQueue) >= c.rollupConstants.MaxL1UserTx { + if len(queue.L1TxQueue) >= eth.RollupConstMaxL1UserTx { r.State.LastToForgeL1TxsNum++ r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct() queue = r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] @@ -881,7 +885,7 @@ func (c *Client) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (tx *types.Tra // } // RollupConstants returns the Constants of the Rollup Smart Contract -func (c *Client) RollupConstants() (*eth.RollupConstants, error) { +func (c *Client) RollupConstants() (*eth.RollupPublicConstants, error) { c.rw.RLock() defer c.rw.RUnlock() @@ -1094,8 +1098,8 @@ func (c *Client) AuctionChangeDefaultSlotSetBid(slotSet int64, newInitialMinBid return nil, errTODO } -// AuctionRegisterCoordinator is the interface to call the smart contract function -func (c *Client) AuctionRegisterCoordinator(forgerAddress ethCommon.Address, URL string) (tx *types.Transaction, err error) { +// AuctionSetCoordinator is the interface to call the smart contract function +func (c *Client) AuctionSetCoordinator(forger ethCommon.Address, URL string) (tx *types.Transaction, err error) { c.rw.Lock() defer c.rw.Unlock() cpy := c.nextBlock().copy() @@ -1107,26 +1111,24 @@ func (c *Client) AuctionRegisterCoordinator(forgerAddress ethCommon.Address, URL nextBlock := c.nextBlock() a := nextBlock.Auction - if _, ok := a.State.Coordinators[forgerAddress]; ok { - return nil, fmt.Errorf("Already registered") - } - a.State.Coordinators[forgerAddress] = ð.Coordinator{ - WithdrawalAddress: *c.addr, - URL: URL, + a.State.Coordinators[*c.addr] = ð.Coordinator{ + Forger: forger, + URL: URL, } - a.Events.NewCoordinator = append(a.Events.NewCoordinator, - eth.AuctionEventNewCoordinator{ - ForgerAddress: forgerAddress, - WithdrawalAddress: *c.addr, - CoordinatorURL: URL, + a.Events.SetCoordinator = append(a.Events.SetCoordinator, + eth.AuctionEventSetCoordinator{ + BidderAddress: *c.addr, + ForgerAddress: forger, + CoordinatorURL: URL, }) type data struct { + BidderAddress ethCommon.Address ForgerAddress ethCommon.Address URL string } - return a.addTransaction(newTransaction("registercoordinator", data{forgerAddress, URL})), nil + return a.addTransaction(newTransaction("registercoordinator", data{*c.addr, forger, URL})), nil } // AuctionIsRegisteredCoordinator is the interface to call the smart contract function @@ -1204,7 +1206,7 @@ func (c *Client) AuctionGetSlotSet(slot int64) (*big.Int, error) { // } // AuctionBid is the interface to call the smart contract function -func (c *Client) AuctionBid(slot int64, bidAmount *big.Int, forger ethCommon.Address) (tx *types.Transaction, err error) { +func (c *Client) AuctionBid(slot int64, bidAmount *big.Int) (tx *types.Transaction, err error) { c.rw.Lock() defer c.rw.Unlock() cpy := c.nextBlock().copy() @@ -1232,7 +1234,7 @@ func (c *Client) AuctionBid(slot int64, bidAmount *big.Int, forger ethCommon.Add return nil, errBidBelowMin } - if _, ok := a.State.Coordinators[forger]; !ok { + if _, ok := a.State.Coordinators[*c.addr]; !ok { return nil, errCoordNotReg } @@ -1241,22 +1243,22 @@ func (c *Client) AuctionBid(slot int64, bidAmount *big.Int, forger ethCommon.Add slotState = eth.NewSlotState() a.State.Slots[slot] = slotState } - slotState.Forger = forger + slotState.Bidder = *c.addr slotState.BidAmount = bidAmount a.Events.NewBid = append(a.Events.NewBid, - eth.AuctionEventNewBid{Slot: slot, BidAmount: bidAmount, CoordinatorForger: forger}) + eth.AuctionEventNewBid{Slot: slot, BidAmount: bidAmount, Bidder: *c.addr}) type data struct { Slot int64 BidAmount *big.Int - Forger ethCommon.Address + Bidder ethCommon.Address } - return a.addTransaction(newTransaction("bid", data{slot, bidAmount, forger})), nil + return a.addTransaction(newTransaction("bid", data{slot, bidAmount, *c.addr})), nil } // AuctionMultiBid is the interface to call the smart contract function -func (c *Client) AuctionMultiBid(startingSlot int64, endingSlot int64, slotSet [6]bool, maxBid, closedMinBid, budget *big.Int, forger ethCommon.Address) (tx *types.Transaction, err error) { +func (c *Client) AuctionMultiBid(startingSlot int64, endingSlot int64, slotSet [6]bool, maxBid, closedMinBid, budget *big.Int) (tx *types.Transaction, err error) { c.rw.Lock() defer c.rw.Unlock() cpy := c.nextBlock().copy() @@ -1280,12 +1282,21 @@ func (c *Client) AuctionCanForge(forger ethCommon.Address, blockNum int64) (bool } // AuctionForge is the interface to call the smart contract function -// func (c *Client) AuctionForge(forger ethCommon.Address) (bool, error) { -// return false, errTODO -// } +func (c *Client) AuctionForge(forger ethCommon.Address) (tx *types.Transaction, err error) { + c.rw.Lock() + defer c.rw.Unlock() + cpy := c.nextBlock().copy() + defer func() { c.revertIfErr(err, cpy) }() + if c.addr == nil { + return nil, eth.ErrAccountNil + } + + log.Error("TODO") + return nil, errTODO +} // AuctionClaimHEZ is the interface to call the smart contract function -func (c *Client) AuctionClaimHEZ(claimAddress ethCommon.Address) (tx *types.Transaction, err error) { +func (c *Client) AuctionClaimHEZ() (tx *types.Transaction, err error) { c.rw.Lock() defer c.rw.Unlock() cpy := c.nextBlock().copy() @@ -1298,6 +1309,15 @@ func (c *Client) AuctionClaimHEZ(claimAddress ethCommon.Address) (tx *types.Tran return nil, errTODO } +// AuctionGetClaimableHEZ is the interface to call the smart contract function +func (c *Client) AuctionGetClaimableHEZ(bidder ethCommon.Address) (*big.Int, error) { + c.rw.RLock() + defer c.rw.RUnlock() + + log.Error("TODO") + return nil, errTODO +} + // AuctionConstants returns the Constants of the Auction Smart Contract func (c *Client) AuctionConstants() (*eth.AuctionConstants, error) { c.rw.RLock() diff --git a/test/ethclient_test.go b/test/ethclient_test.go index 71d20c3..11d1003 100644 --- a/test/ethclient_test.go +++ b/test/ethclient_test.go @@ -65,7 +65,8 @@ func TestClientEth(t *testing.T) { } func TestClientAuction(t *testing.T) { - addrWithdraw := ethCommon.HexToAddress("0x6b175474e89094c44da98b954eedeac495271d0f") + addrBidder1 := ethCommon.HexToAddress("0x6b175474e89094c44da98b954eedeac495271d0f") + addrBidder2 := ethCommon.HexToAddress("0xc27cadc437d067a6ec869502cc9f7F834cFc087a") addrForge := ethCommon.HexToAddress("0xCfAA413eEb796f328620a3630Ae39124cabcEa92") addrForge2 := ethCommon.HexToAddress("0x1fCb4ac309428feCc61B1C8cA5823C15A5e1a800") @@ -76,37 +77,38 @@ func TestClientAuction(t *testing.T) { clientSetup.AuctionVariables.DefaultSlotSetBid = [6]*big.Int{ big.NewInt(1000), big.NewInt(1100), big.NewInt(1200), big.NewInt(1300), big.NewInt(1400), big.NewInt(1500)} - c := NewClient(true, &timer, &addrWithdraw, clientSetup) + c := NewClient(true, &timer, &addrBidder1, clientSetup) // Check several cases in which bid doesn't succed, and also do 2 successful bids. - _, err := c.AuctionBid(0, big.NewInt(1), addrForge) + _, err := c.AuctionBid(0, big.NewInt(1)) assert.Equal(t, errBidClosed, err) - _, err = c.AuctionBid(4322, big.NewInt(1), addrForge) + _, err = c.AuctionBid(4322, big.NewInt(1)) assert.Equal(t, errBidNotOpen, err) // 101 % 6 = 5; defaultSlotSetBid[5] = 1500; 1500 + 10% = 1650 - _, err = c.AuctionBid(101, big.NewInt(1650), addrForge) + _, err = c.AuctionBid(101, big.NewInt(1650)) assert.Equal(t, errCoordNotReg, err) - _, err = c.AuctionRegisterCoordinator(addrForge, "https://foo.bar") + _, err = c.AuctionSetCoordinator(addrForge, "https://foo.bar") assert.Nil(t, err) - _, err = c.AuctionBid(3, big.NewInt(1), addrForge) + _, err = c.AuctionBid(3, big.NewInt(1)) assert.Equal(t, errBidBelowMin, err) - _, err = c.AuctionBid(3, big.NewInt(1650), addrForge) + _, err = c.AuctionBid(3, big.NewInt(1650)) assert.Nil(t, err) - _, err = c.AuctionRegisterCoordinator(addrForge2, "https://foo2.bar") + c.CtlSetAddr(addrBidder2) + _, err = c.AuctionSetCoordinator(addrForge2, "https://foo2.bar") assert.Nil(t, err) - _, err = c.AuctionBid(3, big.NewInt(16), addrForge2) + _, err = c.AuctionBid(3, big.NewInt(16)) assert.Equal(t, errBidBelowMin, err) // 1650 + 10% = 1815 - _, err = c.AuctionBid(3, big.NewInt(1815), addrForge2) + _, err = c.AuctionBid(3, big.NewInt(1815)) assert.Nil(t, err) c.CtlMineBlock() @@ -164,8 +166,8 @@ func TestClientRollup(t *testing.T) { NewStRoot: big.NewInt(1), NewExitRoot: big.NewInt(100), L1CoordinatorTxs: []*common.L1Tx{}, - L2Txs: []*common.L2Tx{}, - FeeIdxCoordinator: make([]common.Idx, eth.FeeIdxCoordinatorLen), + L2TxsData: []*common.L2Tx{}, + FeeIdxCoordinator: make([]common.Idx, eth.RollupConstFeeIdxCoordinatorLen), VerifierIdx: 0, L1Batch: true, }) @@ -201,8 +203,8 @@ func TestClientRollup(t *testing.T) { NewStRoot: big.NewInt(1), NewExitRoot: big.NewInt(100), L1CoordinatorTxs: []*common.L1Tx{}, - L2Txs: []*common.L2Tx{}, - FeeIdxCoordinator: make([]common.Idx, eth.FeeIdxCoordinatorLen), + L2TxsData: []*common.L2Tx{}, + FeeIdxCoordinator: make([]common.Idx, eth.RollupConstFeeIdxCoordinatorLen), VerifierIdx: 0, L1Batch: true, } diff --git a/test/historydb.go b/test/historydb.go index cbfb01c..de01864 100644 --- a/test/historydb.go +++ b/test/historydb.go @@ -363,10 +363,10 @@ func GenCoordinators(nCoords int, blocks []common.Block) []common.Coordinator { coords := []common.Coordinator{} for i := 0; i < nCoords; i++ { coords = append(coords, common.Coordinator{ - EthBlockNum: blocks[i%len(blocks)].EthBlockNum, - Forger: ethCommon.BigToAddress(big.NewInt(int64(i))), - WithdrawAddr: ethCommon.BigToAddress(big.NewInt(int64(i))), - URL: "https://foo.bar", + EthBlockNum: blocks[i%len(blocks)].EthBlockNum, + Forger: ethCommon.BigToAddress(big.NewInt(int64(i))), + Bidder: ethCommon.BigToAddress(big.NewInt(int64(i))), + URL: "https://foo.bar", }) } return coords @@ -380,7 +380,7 @@ func GenBids(nBids int, blocks []common.Block, coords []common.Coordinator) []co SlotNum: common.SlotNum(i), BidValue: big.NewInt(int64(i)), EthBlockNum: blocks[i%len(blocks)].EthBlockNum, - ForgerAddr: coords[i%len(blocks)].Forger, + Bidder: coords[i%len(blocks)].Bidder, }) } return bids