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.

873 lines
27 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
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
  1. package historydb
  2. import (
  3. "database/sql"
  4. "math"
  5. "math/big"
  6. "os"
  7. "testing"
  8. "time"
  9. ethCommon "github.com/ethereum/go-ethereum/common"
  10. "github.com/hermeznetwork/hermez-node/common"
  11. dbUtils "github.com/hermeznetwork/hermez-node/db"
  12. "github.com/hermeznetwork/hermez-node/log"
  13. "github.com/hermeznetwork/hermez-node/test"
  14. "github.com/hermeznetwork/hermez-node/test/til"
  15. "github.com/stretchr/testify/assert"
  16. "github.com/stretchr/testify/require"
  17. )
  18. var historyDB *HistoryDB
  19. // In order to run the test you need to run a Posgres DB with
  20. // a database named "history" that is accessible by
  21. // user: "hermez"
  22. // pass: set it using the env var POSTGRES_PASS
  23. // 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;"
  24. // After running the test you can stop the container by running: sudo docker kill hermez-db-test
  25. // If you already did that for the L2DB you don't have to do it again
  26. func TestMain(m *testing.M) {
  27. // init DB
  28. pass := os.Getenv("POSTGRES_PASS")
  29. db, err := dbUtils.InitSQLDB(5432, "localhost", "hermez", pass, "hermez")
  30. if err != nil {
  31. panic(err)
  32. }
  33. historyDB = NewHistoryDB(db)
  34. if err != nil {
  35. panic(err)
  36. }
  37. // Run tests
  38. result := m.Run()
  39. // Close DB
  40. if err := db.Close(); err != nil {
  41. log.Error("Error closing the history DB:", err)
  42. }
  43. os.Exit(result)
  44. }
  45. func TestBlocks(t *testing.T) {
  46. var fromBlock, toBlock int64
  47. fromBlock = 0
  48. toBlock = 7
  49. // Reset DB
  50. test.WipeDB(historyDB.DB())
  51. // Generate blocks using til
  52. set1 := `
  53. Type: Blockchain
  54. // block 0 is stored as default in the DB
  55. // block 1 does not exist
  56. > block // blockNum=2
  57. > block // blockNum=3
  58. > block // blockNum=4
  59. > block // blockNum=5
  60. > block // blockNum=6
  61. `
  62. tc := til.NewContext(1)
  63. blocks, err := tc.GenerateBlocks(set1)
  64. require.NoError(t, err)
  65. // Save timestamp of a block with UTC and change it without UTC
  66. timestamp := time.Now().Add(time.Second * 13)
  67. blocks[fromBlock].Block.Timestamp = timestamp
  68. // Insert blocks into DB
  69. for i := 0; i < len(blocks); i++ {
  70. err := historyDB.AddBlock(&blocks[i].Block)
  71. assert.NoError(t, err)
  72. }
  73. // Add block 0 to the generated blocks
  74. blocks = append(
  75. []common.BlockData{common.BlockData{Block: test.Block0}}, //nolint:gofmt
  76. blocks...,
  77. )
  78. // Get all blocks from DB
  79. fetchedBlocks, err := historyDB.GetBlocks(fromBlock, toBlock)
  80. assert.Equal(t, len(blocks), len(fetchedBlocks))
  81. // Compare generated vs getted blocks
  82. assert.NoError(t, err)
  83. for i := range fetchedBlocks {
  84. assertEqualBlock(t, &blocks[i].Block, &fetchedBlocks[i])
  85. }
  86. // Compare saved timestamp vs getted
  87. nameZoneUTC, offsetUTC := timestamp.UTC().Zone()
  88. zoneFetchedBlock, offsetFetchedBlock := fetchedBlocks[fromBlock].Timestamp.Zone()
  89. assert.Equal(t, nameZoneUTC, zoneFetchedBlock)
  90. assert.Equal(t, offsetUTC, offsetFetchedBlock)
  91. // Get blocks from the DB one by one
  92. for i := int64(2); i < toBlock; i++ { // avoid block 0 for simplicity
  93. fetchedBlock, err := historyDB.GetBlock(i)
  94. assert.NoError(t, err)
  95. assertEqualBlock(t, &blocks[i-1].Block, fetchedBlock)
  96. }
  97. // Get last block
  98. lastBlock, err := historyDB.GetLastBlock()
  99. assert.NoError(t, err)
  100. assertEqualBlock(t, &blocks[len(blocks)-1].Block, lastBlock)
  101. }
  102. func assertEqualBlock(t *testing.T, expected *common.Block, actual *common.Block) {
  103. assert.Equal(t, expected.Num, actual.Num)
  104. assert.Equal(t, expected.Hash, actual.Hash)
  105. assert.Equal(t, expected.Timestamp.Unix(), actual.Timestamp.Unix())
  106. }
  107. func TestBatches(t *testing.T) {
  108. // Reset DB
  109. test.WipeDB(historyDB.DB())
  110. // Generate batches using til (and blocks for foreign key)
  111. set := `
  112. Type: Blockchain
  113. AddToken(1) // Will have value in USD
  114. AddToken(2) // Will NOT have value in USD
  115. CreateAccountDeposit(1) A: 2000
  116. CreateAccountDeposit(2) A: 2000
  117. CreateAccountDeposit(1) B: 1000
  118. CreateAccountDeposit(2) B: 1000
  119. > batchL1
  120. > batchL1
  121. Transfer(1) A-B: 100 (5)
  122. Transfer(2) B-A: 100 (199)
  123. > batch // batchNum=2, L2 only batch, forges transfers (mixed case of with(out) USD value)
  124. > block
  125. Transfer(1) A-B: 100 (5)
  126. > batch // batchNum=3, L2 only batch, forges transfer (with USD value)
  127. Transfer(2) B-A: 100 (199)
  128. > batch // batchNum=4, L2 only batch, forges transfer (without USD value)
  129. > block
  130. `
  131. tc := til.NewContext(common.RollupConstMaxL1UserTx)
  132. tilCfgExtra := til.ConfigExtra{
  133. BootCoordAddr: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  134. CoordUser: "A",
  135. }
  136. blocks, err := tc.GenerateBlocks(set)
  137. require.Nil(t, err)
  138. err = tc.FillBlocksExtra(blocks, &tilCfgExtra)
  139. assert.Nil(t, err)
  140. // Insert to DB
  141. batches := []common.Batch{}
  142. tokensValue := make(map[common.TokenID]float64)
  143. lastL1TxsNum := new(int64)
  144. lastL1BatchBlockNum := int64(0)
  145. for _, block := range blocks {
  146. // Insert block
  147. assert.NoError(t, historyDB.AddBlock(&block.Block))
  148. // Insert tokens
  149. for i, token := range block.Rollup.AddedTokens {
  150. assert.NoError(t, historyDB.AddToken(&token)) //nolint:gosec
  151. if i%2 != 0 {
  152. // Set value to the token
  153. value := (float64(i) + 5) * 5.389329
  154. assert.NoError(t, historyDB.UpdateTokenValue(token.Symbol, value))
  155. tokensValue[token.TokenID] = value / math.Pow(10, float64(token.Decimals))
  156. }
  157. }
  158. // Combine all generated batches into single array
  159. for _, batch := range block.Rollup.Batches {
  160. batches = append(batches, batch.Batch)
  161. forgeTxsNum := batch.Batch.ForgeL1TxsNum
  162. if forgeTxsNum != nil && (lastL1TxsNum == nil || *lastL1TxsNum < *forgeTxsNum) {
  163. *lastL1TxsNum = *forgeTxsNum
  164. lastL1BatchBlockNum = batch.Batch.EthBlockNum
  165. }
  166. }
  167. }
  168. // Insert batches
  169. assert.NoError(t, historyDB.AddBatches(batches))
  170. // Set expected total fee
  171. for _, batch := range batches {
  172. total := .0
  173. for tokenID, amount := range batch.CollectedFees {
  174. af := new(big.Float).SetInt(amount)
  175. amountFloat, _ := af.Float64()
  176. total += tokensValue[tokenID] * amountFloat
  177. }
  178. batch.TotalFeesUSD = &total
  179. }
  180. // Get batches from the DB
  181. fetchedBatches, err := historyDB.GetBatches(0, common.BatchNum(len(batches)+1))
  182. assert.NoError(t, err)
  183. assert.Equal(t, len(batches), len(fetchedBatches))
  184. for i, fetchedBatch := range fetchedBatches {
  185. assert.Equal(t, batches[i], fetchedBatch)
  186. }
  187. // Test GetLastBatchNum
  188. fetchedLastBatchNum, err := historyDB.GetLastBatchNum()
  189. assert.NoError(t, err)
  190. assert.Equal(t, batches[len(batches)-1].BatchNum, fetchedLastBatchNum)
  191. // Test GetLastL1TxsNum
  192. fetchedLastL1TxsNum, err := historyDB.GetLastL1TxsNum()
  193. assert.NoError(t, err)
  194. assert.Equal(t, lastL1TxsNum, fetchedLastL1TxsNum)
  195. // Test GetLastL1BatchBlockNum
  196. fetchedLastL1BatchBlockNum, err := historyDB.GetLastL1BatchBlockNum()
  197. assert.NoError(t, err)
  198. assert.Equal(t, lastL1BatchBlockNum, fetchedLastL1BatchBlockNum)
  199. }
  200. func TestBids(t *testing.T) {
  201. const fromBlock int64 = 1
  202. const toBlock int64 = 5
  203. // Prepare blocks in the DB
  204. blocks := setTestBlocks(fromBlock, toBlock)
  205. // Generate fake coordinators
  206. const nCoords = 5
  207. coords := test.GenCoordinators(nCoords, blocks)
  208. err := historyDB.AddCoordinators(coords)
  209. assert.NoError(t, err)
  210. // Generate fake bids
  211. const nBids = 20
  212. bids := test.GenBids(nBids, blocks, coords)
  213. err = historyDB.AddBids(bids)
  214. assert.NoError(t, err)
  215. // Fetch bids
  216. fetchedBids, err := historyDB.GetAllBids()
  217. assert.NoError(t, err)
  218. // Compare fetched bids vs generated bids
  219. for i, bid := range fetchedBids {
  220. assert.Equal(t, bids[i], bid)
  221. }
  222. }
  223. func TestTokens(t *testing.T) {
  224. const fromBlock int64 = 1
  225. const toBlock int64 = 5
  226. // Prepare blocks in the DB
  227. blocks := setTestBlocks(fromBlock, toBlock)
  228. // Generate fake tokens
  229. const nTokens = 5
  230. tokens, ethToken := test.GenTokens(nTokens, blocks)
  231. err := historyDB.AddTokens(tokens)
  232. assert.NoError(t, err)
  233. tokens = append([]common.Token{ethToken}, tokens...)
  234. limit := uint(10)
  235. // Fetch tokens
  236. fetchedTokens, _, err := historyDB.GetTokens(nil, nil, "", nil, &limit, OrderAsc)
  237. assert.NoError(t, err)
  238. // Compare fetched tokens vs generated tokens
  239. // All the tokens should have USDUpdate setted by the DB trigger
  240. for i, token := range fetchedTokens {
  241. assert.Equal(t, tokens[i].TokenID, token.TokenID)
  242. assert.Equal(t, tokens[i].EthBlockNum, token.EthBlockNum)
  243. assert.Equal(t, tokens[i].EthAddr, token.EthAddr)
  244. assert.Equal(t, tokens[i].Name, token.Name)
  245. assert.Equal(t, tokens[i].Symbol, token.Symbol)
  246. assert.Nil(t, token.USD)
  247. assert.Nil(t, token.USDUpdate)
  248. }
  249. // Update token value
  250. for i, token := range tokens {
  251. value := 1.01 * float64(i)
  252. assert.NoError(t, historyDB.UpdateTokenValue(token.Symbol, value))
  253. }
  254. // Fetch tokens
  255. fetchedTokens, _, err = historyDB.GetTokens(nil, nil, "", nil, &limit, OrderAsc)
  256. assert.NoError(t, err)
  257. // Compare fetched tokens vs generated tokens
  258. // All the tokens should have USDUpdate setted by the DB trigger
  259. for i, token := range fetchedTokens {
  260. value := 1.01 * float64(i)
  261. assert.Equal(t, value, *token.USD)
  262. nameZone, offset := token.USDUpdate.Zone()
  263. assert.Equal(t, "UTC", nameZone)
  264. assert.Equal(t, 0, offset)
  265. }
  266. }
  267. func TestAccounts(t *testing.T) {
  268. const fromBlock int64 = 1
  269. const toBlock int64 = 5
  270. // Prepare blocks in the DB
  271. blocks := setTestBlocks(fromBlock, toBlock)
  272. // Generate fake tokens
  273. const nTokens = 5
  274. tokens, ethToken := test.GenTokens(nTokens, blocks)
  275. err := historyDB.AddTokens(tokens)
  276. assert.NoError(t, err)
  277. tokens = append([]common.Token{ethToken}, tokens...)
  278. // Generate fake batches
  279. const nBatches = 10
  280. batches := test.GenBatches(nBatches, blocks)
  281. err = historyDB.AddBatches(batches)
  282. assert.NoError(t, err)
  283. // Generate fake accounts
  284. const nAccounts = 3
  285. accs := test.GenAccounts(nAccounts, 0, tokens, nil, nil, batches)
  286. err = historyDB.AddAccounts(accs)
  287. assert.NoError(t, err)
  288. // Fetch accounts
  289. fetchedAccs, err := historyDB.GetAllAccounts()
  290. assert.NoError(t, err)
  291. // Compare fetched accounts vs generated accounts
  292. for i, acc := range fetchedAccs {
  293. accs[i].Balance = nil
  294. assert.Equal(t, accs[i], acc)
  295. }
  296. }
  297. func TestTxs(t *testing.T) {
  298. // Reset DB
  299. test.WipeDB(historyDB.DB())
  300. set := `
  301. Type: Blockchain
  302. AddToken(1)
  303. AddToken(2)
  304. CreateAccountDeposit(1) A: 10
  305. CreateAccountDeposit(1) B: 10
  306. > batchL1
  307. > batchL1
  308. > block
  309. CreateAccountDepositTransfer(1) C-A: 20, 10
  310. CreateAccountCoordinator(1) User0
  311. > batchL1
  312. > batchL1
  313. > block
  314. Deposit(1) B: 10
  315. Deposit(1) C: 10
  316. Transfer(1) C-A : 10 (1)
  317. Transfer(1) B-C : 10 (1)
  318. Transfer(1) A-B : 10 (1)
  319. Exit(1) A: 10 (1)
  320. > batch
  321. > block
  322. DepositTransfer(1) A-B: 10, 10
  323. > batchL1
  324. > block
  325. ForceTransfer(1) A-B: 10
  326. ForceExit(1) A: 5
  327. > batchL1
  328. > batchL1
  329. > block
  330. CreateAccountDeposit(2) D: 10
  331. > batchL1
  332. > block
  333. CreateAccountDeposit(2) E: 10
  334. > batchL1
  335. > batchL1
  336. > block
  337. `
  338. tc := til.NewContext(common.RollupConstMaxL1UserTx)
  339. tilCfgExtra := til.ConfigExtra{
  340. BootCoordAddr: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  341. CoordUser: "A",
  342. }
  343. blocks, err := tc.GenerateBlocks(set)
  344. require.Nil(t, err)
  345. err = tc.FillBlocksExtra(blocks, &tilCfgExtra)
  346. assert.Nil(t, err)
  347. // Sanity check
  348. require.Equal(t, 7, len(blocks))
  349. require.Equal(t, 2, len(blocks[0].Rollup.L1UserTxs))
  350. require.Equal(t, 1, len(blocks[1].Rollup.L1UserTxs))
  351. require.Equal(t, 2, len(blocks[2].Rollup.L1UserTxs))
  352. require.Equal(t, 1, len(blocks[3].Rollup.L1UserTxs))
  353. require.Equal(t, 2, len(blocks[4].Rollup.L1UserTxs))
  354. require.Equal(t, 1, len(blocks[5].Rollup.L1UserTxs))
  355. require.Equal(t, 1, len(blocks[6].Rollup.L1UserTxs))
  356. var null *common.BatchNum = nil
  357. var txID common.TxID
  358. // Insert blocks into DB
  359. for i := range blocks {
  360. if i == len(blocks)-1 {
  361. blocks[i].Block.Timestamp = time.Now()
  362. dbL1Txs, err := historyDB.GetAllL1UserTxs()
  363. assert.NoError(t, err)
  364. // Check batch_num is nil before forging
  365. assert.Equal(t, null, dbL1Txs[len(dbL1Txs)-1].BatchNum)
  366. // Save this TxId
  367. txID = dbL1Txs[len(dbL1Txs)-1].TxID
  368. }
  369. err = historyDB.AddBlockSCData(&blocks[i])
  370. assert.NoError(t, err)
  371. }
  372. // Check blocks
  373. dbBlocks, err := historyDB.GetAllBlocks()
  374. assert.NoError(t, err)
  375. assert.Equal(t, len(blocks)+1, len(dbBlocks))
  376. // Check batches
  377. batches, err := historyDB.GetAllBatches()
  378. assert.NoError(t, err)
  379. assert.Equal(t, 11, len(batches))
  380. // Check L1 Transactions
  381. dbL1Txs, err := historyDB.GetAllL1UserTxs()
  382. assert.NoError(t, err)
  383. assert.Equal(t, 10, len(dbL1Txs))
  384. // Tx Type
  385. assert.Equal(t, common.TxTypeCreateAccountDeposit, dbL1Txs[0].Type)
  386. assert.Equal(t, common.TxTypeCreateAccountDeposit, dbL1Txs[1].Type)
  387. assert.Equal(t, common.TxTypeCreateAccountDepositTransfer, dbL1Txs[2].Type)
  388. assert.Equal(t, common.TxTypeDeposit, dbL1Txs[3].Type)
  389. assert.Equal(t, common.TxTypeDeposit, dbL1Txs[4].Type)
  390. assert.Equal(t, common.TxTypeDepositTransfer, dbL1Txs[5].Type)
  391. assert.Equal(t, common.TxTypeForceTransfer, dbL1Txs[6].Type)
  392. assert.Equal(t, common.TxTypeForceExit, dbL1Txs[7].Type)
  393. assert.Equal(t, common.TxTypeCreateAccountDeposit, dbL1Txs[8].Type)
  394. assert.Equal(t, common.TxTypeCreateAccountDeposit, dbL1Txs[9].Type)
  395. // Tx ID
  396. assert.Equal(t, "0x000000000000000001000000", dbL1Txs[0].TxID.String())
  397. assert.Equal(t, "0x000000000000000001000100", dbL1Txs[1].TxID.String())
  398. assert.Equal(t, "0x000000000000000003000000", dbL1Txs[2].TxID.String())
  399. assert.Equal(t, "0x000000000000000005000000", dbL1Txs[3].TxID.String())
  400. assert.Equal(t, "0x000000000000000005000100", dbL1Txs[4].TxID.String())
  401. assert.Equal(t, "0x000000000000000005000200", dbL1Txs[5].TxID.String())
  402. assert.Equal(t, "0x000000000000000006000000", dbL1Txs[6].TxID.String())
  403. assert.Equal(t, "0x000000000000000006000100", dbL1Txs[7].TxID.String())
  404. assert.Equal(t, "0x000000000000000008000000", dbL1Txs[8].TxID.String())
  405. assert.Equal(t, "0x000000000000000009000000", dbL1Txs[9].TxID.String())
  406. // Tx From IDx
  407. assert.Equal(t, common.Idx(0), dbL1Txs[0].FromIdx)
  408. assert.Equal(t, common.Idx(0), dbL1Txs[1].FromIdx)
  409. assert.Equal(t, common.Idx(0), dbL1Txs[2].FromIdx)
  410. assert.NotEqual(t, common.Idx(0), dbL1Txs[3].FromIdx)
  411. assert.NotEqual(t, common.Idx(0), dbL1Txs[4].FromIdx)
  412. assert.NotEqual(t, common.Idx(0), dbL1Txs[5].FromIdx)
  413. assert.NotEqual(t, common.Idx(0), dbL1Txs[6].FromIdx)
  414. assert.NotEqual(t, common.Idx(0), dbL1Txs[7].FromIdx)
  415. assert.Equal(t, common.Idx(0), dbL1Txs[8].FromIdx)
  416. assert.Equal(t, common.Idx(0), dbL1Txs[9].FromIdx)
  417. assert.Equal(t, common.Idx(0), dbL1Txs[9].FromIdx)
  418. assert.Equal(t, dbL1Txs[5].FromIdx, dbL1Txs[6].FromIdx)
  419. assert.Equal(t, dbL1Txs[5].FromIdx, dbL1Txs[7].FromIdx)
  420. // Tx to IDx
  421. assert.Equal(t, dbL1Txs[2].ToIdx, dbL1Txs[5].FromIdx)
  422. assert.Equal(t, dbL1Txs[5].ToIdx, dbL1Txs[3].FromIdx)
  423. assert.Equal(t, dbL1Txs[6].ToIdx, dbL1Txs[3].FromIdx)
  424. // Token ID
  425. assert.Equal(t, common.TokenID(1), dbL1Txs[0].TokenID)
  426. assert.Equal(t, common.TokenID(1), dbL1Txs[1].TokenID)
  427. assert.Equal(t, common.TokenID(1), dbL1Txs[2].TokenID)
  428. assert.Equal(t, common.TokenID(1), dbL1Txs[3].TokenID)
  429. assert.Equal(t, common.TokenID(1), dbL1Txs[4].TokenID)
  430. assert.Equal(t, common.TokenID(1), dbL1Txs[5].TokenID)
  431. assert.Equal(t, common.TokenID(1), dbL1Txs[6].TokenID)
  432. assert.Equal(t, common.TokenID(1), dbL1Txs[7].TokenID)
  433. assert.Equal(t, common.TokenID(2), dbL1Txs[8].TokenID)
  434. assert.Equal(t, common.TokenID(2), dbL1Txs[9].TokenID)
  435. // Batch Number
  436. var bn common.BatchNum = common.BatchNum(2)
  437. assert.Equal(t, &bn, dbL1Txs[0].BatchNum)
  438. assert.Equal(t, &bn, dbL1Txs[1].BatchNum)
  439. bn = common.BatchNum(4)
  440. assert.Equal(t, &bn, dbL1Txs[2].BatchNum)
  441. bn = common.BatchNum(7)
  442. assert.Equal(t, &bn, dbL1Txs[3].BatchNum)
  443. assert.Equal(t, &bn, dbL1Txs[4].BatchNum)
  444. assert.Equal(t, &bn, dbL1Txs[5].BatchNum)
  445. bn = common.BatchNum(8)
  446. assert.Equal(t, &bn, dbL1Txs[6].BatchNum)
  447. assert.Equal(t, &bn, dbL1Txs[7].BatchNum)
  448. bn = common.BatchNum(10)
  449. assert.Equal(t, &bn, dbL1Txs[8].BatchNum)
  450. bn = common.BatchNum(11)
  451. assert.Equal(t, &bn, dbL1Txs[9].BatchNum)
  452. // eth_block_num
  453. assert.Equal(t, int64(2), dbL1Txs[0].EthBlockNum)
  454. assert.Equal(t, int64(2), dbL1Txs[1].EthBlockNum)
  455. assert.Equal(t, int64(3), dbL1Txs[2].EthBlockNum)
  456. assert.Equal(t, int64(4), dbL1Txs[3].EthBlockNum)
  457. assert.Equal(t, int64(4), dbL1Txs[4].EthBlockNum)
  458. assert.Equal(t, int64(5), dbL1Txs[5].EthBlockNum)
  459. assert.Equal(t, int64(6), dbL1Txs[6].EthBlockNum)
  460. assert.Equal(t, int64(6), dbL1Txs[7].EthBlockNum)
  461. assert.Equal(t, int64(7), dbL1Txs[8].EthBlockNum)
  462. assert.Equal(t, int64(8), dbL1Txs[9].EthBlockNum)
  463. // User Origin
  464. assert.Equal(t, true, dbL1Txs[0].UserOrigin)
  465. assert.Equal(t, true, dbL1Txs[1].UserOrigin)
  466. assert.Equal(t, true, dbL1Txs[2].UserOrigin)
  467. assert.Equal(t, true, dbL1Txs[3].UserOrigin)
  468. assert.Equal(t, true, dbL1Txs[4].UserOrigin)
  469. assert.Equal(t, true, dbL1Txs[5].UserOrigin)
  470. assert.Equal(t, true, dbL1Txs[6].UserOrigin)
  471. assert.Equal(t, true, dbL1Txs[7].UserOrigin)
  472. assert.Equal(t, true, dbL1Txs[8].UserOrigin)
  473. assert.Equal(t, true, dbL1Txs[9].UserOrigin)
  474. // Load Amount
  475. assert.Equal(t, big.NewInt(10), dbL1Txs[0].LoadAmount)
  476. assert.Equal(t, big.NewInt(10), dbL1Txs[1].LoadAmount)
  477. assert.Equal(t, big.NewInt(20), dbL1Txs[2].LoadAmount)
  478. assert.Equal(t, big.NewInt(10), dbL1Txs[3].LoadAmount)
  479. assert.Equal(t, big.NewInt(10), dbL1Txs[4].LoadAmount)
  480. assert.Equal(t, big.NewInt(10), dbL1Txs[5].LoadAmount)
  481. assert.Equal(t, big.NewInt(0), dbL1Txs[6].LoadAmount)
  482. assert.Equal(t, big.NewInt(0), dbL1Txs[7].LoadAmount)
  483. assert.Equal(t, big.NewInt(10), dbL1Txs[8].LoadAmount)
  484. assert.Equal(t, big.NewInt(10), dbL1Txs[9].LoadAmount)
  485. // Check saved txID's batch_num is not nil
  486. assert.Equal(t, txID, dbL1Txs[len(dbL1Txs)-2].TxID)
  487. assert.NotEqual(t, null, dbL1Txs[len(dbL1Txs)-2].BatchNum)
  488. // Check Coordinator TXs
  489. coordTxs, err := historyDB.GetAllL1CoordinatorTxs()
  490. assert.NoError(t, err)
  491. assert.Equal(t, 1, len(coordTxs))
  492. assert.Equal(t, common.TxTypeCreateAccountDeposit, coordTxs[0].Type)
  493. assert.Equal(t, false, coordTxs[0].UserOrigin)
  494. // Check L2 TXs
  495. dbL2Txs, err := historyDB.GetAllL2Txs()
  496. assert.NoError(t, err)
  497. assert.Equal(t, 4, len(dbL2Txs))
  498. // Tx Type
  499. assert.Equal(t, common.TxTypeTransfer, dbL2Txs[0].Type)
  500. assert.Equal(t, common.TxTypeTransfer, dbL2Txs[1].Type)
  501. assert.Equal(t, common.TxTypeTransfer, dbL2Txs[2].Type)
  502. assert.Equal(t, common.TxTypeExit, dbL2Txs[3].Type)
  503. // Tx ID
  504. assert.Equal(t, "0x020000000001030000000001", dbL2Txs[0].TxID.String())
  505. assert.Equal(t, "0x020000000001010000000001", dbL2Txs[1].TxID.String())
  506. assert.Equal(t, "0x020000000001000000000001", dbL2Txs[2].TxID.String())
  507. assert.Equal(t, "0x020000000001000000000002", dbL2Txs[3].TxID.String())
  508. // Tx From and To IDx
  509. assert.Equal(t, dbL2Txs[0].ToIdx, dbL2Txs[2].FromIdx)
  510. assert.Equal(t, dbL2Txs[1].ToIdx, dbL2Txs[0].FromIdx)
  511. assert.Equal(t, dbL2Txs[2].ToIdx, dbL2Txs[1].FromIdx)
  512. // Batch Number
  513. assert.Equal(t, common.BatchNum(5), dbL2Txs[0].BatchNum)
  514. assert.Equal(t, common.BatchNum(5), dbL2Txs[1].BatchNum)
  515. assert.Equal(t, common.BatchNum(5), dbL2Txs[2].BatchNum)
  516. assert.Equal(t, common.BatchNum(5), dbL2Txs[3].BatchNum)
  517. // eth_block_num
  518. assert.Equal(t, int64(4), dbL2Txs[0].EthBlockNum)
  519. assert.Equal(t, int64(4), dbL2Txs[1].EthBlockNum)
  520. assert.Equal(t, int64(4), dbL2Txs[2].EthBlockNum)
  521. // Amount
  522. assert.Equal(t, big.NewInt(10), dbL2Txs[0].Amount)
  523. assert.Equal(t, big.NewInt(10), dbL2Txs[1].Amount)
  524. assert.Equal(t, big.NewInt(10), dbL2Txs[2].Amount)
  525. assert.Equal(t, big.NewInt(10), dbL2Txs[3].Amount)
  526. }
  527. func TestExitTree(t *testing.T) {
  528. nBatches := 17
  529. blocks := setTestBlocks(1, 10)
  530. batches := test.GenBatches(nBatches, blocks)
  531. err := historyDB.AddBatches(batches)
  532. assert.NoError(t, err)
  533. const nTokens = 50
  534. tokens, ethToken := test.GenTokens(nTokens, blocks)
  535. err = historyDB.AddTokens(tokens)
  536. assert.NoError(t, err)
  537. tokens = append([]common.Token{ethToken}, tokens...)
  538. const nAccounts = 3
  539. accs := test.GenAccounts(nAccounts, 0, tokens, nil, nil, batches)
  540. assert.NoError(t, historyDB.AddAccounts(accs))
  541. exitTree := test.GenExitTree(nBatches, batches, accs, blocks)
  542. err = historyDB.AddExitTree(exitTree)
  543. assert.NoError(t, err)
  544. }
  545. func TestGetL1UserTxs(t *testing.T) {
  546. test.WipeDB(historyDB.DB())
  547. set := `
  548. Type: Blockchain
  549. AddToken(1)
  550. AddToken(2)
  551. AddToken(3)
  552. CreateAccountDeposit(1) A: 20
  553. CreateAccountDeposit(2) A: 20
  554. CreateAccountDeposit(1) B: 5
  555. CreateAccountDeposit(1) C: 5
  556. CreateAccountDeposit(1) D: 5
  557. > block
  558. `
  559. tc := til.NewContext(128)
  560. blocks, err := tc.GenerateBlocks(set)
  561. require.Nil(t, err)
  562. // Sanity check
  563. require.Equal(t, 1, len(blocks))
  564. require.Equal(t, 5, len(blocks[0].Rollup.L1UserTxs))
  565. toForgeL1TxsNum := int64(1)
  566. for i := range blocks {
  567. err = historyDB.AddBlockSCData(&blocks[i])
  568. require.Nil(t, err)
  569. }
  570. l1UserTxs, err := historyDB.GetL1UserTxs(toForgeL1TxsNum)
  571. require.Nil(t, err)
  572. assert.Equal(t, 5, len(l1UserTxs))
  573. assert.Equal(t, blocks[0].Rollup.L1UserTxs, l1UserTxs)
  574. // No l1UserTxs for this toForgeL1TxsNum
  575. l1UserTxs, err = historyDB.GetL1UserTxs(2)
  576. require.Nil(t, err)
  577. assert.Equal(t, 0, len(l1UserTxs))
  578. }
  579. func exampleInitSCVars() (*common.RollupVariables, *common.AuctionVariables, *common.WDelayerVariables) {
  580. //nolint:govet
  581. rollup := &common.RollupVariables{
  582. 0,
  583. big.NewInt(10),
  584. 12,
  585. 13,
  586. [5]common.Bucket{},
  587. }
  588. //nolint:govet
  589. auction := &common.AuctionVariables{
  590. 0,
  591. ethCommon.BigToAddress(big.NewInt(2)),
  592. ethCommon.BigToAddress(big.NewInt(3)),
  593. [6]*big.Int{
  594. big.NewInt(1), big.NewInt(2), big.NewInt(3),
  595. big.NewInt(4), big.NewInt(5), big.NewInt(6),
  596. },
  597. 0,
  598. 2,
  599. 4320,
  600. [3]uint16{10, 11, 12},
  601. 1000,
  602. 20,
  603. }
  604. //nolint:govet
  605. wDelayer := &common.WDelayerVariables{
  606. 0,
  607. ethCommon.BigToAddress(big.NewInt(2)),
  608. ethCommon.BigToAddress(big.NewInt(3)),
  609. ethCommon.BigToAddress(big.NewInt(4)),
  610. 13,
  611. 14,
  612. false,
  613. }
  614. return rollup, auction, wDelayer
  615. }
  616. func TestSetInitialSCVars(t *testing.T) {
  617. test.WipeDB(historyDB.DB())
  618. _, _, _, err := historyDB.GetSCVars()
  619. assert.Equal(t, sql.ErrNoRows, err)
  620. rollup, auction, wDelayer := exampleInitSCVars()
  621. err = historyDB.SetInitialSCVars(rollup, auction, wDelayer)
  622. require.Nil(t, err)
  623. dbRollup, dbAuction, dbWDelayer, err := historyDB.GetSCVars()
  624. assert.Nil(t, err)
  625. require.Equal(t, rollup, dbRollup)
  626. require.Equal(t, auction, dbAuction)
  627. require.Equal(t, wDelayer, dbWDelayer)
  628. }
  629. func TestUpdateExitTree(t *testing.T) {
  630. test.WipeDB(historyDB.DB())
  631. set := `
  632. Type: Blockchain
  633. AddToken(1)
  634. CreateAccountDeposit(1) C: 2000 // Idx=256+2=258
  635. CreateAccountDeposit(1) D: 500 // Idx=256+3=259
  636. CreateAccountCoordinator(1) A // Idx=256+0=256
  637. CreateAccountCoordinator(1) B // Idx=256+1=257
  638. > batchL1 // forge L1UserTxs{nil}, freeze defined L1UserTxs{5}
  639. > batchL1 // forge defined L1UserTxs{5}, freeze L1UserTxs{nil}
  640. > block // blockNum=2
  641. ForceExit(1) A: 100
  642. ForceExit(1) B: 80
  643. Exit(1) C: 50 (172)
  644. Exit(1) D: 30 (172)
  645. > batchL1 // forge L1UserTxs{nil}, freeze defined L1UserTxs{3}
  646. > batchL1 // forge L1UserTxs{3}, freeze defined L1UserTxs{nil}
  647. > block // blockNum=3
  648. > block // blockNum=4 (empty block)
  649. > block // blockNum=5 (empty block)
  650. `
  651. tc := til.NewContext(common.RollupConstMaxL1UserTx)
  652. tilCfgExtra := til.ConfigExtra{
  653. BootCoordAddr: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  654. CoordUser: "A",
  655. }
  656. blocks, err := tc.GenerateBlocks(set)
  657. require.Nil(t, err)
  658. err = tc.FillBlocksExtra(blocks, &tilCfgExtra)
  659. assert.Nil(t, err)
  660. // Add all blocks except for the last two
  661. for i := range blocks[:len(blocks)-2] {
  662. err = historyDB.AddBlockSCData(&blocks[i])
  663. require.Nil(t, err)
  664. }
  665. // Add withdraws to the second-to-last block, and insert block into the DB
  666. block := &blocks[len(blocks)-2]
  667. require.Equal(t, int64(4), block.Block.Num)
  668. tokenAddr := blocks[0].Rollup.AddedTokens[0].EthAddr
  669. // block.WDelayer.Deposits = append(block.WDelayer.Deposits,
  670. // common.WDelayerTransfer{Owner: tc.UsersByIdx[257].Addr, Token: tokenAddr, Amount: big.NewInt(80)}, // 257
  671. // common.WDelayerTransfer{Owner: tc.UsersByIdx[259].Addr, Token: tokenAddr, Amount: big.NewInt(15)}, // 259
  672. // )
  673. block.Rollup.Withdrawals = append(block.Rollup.Withdrawals,
  674. common.WithdrawInfo{Idx: 256, NumExitRoot: 4, InstantWithdraw: true},
  675. common.WithdrawInfo{Idx: 257, NumExitRoot: 4, InstantWithdraw: false,
  676. Owner: tc.UsersByIdx[257].Addr, Token: tokenAddr},
  677. common.WithdrawInfo{Idx: 258, NumExitRoot: 3, InstantWithdraw: true},
  678. common.WithdrawInfo{Idx: 259, NumExitRoot: 3, InstantWithdraw: false,
  679. Owner: tc.UsersByIdx[259].Addr, Token: tokenAddr},
  680. )
  681. err = historyDB.addBlock(historyDB.db, &block.Block)
  682. require.Nil(t, err)
  683. err = historyDB.updateExitTree(historyDB.db, block.Block.Num,
  684. block.Rollup.Withdrawals, block.WDelayer.Withdrawals)
  685. require.Nil(t, err)
  686. // Check that exits in DB match with the expected values
  687. dbExits, err := historyDB.GetAllExits()
  688. require.Nil(t, err)
  689. assert.Equal(t, 4, len(dbExits))
  690. dbExitsByIdx := make(map[common.Idx]common.ExitInfo)
  691. for _, dbExit := range dbExits {
  692. dbExitsByIdx[dbExit.AccountIdx] = dbExit
  693. }
  694. for _, withdraw := range block.Rollup.Withdrawals {
  695. assert.Equal(t, withdraw.NumExitRoot, dbExitsByIdx[withdraw.Idx].BatchNum)
  696. if withdraw.InstantWithdraw {
  697. assert.Equal(t, &block.Block.Num, dbExitsByIdx[withdraw.Idx].InstantWithdrawn)
  698. } else {
  699. assert.Equal(t, &block.Block.Num, dbExitsByIdx[withdraw.Idx].DelayedWithdrawRequest)
  700. }
  701. }
  702. // Add delayed withdraw to the last block, and insert block into the DB
  703. block = &blocks[len(blocks)-1]
  704. require.Equal(t, int64(5), block.Block.Num)
  705. block.WDelayer.Withdrawals = append(block.WDelayer.Withdrawals,
  706. common.WDelayerTransfer{
  707. Owner: tc.UsersByIdx[257].Addr,
  708. Token: tokenAddr,
  709. Amount: big.NewInt(80),
  710. })
  711. err = historyDB.addBlock(historyDB.db, &block.Block)
  712. require.Nil(t, err)
  713. err = historyDB.updateExitTree(historyDB.db, block.Block.Num,
  714. block.Rollup.Withdrawals, block.WDelayer.Withdrawals)
  715. require.Nil(t, err)
  716. // Check that delayed withdrawn has been set
  717. dbExits, err = historyDB.GetAllExits()
  718. require.Nil(t, err)
  719. for _, dbExit := range dbExits {
  720. dbExitsByIdx[dbExit.AccountIdx] = dbExit
  721. }
  722. require.Equal(t, &block.Block.Num, dbExitsByIdx[257].DelayedWithdrawn)
  723. }
  724. func TestGetBestBidCoordinator(t *testing.T) {
  725. test.WipeDB(historyDB.DB())
  726. rollup, auction, wDelayer := exampleInitSCVars()
  727. err := historyDB.SetInitialSCVars(rollup, auction, wDelayer)
  728. require.Nil(t, err)
  729. tc := til.NewContext(common.RollupConstMaxL1UserTx)
  730. blocks, err := tc.GenerateBlocks(`
  731. Type: Blockchain
  732. > block // blockNum=2
  733. `)
  734. require.Nil(t, err)
  735. err = historyDB.AddBlockSCData(&blocks[0])
  736. require.Nil(t, err)
  737. coords := []common.Coordinator{
  738. {
  739. Bidder: ethCommon.BigToAddress(big.NewInt(1)),
  740. Forger: ethCommon.BigToAddress(big.NewInt(2)),
  741. EthBlockNum: 2,
  742. URL: "foo",
  743. },
  744. {
  745. Bidder: ethCommon.BigToAddress(big.NewInt(3)),
  746. Forger: ethCommon.BigToAddress(big.NewInt(4)),
  747. EthBlockNum: 2,
  748. URL: "bar",
  749. },
  750. }
  751. err = historyDB.addCoordinators(historyDB.db, coords)
  752. require.Nil(t, err)
  753. err = historyDB.addBids(historyDB.db, []common.Bid{
  754. {
  755. SlotNum: 10,
  756. BidValue: big.NewInt(10),
  757. EthBlockNum: 2,
  758. Bidder: coords[0].Bidder,
  759. },
  760. {
  761. SlotNum: 10,
  762. BidValue: big.NewInt(20),
  763. EthBlockNum: 2,
  764. Bidder: coords[1].Bidder,
  765. },
  766. })
  767. require.Nil(t, err)
  768. forger10, err := historyDB.GetBestBidCoordinator(10)
  769. require.Nil(t, err)
  770. require.Equal(t, coords[1].Forger, forger10.Forger)
  771. require.Equal(t, coords[1].Bidder, forger10.Bidder)
  772. require.Equal(t, coords[1].URL, forger10.URL)
  773. _, err = historyDB.GetBestBidCoordinator(11)
  774. require.Equal(t, sql.ErrNoRows, err)
  775. }
  776. // setTestBlocks WARNING: this will delete the blocks and recreate them
  777. func setTestBlocks(from, to int64) []common.Block {
  778. test.WipeDB(historyDB.DB())
  779. blocks := test.GenBlocks(from, to)
  780. if err := historyDB.AddBlocks(blocks); err != nil {
  781. panic(err)
  782. }
  783. return blocks
  784. }