Reorganize smart contract types, udate eth tests, etc.

- Move smart contract constants and structs for variables to
  common/{ethrollup.go, ethauction.go, ethwdelayer.go}:
    - This removes repeated code of the structs for variables
    - Allows reusing the constants and variables from all modules without
      import cycles
- Remove unused common/scvars.go
- In common.BlockData, split data from each smart contract into a sepparate
  field (Rollup, Auction, WDelayer).  This affects the structures that til uses
  as output, and HistoryDB in the AddBlockSCData.
- In Synchronizer:
    - Pass starting block of each smart contract as config, instead of
      incorrectly using the genesis block found in the acution constant (which
      has a very different meaning)
    - Use variable structs from common instead of an internal copy
    - Synchronize more stuff (resolve some TODOs)
    - Fix some issues found after initial testing with ganache
- In eth:
    - In auction.go: Add method to get constants
    - Update README to use ganache instead of buidlerevm as local blockchain
      for testing
    - Update env variables and test vectors to pass the tests with the
      deployment in the ganache testnet.
    - Use ethereum keys derived from paths (hdwallet) in testing to avoid
      hardcoding private keys and generate the same keys from a mnemonic used
      in the ganache tesnet.
This commit is contained in:
Eduard S
2020-10-28 16:09:05 +01:00
parent 954b24020c
commit e6fb0a03de
36 changed files with 1006 additions and 722 deletions

View File

@@ -1,7 +1,7 @@
GENESIS_BLOCK=97
AUCTION="0x038B86d9d8FAFdd0a02ebd1A476432877b0107C8"
AUCTION_TEST="0xEcc0a6dbC0bb4D51E4F84A315a9e5B0438cAD4f0"
TOKENHEZ="0xf4e77E5Da47AC3125140c470c71cBca77B5c638c"
HERMEZ="0xD6C850aeBFDC46D7F4c207e445cC0d6B0919BDBe"
WDELAYER="0x500D1d6A4c7D8Ae28240b47c8FCde034D827fD5e"
WDELAYER_TEST="0x1d80315fac6aBd3EfeEbE97dEc44461ba7556160"
AUCTION="0x5E0816F0f8bC560cB2B9e9C87187BeCac8c2021F"
AUCTION_TEST="0x56D4563E85477AC8Aa6a3b980b831DDb18a826ec"
TOKENHEZ="0x2b7dEe2CF60484325716A1c6A193519c8c3b19F3"
HERMEZ="0x6F4e99522F4eB37e0B73D0C0373147893EF12fD5"
WDELAYER="0x5D94e3e7aeC542aB0F9129B9a7BAdeb5B3Ca0f77"
WDELAYER_TEST="0xdc05EFc3029024068FCc86f05323411f14D69280"

1
eth/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.env

View File

@@ -8,7 +8,7 @@ The first step is to clone the github repository where the contracts are located
While the prepared deployment is not found to master, branch in repository must be changed:
`git checkout feature/ethclient-test-deployment`
`git checkout feature/ethclient-test-deployment-ganache` (tested with commit `f62c768bd4817921872666b3644403a119e28248`)
Now, install the dependencies:
@@ -21,14 +21,14 @@ Go to where the deployment scripts for the test are found:
`cd scripts/ethclient-deployment/`
Now, a bash script (which uses gnome-terminal) has to be run to do the deployment:
`./test-deploy.sh`
This bash file follows these steps:
- `npx builder node`: a local blockchain to do our tests
- `npx buidler run --network localhost test-deployment.js`: run the deployment on the local blockchain
Alternatively you can run the two previous commands manually in different terminals.
Now, in a terminal start a local blockchain with ganache:
```
../../node_modules/.bin/ganache-cli -d -m "explain tackle mirror kit van hammer degree position ginger unfair soup bonus" -p 8545 -l 12500000 -a 20 -e 10000 --allowUnlimitedContractSize --chainId 31337
```
Once ganache is ready, in another terminal run the deployment in the local ganache network:
```
npx buidler run --network ganache test-deployment.js
```
An output file necessary for the next step is obtained: `deploy-output`.
@@ -43,12 +43,12 @@ They can be provided by file called `.env`:
```
GENESIS_BLOCK=97
AUCTION="0x038B86d9d8FAFdd0a02ebd1A476432877b0107C8"
AUCTION_TEST="0xEcc0a6dbC0bb4D51E4F84A315a9e5B0438cAD4f0"
TOKENHEZ="0xf4e77E5Da47AC3125140c470c71cBca77B5c638c"
HERMEZ="0xD6C850aeBFDC46D7F4c207e445cC0d6B0919BDBe"
WDELAYER="0x500D1d6A4c7D8Ae28240b47c8FCde034D827fD5e"
WDELAYER_TEST="0x1d80315fac6aBd3EfeEbE97dEc44461ba7556160"
AUCTION="0x5E0816F0f8bC560cB2B9e9C87187BeCac8c2021F"
AUCTION_TEST="0x56D4563E85477AC8Aa6a3b980b831DDb18a826ec"
TOKENHEZ="0x2b7dEe2CF60484325716A1c6A193519c8c3b19F3"
HERMEZ="0x6F4e99522F4eB37e0B73D0C0373147893EF12fD5"
WDELAYER="0x5D94e3e7aeC542aB0F9129B9a7BAdeb5B3Ca0f77"
WDELAYER_TEST="0xdc05EFc3029024068FCc86f05323411f14D69280"
```
> An example is found in `hermez-node/eth/.env.example`
@@ -59,4 +59,4 @@ And then run test from `hermez-node/eth/`:
Or they can be provided as a parameter in the command that runs the test:
`INTEGRATION=1 GENESIS_BLOCK=97 AUCTION="0x038B86d9d8FAFdd0a02ebd1A476432877b0107C8" AUCTION_TEST="0xEcc0a6dbC0bb4D51E4F84A315a9e5B0438cAD4f0" TOKENHEZ="0xf4e77E5Da47AC3125140c470c71cBca77B5c638c" HERMEZ="0xD6C850aeBFDC46D7F4c207e445cC0d6B0919BDBe" WDELAYER="0x500D1d6A4c7D8Ae28240b47c8FCde034D827fD5e" WDELAYER_TEST="0x1d80315fac6aBd3EfeEbE97dEc44461ba7556160" go test`
`INTEGRATION=1 GENESIS_BLOCK=97 AUCTION="0x5E0816F0f8bC560cB2B9e9C87187BeCac8c2021F" AUCTION_TEST="0x56D4563E85477AC8Aa6a3b980b831DDb18a826ec" TOKENHEZ="0x2b7dEe2CF60484325716A1c6A193519c8c3b19F3" HERMEZ="0x6F4e99522F4eB37e0B73D0C0373147893EF12fD5" WDELAYER="0x5D94e3e7aeC542aB0F9129B9a7BAdeb5B3Ca0f77" WDELAYER_TEST="0xdc05EFc3029024068FCc86f05323411f14D69280" go test`

View File

@@ -13,27 +13,12 @@ import (
"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"
HermezAuctionProtocol "github.com/hermeznetwork/hermez-node/eth/contracts/auction"
HEZ "github.com/hermeznetwork/hermez-node/eth/contracts/tokenHEZ"
"github.com/hermeznetwork/hermez-node/log"
)
// AuctionConstants are the constants of the Rollup Smart Contract
type AuctionConstants struct {
// Blocks per slot
BlocksPerSlot uint8 `json:"blocksPerSlot"`
// Minimum bid when no one has bid yet
InitialMinimalBidding *big.Int `json:"initialMinimalBidding"`
// First block where the first slot begins
GenesisBlockNum int64 `json:"genesisBlockNum"`
// ERC777 token with which the bids will be made
TokenHEZ ethCommon.Address `json:"tokenHEZ"`
// HermezRollup smartcontract address
HermezRollup ethCommon.Address `json:"hermezRollup"`
// Hermez Governanze Token smartcontract address who controls some parameters and collects HEZ fee
// Only for test
GovernanceAddress ethCommon.Address `json:"governanceAddress"`
}
// SlotState is the state of a slot
type SlotState struct {
Bidder ethCommon.Address
@@ -58,26 +43,6 @@ type Coordinator struct {
URL string
}
// AuctionVariables are the variables of the Auction Smart Contract
type AuctionVariables struct {
// Boot Coordinator Address
DonationAddress ethCommon.Address `json:"donationAddress" meddler:"donation_address"`
// Boot Coordinator Address
BootCoordinator ethCommon.Address `json:"bootCoordinator" meddler:"boot_coordinator"`
// The minimum bid value in a series of 6 slots
DefaultSlotSetBid [6]*big.Int `json:"defaultSlotSetBid" meddler:"default_slot_set_bid,json"`
// Distance (#slots) to the closest slot to which you can bid ( 2 Slots = 2 * 40 Blocks = 20 min )
ClosedAuctionSlots uint16 `json:"closedAuctionSlots" meddler:"closed_auction_slots"`
// Distance (#slots) to the farthest slot to which you can bid (30 days = 4320 slots )
OpenAuctionSlots uint16 `json:"openAuctionSlots" meddler:"open_auction_slots"`
// How the HEZ tokens deposited by the slot winner are distributed (Burn: 40% - Donation: 40% - HGT: 20%)
AllocationRatio [3]uint16 `json:"allocationRatio" meddler:"allocation_ratio,json"`
// Minimum outbid (percentage) over the previous one to consider it valid
Outbidding uint16 `json:"outbidding" meddler:"outbidding"`
// Number of blocks at the end of a slot in which any coordinator can forge if the winner has not forged one before
SlotDeadline uint8 `json:"slotDeadline" meddler:"slot_deadline"`
}
// AuctionState represents the state of the Rollup in the Smart Contract
type AuctionState struct {
// Mapping to control slot state
@@ -251,7 +216,7 @@ type AuctionInterface interface {
// Smart Contract Status
//
AuctionConstants() (*AuctionConstants, error)
AuctionConstants() (*common.AuctionConstants, error)
AuctionEventsByBlock(blockNum int64) (*AuctionEvents, *ethCommon.Hash, error)
}
@@ -655,8 +620,8 @@ func (c *AuctionClient) AuctionForge(forger ethCommon.Address) (tx *types.Transa
}
// AuctionConstants returns the Constants of the Auction Smart Contract
func (c *AuctionClient) AuctionConstants() (auctionConstants *AuctionConstants, err error) {
auctionConstants = new(AuctionConstants)
func (c *AuctionClient) AuctionConstants() (auctionConstants *common.AuctionConstants, err error) {
auctionConstants = new(common.AuctionConstants)
if err := c.client.Call(func(ec *ethclient.Client) error {
auctionConstants.BlocksPerSlot, err = c.auction.BLOCKSPERSLOT(nil)
if err != nil {
@@ -684,8 +649,8 @@ func (c *AuctionClient) AuctionConstants() (auctionConstants *AuctionConstants,
}
// AuctionVariables returns the variables of the Auction Smart Contract
func (c *AuctionClient) AuctionVariables() (auctionVariables *AuctionVariables, err error) {
auctionVariables = new(AuctionVariables)
func (c *AuctionClient) AuctionVariables() (auctionVariables *common.AuctionVariables, err error) {
auctionVariables = new(common.AuctionVariables)
if err := c.client.Call(func(ec *ethclient.Client) error {
auctionVariables.AllocationRatio, err = c.AuctionGetAllocationRatio()
if err != nil {
@@ -751,7 +716,7 @@ var (
// are no events in that block, blockHash is nil.
func (c *AuctionClient) AuctionEventsByBlock(blockNum int64) (*AuctionEvents, *ethCommon.Hash, error) {
var auctionEvents AuctionEvents
var blockHash ethCommon.Hash
var blockHash *ethCommon.Hash
query := ethereum.FilterQuery{
FromBlock: big.NewInt(blockNum),
@@ -767,10 +732,11 @@ func (c *AuctionClient) AuctionEventsByBlock(blockNum int64) (*AuctionEvents, *e
return nil, nil, err
}
if len(logs) > 0 {
blockHash = logs[0].BlockHash
blockHash = &logs[0].BlockHash
}
for _, vLog := range logs {
if vLog.BlockHash != blockHash {
if vLog.BlockHash != *blockHash {
log.Errorw("Block hash mismatch", "expected", blockHash.String(), "got", vLog.BlockHash.String())
return nil, nil, ErrBlockHashMismatchEvent
}
switch vLog.Topics[0] {
@@ -869,5 +835,5 @@ func (c *AuctionClient) AuctionEventsByBlock(blockNum int64) (*AuctionEvents, *e
auctionEvents.HEZClaimed = append(auctionEvents.HEZClaimed, HEZClaimed)
}
}
return &auctionEvents, &blockHash, nil
return &auctionEvents, blockHash, nil
}

View File

@@ -35,7 +35,7 @@ func TestAuctionConstants(t *testing.T) {
require.Nil(t, err)
assert.Equal(t, auctionConstants.BlocksPerSlot, blocksPerSlot)
assert.Equal(t, auctionConstants.GenesisBlockNum, genesisBlock)
assert.Equal(t, auctionConstants.HermezRollup, hermezRollupAddressTestConst)
assert.Equal(t, auctionConstants.HermezRollup, hermezRollupTestAddressConst)
assert.Equal(t, auctionConstants.InitialMinimalBidding, INITMINBID)
assert.Equal(t, auctionConstants.TokenHEZ, tokenHEZAddressConst)
}

View File

@@ -270,6 +270,7 @@ func (c *EthereumClient) EthBlockByNumber(ctx context.Context, number int64) (*c
b := &common.Block{
EthBlockNum: block.Number().Int64(),
Timestamp: time.Unix(int64(block.Time()), 0),
ParentHash: block.ParentHash(),
Hash: block.Hash(),
}
return b, nil

View File

@@ -11,7 +11,7 @@ import (
func TestEthERC20(t *testing.T) {
ethClient, err := ethclient.Dial(ethClientDialURL)
require.Nil(t, err)
client := NewEthereumClient(ethClient, accountAux, ks, nil)
client := NewEthereumClient(ethClient, auxAccount, ks, nil)
consts, err := client.EthERC20Consts(tokenHEZAddressConst)
require.Nil(t, err)

View File

@@ -3,6 +3,7 @@ package eth
import (
"fmt"
"io/ioutil"
"log"
"math/big"
"os"
"strconv"
@@ -11,9 +12,9 @@ import (
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/accounts/keystore"
ethCommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/joho/godotenv"
hdwallet "github.com/miguelmota/go-ethereum-hdwallet"
)
var errEnvVar = fmt.Errorf("Some environment variable is missing")
@@ -22,8 +23,31 @@ var (
ethClientDialURL = "http://localhost:8545"
password = "pass"
deadline, _ = new(big.Int).SetString("ffffffffffffffffffffffffffffffff", 16)
mnemonic = "explain tackle mirror kit van hammer degree position ginger unfair soup bonus"
)
func genAcc(w *hdwallet.Wallet, ks *keystore.KeyStore, i int) (*accounts.Account, ethCommon.Address) {
path := hdwallet.MustParseDerivationPath(fmt.Sprintf("m/44'/60'/0'/0/%d", i))
account, err := w.Derive(path, false)
if err != nil {
log.Fatal(err)
}
key, err := w.PrivateKey(account)
if err != nil {
log.Fatal(err)
}
_, err = ks.ImportECDSA(key, password)
if err != nil {
log.Fatal(err)
}
if err := ks.Unlock(account, password); err != nil {
log.Fatal(err)
}
return &account, account.Address
}
// Smart Contract Addresses
var (
genesisBlock int64
@@ -35,53 +59,41 @@ var (
wdelayerTestAddressConst ethCommon.Address
tokenHEZ TokenConfig
donationAddressStr = "0x6c365935CA8710200C7595F0a72EB6023A7706Cd"
donationAddressConst = ethCommon.HexToAddress(donationAddressStr)
bootCoordinatorAddressStr = "0xc783df8a850f42e7f7e57013759c285caa701eb6"
bootCoordinatorAddressConst = ethCommon.HexToAddress(bootCoordinatorAddressStr)
safetyAddressStr = "0xE5904695748fe4A84b40b3fc79De2277660BD1D3"
safetyAddressConst = ethCommon.HexToAddress(safetyAddressStr)
donationAccount *accounts.Account
donationAddressConst ethCommon.Address
bootCoordinatorAccount *accounts.Account
bootCoordinatorAddressConst ethCommon.Address
safetyAccount *accounts.Account
safetyAddressConst ethCommon.Address
)
// Ethereum Accounts
var (
hermezGovernanceDAOAddressSK = "2a8aede924268f84156a00761de73998dac7bf703408754b776ff3f873bcec60"
hermezGovernanceDAOAddressStr = "0x84Fae3d3Cba24A97817b2a18c2421d462dbBCe9f"
hermezGovernanceDAOAddressConst = ethCommon.HexToAddress(hermezGovernanceDAOAddressStr)
hermezGovernanceDAOAccount *accounts.Account
hermezGovernanceDAOAddressConst ethCommon.Address
whiteHackGroupAddressSK = "8b24fd94f1ce869d81a34b95351e7f97b2cd88a891d5c00abc33d0ec9501902e"
whiteHackGroupAddressStr = "0xfa3BdC8709226Da0dA13A4d904c8b66f16c3c8BA"
whiteHackGroupAddressConst = ethCommon.HexToAddress(whiteHackGroupAddressStr)
whiteHackGroupAccount *accounts.Account
whiteHackGroupAddressConst ethCommon.Address
hermezKeeperAddressSK = "7f307c41137d1ed409f0a7b028f6c7596f12734b1d289b58099b99d60a96efff"
hermezKeeperAddressStr = "0xFbC51a9582D031f2ceaaD3959256596C5D3a5468"
hermezKeeperAddressConst = ethCommon.HexToAddress(hermezKeeperAddressStr)
hermezKeeperAccount *accounts.Account
hermezKeeperAddressConst ethCommon.Address
governanceAddressSK = "d49743deccbccc5dc7baa8e69e5be03298da8688a15dd202e20f15d5e0e9a9fb"
governanceAddressStr = "0xead9c93b79ae7c1591b1fb5323bd777e86e150d4"
governanceAddressConst = ethCommon.HexToAddress(governanceAddressStr)
governanceAccount *accounts.Account
governanceAddressConst ethCommon.Address
auxAddressSK = "28d1bfbbafe9d1d4f5a11c3c16ab6bf9084de48d99fbac4058bdfa3c80b29089"
auxAddressStr = "0x3d91185a02774C70287F6c74Dd26d13DFB58ff16"
auxAddressConst = ethCommon.HexToAddress(auxAddressStr)
auxAccount *accounts.Account
auxAddressConst ethCommon.Address
aux2AddressSK = "28d1bfbbafe9d1d4f5a11c3c16ab6bf9084de48d99fbac4058bdfa3c80b29087"
// aux2AddressStr = "0x532792b73c0c6e7565912e7039c59986f7e1dd1f"
// aux2AddressConst = ethCommon.HexToAddress(aux2AddressStr)
aux2Account *accounts.Account
aux2AddressConst ethCommon.Address
hermezRollupTestSK = "28d1bfbbafe9d1d4f5a11c3c16ab6bf9084de48d99fbac4058bdfa3c80b29088"
hermezRollupTestAddressStr = "0xEa960515F8b4C237730F028cBAcF0a28E7F45dE0"
hermezRollupAddressTestConst = ethCommon.HexToAddress(hermezRollupTestAddressStr)
hermezRollupTestAccount *accounts.Account
hermezRollupTestAddressConst ethCommon.Address
)
var (
accountGov *accounts.Account
accountKep *accounts.Account
accountWhite *accounts.Account
accountGovDAO *accounts.Account
accountAux *accounts.Account
accountAux2 *accounts.Account
accountHermez *accounts.Account
ks *keystore.KeyStore
ethClient *ethclient.Client
ethereumClientWhite *EthereumClient
@@ -92,22 +104,6 @@ var (
ethereumClientHermez *EthereumClient
)
func addKey(ks *keystore.KeyStore, skHex string) *accounts.Account {
key, err := crypto.HexToECDSA(skHex)
if err != nil {
panic(err)
}
account, err := ks.ImportECDSA(key, password)
if err != nil {
panic(err)
}
err = ks.Unlock(account, password)
if err != nil {
panic(err)
}
return &account
}
func getEnvVariables() {
err := godotenv.Load()
if err != nil {
@@ -124,10 +120,10 @@ func getEnvVariables() {
genesisBlockEnv := os.Getenv("GENESIS_BLOCK")
genesisBlock, err = strconv.ParseInt(genesisBlockEnv, 10, 64)
if err != nil {
panic(errEnvVar)
log.Fatal(errEnvVar)
}
if auctionAddressStr == "" || auctionTestAddressStr == "" || tokenHEZAddressStr == "" || hermezRollupAddressStr == "" || wdelayerAddressStr == "" || wdelayerTestAddressStr == "" || genesisBlockEnv == "" {
panic(errEnvVar)
log.Fatal(errEnvVar)
}
auctionAddressConst = ethCommon.HexToAddress(auctionAddressStr)
@@ -149,58 +145,67 @@ func TestMain(m *testing.M) {
getEnvVariables()
dir, err := ioutil.TempDir("", "tmpks")
if err != nil {
panic(err)
log.Fatal(err)
}
defer func() {
if err := os.RemoveAll(dir); err != nil {
panic(err)
log.Fatal(err)
}
}()
ks = keystore.NewKeyStore(dir, keystore.LightScryptN, keystore.LightScryptP)
// Load ethereum accounts from private keys
accountGov = addKey(ks, governanceAddressSK)
accountKep = addKey(ks, hermezKeeperAddressSK)
accountWhite = addKey(ks, whiteHackGroupAddressSK)
accountGovDAO = addKey(ks, hermezGovernanceDAOAddressSK)
accountAux = addKey(ks, auxAddressSK)
accountAux2 = addKey(ks, aux2AddressSK)
accountHermez = addKey(ks, hermezRollupTestSK)
w, err := hdwallet.NewFromMnemonic(mnemonic)
if err != nil {
log.Fatal(err)
}
// Create ethereum accounts from mnemonic and load private keys
// into the keystore
bootCoordinatorAccount, bootCoordinatorAddressConst = genAcc(w, ks, 0)
governanceAccount, governanceAddressConst = genAcc(w, ks, 1)
safetyAccount, safetyAddressConst = genAcc(w, ks, 2)
hermezKeeperAccount, hermezKeeperAddressConst = genAcc(w, ks, 6)
hermezGovernanceDAOAccount, hermezGovernanceDAOAddressConst = genAcc(w, ks, 7)
whiteHackGroupAccount, whiteHackGroupAddressConst = genAcc(w, ks, 8)
donationAccount, donationAddressConst = genAcc(w, ks, 9)
aux2Account, aux2AddressConst = genAcc(w, ks, 11)
hermezRollupTestAccount, hermezRollupTestAddressConst = genAcc(w, ks, 12)
auxAccount, auxAddressConst = genAcc(w, ks, 13)
ethClient, err = ethclient.Dial(ethClientDialURL)
if err != nil {
panic(err)
log.Fatal(err)
}
// Controllable Governance Address
ethereumClientGov := NewEthereumClient(ethClient, accountGov, ks, nil)
ethereumClientGov := NewEthereumClient(ethClient, governanceAccount, ks, nil)
auctionClient, err = NewAuctionClient(ethereumClientGov, auctionAddressConst, tokenHEZ)
if err != nil {
panic(err)
log.Fatal(err)
}
auctionClientTest, err = NewAuctionClient(ethereumClientGov, auctionTestAddressConst, tokenHEZ)
if err != nil {
panic(err)
log.Fatal(err)
}
rollupClient, err = NewRollupClient(ethereumClientGov, hermezRollupAddressConst, tokenHEZ)
if err != nil {
panic(err)
log.Fatal(err)
}
wdelayerClient, err = NewWDelayerClient(ethereumClientGov, wdelayerAddressConst)
if err != nil {
panic(err)
log.Fatal(err)
}
wdelayerClientTest, err = NewWDelayerClient(ethereumClientGov, wdelayerTestAddressConst)
if err != nil {
panic(err)
log.Fatal(err)
}
ethereumClientKep = NewEthereumClient(ethClient, accountKep, ks, nil)
ethereumClientWhite = NewEthereumClient(ethClient, accountWhite, ks, nil)
ethereumClientGovDAO = NewEthereumClient(ethClient, accountGovDAO, ks, nil)
ethereumClientAux = NewEthereumClient(ethClient, accountAux, ks, nil)
ethereumClientAux2 = NewEthereumClient(ethClient, accountAux2, ks, nil)
ethereumClientHermez = NewEthereumClient(ethClient, accountHermez, ks, nil)
ethereumClientKep = NewEthereumClient(ethClient, hermezKeeperAccount, ks, nil)
ethereumClientWhite = NewEthereumClient(ethClient, whiteHackGroupAccount, ks, nil)
ethereumClientGovDAO = NewEthereumClient(ethClient, hermezGovernanceDAOAccount, ks, nil)
ethereumClientAux = NewEthereumClient(ethClient, auxAccount, ks, nil)
ethereumClientAux2 = NewEthereumClient(ethClient, aux2Account, ks, nil)
ethereumClientHermez = NewEthereumClient(ethClient, hermezRollupTestAccount, ks, nil)
exitVal = m.Run()
}

View File

@@ -20,112 +20,6 @@ import (
"github.com/iden3/go-iden3-crypto/babyjub"
)
const (
// RollupConstMaxFeeIdxCoordinator is the maximum number of tokens the
// coordinator can use to collect fees (determines the number of tokens
// that the coordinator can collect fees from). This value is
// determined by the circuit.
RollupConstMaxFeeIdxCoordinator = 64
// RollupConstReservedIDx First 256 indexes reserved, first user index will be the 256
RollupConstReservedIDx = 255
// RollupConstExitIDx IDX 1 is reserved for exits
RollupConstExitIDx = 1
// RollupConstLimitLoadAmount Max load amount allowed (loadAmount: L1 --> L2)
RollupConstLimitLoadAmount = (1 << 128)
// RollupConstLimitL2TransferAmount Max amount allowed (amount L2 --> L2)
RollupConstLimitL2TransferAmount = (1 << 192)
// RollupConstLimitTokens Max number of tokens allowed to be registered inside the rollup
RollupConstLimitTokens = (1 << 32)
// RollupConstL1CoordinatorTotalBytes [4 bytes] token + [32 bytes] babyjub + [65 bytes] compressedSignature
RollupConstL1CoordinatorTotalBytes = 101
// 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
// 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
RollupConstInputSHAConstantBytes = 18542
// RollupConstNumBuckets Number of buckets
RollupConstNumBuckets = 5
// RollupConstMaxWithdrawalDelay max withdrawal delay in seconds
RollupConstMaxWithdrawalDelay = 2 * 7 * 24 * 60 * 60
// RollupConstExchangeMultiplier exchange multiplier
RollupConstExchangeMultiplier = 1e14
// LenVerifiers number of Rollup Smart Contract Verifiers
LenVerifiers = 1
)
var (
// RollupConstEthAddressInternalOnly This ethereum address is used internally for rollup accounts that don't have ethereum address, only Babyjubjub
// 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")
// ERC777 tokens signatures
// 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)"))
// RollupConstAddTokenSignature the signature of the function that can be called thru an ERC777 `send`
RollupConstAddTokenSignature = crypto.Keccak256([]byte("addToken(address)"))
// RollupConstSendSignature ERC777 Signature
RollupConstSendSignature = crypto.Keccak256([]byte("send(address,uint256,bytes)"))
// RollupConstERC777Granularity ERC777 Signature
RollupConstERC777Granularity = crypto.Keccak256([]byte("granularity()"))
// RollupConstWithdrawalDelayerDeposit This constant are used to deposit tokens from ERC77 tokens into withdrawal delayer
RollupConstWithdrawalDelayerDeposit = crypto.Keccak256([]byte("deposit(address,address,uint192)"))
// ERC20 signature
// RollupConstTransferSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
RollupConstTransferSignature = crypto.Keccak256([]byte("transfer(address,uint256)"))
// RollupConstTransferFromSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
RollupConstTransferFromSignature = crypto.Keccak256([]byte("transferFrom(address,address,uint256)"))
// RollupConstApproveSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
RollupConstApproveSignature = crypto.Keccak256([]byte("approve(address,uint256)"))
// RollupConstERC20Signature ERC20 decimals signature
RollupConstERC20Signature = crypto.Keccak256([]byte("decimals()"))
)
// RollupPublicConstants are the constants of the Rollup Smart Contract
type RollupPublicConstants struct {
AbsoluteMaxL1L2BatchTimeout int64 `json:"absoluteMaxL1L2BatchTimeout"`
TokenHEZ ethCommon.Address `json:"tokenHEZ"`
Verifiers []RollupVerifierStruct `json:"verifiers"`
HermezAuctionContract ethCommon.Address `json:"hermezAuctionContract"`
HermezGovernanceDAOAddress ethCommon.Address `json:"hermezGovernanceDAOAddress"`
SafetyAddress ethCommon.Address `json:"safetyAddress"`
WithdrawDelayerContract ethCommon.Address `json:"withdrawDelayerContract"`
}
// Bucket are the variables of each Bucket of Rollup Smart Contract
type Bucket struct {
CeilUSD uint64 `json:"ceilUSD"`
BlockStamp uint64 `json:"blockStamp"`
Withdrawals uint64 `json:"withdrawals"`
BlockWithdrawalRate uint64 `json:"blockWithdrawalRate"`
MaxWithdrawals uint64 `json:"maxWithdrawals"`
}
// RollupVariables are the variables of the Rollup Smart Contract
type RollupVariables struct {
FeeAddToken *big.Int `json:"feeAddToken" meddler:"fee_addtoken"`
ForgeL1L2BatchTimeout int64 `json:"forgeL1L2BatchTimeout" meddler:"forge_l1l2_timeout"`
WithdrawalDelay uint64 `json:"withdrawalDelay" meddler:"withdrawal_delay"`
Buckets [RollupConstNumBuckets]Bucket `json:"buckets" meddler:"buckets,json"`
}
// QueueStruct is the queue of L1Txs for a batch
type QueueStruct struct {
L1TxQueue []common.L1Tx
@@ -140,12 +34,6 @@ func NewQueueStruct() *QueueStruct {
}
}
// RollupVerifierStruct is the information about verifiers of the Rollup Smart Contract
type RollupVerifierStruct struct {
MaxTx int64 `json:"maxTx"`
NLevels int64 `json:"nlevels"`
}
// RollupState represents the state of the Rollup in the Smart Contract
type RollupState struct {
StateRoot *big.Int
@@ -197,8 +85,8 @@ type RollupEventUpdateFeeAddToken struct {
NewFeeAddToken *big.Int
}
// RollupEventWithdrawEvent is an event of the Rollup Smart Contract
type RollupEventWithdrawEvent struct {
// RollupEventWithdraw is an event of the Rollup Smart Contract
type RollupEventWithdraw struct {
Idx uint64
NumExitRoot uint64
InstantWithdraw bool
@@ -211,7 +99,7 @@ type RollupEvents struct {
ForgeBatch []RollupEventForgeBatch
UpdateForgeL1L2BatchTimeout []RollupEventUpdateForgeL1L2BatchTimeout
UpdateFeeAddToken []RollupEventUpdateFeeAddToken
WithdrawEvent []RollupEventWithdrawEvent
Withdraw []RollupEventWithdraw
}
// NewRollupEvents creates an empty RollupEvents with the slices initialized.
@@ -222,7 +110,7 @@ func NewRollupEvents() RollupEvents {
ForgeBatch: make([]RollupEventForgeBatch, 0),
UpdateForgeL1L2BatchTimeout: make([]RollupEventUpdateForgeL1L2BatchTimeout, 0),
UpdateFeeAddToken: make([]RollupEventUpdateFeeAddToken, 0),
WithdrawEvent: make([]RollupEventWithdrawEvent, 0),
Withdraw: make([]RollupEventWithdraw, 0),
}
}
@@ -287,7 +175,7 @@ type RollupInterface interface {
// Smart Contract Status
//
RollupConstants() (*RollupPublicConstants, error)
RollupConstants() (*common.RollupConstants, error)
RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error)
RollupForgeBatchArgs(ethCommon.Hash) (*RollupForgeBatchArgs, *ethCommon.Address, error)
}
@@ -361,11 +249,11 @@ func (c *RollupClient) RollupForgeBatch(args *RollupForgeBatchArgs) (tx *types.T
l2DataBytes = append(l2DataBytes, bytesl2[:]...)
}
var feeIdxCoordinator []byte
if len(args.FeeIdxCoordinator) > RollupConstMaxFeeIdxCoordinator {
if len(args.FeeIdxCoordinator) > common.RollupConstMaxFeeIdxCoordinator {
return nil, fmt.Errorf("len(args.FeeIdxCoordinator) > %v",
RollupConstMaxFeeIdxCoordinator)
common.RollupConstMaxFeeIdxCoordinator)
}
for i := 0; i < RollupConstMaxFeeIdxCoordinator; i++ {
for i := 0; i < common.RollupConstMaxFeeIdxCoordinator; i++ {
feeIdx := common.Idx(0)
if i < len(args.FeeIdxCoordinator) {
feeIdx = args.FeeIdxCoordinator[i]
@@ -552,8 +440,8 @@ func (c *RollupClient) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (tx *typ
}
// RollupConstants returns the Constants of the Rollup Smart Contract
func (c *RollupClient) RollupConstants() (rollupConstants *RollupPublicConstants, err error) {
rollupConstants = new(RollupPublicConstants)
func (c *RollupClient) RollupConstants() (rollupConstants *common.RollupConstants, err error) {
rollupConstants = new(common.RollupConstants)
if err := c.client.Call(func(ec *ethclient.Client) error {
absoluteMaxL1L2BatchTimeout, err := c.hermez.ABSOLUTEMAXL1L2BATCHTIMEOUT(nil)
if err != nil {
@@ -564,8 +452,8 @@ func (c *RollupClient) RollupConstants() (rollupConstants *RollupPublicConstants
if err != nil {
return err
}
for i := int64(0); i < int64(LenVerifiers); i++ {
var newRollupVerifier RollupVerifierStruct
for i := int64(0); i < int64(common.LenVerifiers); i++ {
var newRollupVerifier common.RollupVerifierStruct
rollupVerifier, err := c.hermez.RollupVerifiers(nil, big.NewInt(i))
if err != nil {
return err
@@ -606,7 +494,7 @@ var (
// RollupEventsByBlock returns the events in a block that happened in the Rollup Smart Contract
func (c *RollupClient) RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error) {
var rollupEvents RollupEvents
var blockHash ethCommon.Hash
var blockHash *ethCommon.Hash
query := ethereum.FilterQuery{
FromBlock: big.NewInt(blockNum),
@@ -622,10 +510,14 @@ func (c *RollupClient) RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethC
return nil, nil, err
}
if len(logs) > 0 {
blockHash = logs[0].BlockHash
for i := range logs {
log.Debugw("log", "i", i, "blockHash", logs[i].BlockHash)
}
blockHash = &logs[0].BlockHash
}
for _, vLog := range logs {
if vLog.BlockHash != blockHash {
if vLog.BlockHash != *blockHash {
log.Errorw("Block hash mismatch", "expected", blockHash.String(), "got", vLog.BlockHash.String())
return nil, nil, ErrBlockHashMismatchEvent
}
switch vLog.Topics[0] {
@@ -680,17 +572,17 @@ func (c *RollupClient) RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethC
}
rollupEvents.UpdateFeeAddToken = append(rollupEvents.UpdateFeeAddToken, updateFeeAddToken)
case logHermezWithdrawEvent:
var withdraw RollupEventWithdrawEvent
var withdraw RollupEventWithdraw
withdraw.Idx = new(big.Int).SetBytes(vLog.Topics[1][:]).Uint64()
withdraw.NumExitRoot = new(big.Int).SetBytes(vLog.Topics[2][:]).Uint64()
instantWithdraw := new(big.Int).SetBytes(vLog.Topics[3][:]).Uint64()
if instantWithdraw == 1 {
withdraw.InstantWithdraw = true
}
rollupEvents.WithdrawEvent = append(rollupEvents.WithdrawEvent, withdraw)
rollupEvents.Withdraw = append(rollupEvents.Withdraw, withdraw)
}
}
return &rollupEvents, &blockHash, nil
return &rollupEvents, blockHash, nil
}
// RollupForgeBatchArgs returns the arguments used in a ForgeBatch call in the

View File

@@ -70,7 +70,7 @@ func TestRollupRegisterTokensCount(t *testing.T) {
assert.Equal(t, big.NewInt(1), registerTokensCount)
}
func TestAddToken(t *testing.T) {
func TestRollupAddToken(t *testing.T) {
feeAddToken := big.NewInt(10)
// Addtoken ERC20Permit
registerTokensCount, err := rollupClient.RollupRegisterTokensCount()
@@ -731,7 +731,7 @@ func TestRollupForgeBatch2(t *testing.T) {
newStateRoot := new(big.Int)
newStateRoot.SetString("0", 10)
newExitRoot := new(big.Int)
newExitRoot.SetString("6442511778188868333499919207091562876207840300369859025739972956758642594045", 10)
newExitRoot.SetString("4694629460381124336935185586347620040847956843554725549791403956105308092690", 10)
args.NewLastIdx = int64(1000)
args.NewStRoot = newStateRoot
args.NewExitRoot = newExitRoot
@@ -760,11 +760,12 @@ func TestRollupWithdrawMerkleProof(t *testing.T) {
require.Nil(t, err)
var pkComp babyjub.PublicKeyComp
pkCompB, err := hex.DecodeString("9a0c13552c3a0b7b2b63ec4ab8a906b4af471ef3aa4463491ff08a0b489ac50f")
require.Nil(t, err)
pkCompL := common.SwapEndianness(pkCompB)
err = pkComp.UnmarshalText([]byte(hex.EncodeToString(pkCompL)))
pkCompBE, err := hex.DecodeString("adc3b754f8da621967b073a787bef8eec7052f2ba712b23af57d98f65beea8b2")
require.Nil(t, err)
pkCompLE := common.SwapEndianness(pkCompBE)
copy(pkComp[:], pkCompLE)
// err = pkComp.UnmarshalText([]byte(hex.EncodeToString(pkCompL)))
// require.Nil(t, err)
pk, err := pkComp.Decompress()
require.Nil(t, err)
@@ -774,13 +775,13 @@ func TestRollupWithdrawMerkleProof(t *testing.T) {
numExitRoot := int64(2)
fromIdx := int64(256)
amount := big.NewInt(10)
siblingBytes0, _ := new(big.Int).SetString("19508838618377323910556678335932426220272947530531646682154552299216398748115", 10)
require.Nil(t, err)
siblingBytes1, _ := new(big.Int).SetString("15198806719713909654457742294233381653226080862567104272457668857208564789571", 10)
require.Nil(t, err)
// siblingBytes0, _ := new(big.Int).SetString("19508838618377323910556678335932426220272947530531646682154552299216398748115", 10)
// require.Nil(t, err)
// siblingBytes1, _ := new(big.Int).SetString("15198806719713909654457742294233381653226080862567104272457668857208564789571", 10)
// require.Nil(t, err)
var siblings []*big.Int
siblings = append(siblings, siblingBytes0)
siblings = append(siblings, siblingBytes1)
// siblings = append(siblings, siblingBytes0)
// siblings = append(siblings, siblingBytes1)
instantWithdraw := true
_, err = rollupClientAux.RollupWithdrawMerkleProof(pk, tokenID, numExitRoot, fromIdx, amount, siblings, instantWithdraw)
@@ -789,7 +790,7 @@ func TestRollupWithdrawMerkleProof(t *testing.T) {
currentBlockNum, _ := rollupClient.client.EthCurrentBlock()
rollupEvents, _, _ := rollupClient.RollupEventsByBlock(currentBlockNum)
assert.Equal(t, uint64(fromIdx), rollupEvents.WithdrawEvent[0].Idx)
assert.Equal(t, instantWithdraw, rollupEvents.WithdrawEvent[0].InstantWithdraw)
assert.Equal(t, uint64(numExitRoot), rollupEvents.WithdrawEvent[0].NumExitRoot)
assert.Equal(t, uint64(fromIdx), rollupEvents.Withdraw[0].Idx)
assert.Equal(t, instantWithdraw, rollupEvents.Withdraw[0].InstantWithdraw)
assert.Equal(t, uint64(numExitRoot), rollupEvents.Withdraw[0].NumExitRoot)
}

View File

@@ -13,30 +13,11 @@ import (
"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"
WithdrawalDelayer "github.com/hermeznetwork/hermez-node/eth/contracts/withdrawdelayer"
"github.com/hermeznetwork/hermez-node/log"
)
// WDelayerConstants are the constants of the Withdrawal Delayer Smart Contract
type WDelayerConstants struct {
// Max Withdrawal Delay
MaxWithdrawalDelay uint64 `json:"maxWithdrawalDelay"`
// Max Emergency mode time
MaxEmergencyModeTime uint64 `json:"maxEmergencyModeTime"`
// HermezRollup smartcontract address
HermezRollup ethCommon.Address `json:"hermezRollup"`
}
// WDelayerVariables are the variables of the Withdrawal Delayer Smart Contract
type WDelayerVariables struct {
HermezRollupAddress ethCommon.Address `json:"hermezRollupAddress" meddler:"rollup_address"`
HermezGovernanceDAOAddress ethCommon.Address `json:"hermezGovernanceDAOAddress" meddler:"govdao_address"`
WhiteHackGroupAddress ethCommon.Address `json:"whiteHackGroupAddress" meddler:"whg_address"`
HermezKeeperAddress ethCommon.Address `json:"hermezKeeperAddress" meddler:"keeper_address"`
WithdrawalDelay uint64 `json:"withdrawalDelay" meddler:"withdrawal_delay"`
EmergencyModeStartingTime uint64 `json:"emergencyModeStartingTime" meddler:"emergency_start_time"`
EmergencyMode bool `json:"emergencyMode" meddler:"emergency_mode"`
}
// DepositState is the state of Deposit
type DepositState struct {
Amount *big.Int
@@ -137,6 +118,9 @@ type WDelayerInterface interface {
WDelayerDeposit(onwer, token ethCommon.Address, amount *big.Int) (*types.Transaction, error)
WDelayerWithdrawal(owner, token ethCommon.Address) (*types.Transaction, error)
WDelayerEscapeHatchWithdrawal(to, token ethCommon.Address, amount *big.Int) (*types.Transaction, error)
WDelayerEventsByBlock(blockNum int64) (*WDelayerEvents, *ethCommon.Hash, error)
WDelayerConstants() (*common.WDelayerConstants, error)
}
//
@@ -355,6 +339,28 @@ func (c *WDelayerClient) WDelayerEscapeHatchWithdrawal(to, token ethCommon.Addre
return tx, nil
}
// WDelayerConstants returns the Constants of the WDelayer Smart Contract
func (c *WDelayerClient) WDelayerConstants() (constants common.WDelayerConstants, err error) {
if err := c.client.Call(func(ec *ethclient.Client) error {
constants.MaxWithdrawalDelay, err = c.wdelayer.MAXWITHDRAWALDELAY(nil)
if err != nil {
return err
}
constants.MaxEmergencyModeTime, err = c.wdelayer.MAXEMERGENCYMODETIME(nil)
if err != nil {
return err
}
constants.HermezRollup, err = c.wdelayer.HermezRollupAddress(nil)
if err != nil {
return err
}
return err
}); err != nil {
return constants, err
}
return constants, nil
}
var (
logWDelayerDeposit = crypto.Keccak256Hash([]byte("Deposit(address,address,uint192,uint64)"))
logWDelayerWithdraw = crypto.Keccak256Hash([]byte("Withdraw(address,address,uint192)"))
@@ -392,6 +398,7 @@ func (c *WDelayerClient) WDelayerEventsByBlock(blockNum int64) (*WDelayerEvents,
}
for _, vLog := range logs {
if vLog.BlockHash != blockHash {
log.Errorw("Block hash mismatch", "expected", blockHash.String(), "got", vLog.BlockHash.String())
return nil, nil, ErrBlockHashMismatchEvent
}
switch vLog.Topics[0] {

View File

@@ -17,6 +17,15 @@ var wdelayerClientTest *WDelayerClient
var initWithdrawalDelay = big.NewInt(60)
var newWithdrawalDelay = big.NewInt(79)
var maxEmergencyModeTime = time.Hour * 24 * 7 * 26
var maxWithdrawalDelay = time.Hour * 24 * 7 * 2
func TestWDelayerConstants(t *testing.T) {
wDelayerConstants, err := wdelayerClientTest.WDelayerConstants()
require.Nil(t, err)
assert.Equal(t, uint64(maxWithdrawalDelay.Seconds()), wDelayerConstants.MaxWithdrawalDelay)
assert.Equal(t, uint64(maxEmergencyModeTime.Seconds()), wDelayerConstants.MaxEmergencyModeTime)
assert.Equal(t, hermezRollupTestAddressConst, wDelayerConstants.HermezRollup)
}
func TestWDelayerGetHermezGovernanceDAOAddress(t *testing.T) {
governanceAddress, err := wdelayerClientTest.WDelayerGetHermezGovernanceDAOAddress()
@@ -139,7 +148,8 @@ func TestWDelayerWithdrawal(t *testing.T) {
amount.SetString("1100000000000000000", 10)
_, err := wdelayerClientTest.WDelayerWithdrawal(auxAddressConst, tokenHEZAddressConst)
require.Contains(t, err.Error(), "WITHDRAWAL_NOT_ALLOWED")
addBlocks(newWithdrawalDelay.Int64(), ethClientDialURL)
addTime(float64(newWithdrawalDelay.Int64()), ethClientDialURL)
addBlock(ethClientDialURL)
_, err = wdelayerClientTest.WDelayerWithdrawal(auxAddressConst, tokenHEZAddressConst)
require.Nil(t, err)
currentBlockNum, _ := wdelayerClientTest.client.EthCurrentBlock()