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.

1894 lines
59 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
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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package historydb
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "math/big"
  8. ethCommon "github.com/ethereum/go-ethereum/common"
  9. "github.com/hermeznetwork/hermez-node/common"
  10. "github.com/hermeznetwork/hermez-node/db"
  11. "github.com/hermeznetwork/tracerr"
  12. "github.com/iden3/go-iden3-crypto/babyjub"
  13. "github.com/jmoiron/sqlx"
  14. //nolint:errcheck // driver for postgres DB
  15. _ "github.com/lib/pq"
  16. "github.com/russross/meddler"
  17. )
  18. const (
  19. // OrderAsc indicates ascending order when using pagination
  20. OrderAsc = "ASC"
  21. // OrderDesc indicates descending order when using pagination
  22. OrderDesc = "DESC"
  23. )
  24. // TODO(Edu): Document here how HistoryDB is kept consistent
  25. // HistoryDB persist the historic of the rollup
  26. type HistoryDB struct {
  27. db *sqlx.DB
  28. }
  29. // NewHistoryDB initialize the DB
  30. func NewHistoryDB(db *sqlx.DB) *HistoryDB {
  31. return &HistoryDB{db: db}
  32. }
  33. // DB returns a pointer to the L2DB.db. This method should be used only for
  34. // internal testing purposes.
  35. func (hdb *HistoryDB) DB() *sqlx.DB {
  36. return hdb.db
  37. }
  38. // AddBlock insert a block into the DB
  39. func (hdb *HistoryDB) AddBlock(block *common.Block) error { return hdb.addBlock(hdb.db, block) }
  40. func (hdb *HistoryDB) addBlock(d meddler.DB, block *common.Block) error {
  41. return tracerr.Wrap(meddler.Insert(d, "block", block))
  42. }
  43. // AddBlocks inserts blocks into the DB
  44. func (hdb *HistoryDB) AddBlocks(blocks []common.Block) error {
  45. return tracerr.Wrap(hdb.addBlocks(hdb.db, blocks))
  46. }
  47. func (hdb *HistoryDB) addBlocks(d meddler.DB, blocks []common.Block) error {
  48. return tracerr.Wrap(db.BulkInsert(
  49. d,
  50. `INSERT INTO block (
  51. eth_block_num,
  52. timestamp,
  53. hash
  54. ) VALUES %s;`,
  55. blocks[:],
  56. ))
  57. }
  58. // GetBlock retrieve a block from the DB, given a block number
  59. func (hdb *HistoryDB) GetBlock(blockNum int64) (*common.Block, error) {
  60. block := &common.Block{}
  61. err := meddler.QueryRow(
  62. hdb.db, block,
  63. "SELECT * FROM block WHERE eth_block_num = $1;", blockNum,
  64. )
  65. return block, tracerr.Wrap(err)
  66. }
  67. // GetAllBlocks retrieve all blocks from the DB
  68. func (hdb *HistoryDB) GetAllBlocks() ([]common.Block, error) {
  69. var blocks []*common.Block
  70. err := meddler.QueryAll(
  71. hdb.db, &blocks,
  72. "SELECT * FROM block ORDER BY eth_block_num;",
  73. )
  74. return db.SlicePtrsToSlice(blocks).([]common.Block), tracerr.Wrap(err)
  75. }
  76. // GetBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to
  77. func (hdb *HistoryDB) GetBlocks(from, to int64) ([]common.Block, error) {
  78. var blocks []*common.Block
  79. err := meddler.QueryAll(
  80. hdb.db, &blocks,
  81. "SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2 ORDER BY eth_block_num;",
  82. from, to,
  83. )
  84. return db.SlicePtrsToSlice(blocks).([]common.Block), tracerr.Wrap(err)
  85. }
  86. // GetLastBlock retrieve the block with the highest block number from the DB
  87. func (hdb *HistoryDB) GetLastBlock() (*common.Block, error) {
  88. block := &common.Block{}
  89. err := meddler.QueryRow(
  90. hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;",
  91. )
  92. return block, tracerr.Wrap(err)
  93. }
  94. // AddBatch insert a Batch into the DB
  95. func (hdb *HistoryDB) AddBatch(batch *common.Batch) error { return hdb.addBatch(hdb.db, batch) }
  96. func (hdb *HistoryDB) addBatch(d meddler.DB, batch *common.Batch) error {
  97. // Calculate total collected fees in USD
  98. // Get IDs of collected tokens for fees
  99. tokenIDs := []common.TokenID{}
  100. for id := range batch.CollectedFees {
  101. tokenIDs = append(tokenIDs, id)
  102. }
  103. // Get USD value of the tokens
  104. type tokenPrice struct {
  105. ID common.TokenID `meddler:"token_id"`
  106. USD *float64 `meddler:"usd"`
  107. Decimals int `meddler:"decimals"`
  108. }
  109. var tokenPrices []*tokenPrice
  110. if len(tokenIDs) > 0 {
  111. query, args, err := sqlx.In(
  112. "SELECT token_id, usd, decimals FROM token WHERE token_id IN (?);",
  113. tokenIDs,
  114. )
  115. if err != nil {
  116. return tracerr.Wrap(err)
  117. }
  118. query = hdb.db.Rebind(query)
  119. if err := meddler.QueryAll(
  120. hdb.db, &tokenPrices, query, args...,
  121. ); err != nil {
  122. return tracerr.Wrap(err)
  123. }
  124. }
  125. // Calculate total collected
  126. var total float64
  127. for _, tokenPrice := range tokenPrices {
  128. if tokenPrice.USD == nil {
  129. continue
  130. }
  131. f := new(big.Float).SetInt(batch.CollectedFees[tokenPrice.ID])
  132. amount, _ := f.Float64()
  133. total += *tokenPrice.USD * (amount / math.Pow(10, float64(tokenPrice.Decimals))) //nolint decimals have to be ^10
  134. }
  135. batch.TotalFeesUSD = &total
  136. // Insert to DB
  137. return tracerr.Wrap(meddler.Insert(d, "batch", batch))
  138. }
  139. // AddBatches insert Bids into the DB
  140. func (hdb *HistoryDB) AddBatches(batches []common.Batch) error {
  141. return tracerr.Wrap(hdb.addBatches(hdb.db, batches))
  142. }
  143. func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error {
  144. for i := 0; i < len(batches); i++ {
  145. if err := hdb.addBatch(d, &batches[i]); err != nil {
  146. return tracerr.Wrap(err)
  147. }
  148. }
  149. return nil
  150. }
  151. // GetBatchAPI return the batch with the given batchNum
  152. func (hdb *HistoryDB) GetBatchAPI(batchNum common.BatchNum) (*BatchAPI, error) {
  153. batch := &BatchAPI{}
  154. return batch, tracerr.Wrap(meddler.QueryRow(
  155. hdb.db, batch,
  156. `SELECT batch.*, block.timestamp, block.hash,
  157. COALESCE ((SELECT COUNT(*) FROM tx WHERE batch_num = batch.batch_num), 0) AS forged_txs
  158. FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num
  159. WHERE batch_num = $1;`, batchNum,
  160. ))
  161. }
  162. // GetBatchesAPI return the batches applying the given filters
  163. func (hdb *HistoryDB) GetBatchesAPI(
  164. minBatchNum, maxBatchNum, slotNum *uint,
  165. forgerAddr *ethCommon.Address,
  166. fromItem, limit *uint, order string,
  167. ) ([]BatchAPI, uint64, error) {
  168. var query string
  169. var args []interface{}
  170. queryStr := `SELECT batch.*, block.timestamp, block.hash,
  171. COALESCE ((SELECT COUNT(*) FROM tx WHERE batch_num = batch.batch_num), 0) AS forged_txs,
  172. count(*) OVER() AS total_items
  173. FROM batch INNER JOIN block ON batch.eth_block_num = block.eth_block_num `
  174. // Apply filters
  175. nextIsAnd := false
  176. // minBatchNum filter
  177. if minBatchNum != nil {
  178. if nextIsAnd {
  179. queryStr += "AND "
  180. } else {
  181. queryStr += "WHERE "
  182. }
  183. queryStr += "batch.batch_num > ? "
  184. args = append(args, minBatchNum)
  185. nextIsAnd = true
  186. }
  187. // maxBatchNum filter
  188. if maxBatchNum != nil {
  189. if nextIsAnd {
  190. queryStr += "AND "
  191. } else {
  192. queryStr += "WHERE "
  193. }
  194. queryStr += "batch.batch_num < ? "
  195. args = append(args, maxBatchNum)
  196. nextIsAnd = true
  197. }
  198. // slotNum filter
  199. if slotNum != nil {
  200. if nextIsAnd {
  201. queryStr += "AND "
  202. } else {
  203. queryStr += "WHERE "
  204. }
  205. queryStr += "batch.slot_num = ? "
  206. args = append(args, slotNum)
  207. nextIsAnd = true
  208. }
  209. // forgerAddr filter
  210. if forgerAddr != nil {
  211. if nextIsAnd {
  212. queryStr += "AND "
  213. } else {
  214. queryStr += "WHERE "
  215. }
  216. queryStr += "batch.forger_addr = ? "
  217. args = append(args, forgerAddr)
  218. nextIsAnd = true
  219. }
  220. // pagination
  221. if fromItem != nil {
  222. if nextIsAnd {
  223. queryStr += "AND "
  224. } else {
  225. queryStr += "WHERE "
  226. }
  227. if order == OrderAsc {
  228. queryStr += "batch.item_id >= ? "
  229. } else {
  230. queryStr += "batch.item_id <= ? "
  231. }
  232. args = append(args, fromItem)
  233. }
  234. queryStr += "ORDER BY batch.item_id "
  235. if order == OrderAsc {
  236. queryStr += " ASC "
  237. } else {
  238. queryStr += " DESC "
  239. }
  240. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  241. query = hdb.db.Rebind(queryStr)
  242. // log.Debug(query)
  243. batchPtrs := []*BatchAPI{}
  244. if err := meddler.QueryAll(hdb.db, &batchPtrs, query, args...); err != nil {
  245. return nil, 0, tracerr.Wrap(err)
  246. }
  247. batches := db.SlicePtrsToSlice(batchPtrs).([]BatchAPI)
  248. if len(batches) == 0 {
  249. return nil, 0, tracerr.Wrap(sql.ErrNoRows)
  250. }
  251. return batches, batches[0].TotalItems - uint64(len(batches)), nil
  252. }
  253. // GetAllBatches retrieve all batches from the DB
  254. func (hdb *HistoryDB) GetAllBatches() ([]common.Batch, error) {
  255. var batches []*common.Batch
  256. err := meddler.QueryAll(
  257. hdb.db, &batches,
  258. `SELECT batch.batch_num, batch.eth_block_num, batch.forger_addr, batch.fees_collected,
  259. batch.fee_idxs_coordinator, batch.state_root, batch.num_accounts, batch.last_idx, batch.exit_root,
  260. batch.forge_l1_txs_num, batch.slot_num, batch.total_fees_usd FROM batch
  261. ORDER BY item_id;`,
  262. )
  263. return db.SlicePtrsToSlice(batches).([]common.Batch), tracerr.Wrap(err)
  264. }
  265. // GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to
  266. func (hdb *HistoryDB) GetBatches(from, to common.BatchNum) ([]common.Batch, error) {
  267. var batches []*common.Batch
  268. err := meddler.QueryAll(
  269. hdb.db, &batches,
  270. "SELECT * FROM batch WHERE $1 <= batch_num AND batch_num < $2 ORDER BY batch_num;",
  271. from, to,
  272. )
  273. return db.SlicePtrsToSlice(batches).([]common.Batch), tracerr.Wrap(err)
  274. }
  275. // GetFirstBatchBlockNumBySlot returns the ethereum block number of the first
  276. // batch within a slot
  277. func (hdb *HistoryDB) GetFirstBatchBlockNumBySlot(slotNum int64) (int64, error) {
  278. row := hdb.db.QueryRow(
  279. `SELECT eth_block_num FROM batch
  280. WHERE slot_num = $1 ORDER BY batch_num ASC LIMIT 1;`, slotNum,
  281. )
  282. var blockNum int64
  283. return blockNum, tracerr.Wrap(row.Scan(&blockNum))
  284. }
  285. // GetLastBatchNum returns the BatchNum of the latest forged batch
  286. func (hdb *HistoryDB) GetLastBatchNum() (common.BatchNum, error) {
  287. row := hdb.db.QueryRow("SELECT batch_num FROM batch ORDER BY batch_num DESC LIMIT 1;")
  288. var batchNum common.BatchNum
  289. return batchNum, tracerr.Wrap(row.Scan(&batchNum))
  290. }
  291. // GetLastL1BatchBlockNum returns the blockNum of the latest forged l1Batch
  292. func (hdb *HistoryDB) GetLastL1BatchBlockNum() (int64, error) {
  293. row := hdb.db.QueryRow(`SELECT eth_block_num FROM batch
  294. WHERE forge_l1_txs_num IS NOT NULL
  295. ORDER BY batch_num DESC LIMIT 1;`)
  296. var blockNum int64
  297. return blockNum, tracerr.Wrap(row.Scan(&blockNum))
  298. }
  299. // GetLastL1TxsNum returns the greatest ForgeL1TxsNum in the DB from forged
  300. // batches. If there's no batch in the DB (nil, nil) is returned.
  301. func (hdb *HistoryDB) GetLastL1TxsNum() (*int64, error) {
  302. row := hdb.db.QueryRow("SELECT MAX(forge_l1_txs_num) FROM batch;")
  303. lastL1TxsNum := new(int64)
  304. return lastL1TxsNum, tracerr.Wrap(row.Scan(&lastL1TxsNum))
  305. }
  306. // Reorg deletes all the information that was added into the DB after the
  307. // lastValidBlock. If lastValidBlock is negative, all block information is
  308. // deleted.
  309. func (hdb *HistoryDB) Reorg(lastValidBlock int64) error {
  310. var err error
  311. if lastValidBlock < 0 {
  312. _, err = hdb.db.Exec("DELETE FROM block;")
  313. } else {
  314. _, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock)
  315. }
  316. return tracerr.Wrap(err)
  317. }
  318. // AddBids insert Bids into the DB
  319. func (hdb *HistoryDB) AddBids(bids []common.Bid) error { return hdb.addBids(hdb.db, bids) }
  320. func (hdb *HistoryDB) addBids(d meddler.DB, bids []common.Bid) error {
  321. if len(bids) == 0 {
  322. return nil
  323. }
  324. // TODO: check the coordinator info
  325. return tracerr.Wrap(db.BulkInsert(
  326. d,
  327. "INSERT INTO bid (slot_num, bid_value, eth_block_num, bidder_addr) VALUES %s;",
  328. bids[:],
  329. ))
  330. }
  331. // GetAllBids retrieve all bids from the DB
  332. func (hdb *HistoryDB) GetAllBids() ([]common.Bid, error) {
  333. var bids []*common.Bid
  334. err := meddler.QueryAll(
  335. hdb.db, &bids,
  336. `SELECT bid.slot_num, bid.bid_value, bid.eth_block_num, bid.bidder_addr FROM bid
  337. ORDER BY item_id;`,
  338. )
  339. return db.SlicePtrsToSlice(bids).([]common.Bid), tracerr.Wrap(err)
  340. }
  341. // GetBestBidAPI returns the best bid in specific slot by slotNum
  342. func (hdb *HistoryDB) GetBestBidAPI(slotNum *int64) (BidAPI, error) {
  343. bid := &BidAPI{}
  344. err := meddler.QueryRow(
  345. hdb.db, bid, `SELECT bid.*, block.timestamp, coordinator.forger_addr, coordinator.url
  346. FROM bid INNER JOIN block ON bid.eth_block_num = block.eth_block_num
  347. INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr
  348. WHERE slot_num = $1 ORDER BY item_id DESC LIMIT 1;`, slotNum,
  349. )
  350. return *bid, tracerr.Wrap(err)
  351. }
  352. // GetBestBidCoordinator returns the forger address of the highest bidder in a slot by slotNum
  353. func (hdb *HistoryDB) GetBestBidCoordinator(slotNum int64) (*common.BidCoordinator, error) {
  354. bidCoord := &common.BidCoordinator{}
  355. err := meddler.QueryRow(
  356. hdb.db, bidCoord,
  357. `SELECT (
  358. SELECT default_slot_set_bid
  359. FROM auction_vars
  360. WHERE default_slot_set_bid_slot_num <= $1
  361. ORDER BY eth_block_num DESC LIMIT 1
  362. ),
  363. bid.slot_num, bid.bid_value, bid.bidder_addr,
  364. coordinator.forger_addr, coordinator.url
  365. FROM bid
  366. INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr
  367. WHERE bid.slot_num = $1 ORDER BY bid.item_id DESC LIMIT 1;`,
  368. slotNum)
  369. return bidCoord, tracerr.Wrap(err)
  370. }
  371. // GetBestBidsAPI returns the best bid in specific slot by slotNum
  372. func (hdb *HistoryDB) GetBestBidsAPI(
  373. minSlotNum, maxSlotNum *int64,
  374. bidderAddr *ethCommon.Address,
  375. limit *uint, order string,
  376. ) ([]BidAPI, uint64, error) {
  377. var query string
  378. var args []interface{}
  379. queryStr := `SELECT b.*, block.timestamp, coordinator.forger_addr, coordinator.url,
  380. COUNT(*) OVER() AS total_items FROM (
  381. SELECT slot_num, MAX(item_id) as maxitem
  382. FROM bid GROUP BY slot_num
  383. )
  384. AS x INNER JOIN bid AS b ON b.item_id = x.maxitem
  385. INNER JOIN block ON b.eth_block_num = block.eth_block_num
  386. INNER JOIN coordinator ON b.bidder_addr = coordinator.bidder_addr
  387. WHERE (b.slot_num >= ? AND b.slot_num <= ?)`
  388. args = append(args, minSlotNum)
  389. args = append(args, maxSlotNum)
  390. // Apply filters
  391. if bidderAddr != nil {
  392. queryStr += " AND b.bidder_addr = ? "
  393. args = append(args, bidderAddr)
  394. }
  395. queryStr += " ORDER BY b.slot_num "
  396. if order == OrderAsc {
  397. queryStr += "ASC "
  398. } else {
  399. queryStr += "DESC "
  400. }
  401. if limit != nil {
  402. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  403. }
  404. query = hdb.db.Rebind(queryStr)
  405. bidPtrs := []*BidAPI{}
  406. if err := meddler.QueryAll(hdb.db, &bidPtrs, query, args...); err != nil {
  407. return nil, 0, tracerr.Wrap(err)
  408. }
  409. // log.Debug(query)
  410. bids := db.SlicePtrsToSlice(bidPtrs).([]BidAPI)
  411. if len(bids) == 0 {
  412. return nil, 0, tracerr.Wrap(sql.ErrNoRows)
  413. }
  414. return bids, bids[0].TotalItems - uint64(len(bids)), nil
  415. }
  416. // GetBidsAPI return the bids applying the given filters
  417. func (hdb *HistoryDB) GetBidsAPI(
  418. slotNum *int64, forgerAddr *ethCommon.Address,
  419. fromItem, limit *uint, order string,
  420. ) ([]BidAPI, uint64, error) {
  421. var query string
  422. var args []interface{}
  423. queryStr := `SELECT bid.*, block.timestamp, coordinator.forger_addr, coordinator.url,
  424. COUNT(*) OVER() AS total_items
  425. FROM bid INNER JOIN block ON bid.eth_block_num = block.eth_block_num
  426. INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr `
  427. // Apply filters
  428. nextIsAnd := false
  429. // slotNum filter
  430. if slotNum != nil {
  431. if nextIsAnd {
  432. queryStr += "AND "
  433. } else {
  434. queryStr += "WHERE "
  435. }
  436. queryStr += "bid.slot_num = ? "
  437. args = append(args, slotNum)
  438. nextIsAnd = true
  439. }
  440. // slotNum filter
  441. if forgerAddr != nil {
  442. if nextIsAnd {
  443. queryStr += "AND "
  444. } else {
  445. queryStr += "WHERE "
  446. }
  447. queryStr += "bid.bidder_addr = ? "
  448. args = append(args, forgerAddr)
  449. nextIsAnd = true
  450. }
  451. if fromItem != nil {
  452. if nextIsAnd {
  453. queryStr += "AND "
  454. } else {
  455. queryStr += "WHERE "
  456. }
  457. if order == OrderAsc {
  458. queryStr += "bid.item_id >= ? "
  459. } else {
  460. queryStr += "bid.item_id <= ? "
  461. }
  462. args = append(args, fromItem)
  463. }
  464. // pagination
  465. queryStr += "ORDER BY bid.item_id "
  466. if order == OrderAsc {
  467. queryStr += "ASC "
  468. } else {
  469. queryStr += "DESC "
  470. }
  471. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  472. query, argsQ, err := sqlx.In(queryStr, args...)
  473. if err != nil {
  474. return nil, 0, tracerr.Wrap(err)
  475. }
  476. query = hdb.db.Rebind(query)
  477. bids := []*BidAPI{}
  478. if err := meddler.QueryAll(hdb.db, &bids, query, argsQ...); err != nil {
  479. return nil, 0, tracerr.Wrap(err)
  480. }
  481. if len(bids) == 0 {
  482. return nil, 0, tracerr.Wrap(sql.ErrNoRows)
  483. }
  484. return db.SlicePtrsToSlice(bids).([]BidAPI), bids[0].TotalItems - uint64(len(bids)), nil
  485. }
  486. // AddCoordinators insert Coordinators into the DB
  487. func (hdb *HistoryDB) AddCoordinators(coordinators []common.Coordinator) error {
  488. return tracerr.Wrap(hdb.addCoordinators(hdb.db, coordinators))
  489. }
  490. func (hdb *HistoryDB) addCoordinators(d meddler.DB, coordinators []common.Coordinator) error {
  491. if len(coordinators) == 0 {
  492. return nil
  493. }
  494. return tracerr.Wrap(db.BulkInsert(
  495. d,
  496. "INSERT INTO coordinator (bidder_addr, forger_addr, eth_block_num, url) VALUES %s;",
  497. coordinators[:],
  498. ))
  499. }
  500. // AddExitTree insert Exit tree into the DB
  501. func (hdb *HistoryDB) AddExitTree(exitTree []common.ExitInfo) error {
  502. return tracerr.Wrap(hdb.addExitTree(hdb.db, exitTree))
  503. }
  504. func (hdb *HistoryDB) addExitTree(d meddler.DB, exitTree []common.ExitInfo) error {
  505. if len(exitTree) == 0 {
  506. return nil
  507. }
  508. return tracerr.Wrap(db.BulkInsert(
  509. d,
  510. "INSERT INTO exit_tree (batch_num, account_idx, merkle_proof, balance, "+
  511. "instant_withdrawn, delayed_withdraw_request, delayed_withdrawn) VALUES %s;",
  512. exitTree[:],
  513. ))
  514. }
  515. func (hdb *HistoryDB) updateExitTree(d sqlx.Ext, blockNum int64,
  516. rollupWithdrawals []common.WithdrawInfo, wDelayerWithdrawals []common.WDelayerTransfer) error {
  517. if len(rollupWithdrawals) == 0 && len(wDelayerWithdrawals) == 0 {
  518. return nil
  519. }
  520. type withdrawal struct {
  521. BatchNum int64 `db:"batch_num"`
  522. AccountIdx int64 `db:"account_idx"`
  523. InstantWithdrawn *int64 `db:"instant_withdrawn"`
  524. DelayedWithdrawRequest *int64 `db:"delayed_withdraw_request"`
  525. DelayedWithdrawn *int64 `db:"delayed_withdrawn"`
  526. Owner *ethCommon.Address `db:"owner"`
  527. Token *ethCommon.Address `db:"token"`
  528. }
  529. withdrawals := make([]withdrawal, len(rollupWithdrawals)+len(wDelayerWithdrawals))
  530. for i := range rollupWithdrawals {
  531. info := &rollupWithdrawals[i]
  532. withdrawals[i] = withdrawal{
  533. BatchNum: int64(info.NumExitRoot),
  534. AccountIdx: int64(info.Idx),
  535. }
  536. if info.InstantWithdraw {
  537. withdrawals[i].InstantWithdrawn = &blockNum
  538. } else {
  539. withdrawals[i].DelayedWithdrawRequest = &blockNum
  540. withdrawals[i].Owner = &info.Owner
  541. withdrawals[i].Token = &info.Token
  542. }
  543. }
  544. for i := range wDelayerWithdrawals {
  545. info := &wDelayerWithdrawals[i]
  546. withdrawals[len(rollupWithdrawals)+i] = withdrawal{
  547. DelayedWithdrawn: &blockNum,
  548. Owner: &info.Owner,
  549. Token: &info.Token,
  550. }
  551. }
  552. // In VALUES we set an initial row of NULLs to set the types of each
  553. // variable passed as argument
  554. const query string = `
  555. UPDATE exit_tree e SET
  556. instant_withdrawn = d.instant_withdrawn,
  557. delayed_withdraw_request = CASE
  558. WHEN e.delayed_withdraw_request IS NOT NULL THEN e.delayed_withdraw_request
  559. ELSE d.delayed_withdraw_request
  560. END,
  561. delayed_withdrawn = d.delayed_withdrawn,
  562. owner = d.owner,
  563. token = d.token
  564. FROM (VALUES
  565. (NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BIGINT, NULL::::BYTEA, NULL::::BYTEA),
  566. (:batch_num,
  567. :account_idx,
  568. :instant_withdrawn,
  569. :delayed_withdraw_request,
  570. :delayed_withdrawn,
  571. :owner,
  572. :token)
  573. ) as d (batch_num, account_idx, instant_withdrawn, delayed_withdraw_request, delayed_withdrawn, owner, token)
  574. WHERE
  575. (d.batch_num IS NOT NULL AND e.batch_num = d.batch_num AND e.account_idx = d.account_idx) OR
  576. (d.delayed_withdrawn IS NOT NULL AND e.delayed_withdrawn IS NULL AND e.owner = d.owner AND e.token = d.token);
  577. `
  578. if len(withdrawals) > 0 {
  579. if _, err := sqlx.NamedExec(d, query, withdrawals); err != nil {
  580. return tracerr.Wrap(err)
  581. }
  582. }
  583. return nil
  584. }
  585. // AddToken insert a token into the DB
  586. func (hdb *HistoryDB) AddToken(token *common.Token) error {
  587. return tracerr.Wrap(meddler.Insert(hdb.db, "token", token))
  588. }
  589. // AddTokens insert tokens into the DB
  590. func (hdb *HistoryDB) AddTokens(tokens []common.Token) error { return hdb.addTokens(hdb.db, tokens) }
  591. func (hdb *HistoryDB) addTokens(d meddler.DB, tokens []common.Token) error {
  592. if len(tokens) == 0 {
  593. return nil
  594. }
  595. return tracerr.Wrap(db.BulkInsert(
  596. d,
  597. `INSERT INTO token (
  598. token_id,
  599. eth_block_num,
  600. eth_addr,
  601. name,
  602. symbol,
  603. decimals
  604. ) VALUES %s;`,
  605. tokens[:],
  606. ))
  607. }
  608. // UpdateTokenValue updates the USD value of a token
  609. func (hdb *HistoryDB) UpdateTokenValue(tokenSymbol string, value float64) error {
  610. _, err := hdb.db.Exec(
  611. "UPDATE token SET usd = $1 WHERE symbol = $2;",
  612. value, tokenSymbol,
  613. )
  614. return tracerr.Wrap(err)
  615. }
  616. // GetToken returns a token from the DB given a TokenID
  617. func (hdb *HistoryDB) GetToken(tokenID common.TokenID) (*TokenWithUSD, error) {
  618. token := &TokenWithUSD{}
  619. err := meddler.QueryRow(
  620. hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID,
  621. )
  622. return token, tracerr.Wrap(err)
  623. }
  624. // GetAllTokens returns all tokens from the DB
  625. func (hdb *HistoryDB) GetAllTokens() ([]TokenWithUSD, error) {
  626. var tokens []*TokenWithUSD
  627. err := meddler.QueryAll(
  628. hdb.db, &tokens,
  629. "SELECT * FROM token ORDER BY token_id;",
  630. )
  631. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), tracerr.Wrap(err)
  632. }
  633. // GetTokens returns a list of tokens from the DB
  634. func (hdb *HistoryDB) GetTokens(
  635. ids []common.TokenID, symbols []string, name string, fromItem,
  636. limit *uint, order string,
  637. ) ([]TokenWithUSD, uint64, error) {
  638. var query string
  639. var args []interface{}
  640. queryStr := `SELECT * , COUNT(*) OVER() AS total_items FROM token `
  641. // Apply filters
  642. nextIsAnd := false
  643. if len(ids) > 0 {
  644. queryStr += "WHERE token_id IN (?) "
  645. nextIsAnd = true
  646. args = append(args, ids)
  647. }
  648. if len(symbols) > 0 {
  649. if nextIsAnd {
  650. queryStr += "AND "
  651. } else {
  652. queryStr += "WHERE "
  653. }
  654. queryStr += "symbol IN (?) "
  655. args = append(args, symbols)
  656. nextIsAnd = true
  657. }
  658. if name != "" {
  659. if nextIsAnd {
  660. queryStr += "AND "
  661. } else {
  662. queryStr += "WHERE "
  663. }
  664. queryStr += "name ~ ? "
  665. args = append(args, name)
  666. nextIsAnd = true
  667. }
  668. if fromItem != nil {
  669. if nextIsAnd {
  670. queryStr += "AND "
  671. } else {
  672. queryStr += "WHERE "
  673. }
  674. if order == OrderAsc {
  675. queryStr += "item_id >= ? "
  676. } else {
  677. queryStr += "item_id <= ? "
  678. }
  679. args = append(args, fromItem)
  680. }
  681. // pagination
  682. queryStr += "ORDER BY item_id "
  683. if order == OrderAsc {
  684. queryStr += "ASC "
  685. } else {
  686. queryStr += "DESC "
  687. }
  688. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  689. query, argsQ, err := sqlx.In(queryStr, args...)
  690. if err != nil {
  691. return nil, 0, tracerr.Wrap(err)
  692. }
  693. query = hdb.db.Rebind(query)
  694. tokens := []*TokenWithUSD{}
  695. if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil {
  696. return nil, 0, tracerr.Wrap(err)
  697. }
  698. if len(tokens) == 0 {
  699. return nil, 0, tracerr.Wrap(sql.ErrNoRows)
  700. }
  701. return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), uint64(len(tokens)) - tokens[0].TotalItems, nil
  702. }
  703. // GetTokenSymbols returns all the token symbols from the DB
  704. func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {
  705. var tokenSymbols []string
  706. rows, err := hdb.db.Query("SELECT symbol FROM token;")
  707. if err != nil {
  708. return nil, tracerr.Wrap(err)
  709. }
  710. defer db.RowsClose(rows)
  711. sym := new(string)
  712. for rows.Next() {
  713. err = rows.Scan(sym)
  714. if err != nil {
  715. return nil, tracerr.Wrap(err)
  716. }
  717. tokenSymbols = append(tokenSymbols, *sym)
  718. }
  719. return tokenSymbols, nil
  720. }
  721. // AddAccounts insert accounts into the DB
  722. func (hdb *HistoryDB) AddAccounts(accounts []common.Account) error {
  723. return tracerr.Wrap(hdb.addAccounts(hdb.db, accounts))
  724. }
  725. func (hdb *HistoryDB) addAccounts(d meddler.DB, accounts []common.Account) error {
  726. if len(accounts) == 0 {
  727. return nil
  728. }
  729. return tracerr.Wrap(db.BulkInsert(
  730. d,
  731. `INSERT INTO account (
  732. idx,
  733. token_id,
  734. batch_num,
  735. bjj,
  736. eth_addr
  737. ) VALUES %s;`,
  738. accounts[:],
  739. ))
  740. }
  741. // GetAllAccounts returns a list of accounts from the DB
  742. func (hdb *HistoryDB) GetAllAccounts() ([]common.Account, error) {
  743. var accs []*common.Account
  744. err := meddler.QueryAll(
  745. hdb.db, &accs,
  746. "SELECT * FROM account ORDER BY idx;",
  747. )
  748. return db.SlicePtrsToSlice(accs).([]common.Account), tracerr.Wrap(err)
  749. }
  750. // AddL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx.
  751. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  752. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  753. // EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.
  754. func (hdb *HistoryDB) AddL1Txs(l1txs []common.L1Tx) error {
  755. return tracerr.Wrap(hdb.addL1Txs(hdb.db, l1txs))
  756. }
  757. // addL1Txs inserts L1 txs to the DB. USD and DepositAmountUSD will be set automatically before storing the tx.
  758. // If the tx is originated by a coordinator, BatchNum must be provided. If it's originated by a user,
  759. // BatchNum should be null, and the value will be setted by a trigger when a batch forges the tx.
  760. // EffectiveAmount and EffectiveDepositAmount are seted with default values by the DB.
  761. func (hdb *HistoryDB) addL1Txs(d meddler.DB, l1txs []common.L1Tx) error {
  762. if len(l1txs) == 0 {
  763. return nil
  764. }
  765. txs := []txWrite{}
  766. for i := 0; i < len(l1txs); i++ {
  767. af := new(big.Float).SetInt(l1txs[i].Amount)
  768. amountFloat, _ := af.Float64()
  769. laf := new(big.Float).SetInt(l1txs[i].DepositAmount)
  770. depositAmountFloat, _ := laf.Float64()
  771. txs = append(txs, txWrite{
  772. // Generic
  773. IsL1: true,
  774. TxID: l1txs[i].TxID,
  775. Type: l1txs[i].Type,
  776. Position: l1txs[i].Position,
  777. FromIdx: &l1txs[i].FromIdx,
  778. ToIdx: l1txs[i].ToIdx,
  779. Amount: l1txs[i].Amount,
  780. AmountFloat: amountFloat,
  781. TokenID: l1txs[i].TokenID,
  782. BatchNum: l1txs[i].BatchNum,
  783. EthBlockNum: l1txs[i].EthBlockNum,
  784. // L1
  785. ToForgeL1TxsNum: l1txs[i].ToForgeL1TxsNum,
  786. UserOrigin: &l1txs[i].UserOrigin,
  787. FromEthAddr: &l1txs[i].FromEthAddr,
  788. FromBJJ: &l1txs[i].FromBJJ,
  789. DepositAmount: l1txs[i].DepositAmount,
  790. DepositAmountFloat: &depositAmountFloat,
  791. })
  792. }
  793. return tracerr.Wrap(hdb.addTxs(d, txs))
  794. }
  795. // AddL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  796. func (hdb *HistoryDB) AddL2Txs(l2txs []common.L2Tx) error {
  797. return tracerr.Wrap(hdb.addL2Txs(hdb.db, l2txs))
  798. }
  799. // addL2Txs inserts L2 txs to the DB. TokenID, USD and FeeUSD will be set automatically before storing the tx.
  800. func (hdb *HistoryDB) addL2Txs(d meddler.DB, l2txs []common.L2Tx) error {
  801. txs := []txWrite{}
  802. for i := 0; i < len(l2txs); i++ {
  803. f := new(big.Float).SetInt(l2txs[i].Amount)
  804. amountFloat, _ := f.Float64()
  805. txs = append(txs, txWrite{
  806. // Generic
  807. IsL1: false,
  808. TxID: l2txs[i].TxID,
  809. Type: l2txs[i].Type,
  810. Position: l2txs[i].Position,
  811. FromIdx: &l2txs[i].FromIdx,
  812. ToIdx: l2txs[i].ToIdx,
  813. Amount: l2txs[i].Amount,
  814. AmountFloat: amountFloat,
  815. BatchNum: &l2txs[i].BatchNum,
  816. EthBlockNum: l2txs[i].EthBlockNum,
  817. // L2
  818. Fee: &l2txs[i].Fee,
  819. Nonce: &l2txs[i].Nonce,
  820. })
  821. }
  822. return tracerr.Wrap(hdb.addTxs(d, txs))
  823. }
  824. func (hdb *HistoryDB) addTxs(d meddler.DB, txs []txWrite) error {
  825. if len(txs) == 0 {
  826. return nil
  827. }
  828. return tracerr.Wrap(db.BulkInsert(
  829. d,
  830. `INSERT INTO tx (
  831. is_l1,
  832. id,
  833. type,
  834. position,
  835. from_idx,
  836. to_idx,
  837. amount,
  838. amount_f,
  839. token_id,
  840. batch_num,
  841. eth_block_num,
  842. to_forge_l1_txs_num,
  843. user_origin,
  844. from_eth_addr,
  845. from_bjj,
  846. deposit_amount,
  847. deposit_amount_f,
  848. fee,
  849. nonce
  850. ) VALUES %s;`,
  851. txs[:],
  852. ))
  853. }
  854. // // GetTxs returns a list of txs from the DB
  855. // func (hdb *HistoryDB) GetTxs() ([]common.Tx, error) {
  856. // var txs []*common.Tx
  857. // err := meddler.QueryAll(
  858. // hdb.db, &txs,
  859. // `SELECT * FROM tx
  860. // ORDER BY (batch_num, position) ASC`,
  861. // )
  862. // return db.SlicePtrsToSlice(txs).([]common.Tx), err
  863. // }
  864. // GetHistoryTx returns a tx from the DB given a TxID
  865. func (hdb *HistoryDB) GetHistoryTx(txID common.TxID) (*TxAPI, error) {
  866. // Warning: amount_success and deposit_amount_success have true as default for
  867. // performance reasons. The expected default value is false (when txs are unforged)
  868. // this case is handled at the function func (tx TxAPI) MarshalJSON() ([]byte, error)
  869. tx := &TxAPI{}
  870. err := meddler.QueryRow(
  871. hdb.db, tx, `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  872. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  873. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  874. tx.amount, tx.amount_success, tx.token_id, tx.amount_usd,
  875. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  876. tx.deposit_amount, tx.deposit_amount_usd, tx.deposit_amount_success, tx.fee, tx.fee_usd, tx.nonce,
  877. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  878. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  879. token.usd_update, block.timestamp
  880. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  881. INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  882. WHERE tx.id = $1;`, txID,
  883. )
  884. return tx, tracerr.Wrap(err)
  885. }
  886. // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct
  887. // and pagination info
  888. func (hdb *HistoryDB) GetHistoryTxs(
  889. ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp,
  890. tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,
  891. fromItem, limit *uint, order string,
  892. ) ([]TxAPI, uint64, error) {
  893. // Warning: amount_success and deposit_amount_success have true as default for
  894. // performance reasons. The expected default value is false (when txs are unforged)
  895. // this case is handled at the function func (tx TxAPI) MarshalJSON() ([]byte, error)
  896. if ethAddr != nil && bjj != nil {
  897. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  898. }
  899. var query string
  900. var args []interface{}
  901. queryStr := `SELECT tx.item_id, tx.is_l1, tx.id, tx.type, tx.position,
  902. hez_idx(tx.from_idx, token.symbol) AS from_idx, tx.from_eth_addr, tx.from_bjj,
  903. hez_idx(tx.to_idx, token.symbol) AS to_idx, tx.to_eth_addr, tx.to_bjj,
  904. tx.amount, tx.amount_success, tx.token_id, tx.amount_usd,
  905. tx.batch_num, tx.eth_block_num, tx.to_forge_l1_txs_num, tx.user_origin,
  906. tx.deposit_amount, tx.deposit_amount_usd, tx.deposit_amount_success, tx.fee, tx.fee_usd, tx.nonce,
  907. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  908. token.eth_addr, token.name, token.symbol, token.decimals, token.usd,
  909. token.usd_update, block.timestamp, count(*) OVER() AS total_items
  910. FROM tx INNER JOIN token ON tx.token_id = token.token_id
  911. INNER JOIN block ON tx.eth_block_num = block.eth_block_num `
  912. // Apply filters
  913. nextIsAnd := false
  914. // ethAddr filter
  915. if ethAddr != nil {
  916. queryStr += "WHERE (tx.from_eth_addr = ? OR tx.to_eth_addr = ?) "
  917. nextIsAnd = true
  918. args = append(args, ethAddr, ethAddr)
  919. } else if bjj != nil { // bjj filter
  920. queryStr += "WHERE (tx.from_bjj = ? OR tx.to_bjj = ?) "
  921. nextIsAnd = true
  922. args = append(args, bjj, bjj)
  923. }
  924. // tokenID filter
  925. if tokenID != nil {
  926. if nextIsAnd {
  927. queryStr += "AND "
  928. } else {
  929. queryStr += "WHERE "
  930. }
  931. queryStr += "tx.token_id = ? "
  932. args = append(args, tokenID)
  933. nextIsAnd = true
  934. }
  935. // idx filter
  936. if idx != nil {
  937. if nextIsAnd {
  938. queryStr += "AND "
  939. } else {
  940. queryStr += "WHERE "
  941. }
  942. queryStr += "(tx.from_idx = ? OR tx.to_idx = ?) "
  943. args = append(args, idx, idx)
  944. nextIsAnd = true
  945. }
  946. // batchNum filter
  947. if batchNum != nil {
  948. if nextIsAnd {
  949. queryStr += "AND "
  950. } else {
  951. queryStr += "WHERE "
  952. }
  953. queryStr += "tx.batch_num = ? "
  954. args = append(args, batchNum)
  955. nextIsAnd = true
  956. }
  957. // txType filter
  958. if txType != nil {
  959. if nextIsAnd {
  960. queryStr += "AND "
  961. } else {
  962. queryStr += "WHERE "
  963. }
  964. queryStr += "tx.type = ? "
  965. args = append(args, txType)
  966. nextIsAnd = true
  967. }
  968. if fromItem != nil {
  969. if nextIsAnd {
  970. queryStr += "AND "
  971. } else {
  972. queryStr += "WHERE "
  973. }
  974. if order == OrderAsc {
  975. queryStr += "tx.item_id >= ? "
  976. } else {
  977. queryStr += "tx.item_id <= ? "
  978. }
  979. args = append(args, fromItem)
  980. nextIsAnd = true
  981. }
  982. if nextIsAnd {
  983. queryStr += "AND "
  984. } else {
  985. queryStr += "WHERE "
  986. }
  987. queryStr += "tx.batch_num IS NOT NULL "
  988. // pagination
  989. queryStr += "ORDER BY tx.item_id "
  990. if order == OrderAsc {
  991. queryStr += " ASC "
  992. } else {
  993. queryStr += " DESC "
  994. }
  995. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  996. query = hdb.db.Rebind(queryStr)
  997. // log.Debug(query)
  998. txsPtrs := []*TxAPI{}
  999. if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil {
  1000. return nil, 0, tracerr.Wrap(err)
  1001. }
  1002. txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI)
  1003. if len(txs) == 0 {
  1004. return nil, 0, tracerr.Wrap(sql.ErrNoRows)
  1005. }
  1006. return txs, txs[0].TotalItems - uint64(len(txs)), nil
  1007. }
  1008. // GetAllExits returns all exit from the DB
  1009. func (hdb *HistoryDB) GetAllExits() ([]common.ExitInfo, error) {
  1010. var exits []*common.ExitInfo
  1011. err := meddler.QueryAll(
  1012. hdb.db, &exits,
  1013. `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,
  1014. exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request,
  1015. exit_tree.delayed_withdrawn FROM exit_tree ORDER BY item_id;`,
  1016. )
  1017. return db.SlicePtrsToSlice(exits).([]common.ExitInfo), tracerr.Wrap(err)
  1018. }
  1019. // GetExitAPI returns a exit from the DB
  1020. func (hdb *HistoryDB) GetExitAPI(batchNum *uint, idx *common.Idx) (*ExitAPI, error) {
  1021. exit := &ExitAPI{}
  1022. err := meddler.QueryRow(
  1023. hdb.db, exit, `SELECT exit_tree.item_id, exit_tree.batch_num,
  1024. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  1025. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  1026. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  1027. token.token_id, token.item_id AS token_item_id,
  1028. token.eth_block_num AS token_block, token.eth_addr, token.name, token.symbol,
  1029. token.decimals, token.usd, token.usd_update
  1030. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  1031. INNER JOIN token ON account.token_id = token.token_id
  1032. WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
  1033. )
  1034. return exit, tracerr.Wrap(err)
  1035. }
  1036. // GetExitsAPI returns a list of exits from the DB and pagination info
  1037. func (hdb *HistoryDB) GetExitsAPI(
  1038. ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp, tokenID *common.TokenID,
  1039. idx *common.Idx, batchNum *uint, onlyPendingWithdraws *bool,
  1040. fromItem, limit *uint, order string,
  1041. ) ([]ExitAPI, uint64, error) {
  1042. if ethAddr != nil && bjj != nil {
  1043. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  1044. }
  1045. var query string
  1046. var args []interface{}
  1047. queryStr := `SELECT exit_tree.item_id, exit_tree.batch_num,
  1048. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  1049. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  1050. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  1051. token.token_id, token.item_id AS token_item_id,
  1052. token.eth_block_num AS token_block, token.eth_addr, token.name, token.symbol,
  1053. token.decimals, token.usd, token.usd_update, COUNT(*) OVER() AS total_items
  1054. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  1055. INNER JOIN token ON account.token_id = token.token_id `
  1056. // Apply filters
  1057. nextIsAnd := false
  1058. // ethAddr filter
  1059. if ethAddr != nil {
  1060. queryStr += "WHERE account.eth_addr = ? "
  1061. nextIsAnd = true
  1062. args = append(args, ethAddr)
  1063. } else if bjj != nil { // bjj filter
  1064. queryStr += "WHERE account.bjj = ? "
  1065. nextIsAnd = true
  1066. args = append(args, bjj)
  1067. }
  1068. // tokenID filter
  1069. if tokenID != nil {
  1070. if nextIsAnd {
  1071. queryStr += "AND "
  1072. } else {
  1073. queryStr += "WHERE "
  1074. }
  1075. queryStr += "account.token_id = ? "
  1076. args = append(args, tokenID)
  1077. nextIsAnd = true
  1078. }
  1079. // idx filter
  1080. if idx != nil {
  1081. if nextIsAnd {
  1082. queryStr += "AND "
  1083. } else {
  1084. queryStr += "WHERE "
  1085. }
  1086. queryStr += "exit_tree.account_idx = ? "
  1087. args = append(args, idx)
  1088. nextIsAnd = true
  1089. }
  1090. // batchNum filter
  1091. if batchNum != nil {
  1092. if nextIsAnd {
  1093. queryStr += "AND "
  1094. } else {
  1095. queryStr += "WHERE "
  1096. }
  1097. queryStr += "exit_tree.batch_num = ? "
  1098. args = append(args, batchNum)
  1099. nextIsAnd = true
  1100. }
  1101. // onlyPendingWithdraws
  1102. if onlyPendingWithdraws != nil {
  1103. if *onlyPendingWithdraws {
  1104. if nextIsAnd {
  1105. queryStr += "AND "
  1106. } else {
  1107. queryStr += "WHERE "
  1108. }
  1109. queryStr += "(exit_tree.instant_withdrawn IS NULL AND exit_tree.delayed_withdrawn IS NULL) "
  1110. nextIsAnd = true
  1111. }
  1112. }
  1113. if fromItem != nil {
  1114. if nextIsAnd {
  1115. queryStr += "AND "
  1116. } else {
  1117. queryStr += "WHERE "
  1118. }
  1119. if order == OrderAsc {
  1120. queryStr += "exit_tree.item_id >= ? "
  1121. } else {
  1122. queryStr += "exit_tree.item_id <= ? "
  1123. }
  1124. args = append(args, fromItem)
  1125. // nextIsAnd = true
  1126. }
  1127. // pagination
  1128. queryStr += "ORDER BY exit_tree.item_id "
  1129. if order == OrderAsc {
  1130. queryStr += " ASC "
  1131. } else {
  1132. queryStr += " DESC "
  1133. }
  1134. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1135. query = hdb.db.Rebind(queryStr)
  1136. // log.Debug(query)
  1137. exits := []*ExitAPI{}
  1138. if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
  1139. return nil, 0, tracerr.Wrap(err)
  1140. }
  1141. if len(exits) == 0 {
  1142. return nil, 0, tracerr.Wrap(sql.ErrNoRows)
  1143. }
  1144. return db.SlicePtrsToSlice(exits).([]ExitAPI), exits[0].TotalItems - uint64(len(exits)), nil
  1145. }
  1146. // GetAllL1UserTxs returns all L1UserTxs from the DB
  1147. func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
  1148. var txs []*common.L1Tx
  1149. err := meddler.QueryAll(
  1150. hdb.db, &txs, // Note that '\x' gets parsed as a big.Int with value = 0
  1151. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1152. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1153. tx.amount, (CASE WHEN tx.batch_num IS NULL THEN NULL WHEN tx.amount_success THEN tx.amount ELSE '\x' END) AS effective_amount,
  1154. 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,
  1155. tx.eth_block_num, tx.type, tx.batch_num
  1156. FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE ORDER BY item_id;`,
  1157. )
  1158. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1159. }
  1160. // GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
  1161. func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
  1162. var txs []*common.L1Tx
  1163. // Since the query specifies that only coordinator txs are returned, it's safe to assume
  1164. // that returned txs will always have effective amounts
  1165. err := meddler.QueryAll(
  1166. hdb.db, &txs,
  1167. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1168. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1169. tx.amount, tx.amount AS effective_amount,
  1170. tx.deposit_amount, tx.deposit_amount AS effective_deposit_amount,
  1171. tx.eth_block_num, tx.type, tx.batch_num
  1172. FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE ORDER BY item_id;`,
  1173. )
  1174. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1175. }
  1176. // GetAllL2Txs returns all L2Txs from the DB
  1177. func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
  1178. var txs []*common.L2Tx
  1179. err := meddler.QueryAll(
  1180. hdb.db, &txs,
  1181. `SELECT tx.id, tx.batch_num, tx.position,
  1182. tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
  1183. tx.type, tx.eth_block_num
  1184. FROM tx WHERE is_l1 = FALSE ORDER BY item_id;`,
  1185. )
  1186. return db.SlicePtrsToSlice(txs).([]common.L2Tx), tracerr.Wrap(err)
  1187. }
  1188. // GetUnforgedL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
  1189. func (hdb *HistoryDB) GetUnforgedL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
  1190. var txs []*common.L1Tx
  1191. err := meddler.QueryAll(
  1192. hdb.db, &txs, // only L1 user txs can have batch_num set to null
  1193. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1194. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1195. tx.amount, NULL AS effective_amount,
  1196. tx.deposit_amount, NULL AS effective_deposit_amount,
  1197. tx.eth_block_num, tx.type, tx.batch_num
  1198. FROM tx WHERE batch_num IS NULL AND to_forge_l1_txs_num = $1
  1199. ORDER BY position;`,
  1200. toForgeL1TxsNum,
  1201. )
  1202. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1203. }
  1204. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  1205. // GetLastTxsPosition for a given to_forge_l1_txs_num
  1206. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  1207. row := hdb.db.QueryRow(
  1208. "SELECT position FROM tx WHERE to_forge_l1_txs_num = $1 ORDER BY position DESC;",
  1209. toForgeL1TxsNum,
  1210. )
  1211. var lastL1TxsPosition int
  1212. return lastL1TxsPosition, tracerr.Wrap(row.Scan(&lastL1TxsPosition))
  1213. }
  1214. // GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
  1215. func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
  1216. *common.WDelayerVariables, error) {
  1217. var rollup common.RollupVariables
  1218. var auction common.AuctionVariables
  1219. var wDelayer common.WDelayerVariables
  1220. if err := meddler.QueryRow(hdb.db, &rollup,
  1221. "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1222. return nil, nil, nil, tracerr.Wrap(err)
  1223. }
  1224. if err := meddler.QueryRow(hdb.db, &auction,
  1225. "SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1226. return nil, nil, nil, tracerr.Wrap(err)
  1227. }
  1228. if err := meddler.QueryRow(hdb.db, &wDelayer,
  1229. "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1230. return nil, nil, nil, tracerr.Wrap(err)
  1231. }
  1232. return &rollup, &auction, &wDelayer, nil
  1233. }
  1234. func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
  1235. return tracerr.Wrap(meddler.Insert(d, "rollup_vars", rollup))
  1236. }
  1237. func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
  1238. return tracerr.Wrap(meddler.Insert(d, "auction_vars", auction))
  1239. }
  1240. func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
  1241. return tracerr.Wrap(meddler.Insert(d, "wdelayer_vars", wDelayer))
  1242. }
  1243. func (hdb *HistoryDB) addBucketUpdates(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
  1244. if len(bucketUpdates) == 0 {
  1245. return nil
  1246. }
  1247. return tracerr.Wrap(db.BulkInsert(
  1248. d,
  1249. `INSERT INTO bucket_update (
  1250. eth_block_num,
  1251. num_bucket,
  1252. block_stamp,
  1253. withdrawals
  1254. ) VALUES %s;`,
  1255. bucketUpdates[:],
  1256. ))
  1257. }
  1258. // GetAllBucketUpdates retrieves all the bucket updates
  1259. func (hdb *HistoryDB) GetAllBucketUpdates() ([]common.BucketUpdate, error) {
  1260. var bucketUpdates []*common.BucketUpdate
  1261. err := meddler.QueryAll(
  1262. hdb.db, &bucketUpdates,
  1263. "SELECT * FROM bucket_update ORDER BY item_id;",
  1264. )
  1265. return db.SlicePtrsToSlice(bucketUpdates).([]common.BucketUpdate), tracerr.Wrap(err)
  1266. }
  1267. func (hdb *HistoryDB) addTokenExchanges(d meddler.DB, tokenExchanges []common.TokenExchange) error {
  1268. if len(tokenExchanges) == 0 {
  1269. return nil
  1270. }
  1271. return tracerr.Wrap(db.BulkInsert(
  1272. d,
  1273. `INSERT INTO token_exchange (
  1274. eth_block_num,
  1275. eth_addr,
  1276. value_usd
  1277. ) VALUES %s;`,
  1278. tokenExchanges[:],
  1279. ))
  1280. }
  1281. // GetAllTokenExchanges retrieves all the token exchanges
  1282. func (hdb *HistoryDB) GetAllTokenExchanges() ([]common.TokenExchange, error) {
  1283. var tokenExchanges []*common.TokenExchange
  1284. err := meddler.QueryAll(
  1285. hdb.db, &tokenExchanges,
  1286. "SELECT * FROM token_exchange ORDER BY item_id;",
  1287. )
  1288. return db.SlicePtrsToSlice(tokenExchanges).([]common.TokenExchange), tracerr.Wrap(err)
  1289. }
  1290. func (hdb *HistoryDB) addEscapeHatchWithdrawals(d meddler.DB,
  1291. escapeHatchWithdrawals []common.WDelayerEscapeHatchWithdrawal) error {
  1292. if len(escapeHatchWithdrawals) == 0 {
  1293. return nil
  1294. }
  1295. return tracerr.Wrap(db.BulkInsert(
  1296. d,
  1297. `INSERT INTO escape_hatch_withdrawal (
  1298. eth_block_num,
  1299. who_addr,
  1300. to_addr,
  1301. token_addr,
  1302. amount
  1303. ) VALUES %s;`,
  1304. escapeHatchWithdrawals[:],
  1305. ))
  1306. }
  1307. // GetAllEscapeHatchWithdrawals retrieves all the escape hatch withdrawals
  1308. func (hdb *HistoryDB) GetAllEscapeHatchWithdrawals() ([]common.WDelayerEscapeHatchWithdrawal, error) {
  1309. var escapeHatchWithdrawals []*common.WDelayerEscapeHatchWithdrawal
  1310. err := meddler.QueryAll(
  1311. hdb.db, &escapeHatchWithdrawals,
  1312. "SELECT * FROM escape_hatch_withdrawal ORDER BY item_id;",
  1313. )
  1314. return db.SlicePtrsToSlice(escapeHatchWithdrawals).([]common.WDelayerEscapeHatchWithdrawal),
  1315. tracerr.Wrap(err)
  1316. }
  1317. // SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
  1318. // contract variables. This initial state is stored linked to block 0, which
  1319. // always exist in the DB and is used to store initialization data that always
  1320. // exist in the smart contracts.
  1321. func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
  1322. auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
  1323. txn, err := hdb.db.Beginx()
  1324. if err != nil {
  1325. return tracerr.Wrap(err)
  1326. }
  1327. defer func() {
  1328. if err != nil {
  1329. db.Rollback(txn)
  1330. }
  1331. }()
  1332. // Force EthBlockNum to be 0 because it's the block used to link data
  1333. // that belongs to the creation of the smart contracts
  1334. rollup.EthBlockNum = 0
  1335. auction.EthBlockNum = 0
  1336. wDelayer.EthBlockNum = 0
  1337. auction.DefaultSlotSetBidSlotNum = 0
  1338. if err := hdb.setRollupVars(txn, rollup); err != nil {
  1339. return tracerr.Wrap(err)
  1340. }
  1341. if err := hdb.setAuctionVars(txn, auction); err != nil {
  1342. return tracerr.Wrap(err)
  1343. }
  1344. if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
  1345. return tracerr.Wrap(err)
  1346. }
  1347. return tracerr.Wrap(txn.Commit())
  1348. }
  1349. // setL1UserTxEffectiveAmounts sets the EffectiveAmount and EffectiveDepositAmount
  1350. // of the given l1UserTxs (with an UPDATE)
  1351. func (hdb *HistoryDB) setL1UserTxEffectiveAmounts(d sqlx.Ext, txs []common.L1Tx) error {
  1352. if len(txs) == 0 {
  1353. return nil
  1354. }
  1355. // Effective amounts are stored as success flags in the DB, with true value by default
  1356. // to reduce the amount of updates. Therefore, only amounts that became uneffective should be
  1357. // updated to become false
  1358. type txUpdate struct {
  1359. ID common.TxID `db:"id"`
  1360. AmountSuccess bool `db:"amount_success"`
  1361. DepositAmountSuccess bool `db:"deposit_amount_success"`
  1362. }
  1363. txUpdates := []txUpdate{}
  1364. equal := func(a *big.Int, b *big.Int) bool {
  1365. return a.Cmp(b) == 0
  1366. }
  1367. for i := range txs {
  1368. amountSuccess := equal(txs[i].Amount, txs[i].EffectiveAmount)
  1369. depositAmountSuccess := equal(txs[i].DepositAmount, txs[i].EffectiveDepositAmount)
  1370. if !amountSuccess || !depositAmountSuccess {
  1371. txUpdates = append(txUpdates, txUpdate{
  1372. ID: txs[i].TxID,
  1373. AmountSuccess: amountSuccess,
  1374. DepositAmountSuccess: depositAmountSuccess,
  1375. })
  1376. }
  1377. }
  1378. const query string = `
  1379. UPDATE tx SET
  1380. amount_success = tx_update.amount_success,
  1381. deposit_amount_success = tx_update.deposit_amount_success
  1382. FROM (VALUES
  1383. (NULL::::BYTEA, NULL::::BOOL, NULL::::BOOL),
  1384. (:id, :amount_success, :deposit_amount_success)
  1385. ) as tx_update (id, amount_success, deposit_amount_success)
  1386. WHERE tx.id = tx_update.id;
  1387. `
  1388. if len(txUpdates) > 0 {
  1389. if _, err := sqlx.NamedExec(d, query, txUpdates); err != nil {
  1390. return tracerr.Wrap(err)
  1391. }
  1392. }
  1393. return nil
  1394. }
  1395. // AddBlockSCData stores all the information of a block retrieved by the
  1396. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  1397. // the pagination system of the API/DB depends on this. Within blocks, all
  1398. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  1399. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  1400. txn, err := hdb.db.Beginx()
  1401. if err != nil {
  1402. return tracerr.Wrap(err)
  1403. }
  1404. defer func() {
  1405. if err != nil {
  1406. db.Rollback(txn)
  1407. }
  1408. }()
  1409. // Add block
  1410. if err := hdb.addBlock(txn, &blockData.Block); err != nil {
  1411. return tracerr.Wrap(err)
  1412. }
  1413. // Add Coordinators
  1414. if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
  1415. return tracerr.Wrap(err)
  1416. }
  1417. // Add Bids
  1418. if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
  1419. return tracerr.Wrap(err)
  1420. }
  1421. // Add Tokens
  1422. if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
  1423. return tracerr.Wrap(err)
  1424. }
  1425. // Prepare user L1 txs to be added.
  1426. // They must be added before the batch that will forge them (which can be in the same block)
  1427. // and after the account that will be sent to (also can be in the same block).
  1428. // Note: insert order is not relevant since item_id will be updated by a DB trigger when
  1429. // the batch that forges those txs is inserted
  1430. userL1s := make(map[common.BatchNum][]common.L1Tx)
  1431. for i := range blockData.Rollup.L1UserTxs {
  1432. batchThatForgesIsInTheBlock := false
  1433. for _, batch := range blockData.Rollup.Batches {
  1434. if batch.Batch.ForgeL1TxsNum != nil &&
  1435. *batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
  1436. // Tx is forged in this block. It's guaranteed that:
  1437. // * the first batch of the block won't forge user L1 txs that have been added in this block
  1438. // * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
  1439. batchThatForgesIsInTheBlock = true
  1440. addAtBatchNum := batch.Batch.BatchNum - 1
  1441. userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
  1442. break
  1443. }
  1444. }
  1445. if !batchThatForgesIsInTheBlock {
  1446. // User artificial batchNum 0 to add txs that are not forge in this block
  1447. // after all the accounts of the block have been added
  1448. userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
  1449. }
  1450. }
  1451. // Add Batches
  1452. for i := range blockData.Rollup.Batches {
  1453. batch := &blockData.Rollup.Batches[i]
  1454. // Add Batch: this will trigger an update on the DB
  1455. // that will set the batch num of forged L1 txs in this batch
  1456. if err = hdb.addBatch(txn, &batch.Batch); err != nil {
  1457. return tracerr.Wrap(err)
  1458. }
  1459. // Set the EffectiveAmount and EffectiveDepositAmount of all the
  1460. // L1UserTxs that have been forged in this batch
  1461. if err = hdb.setL1UserTxEffectiveAmounts(txn, batch.L1UserTxs); err != nil {
  1462. return tracerr.Wrap(err)
  1463. }
  1464. // Add accounts
  1465. if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
  1466. return tracerr.Wrap(err)
  1467. }
  1468. // Add forged l1 coordinator Txs
  1469. if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
  1470. return tracerr.Wrap(err)
  1471. }
  1472. // Add l2 Txs
  1473. if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
  1474. return tracerr.Wrap(err)
  1475. }
  1476. // Add user L1 txs that will be forged in next batch
  1477. if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
  1478. if err := hdb.addL1Txs(txn, userlL1s); err != nil {
  1479. return tracerr.Wrap(err)
  1480. }
  1481. }
  1482. // Add exit tree
  1483. if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
  1484. return tracerr.Wrap(err)
  1485. }
  1486. }
  1487. // Add user L1 txs that won't be forged in this block
  1488. if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
  1489. if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
  1490. return tracerr.Wrap(err)
  1491. }
  1492. }
  1493. // Set SC Vars if there was an update
  1494. if blockData.Rollup.Vars != nil {
  1495. if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
  1496. return tracerr.Wrap(err)
  1497. }
  1498. }
  1499. if blockData.Auction.Vars != nil {
  1500. if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
  1501. return tracerr.Wrap(err)
  1502. }
  1503. }
  1504. if blockData.WDelayer.Vars != nil {
  1505. if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
  1506. return tracerr.Wrap(err)
  1507. }
  1508. }
  1509. // Update withdrawals in exit tree table
  1510. if err := hdb.updateExitTree(txn, blockData.Block.Num,
  1511. blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
  1512. return tracerr.Wrap(err)
  1513. }
  1514. // Add Escape Hatch Withdrawals
  1515. if err := hdb.addEscapeHatchWithdrawals(txn,
  1516. blockData.WDelayer.EscapeHatchWithdrawals); err != nil {
  1517. return tracerr.Wrap(err)
  1518. }
  1519. // Add Buckets withdrawals updates
  1520. if err := hdb.addBucketUpdates(txn, blockData.Rollup.UpdateBucketWithdraw); err != nil {
  1521. return tracerr.Wrap(err)
  1522. }
  1523. // Add Token exchange updates
  1524. if err := hdb.addTokenExchanges(txn, blockData.Rollup.TokenExchanges); err != nil {
  1525. return tracerr.Wrap(err)
  1526. }
  1527. return tracerr.Wrap(txn.Commit())
  1528. }
  1529. // GetCoordinatorAPI returns a coordinator by its bidderAddr
  1530. func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
  1531. coordinator := &CoordinatorAPI{}
  1532. err := meddler.QueryRow(hdb.db, coordinator, "SELECT * FROM coordinator WHERE bidder_addr = $1;", bidderAddr)
  1533. return coordinator, tracerr.Wrap(err)
  1534. }
  1535. // GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
  1536. func (hdb *HistoryDB) GetCoordinatorsAPI(
  1537. bidderAddr, forgerAddr *ethCommon.Address,
  1538. fromItem, limit *uint, order string,
  1539. ) ([]CoordinatorAPI, uint64, error) {
  1540. var query string
  1541. var args []interface{}
  1542. queryStr := `SELECT coordinator.*,
  1543. COUNT(*) OVER() AS total_items
  1544. FROM coordinator `
  1545. // Apply filters
  1546. nextIsAnd := false
  1547. if bidderAddr != nil {
  1548. queryStr += "WHERE bidder_addr = ? "
  1549. nextIsAnd = true
  1550. args = append(args, bidderAddr)
  1551. }
  1552. if forgerAddr != nil {
  1553. if nextIsAnd {
  1554. queryStr += "AND "
  1555. } else {
  1556. queryStr += "WHERE "
  1557. }
  1558. queryStr += "forger_addr = ? "
  1559. nextIsAnd = true
  1560. args = append(args, forgerAddr)
  1561. }
  1562. if fromItem != nil {
  1563. if nextIsAnd {
  1564. queryStr += "AND "
  1565. } else {
  1566. queryStr += "WHERE "
  1567. }
  1568. if order == OrderAsc {
  1569. queryStr += "coordinator.item_id >= ? "
  1570. } else {
  1571. queryStr += "coordinator.item_id <= ? "
  1572. }
  1573. args = append(args, fromItem)
  1574. }
  1575. // pagination
  1576. queryStr += "ORDER BY coordinator.item_id "
  1577. if order == OrderAsc {
  1578. queryStr += " ASC "
  1579. } else {
  1580. queryStr += " DESC "
  1581. }
  1582. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1583. query = hdb.db.Rebind(queryStr)
  1584. coordinators := []*CoordinatorAPI{}
  1585. if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
  1586. return nil, 0, tracerr.Wrap(err)
  1587. }
  1588. if len(coordinators) == 0 {
  1589. return nil, 0, tracerr.Wrap(sql.ErrNoRows)
  1590. }
  1591. return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI),
  1592. coordinators[0].TotalItems - uint64(len(coordinators)), nil
  1593. }
  1594. // AddAuctionVars insert auction vars into the DB
  1595. func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
  1596. return tracerr.Wrap(meddler.Insert(hdb.db, "auction_vars", auctionVars))
  1597. }
  1598. // GetAuctionVars returns auction variables
  1599. func (hdb *HistoryDB) GetAuctionVars() (*common.AuctionVariables, error) {
  1600. auctionVars := &common.AuctionVariables{}
  1601. err := meddler.QueryRow(
  1602. hdb.db, auctionVars, `SELECT * FROM auction_vars;`,
  1603. )
  1604. return auctionVars, tracerr.Wrap(err)
  1605. }
  1606. // GetAuctionVarsUntilSetSlotNum returns all the updates of the auction vars
  1607. // from the last entry in which DefaultSlotSetBidSlotNum <= slotNum
  1608. func (hdb *HistoryDB) GetAuctionVarsUntilSetSlotNum(slotNum int64, maxItems int) ([]MinBidInfo, error) {
  1609. auctionVars := []*MinBidInfo{}
  1610. query := `
  1611. SELECT DISTINCT default_slot_set_bid, default_slot_set_bid_slot_num FROM auction_vars
  1612. WHERE default_slot_set_bid_slot_num < $1
  1613. ORDER BY default_slot_set_bid_slot_num DESC
  1614. LIMIT $2;
  1615. `
  1616. err := meddler.QueryAll(hdb.db, &auctionVars, query, slotNum, maxItems)
  1617. if err != nil {
  1618. return nil, tracerr.Wrap(err)
  1619. }
  1620. return db.SlicePtrsToSlice(auctionVars).([]MinBidInfo), nil
  1621. }
  1622. // GetAccountAPI returns an account by its index
  1623. func (hdb *HistoryDB) GetAccountAPI(idx common.Idx) (*AccountAPI, error) {
  1624. account := &AccountAPI{}
  1625. err := meddler.QueryRow(hdb.db, account, `SELECT account.item_id, hez_idx(account.idx,
  1626. token.symbol) as idx, account.batch_num, account.bjj, account.eth_addr,
  1627. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1628. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  1629. FROM account INNER JOIN token ON account.token_id = token.token_id WHERE idx = $1;`, idx)
  1630. if err != nil {
  1631. return nil, tracerr.Wrap(err)
  1632. }
  1633. return account, nil
  1634. }
  1635. // GetAccountsAPI returns a list of accounts from the DB and pagination info
  1636. func (hdb *HistoryDB) GetAccountsAPI(
  1637. tokenIDs []common.TokenID, ethAddr *ethCommon.Address,
  1638. bjj *babyjub.PublicKeyComp, fromItem, limit *uint, order string,
  1639. ) ([]AccountAPI, uint64, error) {
  1640. if ethAddr != nil && bjj != nil {
  1641. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  1642. }
  1643. var query string
  1644. var args []interface{}
  1645. queryStr := `SELECT account.item_id, hez_idx(account.idx, token.symbol) as idx, account.batch_num,
  1646. account.bjj, account.eth_addr, token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1647. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update,
  1648. COUNT(*) OVER() AS total_items
  1649. FROM account INNER JOIN token ON account.token_id = token.token_id `
  1650. // Apply filters
  1651. nextIsAnd := false
  1652. // ethAddr filter
  1653. if ethAddr != nil {
  1654. queryStr += "WHERE account.eth_addr = ? "
  1655. nextIsAnd = true
  1656. args = append(args, ethAddr)
  1657. } else if bjj != nil { // bjj filter
  1658. queryStr += "WHERE account.bjj = ? "
  1659. nextIsAnd = true
  1660. args = append(args, bjj)
  1661. }
  1662. // tokenID filter
  1663. if len(tokenIDs) > 0 {
  1664. if nextIsAnd {
  1665. queryStr += "AND "
  1666. } else {
  1667. queryStr += "WHERE "
  1668. }
  1669. queryStr += "account.token_id IN (?) "
  1670. args = append(args, tokenIDs)
  1671. nextIsAnd = true
  1672. }
  1673. if fromItem != nil {
  1674. if nextIsAnd {
  1675. queryStr += "AND "
  1676. } else {
  1677. queryStr += "WHERE "
  1678. }
  1679. if order == OrderAsc {
  1680. queryStr += "account.item_id >= ? "
  1681. } else {
  1682. queryStr += "account.item_id <= ? "
  1683. }
  1684. args = append(args, fromItem)
  1685. }
  1686. // pagination
  1687. queryStr += "ORDER BY account.item_id "
  1688. if order == OrderAsc {
  1689. queryStr += " ASC "
  1690. } else {
  1691. queryStr += " DESC "
  1692. }
  1693. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1694. query, argsQ, err := sqlx.In(queryStr, args...)
  1695. if err != nil {
  1696. return nil, 0, tracerr.Wrap(err)
  1697. }
  1698. query = hdb.db.Rebind(query)
  1699. accounts := []*AccountAPI{}
  1700. if err := meddler.QueryAll(hdb.db, &accounts, query, argsQ...); err != nil {
  1701. return nil, 0, tracerr.Wrap(err)
  1702. }
  1703. if len(accounts) == 0 {
  1704. return nil, 0, tracerr.Wrap(sql.ErrNoRows)
  1705. }
  1706. return db.SlicePtrsToSlice(accounts).([]AccountAPI),
  1707. accounts[0].TotalItems - uint64(len(accounts)), nil
  1708. }
  1709. // GetMetrics returns metrics
  1710. func (hdb *HistoryDB) GetMetrics(lastBatchNum common.BatchNum) (*Metrics, error) {
  1711. metricsTotals := &MetricsTotals{}
  1712. metrics := &Metrics{}
  1713. err := meddler.QueryRow(
  1714. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs,
  1715. COALESCE (MIN(tx.batch_num), 0) as batch_num
  1716. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1717. WHERE block.timestamp >= NOW() - INTERVAL '24 HOURS';`)
  1718. if err != nil {
  1719. return nil, tracerr.Wrap(err)
  1720. }
  1721. metrics.TransactionsPerSecond = float64(metricsTotals.TotalTransactions / (24 * 60 * 60))
  1722. if (lastBatchNum - metricsTotals.FirstBatchNum) > 0 {
  1723. metrics.TransactionsPerBatch = float64(int64(metricsTotals.TotalTransactions) /
  1724. int64(lastBatchNum-metricsTotals.FirstBatchNum))
  1725. } else {
  1726. metrics.TransactionsPerBatch = float64(0)
  1727. }
  1728. err = meddler.QueryRow(
  1729. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1730. COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch
  1731. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1732. if err != nil {
  1733. return nil, tracerr.Wrap(err)
  1734. }
  1735. if metricsTotals.TotalBatches > 0 {
  1736. metrics.BatchFrequency = float64((24 * 60 * 60) / metricsTotals.TotalBatches)
  1737. } else {
  1738. metrics.BatchFrequency = 0
  1739. }
  1740. if metricsTotals.TotalTransactions > 0 {
  1741. metrics.AvgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1742. } else {
  1743. metrics.AvgTransactionFee = 0
  1744. }
  1745. err = meddler.QueryRow(
  1746. hdb.db, metrics,
  1747. `SELECT COUNT(*) AS total_bjjs, COUNT(DISTINCT(bjj)) AS total_accounts FROM account;`)
  1748. if err != nil {
  1749. return nil, tracerr.Wrap(err)
  1750. }
  1751. return metrics, nil
  1752. }
  1753. // GetAvgTxFee returns average transaction fee of the last 1h
  1754. func (hdb *HistoryDB) GetAvgTxFee() (float64, error) {
  1755. metricsTotals := &MetricsTotals{}
  1756. err := meddler.QueryRow(
  1757. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs,
  1758. COALESCE (MIN(tx.batch_num), 0) as batch_num
  1759. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1760. WHERE block.timestamp >= NOW() - INTERVAL '1 HOURS';`)
  1761. if err != nil {
  1762. return 0, tracerr.Wrap(err)
  1763. }
  1764. err = meddler.QueryRow(
  1765. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1766. COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch
  1767. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1768. if err != nil {
  1769. return 0, tracerr.Wrap(err)
  1770. }
  1771. var avgTransactionFee float64
  1772. if metricsTotals.TotalTransactions > 0 {
  1773. avgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1774. } else {
  1775. avgTransactionFee = 0
  1776. }
  1777. return avgTransactionFee, nil
  1778. }