You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1462 lines
46 KiB

Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
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.
3 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
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.
3 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
  1. package historydb
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "math"
  6. "math/big"
  7. "os"
  8. "strings"
  9. "testing"
  10. "time"
  11. ethCommon "github.com/ethereum/go-ethereum/common"
  12. "github.com/hermeznetwork/hermez-node/common"
  13. dbUtils "github.com/hermeznetwork/hermez-node/db"
  14. "github.com/hermeznetwork/hermez-node/log"
  15. "github.com/hermeznetwork/hermez-node/test"
  16. "github.com/hermeznetwork/hermez-node/test/til"
  17. "github.com/hermeznetwork/tracerr"
  18. "github.com/stretchr/testify/assert"
  19. "github.com/stretchr/testify/require"
  20. )
  21. var historyDB *HistoryDB
  22. var historyDBWithACC *HistoryDB
  23. // In order to run the test you need to run a Posgres DB with
  24. // a database named "history" that is accessible by
  25. // user: "hermez"
  26. // pass: set it using the env var POSTGRES_PASS
  27. // This can be achieved by running: POSTGRES_PASS=your_strong_pass && sudo docker run --rm --name hermez-db-test -p 5432:5432 -e POSTGRES_DB=history -e POSTGRES_USER=hermez -e POSTGRES_PASSWORD=$POSTGRES_PASS -d postgres && sleep 2s && sudo docker exec -it hermez-db-test psql -a history -U hermez -c "CREATE DATABASE l2;"
  28. // After running the test you can stop the container by running: sudo docker kill hermez-db-test
  29. // If you already did that for the L2DB you don't have to do it again
  30. func TestMain(m *testing.M) {
  31. // init DB
  32. pass := os.Getenv("POSTGRES_PASS")
  33. db, err := dbUtils.InitSQLDB(5432, "localhost", "hermez", pass, "hermez")
  34. if err != nil {
  35. panic(err)
  36. }
  37. historyDB = NewHistoryDB(db, db, nil)
  38. if err != nil {
  39. panic(err)
  40. }
  41. apiConnCon := dbUtils.NewAPICnnectionController(1, time.Second)
  42. historyDBWithACC = NewHistoryDB(db, db, apiConnCon)
  43. // Run tests
  44. result := m.Run()
  45. // Close DB
  46. if err := db.Close(); err != nil {
  47. log.Error("Error closing the history DB:", err)
  48. }
  49. os.Exit(result)
  50. }
  51. func TestBlocks(t *testing.T) {
  52. var fromBlock, toBlock int64
  53. fromBlock = 0
  54. toBlock = 7
  55. // Reset DB
  56. test.WipeDB(historyDB.DB())
  57. // Generate blocks using til
  58. set1 := `
  59. Type: Blockchain
  60. // block 0 is stored as default in the DB
  61. // block 1 does not exist
  62. > block // blockNum=2
  63. > block // blockNum=3
  64. > block // blockNum=4
  65. > block // blockNum=5
  66. > block // blockNum=6
  67. `
  68. tc := til.NewContext(uint16(0), 1)
  69. blocks, err := tc.GenerateBlocks(set1)
  70. require.NoError(t, err)
  71. // Save timestamp of a block with UTC and change it without UTC
  72. timestamp := time.Now().Add(time.Second * 13)
  73. blocks[fromBlock].Block.Timestamp = timestamp
  74. // Insert blocks into DB
  75. for i := 0; i < len(blocks); i++ {
  76. err := historyDB.AddBlock(&blocks[i].Block)
  77. assert.NoError(t, err)
  78. }
  79. // Add block 0 to the generated blocks
  80. blocks = append(
  81. []common.BlockData{{Block: test.Block0}}, //nolint:gofmt
  82. blocks...,
  83. )
  84. // Get all blocks from DB
  85. fetchedBlocks, err := historyDB.getBlocks(fromBlock, toBlock)
  86. assert.Equal(t, len(blocks), len(fetchedBlocks))
  87. // Compare generated vs getted blocks
  88. assert.NoError(t, err)
  89. for i := range fetchedBlocks {
  90. assertEqualBlock(t, &blocks[i].Block, &fetchedBlocks[i])
  91. }
  92. // Compare saved timestamp vs getted
  93. nameZoneUTC, offsetUTC := timestamp.UTC().Zone()
  94. zoneFetchedBlock, offsetFetchedBlock := fetchedBlocks[fromBlock].Timestamp.Zone()
  95. assert.Equal(t, nameZoneUTC, zoneFetchedBlock)
  96. assert.Equal(t, offsetUTC, offsetFetchedBlock)
  97. // Get blocks from the DB one by one
  98. for i := int64(2); i < toBlock; i++ { // avoid block 0 for simplicity
  99. fetchedBlock, err := historyDB.GetBlock(i)
  100. assert.NoError(t, err)
  101. assertEqualBlock(t, &blocks[i-1].Block, fetchedBlock)
  102. }
  103. // Get last block
  104. lastBlock, err := historyDB.GetLastBlock()
  105. assert.NoError(t, err)
  106. assertEqualBlock(t, &blocks[len(blocks)-1].Block, lastBlock)
  107. }
  108. func assertEqualBlock(t *testing.T, expected *common.Block, actual *common.Block) {
  109. assert.Equal(t, expected.Num, actual.Num)
  110. assert.Equal(t, expected.Hash, actual.Hash)
  111. assert.Equal(t, expected.Timestamp.Unix(), actual.Timestamp.Unix())
  112. }
  113. func TestBatches(t *testing.T) {
  114. // Reset DB
  115. test.WipeDB(historyDB.DB())
  116. // Generate batches using til (and blocks for foreign key)
  117. set := `
  118. Type: Blockchain
  119. AddToken(1) // Will have value in USD
  120. AddToken(2) // Will NOT have value in USD
  121. CreateAccountDeposit(1) A: 2000
  122. CreateAccountDeposit(2) A: 2000
  123. CreateAccountDeposit(1) B: 1000
  124. CreateAccountDeposit(2) B: 1000
  125. > batchL1
  126. > batchL1
  127. Transfer(1) A-B: 100 (5)
  128. Transfer(2) B-A: 100 (199)
  129. > batch // batchNum=2, L2 only batch, forges transfers (mixed case of with(out) USD value)
  130. > block
  131. Transfer(1) A-B: 100 (5)
  132. > batch // batchNum=3, L2 only batch, forges transfer (with USD value)
  133. Transfer(2) B-A: 100 (199)
  134. > batch // batchNum=4, L2 only batch, forges transfer (without USD value)
  135. > block
  136. `
  137. tc := til.NewContext(uint16(0), common.RollupConstMaxL1UserTx)
  138. tilCfgExtra := til.ConfigExtra{
  139. BootCoordAddr: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  140. CoordUser: "A",
  141. }
  142. blocks, err := tc.GenerateBlocks(set)
  143. require.NoError(t, err)
  144. err = tc.FillBlocksExtra(blocks, &tilCfgExtra)
  145. require.NoError(t, err)
  146. // Insert to DB
  147. batches := []common.Batch{}
  148. tokensValue := make(map[common.TokenID]float64)
  149. lastL1TxsNum := new(int64)
  150. lastL1BatchBlockNum := int64(0)
  151. for _, block := range blocks {
  152. // Insert block
  153. assert.NoError(t, historyDB.AddBlock(&block.Block))
  154. // Insert tokens
  155. for i, token := range block.Rollup.AddedTokens {
  156. assert.NoError(t, historyDB.AddToken(&token)) //nolint:gosec
  157. if i%2 != 0 {
  158. // Set value to the token
  159. value := (float64(i) + 5) * 5.389329
  160. assert.NoError(t, historyDB.UpdateTokenValue(token.Symbol, value))
  161. tokensValue[token.TokenID] = value / math.Pow(10, float64(token.Decimals))
  162. }
  163. }
  164. // Combine all generated batches into single array
  165. for _, batch := range block.Rollup.Batches {
  166. batches = append(batches, batch.Batch)
  167. forgeTxsNum := batch.Batch.ForgeL1TxsNum
  168. if forgeTxsNum != nil && (lastL1TxsNum == nil || *lastL1TxsNum < *forgeTxsNum) {
  169. *lastL1TxsNum = *forgeTxsNum
  170. lastL1BatchBlockNum = batch.Batch.EthBlockNum
  171. }
  172. }
  173. }
  174. // Insert batches
  175. assert.NoError(t, historyDB.AddBatches(batches))
  176. // Set expected total fee
  177. for _, batch := range batches {
  178. total := .0
  179. for tokenID, amount := range batch.CollectedFees {
  180. af := new(big.Float).SetInt(amount)
  181. amountFloat, _ := af.Float64()
  182. total += tokensValue[tokenID] * amountFloat
  183. }
  184. batch.TotalFeesUSD = &total
  185. }
  186. // Get batches from the DB
  187. fetchedBatches, err := historyDB.GetBatches(0, common.BatchNum(len(batches)+1))
  188. assert.NoError(t, err)
  189. assert.Equal(t, len(batches), len(fetchedBatches))
  190. for i, fetchedBatch := range fetchedBatches {
  191. assert.Equal(t, batches[i], fetchedBatch)
  192. }
  193. // Test GetLastBatchNum
  194. fetchedLastBatchNum, err := historyDB.GetLastBatchNum()
  195. assert.NoError(t, err)
  196. assert.Equal(t, batches[len(batches)-1].BatchNum, fetchedLastBatchNum)
  197. // Test GetLastBatch
  198. fetchedLastBatch, err := historyDB.GetLastBatch()
  199. assert.NoError(t, err)
  200. assert.Equal(t, &batches[len(batches)-1], fetchedLastBatch)
  201. // Test GetLastL1TxsNum
  202. fetchedLastL1TxsNum, err := historyDB.GetLastL1TxsNum()
  203. assert.NoError(t, err)
  204. assert.Equal(t, lastL1TxsNum, fetchedLastL1TxsNum)
  205. // Test GetLastL1BatchBlockNum
  206. fetchedLastL1BatchBlockNum, err := historyDB.GetLastL1BatchBlockNum()
  207. assert.NoError(t, err)
  208. assert.Equal(t, lastL1BatchBlockNum, fetchedLastL1BatchBlockNum)
  209. // Test GetBatch
  210. fetchedBatch, err := historyDB.GetBatch(1)
  211. require.NoError(t, err)
  212. assert.Equal(t, &batches[0], fetchedBatch)
  213. _, err = historyDB.GetBatch(common.BatchNum(len(batches) + 1))
  214. assert.Equal(t, sql.ErrNoRows, tracerr.Unwrap(err))
  215. }
  216. func TestBids(t *testing.T) {
  217. const fromBlock int64 = 1
  218. const toBlock int64 = 5
  219. // Prepare blocks in the DB
  220. blocks := setTestBlocks(fromBlock, toBlock)
  221. // Generate fake coordinators
  222. const nCoords = 5
  223. coords := test.GenCoordinators(nCoords, blocks)
  224. err := historyDB.AddCoordinators(coords)
  225. assert.NoError(t, err)
  226. // Generate fake bids
  227. const nBids = 20
  228. bids := test.GenBids(nBids, blocks, coords)
  229. err = historyDB.AddBids(bids)
  230. assert.NoError(t, err)
  231. // Fetch bids
  232. fetchedBids, err := historyDB.GetAllBids()
  233. assert.NoError(t, err)
  234. // Compare fetched bids vs generated bids
  235. for i, bid := range fetchedBids {
  236. assert.Equal(t, bids[i], bid)
  237. }
  238. }
  239. func TestTokens(t *testing.T) {
  240. const fromBlock int64 = 1
  241. const toBlock int64 = 5
  242. // Prepare blocks in the DB
  243. blocks := setTestBlocks(fromBlock, toBlock)
  244. // Generate fake tokens
  245. const nTokens = 5
  246. tokens, ethToken := test.GenTokens(nTokens, blocks)
  247. err := historyDB.AddTokens(tokens)
  248. assert.NoError(t, err)
  249. tokens = append([]common.Token{ethToken}, tokens...)
  250. // Fetch tokens
  251. fetchedTokens, err := historyDB.GetTokensTest()
  252. assert.NoError(t, err)
  253. // Compare fetched tokens vs generated tokens
  254. // All the tokens should have USDUpdate setted by the DB trigger
  255. for i, token := range fetchedTokens {
  256. assert.Equal(t, tokens[i].TokenID, token.TokenID)
  257. assert.Equal(t, tokens[i].EthBlockNum, token.EthBlockNum)
  258. assert.Equal(t, tokens[i].EthAddr, token.EthAddr)
  259. assert.Equal(t, tokens[i].Name, token.Name)
  260. assert.Equal(t, tokens[i].Symbol, token.Symbol)
  261. assert.Nil(t, token.USD)
  262. assert.Nil(t, token.USDUpdate)
  263. }
  264. // Update token value
  265. for i, token := range tokens {
  266. value := 1.01 * float64(i)
  267. assert.NoError(t, historyDB.UpdateTokenValue(token.Symbol, value))
  268. }
  269. // Fetch tokens
  270. fetchedTokens, err = historyDB.GetTokensTest()
  271. assert.NoError(t, err)
  272. // Compare fetched tokens vs generated tokens
  273. // All the tokens should have USDUpdate setted by the DB trigger
  274. for i, token := range fetchedTokens {
  275. value := 1.01 * float64(i)
  276. assert.Equal(t, value, *token.USD)
  277. nameZone, offset := token.USDUpdate.Zone()
  278. assert.Equal(t, "UTC", nameZone)
  279. assert.Equal(t, 0, offset)
  280. }
  281. }
  282. func TestTokensUTF8(t *testing.T) {
  283. // Reset DB
  284. test.WipeDB(historyDB.DB())
  285. const fromBlock int64 = 1
  286. const toBlock int64 = 5
  287. // Prepare blocks in the DB
  288. blocks := setTestBlocks(fromBlock, toBlock)
  289. // Generate fake tokens
  290. const nTokens = 5
  291. tokens, ethToken := test.GenTokens(nTokens, blocks)
  292. nonUTFTokens := make([]common.Token, len(tokens)+1)
  293. // Force token.name and token.symbol to be non UTF-8 Strings
  294. for i, token := range tokens {
  295. token.Name = fmt.Sprint("NON-UTF8-NAME-\xc5-", i)
  296. token.Symbol = fmt.Sprint("S-\xc5-", i)
  297. tokens[i] = token
  298. nonUTFTokens[i] = token
  299. }
  300. err := historyDB.AddTokens(tokens)
  301. assert.NoError(t, err)
  302. // Work with nonUTFTokens as tokens one gets updated and non UTF-8 characters are lost
  303. nonUTFTokens = append([]common.Token{ethToken}, nonUTFTokens...)
  304. // Fetch tokens
  305. fetchedTokens, err := historyDB.GetTokensTest()
  306. assert.NoError(t, err)
  307. // Compare fetched tokens vs generated tokens
  308. // All the tokens should have USDUpdate setted by the DB trigger
  309. for i, token := range fetchedTokens {
  310. assert.Equal(t, nonUTFTokens[i].TokenID, token.TokenID)
  311. assert.Equal(t, nonUTFTokens[i].EthBlockNum, token.EthBlockNum)
  312. assert.Equal(t, nonUTFTokens[i].EthAddr, token.EthAddr)
  313. assert.Equal(t, strings.ToValidUTF8(nonUTFTokens[i].Name, " "), token.Name)
  314. assert.Equal(t, strings.ToValidUTF8(nonUTFTokens[i].Symbol, " "), token.Symbol)
  315. assert.Nil(t, token.USD)
  316. assert.Nil(t, token.USDUpdate)
  317. }
  318. // Update token value
  319. for i, token := range nonUTFTokens {
  320. value := 1.01 * float64(i)
  321. assert.NoError(t, historyDB.UpdateTokenValue(token.Symbol, value))
  322. }
  323. // Fetch tokens
  324. fetchedTokens, err = historyDB.GetTokensTest()
  325. assert.NoError(t, err)
  326. // Compare fetched tokens vs generated tokens
  327. // All the tokens should have USDUpdate setted by the DB trigger
  328. for i, token := range fetchedTokens {
  329. value := 1.01 * float64(i)
  330. assert.Equal(t, value, *token.USD)
  331. nameZone, offset := token.USDUpdate.Zone()
  332. assert.Equal(t, "UTC", nameZone)
  333. assert.Equal(t, 0, offset)
  334. }
  335. }
  336. func TestAccounts(t *testing.T) {
  337. const fromBlock int64 = 1
  338. const toBlock int64 = 5
  339. // Prepare blocks in the DB
  340. blocks := setTestBlocks(fromBlock, toBlock)
  341. // Generate fake tokens
  342. const nTokens = 5
  343. tokens, ethToken := test.GenTokens(nTokens, blocks)
  344. err := historyDB.AddTokens(tokens)
  345. assert.NoError(t, err)
  346. tokens = append([]common.Token{ethToken}, tokens...)
  347. // Generate fake batches
  348. const nBatches = 10
  349. batches := test.GenBatches(nBatches, blocks)
  350. err = historyDB.AddBatches(batches)
  351. assert.NoError(t, err)
  352. // Generate fake accounts
  353. const nAccounts = 3
  354. accs := test.GenAccounts(nAccounts, 0, tokens, nil, nil, batches)
  355. err = historyDB.AddAccounts(accs)
  356. assert.NoError(t, err)
  357. // Fetch accounts
  358. fetchedAccs, err := historyDB.GetAllAccounts()
  359. assert.NoError(t, err)
  360. // Compare fetched accounts vs generated accounts
  361. for i, acc := range fetchedAccs {
  362. accs[i].Balance = nil
  363. assert.Equal(t, accs[i], acc)
  364. }
  365. // Test AccountBalances
  366. accUpdates := make([]common.AccountUpdate, len(accs))
  367. for i, acc := range accs {
  368. accUpdates[i] = common.AccountUpdate{
  369. EthBlockNum: batches[acc.BatchNum-1].EthBlockNum,
  370. BatchNum: acc.BatchNum,
  371. Idx: acc.Idx,
  372. Nonce: common.Nonce(i),
  373. Balance: big.NewInt(int64(i)),
  374. }
  375. }
  376. err = historyDB.AddAccountUpdates(accUpdates)
  377. require.NoError(t, err)
  378. fetchedAccBalances, err := historyDB.GetAllAccountUpdates()
  379. require.NoError(t, err)
  380. assert.Equal(t, accUpdates, fetchedAccBalances)
  381. }
  382. func TestTxs(t *testing.T) {
  383. // Reset DB
  384. test.WipeDB(historyDB.DB())
  385. set := `
  386. Type: Blockchain
  387. AddToken(1)
  388. AddToken(2)
  389. CreateAccountDeposit(1) A: 10
  390. CreateAccountDeposit(1) B: 10
  391. > batchL1
  392. > batchL1
  393. > block
  394. CreateAccountDepositTransfer(1) C-A: 20, 10
  395. CreateAccountCoordinator(1) User0
  396. > batchL1
  397. > batchL1
  398. > block
  399. Deposit(1) B: 10
  400. Deposit(1) C: 10
  401. Transfer(1) C-A : 10 (1)
  402. Transfer(1) B-C : 10 (1)
  403. Transfer(1) A-B : 10 (1)
  404. Exit(1) A: 10 (1)
  405. > batch
  406. > block
  407. DepositTransfer(1) A-B: 10, 10
  408. > batchL1
  409. > block
  410. ForceTransfer(1) A-B: 10
  411. ForceExit(1) A: 5
  412. > batchL1
  413. > batchL1
  414. > block
  415. CreateAccountDeposit(2) D: 10
  416. > batchL1
  417. > block
  418. CreateAccountDeposit(2) E: 10
  419. > batchL1
  420. > batchL1
  421. > block
  422. `
  423. tc := til.NewContext(uint16(0), common.RollupConstMaxL1UserTx)
  424. tilCfgExtra := til.ConfigExtra{
  425. BootCoordAddr: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  426. CoordUser: "A",
  427. }
  428. blocks, err := tc.GenerateBlocks(set)
  429. require.NoError(t, err)
  430. err = tc.FillBlocksExtra(blocks, &tilCfgExtra)
  431. require.NoError(t, err)
  432. // Sanity check
  433. require.Equal(t, 7, len(blocks))
  434. require.Equal(t, 2, len(blocks[0].Rollup.L1UserTxs))
  435. require.Equal(t, 1, len(blocks[1].Rollup.L1UserTxs))
  436. require.Equal(t, 2, len(blocks[2].Rollup.L1UserTxs))
  437. require.Equal(t, 1, len(blocks[3].Rollup.L1UserTxs))
  438. require.Equal(t, 2, len(blocks[4].Rollup.L1UserTxs))
  439. require.Equal(t, 1, len(blocks[5].Rollup.L1UserTxs))
  440. require.Equal(t, 1, len(blocks[6].Rollup.L1UserTxs))
  441. var null *common.BatchNum = nil
  442. var txID common.TxID
  443. // Insert blocks into DB
  444. for i := range blocks {
  445. if i == len(blocks)-1 {
  446. blocks[i].Block.Timestamp = time.Now()
  447. dbL1Txs, err := historyDB.GetAllL1UserTxs()
  448. assert.NoError(t, err)
  449. // Check batch_num is nil before forging
  450. assert.Equal(t, null, dbL1Txs[len(dbL1Txs)-1].BatchNum)
  451. // Save this TxId
  452. txID = dbL1Txs[len(dbL1Txs)-1].TxID
  453. }
  454. err = historyDB.AddBlockSCData(&blocks[i])
  455. assert.NoError(t, err)
  456. }
  457. // Check blocks
  458. dbBlocks, err := historyDB.GetAllBlocks()
  459. assert.NoError(t, err)
  460. assert.Equal(t, len(blocks)+1, len(dbBlocks))
  461. // Check batches
  462. batches, err := historyDB.GetAllBatches()
  463. assert.NoError(t, err)
  464. assert.Equal(t, 11, len(batches))
  465. // Check L1 Transactions
  466. dbL1Txs, err := historyDB.GetAllL1UserTxs()
  467. assert.NoError(t, err)
  468. assert.Equal(t, 10, len(dbL1Txs))
  469. // Tx Type
  470. assert.Equal(t, common.TxTypeCreateAccountDeposit, dbL1Txs[0].Type)
  471. assert.Equal(t, common.TxTypeCreateAccountDeposit, dbL1Txs[1].Type)
  472. assert.Equal(t, common.TxTypeCreateAccountDepositTransfer, dbL1Txs[2].Type)
  473. assert.Equal(t, common.TxTypeDeposit, dbL1Txs[3].Type)
  474. assert.Equal(t, common.TxTypeDeposit, dbL1Txs[4].Type)
  475. assert.Equal(t, common.TxTypeDepositTransfer, dbL1Txs[5].Type)
  476. assert.Equal(t, common.TxTypeForceTransfer, dbL1Txs[6].Type)
  477. assert.Equal(t, common.TxTypeForceExit, dbL1Txs[7].Type)
  478. assert.Equal(t, common.TxTypeCreateAccountDeposit, dbL1Txs[8].Type)
  479. assert.Equal(t, common.TxTypeCreateAccountDeposit, dbL1Txs[9].Type)
  480. // Tx ID
  481. assert.Equal(t, "0x00e979da4b80d60a17ce56fa19278c6f3a7e1b43359fb8a8ea46d0264de7d653ab", dbL1Txs[0].TxID.String())
  482. assert.Equal(t, "0x00af9bf96eb60f2d618519402a2f6b07057a034fa2baefd379fe8e1c969f1c5cf4", dbL1Txs[1].TxID.String())
  483. assert.Equal(t, "0x00a256ee191905243320ea830840fd666a73c7b4e6f89ce4bd47ddf998dfee627a", dbL1Txs[2].TxID.String())
  484. assert.Equal(t, "0x00930696d03ae0a1e6150b6ccb88043cb539a4e06a7f8baf213029ce9a0600197e", dbL1Txs[3].TxID.String())
  485. assert.Equal(t, "0x00de8e41d49f23832f66364e8702c4b78237eb0c95542a94d34188e51696e74fc8", dbL1Txs[4].TxID.String())
  486. assert.Equal(t, "0x007a44d6d60b15f3789d4ff49d62377a70255bf13a8d42e41ef49bf4c7b77d2c1b", dbL1Txs[5].TxID.String())
  487. assert.Equal(t, "0x00c33f316240f8d33a973db2d0e901e4ac1c96de30b185fcc6b63dac4d0e147bd4", dbL1Txs[6].TxID.String())
  488. assert.Equal(t, "0x00b55f0882c5229d1be3d9d3c1a076290f249cd0bae5ae6e609234606befb91233", dbL1Txs[7].TxID.String())
  489. assert.Equal(t, "0x009133d4c8a412ca45f50bccdbcfdb8393b0dd8efe953d0cc3bcc82796b7a581b6", dbL1Txs[8].TxID.String())
  490. assert.Equal(t, "0x00f5e8ab141ac16d673e654ba7747c2f12e93ea2c50ba6c05563752ca531968c62", dbL1Txs[9].TxID.String())
  491. // Tx From IDx
  492. assert.Equal(t, common.Idx(0), dbL1Txs[0].FromIdx)
  493. assert.Equal(t, common.Idx(0), dbL1Txs[1].FromIdx)
  494. assert.Equal(t, common.Idx(0), dbL1Txs[2].FromIdx)
  495. assert.NotEqual(t, common.Idx(0), dbL1Txs[3].FromIdx)
  496. assert.NotEqual(t, common.Idx(0), dbL1Txs[4].FromIdx)
  497. assert.NotEqual(t, common.Idx(0), dbL1Txs[5].FromIdx)
  498. assert.NotEqual(t, common.Idx(0), dbL1Txs[6].FromIdx)
  499. assert.NotEqual(t, common.Idx(0), dbL1Txs[7].FromIdx)
  500. assert.Equal(t, common.Idx(0), dbL1Txs[8].FromIdx)
  501. assert.Equal(t, common.Idx(0), dbL1Txs[9].FromIdx)
  502. assert.Equal(t, common.Idx(0), dbL1Txs[9].FromIdx)
  503. assert.Equal(t, dbL1Txs[5].FromIdx, dbL1Txs[6].FromIdx)
  504. assert.Equal(t, dbL1Txs[5].FromIdx, dbL1Txs[7].FromIdx)
  505. // Tx to IDx
  506. assert.Equal(t, dbL1Txs[2].ToIdx, dbL1Txs[5].FromIdx)
  507. assert.Equal(t, dbL1Txs[5].ToIdx, dbL1Txs[3].FromIdx)
  508. assert.Equal(t, dbL1Txs[6].ToIdx, dbL1Txs[3].FromIdx)
  509. // Token ID
  510. assert.Equal(t, common.TokenID(1), dbL1Txs[0].TokenID)
  511. assert.Equal(t, common.TokenID(1), dbL1Txs[1].TokenID)
  512. assert.Equal(t, common.TokenID(1), dbL1Txs[2].TokenID)
  513. assert.Equal(t, common.TokenID(1), dbL1Txs[3].TokenID)
  514. assert.Equal(t, common.TokenID(1), dbL1Txs[4].TokenID)
  515. assert.Equal(t, common.TokenID(1), dbL1Txs[5].TokenID)
  516. assert.Equal(t, common.TokenID(1), dbL1Txs[6].TokenID)
  517. assert.Equal(t, common.TokenID(1), dbL1Txs[7].TokenID)
  518. assert.Equal(t, common.TokenID(2), dbL1Txs[8].TokenID)
  519. assert.Equal(t, common.TokenID(2), dbL1Txs[9].TokenID)
  520. // Batch Number
  521. var bn common.BatchNum = common.BatchNum(2)
  522. assert.Equal(t, &bn, dbL1Txs[0].BatchNum)
  523. assert.Equal(t, &bn, dbL1Txs[1].BatchNum)
  524. bn = common.BatchNum(4)
  525. assert.Equal(t, &bn, dbL1Txs[2].BatchNum)
  526. bn = common.BatchNum(7)
  527. assert.Equal(t, &bn, dbL1Txs[3].BatchNum)
  528. assert.Equal(t, &bn, dbL1Txs[4].BatchNum)
  529. assert.Equal(t, &bn, dbL1Txs[5].BatchNum)
  530. bn = common.BatchNum(8)
  531. assert.Equal(t, &bn, dbL1Txs[6].BatchNum)
  532. assert.Equal(t, &bn, dbL1Txs[7].BatchNum)
  533. bn = common.BatchNum(10)
  534. assert.Equal(t, &bn, dbL1Txs[8].BatchNum)
  535. bn = common.BatchNum(11)
  536. assert.Equal(t, &bn, dbL1Txs[9].BatchNum)
  537. // eth_block_num
  538. assert.Equal(t, int64(2), dbL1Txs[0].EthBlockNum)
  539. assert.Equal(t, int64(2), dbL1Txs[1].EthBlockNum)
  540. assert.Equal(t, int64(3), dbL1Txs[2].EthBlockNum)
  541. assert.Equal(t, int64(4), dbL1Txs[3].EthBlockNum)
  542. assert.Equal(t, int64(4), dbL1Txs[4].EthBlockNum)
  543. assert.Equal(t, int64(5), dbL1Txs[5].EthBlockNum)
  544. assert.Equal(t, int64(6), dbL1Txs[6].EthBlockNum)
  545. assert.Equal(t, int64(6), dbL1Txs[7].EthBlockNum)
  546. assert.Equal(t, int64(7), dbL1Txs[8].EthBlockNum)
  547. assert.Equal(t, int64(8), dbL1Txs[9].EthBlockNum)
  548. // User Origin
  549. assert.Equal(t, true, dbL1Txs[0].UserOrigin)
  550. assert.Equal(t, true, dbL1Txs[1].UserOrigin)
  551. assert.Equal(t, true, dbL1Txs[2].UserOrigin)
  552. assert.Equal(t, true, dbL1Txs[3].UserOrigin)
  553. assert.Equal(t, true, dbL1Txs[4].UserOrigin)
  554. assert.Equal(t, true, dbL1Txs[5].UserOrigin)
  555. assert.Equal(t, true, dbL1Txs[6].UserOrigin)
  556. assert.Equal(t, true, dbL1Txs[7].UserOrigin)
  557. assert.Equal(t, true, dbL1Txs[8].UserOrigin)
  558. assert.Equal(t, true, dbL1Txs[9].UserOrigin)
  559. // Deposit Amount
  560. assert.Equal(t, big.NewInt(10), dbL1Txs[0].DepositAmount)
  561. assert.Equal(t, big.NewInt(10), dbL1Txs[1].DepositAmount)
  562. assert.Equal(t, big.NewInt(20), dbL1Txs[2].DepositAmount)
  563. assert.Equal(t, big.NewInt(10), dbL1Txs[3].DepositAmount)
  564. assert.Equal(t, big.NewInt(10), dbL1Txs[4].DepositAmount)
  565. assert.Equal(t, big.NewInt(10), dbL1Txs[5].DepositAmount)
  566. assert.Equal(t, big.NewInt(0), dbL1Txs[6].DepositAmount)
  567. assert.Equal(t, big.NewInt(0), dbL1Txs[7].DepositAmount)
  568. assert.Equal(t, big.NewInt(10), dbL1Txs[8].DepositAmount)
  569. assert.Equal(t, big.NewInt(10), dbL1Txs[9].DepositAmount)
  570. // Check saved txID's batch_num is not nil
  571. assert.Equal(t, txID, dbL1Txs[len(dbL1Txs)-2].TxID)
  572. assert.NotEqual(t, null, dbL1Txs[len(dbL1Txs)-2].BatchNum)
  573. // Check Coordinator TXs
  574. coordTxs, err := historyDB.GetAllL1CoordinatorTxs()
  575. assert.NoError(t, err)
  576. assert.Equal(t, 1, len(coordTxs))
  577. assert.Equal(t, common.TxTypeCreateAccountDeposit, coordTxs[0].Type)
  578. assert.Equal(t, false, coordTxs[0].UserOrigin)
  579. // Check L2 TXs
  580. dbL2Txs, err := historyDB.GetAllL2Txs()
  581. assert.NoError(t, err)
  582. assert.Equal(t, 4, len(dbL2Txs))
  583. // Tx Type
  584. assert.Equal(t, common.TxTypeTransfer, dbL2Txs[0].Type)
  585. assert.Equal(t, common.TxTypeTransfer, dbL2Txs[1].Type)
  586. assert.Equal(t, common.TxTypeTransfer, dbL2Txs[2].Type)
  587. assert.Equal(t, common.TxTypeExit, dbL2Txs[3].Type)
  588. // Tx ID
  589. assert.Equal(t, "0x024e555248100b69a8aabf6d31719b9fe8a60dcc6c3407904a93c8d2d9ade18ee5", dbL2Txs[0].TxID.String())
  590. assert.Equal(t, "0x021ae87ca34d50ff35d98dfc0d7c95f2bf2e4ffeebb82ea71f43a8b0dfa5d36d89", dbL2Txs[1].TxID.String())
  591. assert.Equal(t, "0x024abce7f3f2382dc520ed557593f11dea1ee197e55b60402e664facc27aa19774", dbL2Txs[2].TxID.String())
  592. assert.Equal(t, "0x02f921ad9e7a6e59606570fe12a7dde0e36014197de0363b9b45e5097d6f2b1dd0", dbL2Txs[3].TxID.String())
  593. // Tx From and To IDx
  594. assert.Equal(t, dbL2Txs[0].ToIdx, dbL2Txs[2].FromIdx)
  595. assert.Equal(t, dbL2Txs[1].ToIdx, dbL2Txs[0].FromIdx)
  596. assert.Equal(t, dbL2Txs[2].ToIdx, dbL2Txs[1].FromIdx)
  597. // Batch Number
  598. assert.Equal(t, common.BatchNum(5), dbL2Txs[0].BatchNum)
  599. assert.Equal(t, common.BatchNum(5), dbL2Txs[1].BatchNum)
  600. assert.Equal(t, common.BatchNum(5), dbL2Txs[2].BatchNum)
  601. assert.Equal(t, common.BatchNum(5), dbL2Txs[3].BatchNum)
  602. // eth_block_num
  603. assert.Equal(t, int64(4), dbL2Txs[0].EthBlockNum)
  604. assert.Equal(t, int64(4), dbL2Txs[1].EthBlockNum)
  605. assert.Equal(t, int64(4), dbL2Txs[2].EthBlockNum)
  606. // Amount
  607. assert.Equal(t, big.NewInt(10), dbL2Txs[0].Amount)
  608. assert.Equal(t, big.NewInt(10), dbL2Txs[1].Amount)
  609. assert.Equal(t, big.NewInt(10), dbL2Txs[2].Amount)
  610. assert.Equal(t, big.NewInt(10), dbL2Txs[3].Amount)
  611. }
  612. func TestExitTree(t *testing.T) {
  613. nBatches := 17
  614. blocks := setTestBlocks(1, 10)
  615. batches := test.GenBatches(nBatches, blocks)
  616. err := historyDB.AddBatches(batches)
  617. assert.NoError(t, err)
  618. const nTokens = 50
  619. tokens, ethToken := test.GenTokens(nTokens, blocks)
  620. err = historyDB.AddTokens(tokens)
  621. assert.NoError(t, err)
  622. tokens = append([]common.Token{ethToken}, tokens...)
  623. const nAccounts = 3
  624. accs := test.GenAccounts(nAccounts, 0, tokens, nil, nil, batches)
  625. assert.NoError(t, historyDB.AddAccounts(accs))
  626. exitTree := test.GenExitTree(nBatches, batches, accs, blocks)
  627. err = historyDB.AddExitTree(exitTree)
  628. assert.NoError(t, err)
  629. }
  630. func TestGetUnforgedL1UserTxs(t *testing.T) {
  631. test.WipeDB(historyDB.DB())
  632. set := `
  633. Type: Blockchain
  634. AddToken(1)
  635. AddToken(2)
  636. AddToken(3)
  637. CreateAccountDeposit(1) A: 20
  638. CreateAccountDeposit(2) A: 20
  639. CreateAccountDeposit(1) B: 5
  640. CreateAccountDeposit(1) C: 5
  641. CreateAccountDeposit(1) D: 5
  642. > block
  643. `
  644. tc := til.NewContext(uint16(0), 128)
  645. blocks, err := tc.GenerateBlocks(set)
  646. require.NoError(t, err)
  647. // Sanity check
  648. require.Equal(t, 1, len(blocks))
  649. require.Equal(t, 5, len(blocks[0].Rollup.L1UserTxs))
  650. toForgeL1TxsNum := int64(1)
  651. for i := range blocks {
  652. err = historyDB.AddBlockSCData(&blocks[i])
  653. require.NoError(t, err)
  654. }
  655. l1UserTxs, err := historyDB.GetUnforgedL1UserTxs(toForgeL1TxsNum)
  656. require.NoError(t, err)
  657. assert.Equal(t, 5, len(l1UserTxs))
  658. assert.Equal(t, blocks[0].Rollup.L1UserTxs, l1UserTxs)
  659. // No l1UserTxs for this toForgeL1TxsNum
  660. l1UserTxs, err = historyDB.GetUnforgedL1UserTxs(2)
  661. require.NoError(t, err)
  662. assert.Equal(t, 0, len(l1UserTxs))
  663. }
  664. func exampleInitSCVars() (*common.RollupVariables, *common.AuctionVariables, *common.WDelayerVariables) {
  665. //nolint:govet
  666. rollup := &common.RollupVariables{
  667. 0,
  668. big.NewInt(10),
  669. 12,
  670. 13,
  671. [5]common.BucketParams{},
  672. false,
  673. }
  674. //nolint:govet
  675. auction := &common.AuctionVariables{
  676. 0,
  677. ethCommon.BigToAddress(big.NewInt(2)),
  678. ethCommon.BigToAddress(big.NewInt(3)),
  679. "https://boot.coord.com",
  680. [6]*big.Int{
  681. big.NewInt(1), big.NewInt(2), big.NewInt(3),
  682. big.NewInt(4), big.NewInt(5), big.NewInt(6),
  683. },
  684. 0,
  685. 2,
  686. 4320,
  687. [3]uint16{10, 11, 12},
  688. 1000,
  689. 20,
  690. }
  691. //nolint:govet
  692. wDelayer := &common.WDelayerVariables{
  693. 0,
  694. ethCommon.BigToAddress(big.NewInt(2)),
  695. ethCommon.BigToAddress(big.NewInt(3)),
  696. 13,
  697. 14,
  698. false,
  699. }
  700. return rollup, auction, wDelayer
  701. }
  702. func TestSetInitialSCVars(t *testing.T) {
  703. test.WipeDB(historyDB.DB())
  704. _, _, _, err := historyDB.GetSCVars()
  705. assert.Equal(t, sql.ErrNoRows, tracerr.Unwrap(err))
  706. rollup, auction, wDelayer := exampleInitSCVars()
  707. err = historyDB.SetInitialSCVars(rollup, auction, wDelayer)
  708. require.NoError(t, err)
  709. dbRollup, dbAuction, dbWDelayer, err := historyDB.GetSCVars()
  710. require.NoError(t, err)
  711. require.Equal(t, rollup, dbRollup)
  712. require.Equal(t, auction, dbAuction)
  713. require.Equal(t, wDelayer, dbWDelayer)
  714. }
  715. func TestSetExtraInfoForgedL1UserTxs(t *testing.T) {
  716. test.WipeDB(historyDB.DB())
  717. set := `
  718. Type: Blockchain
  719. AddToken(1)
  720. CreateAccountDeposit(1) A: 2000
  721. CreateAccountDeposit(1) B: 500
  722. CreateAccountDeposit(1) C: 500
  723. > batchL1 // forge L1UserTxs{nil}, freeze defined L1UserTxs{*}
  724. > block // blockNum=2
  725. > batchL1 // forge defined L1UserTxs{*}
  726. > block // blockNum=3
  727. `
  728. tc := til.NewContext(uint16(0), common.RollupConstMaxL1UserTx)
  729. tilCfgExtra := til.ConfigExtra{
  730. BootCoordAddr: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  731. CoordUser: "A",
  732. }
  733. blocks, err := tc.GenerateBlocks(set)
  734. require.NoError(t, err)
  735. err = tc.FillBlocksExtra(blocks, &tilCfgExtra)
  736. require.NoError(t, err)
  737. err = tc.FillBlocksForgedL1UserTxs(blocks)
  738. require.NoError(t, err)
  739. // Add only first block so that the L1UserTxs are not marked as forged
  740. for i := range blocks[:1] {
  741. err = historyDB.AddBlockSCData(&blocks[i])
  742. require.NoError(t, err)
  743. }
  744. // Add second batch to trigger the update of the batch_num,
  745. // while avoiding the implicit call of setExtraInfoForgedL1UserTxs
  746. err = historyDB.addBlock(historyDB.dbWrite, &blocks[1].Block)
  747. require.NoError(t, err)
  748. err = historyDB.addBatch(historyDB.dbWrite, &blocks[1].Rollup.Batches[0].Batch)
  749. require.NoError(t, err)
  750. err = historyDB.addAccounts(historyDB.dbWrite, blocks[1].Rollup.Batches[0].CreatedAccounts)
  751. require.NoError(t, err)
  752. // Set the Effective{Amount,DepositAmount} of the L1UserTxs that are forged in the second block
  753. l1Txs := blocks[1].Rollup.Batches[0].L1UserTxs
  754. require.Equal(t, 3, len(l1Txs))
  755. // Change some values to test all cases
  756. l1Txs[1].EffectiveAmount = big.NewInt(0)
  757. l1Txs[2].EffectiveDepositAmount = big.NewInt(0)
  758. l1Txs[2].EffectiveAmount = big.NewInt(0)
  759. err = historyDB.setExtraInfoForgedL1UserTxs(historyDB.dbWrite, l1Txs)
  760. require.NoError(t, err)
  761. dbL1Txs, err := historyDB.GetAllL1UserTxs()
  762. require.NoError(t, err)
  763. for i, tx := range dbL1Txs {
  764. log.Infof("%d %v %v", i, tx.EffectiveAmount, tx.EffectiveDepositAmount)
  765. assert.NotNil(t, tx.EffectiveAmount)
  766. assert.NotNil(t, tx.EffectiveDepositAmount)
  767. switch tx.TxID {
  768. case l1Txs[0].TxID:
  769. assert.Equal(t, l1Txs[0].DepositAmount, tx.EffectiveDepositAmount)
  770. assert.Equal(t, l1Txs[0].Amount, tx.EffectiveAmount)
  771. case l1Txs[1].TxID:
  772. assert.Equal(t, l1Txs[1].DepositAmount, tx.EffectiveDepositAmount)
  773. assert.Equal(t, big.NewInt(0), tx.EffectiveAmount)
  774. case l1Txs[2].TxID:
  775. assert.Equal(t, big.NewInt(0), tx.EffectiveDepositAmount)
  776. assert.Equal(t, big.NewInt(0), tx.EffectiveAmount)
  777. }
  778. }
  779. }
  780. func TestUpdateExitTree(t *testing.T) {
  781. test.WipeDB(historyDB.DB())
  782. set := `
  783. Type: Blockchain
  784. AddToken(1)
  785. CreateAccountDeposit(1) C: 2000 // Idx=256+2=258
  786. CreateAccountDeposit(1) D: 500 // Idx=256+3=259
  787. CreateAccountCoordinator(1) A // Idx=256+0=256
  788. CreateAccountCoordinator(1) B // Idx=256+1=257
  789. > batchL1 // forge L1UserTxs{nil}, freeze defined L1UserTxs{5}
  790. > batchL1 // forge defined L1UserTxs{5}, freeze L1UserTxs{nil}
  791. > block // blockNum=2
  792. ForceExit(1) A: 100
  793. ForceExit(1) B: 80
  794. Exit(1) C: 50 (172)
  795. Exit(1) D: 30 (172)
  796. > batchL1 // forge L1UserTxs{nil}, freeze defined L1UserTxs{3}
  797. > batchL1 // forge L1UserTxs{3}, freeze defined L1UserTxs{nil}
  798. > block // blockNum=3
  799. > block // blockNum=4 (empty block)
  800. > block // blockNum=5 (empty block)
  801. `
  802. tc := til.NewContext(uint16(0), common.RollupConstMaxL1UserTx)
  803. tilCfgExtra := til.ConfigExtra{
  804. BootCoordAddr: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  805. CoordUser: "A",
  806. }
  807. blocks, err := tc.GenerateBlocks(set)
  808. require.NoError(t, err)
  809. err = tc.FillBlocksExtra(blocks, &tilCfgExtra)
  810. require.NoError(t, err)
  811. // Add all blocks except for the last two
  812. for i := range blocks[:len(blocks)-2] {
  813. err = historyDB.AddBlockSCData(&blocks[i])
  814. require.NoError(t, err)
  815. }
  816. // Add withdraws to the second-to-last block, and insert block into the DB
  817. block := &blocks[len(blocks)-2]
  818. require.Equal(t, int64(4), block.Block.Num)
  819. tokenAddr := blocks[0].Rollup.AddedTokens[0].EthAddr
  820. // block.WDelayer.Deposits = append(block.WDelayer.Deposits,
  821. // common.WDelayerTransfer{Owner: tc.UsersByIdx[257].Addr, Token: tokenAddr, Amount: big.NewInt(80)}, // 257
  822. // common.WDelayerTransfer{Owner: tc.UsersByIdx[259].Addr, Token: tokenAddr, Amount: big.NewInt(15)}, // 259
  823. // )
  824. block.Rollup.Withdrawals = append(block.Rollup.Withdrawals,
  825. common.WithdrawInfo{Idx: 256, NumExitRoot: 4, InstantWithdraw: true},
  826. common.WithdrawInfo{Idx: 257, NumExitRoot: 4, InstantWithdraw: false,
  827. Owner: tc.UsersByIdx[257].Addr, Token: tokenAddr},
  828. common.WithdrawInfo{Idx: 258, NumExitRoot: 3, InstantWithdraw: true},
  829. common.WithdrawInfo{Idx: 259, NumExitRoot: 3, InstantWithdraw: false,
  830. Owner: tc.UsersByIdx[259].Addr, Token: tokenAddr},
  831. )
  832. err = historyDB.addBlock(historyDB.dbWrite, &block.Block)
  833. require.NoError(t, err)
  834. err = historyDB.updateExitTree(historyDB.dbWrite, block.Block.Num,
  835. block.Rollup.Withdrawals, block.WDelayer.Withdrawals)
  836. require.NoError(t, err)
  837. // Check that exits in DB match with the expected values
  838. dbExits, err := historyDB.GetAllExits()
  839. require.NoError(t, err)
  840. assert.Equal(t, 4, len(dbExits))
  841. dbExitsByIdx := make(map[common.Idx]common.ExitInfo)
  842. for _, dbExit := range dbExits {
  843. dbExitsByIdx[dbExit.AccountIdx] = dbExit
  844. }
  845. for _, withdraw := range block.Rollup.Withdrawals {
  846. assert.Equal(t, withdraw.NumExitRoot, dbExitsByIdx[withdraw.Idx].BatchNum)
  847. if withdraw.InstantWithdraw {
  848. assert.Equal(t, &block.Block.Num, dbExitsByIdx[withdraw.Idx].InstantWithdrawn)
  849. } else {
  850. assert.Equal(t, &block.Block.Num, dbExitsByIdx[withdraw.Idx].DelayedWithdrawRequest)
  851. }
  852. }
  853. // Add delayed withdraw to the last block, and insert block into the DB
  854. block = &blocks[len(blocks)-1]
  855. require.Equal(t, int64(5), block.Block.Num)
  856. block.WDelayer.Withdrawals = append(block.WDelayer.Withdrawals,
  857. common.WDelayerTransfer{
  858. Owner: tc.UsersByIdx[257].Addr,
  859. Token: tokenAddr,
  860. Amount: big.NewInt(80),
  861. })
  862. err = historyDB.addBlock(historyDB.dbWrite, &block.Block)
  863. require.NoError(t, err)
  864. err = historyDB.updateExitTree(historyDB.dbWrite, block.Block.Num,
  865. block.Rollup.Withdrawals, block.WDelayer.Withdrawals)
  866. require.NoError(t, err)
  867. // Check that delayed withdrawn has been set
  868. dbExits, err = historyDB.GetAllExits()
  869. require.NoError(t, err)
  870. for _, dbExit := range dbExits {
  871. dbExitsByIdx[dbExit.AccountIdx] = dbExit
  872. }
  873. require.Equal(t, &block.Block.Num, dbExitsByIdx[257].DelayedWithdrawn)
  874. }
  875. func TestGetBestBidCoordinator(t *testing.T) {
  876. test.WipeDB(historyDB.DB())
  877. rollup, auction, wDelayer := exampleInitSCVars()
  878. err := historyDB.SetInitialSCVars(rollup, auction, wDelayer)
  879. require.NoError(t, err)
  880. tc := til.NewContext(uint16(0), common.RollupConstMaxL1UserTx)
  881. blocks, err := tc.GenerateBlocks(`
  882. Type: Blockchain
  883. > block // blockNum=2
  884. `)
  885. require.NoError(t, err)
  886. err = historyDB.AddBlockSCData(&blocks[0])
  887. require.NoError(t, err)
  888. coords := []common.Coordinator{
  889. {
  890. Bidder: ethCommon.BigToAddress(big.NewInt(1)),
  891. Forger: ethCommon.BigToAddress(big.NewInt(2)),
  892. EthBlockNum: 2,
  893. URL: "foo",
  894. },
  895. {
  896. Bidder: ethCommon.BigToAddress(big.NewInt(3)),
  897. Forger: ethCommon.BigToAddress(big.NewInt(4)),
  898. EthBlockNum: 2,
  899. URL: "bar",
  900. },
  901. }
  902. err = historyDB.addCoordinators(historyDB.dbWrite, coords)
  903. require.NoError(t, err)
  904. bids := []common.Bid{
  905. {
  906. SlotNum: 10,
  907. BidValue: big.NewInt(10),
  908. EthBlockNum: 2,
  909. Bidder: coords[0].Bidder,
  910. },
  911. {
  912. SlotNum: 10,
  913. BidValue: big.NewInt(20),
  914. EthBlockNum: 2,
  915. Bidder: coords[1].Bidder,
  916. },
  917. }
  918. err = historyDB.addBids(historyDB.dbWrite, bids)
  919. require.NoError(t, err)
  920. forger10, err := historyDB.GetBestBidCoordinator(10)
  921. require.NoError(t, err)
  922. require.Equal(t, coords[1].Forger, forger10.Forger)
  923. require.Equal(t, coords[1].Bidder, forger10.Bidder)
  924. require.Equal(t, coords[1].URL, forger10.URL)
  925. require.Equal(t, bids[1].SlotNum, forger10.SlotNum)
  926. require.Equal(t, bids[1].BidValue, forger10.BidValue)
  927. for i := range forger10.DefaultSlotSetBid {
  928. require.Equal(t, auction.DefaultSlotSetBid[i], forger10.DefaultSlotSetBid[i])
  929. }
  930. _, err = historyDB.GetBestBidCoordinator(11)
  931. require.Equal(t, sql.ErrNoRows, tracerr.Unwrap(err))
  932. }
  933. func TestAddBucketUpdates(t *testing.T) {
  934. test.WipeDB(historyDB.DB())
  935. const fromBlock int64 = 1
  936. const toBlock int64 = 5 + 1
  937. setTestBlocks(fromBlock, toBlock)
  938. bucketUpdates := []common.BucketUpdate{
  939. {
  940. EthBlockNum: 4,
  941. NumBucket: 0,
  942. BlockStamp: 4,
  943. Withdrawals: big.NewInt(123),
  944. },
  945. {
  946. EthBlockNum: 5,
  947. NumBucket: 2,
  948. BlockStamp: 5,
  949. Withdrawals: big.NewInt(42),
  950. },
  951. }
  952. err := historyDB.addBucketUpdates(historyDB.dbWrite, bucketUpdates)
  953. require.NoError(t, err)
  954. dbBucketUpdates, err := historyDB.GetAllBucketUpdates()
  955. require.NoError(t, err)
  956. assert.Equal(t, bucketUpdates, dbBucketUpdates)
  957. }
  958. func TestAddTokenExchanges(t *testing.T) {
  959. test.WipeDB(historyDB.DB())
  960. const fromBlock int64 = 1
  961. const toBlock int64 = 5 + 1
  962. setTestBlocks(fromBlock, toBlock)
  963. tokenExchanges := []common.TokenExchange{
  964. {
  965. EthBlockNum: 4,
  966. Address: ethCommon.BigToAddress(big.NewInt(111)),
  967. ValueUSD: 12345,
  968. },
  969. {
  970. EthBlockNum: 5,
  971. Address: ethCommon.BigToAddress(big.NewInt(222)),
  972. ValueUSD: 67890,
  973. },
  974. }
  975. err := historyDB.addTokenExchanges(historyDB.dbWrite, tokenExchanges)
  976. require.NoError(t, err)
  977. dbTokenExchanges, err := historyDB.GetAllTokenExchanges()
  978. require.NoError(t, err)
  979. assert.Equal(t, tokenExchanges, dbTokenExchanges)
  980. }
  981. func TestAddEscapeHatchWithdrawals(t *testing.T) {
  982. test.WipeDB(historyDB.DB())
  983. const fromBlock int64 = 1
  984. const toBlock int64 = 5 + 1
  985. setTestBlocks(fromBlock, toBlock)
  986. escapeHatchWithdrawals := []common.WDelayerEscapeHatchWithdrawal{
  987. {
  988. EthBlockNum: 4,
  989. Who: ethCommon.BigToAddress(big.NewInt(111)),
  990. To: ethCommon.BigToAddress(big.NewInt(222)),
  991. TokenAddr: ethCommon.BigToAddress(big.NewInt(333)),
  992. Amount: big.NewInt(10002),
  993. },
  994. {
  995. EthBlockNum: 5,
  996. Who: ethCommon.BigToAddress(big.NewInt(444)),
  997. To: ethCommon.BigToAddress(big.NewInt(555)),
  998. TokenAddr: ethCommon.BigToAddress(big.NewInt(666)),
  999. Amount: big.NewInt(20003),
  1000. },
  1001. }
  1002. err := historyDB.addEscapeHatchWithdrawals(historyDB.dbWrite, escapeHatchWithdrawals)
  1003. require.NoError(t, err)
  1004. dbEscapeHatchWithdrawals, err := historyDB.GetAllEscapeHatchWithdrawals()
  1005. require.NoError(t, err)
  1006. assert.Equal(t, escapeHatchWithdrawals, dbEscapeHatchWithdrawals)
  1007. }
  1008. func TestGetMetricsAPI(t *testing.T) {
  1009. test.WipeDB(historyDB.DB())
  1010. set := `
  1011. Type: Blockchain
  1012. AddToken(1)
  1013. CreateAccountDeposit(1) A: 1000 // numTx=1
  1014. CreateAccountDeposit(1) B: 2000 // numTx=2
  1015. CreateAccountDeposit(1) C: 3000 //numTx=3
  1016. // block 0 is stored as default in the DB
  1017. // block 1 does not exist
  1018. > batchL1 // numBatches=1
  1019. > batchL1 // numBatches=2
  1020. > block // blockNum=2
  1021. Transfer(1) C-A : 10 (1) // numTx=4
  1022. > batch // numBatches=3
  1023. > block // blockNum=3
  1024. Transfer(1) B-C : 10 (1) // numTx=5
  1025. > batch // numBatches=5
  1026. > block // blockNum=4
  1027. Transfer(1) A-B : 10 (1) // numTx=6
  1028. > batch // numBatches=5
  1029. > block // blockNum=5
  1030. Transfer(1) A-B : 10 (1) // numTx=7
  1031. > batch // numBatches=6
  1032. > block // blockNum=6
  1033. `
  1034. const numBatches int = 6
  1035. const numTx int = 7
  1036. const blockNum = 6 - 1
  1037. tc := til.NewContext(uint16(0), common.RollupConstMaxL1UserTx)
  1038. tilCfgExtra := til.ConfigExtra{
  1039. BootCoordAddr: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  1040. CoordUser: "A",
  1041. }
  1042. blocks, err := tc.GenerateBlocks(set)
  1043. require.NoError(t, err)
  1044. err = tc.FillBlocksExtra(blocks, &tilCfgExtra)
  1045. require.NoError(t, err)
  1046. // Sanity check
  1047. require.Equal(t, blockNum, len(blocks))
  1048. // Adding one batch per block
  1049. // batch frequency can be chosen
  1050. const frequency int = 15
  1051. for i := range blocks {
  1052. blocks[i].Block.Timestamp = time.Now().Add(-time.Second * time.Duration(frequency*(len(blocks)-i)))
  1053. err = historyDB.AddBlockSCData(&blocks[i])
  1054. assert.NoError(t, err)
  1055. }
  1056. res, err := historyDBWithACC.GetMetricsAPI(common.BatchNum(numBatches))
  1057. assert.NoError(t, err)
  1058. assert.Equal(t, float64(numTx)/float64(numBatches), res.TransactionsPerBatch)
  1059. // Frequency is not exactly the desired one, some decimals may appear
  1060. // There is a -2 as time for first and last batch is not taken into account
  1061. assert.InEpsilon(t, float64(frequency)*float64(numBatches-2)/float64(numBatches), res.BatchFrequency, 0.01)
  1062. assert.InEpsilon(t, float64(numTx)/float64(frequency*blockNum-frequency), res.TransactionsPerSecond, 0.01)
  1063. assert.Equal(t, int64(3), res.TotalAccounts)
  1064. assert.Equal(t, int64(3), res.TotalBJJs)
  1065. // Til does not set fees
  1066. assert.Equal(t, float64(0), res.AvgTransactionFee)
  1067. }
  1068. func TestGetMetricsAPIMoreThan24Hours(t *testing.T) {
  1069. test.WipeDB(historyDB.DB())
  1070. testUsersLen := 3
  1071. var set []til.Instruction
  1072. for user := 0; user < testUsersLen; user++ {
  1073. set = append(set, til.Instruction{
  1074. Typ: common.TxTypeCreateAccountDeposit,
  1075. TokenID: common.TokenID(0),
  1076. DepositAmount: big.NewInt(1000000),
  1077. Amount: big.NewInt(0),
  1078. From: fmt.Sprintf("User%02d", user),
  1079. })
  1080. set = append(set, til.Instruction{Typ: til.TypeNewBlock})
  1081. }
  1082. set = append(set, til.Instruction{Typ: til.TypeNewBatchL1})
  1083. set = append(set, til.Instruction{Typ: til.TypeNewBatchL1})
  1084. set = append(set, til.Instruction{Typ: til.TypeNewBlock})
  1085. // Transfers
  1086. const numBlocks int = 30
  1087. for x := 0; x < numBlocks; x++ {
  1088. set = append(set, til.Instruction{
  1089. Typ: common.TxTypeTransfer,
  1090. TokenID: common.TokenID(0),
  1091. DepositAmount: big.NewInt(1),
  1092. Amount: big.NewInt(0),
  1093. From: "User00",
  1094. To: "User01",
  1095. })
  1096. set = append(set, til.Instruction{Typ: til.TypeNewBatch})
  1097. set = append(set, til.Instruction{Typ: til.TypeNewBlock})
  1098. }
  1099. var chainID uint16 = 0
  1100. tc := til.NewContext(chainID, common.RollupConstMaxL1UserTx)
  1101. blocks, err := tc.GenerateBlocksFromInstructions(set)
  1102. assert.NoError(t, err)
  1103. tilCfgExtra := til.ConfigExtra{
  1104. CoordUser: "A",
  1105. }
  1106. err = tc.FillBlocksExtra(blocks, &tilCfgExtra)
  1107. require.NoError(t, err)
  1108. const numBatches int = 2 + numBlocks
  1109. const blockNum = 4 + numBlocks
  1110. // Sanity check
  1111. require.Equal(t, blockNum, len(blocks))
  1112. // Adding one batch per block
  1113. // batch frequency can be chosen
  1114. const blockTime time.Duration = 3600 * time.Second
  1115. now := time.Now()
  1116. require.NoError(t, err)
  1117. for i := range blocks {
  1118. blocks[i].Block.Timestamp = now.Add(-time.Duration(len(blocks)-1-i) * blockTime)
  1119. err = historyDB.AddBlockSCData(&blocks[i])
  1120. assert.NoError(t, err)
  1121. }
  1122. res, err := historyDBWithACC.GetMetricsAPI(common.BatchNum(numBatches))
  1123. assert.NoError(t, err)
  1124. assert.InEpsilon(t, 1.0, res.TransactionsPerBatch, 0.1)
  1125. assert.InEpsilon(t, res.BatchFrequency, float64(blockTime/time.Second), 0.1)
  1126. assert.InEpsilon(t, 1.0/float64(blockTime/time.Second), res.TransactionsPerSecond, 0.1)
  1127. assert.Equal(t, int64(3), res.TotalAccounts)
  1128. assert.Equal(t, int64(3), res.TotalBJJs)
  1129. // Til does not set fees
  1130. assert.Equal(t, float64(0), res.AvgTransactionFee)
  1131. }
  1132. func TestGetMetricsAPIEmpty(t *testing.T) {
  1133. test.WipeDB(historyDB.DB())
  1134. _, err := historyDBWithACC.GetMetricsAPI(0)
  1135. assert.NoError(t, err)
  1136. }
  1137. func TestGetAvgTxFeeEmpty(t *testing.T) {
  1138. test.WipeDB(historyDB.DB())
  1139. _, err := historyDBWithACC.GetAvgTxFeeAPI()
  1140. assert.NoError(t, err)
  1141. }
  1142. func TestGetLastL1TxsNum(t *testing.T) {
  1143. test.WipeDB(historyDB.DB())
  1144. _, err := historyDB.GetLastL1TxsNum()
  1145. assert.NoError(t, err)
  1146. }
  1147. func TestGetLastTxsPosition(t *testing.T) {
  1148. test.WipeDB(historyDB.DB())
  1149. _, err := historyDB.GetLastTxsPosition(0)
  1150. assert.Equal(t, sql.ErrNoRows.Error(), err.Error())
  1151. }
  1152. func TestGetFirstBatchBlockNumBySlot(t *testing.T) {
  1153. test.WipeDB(historyDB.DB())
  1154. set := `
  1155. Type: Blockchain
  1156. // Slot = 0
  1157. > block // 2
  1158. > block // 3
  1159. > block // 4
  1160. > block // 5
  1161. // Slot = 1
  1162. > block // 6
  1163. > block // 7
  1164. > batch
  1165. > block // 8
  1166. > block // 9
  1167. // Slot = 2
  1168. > batch
  1169. > block // 10
  1170. > block // 11
  1171. > block // 12
  1172. > block // 13
  1173. `
  1174. tc := til.NewContext(uint16(0), common.RollupConstMaxL1UserTx)
  1175. blocks, err := tc.GenerateBlocks(set)
  1176. assert.NoError(t, err)
  1177. tilCfgExtra := til.ConfigExtra{
  1178. CoordUser: "A",
  1179. }
  1180. err = tc.FillBlocksExtra(blocks, &tilCfgExtra)
  1181. require.NoError(t, err)
  1182. for i := range blocks {
  1183. for j := range blocks[i].Rollup.Batches {
  1184. blocks[i].Rollup.Batches[j].Batch.SlotNum = int64(i) / 4
  1185. }
  1186. }
  1187. // Add all blocks
  1188. for i := range blocks {
  1189. err = historyDB.AddBlockSCData(&blocks[i])
  1190. require.NoError(t, err)
  1191. }
  1192. _, err = historyDB.GetFirstBatchBlockNumBySlot(0)
  1193. require.Equal(t, sql.ErrNoRows, tracerr.Unwrap(err))
  1194. bn1, err := historyDB.GetFirstBatchBlockNumBySlot(1)
  1195. require.NoError(t, err)
  1196. assert.Equal(t, int64(8), bn1)
  1197. bn2, err := historyDB.GetFirstBatchBlockNumBySlot(2)
  1198. require.NoError(t, err)
  1199. assert.Equal(t, int64(10), bn2)
  1200. }
  1201. func TestTxItemID(t *testing.T) {
  1202. test.WipeDB(historyDB.DB())
  1203. testUsersLen := 10
  1204. var set []til.Instruction
  1205. for user := 0; user < testUsersLen; user++ {
  1206. set = append(set, til.Instruction{
  1207. Typ: common.TxTypeCreateAccountDeposit,
  1208. TokenID: common.TokenID(0),
  1209. DepositAmount: big.NewInt(1000000),
  1210. Amount: big.NewInt(0),
  1211. From: fmt.Sprintf("User%02d", user),
  1212. })
  1213. set = append(set, til.Instruction{Typ: til.TypeNewBlock})
  1214. }
  1215. set = append(set, til.Instruction{Typ: til.TypeNewBatchL1})
  1216. set = append(set, til.Instruction{Typ: til.TypeNewBatchL1})
  1217. set = append(set, til.Instruction{Typ: til.TypeNewBlock})
  1218. for user := 0; user < testUsersLen; user++ {
  1219. set = append(set, til.Instruction{
  1220. Typ: common.TxTypeDeposit,
  1221. TokenID: common.TokenID(0),
  1222. DepositAmount: big.NewInt(100000),
  1223. Amount: big.NewInt(0),
  1224. From: fmt.Sprintf("User%02d", user),
  1225. })
  1226. set = append(set, til.Instruction{Typ: til.TypeNewBlock})
  1227. }
  1228. set = append(set, til.Instruction{Typ: til.TypeNewBatchL1})
  1229. set = append(set, til.Instruction{Typ: til.TypeNewBatchL1})
  1230. set = append(set, til.Instruction{Typ: til.TypeNewBlock})
  1231. for user := 0; user < testUsersLen; user++ {
  1232. set = append(set, til.Instruction{
  1233. Typ: common.TxTypeDepositTransfer,
  1234. TokenID: common.TokenID(0),
  1235. DepositAmount: big.NewInt(10000 * int64(user+1)),
  1236. Amount: big.NewInt(1000 * int64(user+1)),
  1237. From: fmt.Sprintf("User%02d", user),
  1238. To: fmt.Sprintf("User%02d", (user+1)%testUsersLen),
  1239. })
  1240. set = append(set, til.Instruction{Typ: til.TypeNewBlock})
  1241. }
  1242. set = append(set, til.Instruction{Typ: til.TypeNewBatchL1})
  1243. set = append(set, til.Instruction{Typ: til.TypeNewBatchL1})
  1244. set = append(set, til.Instruction{Typ: til.TypeNewBlock})
  1245. for user := 0; user < testUsersLen; user++ {
  1246. set = append(set, til.Instruction{
  1247. Typ: common.TxTypeForceTransfer,
  1248. TokenID: common.TokenID(0),
  1249. Amount: big.NewInt(100 * int64(user+1)),
  1250. DepositAmount: big.NewInt(0),
  1251. From: fmt.Sprintf("User%02d", user),
  1252. To: fmt.Sprintf("User%02d", (user+1)%testUsersLen),
  1253. })
  1254. set = append(set, til.Instruction{Typ: til.TypeNewBlock})
  1255. }
  1256. set = append(set, til.Instruction{Typ: til.TypeNewBatchL1})
  1257. set = append(set, til.Instruction{Typ: til.TypeNewBatchL1})
  1258. set = append(set, til.Instruction{Typ: til.TypeNewBlock})
  1259. for user := 0; user < testUsersLen; user++ {
  1260. set = append(set, til.Instruction{
  1261. Typ: common.TxTypeForceExit,
  1262. TokenID: common.TokenID(0),
  1263. Amount: big.NewInt(10 * int64(user+1)),
  1264. DepositAmount: big.NewInt(0),
  1265. From: fmt.Sprintf("User%02d", user),
  1266. })
  1267. set = append(set, til.Instruction{Typ: til.TypeNewBlock})
  1268. }
  1269. set = append(set, til.Instruction{Typ: til.TypeNewBatchL1})
  1270. set = append(set, til.Instruction{Typ: til.TypeNewBatchL1})
  1271. set = append(set, til.Instruction{Typ: til.TypeNewBlock})
  1272. var chainID uint16 = 0
  1273. tc := til.NewContext(chainID, common.RollupConstMaxL1UserTx)
  1274. blocks, err := tc.GenerateBlocksFromInstructions(set)
  1275. assert.NoError(t, err)
  1276. tilCfgExtra := til.ConfigExtra{
  1277. CoordUser: "A",
  1278. }
  1279. err = tc.FillBlocksExtra(blocks, &tilCfgExtra)
  1280. require.NoError(t, err)
  1281. // Add all blocks
  1282. for i := range blocks {
  1283. err = historyDB.AddBlockSCData(&blocks[i])
  1284. require.NoError(t, err)
  1285. }
  1286. txs, err := historyDB.GetAllL1UserTxs()
  1287. require.NoError(t, err)
  1288. position := 0
  1289. for _, tx := range txs {
  1290. if tx.Position == 0 {
  1291. position = 0
  1292. }
  1293. assert.Equal(t, position, tx.Position)
  1294. position++
  1295. }
  1296. }
  1297. // setTestBlocks WARNING: this will delete the blocks and recreate them
  1298. func setTestBlocks(from, to int64) []common.Block {
  1299. test.WipeDB(historyDB.DB())
  1300. blocks := test.GenBlocks(from, to)
  1301. if err := historyDB.AddBlocks(blocks); err != nil {
  1302. panic(err)
  1303. }
  1304. return blocks
  1305. }