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