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.

1896 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. account.bjj, account.eth_addr,
  1026. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  1027. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  1028. token.token_id, token.item_id AS token_item_id,
  1029. token.eth_block_num AS token_block, token.eth_addr AS token_eth_addr, token.name, token.symbol,
  1030. token.decimals, token.usd, token.usd_update
  1031. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  1032. INNER JOIN token ON account.token_id = token.token_id
  1033. WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx,
  1034. )
  1035. return exit, tracerr.Wrap(err)
  1036. }
  1037. // GetExitsAPI returns a list of exits from the DB and pagination info
  1038. func (hdb *HistoryDB) GetExitsAPI(
  1039. ethAddr *ethCommon.Address, bjj *babyjub.PublicKeyComp, tokenID *common.TokenID,
  1040. idx *common.Idx, batchNum *uint, onlyPendingWithdraws *bool,
  1041. fromItem, limit *uint, order string,
  1042. ) ([]ExitAPI, uint64, error) {
  1043. if ethAddr != nil && bjj != nil {
  1044. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  1045. }
  1046. var query string
  1047. var args []interface{}
  1048. queryStr := `SELECT exit_tree.item_id, exit_tree.batch_num,
  1049. hez_idx(exit_tree.account_idx, token.symbol) AS account_idx,
  1050. account.bjj, account.eth_addr,
  1051. exit_tree.merkle_proof, exit_tree.balance, exit_tree.instant_withdrawn,
  1052. exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn,
  1053. token.token_id, token.item_id AS token_item_id,
  1054. token.eth_block_num AS token_block, token.eth_addr AS token_eth_addr, token.name, token.symbol,
  1055. token.decimals, token.usd, token.usd_update, COUNT(*) OVER() AS total_items
  1056. FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx
  1057. INNER JOIN token ON account.token_id = token.token_id `
  1058. // Apply filters
  1059. nextIsAnd := false
  1060. // ethAddr filter
  1061. if ethAddr != nil {
  1062. queryStr += "WHERE account.eth_addr = ? "
  1063. nextIsAnd = true
  1064. args = append(args, ethAddr)
  1065. } else if bjj != nil { // bjj filter
  1066. queryStr += "WHERE account.bjj = ? "
  1067. nextIsAnd = true
  1068. args = append(args, bjj)
  1069. }
  1070. // tokenID filter
  1071. if tokenID != nil {
  1072. if nextIsAnd {
  1073. queryStr += "AND "
  1074. } else {
  1075. queryStr += "WHERE "
  1076. }
  1077. queryStr += "account.token_id = ? "
  1078. args = append(args, tokenID)
  1079. nextIsAnd = true
  1080. }
  1081. // idx filter
  1082. if idx != nil {
  1083. if nextIsAnd {
  1084. queryStr += "AND "
  1085. } else {
  1086. queryStr += "WHERE "
  1087. }
  1088. queryStr += "exit_tree.account_idx = ? "
  1089. args = append(args, idx)
  1090. nextIsAnd = true
  1091. }
  1092. // batchNum filter
  1093. if batchNum != nil {
  1094. if nextIsAnd {
  1095. queryStr += "AND "
  1096. } else {
  1097. queryStr += "WHERE "
  1098. }
  1099. queryStr += "exit_tree.batch_num = ? "
  1100. args = append(args, batchNum)
  1101. nextIsAnd = true
  1102. }
  1103. // onlyPendingWithdraws
  1104. if onlyPendingWithdraws != nil {
  1105. if *onlyPendingWithdraws {
  1106. if nextIsAnd {
  1107. queryStr += "AND "
  1108. } else {
  1109. queryStr += "WHERE "
  1110. }
  1111. queryStr += "(exit_tree.instant_withdrawn IS NULL AND exit_tree.delayed_withdrawn IS NULL) "
  1112. nextIsAnd = true
  1113. }
  1114. }
  1115. if fromItem != nil {
  1116. if nextIsAnd {
  1117. queryStr += "AND "
  1118. } else {
  1119. queryStr += "WHERE "
  1120. }
  1121. if order == OrderAsc {
  1122. queryStr += "exit_tree.item_id >= ? "
  1123. } else {
  1124. queryStr += "exit_tree.item_id <= ? "
  1125. }
  1126. args = append(args, fromItem)
  1127. // nextIsAnd = true
  1128. }
  1129. // pagination
  1130. queryStr += "ORDER BY exit_tree.item_id "
  1131. if order == OrderAsc {
  1132. queryStr += " ASC "
  1133. } else {
  1134. queryStr += " DESC "
  1135. }
  1136. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1137. query = hdb.db.Rebind(queryStr)
  1138. // log.Debug(query)
  1139. exits := []*ExitAPI{}
  1140. if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil {
  1141. return nil, 0, tracerr.Wrap(err)
  1142. }
  1143. if len(exits) == 0 {
  1144. return nil, 0, tracerr.Wrap(sql.ErrNoRows)
  1145. }
  1146. return db.SlicePtrsToSlice(exits).([]ExitAPI), exits[0].TotalItems - uint64(len(exits)), nil
  1147. }
  1148. // GetAllL1UserTxs returns all L1UserTxs from the DB
  1149. func (hdb *HistoryDB) GetAllL1UserTxs() ([]common.L1Tx, error) {
  1150. var txs []*common.L1Tx
  1151. err := meddler.QueryAll(
  1152. hdb.db, &txs, // Note that '\x' gets parsed as a big.Int with value = 0
  1153. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1154. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1155. tx.amount, (CASE WHEN tx.batch_num IS NULL THEN NULL WHEN tx.amount_success THEN tx.amount ELSE '\x' END) AS effective_amount,
  1156. 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,
  1157. tx.eth_block_num, tx.type, tx.batch_num
  1158. FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE ORDER BY item_id;`,
  1159. )
  1160. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1161. }
  1162. // GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB
  1163. func (hdb *HistoryDB) GetAllL1CoordinatorTxs() ([]common.L1Tx, error) {
  1164. var txs []*common.L1Tx
  1165. // Since the query specifies that only coordinator txs are returned, it's safe to assume
  1166. // that returned txs will always have effective amounts
  1167. err := meddler.QueryAll(
  1168. hdb.db, &txs,
  1169. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1170. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1171. tx.amount, tx.amount AS effective_amount,
  1172. tx.deposit_amount, tx.deposit_amount AS effective_deposit_amount,
  1173. tx.eth_block_num, tx.type, tx.batch_num
  1174. FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE ORDER BY item_id;`,
  1175. )
  1176. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1177. }
  1178. // GetAllL2Txs returns all L2Txs from the DB
  1179. func (hdb *HistoryDB) GetAllL2Txs() ([]common.L2Tx, error) {
  1180. var txs []*common.L2Tx
  1181. err := meddler.QueryAll(
  1182. hdb.db, &txs,
  1183. `SELECT tx.id, tx.batch_num, tx.position,
  1184. tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,
  1185. tx.type, tx.eth_block_num
  1186. FROM tx WHERE is_l1 = FALSE ORDER BY item_id;`,
  1187. )
  1188. return db.SlicePtrsToSlice(txs).([]common.L2Tx), tracerr.Wrap(err)
  1189. }
  1190. // GetUnforgedL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.
  1191. func (hdb *HistoryDB) GetUnforgedL1UserTxs(toForgeL1TxsNum int64) ([]common.L1Tx, error) {
  1192. var txs []*common.L1Tx
  1193. err := meddler.QueryAll(
  1194. hdb.db, &txs, // only L1 user txs can have batch_num set to null
  1195. `SELECT tx.id, tx.to_forge_l1_txs_num, tx.position, tx.user_origin,
  1196. tx.from_idx, tx.from_eth_addr, tx.from_bjj, tx.to_idx, tx.token_id,
  1197. tx.amount, NULL AS effective_amount,
  1198. tx.deposit_amount, NULL AS effective_deposit_amount,
  1199. tx.eth_block_num, tx.type, tx.batch_num
  1200. FROM tx WHERE batch_num IS NULL AND to_forge_l1_txs_num = $1
  1201. ORDER BY position;`,
  1202. toForgeL1TxsNum,
  1203. )
  1204. return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err)
  1205. }
  1206. // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.
  1207. // GetLastTxsPosition for a given to_forge_l1_txs_num
  1208. func (hdb *HistoryDB) GetLastTxsPosition(toForgeL1TxsNum int64) (int, error) {
  1209. row := hdb.db.QueryRow(
  1210. "SELECT position FROM tx WHERE to_forge_l1_txs_num = $1 ORDER BY position DESC;",
  1211. toForgeL1TxsNum,
  1212. )
  1213. var lastL1TxsPosition int
  1214. return lastL1TxsPosition, tracerr.Wrap(row.Scan(&lastL1TxsPosition))
  1215. }
  1216. // GetSCVars returns the rollup, auction and wdelayer smart contracts variables at their last update.
  1217. func (hdb *HistoryDB) GetSCVars() (*common.RollupVariables, *common.AuctionVariables,
  1218. *common.WDelayerVariables, error) {
  1219. var rollup common.RollupVariables
  1220. var auction common.AuctionVariables
  1221. var wDelayer common.WDelayerVariables
  1222. if err := meddler.QueryRow(hdb.db, &rollup,
  1223. "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1224. return nil, nil, nil, tracerr.Wrap(err)
  1225. }
  1226. if err := meddler.QueryRow(hdb.db, &auction,
  1227. "SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1228. return nil, nil, nil, tracerr.Wrap(err)
  1229. }
  1230. if err := meddler.QueryRow(hdb.db, &wDelayer,
  1231. "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil {
  1232. return nil, nil, nil, tracerr.Wrap(err)
  1233. }
  1234. return &rollup, &auction, &wDelayer, nil
  1235. }
  1236. func (hdb *HistoryDB) setRollupVars(d meddler.DB, rollup *common.RollupVariables) error {
  1237. return tracerr.Wrap(meddler.Insert(d, "rollup_vars", rollup))
  1238. }
  1239. func (hdb *HistoryDB) setAuctionVars(d meddler.DB, auction *common.AuctionVariables) error {
  1240. return tracerr.Wrap(meddler.Insert(d, "auction_vars", auction))
  1241. }
  1242. func (hdb *HistoryDB) setWDelayerVars(d meddler.DB, wDelayer *common.WDelayerVariables) error {
  1243. return tracerr.Wrap(meddler.Insert(d, "wdelayer_vars", wDelayer))
  1244. }
  1245. func (hdb *HistoryDB) addBucketUpdates(d meddler.DB, bucketUpdates []common.BucketUpdate) error {
  1246. if len(bucketUpdates) == 0 {
  1247. return nil
  1248. }
  1249. return tracerr.Wrap(db.BulkInsert(
  1250. d,
  1251. `INSERT INTO bucket_update (
  1252. eth_block_num,
  1253. num_bucket,
  1254. block_stamp,
  1255. withdrawals
  1256. ) VALUES %s;`,
  1257. bucketUpdates[:],
  1258. ))
  1259. }
  1260. // GetAllBucketUpdates retrieves all the bucket updates
  1261. func (hdb *HistoryDB) GetAllBucketUpdates() ([]common.BucketUpdate, error) {
  1262. var bucketUpdates []*common.BucketUpdate
  1263. err := meddler.QueryAll(
  1264. hdb.db, &bucketUpdates,
  1265. "SELECT * FROM bucket_update ORDER BY item_id;",
  1266. )
  1267. return db.SlicePtrsToSlice(bucketUpdates).([]common.BucketUpdate), tracerr.Wrap(err)
  1268. }
  1269. func (hdb *HistoryDB) addTokenExchanges(d meddler.DB, tokenExchanges []common.TokenExchange) error {
  1270. if len(tokenExchanges) == 0 {
  1271. return nil
  1272. }
  1273. return tracerr.Wrap(db.BulkInsert(
  1274. d,
  1275. `INSERT INTO token_exchange (
  1276. eth_block_num,
  1277. eth_addr,
  1278. value_usd
  1279. ) VALUES %s;`,
  1280. tokenExchanges[:],
  1281. ))
  1282. }
  1283. // GetAllTokenExchanges retrieves all the token exchanges
  1284. func (hdb *HistoryDB) GetAllTokenExchanges() ([]common.TokenExchange, error) {
  1285. var tokenExchanges []*common.TokenExchange
  1286. err := meddler.QueryAll(
  1287. hdb.db, &tokenExchanges,
  1288. "SELECT * FROM token_exchange ORDER BY item_id;",
  1289. )
  1290. return db.SlicePtrsToSlice(tokenExchanges).([]common.TokenExchange), tracerr.Wrap(err)
  1291. }
  1292. func (hdb *HistoryDB) addEscapeHatchWithdrawals(d meddler.DB,
  1293. escapeHatchWithdrawals []common.WDelayerEscapeHatchWithdrawal) error {
  1294. if len(escapeHatchWithdrawals) == 0 {
  1295. return nil
  1296. }
  1297. return tracerr.Wrap(db.BulkInsert(
  1298. d,
  1299. `INSERT INTO escape_hatch_withdrawal (
  1300. eth_block_num,
  1301. who_addr,
  1302. to_addr,
  1303. token_addr,
  1304. amount
  1305. ) VALUES %s;`,
  1306. escapeHatchWithdrawals[:],
  1307. ))
  1308. }
  1309. // GetAllEscapeHatchWithdrawals retrieves all the escape hatch withdrawals
  1310. func (hdb *HistoryDB) GetAllEscapeHatchWithdrawals() ([]common.WDelayerEscapeHatchWithdrawal, error) {
  1311. var escapeHatchWithdrawals []*common.WDelayerEscapeHatchWithdrawal
  1312. err := meddler.QueryAll(
  1313. hdb.db, &escapeHatchWithdrawals,
  1314. "SELECT * FROM escape_hatch_withdrawal ORDER BY item_id;",
  1315. )
  1316. return db.SlicePtrsToSlice(escapeHatchWithdrawals).([]common.WDelayerEscapeHatchWithdrawal),
  1317. tracerr.Wrap(err)
  1318. }
  1319. // SetInitialSCVars sets the initial state of rollup, auction, wdelayer smart
  1320. // contract variables. This initial state is stored linked to block 0, which
  1321. // always exist in the DB and is used to store initialization data that always
  1322. // exist in the smart contracts.
  1323. func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,
  1324. auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error {
  1325. txn, err := hdb.db.Beginx()
  1326. if err != nil {
  1327. return tracerr.Wrap(err)
  1328. }
  1329. defer func() {
  1330. if err != nil {
  1331. db.Rollback(txn)
  1332. }
  1333. }()
  1334. // Force EthBlockNum to be 0 because it's the block used to link data
  1335. // that belongs to the creation of the smart contracts
  1336. rollup.EthBlockNum = 0
  1337. auction.EthBlockNum = 0
  1338. wDelayer.EthBlockNum = 0
  1339. auction.DefaultSlotSetBidSlotNum = 0
  1340. if err := hdb.setRollupVars(txn, rollup); err != nil {
  1341. return tracerr.Wrap(err)
  1342. }
  1343. if err := hdb.setAuctionVars(txn, auction); err != nil {
  1344. return tracerr.Wrap(err)
  1345. }
  1346. if err := hdb.setWDelayerVars(txn, wDelayer); err != nil {
  1347. return tracerr.Wrap(err)
  1348. }
  1349. return tracerr.Wrap(txn.Commit())
  1350. }
  1351. // setL1UserTxEffectiveAmounts sets the EffectiveAmount and EffectiveDepositAmount
  1352. // of the given l1UserTxs (with an UPDATE)
  1353. func (hdb *HistoryDB) setL1UserTxEffectiveAmounts(d sqlx.Ext, txs []common.L1Tx) error {
  1354. if len(txs) == 0 {
  1355. return nil
  1356. }
  1357. // Effective amounts are stored as success flags in the DB, with true value by default
  1358. // to reduce the amount of updates. Therefore, only amounts that became uneffective should be
  1359. // updated to become false
  1360. type txUpdate struct {
  1361. ID common.TxID `db:"id"`
  1362. AmountSuccess bool `db:"amount_success"`
  1363. DepositAmountSuccess bool `db:"deposit_amount_success"`
  1364. }
  1365. txUpdates := []txUpdate{}
  1366. equal := func(a *big.Int, b *big.Int) bool {
  1367. return a.Cmp(b) == 0
  1368. }
  1369. for i := range txs {
  1370. amountSuccess := equal(txs[i].Amount, txs[i].EffectiveAmount)
  1371. depositAmountSuccess := equal(txs[i].DepositAmount, txs[i].EffectiveDepositAmount)
  1372. if !amountSuccess || !depositAmountSuccess {
  1373. txUpdates = append(txUpdates, txUpdate{
  1374. ID: txs[i].TxID,
  1375. AmountSuccess: amountSuccess,
  1376. DepositAmountSuccess: depositAmountSuccess,
  1377. })
  1378. }
  1379. }
  1380. const query string = `
  1381. UPDATE tx SET
  1382. amount_success = tx_update.amount_success,
  1383. deposit_amount_success = tx_update.deposit_amount_success
  1384. FROM (VALUES
  1385. (NULL::::BYTEA, NULL::::BOOL, NULL::::BOOL),
  1386. (:id, :amount_success, :deposit_amount_success)
  1387. ) as tx_update (id, amount_success, deposit_amount_success)
  1388. WHERE tx.id = tx_update.id;
  1389. `
  1390. if len(txUpdates) > 0 {
  1391. if _, err := sqlx.NamedExec(d, query, txUpdates); err != nil {
  1392. return tracerr.Wrap(err)
  1393. }
  1394. }
  1395. return nil
  1396. }
  1397. // AddBlockSCData stores all the information of a block retrieved by the
  1398. // Synchronizer. Blocks should be inserted in order, leaving no gaps because
  1399. // the pagination system of the API/DB depends on this. Within blocks, all
  1400. // items should also be in the correct order (Accounts, Tokens, Txs, etc.)
  1401. func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) {
  1402. txn, err := hdb.db.Beginx()
  1403. if err != nil {
  1404. return tracerr.Wrap(err)
  1405. }
  1406. defer func() {
  1407. if err != nil {
  1408. db.Rollback(txn)
  1409. }
  1410. }()
  1411. // Add block
  1412. if err := hdb.addBlock(txn, &blockData.Block); err != nil {
  1413. return tracerr.Wrap(err)
  1414. }
  1415. // Add Coordinators
  1416. if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil {
  1417. return tracerr.Wrap(err)
  1418. }
  1419. // Add Bids
  1420. if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil {
  1421. return tracerr.Wrap(err)
  1422. }
  1423. // Add Tokens
  1424. if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil {
  1425. return tracerr.Wrap(err)
  1426. }
  1427. // Prepare user L1 txs to be added.
  1428. // They must be added before the batch that will forge them (which can be in the same block)
  1429. // and after the account that will be sent to (also can be in the same block).
  1430. // Note: insert order is not relevant since item_id will be updated by a DB trigger when
  1431. // the batch that forges those txs is inserted
  1432. userL1s := make(map[common.BatchNum][]common.L1Tx)
  1433. for i := range blockData.Rollup.L1UserTxs {
  1434. batchThatForgesIsInTheBlock := false
  1435. for _, batch := range blockData.Rollup.Batches {
  1436. if batch.Batch.ForgeL1TxsNum != nil &&
  1437. *batch.Batch.ForgeL1TxsNum == *blockData.Rollup.L1UserTxs[i].ToForgeL1TxsNum {
  1438. // Tx is forged in this block. It's guaranteed that:
  1439. // * the first batch of the block won't forge user L1 txs that have been added in this block
  1440. // * batch nums are sequential therefore it's safe to add the tx at batch.BatchNum -1
  1441. batchThatForgesIsInTheBlock = true
  1442. addAtBatchNum := batch.Batch.BatchNum - 1
  1443. userL1s[addAtBatchNum] = append(userL1s[addAtBatchNum], blockData.Rollup.L1UserTxs[i])
  1444. break
  1445. }
  1446. }
  1447. if !batchThatForgesIsInTheBlock {
  1448. // User artificial batchNum 0 to add txs that are not forge in this block
  1449. // after all the accounts of the block have been added
  1450. userL1s[0] = append(userL1s[0], blockData.Rollup.L1UserTxs[i])
  1451. }
  1452. }
  1453. // Add Batches
  1454. for i := range blockData.Rollup.Batches {
  1455. batch := &blockData.Rollup.Batches[i]
  1456. // Add Batch: this will trigger an update on the DB
  1457. // that will set the batch num of forged L1 txs in this batch
  1458. if err = hdb.addBatch(txn, &batch.Batch); err != nil {
  1459. return tracerr.Wrap(err)
  1460. }
  1461. // Set the EffectiveAmount and EffectiveDepositAmount of all the
  1462. // L1UserTxs that have been forged in this batch
  1463. if err = hdb.setL1UserTxEffectiveAmounts(txn, batch.L1UserTxs); err != nil {
  1464. return tracerr.Wrap(err)
  1465. }
  1466. // Add accounts
  1467. if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil {
  1468. return tracerr.Wrap(err)
  1469. }
  1470. // Add forged l1 coordinator Txs
  1471. if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil {
  1472. return tracerr.Wrap(err)
  1473. }
  1474. // Add l2 Txs
  1475. if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil {
  1476. return tracerr.Wrap(err)
  1477. }
  1478. // Add user L1 txs that will be forged in next batch
  1479. if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok {
  1480. if err := hdb.addL1Txs(txn, userlL1s); err != nil {
  1481. return tracerr.Wrap(err)
  1482. }
  1483. }
  1484. // Add exit tree
  1485. if err := hdb.addExitTree(txn, batch.ExitTree); err != nil {
  1486. return tracerr.Wrap(err)
  1487. }
  1488. }
  1489. // Add user L1 txs that won't be forged in this block
  1490. if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok {
  1491. if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil {
  1492. return tracerr.Wrap(err)
  1493. }
  1494. }
  1495. // Set SC Vars if there was an update
  1496. if blockData.Rollup.Vars != nil {
  1497. if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil {
  1498. return tracerr.Wrap(err)
  1499. }
  1500. }
  1501. if blockData.Auction.Vars != nil {
  1502. if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil {
  1503. return tracerr.Wrap(err)
  1504. }
  1505. }
  1506. if blockData.WDelayer.Vars != nil {
  1507. if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil {
  1508. return tracerr.Wrap(err)
  1509. }
  1510. }
  1511. // Update withdrawals in exit tree table
  1512. if err := hdb.updateExitTree(txn, blockData.Block.Num,
  1513. blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil {
  1514. return tracerr.Wrap(err)
  1515. }
  1516. // Add Escape Hatch Withdrawals
  1517. if err := hdb.addEscapeHatchWithdrawals(txn,
  1518. blockData.WDelayer.EscapeHatchWithdrawals); err != nil {
  1519. return tracerr.Wrap(err)
  1520. }
  1521. // Add Buckets withdrawals updates
  1522. if err := hdb.addBucketUpdates(txn, blockData.Rollup.UpdateBucketWithdraw); err != nil {
  1523. return tracerr.Wrap(err)
  1524. }
  1525. // Add Token exchange updates
  1526. if err := hdb.addTokenExchanges(txn, blockData.Rollup.TokenExchanges); err != nil {
  1527. return tracerr.Wrap(err)
  1528. }
  1529. return tracerr.Wrap(txn.Commit())
  1530. }
  1531. // GetCoordinatorAPI returns a coordinator by its bidderAddr
  1532. func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) {
  1533. coordinator := &CoordinatorAPI{}
  1534. err := meddler.QueryRow(hdb.db, coordinator, "SELECT * FROM coordinator WHERE bidder_addr = $1;", bidderAddr)
  1535. return coordinator, tracerr.Wrap(err)
  1536. }
  1537. // GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info
  1538. func (hdb *HistoryDB) GetCoordinatorsAPI(
  1539. bidderAddr, forgerAddr *ethCommon.Address,
  1540. fromItem, limit *uint, order string,
  1541. ) ([]CoordinatorAPI, uint64, error) {
  1542. var query string
  1543. var args []interface{}
  1544. queryStr := `SELECT coordinator.*,
  1545. COUNT(*) OVER() AS total_items
  1546. FROM coordinator `
  1547. // Apply filters
  1548. nextIsAnd := false
  1549. if bidderAddr != nil {
  1550. queryStr += "WHERE bidder_addr = ? "
  1551. nextIsAnd = true
  1552. args = append(args, bidderAddr)
  1553. }
  1554. if forgerAddr != nil {
  1555. if nextIsAnd {
  1556. queryStr += "AND "
  1557. } else {
  1558. queryStr += "WHERE "
  1559. }
  1560. queryStr += "forger_addr = ? "
  1561. nextIsAnd = true
  1562. args = append(args, forgerAddr)
  1563. }
  1564. if fromItem != nil {
  1565. if nextIsAnd {
  1566. queryStr += "AND "
  1567. } else {
  1568. queryStr += "WHERE "
  1569. }
  1570. if order == OrderAsc {
  1571. queryStr += "coordinator.item_id >= ? "
  1572. } else {
  1573. queryStr += "coordinator.item_id <= ? "
  1574. }
  1575. args = append(args, fromItem)
  1576. }
  1577. // pagination
  1578. queryStr += "ORDER BY coordinator.item_id "
  1579. if order == OrderAsc {
  1580. queryStr += " ASC "
  1581. } else {
  1582. queryStr += " DESC "
  1583. }
  1584. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1585. query = hdb.db.Rebind(queryStr)
  1586. coordinators := []*CoordinatorAPI{}
  1587. if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil {
  1588. return nil, 0, tracerr.Wrap(err)
  1589. }
  1590. if len(coordinators) == 0 {
  1591. return nil, 0, tracerr.Wrap(sql.ErrNoRows)
  1592. }
  1593. return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI),
  1594. coordinators[0].TotalItems - uint64(len(coordinators)), nil
  1595. }
  1596. // AddAuctionVars insert auction vars into the DB
  1597. func (hdb *HistoryDB) AddAuctionVars(auctionVars *common.AuctionVariables) error {
  1598. return tracerr.Wrap(meddler.Insert(hdb.db, "auction_vars", auctionVars))
  1599. }
  1600. // GetAuctionVars returns auction variables
  1601. func (hdb *HistoryDB) GetAuctionVars() (*common.AuctionVariables, error) {
  1602. auctionVars := &common.AuctionVariables{}
  1603. err := meddler.QueryRow(
  1604. hdb.db, auctionVars, `SELECT * FROM auction_vars;`,
  1605. )
  1606. return auctionVars, tracerr.Wrap(err)
  1607. }
  1608. // GetAuctionVarsUntilSetSlotNum returns all the updates of the auction vars
  1609. // from the last entry in which DefaultSlotSetBidSlotNum <= slotNum
  1610. func (hdb *HistoryDB) GetAuctionVarsUntilSetSlotNum(slotNum int64, maxItems int) ([]MinBidInfo, error) {
  1611. auctionVars := []*MinBidInfo{}
  1612. query := `
  1613. SELECT DISTINCT default_slot_set_bid, default_slot_set_bid_slot_num FROM auction_vars
  1614. WHERE default_slot_set_bid_slot_num < $1
  1615. ORDER BY default_slot_set_bid_slot_num DESC
  1616. LIMIT $2;
  1617. `
  1618. err := meddler.QueryAll(hdb.db, &auctionVars, query, slotNum, maxItems)
  1619. if err != nil {
  1620. return nil, tracerr.Wrap(err)
  1621. }
  1622. return db.SlicePtrsToSlice(auctionVars).([]MinBidInfo), nil
  1623. }
  1624. // GetAccountAPI returns an account by its index
  1625. func (hdb *HistoryDB) GetAccountAPI(idx common.Idx) (*AccountAPI, error) {
  1626. account := &AccountAPI{}
  1627. err := meddler.QueryRow(hdb.db, account, `SELECT account.item_id, hez_idx(account.idx,
  1628. token.symbol) as idx, account.batch_num, account.bjj, account.eth_addr,
  1629. token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1630. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update
  1631. FROM account INNER JOIN token ON account.token_id = token.token_id WHERE idx = $1;`, idx)
  1632. if err != nil {
  1633. return nil, tracerr.Wrap(err)
  1634. }
  1635. return account, nil
  1636. }
  1637. // GetAccountsAPI returns a list of accounts from the DB and pagination info
  1638. func (hdb *HistoryDB) GetAccountsAPI(
  1639. tokenIDs []common.TokenID, ethAddr *ethCommon.Address,
  1640. bjj *babyjub.PublicKeyComp, fromItem, limit *uint, order string,
  1641. ) ([]AccountAPI, uint64, error) {
  1642. if ethAddr != nil && bjj != nil {
  1643. return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible"))
  1644. }
  1645. var query string
  1646. var args []interface{}
  1647. queryStr := `SELECT account.item_id, hez_idx(account.idx, token.symbol) as idx, account.batch_num,
  1648. account.bjj, account.eth_addr, token.token_id, token.item_id AS token_item_id, token.eth_block_num AS token_block,
  1649. token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update,
  1650. COUNT(*) OVER() AS total_items
  1651. FROM account INNER JOIN token ON account.token_id = token.token_id `
  1652. // Apply filters
  1653. nextIsAnd := false
  1654. // ethAddr filter
  1655. if ethAddr != nil {
  1656. queryStr += "WHERE account.eth_addr = ? "
  1657. nextIsAnd = true
  1658. args = append(args, ethAddr)
  1659. } else if bjj != nil { // bjj filter
  1660. queryStr += "WHERE account.bjj = ? "
  1661. nextIsAnd = true
  1662. args = append(args, bjj)
  1663. }
  1664. // tokenID filter
  1665. if len(tokenIDs) > 0 {
  1666. if nextIsAnd {
  1667. queryStr += "AND "
  1668. } else {
  1669. queryStr += "WHERE "
  1670. }
  1671. queryStr += "account.token_id IN (?) "
  1672. args = append(args, tokenIDs)
  1673. nextIsAnd = true
  1674. }
  1675. if fromItem != nil {
  1676. if nextIsAnd {
  1677. queryStr += "AND "
  1678. } else {
  1679. queryStr += "WHERE "
  1680. }
  1681. if order == OrderAsc {
  1682. queryStr += "account.item_id >= ? "
  1683. } else {
  1684. queryStr += "account.item_id <= ? "
  1685. }
  1686. args = append(args, fromItem)
  1687. }
  1688. // pagination
  1689. queryStr += "ORDER BY account.item_id "
  1690. if order == OrderAsc {
  1691. queryStr += " ASC "
  1692. } else {
  1693. queryStr += " DESC "
  1694. }
  1695. queryStr += fmt.Sprintf("LIMIT %d;", *limit)
  1696. query, argsQ, err := sqlx.In(queryStr, args...)
  1697. if err != nil {
  1698. return nil, 0, tracerr.Wrap(err)
  1699. }
  1700. query = hdb.db.Rebind(query)
  1701. accounts := []*AccountAPI{}
  1702. if err := meddler.QueryAll(hdb.db, &accounts, query, argsQ...); err != nil {
  1703. return nil, 0, tracerr.Wrap(err)
  1704. }
  1705. if len(accounts) == 0 {
  1706. return nil, 0, tracerr.Wrap(sql.ErrNoRows)
  1707. }
  1708. return db.SlicePtrsToSlice(accounts).([]AccountAPI),
  1709. accounts[0].TotalItems - uint64(len(accounts)), nil
  1710. }
  1711. // GetMetrics returns metrics
  1712. func (hdb *HistoryDB) GetMetrics(lastBatchNum common.BatchNum) (*Metrics, error) {
  1713. metricsTotals := &MetricsTotals{}
  1714. metrics := &Metrics{}
  1715. err := meddler.QueryRow(
  1716. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs,
  1717. COALESCE (MIN(tx.batch_num), 0) as batch_num
  1718. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1719. WHERE block.timestamp >= NOW() - INTERVAL '24 HOURS';`)
  1720. if err != nil {
  1721. return nil, tracerr.Wrap(err)
  1722. }
  1723. metrics.TransactionsPerSecond = float64(metricsTotals.TotalTransactions / (24 * 60 * 60))
  1724. if (lastBatchNum - metricsTotals.FirstBatchNum) > 0 {
  1725. metrics.TransactionsPerBatch = float64(int64(metricsTotals.TotalTransactions) /
  1726. int64(lastBatchNum-metricsTotals.FirstBatchNum))
  1727. } else {
  1728. metrics.TransactionsPerBatch = float64(0)
  1729. }
  1730. err = meddler.QueryRow(
  1731. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1732. COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch
  1733. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1734. if err != nil {
  1735. return nil, tracerr.Wrap(err)
  1736. }
  1737. if metricsTotals.TotalBatches > 0 {
  1738. metrics.BatchFrequency = float64((24 * 60 * 60) / metricsTotals.TotalBatches)
  1739. } else {
  1740. metrics.BatchFrequency = 0
  1741. }
  1742. if metricsTotals.TotalTransactions > 0 {
  1743. metrics.AvgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1744. } else {
  1745. metrics.AvgTransactionFee = 0
  1746. }
  1747. err = meddler.QueryRow(
  1748. hdb.db, metrics,
  1749. `SELECT COUNT(*) AS total_bjjs, COUNT(DISTINCT(bjj)) AS total_accounts FROM account;`)
  1750. if err != nil {
  1751. return nil, tracerr.Wrap(err)
  1752. }
  1753. return metrics, nil
  1754. }
  1755. // GetAvgTxFee returns average transaction fee of the last 1h
  1756. func (hdb *HistoryDB) GetAvgTxFee() (float64, error) {
  1757. metricsTotals := &MetricsTotals{}
  1758. err := meddler.QueryRow(
  1759. hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs,
  1760. COALESCE (MIN(tx.batch_num), 0) as batch_num
  1761. FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num
  1762. WHERE block.timestamp >= NOW() - INTERVAL '1 HOURS';`)
  1763. if err != nil {
  1764. return 0, tracerr.Wrap(err)
  1765. }
  1766. err = meddler.QueryRow(
  1767. hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,
  1768. COALESCE (SUM(total_fees_usd), 0) AS total_fees FROM batch
  1769. WHERE batch_num > $1;`, metricsTotals.FirstBatchNum)
  1770. if err != nil {
  1771. return 0, tracerr.Wrap(err)
  1772. }
  1773. var avgTransactionFee float64
  1774. if metricsTotals.TotalTransactions > 0 {
  1775. avgTransactionFee = metricsTotals.TotalFeesUSD / float64(metricsTotals.TotalTransactions)
  1776. } else {
  1777. avgTransactionFee = 0
  1778. }
  1779. return avgTransactionFee, nil
  1780. }