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.

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