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.

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