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.

1102 lines
36 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 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
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
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
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
  1. package historydb
  2. import (
  3. "math"
  4. "math/big"
  5. "strings"
  6. ethCommon "github.com/ethereum/go-ethereum/common"
  7. "github.com/hermeznetwork/hermez-node/common"
  8. "github.com/hermeznetwork/hermez-node/db"
  9. "github.com/hermeznetwork/tracerr"
  10. "github.com/jmoiron/sqlx"
  11. //nolint:errcheck // driver for postgres DB
  12. _ "github.com/lib/pq"
  13. "github.com/russross/meddler"
  14. )
  15. const (
  16. // OrderAsc indicates ascending order when using pagination
  17. OrderAsc = "ASC"
  18. // OrderDesc indicates descending order when using pagination
  19. OrderDesc = "DESC"
  20. )
  21. // TODO(Edu): Document here how HistoryDB is kept consistent
  22. // HistoryDB persist the historic of the rollup
  23. type HistoryDB struct {
  24. db *sqlx.DB
  25. apiConnCon *db.APIConnectionController
  26. }
  27. // NewHistoryDB initialize the DB
  28. func NewHistoryDB(db *sqlx.DB, apiConnCon *db.APIConnectionController) *HistoryDB {
  29. return &HistoryDB{db: db, apiConnCon: apiConnCon}
  30. }
  31. // DB returns a pointer to the L2DB.db. This method should be used only for
  32. // internal testing purposes.
  33. func (hdb *HistoryDB) DB() *sqlx.DB {
  34. return hdb.db
  35. }
  36. // AddBlock insert a block into the DB
  37. func (hdb *HistoryDB) AddBlock(block *common.Block) error { return hdb.addBlock(hdb.db, block) }
  38. func (hdb *HistoryDB) addBlock(d meddler.DB, block *common.Block) error {
  39. return tracerr.Wrap(meddler.Insert(d, "block", block))
  40. }
  41. // AddBlocks inserts blocks into the DB
  42. func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error {
  43. return tracerr.Wrap(hdb.addBlocks(hdb.db, blocks))
  44. }
  45. func (hdb *HistoryDB) addBlocks(d meddler.DB, blocks []common.Block) error {
  46. return tracerr.Wrap(db.BulkInsert(
  47. d,
  48. `INSERT INTO block (
  49. eth_block_num,
  50. timestamp,
  51. hash
  52. ) VALUES %s;`,
  53. blocks[:],
  54. ))
  55. }
  56. // GetBlock retrieve a block from the DB, given a block number
  57. func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error) {
  58. block := &common.Block{}
  59. err := meddler.QueryRow(
  60. hdb.db, block,
  61. "SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
  62. )
  63. return block, tracerr.Wrap(err)
  64. }
  65. // GetAllBlocks retrieve all blocks from the DB
  66. func (hdb *HistoryDB) GetAllBlocks() ([]common.Block, error) {
  67. var blocks []*common.Block
  68. err := meddler.QueryAll(
  69. hdb.db, &blocks,
  70. "SELECT * FROM block ORDER BY eth_block_num;",
  71. )
  72. return db.SlicePtrsToSlice(blocks).([]common.Block), tracerr.Wrap(err)
  73. }
  74. // getBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
  75. func (hdb *HistoryDB) getBlocks(from, to int64) ([]common.Block, error) {
  76. var blocks []*common.Block
  77. err := meddler.QueryAll(
  78. hdb.db, &blocks,
  79. "SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2 ORDER BY eth_block_num;",
  80. from, to,
  81. )
  82. return db.SlicePtrsToSlice(blocks).([]common.Block), tracerr.Wrap(err)
  83. }
  84. // GetLastBlock retrieve the block with the highest block number from the DB
  85. func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
  86. block := &common.Block{}
  87. err := meddler.QueryRow(
  88. hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
  89. )
  90. return block, tracerr.Wrap(err)
  91. }
  92. // AddBatch insert a Batch into the DB
  93. func (hdb *HistoryDB) AddBatch(batch *common.Batch) error { return hdb.addBatch(hdb.db, batch) }
  94. func (hdb *HistoryDB) addBatch(d meddler.DB, batch *common.Batch) error {
  95. // Calculate total collected fees in USD
  96. // Get IDs of collected tokens for fees
  97. tokenIDs := []common.TokenID{}
  98. for id := range batch.CollectedFees {
  99. tokenIDs = append(tokenIDs, id)
  100. }
  101. // Get USD value of the tokens
  102. type tokenPrice struct {
  103. ID common.TokenID `meddler:"token_id"`
  104. USD *float64 `meddler:"usd"`
  105. Decimals int `meddler:"decimals"`
  106. }
  107. var tokenPrices []*tokenPrice
  108. if len(tokenIDs) > 0 {
  109. query, args, err := sqlx.In(
  110. "SELECT token_id, usd, decimals FROM token WHERE token_id IN (?);",
  111. tokenIDs,
  112. )
  113. if err != nil {
  114. return tracerr.Wrap(err)
  115. }
  116. query = hdb.db.Rebind(query)
  117. if err := meddler.QueryAll(
  118. hdb.db, &tokenPrices, query, args...,
  119. ); err != nil {
  120. return tracerr.Wrap(err)
  121. }
  122. }
  123. // Calculate total collected
  124. var total float64
  125. for _, tokenPrice := range tokenPrices {
  126. if tokenPrice.USD == nil {
  127. continue
  128. }
  129. f := new(big.Float).SetInt(batch.CollectedFees[tokenPrice.ID])
  130. amount, _ := f.Float64()
  131. total += *tokenPrice.USD * (amount / math.Pow(10, float64(tokenPrice.Decimals))) //nolint decimals have to be ^10
  132. }
  133. batch.TotalFeesUSD = &total
  134. // Insert to DB
  135. return tracerr.Wrap(meddler.Insert(d, "batch", batch))
  136. }
  137. // AddBatches insert Bids into the DB
  138. func (hdb *HistoryDB) AddBatches(batches []common.Batch) error {
  139. return tracerr.Wrap(hdb.addBatches(hdb.db, batches))
  140. }
  141. func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error {
  142. for i := 0; i < len(batches); i++ {
  143. if err := hdb.addBatch(d, &batches[i]); err != nil {
  144. return tracerr.Wrap(err)
  145. }
  146. }
  147. return nil
  148. }
  149. // GetAllBatches retrieve all batches from the DB
  150. func (hdb *HistoryDB) GetAllBatches() ([]common.Batch, error) {
  151. var batches []*common.Batch
  152. err := meddler.QueryAll(
  153. hdb.db, &batches,
  154. `SELECT batch.batch_num, batch.eth_block_num, batch.forger_addr, batch.fees_collected,
  155. batch.fee_idxs_coordinator, batch.state_root, batch.num_accounts, batch.last_idx, batch.exit_root,
  156. batch.forge_l1_txs_num, batch.slot_num, batch.total_fees_usd FROM batch
  157. ORDER BY item_id;`,
  158. )
  159. return db.SlicePtrsToSlice(batches).([]common.Batch), tracerr.Wrap(err)
  160. }
  161. // GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
  162. func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error) {
  163. var batches []*common.Batch
  164. err := meddler.QueryAll(
  165. hdb.db, &batches,
  166. `SELECT batch_num, eth_block_num, forger_addr, fees_collected, fee_idxs_coordinator,
  167. state_root, num_accounts, last_idx, exit_root, forge_l1_txs_num, slot_num, total_fees_usd
  168. FROM batch WHERE $1 <= batch_num AND batch_num < $2 ORDER BY batch_num;`,
  169. from, to,
  170. )
  171. return db.SlicePtrsToSlice(batches).([]common.Batch), tracerr.Wrap(err)
  172. }
  173. // GetFirstBatchBlockNumBySlot returns the ethereum block number of the first
  174. // batch within a slot
  175. func (hdb *HistoryDB) GetFirstBatchBlockNumBySlot(slotNum int64) (int64, error) {
  176. row := hdb.db.QueryRow(
  177. `SELECT eth_block_num FROM batch
  178. WHERE slot_num = $1 ORDER BY batch_num ASC LIMIT 1;`, slotNum,
  179. )
  180. var blockNum int64
  181. return blockNum, tracerr.Wrap(row.Scan(&blockNum))
  182. }
  183. // GetLastBatchNum returns the BatchNum of the latest forged batch
  184. func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
  185. row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
  186. var batchNum common.BatchNum
  187. return batchNum, tracerr.Wrap(row.Scan(&batchNum))
  188. }
  189. // GetLastL1BatchBlockNum returns the blockNum of the latest forged l1Batch
  190. func (hdb *HistoryDB) GetLastL1BatchBlockNum() (int64, error) {
  191. row := hdb.db.QueryRow(`SELECT eth_block_num FROM batch
  192. WHERE forge_l1_txs_num IS NOT NULL
  193. ORDER BY batch_num DESC LIMIT 1;`)
  194. var blockNum int64
  195. return blockNum, tracerr.Wrap(row.Scan(&blockNum))
  196. }
  197. // GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged
  198. // batches. If there's no batch in the DB (nil, nil) is returned.
  199. func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
  200. row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
  201. lastL1TxsNum := new(int64)
  202. return lastL1TxsNum, tracerr.Wrap(row.Scan(&lastL1TxsNum))
  203. }
  204. // Reorg deletes all the information that was added into the DB after the
  205. // lastValidBlock. If lastValidBlock is negative, all block information is
  206. // deleted.
  207. func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
  208. var err error
  209. if lastValidBlock < 0 {
  210. _, err = hdb.db.Exec("DELETE FROM block;")
  211. } else {
  212. _, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
  213. }
  214. return tracerr.Wrap(err)
  215. }
  216. // AddBids insert Bids into the DB
  217. func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
  218. func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
  219. if len(bids) == 0 {
  220. return nil
  221. }
  222. // TODO: check the coordinator info
  223. return tracerr.Wrap(db.BulkInsert(
  224. d,
  225. "INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
  226. bids[:],
  227. ))
  228. }
  229. // GetAllBids retrieve all bids from the DB
  230. func (hdb *HistoryDB) GetAllBids() ([]common.Bid, error) {
  231. var bids []*common.Bid
  232. err := meddler.QueryAll(
  233. hdb.db, &bids,
  234. `SELECT bid.slot_num, bid.bid_value, bid.eth_block_num, bid.bidder_addr FROM bid
  235. ORDER BY item_id;`,
  236. )
  237. return db.SlicePtrsToSlice(bids).([]common.Bid), tracerr.Wrap(err)
  238. }
  239. // GetBestBidCoordinator returns the forger address of the highest bidder in a slot by slotNum
  240. func (hdb *HistoryDB) GetBestBidCoordinator(slotNum int64) (*common.BidCoordinator, error) {
  241. bidCoord := &common.BidCoordinator{}
  242. err := meddler.QueryRow(
  243. hdb.db, bidCoord,
  244. `SELECT (
  245. SELECT default_slot_set_bid
  246. FROM auction_vars
  247. WHERE default_slot_set_bid_slot_num <= $1
  248. ORDER BY eth_block_num DESC LIMIT 1
  249. ),
  250. bid.slot_num, bid.bid_value, bid.bidder_addr,
  251. coordinator.forger_addr, coordinator.url
  252. FROM bid
  253. INNER JOIN (
  254. SELECT bidder_addr, MAX(item_id) AS item_id FROM coordinator
  255. GROUP BY bidder_addr
  256. ) c ON bid.bidder_addr = c.bidder_addr
  257. INNER JOIN coordinator ON c.item_id = coordinator.item_id
  258. WHERE bid.slot_num = $1 ORDER BY bid.item_id DESC LIMIT 1;`,
  259. slotNum)
  260. return bidCoord, tracerr.Wrap(err)
  261. }
  262. // AddCoordinators insert Coordinators into the DB
  263. func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
  264. return tracerr.Wrap(hdb.addCoordinators(hdb.db, coordinators))
  265. }
  266. func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
  267. if len(coordinators) == 0 {
  268. return nil
  269. }
  270. return tracerr.Wrap(db.BulkInsert(
  271. d,
  272. "INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
  273. coordinators[:],
  274. ))
  275. }
  276. // AddExitTree insert Exit tree into the DB
  277. func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
  278. return tracerr.Wrap(hdb.addExitTree(hdb.db, exitTree))
  279. }
  280. func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
  281. if len(exitTree) == 0 {
  282. return nil
  283. }
  284. return tracerr.Wrap(db.BulkInsert(
  285. d,
  286. "INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
  287. "instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
  288. exitTree[:],
  289. ))
  290. }
  291. func (hdb *HistoryDB) updateExitTree(d sqlx.Ext, blockNum int64,
  292. rollupWithdrawals []common.WithdrawInfo, wDelayerWithdrawals []common.WDelayerTransfer) error {
  293. if len(rollupWithdrawals) == 0 && len(wDelayerWithdrawals) == 0 {
  294. return nil
  295. }
  296. type withdrawal struct {
  297. BatchNum int64 `db:"batch_num"`
  298. AccountIdx int64 `db:"account_idx"`
  299. InstantWithdrawn *int64 `db:"instant_withdrawn"`
  300. DelayedWithdrawRequest *int64 `db:"delayed_withdraw_request"`
  301. DelayedWithdrawn *int64 `db:"delayed_withdrawn"`
  302. Owner *ethCommon.Address `db:"owner"`
  303. Token *ethCommon.Address `db:"token"`
  304. }
  305. withdrawals := make([]withdrawal, len(rollupWithdrawals)+len(wDelayerWithdrawals))
  306. for i := range rollupWithdrawals {
  307. info := &rollupWithdrawals[i]
  308. withdrawals[i] = withdrawal{
  309. BatchNum: int64(info.NumExitRoot),
  310. AccountIdx: int64(info.Idx),
  311. }
  312. if info.InstantWithdraw {
  313. withdrawals[i].InstantWithdrawn = &blockNum
  314. } else {
  315. withdrawals[i].DelayedWithdrawRequest = &blockNum
  316. withdrawals[i].Owner = &info.Owner
  317. withdrawals[i].Token = &info.Token
  318. }
  319. }
  320. for i := range wDelayerWithdrawals {
  321. info := &wDelayerWithdrawals[i]
  322. withdrawals[len(rollupWithdrawals)+i] = withdrawal{
  323. DelayedWithdrawn: &blockNum,
  324. Owner: &info.Owner,
  325. Token: &info.Token,
  326. }
  327. }
  328. // In VALUES we set an initial row of NULLs to set the types of each
  329. // variable passed as argument
  330. const query string = `
  331. UPDATE exit_tree e SET
  332. instant_withdrawn = d.instant_withdrawn,
  333. delayed_withdraw_request = CASE
  334. WHEN e.delayed_withdraw_request IS NOT NULL THEN e.delayed_withdraw_request
  335. ELSE d.delayed_withdraw_request
  336. END,
  337. delayed_withdrawn = d.delayed_withdrawn,
  338. owner = d.owner,
  339. token = d.token
  340. FROM (VALUES
  341. (NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BYTEA, NULL::::BYTEA),
  342. (:batch_num,
  343. :account_idx,
  344. :instant_withdrawn,
  345. :delayed_withdraw_request,
  346. :delayed_withdrawn,
  347. :owner,
  348. :token)
  349. ) as d (batch_num, account_idx, instant_withdrawn, delayed_withdraw_request, delayed_withdrawn, owner, token)
  350. WHERE
  351. (d.batch_num IS NOT NULL AND e.batch_num = d.batch_num AND e.account_idx = d.account_idx) OR
  352. (d.delayed_withdrawn IS NOT NULL AND e.delayed_withdrawn IS NULL AND e.owner = d.owner AND e.token = d.token);
  353. `
  354. if len(withdrawals) > 0 {
  355. if _, err := sqlx.NamedExec(d, query, withdrawals); err != nil {
  356. return tracerr.Wrap(err)
  357. }
  358. }
  359. return nil
  360. }
  361. // AddToken insert a token into the DB
  362. func (hdb *HistoryDB) AddToken(token *common.Token) error {
  363. return tracerr.Wrap(meddler.Insert(hdb.db, "token", token))
  364. }
  365. // AddTokens insert tokens into the DB
  366. func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
  367. func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
  368. if len(tokens) == 0 {
  369. return nil
  370. }
  371. // Sanitize name and symbol
  372. for i, token := range tokens {
  373. token.Name = strings.ToValidUTF8(token.Name, " ")
  374. token.Symbol = strings.ToValidUTF8(token.Symbol, " ")
  375. tokens[i] = token
  376. }
  377. return tracerr.Wrap(db.BulkInsert(
  378. d,
  379. `INSERT INTO token (
  380. token_id,
  381. eth_block_num,
  382. eth_addr,
  383. name,
  384. symbol,
  385. decimals
  386. ) VALUES %s;`,
  387. tokens[:],
  388. ))
  389. }
  390. // UpdateTokenValue updates the USD value of a token
  391. func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
  392. // Sanitize symbol
  393. tokenSymbol = strings.ToValidUTF8(tokenSymbol, " ")
  394. _, err := hdb.db.Exec(
  395. "UPDATE token SET usd = $1 WHERE symbol = $2;",
  396. value, tokenSymbol,
  397. )
  398. return tracerr.Wrap(err)
  399. }
  400. // GetToken returns a token from the DB given a TokenID
  401. func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
  402. token := &TokenWithUSD{}
  403. err := meddler.QueryRow(
  404. hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
  405. )
  406. return token, tracerr.Wrap(err)
  407. }
  408. // GetAllTokens returns all tokens from the DB
  409. func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
  410. var tokens []*TokenWithUSD
  411. err := meddler.QueryAll(
  412. hdb.db, &tokens,
  413. "SELECT * FROM token ORDER BY token_id;",
  414. )
  415. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), tracerr.Wrap(err)
  416. }
  417. // GetTokenSymbols returns all the token symbols from the DB
  418. func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
  419. var tokenSymbols []string
  420. rows, err := hdb.db.Query("SELECT symbol FROM token;")
  421. if err != nil {
  422. return nil, tracerr.Wrap(err)
  423. }
  424. defer db.RowsClose(rows)
  425. sym := new(string)
  426. for rows.Next() {
  427. err = rows.Scan(sym)
  428. if err != nil {
  429. return nil, tracerr.Wrap(err)
  430. }
  431. tokenSymbols = append(tokenSymbols, *sym)
  432. }
  433. return tokenSymbols, nil
  434. }
  435. // AddAccounts insert accounts into the DB
  436. func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
  437. return tracerr.Wrap(hdb.addAccounts(hdb.db, accounts))
  438. }
  439. func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
  440. if len(accounts) == 0 {
  441. return nil
  442. }
  443. return tracerr.Wrap(db.BulkInsert(
  444. d,
  445. `INSERT INTO account (
  446. idx,
  447. token_id,
  448. batch_num,
  449. bjj,
  450. eth_addr
  451. ) VALUES %s;`,
  452. accounts[:],
  453. ))
  454. }
  455. // GetAllAccounts returns a list of accounts from the DB
  456. func (hdb *HistoryDB) GetAllAccounts() ([]common.Account, error) {
  457. var accs []*common.Account
  458. err := meddler.QueryAll(
  459. hdb.db, &accs,
  460. "SELECT idx, token_id, batch_num, bjj, eth_addr FROM account ORDER BY idx;",
  461. )
  462. return db.SlicePtrsToSlice(accs).([]common.Account), tracerr.Wrap(err)
  463. }
  464. // AddL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx.
  465. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  466. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  467. // EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.
  468. func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error {
  469. return tracerr.Wrap(hdb.addL1Txs(hdb.db, l1txs))
  470. }
  471. // addL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx.
  472. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  473. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  474. // EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.
  475. func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
  476. if len(l1txs) == 0 {
  477. return nil
  478. }
  479. txs := []txWrite{}
  480. for i := 0; i < len(l1txs); i++ {
  481. af := new(big.Float).SetInt(l1txs[i].Amount)
  482. amountFloat, _ := af.Float64()
  483. laf := new(big.Float).SetInt(l1txs[i].DepositAmount)
  484. depositAmountFloat, _ := laf.Float64()
  485. var effectiveFromIdx *common.Idx
  486. if l1txs[i].UserOrigin {
  487. if l1txs[i].Type != common.TxTypeCreateAccountDeposit &&
  488. l1txs[i].Type != common.TxTypeCreateAccountDepositTransfer {
  489. effectiveFromIdx = &l1txs[i].FromIdx
  490. }
  491. } else {
  492. effectiveFromIdx = &l1txs[i].EffectiveFromIdx
  493. }
  494. txs = append(txs, txWrite{
  495. // Generic
  496. IsL1: true,
  497. TxID: l1txs[i].TxID,
  498. Type: l1txs[i].Type,
  499. Position: l1txs[i].Position,
  500. FromIdx: &l1txs[i].FromIdx,
  501. EffectiveFromIdx: effectiveFromIdx,
  502. ToIdx: l1txs[i].ToIdx,
  503. Amount: l1txs[i].Amount,
  504. AmountFloat: amountFloat,
  505. TokenID: l1txs[i].TokenID,
  506. BatchNum: l1txs[i].BatchNum,
  507. EthBlockNum: l1txs[i].EthBlockNum,
  508. // L1
  509. ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
  510. UserOrigin: &l1txs[i].UserOrigin,
  511. FromEthAddr: &l1txs[i].FromEthAddr,
  512. FromBJJ: &l1txs[i].FromBJJ,
  513. DepositAmount: l1txs[i].DepositAmount,
  514. DepositAmountFloat: &depositAmountFloat,
  515. })
  516. }
  517. return tracerr.Wrap(hdb.addTxs(d, txs))
  518. }
  519. // AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  520. func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error {
  521. return tracerr.Wrap(hdb.addL2Txs(hdb.db, l2txs))
  522. }
  523. // addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  524. func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
  525. txs := []txWrite{}
  526. for i := 0; i < len(l2txs); i++ {
  527. f := new(big.Float).SetInt(l2txs[i].Amount)
  528. amountFloat, _ := f.Float64()
  529. txs = append(txs, txWrite{
  530. // Generic
  531. IsL1: false,
  532. TxID: l2txs[i].TxID,
  533. Type: l2txs[i].Type,
  534. Position: l2txs[i].Position,
  535. FromIdx: &l2txs[i].FromIdx,
  536. EffectiveFromIdx: &l2txs[i].FromIdx,
  537. ToIdx: l2txs[i].ToIdx,
  538. TokenID: l2txs[i].TokenID,
  539. Amount: l2txs[i].Amount,
  540. AmountFloat: amountFloat,
  541. BatchNum: &l2txs[i].BatchNum,
  542. EthBlockNum: l2txs[i].EthBlockNum,
  543. // L2
  544. Fee: &l2txs[i].Fee,
  545. Nonce: &l2txs[i].Nonce,
  546. })
  547. }
  548. return tracerr.Wrap(hdb.addTxs(d, txs))
  549. }
  550. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
  551. if len(txs) == 0 {
  552. return nil
  553. }
  554. return tracerr.Wrap(db.BulkInsert(
  555. d,
  556. `INSERT INTO tx (
  557. is_l1,
  558. id,
  559. type,
  560. position,
  561. from_idx,
  562. effective_from_idx,
  563. to_idx,
  564. amount,
  565. amount_f,
  566. token_id,
  567. batch_num,
  568. eth_block_num,
  569. to_forge_l1_txs_num,
  570. user_origin,
  571. from_eth_addr,
  572. from_bjj,
  573. deposit_amount,
  574. deposit_amount_f,
  575. fee,
  576. nonce
  577. ) VALUES %s;`,
  578. txs[:],
  579. ))
  580. }
  581. // GetAllExits returns all exit from the DB
  582. func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
  583. var exits []*common.ExitInfo
  584. err := meddler.QueryAll(
  585. hdb.db, &exits,
  586. `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
  587. exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
  588. exit_tree.delayed_withdrawn FROM exit_tree ORDER BY item_id;`,
  589. )
  590. return db.SlicePtrsToSlice(exits).([]common.ExitInfo), tracerr.Wrap(err)
  591. }
  592. // GetAllL1UserTxs returns all L1UserTxs from the DB
  593. func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
  594. var txs []*common.L1Tx
  595. err := meddler.QueryAll(
  596. hdb.db, &txs, // Note that '\x' gets parsed as a big.Int with value = 0
  597. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  598. tx.from_idx, tx.effective_from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  599. tx.amount, (CASE WHEN tx.batch_num IS NULL THEN NULL WHEN tx.amount_success THEN tx.amount ELSE '\x' END) AS effective_amount,
  600. tx.deposit_amount, (CASE WHEN tx.batch_num IS NULL THEN NULL WHEN tx.deposit_amount_success THEN tx.deposit_amount ELSE '\x' END) AS effective_deposit_amount,
  601. tx.eth_block_num, tx.type, tx.batch_num
  602. FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE ORDER BY item_id;`,
  603. )
  604. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  605. }
  606. // GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
  607. func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
  608. var txs []*common.L1Tx
  609. // Since the query specifies that only coordinator txs are returned, it's safe to assume
  610. // that returned txs will always have effective amounts
  611. err := meddler.QueryAll(
  612. hdb.db, &txs,
  613. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  614. tx.from_idx, tx.effective_from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  615. tx.amount, tx.amount AS effective_amount,
  616. tx.deposit_amount, tx.deposit_amount AS effective_deposit_amount,
  617. tx.eth_block_num, tx.type, tx.batch_num
  618. FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE ORDER BY item_id;`,
  619. )
  620. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  621. }
  622. // GetAllL2Txs returns all L2Txs from the DB
  623. func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
  624. var txs []*common.L2Tx
  625. err := meddler.QueryAll(
  626. hdb.db, &txs,
  627. `SELECT tx.id, tx.batch_num, tx.position,
  628. tx.from_idx, tx.to_idx, tx.amount, tx.token_id,
  629. tx.fee, tx.nonce, tx.type, tx.eth_block_num
  630. FROM tx WHERE is_l1 = FALSE ORDER BY item_id;`,
  631. )
  632. return db.SlicePtrsToSlice(txs).([]common.L2Tx), tracerr.Wrap(err)
  633. }
  634. // GetUnforgedL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
  635. func (hdb *HistoryDB) GetUnforgedL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
  636. var txs []*common.L1Tx
  637. err := meddler.QueryAll(
  638. hdb.db, &txs, // only L1 user txs can have batch_num set to null
  639. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  640. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  641. tx.amount, NULL AS effective_amount,
  642. tx.deposit_amount, NULL AS effective_deposit_amount,
  643. tx.eth_block_num, tx.type, tx.batch_num
  644. FROM tx WHERE batch_num IS NULL AND to_forge_l1_txs_num = $1
  645. ORDER BY position;`,
  646. toForgeL1TxsNum,
  647. )
  648. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  649. }
  650. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  651. // GetLastTxsPosition for a given to_forge_l1_txs_num
  652. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  653. row := hdb.db.QueryRow(
  654. "SELECT position FROM tx WHERE to_forge_l1_txs_num = $1 ORDER BY position DESC;",
  655. toForgeL1TxsNum,
  656. )
  657. var lastL1TxsPosition int
  658. return lastL1TxsPosition, tracerr.Wrap(row.Scan(&lastL1TxsPosition))
  659. }
  660. // GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
  661. func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
  662. *common.WDelayerVariables, error) {
  663. var rollup common.RollupVariables
  664. var auction common.AuctionVariables
  665. var wDelayer common.WDelayerVariables
  666. if err := meddler.QueryRow(hdb.db, &rollup,
  667. "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  668. return nil, nil, nil, tracerr.Wrap(err)
  669. }
  670. if err := meddler.QueryRow(hdb.db, &auction,
  671. "SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  672. return nil, nil, nil, tracerr.Wrap(err)
  673. }
  674. if err := meddler.QueryRow(hdb.db, &wDelayer,
  675. "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  676. return nil, nil, nil, tracerr.Wrap(err)
  677. }
  678. return &rollup, &auction, &wDelayer, nil
  679. }
  680. func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
  681. return tracerr.Wrap(meddler.Insert(d, "rollup_vars", rollup))
  682. }
  683. func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
  684. return tracerr.Wrap(meddler.Insert(d, "auction_vars", auction))
  685. }
  686. func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
  687. return tracerr.Wrap(meddler.Insert(d, "wdelayer_vars", wDelayer))
  688. }
  689. func (hdb *HistoryDB) addBucketUpdates(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
  690. if len(bucketUpdates) == 0 {
  691. return nil
  692. }
  693. return tracerr.Wrap(db.BulkInsert(
  694. d,
  695. `INSERT INTO bucket_update (
  696. eth_block_num,
  697. num_bucket,
  698. block_stamp,
  699. withdrawals
  700. ) VALUES %s;`,
  701. bucketUpdates[:],
  702. ))
  703. }
  704. // AddBucketUpdatesTest allows call to unexported method
  705. // only for internal testing purposes
  706. func (hdb *HistoryDB) AddBucketUpdatesTest(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
  707. return hdb.addBucketUpdates(d, bucketUpdates)
  708. }
  709. // GetAllBucketUpdates retrieves all the bucket updates
  710. func (hdb *HistoryDB) GetAllBucketUpdates() ([]common.BucketUpdate, error) {
  711. var bucketUpdates []*common.BucketUpdate
  712. err := meddler.QueryAll(
  713. hdb.db, &bucketUpdates,
  714. `SELECT eth_block_num, num_bucket, block_stamp, withdrawals
  715. FROM bucket_update ORDER BY item_id;`,
  716. )
  717. return db.SlicePtrsToSlice(bucketUpdates).([]common.BucketUpdate), tracerr.Wrap(err)
  718. }
  719. func (hdb *HistoryDB) addTokenExchanges(d meddler.DB, tokenExchanges []common.TokenExchange) error {
  720. if len(tokenExchanges) == 0 {
  721. return nil
  722. }
  723. return tracerr.Wrap(db.BulkInsert(
  724. d,
  725. `INSERT INTO token_exchange (
  726. eth_block_num,
  727. eth_addr,
  728. value_usd
  729. ) VALUES %s;`,
  730. tokenExchanges[:],
  731. ))
  732. }
  733. // GetAllTokenExchanges retrieves all the token exchanges
  734. func (hdb *HistoryDB) GetAllTokenExchanges() ([]common.TokenExchange, error) {
  735. var tokenExchanges []*common.TokenExchange
  736. err := meddler.QueryAll(
  737. hdb.db, &tokenExchanges,
  738. "SELECT eth_block_num, eth_addr, value_usd FROM token_exchange ORDER BY item_id;",
  739. )
  740. return db.SlicePtrsToSlice(tokenExchanges).([]common.TokenExchange), tracerr.Wrap(err)
  741. }
  742. func (hdb *HistoryDB) addEscapeHatchWithdrawals(d meddler.DB,
  743. escapeHatchWithdrawals []common.WDelayerEscapeHatchWithdrawal) error {
  744. if len(escapeHatchWithdrawals) == 0 {
  745. return nil
  746. }
  747. return tracerr.Wrap(db.BulkInsert(
  748. d,
  749. `INSERT INTO escape_hatch_withdrawal (
  750. eth_block_num,
  751. who_addr,
  752. to_addr,
  753. token_addr,
  754. amount
  755. ) VALUES %s;`,
  756. escapeHatchWithdrawals[:],
  757. ))
  758. }
  759. // GetAllEscapeHatchWithdrawals retrieves all the escape hatch withdrawals
  760. func (hdb *HistoryDB) GetAllEscapeHatchWithdrawals() ([]common.WDelayerEscapeHatchWithdrawal, error) {
  761. var escapeHatchWithdrawals []*common.WDelayerEscapeHatchWithdrawal
  762. err := meddler.QueryAll(
  763. hdb.db, &escapeHatchWithdrawals,
  764. "SELECT eth_block_num, who_addr, to_addr, token_addr, amount FROM escape_hatch_withdrawal ORDER BY item_id;",
  765. )
  766. return db.SlicePtrsToSlice(escapeHatchWithdrawals).([]common.WDelayerEscapeHatchWithdrawal),
  767. tracerr.Wrap(err)
  768. }
  769. // SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
  770. // contract variables. This initial state is stored linked to block 0, which
  771. // always exist in the DB and is used to store initialization data that always
  772. // exist in the smart contracts.
  773. func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
  774. auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
  775. txn, err := hdb.db.Beginx()
  776. if err != nil {
  777. return tracerr.Wrap(err)
  778. }
  779. defer func() {
  780. if err != nil {
  781. db.Rollback(txn)
  782. }
  783. }()
  784. // Force EthBlockNum to be 0 because it's the block used to link data
  785. // that belongs to the creation of the smart contracts
  786. rollup.EthBlockNum = 0
  787. auction.EthBlockNum = 0
  788. wDelayer.EthBlockNum = 0
  789. auction.DefaultSlotSetBidSlotNum = 0
  790. if err := hdb.setRollupVars(txn, rollup); err != nil {
  791. return tracerr.Wrap(err)
  792. }
  793. if err := hdb.setAuctionVars(txn, auction); err != nil {
  794. return tracerr.Wrap(err)
  795. }
  796. if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
  797. return tracerr.Wrap(err)
  798. }
  799. return tracerr.Wrap(txn.Commit())
  800. }
  801. // setExtraInfoForgedL1UserTxs sets the EffectiveAmount, EffectiveDepositAmount
  802. // and EffectiveFromIdx of the given l1UserTxs (with an UPDATE)
  803. func (hdb *HistoryDB) setExtraInfoForgedL1UserTxs(d sqlx.Ext, txs []common.L1Tx) error {
  804. if len(txs) == 0 {
  805. return nil
  806. }
  807. // Effective amounts are stored as success flags in the DB, with true value by default
  808. // to reduce the amount of updates. Therefore, only amounts that became uneffective should be
  809. // updated to become false. At the same time, all the txs that contain
  810. // accounts (FromIdx == 0) are updated to set the EffectiveFromIdx.
  811. type txUpdate struct {
  812. ID common.TxID `db:"id"`
  813. AmountSuccess bool `db:"amount_success"`
  814. DepositAmountSuccess bool `db:"deposit_amount_success"`
  815. EffectiveFromIdx common.Idx `db:"effective_from_idx"`
  816. }
  817. txUpdates := []txUpdate{}
  818. equal := func(a *big.Int, b *big.Int) bool {
  819. return a.Cmp(b) == 0
  820. }
  821. for i := range txs {
  822. amountSuccess := equal(txs[i].Amount, txs[i].EffectiveAmount)
  823. depositAmountSuccess := equal(txs[i].DepositAmount, txs[i].EffectiveDepositAmount)
  824. if !amountSuccess || !depositAmountSuccess || txs[i].FromIdx == 0 {
  825. txUpdates = append(txUpdates, txUpdate{
  826. ID: txs[i].TxID,
  827. AmountSuccess: amountSuccess,
  828. DepositAmountSuccess: depositAmountSuccess,
  829. EffectiveFromIdx: txs[i].EffectiveFromIdx,
  830. })
  831. }
  832. }
  833. const query string = `
  834. UPDATE tx SET
  835. amount_success = tx_update.amount_success,
  836. deposit_amount_success = tx_update.deposit_amount_success,
  837. effective_from_idx = tx_update.effective_from_idx
  838. FROM (VALUES
  839. (NULL::::BYTEA, NULL::::BOOL, NULL::::BOOL, NULL::::BIGINT),
  840. (:id, :amount_success, :deposit_amount_success, :effective_from_idx)
  841. ) as tx_update (id, amount_success, deposit_amount_success, effective_from_idx)
  842. WHERE tx.id = tx_update.id;
  843. `
  844. if len(txUpdates) > 0 {
  845. if _, err := sqlx.NamedExec(d, query, txUpdates); err != nil {
  846. return tracerr.Wrap(err)
  847. }
  848. }
  849. return nil
  850. }
  851. // AddBlockSCData stores all the information of a block retrieved by the
  852. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  853. // the pagination system of the API/DB depends on this. Within blocks, all
  854. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  855. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  856. txn, err := hdb.db.Beginx()
  857. if err != nil {
  858. return tracerr.Wrap(err)
  859. }
  860. defer func() {
  861. if err != nil {
  862. db.Rollback(txn)
  863. }
  864. }()
  865. // Add block
  866. if err := hdb.addBlock(txn, &blockData.Block); err != nil {
  867. return tracerr.Wrap(err)
  868. }
  869. // Add Coordinators
  870. if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
  871. return tracerr.Wrap(err)
  872. }
  873. // Add Bids
  874. if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
  875. return tracerr.Wrap(err)
  876. }
  877. // Add Tokens
  878. if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
  879. return tracerr.Wrap(err)
  880. }
  881. // Prepare user L1 txs to be added.
  882. // They must be added before the batch that will forge them (which can be in the same block)
  883. // and after the account that will be sent to (also can be in the same block).
  884. // Note: insert order is not relevant since item_id will be updated by a DB trigger when
  885. // the batch that forges those txs is inserted
  886. userL1s := make(map[common.BatchNum][]common.L1Tx)
  887. for i := range blockData.Rollup.L1UserTxs {
  888. batchThatForgesIsInTheBlock := false
  889. for _, batch := range blockData.Rollup.Batches {
  890. if batch.Batch.ForgeL1TxsNum != nil &&
  891. *batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
  892. // Tx is forged in this block. It's guaranteed that:
  893. // * the first batch of the block won't forge user L1 txs that have been added in this block
  894. // * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
  895. batchThatForgesIsInTheBlock = true
  896. addAtBatchNum := batch.Batch.BatchNum - 1
  897. userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
  898. break
  899. }
  900. }
  901. if !batchThatForgesIsInTheBlock {
  902. // User artificial batchNum 0 to add txs that are not forge in this block
  903. // after all the accounts of the block have been added
  904. userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
  905. }
  906. }
  907. // Add Batches
  908. for i := range blockData.Rollup.Batches {
  909. batch := &blockData.Rollup.Batches[i]
  910. // Add Batch: this will trigger an update on the DB
  911. // that will set the batch num of forged L1 txs in this batch
  912. if err = hdb.addBatch(txn, &batch.Batch); err != nil {
  913. return tracerr.Wrap(err)
  914. }
  915. // Add accounts
  916. if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
  917. return tracerr.Wrap(err)
  918. }
  919. // Set the EffectiveAmount and EffectiveDepositAmount of all the
  920. // L1UserTxs that have been forged in this batch
  921. if err = hdb.setExtraInfoForgedL1UserTxs(txn, batch.L1UserTxs); err != nil {
  922. return tracerr.Wrap(err)
  923. }
  924. // Add forged l1 coordinator Txs
  925. if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
  926. return tracerr.Wrap(err)
  927. }
  928. // Add l2 Txs
  929. if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
  930. return tracerr.Wrap(err)
  931. }
  932. // Add user L1 txs that will be forged in next batch
  933. if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
  934. if err := hdb.addL1Txs(txn, userlL1s); err != nil {
  935. return tracerr.Wrap(err)
  936. }
  937. }
  938. // Add exit tree
  939. if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
  940. return tracerr.Wrap(err)
  941. }
  942. }
  943. // Add user L1 txs that won't be forged in this block
  944. if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
  945. if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
  946. return tracerr.Wrap(err)
  947. }
  948. }
  949. // Set SC Vars if there was an update
  950. if blockData.Rollup.Vars != nil {
  951. if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
  952. return tracerr.Wrap(err)
  953. }
  954. }
  955. if blockData.Auction.Vars != nil {
  956. if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
  957. return tracerr.Wrap(err)
  958. }
  959. }
  960. if blockData.WDelayer.Vars != nil {
  961. if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
  962. return tracerr.Wrap(err)
  963. }
  964. }
  965. // Update withdrawals in exit tree table
  966. if err := hdb.updateExitTree(txn, blockData.Block.Num,
  967. blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
  968. return tracerr.Wrap(err)
  969. }
  970. // Add Escape Hatch Withdrawals
  971. if err := hdb.addEscapeHatchWithdrawals(txn,
  972. blockData.WDelayer.EscapeHatchWithdrawals); err != nil {
  973. return tracerr.Wrap(err)
  974. }
  975. // Add Buckets withdrawals updates
  976. if err := hdb.addBucketUpdates(txn, blockData.Rollup.UpdateBucketWithdraw); err != nil {
  977. return tracerr.Wrap(err)
  978. }
  979. // Add Token exchange updates
  980. if err := hdb.addTokenExchanges(txn, blockData.Rollup.TokenExchanges); err != nil {
  981. return tracerr.Wrap(err)
  982. }
  983. return tracerr.Wrap(txn.Commit())
  984. }
  985. // GetCoordinatorAPI returns a coordinator by its bidderAddr
  986. func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
  987. coordinator := &CoordinatorAPI{}
  988. err := meddler.QueryRow(
  989. hdb.db, coordinator,
  990. "SELECT * FROM coordinator WHERE bidder_addr = $1 ORDER BY item_id DESC LIMIT 1;",
  991. bidderAddr,
  992. )
  993. return coordinator, tracerr.Wrap(err)
  994. }
  995. // AddAuctionVars insert auction vars into the DB
  996. func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
  997. return tracerr.Wrap(meddler.Insert(hdb.db, "auction_vars", auctionVars))
  998. }
  999. // GetTokensTest used to get tokens in a testing context
  1000. func (hdb *HistoryDB) GetTokensTest() ([]TokenWithUSD, error) {
  1001. tokens := []*TokenWithUSD{}
  1002. if err := meddler.QueryAll(
  1003. hdb.db, &tokens,
  1004. "SELECT * FROM TOKEN",
  1005. ); err != nil {
  1006. return nil, tracerr.Wrap(err)
  1007. }
  1008. if len(tokens) == 0 {
  1009. return []TokenWithUSD{}, nil
  1010. }
  1011. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), nil
  1012. }