194 Commits

Author SHA1 Message Date
arnaucube
6f1a44df02 TxSel avoid L1CoordTx for L2Tx that have a L1UserTx in the frozen queue
For the L2Txs of TransferToEthAddr & TransferToBJJ for a not-yet
existing accounts, in the TxSelector check if L2Tx receiver account will
be created by a L1UserFrozenTxs (in the next batch, the current frozen
queue). In that case, the L2Tx will be discarded at the current batch,
even if there is an AccountCreationAuth for the account, as there is a
L1UserTx in the frozen queue that will create the receiver Account.  The
L2Tx is discarded to avoid the Coordinator creating a new
L1CoordinatorTx to create the receiver account, which will be also
created in the next batch from the L1UserFrozenTx, ending with the user
having 2 different accounts for the same TokenID.
The double account creation is supported by the Hermez zkRollup
specification, but it was decided to mitigate it at the TxSelector level
for the explained cases.
2021-03-31 13:02:51 +02:00
arnau
6c6d1ea7b8 Merge pull request #631 from hermeznetwork/feature/serveapicli2
Allow serving API only via new cli command
2021-03-15 15:41:36 +01:00
Eduard S
d625cc9287 Allow serving API only via new cli command
- Add new command to the cli/node: `serveapi` that alows serving the API just
  by connecting to the PostgreSQL database.  The mode flag should me passed in
  order to select whether we are connecting to a synchronizer database or a
  coordinator database.  If `coord` is chosen as mode, the coordinator
  endpoints can be activated in order to allow inserting l2txs and
  authorizations into the L2DB.

Summary of the implementation details
- New SQL table with 3 columns (plus `item_id` pk).  The table only contains a
  single row with `item_id` = 1.  Columns:
    - state: historydb.StateAPI in JSON.  This is the struct that is served via
      the `/state` API endpoint.  The node will periodically update this struct
      and store it int he DB.  The api server will query it from the DB to
      serve it.
    - config: historydb.NodeConfig in JSON.  This struct contains node
      configuration parameters that the API needs to be aware of.  It's updated
      once every time the node starts.
    - constants: historydb.Constants in JSON.  This struct contains all the
      hermez network constants gathered via the ethereum client by the node.
      It's written once every time the node starts.
- The HistoryDB contains methods to get and update each one of these columns
  individually.
- The HistoryDB contains all methods that query the DB and prepare objects that
  will appear in the StateAPI endpoint.
- The configuration used in for the `serveapi` cli/node command is defined in
  `config.APIServer`, and is a subset of `node.Config` in order to allow
  reusing the same configuration file of the node if desired.
- A new object is introduced in the api: `StateAPIUpdater`, which contains all
  the necessary information to update the StateAPI in the DB periodically by
  the node.

- Moved the types `SCConsts`, `SCVariables` and `SCVariablesPtr` from
  `syncrhonizer` to `common` for convenience.
2021-03-15 15:35:20 +01:00
arnaucube
5d8579a609 Fix TxSel discard tx when ProcessL2Tx gives err
Refactor getL1L2TxSelection, which fixes some problems for certain
combinations of txs.
2021-03-15 13:36:15 +01:00
Eduard S
b724348ddc Merge pull request #630 from hermeznetwork/feature/update-poseidon
Update to last Poseidon & go-merkletree versions
2021-03-10 12:18:59 +01:00
arnaucube
a39d880fd4 Update to last Poseidon & go-merkletree versions
Update to last Poseidon (go-iden3-crypto) & go-merkletree versions,
update the affected test vectors, and check ZKInputs compatibility with
last version of circuits.

Update to last Poseidon version (which includes the changes of the
reference implementation from
26ddaa91db)

Compatible with update at circomlib
(cf853c1cc9)
2021-03-09 14:43:08 +01:00
Eduard S
7305a8d7f1 Merge pull request #615 from hermeznetwork/fix/l2txs-all-tonull
API doesnt accept pool txs without to
2021-03-08 15:24:35 +01:00
arnaubennassar
81690039da API doesnt accept pool txs without to 2021-03-08 15:16:49 +01:00
Eduard S
661da0d53e Merge pull request #619 from hermeznetwork/fix/floor-float40-helper
Fix NewFloat40Floor helper method
2021-03-08 15:16:45 +01:00
arnau
d0ace0773d Merge pull request #616 from hermeznetwork/fix/typos-and-lint
fix some code typos
2021-03-08 14:35:30 +01:00
arnaucube
4fd757a03c Fix NewFloat40Floor helper method 2021-03-08 14:32:05 +01:00
arnaubennassar
dcd40f1943 Fix tx signature when toEthAddr starts with 0x0 2021-03-05 17:21:14 +01:00
Danilo Pantani
7833cb11de fix some code and comment typos 2021-03-04 18:26:00 -03:00
arnaucube
dfd49164f4 Add NewFloor40Floor helper method
Also added tracerr.Wrap(...) to missing places.
2021-03-03 11:58:17 +01:00
arnaucube
97fdbfe037 Extend TxProcessor documentation and explanation 2021-03-02 14:13:45 +01:00
arnaucube
93b7866d3e Add lll to linter checks
Updated:
	batchbuilder
	common
	coordinator
	db/statedb
	eth
	log
	node
	priceupdater
	prover
	synchronizer
	test/*
	txprocessor
	txselector

Pending (once
https://github.com/hermeznetwork/hermez-node/tree/feature/serveapicli is
merged to master):
	Update golangci-lint version to v1.37.1
	api
	apitypes
	cli
	config
	db/historydb
	db/l2db
2021-03-01 18:02:10 +01:00
arnaucube
56ffea2190 Update L1CoordinatorTxFromBytes to EIP712 2021-02-28 10:56:51 +01:00
arnaucube
60023e4574 Update AccCreationAuth signature hash to EIP-712
Compatible with `hermeznetwork/contracts` commit: `67726208723a40f2251953aaabf4d2b6221f8b13`
Compatible with `hermeznetwork/commonjs` commit: `dee266fb036a64bebc65756ebd5f0361929c110d`
2021-02-26 13:46:35 +01:00
arnaubennassar
4acfeb0ad9 Add API metric for time to forge L1 tx 2021-02-25 13:06:26 +01:00
Eduard S
3706ddb2fb Add minPriceUSD in L2DB, check maxTxs atomically
- Add config parameter `Coordinator.L2DB.MinPriceUSD` which allows rejecting
  txs to the pool that have a fee lower than the minimum.
- In pool tx insertion, checking the number of pending txs atomically with the
  insertion to avoid data races leading to more than MaxTxs pending txs in the
  pool.
2021-02-22 16:45:15 +01:00
Eduard S
ed4d39fcd1 Add account_update SQL table with balances and nonces 2021-02-19 13:16:14 +01:00
Eduard S
f0e79f3d55 Update coordinator to work better under real net
- cli / node
    - Update handler of SIGINT so that after 3 SIGINTs, the process terminates
      unconditionally
- coordinator
    - Store stats without pointer
    - In all functions that send a variable via channel, check for context done
      to avoid deadlock (due to no process reading from the channel, which has
      no queue) when the node is stopped.
    - Abstract `canForge` so that it can be used outside of the `Coordinator`
    - In `canForge` check the blockNumber in current and next slot.
    - Update tests due to smart contract changes in slot handling, and minimum
      bid defaults
    - TxManager
        - Add consts, vars and stats to allow evaluating `canForge`
        - Add `canForge` method (not used yet)
        - Store batch and nonces status (last success and last pending)
        - Track nonces internally instead of relying on the ethereum node (this
          is required to work with ganache when there are pending txs)
        - Handle the (common) case of the receipt not being found after the tx
          is sent.
        - Don't start the main loop until we get an initial messae fo the stats
          and vars (so that in the loop the stats and vars are set to
          synchronizer values)
        - When a tx fails, check and discard all the failed transactions before
          sending the message to stop the pipeline.  This will avoid sending
          consecutive messages of stop the pipeline when multiple txs are
          detected to be failed consecutively.  Also, future txs of the same
          pipeline after a discarded txs are discarded, and their nonces reused.
        - Robust handling of nonces:
            - If geth returns nonce is too low, increase it
            - If geth returns nonce too hight, decrease it
            - If geth returns underpriced, increase gas price
            - If geth returns replace underpriced, increase gas price
        - Add support for resending transactions after a timeout
        - Store `BatchInfos` in a queue
    - Pipeline
        - When an error is found, stop forging batches and send a message to the
          coordinator to stop the pipeline with information of the failed batch
          number so that in a restart, non-failed batches are not repated.
        - When doing a reset of the stateDB, if possible reset from the local
          checkpoint instead of resetting from the synchronizer.  This allows
          resetting from a batch that is valid but not yet sent / synced.
    - Every time a pipeline is started, assign it a number from a counter.  This
      allows the TxManager to ignore batches from stopped pipelines, via a
      message sent by the coordinator.
    - Avoid forging when we haven't reached the rollup genesis block number.
    - Add config parameter `StartSlotBlocksDelay`: StartSlotBlocksDelay is the
      number of blocks of delay to wait before starting the pipeline when we
      reach a slot in which we can forge.
    - When detecting a reorg, only reset the pipeline if the batch from which
      the pipeline started changed and wasn't sent by us.
    - Add config parameter `ScheduleBatchBlocksAheadCheck`:
      ScheduleBatchBlocksAheadCheck is the number of blocks ahead in which the
      forger address is checked to be allowed to forge (apart from checking the
      next block), used to decide when to stop scheduling new batches (by
      stopping the pipeline).  For example, if we are at block 10 and
      ScheduleBatchBlocksAheadCheck is 5, eventhough at block 11 we canForge,
      the pipeline will be stopped if we can't forge at block 15.  This value
      should be the expected number of blocks it takes between scheduling a
      batch and having it mined.
    - Add config parameter `SendBatchBlocksMarginCheck`:
      SendBatchBlocksMarginCheck is the number of margin blocks ahead in which
      the coordinator is also checked to be allowed to forge, apart from the
      next block; used to decide when to stop sending batches to the smart
      contract.  For example, if we are at block 10 and
      SendBatchBlocksMarginCheck is 5, eventhough at block 11 we canForge, the
      batch will be discarded if we can't forge at block 15.
    - Add config parameter `TxResendTimeout`: TxResendTimeout is the timeout
      after which a non-mined ethereum transaction will be resent (reusing the
      nonce) with a newly calculated gas price
    - Add config parameter `MaxGasPrice`: MaxGasPrice is the maximum gas price
      allowed for ethereum transactions
    - Add config parameter `NoReuseNonce`: NoReuseNonce disables reusing nonces
      of pending transactions for new replacement transactions.  This is useful
      for testing with Ganache.
    - Extend BatchInfo with more useful information for debugging

- eth / ethereum client
    - Add necessary methods to create the auth object for transactions manually
      so that we can set the nonce, gas price, gas limit, etc manually
    - Update `RollupForgeBatch` to take an auth object as input (so that the
      coordinator can set parameters manually)
- synchronizer
    - In stats, add `NextSlot`
    - In stats, store full last batch instead of just last batch number
    - Instead of calculating a nextSlot from scratch every time, update the
      current struct (only updating the forger info if we are Synced)
    - Afer every processed batch, check that the calculated StateDB MTRoot
      matches the StateRoot found in the forgeBatch event.
2021-02-16 16:10:23 +01:00
arnaucube
1d0abe438f Remove Float16 related files & minor typos fixes 2021-02-15 12:09:08 +01:00
arnaucube
6a01c0ac14 Update ZKInputs test vectors with float40 & other
- Add AmountF new parameter to ZKInputs
- Update ZKInputs test vectors with float40 checked with circom circuits
- Small fix at eth/rollup.go with lenL1L2TxsBytes with new length of
Float40
2021-02-12 16:40:36 +01:00
arnaucube
63151a285c Migrate all packages to use Float40
Migrate all packages to use Float40 & Add more test vectors at common
2021-02-12 14:27:07 +01:00
arnaucube
52d4197330 Add Float40 methods
This commit adds Float40 related methods, and keeps the Float16 version
which will be deleted in a near future once the Float40 migration is
ready.
2021-02-12 14:27:07 +01:00
Eduard S
c7e6267189 Fix txselector TransferToBJJ behaviour 2021-02-11 18:19:29 +01:00
arnaucube
a8f6891aea Add PoolL2Tx.Info about the status of the tx
PoolL2Tx.Info contains information about the status & State of the
transaction. As for example, if the Tx has not been selected in the last
batch due not enough Balance at the Sender account, this reason would
appear at this parameter.
This will help the client (wallet, batchexplorer, etc) to reason why a
L2Tx is not selected in the forged batches.
2021-02-03 13:03:30 +01:00
Eduard S
510d5c548c Merge pull request #520 from hermeznetwork/feature/txid-keccak256
Update TxID to use eth Keccak256
2021-02-01 16:33:37 +01:00
Alberto Elias
cea3af4291 Merge pull request #518 from hermeznetwork/fix/api-recommended-fee
Fix api resopnse format for recommended fee
2021-02-01 15:04:15 +00:00
arnaucube
c1cd37913f Update TxID to use eth Keccak256
- Update TxID to use eth Keccak256
- Added more tests to L2Tx TxID calculation to check compatibility with
js version from https://github.com/hermeznetwork/hermezjs/pull/57
2021-02-01 16:01:55 +01:00
Arnau B
dd1657847e Fix api resopnse format for recommended fee 2021-02-01 13:40:24 +01:00
Eduard S
90fe98d15c Update contracts and get verifiersLen from SC 2021-01-29 17:46:14 +01:00
arnaucube
aade6220d4 Update TxID to avoid collisions on DB (fix #503) 2021-01-29 11:38:22 +01:00
arnaucube
a899f43914 Add TokenID to L2Tx
L2Tx.TokenID is not on the data obtained by the Synchronizer from the
blockchain, but is set by the TxProcessor when processing the
transactions in the StateDB.
2021-01-27 12:40:09 +01:00
Eduard S
ec194d5066 Set l1tx.EffectiveFromIdx in TxProcessor and til 2021-01-13 18:20:47 +01:00
Eduard S
75f068baa8 Fix ChainID in zkInputs empty TxCmpData
Test TxProcessor zkInputs against a real proof server
2021-01-13 12:41:00 +01:00
ToniRamirezM
170da500db Remove big.Int from state API 2021-01-12 18:37:56 +01:00
arnaucube
b59710a149 ZKInput with L2Txs compatible with circom circuits
- Til
  - update Til users BJJ key generation for better js tests
    compatibility
- Common
  - PoolL2Tx to L2Tx use AuxToIdx in case that ToIdx is 0
  - Update ZKInputs parameter descriptions
- TxProcessor
  - Fix AccumulatedFees in case that there is no CoordIdx for that token
  - Fix zki.NewExit usage
  - Use same order for AccumulatedFees & FeeIdx & FeePlanTokens
  - Add Nonce usage to ExitLeafs
  - Update TestZKInput6 and check its compatibility with circom Hermez
circuits
2021-01-11 11:23:04 +01:00
Eduard S
a79cb4edfd Update node and apply some fixes
- Node
	- Load Coordinator Fee Account from config
		- Sign the AccountCreationMsg to generate the
		  AccountCreationAuth
		- Resolve #465
	- Wait for synchronizer termination before stopping coordinator to avoid
	  getting stuck when closing in the following case:
		- The coordinator stops reading the synchronizer msg channel,
		  and the node gets stuck sending a message to that channel.
- Common
	- Move account creation auth signature code to common.
	- Update RollupConstInputSHAConstantBytes
- Coordinator
	- Set batch status in the debug file
	- Propagate SCVariables on reorg
	- Pipeline: Get SCVariables updates
		- Resolve #457
	- Fix off by 1 error in Pipeline.shouldL1L2Batch() (which shouldn't have
	  caused any problem, but it was not right)
- KVDB
	- Delete future checkpoints after reset
	- In `ResetFromSynchronizer`, remove all checkpoints first, and follow
	  the same logic as `reset()`.
- Cli
	- Add command to generate a BabyJubJub key pair (to be used for the
	  Coordinator Fee Account)
- Node
	- Adjust example config `Coordinator.L1BatchTimeoutPerc` to avoid
	  missing the L1Batch deadline with the following setup:
		- a block is mined every 2 seconds
		- single proof server that takes 2 seconds to calculate a proof
- TxProcessor
	- Close temporary pebble used for the exit tree after usage.
		- Resolve #463
2021-01-07 16:09:28 +01:00
arnaucube
bf5ab12d0e Update Account.PublicKey to Account.BJJ
Update account.PublicKey to account.BJJ for naming consistency with the rest of the code
2021-01-05 15:34:50 +01:00
arnaucube
48bdec1397 Fix TxProcessor TokenID use &updates at Til&Common
- Til
  - tests that were using `til.SetBlockchainMinimumFlow0` have been
updated, as now the L1CoordinatorTxs are placed simulating TxSelector
creation (when needed, not before)
  - Add `EthSk` to `tc.User` to allow to sign `AccoutCreationAuths` at
the tests flows
- TxProcessor
  - for L2Txs get TokenID from tx.FromIdx Account.TokenID instead than
  - update tests vectors for new values
from tx.TokenID (which not always is set)
- Common
  - move TxIDsFromL2Txs & TxIDsFromPoolL2Txs from `coordinator` to
`common` to allow usage from other packages
2021-01-04 15:28:04 +01:00
Eduard S
18c854fbaa Add circuit configuration to node config
- Remove MaxL1CoordTxs parameter from the TxSelector because this parameter
  doesn't exist
- Use ChainID in l1tx byte encoding
- Pass txprocessor configuration to batch builder via an existing parameter
2020-12-31 10:44:19 +01:00
arnaucube
ca5870e3ba Update ExitProofs-Siblings padding 2020-12-30 10:44:34 +01:00
Eduard S
890b94a41a Merge pull request #428 from hermeznetwork/fix/api-next-forgers
Fix next forgers api response
2020-12-29 15:32:02 +01:00
Arnau B
6058d3c41a Fix next forgers api response 2020-12-29 15:17:55 +01:00
Eduard S
025b56c8c3 Merge pull request #425 from hermeznetwork/fix/zki-ntx
Fix ZKI NTx for MaxTx
2020-12-28 12:17:51 +01:00
arnaucube
cf199fd832 Fix ZKI NTx for MaxTx
On the Circuits uses the name `nTx` (and on the tests `maxTx`), but
Contracts `maxTx`. On Go we had both variables, but really only used
one, now at Go we use `MaxTx` to refer to the maximum number of
transactions.
2020-12-28 11:26:47 +01:00
arnaucube
ca010275e1 AccountCreationAuth compatible with js implementation 2020-12-28 11:16:00 +01:00
arnaucube
8615a462ab Update AccountCreationAuth & fix auth.HashToSign
- Fix AccountCreationAuth.HashToSign (was using `[]byte("0x...")`, which
uses the bytes of the string. Now uses the bytearray of the compressed
BJJ public key (compatible with js implementation))
- Update AccountCreationAuth to last specification (add to hash
parameters ChainID & HermezAddress)
- Add missing test to AccountCreationAuth
2020-12-24 10:41:35 +01:00