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.

1076 lines
39 KiB

4 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
  1. package eth
  2. import (
  3. "context"
  4. "fmt"
  5. "math/big"
  6. "strings"
  7. "github.com/ethereum/go-ethereum"
  8. "github.com/ethereum/go-ethereum/accounts/abi"
  9. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  10. ethCommon "github.com/ethereum/go-ethereum/common"
  11. "github.com/ethereum/go-ethereum/core/types"
  12. "github.com/ethereum/go-ethereum/crypto"
  13. "github.com/ethereum/go-ethereum/ethclient"
  14. "github.com/hermeznetwork/hermez-node/common"
  15. Hermez "github.com/hermeznetwork/hermez-node/eth/contracts/hermez"
  16. HEZ "github.com/hermeznetwork/hermez-node/eth/contracts/tokenHEZ"
  17. "github.com/hermeznetwork/hermez-node/log"
  18. "github.com/hermeznetwork/tracerr"
  19. "github.com/iden3/go-iden3-crypto/babyjub"
  20. )
  21. // QueueStruct is the queue of L1Txs for a batch
  22. type QueueStruct struct {
  23. L1TxQueue []common.L1Tx
  24. TotalL1TxFee *big.Int
  25. }
  26. // NewQueueStruct creates a new clear QueueStruct.
  27. func NewQueueStruct() *QueueStruct {
  28. return &QueueStruct{
  29. L1TxQueue: make([]common.L1Tx, 0),
  30. TotalL1TxFee: big.NewInt(0),
  31. }
  32. }
  33. // RollupState represents the state of the Rollup in the Smart Contract
  34. type RollupState struct {
  35. StateRoot *big.Int
  36. ExitRoots []*big.Int
  37. // ExitNullifierMap map[[256 / 8]byte]bool
  38. ExitNullifierMap map[int64]map[int64]bool // batchNum -> idx -> bool
  39. TokenList []ethCommon.Address
  40. TokenMap map[ethCommon.Address]bool
  41. MapL1TxQueue map[int64]*QueueStruct
  42. LastL1L2Batch int64
  43. CurrentToForgeL1TxsNum int64
  44. LastToForgeL1TxsNum int64
  45. CurrentIdx int64
  46. }
  47. // RollupEventInitialize is the InitializeHermezEvent event of the
  48. // Smart Contract
  49. type RollupEventInitialize struct {
  50. ForgeL1L2BatchTimeout uint8
  51. FeeAddToken *big.Int
  52. WithdrawalDelay uint64
  53. }
  54. // RollupVariables returns the RollupVariables from the initialize event
  55. func (ei *RollupEventInitialize) RollupVariables() *common.RollupVariables {
  56. buckets := make([]common.BucketParams, 1)
  57. for i := range buckets {
  58. buckets[i] = common.BucketParams{
  59. CeilUSD: big.NewInt(0),
  60. BlockStamp: big.NewInt(0),
  61. Withdrawals: big.NewInt(0),
  62. RateBlocks: big.NewInt(0),
  63. RateWithdrawals: big.NewInt(0),
  64. MaxWithdrawals: big.NewInt(0),
  65. }
  66. }
  67. return &common.RollupVariables{
  68. EthBlockNum: 0,
  69. FeeAddToken: ei.FeeAddToken,
  70. ForgeL1L2BatchTimeout: int64(ei.ForgeL1L2BatchTimeout),
  71. WithdrawalDelay: ei.WithdrawalDelay,
  72. Buckets: buckets,
  73. SafeMode: false,
  74. }
  75. }
  76. // RollupEventL1UserTx is an event of the Rollup Smart Contract
  77. type RollupEventL1UserTx struct {
  78. // ToForgeL1TxsNum int64 // QueueIndex *big.Int
  79. // Position int // TransactionIndex *big.Int
  80. L1UserTx common.L1Tx
  81. }
  82. // RollupEventL1UserTxAux is an event of the Rollup Smart Contract
  83. type rollupEventL1UserTxAux struct {
  84. ToForgeL1TxsNum uint64 // QueueIndex *big.Int
  85. Position uint8 // TransactionIndex *big.Int
  86. L1UserTx []byte
  87. }
  88. // RollupEventAddToken is an event of the Rollup Smart Contract
  89. type RollupEventAddToken struct {
  90. TokenAddress ethCommon.Address
  91. TokenID uint32
  92. }
  93. // RollupEventForgeBatch is an event of the Rollup Smart Contract
  94. type RollupEventForgeBatch struct {
  95. BatchNum int64
  96. // Sender ethCommon.Address
  97. EthTxHash ethCommon.Hash
  98. L1UserTxsLen uint16
  99. }
  100. // RollupEventUpdateForgeL1L2BatchTimeout is an event of the Rollup Smart Contract
  101. type RollupEventUpdateForgeL1L2BatchTimeout struct {
  102. NewForgeL1L2BatchTimeout int64
  103. }
  104. // RollupEventUpdateFeeAddToken is an event of the Rollup Smart Contract
  105. type RollupEventUpdateFeeAddToken struct {
  106. NewFeeAddToken *big.Int
  107. }
  108. // RollupEventWithdraw is an event of the Rollup Smart Contract
  109. type RollupEventWithdraw struct {
  110. Idx uint64
  111. NumExitRoot uint64
  112. InstantWithdraw bool
  113. TxHash ethCommon.Hash // Hash of the transaction that generated this event
  114. }
  115. type rollupEventUpdateBucketWithdrawAux struct {
  116. NumBucket uint8
  117. BlockStamp *big.Int
  118. Withdrawals *big.Int
  119. }
  120. // RollupEventUpdateBucketWithdraw is an event of the Rollup Smart Contract
  121. type RollupEventUpdateBucketWithdraw struct {
  122. NumBucket int
  123. BlockStamp int64 // blockNum
  124. Withdrawals *big.Int
  125. }
  126. // RollupEventUpdateWithdrawalDelay is an event of the Rollup Smart Contract
  127. type RollupEventUpdateWithdrawalDelay struct {
  128. NewWithdrawalDelay uint64
  129. }
  130. // RollupUpdateBucketsParameters are the bucket parameters used in an update
  131. type RollupUpdateBucketsParameters struct {
  132. CeilUSD *big.Int
  133. BlockStamp *big.Int
  134. Withdrawals *big.Int
  135. RateBlocks *big.Int
  136. RateWithdrawals *big.Int
  137. MaxWithdrawals *big.Int
  138. }
  139. type rollupEventUpdateBucketsParametersAux struct {
  140. ArrayBuckets []*big.Int
  141. }
  142. // RollupEventUpdateBucketsParameters is an event of the Rollup Smart Contract
  143. type RollupEventUpdateBucketsParameters struct {
  144. ArrayBuckets []RollupUpdateBucketsParameters
  145. SafeMode bool
  146. }
  147. // RollupEventUpdateTokenExchange is an event of the Rollup Smart Contract
  148. type RollupEventUpdateTokenExchange struct {
  149. AddressArray []ethCommon.Address
  150. ValueArray []uint64
  151. }
  152. // RollupEventSafeMode is an event of the Rollup Smart Contract
  153. type RollupEventSafeMode struct {
  154. }
  155. // RollupEvents is the list of events in a block of the Rollup Smart Contract
  156. type RollupEvents struct {
  157. L1UserTx []RollupEventL1UserTx
  158. AddToken []RollupEventAddToken
  159. ForgeBatch []RollupEventForgeBatch
  160. UpdateForgeL1L2BatchTimeout []RollupEventUpdateForgeL1L2BatchTimeout
  161. UpdateFeeAddToken []RollupEventUpdateFeeAddToken
  162. Withdraw []RollupEventWithdraw
  163. UpdateWithdrawalDelay []RollupEventUpdateWithdrawalDelay
  164. UpdateBucketWithdraw []RollupEventUpdateBucketWithdraw
  165. UpdateBucketsParameters []RollupEventUpdateBucketsParameters
  166. UpdateTokenExchange []RollupEventUpdateTokenExchange
  167. SafeMode []RollupEventSafeMode
  168. }
  169. // NewRollupEvents creates an empty RollupEvents with the slices initialized.
  170. func NewRollupEvents() RollupEvents {
  171. return RollupEvents{
  172. L1UserTx: make([]RollupEventL1UserTx, 0),
  173. AddToken: make([]RollupEventAddToken, 0),
  174. ForgeBatch: make([]RollupEventForgeBatch, 0),
  175. UpdateForgeL1L2BatchTimeout: make([]RollupEventUpdateForgeL1L2BatchTimeout, 0),
  176. UpdateFeeAddToken: make([]RollupEventUpdateFeeAddToken, 0),
  177. Withdraw: make([]RollupEventWithdraw, 0),
  178. }
  179. }
  180. // RollupForgeBatchArgs are the arguments to the ForgeBatch function in the Rollup Smart Contract
  181. type RollupForgeBatchArgs struct {
  182. NewLastIdx int64
  183. NewStRoot *big.Int
  184. NewExitRoot *big.Int
  185. L1UserTxs []common.L1Tx
  186. L1CoordinatorTxs []common.L1Tx
  187. L1CoordinatorTxsAuths [][]byte // Authorization for accountCreations for each L1CoordinatorTx
  188. L2TxsData []common.L2Tx
  189. FeeIdxCoordinator []common.Idx
  190. // Circuit selector
  191. VerifierIdx uint8
  192. L1Batch bool
  193. ProofA [2]*big.Int
  194. ProofB [2][2]*big.Int
  195. ProofC [2]*big.Int
  196. }
  197. // RollupForgeBatchArgsAux are the arguments to the ForgeBatch function in the Rollup Smart Contract
  198. type rollupForgeBatchArgsAux struct {
  199. NewLastIdx *big.Int
  200. NewStRoot *big.Int
  201. NewExitRoot *big.Int
  202. EncodedL1CoordinatorTx []byte
  203. L1L2TxsData []byte
  204. FeeIdxCoordinator []byte
  205. // Circuit selector
  206. VerifierIdx uint8
  207. L1Batch bool
  208. ProofA [2]*big.Int
  209. ProofB [2][2]*big.Int
  210. ProofC [2]*big.Int
  211. }
  212. // RollupInterface is the inteface to to Rollup Smart Contract
  213. type RollupInterface interface {
  214. //
  215. // Smart Contract Methods
  216. //
  217. // Public Functions
  218. RollupForgeBatch(*RollupForgeBatchArgs, *bind.TransactOpts) (*types.Transaction, error)
  219. RollupAddToken(tokenAddress ethCommon.Address, feeAddToken,
  220. deadline *big.Int) (*types.Transaction, error)
  221. RollupWithdrawMerkleProof(babyPubKey babyjub.PublicKeyComp, tokenID uint32, numExitRoot,
  222. idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (*types.Transaction,
  223. error)
  224. RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]*big.Int, tokenID uint32,
  225. numExitRoot, idx int64, amount *big.Int, instantWithdraw bool) (*types.Transaction, error)
  226. RollupL1UserTxERC20ETH(fromBJJ babyjub.PublicKeyComp, fromIdx int64, depositAmount *big.Int,
  227. amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error)
  228. RollupL1UserTxERC20Permit(fromBJJ babyjub.PublicKeyComp, fromIdx int64,
  229. depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64,
  230. deadline *big.Int) (tx *types.Transaction, err error)
  231. // Governance Public Functions
  232. RollupUpdateForgeL1L2BatchTimeout(newForgeL1L2BatchTimeout int64) (*types.Transaction, error)
  233. RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (*types.Transaction, error)
  234. // Viewers
  235. RollupRegisterTokensCount() (*big.Int, error)
  236. RollupLastForgedBatch() (int64, error)
  237. //
  238. // Smart Contract Status
  239. //
  240. RollupConstants() (*common.RollupConstants, error)
  241. RollupEventsByBlock(blockNum int64, blockHash *ethCommon.Hash) (*RollupEvents, error)
  242. RollupForgeBatchArgs(ethCommon.Hash, uint16) (*RollupForgeBatchArgs, *ethCommon.Address, error)
  243. RollupEventInit() (*RollupEventInitialize, int64, error)
  244. }
  245. //
  246. // Implementation
  247. //
  248. // RollupClient is the implementation of the interface to the Rollup Smart Contract in ethereum.
  249. type RollupClient struct {
  250. client *EthereumClient
  251. chainID *big.Int
  252. address ethCommon.Address
  253. tokenHEZCfg TokenConfig
  254. hermez *Hermez.Hermez
  255. tokenHEZ *HEZ.HEZ
  256. contractAbi abi.ABI
  257. opts *bind.CallOpts
  258. consts *common.RollupConstants
  259. }
  260. // NewRollupClient creates a new RollupClient
  261. func NewRollupClient(client *EthereumClient, address ethCommon.Address,
  262. tokenHEZCfg TokenConfig) (*RollupClient, error) {
  263. contractAbi, err := abi.JSON(strings.NewReader(string(Hermez.HermezABI)))
  264. if err != nil {
  265. return nil, tracerr.Wrap(err)
  266. }
  267. hermez, err := Hermez.NewHermez(address, client.Client())
  268. if err != nil {
  269. return nil, tracerr.Wrap(err)
  270. }
  271. tokenHEZ, err := HEZ.NewHEZ(tokenHEZCfg.Address, client.Client())
  272. if err != nil {
  273. return nil, tracerr.Wrap(err)
  274. }
  275. chainID, err := client.EthChainID()
  276. if err != nil {
  277. return nil, tracerr.Wrap(err)
  278. }
  279. c := &RollupClient{
  280. client: client,
  281. chainID: chainID,
  282. address: address,
  283. tokenHEZCfg: tokenHEZCfg,
  284. hermez: hermez,
  285. tokenHEZ: tokenHEZ,
  286. contractAbi: contractAbi,
  287. opts: newCallOpts(),
  288. }
  289. consts, err := c.RollupConstants()
  290. if err != nil {
  291. return nil, tracerr.Wrap(fmt.Errorf("RollupConstants at %v: %w", address, err))
  292. }
  293. c.consts = consts
  294. return c, nil
  295. }
  296. // RollupForgeBatch is the interface to call the smart contract function
  297. func (c *RollupClient) RollupForgeBatch(args *RollupForgeBatchArgs,
  298. auth *bind.TransactOpts) (tx *types.Transaction, err error) {
  299. if auth == nil {
  300. auth, err = c.client.NewAuth()
  301. if err != nil {
  302. return nil, tracerr.Wrap(err)
  303. }
  304. auth.GasLimit = 1000000
  305. }
  306. nLevels := c.consts.Verifiers[args.VerifierIdx].NLevels
  307. lenBytes := nLevels / 8 //nolint:gomnd
  308. newLastIdx := big.NewInt(int64(args.NewLastIdx))
  309. // L1CoordinatorBytes
  310. var l1CoordinatorBytes []byte
  311. for i := 0; i < len(args.L1CoordinatorTxs); i++ {
  312. l1 := args.L1CoordinatorTxs[i]
  313. bytesl1, err := l1.BytesCoordinatorTx(args.L1CoordinatorTxsAuths[i])
  314. if err != nil {
  315. return nil, tracerr.Wrap(err)
  316. }
  317. l1CoordinatorBytes = append(l1CoordinatorBytes, bytesl1[:]...)
  318. }
  319. // L1L2TxData
  320. var l1l2TxData []byte
  321. for i := 0; i < len(args.L1UserTxs); i++ {
  322. l1User := args.L1UserTxs[i]
  323. bytesl1User, err := l1User.BytesDataAvailability(uint32(nLevels))
  324. if err != nil {
  325. return nil, tracerr.Wrap(err)
  326. }
  327. l1l2TxData = append(l1l2TxData, bytesl1User[:]...)
  328. }
  329. for i := 0; i < len(args.L1CoordinatorTxs); i++ {
  330. l1Coord := args.L1CoordinatorTxs[i]
  331. bytesl1Coord, err := l1Coord.BytesDataAvailability(uint32(nLevels))
  332. if err != nil {
  333. return nil, tracerr.Wrap(err)
  334. }
  335. l1l2TxData = append(l1l2TxData, bytesl1Coord[:]...)
  336. }
  337. for i := 0; i < len(args.L2TxsData); i++ {
  338. l2 := args.L2TxsData[i]
  339. bytesl2, err := l2.BytesDataAvailability(uint32(nLevels))
  340. if err != nil {
  341. return nil, tracerr.Wrap(err)
  342. }
  343. l1l2TxData = append(l1l2TxData, bytesl2[:]...)
  344. }
  345. // FeeIdxCoordinator
  346. var feeIdxCoordinator []byte
  347. if len(args.FeeIdxCoordinator) > common.RollupConstMaxFeeIdxCoordinator {
  348. return nil, tracerr.Wrap(fmt.Errorf("len(args.FeeIdxCoordinator) > %v",
  349. common.RollupConstMaxFeeIdxCoordinator))
  350. }
  351. for i := 0; i < common.RollupConstMaxFeeIdxCoordinator; i++ {
  352. feeIdx := common.Idx(0)
  353. if i < len(args.FeeIdxCoordinator) {
  354. feeIdx = args.FeeIdxCoordinator[i]
  355. }
  356. bytesFeeIdx, err := feeIdx.Bytes()
  357. if err != nil {
  358. return nil, tracerr.Wrap(err)
  359. }
  360. feeIdxCoordinator = append(feeIdxCoordinator,
  361. bytesFeeIdx[len(bytesFeeIdx)-int(lenBytes):]...)
  362. }
  363. tx, err = c.hermez.ForgeBatch(auth, newLastIdx, args.NewStRoot, args.NewExitRoot,
  364. l1CoordinatorBytes, l1l2TxData, feeIdxCoordinator, args.VerifierIdx, args.L1Batch,
  365. args.ProofA, args.ProofB, args.ProofC)
  366. if err != nil {
  367. return nil, tracerr.Wrap(fmt.Errorf("Hermez.ForgeBatch: %w", err))
  368. }
  369. return tx, nil
  370. }
  371. // RollupAddToken is the interface to call the smart contract function.
  372. // `feeAddToken` is the amount of HEZ tokens that will be paid to add the
  373. // token. `feeAddToken` must match the public value of the smart contract.
  374. func (c *RollupClient) RollupAddToken(tokenAddress ethCommon.Address, feeAddToken,
  375. deadline *big.Int) (tx *types.Transaction, err error) {
  376. if tx, err = c.client.CallAuth(
  377. 0,
  378. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  379. owner := c.client.account.Address
  380. spender := c.address
  381. nonce, err := c.tokenHEZ.Nonces(c.opts, owner)
  382. if err != nil {
  383. return nil, tracerr.Wrap(err)
  384. }
  385. tokenName := c.tokenHEZCfg.Name
  386. tokenAddr := c.tokenHEZCfg.Address
  387. digest, _ := createPermitDigest(tokenAddr, owner, spender, c.chainID,
  388. feeAddToken, nonce, deadline, tokenName)
  389. signature, _ := c.client.ks.SignHash(*c.client.account, digest)
  390. permit := createPermit(owner, spender, feeAddToken, deadline, digest,
  391. signature)
  392. return c.hermez.AddToken(auth, tokenAddress, permit)
  393. },
  394. ); err != nil {
  395. return nil, tracerr.Wrap(fmt.Errorf("Failed add Token %w", err))
  396. }
  397. return tx, nil
  398. }
  399. // RollupWithdrawMerkleProof is the interface to call the smart contract function
  400. func (c *RollupClient) RollupWithdrawMerkleProof(fromBJJ babyjub.PublicKeyComp, tokenID uint32,
  401. numExitRoot, idx int64, amount *big.Int, siblings []*big.Int,
  402. instantWithdraw bool) (tx *types.Transaction, err error) {
  403. if tx, err = c.client.CallAuth(
  404. 0,
  405. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  406. pkCompB := common.SwapEndianness(fromBJJ[:])
  407. babyPubKey := new(big.Int).SetBytes(pkCompB)
  408. numExitRootB := uint32(numExitRoot)
  409. idxBig := big.NewInt(idx)
  410. return c.hermez.WithdrawMerkleProof(auth, tokenID, amount, babyPubKey,
  411. numExitRootB, siblings, idxBig, instantWithdraw)
  412. },
  413. ); err != nil {
  414. return nil, tracerr.Wrap(fmt.Errorf("Failed update WithdrawMerkleProof: %w", err))
  415. }
  416. return tx, nil
  417. }
  418. // RollupWithdrawCircuit is the interface to call the smart contract function
  419. func (c *RollupClient) RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]*big.Int,
  420. tokenID uint32, numExitRoot, idx int64, amount *big.Int, instantWithdraw bool) (*types.Transaction,
  421. error) {
  422. log.Error("TODO")
  423. return nil, tracerr.Wrap(errTODO)
  424. }
  425. // RollupL1UserTxERC20ETH is the interface to call the smart contract function
  426. func (c *RollupClient) RollupL1UserTxERC20ETH(fromBJJ babyjub.PublicKeyComp, fromIdx int64,
  427. depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (tx *types.Transaction,
  428. err error) {
  429. if tx, err = c.client.CallAuth(
  430. 0,
  431. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  432. var babyPubKey *big.Int
  433. if fromBJJ != common.EmptyBJJComp {
  434. pkCompB := common.SwapEndianness(fromBJJ[:])
  435. babyPubKey = new(big.Int).SetBytes(pkCompB)
  436. } else {
  437. babyPubKey = big.NewInt(0)
  438. }
  439. fromIdxBig := big.NewInt(fromIdx)
  440. toIdxBig := big.NewInt(toIdx)
  441. depositAmountF, err := common.NewFloat40(depositAmount)
  442. if err != nil {
  443. return nil, tracerr.Wrap(err)
  444. }
  445. amountF, err := common.NewFloat40(amount)
  446. if err != nil {
  447. return nil, tracerr.Wrap(err)
  448. }
  449. if tokenID == 0 {
  450. auth.Value = depositAmount
  451. }
  452. var permit []byte
  453. return c.hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig, big.NewInt(int64(depositAmountF)),
  454. big.NewInt(int64(amountF)), tokenID, toIdxBig, permit)
  455. },
  456. ); err != nil {
  457. return nil, tracerr.Wrap(fmt.Errorf("Failed add L1 Tx ERC20/ETH: %w", err))
  458. }
  459. return tx, nil
  460. }
  461. // RollupL1UserTxERC20Permit is the interface to call the smart contract function
  462. func (c *RollupClient) RollupL1UserTxERC20Permit(fromBJJ babyjub.PublicKeyComp, fromIdx int64,
  463. depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64,
  464. deadline *big.Int) (tx *types.Transaction, err error) {
  465. if tx, err = c.client.CallAuth(
  466. 0,
  467. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  468. var babyPubKey *big.Int
  469. if fromBJJ != common.EmptyBJJComp {
  470. pkCompB := common.SwapEndianness(fromBJJ[:])
  471. babyPubKey = new(big.Int).SetBytes(pkCompB)
  472. } else {
  473. babyPubKey = big.NewInt(0)
  474. }
  475. fromIdxBig := big.NewInt(fromIdx)
  476. toIdxBig := big.NewInt(toIdx)
  477. depositAmountF, err := common.NewFloat40(depositAmount)
  478. if err != nil {
  479. return nil, tracerr.Wrap(err)
  480. }
  481. amountF, err := common.NewFloat40(amount)
  482. if err != nil {
  483. return nil, tracerr.Wrap(err)
  484. }
  485. if tokenID == 0 {
  486. auth.Value = depositAmount
  487. }
  488. owner := c.client.account.Address
  489. spender := c.address
  490. nonce, err := c.tokenHEZ.Nonces(c.opts, owner)
  491. if err != nil {
  492. return nil, tracerr.Wrap(err)
  493. }
  494. tokenName := c.tokenHEZCfg.Name
  495. tokenAddr := c.tokenHEZCfg.Address
  496. digest, _ := createPermitDigest(tokenAddr, owner, spender, c.chainID,
  497. amount, nonce, deadline, tokenName)
  498. signature, _ := c.client.ks.SignHash(*c.client.account, digest)
  499. permit := createPermit(owner, spender, amount, deadline, digest, signature)
  500. return c.hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig,
  501. big.NewInt(int64(depositAmountF)), big.NewInt(int64(amountF)), tokenID, toIdxBig, permit)
  502. },
  503. ); err != nil {
  504. return nil, tracerr.Wrap(fmt.Errorf("Failed add L1 Tx ERC20Permit: %w", err))
  505. }
  506. return tx, nil
  507. }
  508. // RollupRegisterTokensCount is the interface to call the smart contract function
  509. func (c *RollupClient) RollupRegisterTokensCount() (registerTokensCount *big.Int, err error) {
  510. if err := c.client.Call(func(ec *ethclient.Client) error {
  511. registerTokensCount, err = c.hermez.RegisterTokensCount(c.opts)
  512. return tracerr.Wrap(err)
  513. }); err != nil {
  514. return nil, tracerr.Wrap(err)
  515. }
  516. return registerTokensCount, nil
  517. }
  518. // RollupLastForgedBatch is the interface to call the smart contract function
  519. func (c *RollupClient) RollupLastForgedBatch() (lastForgedBatch int64, err error) {
  520. if err := c.client.Call(func(ec *ethclient.Client) error {
  521. _lastForgedBatch, err := c.hermez.LastForgedBatch(c.opts)
  522. lastForgedBatch = int64(_lastForgedBatch)
  523. return tracerr.Wrap(err)
  524. }); err != nil {
  525. return 0, tracerr.Wrap(err)
  526. }
  527. return lastForgedBatch, nil
  528. }
  529. // RollupUpdateForgeL1L2BatchTimeout is the interface to call the smart contract function
  530. func (c *RollupClient) RollupUpdateForgeL1L2BatchTimeout(
  531. newForgeL1L2BatchTimeout int64) (tx *types.Transaction, err error) {
  532. if tx, err = c.client.CallAuth(
  533. 0,
  534. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  535. return c.hermez.UpdateForgeL1L2BatchTimeout(auth,
  536. uint8(newForgeL1L2BatchTimeout))
  537. },
  538. ); err != nil {
  539. return nil, tracerr.Wrap(fmt.Errorf("Failed update ForgeL1L2BatchTimeout: %w", err))
  540. }
  541. return tx, nil
  542. }
  543. // RollupUpdateFeeAddToken is the interface to call the smart contract function
  544. func (c *RollupClient) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (tx *types.Transaction,
  545. err error) {
  546. if tx, err = c.client.CallAuth(
  547. 0,
  548. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  549. return c.hermez.UpdateFeeAddToken(auth, newFeeAddToken)
  550. },
  551. ); err != nil {
  552. return nil, tracerr.Wrap(fmt.Errorf("Failed update FeeAddToken: %w", err))
  553. }
  554. return tx, nil
  555. }
  556. // RollupUpdateBucketsParameters is the interface to call the smart contract function
  557. func (c *RollupClient) RollupUpdateBucketsParameters(
  558. arrayBuckets []RollupUpdateBucketsParameters,
  559. ) (tx *types.Transaction, err error) {
  560. if tx, err = c.client.CallAuth(
  561. 12500000, //nolint:gomnd
  562. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  563. params := make([]*big.Int, len(arrayBuckets))
  564. for i, bucket := range arrayBuckets {
  565. params[i], err = c.hermez.PackBucket(c.opts,
  566. bucket.CeilUSD, bucket.BlockStamp, bucket.Withdrawals,
  567. bucket.RateBlocks, bucket.RateWithdrawals, bucket.MaxWithdrawals)
  568. if err != nil {
  569. return nil, tracerr.Wrap(fmt.Errorf("failed to pack bucket: %w", err))
  570. }
  571. }
  572. return c.hermez.UpdateBucketsParameters(auth, params)
  573. },
  574. ); err != nil {
  575. return nil, tracerr.Wrap(fmt.Errorf("Failed update Buckets Parameters: %w", err))
  576. }
  577. return tx, nil
  578. }
  579. // RollupUpdateTokenExchange is the interface to call the smart contract function
  580. func (c *RollupClient) RollupUpdateTokenExchange(addressArray []ethCommon.Address,
  581. valueArray []uint64) (tx *types.Transaction, err error) {
  582. if tx, err = c.client.CallAuth(
  583. 0,
  584. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  585. return c.hermez.UpdateTokenExchange(auth, addressArray, valueArray)
  586. },
  587. ); err != nil {
  588. return nil, tracerr.Wrap(fmt.Errorf("Failed update Token Exchange: %w", err))
  589. }
  590. return tx, nil
  591. }
  592. // RollupUpdateWithdrawalDelay is the interface to call the smart contract function
  593. func (c *RollupClient) RollupUpdateWithdrawalDelay(newWithdrawalDelay int64) (tx *types.Transaction,
  594. err error) {
  595. if tx, err = c.client.CallAuth(
  596. 0,
  597. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  598. return c.hermez.UpdateWithdrawalDelay(auth, uint64(newWithdrawalDelay))
  599. },
  600. ); err != nil {
  601. return nil, tracerr.Wrap(fmt.Errorf("Failed update WithdrawalDelay: %w", err))
  602. }
  603. return tx, nil
  604. }
  605. // RollupSafeMode is the interface to call the smart contract function
  606. func (c *RollupClient) RollupSafeMode() (tx *types.Transaction, err error) {
  607. if tx, err = c.client.CallAuth(
  608. 0,
  609. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  610. return c.hermez.SafeMode(auth)
  611. },
  612. ); err != nil {
  613. return nil, tracerr.Wrap(fmt.Errorf("Failed update Safe Mode: %w", err))
  614. }
  615. return tx, nil
  616. }
  617. // RollupInstantWithdrawalViewer is the interface to call the smart contract function
  618. func (c *RollupClient) RollupInstantWithdrawalViewer(tokenAddress ethCommon.Address,
  619. amount *big.Int) (instantAllowed bool, err error) {
  620. if err := c.client.Call(func(ec *ethclient.Client) error {
  621. instantAllowed, err = c.hermez.InstantWithdrawalViewer(c.opts, tokenAddress, amount)
  622. return tracerr.Wrap(err)
  623. }); err != nil {
  624. return false, tracerr.Wrap(err)
  625. }
  626. return instantAllowed, nil
  627. }
  628. // RollupConstants returns the Constants of the Rollup Smart Contract
  629. func (c *RollupClient) RollupConstants() (rollupConstants *common.RollupConstants, err error) {
  630. rollupConstants = new(common.RollupConstants)
  631. if err := c.client.Call(func(ec *ethclient.Client) error {
  632. absoluteMaxL1L2BatchTimeout, err := c.hermez.ABSOLUTEMAXL1L2BATCHTIMEOUT(c.opts)
  633. if err != nil {
  634. return tracerr.Wrap(err)
  635. }
  636. rollupConstants.AbsoluteMaxL1L2BatchTimeout = int64(absoluteMaxL1L2BatchTimeout)
  637. rollupConstants.TokenHEZ, err = c.hermez.TokenHEZ(c.opts)
  638. if err != nil {
  639. return tracerr.Wrap(err)
  640. }
  641. rollupVerifiersLength, err := c.hermez.RollupVerifiersLength(c.opts)
  642. if err != nil {
  643. return tracerr.Wrap(err)
  644. }
  645. for i := int64(0); i < rollupVerifiersLength.Int64(); i++ {
  646. var newRollupVerifier common.RollupVerifierStruct
  647. rollupVerifier, err := c.hermez.RollupVerifiers(c.opts, big.NewInt(i))
  648. if err != nil {
  649. return tracerr.Wrap(err)
  650. }
  651. newRollupVerifier.MaxTx = rollupVerifier.MaxTx.Int64()
  652. newRollupVerifier.NLevels = rollupVerifier.NLevels.Int64()
  653. rollupConstants.Verifiers = append(rollupConstants.Verifiers,
  654. newRollupVerifier)
  655. }
  656. rollupConstants.HermezAuctionContract, err = c.hermez.HermezAuctionContract(c.opts)
  657. if err != nil {
  658. return tracerr.Wrap(err)
  659. }
  660. rollupConstants.HermezGovernanceAddress, err = c.hermez.HermezGovernanceAddress(c.opts)
  661. if err != nil {
  662. return tracerr.Wrap(err)
  663. }
  664. rollupConstants.WithdrawDelayerContract, err = c.hermez.WithdrawDelayerContract(c.opts)
  665. return tracerr.Wrap(err)
  666. }); err != nil {
  667. return nil, tracerr.Wrap(err)
  668. }
  669. return rollupConstants, nil
  670. }
  671. var (
  672. logHermezL1UserTxEvent = crypto.Keccak256Hash([]byte(
  673. "L1UserTxEvent(uint32,uint8,bytes)"))
  674. logHermezAddToken = crypto.Keccak256Hash([]byte(
  675. "AddToken(address,uint32)"))
  676. logHermezForgeBatch = crypto.Keccak256Hash([]byte(
  677. "ForgeBatch(uint32,uint16)"))
  678. logHermezUpdateForgeL1L2BatchTimeout = crypto.Keccak256Hash([]byte(
  679. "UpdateForgeL1L2BatchTimeout(uint8)"))
  680. logHermezUpdateFeeAddToken = crypto.Keccak256Hash([]byte(
  681. "UpdateFeeAddToken(uint256)"))
  682. logHermezWithdrawEvent = crypto.Keccak256Hash([]byte(
  683. "WithdrawEvent(uint48,uint32,bool)"))
  684. logHermezUpdateBucketWithdraw = crypto.Keccak256Hash([]byte(
  685. "UpdateBucketWithdraw(uint8,uint256,uint256)"))
  686. logHermezUpdateWithdrawalDelay = crypto.Keccak256Hash([]byte(
  687. "UpdateWithdrawalDelay(uint64)"))
  688. logHermezUpdateBucketsParameters = crypto.Keccak256Hash([]byte(
  689. "UpdateBucketsParameters(uint256[])"))
  690. logHermezUpdateTokenExchange = crypto.Keccak256Hash([]byte(
  691. "UpdateTokenExchange(address[],uint64[])"))
  692. logHermezSafeMode = crypto.Keccak256Hash([]byte(
  693. "SafeMode()"))
  694. logHermezInitialize = crypto.Keccak256Hash([]byte(
  695. "InitializeHermezEvent(uint8,uint256,uint64)"))
  696. )
  697. // RollupEventInit returns the initialize event with its corresponding block number
  698. func (c *RollupClient) RollupEventInit() (*RollupEventInitialize, int64, error) {
  699. query := ethereum.FilterQuery{
  700. Addresses: []ethCommon.Address{
  701. c.address,
  702. },
  703. Topics: [][]ethCommon.Hash{{logHermezInitialize}},
  704. }
  705. logs, err := c.client.client.FilterLogs(context.Background(), query)
  706. if err != nil {
  707. return nil, 0, tracerr.Wrap(err)
  708. }
  709. if len(logs) != 1 {
  710. return nil, 0, tracerr.Wrap(fmt.Errorf("no event of type InitializeHermezEvent found"))
  711. }
  712. vLog := logs[0]
  713. if vLog.Topics[0] != logHermezInitialize {
  714. return nil, 0, tracerr.Wrap(fmt.Errorf("event is not InitializeHermezEvent"))
  715. }
  716. var rollupInit RollupEventInitialize
  717. if err := c.contractAbi.UnpackIntoInterface(&rollupInit, "InitializeHermezEvent",
  718. vLog.Data); err != nil {
  719. return nil, 0, tracerr.Wrap(err)
  720. }
  721. return &rollupInit, int64(vLog.BlockNumber), tracerr.Wrap(err)
  722. }
  723. // RollupEventsByBlock returns the events in a block that happened in the
  724. // Rollup Smart Contract.
  725. // To query by blockNum, set blockNum >= 0 and blockHash == nil.
  726. // To query by blockHash set blockHash != nil, and blockNum will be ignored.
  727. // If there are no events in that block the result is nil.
  728. func (c *RollupClient) RollupEventsByBlock(blockNum int64,
  729. blockHash *ethCommon.Hash) (*RollupEvents, error) {
  730. var rollupEvents RollupEvents
  731. var blockNumBigInt *big.Int
  732. if blockHash == nil {
  733. blockNumBigInt = big.NewInt(blockNum)
  734. }
  735. query := ethereum.FilterQuery{
  736. BlockHash: blockHash,
  737. FromBlock: blockNumBigInt,
  738. ToBlock: blockNumBigInt,
  739. Addresses: []ethCommon.Address{
  740. c.address,
  741. },
  742. Topics: [][]ethCommon.Hash{},
  743. }
  744. logs, err := c.client.client.FilterLogs(context.Background(), query)
  745. if err != nil {
  746. return nil, tracerr.Wrap(err)
  747. }
  748. if len(logs) == 0 {
  749. return nil, nil
  750. }
  751. for _, vLog := range logs {
  752. if blockHash != nil && vLog.BlockHash != *blockHash {
  753. log.Errorw("Block hash mismatch", "expected", blockHash.String(), "got", vLog.BlockHash.String())
  754. return nil, tracerr.Wrap(ErrBlockHashMismatchEvent)
  755. }
  756. switch vLog.Topics[0] {
  757. case logHermezL1UserTxEvent:
  758. var L1UserTxAux rollupEventL1UserTxAux
  759. var L1UserTx RollupEventL1UserTx
  760. err := c.contractAbi.UnpackIntoInterface(&L1UserTxAux, "L1UserTxEvent", vLog.Data)
  761. if err != nil {
  762. return nil, tracerr.Wrap(err)
  763. }
  764. L1Tx, err := common.L1UserTxFromBytes(L1UserTxAux.L1UserTx)
  765. if err != nil {
  766. return nil, tracerr.Wrap(err)
  767. }
  768. toForgeL1TxsNum := new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
  769. L1Tx.ToForgeL1TxsNum = &toForgeL1TxsNum
  770. L1Tx.Position = int(new(big.Int).SetBytes(vLog.Topics[2][:]).Int64())
  771. L1Tx.UserOrigin = true
  772. L1UserTx.L1UserTx = *L1Tx
  773. rollupEvents.L1UserTx = append(rollupEvents.L1UserTx, L1UserTx)
  774. case logHermezAddToken:
  775. var addToken RollupEventAddToken
  776. err := c.contractAbi.UnpackIntoInterface(&addToken, "AddToken", vLog.Data)
  777. if err != nil {
  778. return nil, tracerr.Wrap(err)
  779. }
  780. addToken.TokenAddress = ethCommon.BytesToAddress(vLog.Topics[1].Bytes())
  781. rollupEvents.AddToken = append(rollupEvents.AddToken, addToken)
  782. case logHermezForgeBatch:
  783. var forgeBatch RollupEventForgeBatch
  784. err := c.contractAbi.UnpackIntoInterface(&forgeBatch, "ForgeBatch", vLog.Data)
  785. if err != nil {
  786. return nil, tracerr.Wrap(err)
  787. }
  788. forgeBatch.BatchNum = new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
  789. forgeBatch.EthTxHash = vLog.TxHash
  790. // forgeBatch.Sender = vLog.Address
  791. rollupEvents.ForgeBatch = append(rollupEvents.ForgeBatch, forgeBatch)
  792. case logHermezUpdateForgeL1L2BatchTimeout:
  793. var updateForgeL1L2BatchTimeout struct {
  794. NewForgeL1L2BatchTimeout uint8
  795. }
  796. err := c.contractAbi.UnpackIntoInterface(&updateForgeL1L2BatchTimeout,
  797. "UpdateForgeL1L2BatchTimeout", vLog.Data)
  798. if err != nil {
  799. return nil, tracerr.Wrap(err)
  800. }
  801. rollupEvents.UpdateForgeL1L2BatchTimeout = append(rollupEvents.UpdateForgeL1L2BatchTimeout,
  802. RollupEventUpdateForgeL1L2BatchTimeout{
  803. NewForgeL1L2BatchTimeout: int64(updateForgeL1L2BatchTimeout.NewForgeL1L2BatchTimeout),
  804. })
  805. case logHermezUpdateFeeAddToken:
  806. var updateFeeAddToken RollupEventUpdateFeeAddToken
  807. err := c.contractAbi.UnpackIntoInterface(&updateFeeAddToken, "UpdateFeeAddToken", vLog.Data)
  808. if err != nil {
  809. return nil, tracerr.Wrap(err)
  810. }
  811. rollupEvents.UpdateFeeAddToken = append(rollupEvents.UpdateFeeAddToken, updateFeeAddToken)
  812. case logHermezWithdrawEvent:
  813. var withdraw RollupEventWithdraw
  814. withdraw.Idx = new(big.Int).SetBytes(vLog.Topics[1][:]).Uint64()
  815. withdraw.NumExitRoot = new(big.Int).SetBytes(vLog.Topics[2][:]).Uint64()
  816. instantWithdraw := new(big.Int).SetBytes(vLog.Topics[3][:]).Uint64()
  817. if instantWithdraw == 1 {
  818. withdraw.InstantWithdraw = true
  819. }
  820. withdraw.TxHash = vLog.TxHash
  821. rollupEvents.Withdraw = append(rollupEvents.Withdraw, withdraw)
  822. case logHermezUpdateBucketWithdraw:
  823. var updateBucketWithdrawAux rollupEventUpdateBucketWithdrawAux
  824. var updateBucketWithdraw RollupEventUpdateBucketWithdraw
  825. err := c.contractAbi.UnpackIntoInterface(&updateBucketWithdrawAux,
  826. "UpdateBucketWithdraw", vLog.Data)
  827. if err != nil {
  828. return nil, tracerr.Wrap(err)
  829. }
  830. updateBucketWithdraw.Withdrawals = updateBucketWithdrawAux.Withdrawals
  831. updateBucketWithdraw.NumBucket = int(new(big.Int).SetBytes(vLog.Topics[1][:]).Int64())
  832. updateBucketWithdraw.BlockStamp = new(big.Int).SetBytes(vLog.Topics[2][:]).Int64()
  833. rollupEvents.UpdateBucketWithdraw =
  834. append(rollupEvents.UpdateBucketWithdraw, updateBucketWithdraw)
  835. case logHermezUpdateWithdrawalDelay:
  836. var withdrawalDelay RollupEventUpdateWithdrawalDelay
  837. err := c.contractAbi.UnpackIntoInterface(&withdrawalDelay, "UpdateWithdrawalDelay", vLog.Data)
  838. if err != nil {
  839. return nil, tracerr.Wrap(err)
  840. }
  841. rollupEvents.UpdateWithdrawalDelay = append(rollupEvents.UpdateWithdrawalDelay, withdrawalDelay)
  842. case logHermezUpdateBucketsParameters:
  843. var bucketsParametersAux rollupEventUpdateBucketsParametersAux
  844. var bucketsParameters RollupEventUpdateBucketsParameters
  845. err := c.contractAbi.UnpackIntoInterface(&bucketsParametersAux,
  846. "UpdateBucketsParameters", vLog.Data)
  847. if err != nil {
  848. return nil, tracerr.Wrap(err)
  849. }
  850. bucketsParameters.ArrayBuckets = make([]RollupUpdateBucketsParameters, len(bucketsParametersAux.ArrayBuckets))
  851. for i, bucket := range bucketsParametersAux.ArrayBuckets {
  852. bucket, err := c.hermez.UnpackBucket(c.opts, bucket)
  853. if err != nil {
  854. return nil, tracerr.Wrap(err)
  855. }
  856. bucketsParameters.ArrayBuckets[i].CeilUSD = bucket.CeilUSD
  857. bucketsParameters.ArrayBuckets[i].BlockStamp = bucket.BlockStamp
  858. bucketsParameters.ArrayBuckets[i].Withdrawals = bucket.Withdrawals
  859. bucketsParameters.ArrayBuckets[i].RateBlocks = bucket.RateBlocks
  860. bucketsParameters.ArrayBuckets[i].RateWithdrawals = bucket.RateWithdrawals
  861. bucketsParameters.ArrayBuckets[i].MaxWithdrawals = bucket.MaxWithdrawals
  862. }
  863. rollupEvents.UpdateBucketsParameters =
  864. append(rollupEvents.UpdateBucketsParameters, bucketsParameters)
  865. case logHermezUpdateTokenExchange:
  866. var tokensExchange RollupEventUpdateTokenExchange
  867. err := c.contractAbi.UnpackIntoInterface(&tokensExchange, "UpdateTokenExchange", vLog.Data)
  868. if err != nil {
  869. return nil, tracerr.Wrap(err)
  870. }
  871. rollupEvents.UpdateTokenExchange = append(rollupEvents.UpdateTokenExchange, tokensExchange)
  872. case logHermezSafeMode:
  873. var safeMode RollupEventSafeMode
  874. rollupEvents.SafeMode = append(rollupEvents.SafeMode, safeMode)
  875. // Also add an UpdateBucketsParameter with
  876. // SafeMode=true to keep the order between `safeMode`
  877. // and `UpdateBucketsParameters`
  878. bucketsParameters := RollupEventUpdateBucketsParameters{
  879. SafeMode: true,
  880. }
  881. for i := range bucketsParameters.ArrayBuckets {
  882. bucketsParameters.ArrayBuckets[i].CeilUSD = big.NewInt(0)
  883. bucketsParameters.ArrayBuckets[i].BlockStamp = big.NewInt(0)
  884. bucketsParameters.ArrayBuckets[i].Withdrawals = big.NewInt(0)
  885. bucketsParameters.ArrayBuckets[i].RateBlocks = big.NewInt(0)
  886. bucketsParameters.ArrayBuckets[i].RateWithdrawals = big.NewInt(0)
  887. bucketsParameters.ArrayBuckets[i].MaxWithdrawals = big.NewInt(0)
  888. }
  889. rollupEvents.UpdateBucketsParameters = append(rollupEvents.UpdateBucketsParameters,
  890. bucketsParameters)
  891. }
  892. }
  893. return &rollupEvents, nil
  894. }
  895. // RollupForgeBatchArgs returns the arguments used in a ForgeBatch call in the
  896. // Rollup Smart Contract in the given transaction, and the sender address.
  897. func (c *RollupClient) RollupForgeBatchArgs(ethTxHash ethCommon.Hash,
  898. l1UserTxsLen uint16) (*RollupForgeBatchArgs, *ethCommon.Address, error) {
  899. tx, _, err := c.client.client.TransactionByHash(context.Background(), ethTxHash)
  900. if err != nil {
  901. return nil, nil, tracerr.Wrap(fmt.Errorf("TransactionByHash: %w", err))
  902. }
  903. txData := tx.Data()
  904. method, err := c.contractAbi.MethodById(txData[:4])
  905. if err != nil {
  906. return nil, nil, tracerr.Wrap(err)
  907. }
  908. receipt, err := c.client.client.TransactionReceipt(context.Background(), ethTxHash)
  909. if err != nil {
  910. return nil, nil, tracerr.Wrap(err)
  911. }
  912. sender, err := c.client.client.TransactionSender(context.Background(), tx,
  913. receipt.Logs[0].BlockHash, receipt.Logs[0].Index)
  914. if err != nil {
  915. return nil, nil, tracerr.Wrap(err)
  916. }
  917. var aux rollupForgeBatchArgsAux
  918. if values, err := method.Inputs.Unpack(txData[4:]); err != nil {
  919. return nil, nil, tracerr.Wrap(err)
  920. } else if err := method.Inputs.Copy(&aux, values); err != nil {
  921. return nil, nil, tracerr.Wrap(err)
  922. }
  923. rollupForgeBatchArgs := RollupForgeBatchArgs{
  924. L1Batch: aux.L1Batch,
  925. NewExitRoot: aux.NewExitRoot,
  926. NewLastIdx: aux.NewLastIdx.Int64(),
  927. NewStRoot: aux.NewStRoot,
  928. ProofA: aux.ProofA,
  929. ProofB: aux.ProofB,
  930. ProofC: aux.ProofC,
  931. VerifierIdx: aux.VerifierIdx,
  932. L1CoordinatorTxs: []common.L1Tx{},
  933. L1CoordinatorTxsAuths: [][]byte{},
  934. L2TxsData: []common.L2Tx{},
  935. FeeIdxCoordinator: []common.Idx{},
  936. }
  937. nLevels := c.consts.Verifiers[rollupForgeBatchArgs.VerifierIdx].NLevels
  938. lenL1L2TxsBytes := int((nLevels/8)*2 + common.Float40BytesLength + 1) //nolint:gomnd
  939. numBytesL1TxUser := int(l1UserTxsLen) * lenL1L2TxsBytes
  940. numTxsL1Coord := len(aux.EncodedL1CoordinatorTx) / common.RollupConstL1CoordinatorTotalBytes
  941. numBytesL1TxCoord := numTxsL1Coord * lenL1L2TxsBytes
  942. numBeginL2Tx := numBytesL1TxCoord + numBytesL1TxUser
  943. l1UserTxsData := []byte{}
  944. if l1UserTxsLen > 0 {
  945. l1UserTxsData = aux.L1L2TxsData[:numBytesL1TxUser]
  946. }
  947. for i := 0; i < int(l1UserTxsLen); i++ {
  948. l1Tx, err :=
  949. common.L1TxFromDataAvailability(l1UserTxsData[i*lenL1L2TxsBytes:(i+1)*lenL1L2TxsBytes],
  950. uint32(nLevels))
  951. if err != nil {
  952. return nil, nil, tracerr.Wrap(err)
  953. }
  954. rollupForgeBatchArgs.L1UserTxs = append(rollupForgeBatchArgs.L1UserTxs, *l1Tx)
  955. }
  956. l2TxsData := []byte{}
  957. if numBeginL2Tx < len(aux.L1L2TxsData) {
  958. l2TxsData = aux.L1L2TxsData[numBeginL2Tx:]
  959. }
  960. numTxsL2 := len(l2TxsData) / lenL1L2TxsBytes
  961. for i := 0; i < numTxsL2; i++ {
  962. l2Tx, err :=
  963. common.L2TxFromBytesDataAvailability(l2TxsData[i*lenL1L2TxsBytes:(i+1)*lenL1L2TxsBytes],
  964. int(nLevels))
  965. if err != nil {
  966. return nil, nil, tracerr.Wrap(err)
  967. }
  968. rollupForgeBatchArgs.L2TxsData = append(rollupForgeBatchArgs.L2TxsData, *l2Tx)
  969. }
  970. for i := 0; i < numTxsL1Coord; i++ {
  971. bytesL1Coordinator :=
  972. aux.EncodedL1CoordinatorTx[i*common.RollupConstL1CoordinatorTotalBytes : (i+1)*common.RollupConstL1CoordinatorTotalBytes] //nolint:lll
  973. var signature []byte
  974. v := bytesL1Coordinator[0]
  975. s := bytesL1Coordinator[1:33]
  976. r := bytesL1Coordinator[33:65]
  977. signature = append(signature, r[:]...)
  978. signature = append(signature, s[:]...)
  979. signature = append(signature, v)
  980. l1Tx, err := common.L1CoordinatorTxFromBytes(bytesL1Coordinator, c.chainID, c.address)
  981. if err != nil {
  982. return nil, nil, tracerr.Wrap(err)
  983. }
  984. rollupForgeBatchArgs.L1CoordinatorTxs = append(rollupForgeBatchArgs.L1CoordinatorTxs, *l1Tx)
  985. rollupForgeBatchArgs.L1CoordinatorTxsAuths =
  986. append(rollupForgeBatchArgs.L1CoordinatorTxsAuths, signature)
  987. }
  988. lenFeeIdxCoordinatorBytes := int(nLevels / 8) //nolint:gomnd
  989. numFeeIdxCoordinator := len(aux.FeeIdxCoordinator) / lenFeeIdxCoordinatorBytes
  990. for i := 0; i < numFeeIdxCoordinator; i++ {
  991. var paddedFeeIdx [6]byte
  992. // TODO: This check is not necessary: the first case will always work. Test it
  993. // before removing the if.
  994. if lenFeeIdxCoordinatorBytes < common.IdxBytesLen {
  995. copy(paddedFeeIdx[6-lenFeeIdxCoordinatorBytes:],
  996. aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
  997. } else {
  998. copy(paddedFeeIdx[:],
  999. aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
  1000. }
  1001. feeIdxCoordinator, err := common.IdxFromBytes(paddedFeeIdx[:])
  1002. if err != nil {
  1003. return nil, nil, tracerr.Wrap(err)
  1004. }
  1005. if feeIdxCoordinator != common.Idx(0) {
  1006. rollupForgeBatchArgs.FeeIdxCoordinator =
  1007. append(rollupForgeBatchArgs.FeeIdxCoordinator, feeIdxCoordinator)
  1008. }
  1009. }
  1010. return &rollupForgeBatchArgs, &sender, nil
  1011. }