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.

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