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.

1768 lines
54 KiB

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.
3 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.
3 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.
3 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.
3 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.
3 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.
3 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.
3 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.
3 years ago
  1. package test
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "encoding/json"
  6. "fmt"
  7. "math/big"
  8. "reflect"
  9. "sync"
  10. "time"
  11. "github.com/ethereum/go-ethereum"
  12. ethCommon "github.com/ethereum/go-ethereum/common"
  13. "github.com/ethereum/go-ethereum/core/types"
  14. "github.com/hermeznetwork/hermez-node/common"
  15. "github.com/hermeznetwork/hermez-node/eth"
  16. "github.com/hermeznetwork/hermez-node/log"
  17. "github.com/hermeznetwork/tracerr"
  18. "github.com/iden3/go-iden3-crypto/babyjub"
  19. "github.com/mitchellh/copystructure"
  20. )
  21. func init() {
  22. copystructure.Copiers[reflect.TypeOf(big.Int{})] =
  23. func(raw interface{}) (interface{}, error) {
  24. in := raw.(big.Int)
  25. out := new(big.Int).Set(&in)
  26. return *out, nil
  27. }
  28. }
  29. // WDelayerBlock stores all the data related to the WDelayer SC from an ethereum block
  30. type WDelayerBlock struct {
  31. // State eth.WDelayerState // TODO
  32. Vars common.WDelayerVariables
  33. Events eth.WDelayerEvents
  34. Txs map[ethCommon.Hash]*types.Transaction
  35. Constants *common.WDelayerConstants
  36. Eth *EthereumBlock
  37. }
  38. func (w *WDelayerBlock) addTransaction(tx *types.Transaction) *types.Transaction {
  39. txHash := tx.Hash()
  40. w.Txs[txHash] = tx
  41. return tx
  42. }
  43. func (w *WDelayerBlock) deposit(txHash ethCommon.Hash, owner, token ethCommon.Address, amount *big.Int) {
  44. w.Events.Deposit = append(w.Events.Deposit, eth.WDelayerEventDeposit{
  45. Owner: owner,
  46. Token: token,
  47. Amount: amount,
  48. DepositTimestamp: uint64(w.Eth.Time),
  49. TxHash: txHash,
  50. })
  51. }
  52. // RollupBlock stores all the data related to the Rollup SC from an ethereum block
  53. type RollupBlock struct {
  54. State eth.RollupState
  55. Vars common.RollupVariables
  56. Events eth.RollupEvents
  57. Txs map[ethCommon.Hash]*types.Transaction
  58. Constants *common.RollupConstants
  59. Eth *EthereumBlock
  60. }
  61. func (r *RollupBlock) addTransaction(tx *types.Transaction) *types.Transaction {
  62. txHash := tx.Hash()
  63. r.Txs[txHash] = tx
  64. return tx
  65. }
  66. var (
  67. errBidClosed = fmt.Errorf("Bid has already been closed")
  68. errBidNotOpen = fmt.Errorf("Bid has not been opened yet")
  69. errBidBelowMin = fmt.Errorf("Bid below minimum")
  70. errCoordNotReg = fmt.Errorf("Coordinator not registered")
  71. )
  72. // AuctionBlock stores all the data related to the Auction SC from an ethereum block
  73. type AuctionBlock struct {
  74. State eth.AuctionState
  75. Vars common.AuctionVariables
  76. Events eth.AuctionEvents
  77. Txs map[ethCommon.Hash]*types.Transaction
  78. Constants *common.AuctionConstants
  79. Eth *EthereumBlock
  80. }
  81. func (a *AuctionBlock) addTransaction(tx *types.Transaction) *types.Transaction {
  82. txHash := tx.Hash()
  83. a.Txs[txHash] = tx
  84. return tx
  85. }
  86. func (a *AuctionBlock) getSlotNumber(blockNumber int64) int64 {
  87. if a.Eth.BlockNum >= a.Constants.GenesisBlockNum {
  88. return (blockNumber - a.Constants.GenesisBlockNum) / int64(a.Constants.BlocksPerSlot)
  89. }
  90. return 0
  91. }
  92. func (a *AuctionBlock) getCurrentSlotNumber() int64 {
  93. return a.getSlotNumber(a.Eth.BlockNum)
  94. }
  95. func (a *AuctionBlock) getSlotSet(slot int64) int64 {
  96. return slot % int64(len(a.Vars.DefaultSlotSetBid))
  97. }
  98. func (a *AuctionBlock) getMinBidBySlot(slot int64) (*big.Int, error) {
  99. if slot < a.getCurrentSlotNumber()+int64(a.Vars.ClosedAuctionSlots) {
  100. return nil, tracerr.Wrap(errBidClosed)
  101. }
  102. slotSet := a.getSlotSet(slot)
  103. // fmt.Println("slot:", slot, "slotSet:", slotSet)
  104. var prevBid *big.Int
  105. slotState, ok := a.State.Slots[slot]
  106. if !ok {
  107. slotState = eth.NewSlotState()
  108. a.State.Slots[slot] = slotState
  109. }
  110. // If the bidAmount for a slot is 0 it means that it has not yet been
  111. // bid, so the midBid will be the minimum bid for the slot time plus
  112. // the outbidding set, otherwise it will be the bidAmount plus the
  113. // outbidding
  114. if slotState.BidAmount.Cmp(big.NewInt(0)) == 0 {
  115. prevBid = a.Vars.DefaultSlotSetBid[slotSet]
  116. } else {
  117. prevBid = slotState.BidAmount
  118. }
  119. outBid := new(big.Int).Set(prevBid)
  120. // fmt.Println("outBid:", outBid)
  121. outBid.Mul(outBid, big.NewInt(int64(a.Vars.Outbidding)))
  122. outBid.Div(outBid, big.NewInt(10000)) //nolint:gomnd
  123. outBid.Add(prevBid, outBid)
  124. // fmt.Println("minBid:", outBid)
  125. return outBid, nil
  126. }
  127. func (a *AuctionBlock) forge(forger ethCommon.Address) error {
  128. if ok, err := a.canForge(forger, a.Eth.BlockNum); err != nil {
  129. return tracerr.Wrap(err)
  130. } else if !ok {
  131. return tracerr.Wrap(fmt.Errorf("Can't forge"))
  132. }
  133. slotToForge := a.getSlotNumber(a.Eth.BlockNum)
  134. slotState, ok := a.State.Slots[slotToForge]
  135. if !ok {
  136. slotState = eth.NewSlotState()
  137. a.State.Slots[slotToForge] = slotState
  138. }
  139. if !slotState.ForgerCommitment {
  140. // Get the relativeBlock to check if the slotDeadline has been exceeded
  141. relativeBlock := a.Eth.BlockNum - (a.Constants.GenesisBlockNum +
  142. (slotToForge * int64(a.Constants.BlocksPerSlot)))
  143. if relativeBlock < int64(a.Vars.SlotDeadline) {
  144. slotState.ForgerCommitment = true
  145. }
  146. }
  147. slotState.Fulfilled = true
  148. a.Events.NewForge = append(a.Events.NewForge, eth.AuctionEventNewForge{
  149. Forger: forger,
  150. SlotToForge: slotToForge,
  151. })
  152. return nil
  153. }
  154. func (a *AuctionBlock) canForge(forger ethCommon.Address, blockNum int64) (bool, error) {
  155. if blockNum < a.Constants.GenesisBlockNum {
  156. return false, tracerr.Wrap(fmt.Errorf("Auction has not started yet"))
  157. }
  158. slotToForge := a.getSlotNumber(blockNum)
  159. // fmt.Printf("DBG canForge slot: %v\n", slotToForge)
  160. // Get the relativeBlock to check if the slotDeadline has been exceeded
  161. relativeBlock := blockNum - (a.Constants.GenesisBlockNum + (slotToForge * int64(a.Constants.BlocksPerSlot)))
  162. // If the closedMinBid is 0 it means that we have to take as minBid the
  163. // one that is set for this slot set, otherwise the one that has been
  164. // saved will be used
  165. var minBid *big.Int
  166. slotState, ok := a.State.Slots[slotToForge]
  167. if !ok {
  168. slotState = eth.NewSlotState()
  169. a.State.Slots[slotToForge] = slotState
  170. }
  171. if slotState.ClosedMinBid.Cmp(big.NewInt(0)) == 0 {
  172. minBid = a.Vars.DefaultSlotSetBid[a.getSlotSet(slotToForge)]
  173. } else {
  174. minBid = slotState.ClosedMinBid
  175. }
  176. if !slotState.ForgerCommitment && (relativeBlock >= int64(a.Vars.SlotDeadline)) {
  177. // if the relative block has exceeded the slotDeadline and no
  178. // batch has been forged, anyone can forge
  179. return true, nil
  180. } else if coord, ok := a.State.Coordinators[slotState.Bidder]; ok &&
  181. coord.Forger == forger && slotState.BidAmount.Cmp(minBid) >= 0 {
  182. // if forger bidAmount has exceeded the minBid it can forge
  183. return true, nil
  184. } else if a.Vars.BootCoordinator == forger && slotState.BidAmount.Cmp(minBid) == -1 {
  185. // if it's the boot coordinator and it has not been bid or the
  186. // bid is below the minimum it can forge
  187. return true, nil
  188. } else {
  189. return false, nil
  190. }
  191. }
  192. // EthereumBlock stores all the generic data related to the an ethereum block
  193. type EthereumBlock struct {
  194. BlockNum int64
  195. Time int64
  196. Hash ethCommon.Hash
  197. ParentHash ethCommon.Hash
  198. Tokens map[ethCommon.Address]eth.ERC20Consts
  199. Nonce uint64
  200. // state ethState
  201. }
  202. // Block represents a ethereum block
  203. type Block struct {
  204. Rollup *RollupBlock
  205. Auction *AuctionBlock
  206. WDelayer *WDelayerBlock
  207. Eth *EthereumBlock
  208. }
  209. func (b *Block) copy() *Block {
  210. bCopyRaw, err := copystructure.Copy(b)
  211. if err != nil {
  212. panic(err)
  213. }
  214. bCopy := bCopyRaw.(*Block)
  215. return bCopy
  216. }
  217. // Next prepares the successive block.
  218. func (b *Block) Next() *Block {
  219. blockNext := b.copy()
  220. blockNext.Rollup.Events = eth.NewRollupEvents()
  221. blockNext.Auction.Events = eth.NewAuctionEvents()
  222. blockNext.Eth.BlockNum = b.Eth.BlockNum + 1
  223. blockNext.Eth.ParentHash = b.Eth.Hash
  224. blockNext.Rollup.Constants = b.Rollup.Constants
  225. blockNext.Auction.Constants = b.Auction.Constants
  226. blockNext.WDelayer.Constants = b.WDelayer.Constants
  227. blockNext.Rollup.Eth = blockNext.Eth
  228. blockNext.Auction.Eth = blockNext.Eth
  229. blockNext.WDelayer.Eth = blockNext.Eth
  230. return blockNext
  231. }
  232. // ClientSetup is used to initialize the constants of the Smart Contracts and
  233. // other details of the test Client
  234. type ClientSetup struct {
  235. RollupConstants *common.RollupConstants
  236. RollupVariables *common.RollupVariables
  237. AuctionConstants *common.AuctionConstants
  238. AuctionVariables *common.AuctionVariables
  239. WDelayerConstants *common.WDelayerConstants
  240. WDelayerVariables *common.WDelayerVariables
  241. VerifyProof bool
  242. }
  243. // NewClientSetupExample returns a ClientSetup example with hardcoded realistic
  244. // values. With this setup, the rollup genesis will be block 1, and block 0
  245. // and 1 will be premined.
  246. //nolint:gomnd
  247. func NewClientSetupExample() *ClientSetup {
  248. // rfield, ok := new(big.Int).SetString("21888242871839275222246405745257275088548364400416034343698204186575808495617", 10)
  249. // if !ok {
  250. // panic("bad rfield")
  251. // }
  252. initialMinimalBidding, ok := new(big.Int).SetString("10000000000000000000", 10) // 10 * (1e18)
  253. if !ok {
  254. panic("bad initialMinimalBidding")
  255. }
  256. tokenHEZ := ethCommon.HexToAddress("0x51D243D62852Bba334DD5cc33f242BAc8c698074")
  257. governanceAddress := ethCommon.HexToAddress("0x688EfD95BA4391f93717CF02A9aED9DBD2855cDd")
  258. rollupConstants := &common.RollupConstants{
  259. Verifiers: []common.RollupVerifierStruct{
  260. {
  261. MaxTx: 2048,
  262. NLevels: 32,
  263. },
  264. },
  265. TokenHEZ: tokenHEZ,
  266. HermezGovernanceAddress: governanceAddress,
  267. HermezAuctionContract: ethCommon.HexToAddress("0x8E442975805fb1908f43050c9C1A522cB0e28D7b"),
  268. WithdrawDelayerContract: ethCommon.HexToAddress("0x5CB7979cBdbf65719BEE92e4D15b7b7Ed3D79114"),
  269. }
  270. rollupVariables := &common.RollupVariables{
  271. FeeAddToken: big.NewInt(11),
  272. ForgeL1L2BatchTimeout: 9,
  273. WithdrawalDelay: 80,
  274. }
  275. auctionConstants := &common.AuctionConstants{
  276. BlocksPerSlot: 40,
  277. InitialMinimalBidding: initialMinimalBidding,
  278. GenesisBlockNum: 1,
  279. GovernanceAddress: governanceAddress,
  280. TokenHEZ: tokenHEZ,
  281. HermezRollup: ethCommon.HexToAddress("0x474B6e29852257491cf283EfB1A9C61eBFe48369"),
  282. }
  283. auctionVariables := &common.AuctionVariables{
  284. DonationAddress: ethCommon.HexToAddress("0x61Ed87CF0A1496b49A420DA6D84B58196b98f2e7"),
  285. BootCoordinator: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  286. BootCoordinatorURL: "https://boot.coordinator.com",
  287. DefaultSlotSetBid: [6]*big.Int{
  288. big.NewInt(1000), big.NewInt(1100), big.NewInt(1200),
  289. big.NewInt(1300), big.NewInt(1400), big.NewInt(1500)},
  290. ClosedAuctionSlots: 2,
  291. OpenAuctionSlots: 4320,
  292. AllocationRatio: [3]uint16{4000, 4000, 2000},
  293. Outbidding: 1000,
  294. SlotDeadline: 20,
  295. }
  296. wDelayerConstants := &common.WDelayerConstants{
  297. MaxWithdrawalDelay: 60 * 60 * 24 * 7 * 2, // 2 weeks
  298. MaxEmergencyModeTime: 60 * 60 * 24 * 7 * 26, // 26 weeks
  299. HermezRollup: auctionConstants.HermezRollup,
  300. }
  301. wDelayerVariables := &common.WDelayerVariables{
  302. HermezGovernanceAddress: ethCommon.HexToAddress("0xcfD0d163AE6432a72682323E2C3A5a69e6B37D12"),
  303. EmergencyCouncilAddress: ethCommon.HexToAddress("0x2730700932a4FDB97B9268A3Ca29f97Ea5fd7EA0"),
  304. WithdrawalDelay: 60,
  305. EmergencyModeStartingBlock: 0,
  306. EmergencyMode: false,
  307. }
  308. return &ClientSetup{
  309. RollupConstants: rollupConstants,
  310. RollupVariables: rollupVariables,
  311. AuctionConstants: auctionConstants,
  312. AuctionVariables: auctionVariables,
  313. WDelayerConstants: wDelayerConstants,
  314. WDelayerVariables: wDelayerVariables,
  315. }
  316. }
  317. // Timer is an interface to simulate a source of time, useful to advance time
  318. // virtually.
  319. type Timer interface {
  320. Time() int64
  321. }
  322. // type forgeBatchArgs struct {
  323. // ethTx *types.Transaction
  324. // blockNum int64
  325. // blockHash ethCommon.Hash
  326. // }
  327. type batch struct {
  328. ForgeBatchArgs eth.RollupForgeBatchArgs
  329. Sender ethCommon.Address
  330. }
  331. // Client implements the eth.ClientInterface interface, allowing to manipulate the
  332. // values for testing, working with deterministic results.
  333. type Client struct {
  334. rw *sync.RWMutex
  335. log bool
  336. addr *ethCommon.Address
  337. rollupConstants *common.RollupConstants
  338. auctionConstants *common.AuctionConstants
  339. wDelayerConstants *common.WDelayerConstants
  340. blocks map[int64]*Block
  341. // state state
  342. blockNum int64 // last mined block num
  343. maxBlockNum int64 // highest block num calculated
  344. timer Timer
  345. hasher hasher
  346. forgeBatchArgsPending map[ethCommon.Hash]*batch
  347. forgeBatchArgs map[ethCommon.Hash]*batch
  348. }
  349. // NewClient returns a new test Client that implements the eth.IClient
  350. // interface, at the given initialBlockNumber.
  351. func NewClient(l bool, timer Timer, addr *ethCommon.Address, setup *ClientSetup) *Client {
  352. blocks := make(map[int64]*Block)
  353. blockNum := int64(0)
  354. hasher := hasher{}
  355. // Add ethereum genesis block
  356. mapL1TxQueue := make(map[int64]*eth.QueueStruct)
  357. mapL1TxQueue[0] = eth.NewQueueStruct()
  358. mapL1TxQueue[1] = eth.NewQueueStruct()
  359. blockCurrent := &Block{
  360. Rollup: &RollupBlock{
  361. State: eth.RollupState{
  362. StateRoot: big.NewInt(0),
  363. ExitRoots: make([]*big.Int, 1),
  364. ExitNullifierMap: make(map[int64]map[int64]bool),
  365. // TokenID = 0 is ETH. Set first entry in TokenList with 0x0 address for ETH.
  366. TokenList: []ethCommon.Address{{}},
  367. TokenMap: make(map[ethCommon.Address]bool),
  368. MapL1TxQueue: mapL1TxQueue,
  369. LastL1L2Batch: 0,
  370. CurrentToForgeL1TxsNum: 0,
  371. LastToForgeL1TxsNum: 1,
  372. CurrentIdx: 0,
  373. },
  374. Vars: *setup.RollupVariables,
  375. Txs: make(map[ethCommon.Hash]*types.Transaction),
  376. Events: eth.NewRollupEvents(),
  377. Constants: setup.RollupConstants,
  378. },
  379. Auction: &AuctionBlock{
  380. State: eth.AuctionState{
  381. Slots: make(map[int64]*eth.SlotState),
  382. PendingBalances: make(map[ethCommon.Address]*big.Int),
  383. Coordinators: make(map[ethCommon.Address]*eth.Coordinator),
  384. },
  385. Vars: *setup.AuctionVariables,
  386. Txs: make(map[ethCommon.Hash]*types.Transaction),
  387. Events: eth.NewAuctionEvents(),
  388. Constants: setup.AuctionConstants,
  389. },
  390. WDelayer: &WDelayerBlock{
  391. // State: TODO
  392. Vars: *setup.WDelayerVariables,
  393. Txs: make(map[ethCommon.Hash]*types.Transaction),
  394. Events: eth.NewWDelayerEvents(),
  395. Constants: setup.WDelayerConstants,
  396. },
  397. Eth: &EthereumBlock{
  398. BlockNum: blockNum,
  399. Time: timer.Time(),
  400. Hash: hasher.Next(),
  401. ParentHash: ethCommon.Hash{},
  402. Tokens: make(map[ethCommon.Address]eth.ERC20Consts),
  403. },
  404. }
  405. blockCurrent.Rollup.Eth = blockCurrent.Eth
  406. blockCurrent.Auction.Eth = blockCurrent.Eth
  407. blocks[blockNum] = blockCurrent
  408. blockNext := blockCurrent.Next()
  409. blocks[blockNum+1] = blockNext
  410. c := Client{
  411. rw: &sync.RWMutex{},
  412. log: l,
  413. addr: addr,
  414. rollupConstants: setup.RollupConstants,
  415. auctionConstants: setup.AuctionConstants,
  416. wDelayerConstants: setup.WDelayerConstants,
  417. blocks: blocks,
  418. timer: timer,
  419. hasher: hasher,
  420. forgeBatchArgsPending: make(map[ethCommon.Hash]*batch),
  421. forgeBatchArgs: make(map[ethCommon.Hash]*batch),
  422. blockNum: blockNum,
  423. maxBlockNum: blockNum,
  424. }
  425. for i := int64(1); i < setup.AuctionConstants.GenesisBlockNum+1; i++ {
  426. c.CtlMineBlock()
  427. }
  428. return &c
  429. }
  430. //
  431. // Mock Control
  432. //
  433. func (c *Client) setNextBlock(block *Block) {
  434. c.blocks[c.blockNum+1] = block
  435. }
  436. func (c *Client) revertIfErr(err error, block *Block) {
  437. if err != nil {
  438. log.Infow("TestClient revert", "block", block.Eth.BlockNum, "err", err)
  439. c.setNextBlock(block)
  440. }
  441. }
  442. // Debugf calls log.Debugf if c.log is true
  443. func (c *Client) Debugf(template string, args ...interface{}) {
  444. if c.log {
  445. log.Debugf(template, args...)
  446. }
  447. }
  448. // Debugw calls log.Debugw if c.log is true
  449. func (c *Client) Debugw(template string, kv ...interface{}) {
  450. if c.log {
  451. log.Debugw(template, kv...)
  452. }
  453. }
  454. type hasher struct {
  455. counter uint64
  456. }
  457. // Next returns the next hash
  458. func (h *hasher) Next() ethCommon.Hash {
  459. var hash ethCommon.Hash
  460. binary.LittleEndian.PutUint64(hash[:], h.counter)
  461. h.counter++
  462. return hash
  463. }
  464. func (c *Client) nextBlock() *Block {
  465. return c.blocks[c.blockNum+1]
  466. }
  467. func (c *Client) currentBlock() *Block {
  468. return c.blocks[c.blockNum]
  469. }
  470. // CtlSetAddr sets the address of the client
  471. func (c *Client) CtlSetAddr(addr ethCommon.Address) {
  472. c.addr = &addr
  473. }
  474. // CtlMineBlock moves one block forward
  475. func (c *Client) CtlMineBlock() {
  476. c.rw.Lock()
  477. defer c.rw.Unlock()
  478. blockCurrent := c.nextBlock()
  479. c.blockNum++
  480. c.maxBlockNum = c.blockNum
  481. blockCurrent.Eth.Time = c.timer.Time()
  482. blockCurrent.Eth.Hash = c.hasher.Next()
  483. for ethTxHash, forgeBatchArgs := range c.forgeBatchArgsPending {
  484. c.forgeBatchArgs[ethTxHash] = forgeBatchArgs
  485. }
  486. c.forgeBatchArgsPending = make(map[ethCommon.Hash]*batch)
  487. blockNext := blockCurrent.Next()
  488. c.blocks[c.blockNum+1] = blockNext
  489. c.Debugw("TestClient mined block", "blockNum", c.blockNum)
  490. }
  491. // CtlRollback discards the last mined block. Use this to replace a mined
  492. // block to simulate reorgs.
  493. func (c *Client) CtlRollback() {
  494. c.rw.Lock()
  495. defer c.rw.Unlock()
  496. if c.blockNum == 0 {
  497. panic("Can't rollback at blockNum = 0")
  498. }
  499. delete(c.blocks, c.blockNum+1) // delete next block
  500. delete(c.blocks, c.blockNum) // delete current block
  501. c.blockNum--
  502. blockCurrent := c.blocks[c.blockNum]
  503. blockNext := blockCurrent.Next()
  504. c.blocks[c.blockNum+1] = blockNext
  505. }
  506. //
  507. // Ethereum
  508. //
  509. // CtlLastBlock returns the last blockNum without checks
  510. func (c *Client) CtlLastBlock() *common.Block {
  511. c.rw.RLock()
  512. defer c.rw.RUnlock()
  513. block := c.blocks[c.blockNum]
  514. return &common.Block{
  515. Num: c.blockNum,
  516. Timestamp: time.Unix(block.Eth.Time, 0),
  517. Hash: block.Eth.Hash,
  518. ParentHash: block.Eth.ParentHash,
  519. }
  520. }
  521. // CtlLastForgedBatch returns the last batchNum without checks
  522. func (c *Client) CtlLastForgedBatch() int64 {
  523. c.rw.RLock()
  524. defer c.rw.RUnlock()
  525. currentBlock := c.currentBlock()
  526. e := currentBlock.Rollup
  527. return int64(len(e.State.ExitRoots)) - 1
  528. }
  529. // EthLastBlock returns the last blockNum
  530. func (c *Client) EthLastBlock() (int64, error) {
  531. c.rw.RLock()
  532. defer c.rw.RUnlock()
  533. if c.blockNum < c.maxBlockNum {
  534. panic("blockNum has decreased. " +
  535. "After a rollback you must mine to reach the same or higher blockNum")
  536. }
  537. return c.blockNum, nil
  538. }
  539. // EthTransactionReceipt returns the transaction receipt of the given txHash
  540. func (c *Client) EthTransactionReceipt(ctx context.Context, txHash ethCommon.Hash) (*types.Receipt, error) {
  541. c.rw.RLock()
  542. defer c.rw.RUnlock()
  543. for i := int64(0); i < c.blockNum; i++ {
  544. b := c.blocks[i]
  545. _, ok := b.Rollup.Txs[txHash]
  546. if !ok {
  547. _, ok = b.Auction.Txs[txHash]
  548. }
  549. if ok {
  550. return &types.Receipt{
  551. TxHash: txHash,
  552. Status: types.ReceiptStatusSuccessful,
  553. BlockHash: b.Eth.Hash,
  554. BlockNumber: big.NewInt(b.Eth.BlockNum),
  555. }, nil
  556. }
  557. }
  558. return nil, nil
  559. }
  560. // CtlAddERC20 adds an ERC20 token to the blockchain.
  561. func (c *Client) CtlAddERC20(tokenAddr ethCommon.Address, constants eth.ERC20Consts) {
  562. nextBlock := c.nextBlock()
  563. e := nextBlock.Eth
  564. e.Tokens[tokenAddr] = constants
  565. }
  566. // EthERC20Consts returns the constants defined for a particular ERC20 Token instance.
  567. func (c *Client) EthERC20Consts(tokenAddr ethCommon.Address) (*eth.ERC20Consts, error) {
  568. currentBlock := c.currentBlock()
  569. e := currentBlock.Eth
  570. if constants, ok := e.Tokens[tokenAddr]; ok {
  571. return &constants, nil
  572. }
  573. return nil, tracerr.Wrap(fmt.Errorf("tokenAddr not found"))
  574. }
  575. // func newHeader(number *big.Int) *types.Header {
  576. // return &types.Header{
  577. // Number: number,
  578. // Time: uint64(number.Int64()),
  579. // }
  580. // }
  581. // EthHeaderByNumber returns the *types.Header for the given block number in a
  582. // deterministic way.
  583. // func (c *Client) EthHeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
  584. // return newHeader(number), nil
  585. // }
  586. // EthBlockByNumber returns the *common.Block for the given block number in a
  587. // deterministic way. If number == -1, the latests known block is returned.
  588. func (c *Client) EthBlockByNumber(ctx context.Context, blockNum int64) (*common.Block, error) {
  589. c.rw.RLock()
  590. defer c.rw.RUnlock()
  591. if blockNum > c.blockNum {
  592. return nil, ethereum.NotFound
  593. }
  594. if blockNum == -1 {
  595. blockNum = c.blockNum
  596. }
  597. block := c.blocks[blockNum]
  598. return &common.Block{
  599. Num: blockNum,
  600. Timestamp: time.Unix(block.Eth.Time, 0),
  601. Hash: block.Eth.Hash,
  602. ParentHash: block.Eth.ParentHash,
  603. }, nil
  604. }
  605. // EthAddress returns the ethereum address of the account loaded into the Client
  606. func (c *Client) EthAddress() (*ethCommon.Address, error) {
  607. if c.addr == nil {
  608. return nil, tracerr.Wrap(eth.ErrAccountNil)
  609. }
  610. return c.addr, nil
  611. }
  612. var errTODO = fmt.Errorf("TODO: Not implemented yet")
  613. //
  614. // Rollup
  615. //
  616. // CtlAddL1TxUser adds an L1TxUser to the L1UserTxs queue of the Rollup
  617. // func (c *Client) CtlAddL1TxUser(l1Tx *common.L1Tx) {
  618. // c.rw.Lock()
  619. // defer c.rw.Unlock()
  620. //
  621. // nextBlock := c.nextBlock()
  622. // r := nextBlock.Rollup
  623. // queue := r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  624. // if len(queue.L1TxQueue) >= eth.RollupConstMaxL1UserTx {
  625. // r.State.LastToForgeL1TxsNum++
  626. // r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
  627. // queue = r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  628. // }
  629. // if int64(l1Tx.FromIdx) > r.State.CurrentIdx {
  630. // panic("l1Tx.FromIdx > r.State.CurrentIdx")
  631. // }
  632. // if int(l1Tx.TokenID)+1 > len(r.State.TokenList) {
  633. // panic("l1Tx.TokenID + 1 > len(r.State.TokenList)")
  634. // }
  635. // queue.L1TxQueue = append(queue.L1TxQueue, *l1Tx)
  636. // r.Events.L1UserTx = append(r.Events.L1UserTx, eth.RollupEventL1UserTx{
  637. // L1Tx: *l1Tx,
  638. // ToForgeL1TxsNum: r.State.LastToForgeL1TxsNum,
  639. // Position: len(queue.L1TxQueue) - 1,
  640. // })
  641. // }
  642. // RollupL1UserTxERC20Permit is the interface to call the smart contract function
  643. func (c *Client) RollupL1UserTxERC20Permit(fromBJJ *babyjub.PublicKey, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error) {
  644. log.Error("TODO")
  645. return nil, tracerr.Wrap(errTODO)
  646. }
  647. // RollupL1UserTxERC20ETH sends an L1UserTx to the Rollup.
  648. func (c *Client) RollupL1UserTxERC20ETH(
  649. fromBJJ *babyjub.PublicKey,
  650. fromIdx int64,
  651. depositAmount *big.Int,
  652. amount *big.Int,
  653. tokenID uint32,
  654. toIdx int64,
  655. ) (tx *types.Transaction, err error) {
  656. c.rw.Lock()
  657. defer c.rw.Unlock()
  658. cpy := c.nextBlock().copy()
  659. defer func() { c.revertIfErr(err, cpy) }()
  660. _, err = common.NewFloat16(amount)
  661. if err != nil {
  662. return nil, tracerr.Wrap(err)
  663. }
  664. _, err = common.NewFloat16(depositAmount)
  665. if err != nil {
  666. return nil, tracerr.Wrap(err)
  667. }
  668. nextBlock := c.nextBlock()
  669. r := nextBlock.Rollup
  670. queue := r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  671. if len(queue.L1TxQueue) >= common.RollupConstMaxL1UserTx {
  672. r.State.LastToForgeL1TxsNum++
  673. r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
  674. queue = r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  675. }
  676. if fromIdx > r.State.CurrentIdx {
  677. panic("l1Tx.FromIdx > r.State.CurrentIdx")
  678. }
  679. if int(tokenID)+1 > len(r.State.TokenList) {
  680. panic("l1Tx.TokenID + 1 > len(r.State.TokenList)")
  681. }
  682. toForgeL1TxsNum := r.State.LastToForgeL1TxsNum
  683. l1Tx, err := common.NewL1Tx(&common.L1Tx{
  684. FromIdx: common.Idx(fromIdx),
  685. FromEthAddr: *c.addr,
  686. FromBJJ: fromBJJ,
  687. Amount: amount,
  688. DepositAmount: depositAmount,
  689. TokenID: common.TokenID(tokenID),
  690. ToIdx: common.Idx(toIdx),
  691. ToForgeL1TxsNum: &toForgeL1TxsNum,
  692. Position: len(queue.L1TxQueue),
  693. UserOrigin: true,
  694. })
  695. if err != nil {
  696. return nil, tracerr.Wrap(err)
  697. }
  698. queue.L1TxQueue = append(queue.L1TxQueue, *l1Tx)
  699. r.Events.L1UserTx = append(r.Events.L1UserTx, eth.RollupEventL1UserTx{
  700. L1UserTx: *l1Tx,
  701. })
  702. return r.addTransaction(c.newTransaction("l1UserTxERC20ETH", l1Tx)), nil
  703. }
  704. // RollupL1UserTxERC777 is the interface to call the smart contract function
  705. // func (c *Client) RollupL1UserTxERC777(fromBJJ *babyjub.PublicKey, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error) {
  706. // log.Error("TODO")
  707. // return nil, errTODO
  708. // }
  709. // RollupRegisterTokensCount is the interface to call the smart contract function
  710. func (c *Client) RollupRegisterTokensCount() (*big.Int, error) {
  711. log.Error("TODO")
  712. return nil, tracerr.Wrap(errTODO)
  713. }
  714. // RollupLastForgedBatch is the interface to call the smart contract function
  715. func (c *Client) RollupLastForgedBatch() (int64, error) {
  716. c.rw.RLock()
  717. defer c.rw.RUnlock()
  718. currentBlock := c.currentBlock()
  719. e := currentBlock.Rollup
  720. return int64(len(e.State.ExitRoots)) - 1, nil
  721. }
  722. // RollupWithdrawCircuit is the interface to call the smart contract function
  723. func (c *Client) RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]*big.Int, tokenID uint32, numExitRoot, idx int64, amount *big.Int, instantWithdraw bool) (*types.Transaction, error) {
  724. log.Error("TODO")
  725. return nil, tracerr.Wrap(errTODO)
  726. }
  727. // RollupWithdrawMerkleProof is the interface to call the smart contract function
  728. func (c *Client) RollupWithdrawMerkleProof(babyPubKey *babyjub.PublicKey, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (tx *types.Transaction, err error) {
  729. c.rw.Lock()
  730. defer c.rw.Unlock()
  731. cpy := c.nextBlock().copy()
  732. defer func() { c.revertIfErr(err, cpy) }()
  733. nextBlock := c.nextBlock()
  734. r := nextBlock.Rollup
  735. if int(numExitRoot) >= len(r.State.ExitRoots) {
  736. return nil, tracerr.Wrap(fmt.Errorf("numExitRoot >= len(r.State.ExitRoots)"))
  737. }
  738. if _, ok := r.State.ExitNullifierMap[numExitRoot][idx]; ok {
  739. return nil, tracerr.Wrap(fmt.Errorf("exit already withdrawn"))
  740. }
  741. r.State.ExitNullifierMap[numExitRoot][idx] = true
  742. type data struct {
  743. BabyPubKey *babyjub.PublicKey
  744. TokenID uint32
  745. NumExitRoot int64
  746. Idx int64
  747. Amount *big.Int
  748. Siblings []*big.Int
  749. InstantWithdraw bool
  750. }
  751. tx = r.addTransaction(c.newTransaction("withdrawMerkleProof", data{
  752. BabyPubKey: babyPubKey,
  753. TokenID: tokenID,
  754. NumExitRoot: numExitRoot,
  755. Idx: idx,
  756. Amount: amount,
  757. Siblings: siblings,
  758. InstantWithdraw: instantWithdraw,
  759. }))
  760. r.Events.Withdraw = append(r.Events.Withdraw, eth.RollupEventWithdraw{
  761. Idx: uint64(idx),
  762. NumExitRoot: uint64(numExitRoot),
  763. InstantWithdraw: instantWithdraw,
  764. TxHash: tx.Hash(),
  765. })
  766. if !instantWithdraw {
  767. w := nextBlock.WDelayer
  768. w.deposit(tx.Hash(), *c.addr, r.State.TokenList[int(tokenID)], amount)
  769. }
  770. return tx, nil
  771. }
  772. type transactionData struct {
  773. Name string
  774. Value interface{}
  775. }
  776. func (c *Client) newTransaction(name string, value interface{}) *types.Transaction {
  777. eth := c.nextBlock().Eth
  778. nonce := eth.Nonce
  779. eth.Nonce++
  780. data, err := json.Marshal(transactionData{name, value})
  781. if err != nil {
  782. panic(err)
  783. }
  784. return types.NewTransaction(nonce, ethCommon.Address{}, nil, 0, nil,
  785. data)
  786. }
  787. // RollupForgeBatch is the interface to call the smart contract function
  788. func (c *Client) RollupForgeBatch(args *eth.RollupForgeBatchArgs) (tx *types.Transaction, err error) {
  789. c.rw.Lock()
  790. defer c.rw.Unlock()
  791. cpy := c.nextBlock().copy()
  792. defer func() { c.revertIfErr(err, cpy) }()
  793. if c.addr == nil {
  794. return nil, tracerr.Wrap(eth.ErrAccountNil)
  795. }
  796. a := c.nextBlock().Auction
  797. ok, err := a.canForge(*c.addr, a.Eth.BlockNum)
  798. if err != nil {
  799. return nil, tracerr.Wrap(err)
  800. }
  801. if !ok {
  802. return nil, tracerr.Wrap(fmt.Errorf(common.AuctionErrMsgCannotForge))
  803. }
  804. // TODO: Verify proof
  805. // Auction
  806. err = a.forge(*c.addr)
  807. if err != nil {
  808. return nil, tracerr.Wrap(err)
  809. }
  810. // TODO: If successful, store the tx in a successful array.
  811. // TODO: If failed, store the tx in a failed array.
  812. // TODO: Add method to move the tx to another block, reapply it there, and possibly go from successful to failed.
  813. return c.addBatch(args)
  814. }
  815. // CtlAddBatch adds forged batch to the Rollup, without checking any ZKProof
  816. func (c *Client) CtlAddBatch(args *eth.RollupForgeBatchArgs) {
  817. c.rw.Lock()
  818. defer c.rw.Unlock()
  819. if _, err := c.addBatch(args); err != nil {
  820. panic(err)
  821. }
  822. }
  823. func (c *Client) addBatch(args *eth.RollupForgeBatchArgs) (*types.Transaction, error) {
  824. nextBlock := c.nextBlock()
  825. r := nextBlock.Rollup
  826. r.State.StateRoot = args.NewStRoot
  827. if args.NewLastIdx < r.State.CurrentIdx {
  828. return nil, tracerr.Wrap(fmt.Errorf("args.NewLastIdx < r.State.CurrentIdx"))
  829. }
  830. r.State.CurrentIdx = args.NewLastIdx
  831. r.State.ExitNullifierMap[int64(len(r.State.ExitRoots))] = make(map[int64]bool)
  832. r.State.ExitRoots = append(r.State.ExitRoots, args.NewExitRoot)
  833. if args.L1Batch {
  834. r.State.CurrentToForgeL1TxsNum++
  835. if r.State.CurrentToForgeL1TxsNum == r.State.LastToForgeL1TxsNum {
  836. r.State.LastToForgeL1TxsNum++
  837. r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
  838. }
  839. }
  840. ethTx := r.addTransaction(c.newTransaction("forgebatch", args))
  841. c.forgeBatchArgsPending[ethTx.Hash()] = &batch{*args, *c.addr}
  842. r.Events.ForgeBatch = append(r.Events.ForgeBatch, eth.RollupEventForgeBatch{
  843. BatchNum: int64(len(r.State.ExitRoots)) - 1,
  844. EthTxHash: ethTx.Hash(),
  845. L1UserTxsLen: uint16(len(args.L1UserTxs)),
  846. })
  847. return ethTx, nil
  848. }
  849. // RollupAddTokenSimple is a wrapper around RollupAddToken that automatically
  850. // sets `deadlie`.
  851. func (c *Client) RollupAddTokenSimple(tokenAddress ethCommon.Address, feeAddToken *big.Int) (tx *types.Transaction, err error) {
  852. return c.RollupAddToken(tokenAddress, feeAddToken, big.NewInt(9999)) //nolint:gomnd
  853. }
  854. // RollupAddToken is the interface to call the smart contract function
  855. func (c *Client) RollupAddToken(tokenAddress ethCommon.Address, feeAddToken *big.Int,
  856. deadline *big.Int) (tx *types.Transaction, err error) {
  857. c.rw.Lock()
  858. defer c.rw.Unlock()
  859. cpy := c.nextBlock().copy()
  860. defer func() { c.revertIfErr(err, cpy) }()
  861. if c.addr == nil {
  862. return nil, tracerr.Wrap(eth.ErrAccountNil)
  863. }
  864. nextBlock := c.nextBlock()
  865. r := nextBlock.Rollup
  866. if _, ok := r.State.TokenMap[tokenAddress]; ok {
  867. return nil, tracerr.Wrap(fmt.Errorf("Token %v already registered", tokenAddress))
  868. }
  869. if feeAddToken.Cmp(r.Vars.FeeAddToken) != 0 {
  870. return nil, tracerr.Wrap(fmt.Errorf("Expected fee: %v but got: %v", r.Vars.FeeAddToken, feeAddToken))
  871. }
  872. r.State.TokenMap[tokenAddress] = true
  873. r.State.TokenList = append(r.State.TokenList, tokenAddress)
  874. r.Events.AddToken = append(r.Events.AddToken, eth.RollupEventAddToken{TokenAddress: tokenAddress,
  875. TokenID: uint32(len(r.State.TokenList) - 1)})
  876. return r.addTransaction(c.newTransaction("addtoken", tokenAddress)), nil
  877. }
  878. // RollupGetCurrentTokens is the interface to call the smart contract function
  879. func (c *Client) RollupGetCurrentTokens() (*big.Int, error) {
  880. c.rw.RLock()
  881. defer c.rw.RUnlock()
  882. log.Error("TODO")
  883. return nil, tracerr.Wrap(errTODO)
  884. }
  885. // RollupUpdateForgeL1L2BatchTimeout is the interface to call the smart contract function
  886. func (c *Client) RollupUpdateForgeL1L2BatchTimeout(newForgeL1Timeout int64) (tx *types.Transaction, err error) {
  887. c.rw.Lock()
  888. defer c.rw.Unlock()
  889. cpy := c.nextBlock().copy()
  890. defer func() { c.revertIfErr(err, cpy) }()
  891. if c.addr == nil {
  892. return nil, tracerr.Wrap(eth.ErrAccountNil)
  893. }
  894. nextBlock := c.nextBlock()
  895. r := nextBlock.Rollup
  896. r.Vars.ForgeL1L2BatchTimeout = newForgeL1Timeout
  897. r.Events.UpdateForgeL1L2BatchTimeout = append(r.Events.UpdateForgeL1L2BatchTimeout,
  898. eth.RollupEventUpdateForgeL1L2BatchTimeout{NewForgeL1L2BatchTimeout: newForgeL1Timeout})
  899. return r.addTransaction(c.newTransaction("updateForgeL1L2BatchTimeout", newForgeL1Timeout)), nil
  900. }
  901. // RollupUpdateFeeAddToken is the interface to call the smart contract function
  902. func (c *Client) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (tx *types.Transaction, err error) {
  903. c.rw.Lock()
  904. defer c.rw.Unlock()
  905. cpy := c.nextBlock().copy()
  906. defer func() { c.revertIfErr(err, cpy) }()
  907. if c.addr == nil {
  908. return nil, tracerr.Wrap(eth.ErrAccountNil)
  909. }
  910. log.Error("TODO")
  911. return nil, tracerr.Wrap(errTODO)
  912. }
  913. // RollupUpdateTokensHEZ is the interface to call the smart contract function
  914. // func (c *Client) RollupUpdateTokensHEZ(newTokenHEZ ethCommon.Address) (tx *types.Transaction, err error) {
  915. // c.rw.Lock()
  916. // defer c.rw.Unlock()
  917. // cpy := c.nextBlock().copy()
  918. // defer func() { c.revertIfErr(err, cpy) }()
  919. //
  920. // log.Error("TODO")
  921. // return nil, errTODO
  922. // }
  923. // RollupUpdateGovernance is the interface to call the smart contract function
  924. // func (c *Client) RollupUpdateGovernance() (*types.Transaction, error) { // TODO (Not defined in Hermez.sol)
  925. // return nil, errTODO
  926. // }
  927. // RollupConstants returns the Constants of the Rollup Smart Contract
  928. func (c *Client) RollupConstants() (*common.RollupConstants, error) {
  929. c.rw.RLock()
  930. defer c.rw.RUnlock()
  931. return c.rollupConstants, nil
  932. }
  933. // RollupEventsByBlock returns the events in a block that happened in the Rollup Smart Contract
  934. func (c *Client) RollupEventsByBlock(blockNum int64) (*eth.RollupEvents, *ethCommon.Hash, error) {
  935. c.rw.RLock()
  936. defer c.rw.RUnlock()
  937. block, ok := c.blocks[blockNum]
  938. if !ok {
  939. return nil, nil, tracerr.Wrap(fmt.Errorf("Block %v doesn't exist", blockNum))
  940. }
  941. return &block.Rollup.Events, &block.Eth.Hash, nil
  942. }
  943. // RollupForgeBatchArgs returns the arguments used in a ForgeBatch call in the Rollup Smart Contract in the given transaction
  944. func (c *Client) RollupForgeBatchArgs(ethTxHash ethCommon.Hash, l1UserTxsLen uint16) (*eth.RollupForgeBatchArgs, *ethCommon.Address, error) {
  945. c.rw.RLock()
  946. defer c.rw.RUnlock()
  947. batch, ok := c.forgeBatchArgs[ethTxHash]
  948. if !ok {
  949. return nil, nil, tracerr.Wrap(fmt.Errorf("transaction not found"))
  950. }
  951. return &batch.ForgeBatchArgs, &batch.Sender, nil
  952. }
  953. //
  954. // Auction
  955. //
  956. // AuctionSetSlotDeadline is the interface to call the smart contract function
  957. func (c *Client) AuctionSetSlotDeadline(newDeadline uint8) (tx *types.Transaction, err error) {
  958. c.rw.Lock()
  959. defer c.rw.Unlock()
  960. cpy := c.nextBlock().copy()
  961. defer func() { c.revertIfErr(err, cpy) }()
  962. if c.addr == nil {
  963. return nil, tracerr.Wrap(eth.ErrAccountNil)
  964. }
  965. log.Error("TODO")
  966. return nil, tracerr.Wrap(errTODO)
  967. }
  968. // AuctionGetSlotDeadline is the interface to call the smart contract function
  969. func (c *Client) AuctionGetSlotDeadline() (uint8, error) {
  970. c.rw.RLock()
  971. defer c.rw.RUnlock()
  972. log.Error("TODO")
  973. return 0, tracerr.Wrap(errTODO)
  974. }
  975. // AuctionSetOpenAuctionSlots is the interface to call the smart contract function
  976. func (c *Client) AuctionSetOpenAuctionSlots(newOpenAuctionSlots uint16) (tx *types.Transaction, err error) {
  977. c.rw.Lock()
  978. defer c.rw.Unlock()
  979. cpy := c.nextBlock().copy()
  980. defer func() { c.revertIfErr(err, cpy) }()
  981. if c.addr == nil {
  982. return nil, tracerr.Wrap(eth.ErrAccountNil)
  983. }
  984. nextBlock := c.nextBlock()
  985. a := nextBlock.Auction
  986. a.Vars.OpenAuctionSlots = newOpenAuctionSlots
  987. a.Events.NewOpenAuctionSlots = append(a.Events.NewOpenAuctionSlots,
  988. eth.AuctionEventNewOpenAuctionSlots{NewOpenAuctionSlots: newOpenAuctionSlots})
  989. return a.addTransaction(c.newTransaction("setOpenAuctionSlots", newOpenAuctionSlots)), nil
  990. }
  991. // AuctionGetOpenAuctionSlots is the interface to call the smart contract function
  992. func (c *Client) AuctionGetOpenAuctionSlots() (uint16, error) {
  993. c.rw.RLock()
  994. defer c.rw.RUnlock()
  995. log.Error("TODO")
  996. return 0, tracerr.Wrap(errTODO)
  997. }
  998. // AuctionSetClosedAuctionSlots is the interface to call the smart contract function
  999. func (c *Client) AuctionSetClosedAuctionSlots(newClosedAuctionSlots uint16) (tx *types.Transaction, err error) {
  1000. c.rw.Lock()
  1001. defer c.rw.Unlock()
  1002. cpy := c.nextBlock().copy()
  1003. defer func() { c.revertIfErr(err, cpy) }()
  1004. if c.addr == nil {
  1005. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1006. }
  1007. log.Error("TODO")
  1008. return nil, tracerr.Wrap(errTODO)
  1009. }
  1010. // AuctionGetClosedAuctionSlots is the interface to call the smart contract function
  1011. func (c *Client) AuctionGetClosedAuctionSlots() (uint16, error) {
  1012. c.rw.RLock()
  1013. defer c.rw.RUnlock()
  1014. log.Error("TODO")
  1015. return 0, tracerr.Wrap(errTODO)
  1016. }
  1017. // AuctionSetOutbidding is the interface to call the smart contract function
  1018. func (c *Client) AuctionSetOutbidding(newOutbidding uint16) (tx *types.Transaction, err error) {
  1019. c.rw.Lock()
  1020. defer c.rw.Unlock()
  1021. cpy := c.nextBlock().copy()
  1022. defer func() { c.revertIfErr(err, cpy) }()
  1023. if c.addr == nil {
  1024. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1025. }
  1026. log.Error("TODO")
  1027. return nil, tracerr.Wrap(errTODO)
  1028. }
  1029. // AuctionGetOutbidding is the interface to call the smart contract function
  1030. func (c *Client) AuctionGetOutbidding() (uint16, error) {
  1031. c.rw.RLock()
  1032. defer c.rw.RUnlock()
  1033. log.Error("TODO")
  1034. return 0, tracerr.Wrap(errTODO)
  1035. }
  1036. // AuctionSetAllocationRatio is the interface to call the smart contract function
  1037. func (c *Client) AuctionSetAllocationRatio(newAllocationRatio [3]uint16) (tx *types.Transaction, err error) {
  1038. c.rw.Lock()
  1039. defer c.rw.Unlock()
  1040. cpy := c.nextBlock().copy()
  1041. defer func() { c.revertIfErr(err, cpy) }()
  1042. if c.addr == nil {
  1043. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1044. }
  1045. log.Error("TODO")
  1046. return nil, tracerr.Wrap(errTODO)
  1047. }
  1048. // AuctionGetAllocationRatio is the interface to call the smart contract function
  1049. func (c *Client) AuctionGetAllocationRatio() ([3]uint16, error) {
  1050. c.rw.RLock()
  1051. defer c.rw.RUnlock()
  1052. log.Error("TODO")
  1053. return [3]uint16{}, tracerr.Wrap(errTODO)
  1054. }
  1055. // AuctionSetDonationAddress is the interface to call the smart contract function
  1056. func (c *Client) AuctionSetDonationAddress(newDonationAddress ethCommon.Address) (tx *types.Transaction, err error) {
  1057. c.rw.Lock()
  1058. defer c.rw.Unlock()
  1059. cpy := c.nextBlock().copy()
  1060. defer func() { c.revertIfErr(err, cpy) }()
  1061. if c.addr == nil {
  1062. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1063. }
  1064. log.Error("TODO")
  1065. return nil, tracerr.Wrap(errTODO)
  1066. }
  1067. // AuctionGetDonationAddress is the interface to call the smart contract function
  1068. func (c *Client) AuctionGetDonationAddress() (*ethCommon.Address, error) {
  1069. c.rw.RLock()
  1070. defer c.rw.RUnlock()
  1071. log.Error("TODO")
  1072. return nil, tracerr.Wrap(errTODO)
  1073. }
  1074. // AuctionSetBootCoordinator is the interface to call the smart contract function
  1075. func (c *Client) AuctionSetBootCoordinator(newBootCoordinator ethCommon.Address, newBootCoordinatorURL string) (tx *types.Transaction, err error) {
  1076. c.rw.Lock()
  1077. defer c.rw.Unlock()
  1078. cpy := c.nextBlock().copy()
  1079. defer func() { c.revertIfErr(err, cpy) }()
  1080. if c.addr == nil {
  1081. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1082. }
  1083. log.Error("TODO")
  1084. return nil, tracerr.Wrap(errTODO)
  1085. }
  1086. // AuctionGetBootCoordinator is the interface to call the smart contract function
  1087. func (c *Client) AuctionGetBootCoordinator() (*ethCommon.Address, error) {
  1088. c.rw.RLock()
  1089. defer c.rw.RUnlock()
  1090. currentBlock := c.currentBlock()
  1091. a := currentBlock.Auction
  1092. return &a.Vars.BootCoordinator, nil
  1093. }
  1094. // AuctionChangeDefaultSlotSetBid is the interface to call the smart contract function
  1095. func (c *Client) AuctionChangeDefaultSlotSetBid(slotSet int64, newInitialMinBid *big.Int) (tx *types.Transaction, err error) {
  1096. c.rw.Lock()
  1097. defer c.rw.Unlock()
  1098. cpy := c.nextBlock().copy()
  1099. defer func() { c.revertIfErr(err, cpy) }()
  1100. if c.addr == nil {
  1101. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1102. }
  1103. log.Error("TODO")
  1104. return nil, tracerr.Wrap(errTODO)
  1105. }
  1106. // AuctionSetCoordinator is the interface to call the smart contract function
  1107. func (c *Client) AuctionSetCoordinator(forger ethCommon.Address, URL string) (tx *types.Transaction, err error) {
  1108. c.rw.Lock()
  1109. defer c.rw.Unlock()
  1110. cpy := c.nextBlock().copy()
  1111. defer func() { c.revertIfErr(err, cpy) }()
  1112. if c.addr == nil {
  1113. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1114. }
  1115. nextBlock := c.nextBlock()
  1116. a := nextBlock.Auction
  1117. a.State.Coordinators[*c.addr] = &eth.Coordinator{
  1118. Forger: forger,
  1119. URL: URL,
  1120. }
  1121. a.Events.SetCoordinator = append(a.Events.SetCoordinator,
  1122. eth.AuctionEventSetCoordinator{
  1123. BidderAddress: *c.addr,
  1124. ForgerAddress: forger,
  1125. CoordinatorURL: URL,
  1126. })
  1127. type data struct {
  1128. BidderAddress ethCommon.Address
  1129. ForgerAddress ethCommon.Address
  1130. URL string
  1131. }
  1132. return a.addTransaction(c.newTransaction("registercoordinator", data{*c.addr, forger, URL})), nil
  1133. }
  1134. // AuctionIsRegisteredCoordinator is the interface to call the smart contract function
  1135. func (c *Client) AuctionIsRegisteredCoordinator(forgerAddress ethCommon.Address) (bool, error) {
  1136. c.rw.RLock()
  1137. defer c.rw.RUnlock()
  1138. log.Error("TODO")
  1139. return false, tracerr.Wrap(errTODO)
  1140. }
  1141. // AuctionUpdateCoordinatorInfo is the interface to call the smart contract function
  1142. func (c *Client) AuctionUpdateCoordinatorInfo(forgerAddress ethCommon.Address, newWithdrawAddress ethCommon.Address, newURL string) (tx *types.Transaction, err error) {
  1143. c.rw.Lock()
  1144. defer c.rw.Unlock()
  1145. cpy := c.nextBlock().copy()
  1146. defer func() { c.revertIfErr(err, cpy) }()
  1147. if c.addr == nil {
  1148. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1149. }
  1150. log.Error("TODO")
  1151. return nil, tracerr.Wrap(errTODO)
  1152. }
  1153. // AuctionGetSlotNumber is the interface to call the smart contract function
  1154. func (c *Client) AuctionGetSlotNumber(blockNum int64) (int64, error) {
  1155. c.rw.RLock()
  1156. defer c.rw.RUnlock()
  1157. currentBlock := c.currentBlock()
  1158. a := currentBlock.Auction
  1159. return a.getSlotNumber(blockNum), nil
  1160. }
  1161. // AuctionGetCurrentSlotNumber is the interface to call the smart contract function
  1162. func (c *Client) AuctionGetCurrentSlotNumber() (int64, error) {
  1163. c.rw.RLock()
  1164. defer c.rw.RUnlock()
  1165. log.Error("TODO")
  1166. return 0, tracerr.Wrap(errTODO)
  1167. }
  1168. // AuctionGetMinBidBySlot is the interface to call the smart contract function
  1169. func (c *Client) AuctionGetMinBidBySlot(slot int64) (*big.Int, error) {
  1170. c.rw.RLock()
  1171. defer c.rw.RUnlock()
  1172. log.Error("TODO")
  1173. return nil, tracerr.Wrap(errTODO)
  1174. }
  1175. // AuctionGetDefaultSlotSetBid is the interface to call the smart contract function
  1176. func (c *Client) AuctionGetDefaultSlotSetBid(slotSet uint8) (*big.Int, error) {
  1177. c.rw.RLock()
  1178. defer c.rw.RUnlock()
  1179. log.Error("TODO")
  1180. return nil, tracerr.Wrap(errTODO)
  1181. }
  1182. // AuctionGetSlotSet is the interface to call the smart contract function
  1183. func (c *Client) AuctionGetSlotSet(slot int64) (*big.Int, error) {
  1184. c.rw.RLock()
  1185. defer c.rw.RUnlock()
  1186. log.Error("TODO")
  1187. return nil, tracerr.Wrap(errTODO)
  1188. }
  1189. // AuctionTokensReceived is the interface to call the smart contract function
  1190. // func (c *Client) AuctionTokensReceived(operator, from, to ethCommon.Address, amount *big.Int, userData, operatorData []byte) error {
  1191. // return errTODO
  1192. // }
  1193. // AuctionBidSimple is a wrapper around AuctionBid that automatically sets `amount` and `deadline`.
  1194. func (c *Client) AuctionBidSimple(slot int64, bidAmount *big.Int) (tx *types.Transaction, err error) {
  1195. return c.AuctionBid(bidAmount, slot, bidAmount, big.NewInt(99999)) //nolint:gomnd
  1196. }
  1197. // AuctionBid is the interface to call the smart contract function. This
  1198. // implementation behaves as if any address has infinite tokens.
  1199. func (c *Client) AuctionBid(amount *big.Int, slot int64, bidAmount *big.Int,
  1200. deadline *big.Int) (tx *types.Transaction, err error) {
  1201. c.rw.Lock()
  1202. defer c.rw.Unlock()
  1203. cpy := c.nextBlock().copy()
  1204. defer func() { func() { c.revertIfErr(err, cpy) }() }()
  1205. if c.addr == nil {
  1206. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1207. }
  1208. nextBlock := c.nextBlock()
  1209. a := nextBlock.Auction
  1210. if slot < a.getCurrentSlotNumber()+int64(a.Vars.ClosedAuctionSlots) {
  1211. return nil, tracerr.Wrap(errBidClosed)
  1212. }
  1213. if slot >= a.getCurrentSlotNumber()+int64(a.Vars.ClosedAuctionSlots)+int64(a.Vars.OpenAuctionSlots) {
  1214. return nil, tracerr.Wrap(errBidNotOpen)
  1215. }
  1216. minBid, err := a.getMinBidBySlot(slot)
  1217. if err != nil {
  1218. return nil, tracerr.Wrap(err)
  1219. }
  1220. if bidAmount.Cmp(minBid) == -1 {
  1221. return nil, tracerr.Wrap(errBidBelowMin)
  1222. }
  1223. if _, ok := a.State.Coordinators[*c.addr]; !ok {
  1224. return nil, tracerr.Wrap(errCoordNotReg)
  1225. }
  1226. slotState, ok := a.State.Slots[slot]
  1227. if !ok {
  1228. slotState = eth.NewSlotState()
  1229. a.State.Slots[slot] = slotState
  1230. }
  1231. slotState.Bidder = *c.addr
  1232. slotState.BidAmount = bidAmount
  1233. a.Events.NewBid = append(a.Events.NewBid,
  1234. eth.AuctionEventNewBid{Slot: slot, BidAmount: bidAmount, Bidder: *c.addr})
  1235. type data struct {
  1236. Slot int64
  1237. BidAmount *big.Int
  1238. Bidder ethCommon.Address
  1239. }
  1240. return a.addTransaction(c.newTransaction("bid", data{slot, bidAmount, *c.addr})), nil
  1241. }
  1242. // AuctionMultiBid is the interface to call the smart contract function. This
  1243. // implementation behaves as if any address has infinite tokens.
  1244. func (c *Client) AuctionMultiBid(amount *big.Int, startingSlot int64, endingSlot int64, slotSet [6]bool,
  1245. maxBid, closedMinBid, deadline *big.Int) (tx *types.Transaction, err error) {
  1246. c.rw.Lock()
  1247. defer c.rw.Unlock()
  1248. cpy := c.nextBlock().copy()
  1249. defer func() { c.revertIfErr(err, cpy) }()
  1250. if c.addr == nil {
  1251. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1252. }
  1253. log.Error("TODO")
  1254. return nil, tracerr.Wrap(errTODO)
  1255. }
  1256. // AuctionCanForge is the interface to call the smart contract function
  1257. func (c *Client) AuctionCanForge(forger ethCommon.Address, blockNum int64) (bool, error) {
  1258. c.rw.RLock()
  1259. defer c.rw.RUnlock()
  1260. currentBlock := c.currentBlock()
  1261. a := currentBlock.Auction
  1262. return a.canForge(forger, blockNum)
  1263. }
  1264. // AuctionForge is the interface to call the smart contract function
  1265. func (c *Client) AuctionForge(forger ethCommon.Address) (tx *types.Transaction, err error) {
  1266. c.rw.Lock()
  1267. defer c.rw.Unlock()
  1268. cpy := c.nextBlock().copy()
  1269. defer func() { c.revertIfErr(err, cpy) }()
  1270. if c.addr == nil {
  1271. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1272. }
  1273. log.Error("TODO")
  1274. return nil, tracerr.Wrap(errTODO)
  1275. }
  1276. // AuctionClaimHEZ is the interface to call the smart contract function
  1277. func (c *Client) AuctionClaimHEZ() (tx *types.Transaction, err error) {
  1278. c.rw.Lock()
  1279. defer c.rw.Unlock()
  1280. cpy := c.nextBlock().copy()
  1281. defer func() { c.revertIfErr(err, cpy) }()
  1282. if c.addr == nil {
  1283. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1284. }
  1285. log.Error("TODO")
  1286. return nil, tracerr.Wrap(errTODO)
  1287. }
  1288. // AuctionGetClaimableHEZ is the interface to call the smart contract function
  1289. func (c *Client) AuctionGetClaimableHEZ(bidder ethCommon.Address) (*big.Int, error) {
  1290. c.rw.RLock()
  1291. defer c.rw.RUnlock()
  1292. log.Error("TODO")
  1293. return nil, tracerr.Wrap(errTODO)
  1294. }
  1295. // AuctionConstants returns the Constants of the Auction Smart Contract
  1296. func (c *Client) AuctionConstants() (*common.AuctionConstants, error) {
  1297. c.rw.RLock()
  1298. defer c.rw.RUnlock()
  1299. return c.auctionConstants, nil
  1300. }
  1301. // AuctionEventsByBlock returns the events in a block that happened in the Auction Smart Contract
  1302. func (c *Client) AuctionEventsByBlock(blockNum int64) (*eth.AuctionEvents, *ethCommon.Hash, error) {
  1303. c.rw.RLock()
  1304. defer c.rw.RUnlock()
  1305. block, ok := c.blocks[blockNum]
  1306. if !ok {
  1307. return nil, nil, tracerr.Wrap(fmt.Errorf("Block %v doesn't exist", blockNum))
  1308. }
  1309. return &block.Auction.Events, &block.Eth.Hash, nil
  1310. }
  1311. //
  1312. // WDelayer
  1313. //
  1314. // WDelayerGetHermezGovernanceAddress is the interface to call the smart contract function
  1315. func (c *Client) WDelayerGetHermezGovernanceAddress() (*ethCommon.Address, error) {
  1316. c.rw.RLock()
  1317. defer c.rw.RUnlock()
  1318. log.Error("TODO")
  1319. return nil, tracerr.Wrap(errTODO)
  1320. }
  1321. // WDelayerTransferGovernance is the interface to call the smart contract function
  1322. func (c *Client) WDelayerTransferGovernance(newAddress ethCommon.Address) (tx *types.Transaction, err error) {
  1323. c.rw.Lock()
  1324. defer c.rw.Unlock()
  1325. cpy := c.nextBlock().copy()
  1326. defer func() { c.revertIfErr(err, cpy) }()
  1327. if c.addr == nil {
  1328. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1329. }
  1330. log.Error("TODO")
  1331. return nil, tracerr.Wrap(errTODO)
  1332. }
  1333. // WDelayerClaimGovernance is the interface to call the smart contract function
  1334. func (c *Client) WDelayerClaimGovernance() (tx *types.Transaction, err error) {
  1335. c.rw.Lock()
  1336. defer c.rw.Unlock()
  1337. cpy := c.nextBlock().copy()
  1338. defer func() { c.revertIfErr(err, cpy) }()
  1339. if c.addr == nil {
  1340. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1341. }
  1342. log.Error("TODO")
  1343. return nil, tracerr.Wrap(errTODO)
  1344. }
  1345. // WDelayerGetEmergencyCouncil is the interface to call the smart contract function
  1346. func (c *Client) WDelayerGetEmergencyCouncil() (*ethCommon.Address, error) {
  1347. c.rw.RLock()
  1348. defer c.rw.RUnlock()
  1349. log.Error("TODO")
  1350. return nil, tracerr.Wrap(errTODO)
  1351. }
  1352. // WDelayerTransferEmergencyCouncil is the interface to call the smart contract function
  1353. func (c *Client) WDelayerTransferEmergencyCouncil(newAddress ethCommon.Address) (tx *types.Transaction, err error) {
  1354. c.rw.Lock()
  1355. defer c.rw.Unlock()
  1356. cpy := c.nextBlock().copy()
  1357. defer func() { c.revertIfErr(err, cpy) }()
  1358. if c.addr == nil {
  1359. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1360. }
  1361. log.Error("TODO")
  1362. return nil, tracerr.Wrap(errTODO)
  1363. }
  1364. // WDelayerClaimEmergencyCouncil is the interface to call the smart contract function
  1365. func (c *Client) WDelayerClaimEmergencyCouncil() (tx *types.Transaction, err error) {
  1366. c.rw.Lock()
  1367. defer c.rw.Unlock()
  1368. cpy := c.nextBlock().copy()
  1369. defer func() { c.revertIfErr(err, cpy) }()
  1370. if c.addr == nil {
  1371. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1372. }
  1373. log.Error("TODO")
  1374. return nil, tracerr.Wrap(errTODO)
  1375. }
  1376. // WDelayerIsEmergencyMode is the interface to call the smart contract function
  1377. func (c *Client) WDelayerIsEmergencyMode() (bool, error) {
  1378. c.rw.RLock()
  1379. defer c.rw.RUnlock()
  1380. log.Error("TODO")
  1381. return false, tracerr.Wrap(errTODO)
  1382. }
  1383. // WDelayerGetWithdrawalDelay is the interface to call the smart contract function
  1384. func (c *Client) WDelayerGetWithdrawalDelay() (*big.Int, error) {
  1385. c.rw.RLock()
  1386. defer c.rw.RUnlock()
  1387. log.Error("TODO")
  1388. return nil, tracerr.Wrap(errTODO)
  1389. }
  1390. // WDelayerGetEmergencyModeStartingTime is the interface to call the smart contract function
  1391. func (c *Client) WDelayerGetEmergencyModeStartingTime() (*big.Int, error) {
  1392. c.rw.RLock()
  1393. defer c.rw.RUnlock()
  1394. log.Error("TODO")
  1395. return nil, tracerr.Wrap(errTODO)
  1396. }
  1397. // WDelayerEnableEmergencyMode is the interface to call the smart contract function
  1398. func (c *Client) WDelayerEnableEmergencyMode() (tx *types.Transaction, err error) {
  1399. c.rw.Lock()
  1400. defer c.rw.Unlock()
  1401. cpy := c.nextBlock().copy()
  1402. defer func() { c.revertIfErr(err, cpy) }()
  1403. if c.addr == nil {
  1404. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1405. }
  1406. log.Error("TODO")
  1407. return nil, tracerr.Wrap(errTODO)
  1408. }
  1409. // WDelayerChangeWithdrawalDelay is the interface to call the smart contract function
  1410. func (c *Client) WDelayerChangeWithdrawalDelay(newWithdrawalDelay uint64) (tx *types.Transaction, err error) {
  1411. c.rw.Lock()
  1412. defer c.rw.Unlock()
  1413. cpy := c.nextBlock().copy()
  1414. defer func() { c.revertIfErr(err, cpy) }()
  1415. if c.addr == nil {
  1416. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1417. }
  1418. nextBlock := c.nextBlock()
  1419. w := nextBlock.WDelayer
  1420. w.Vars.WithdrawalDelay = newWithdrawalDelay
  1421. w.Events.NewWithdrawalDelay = append(w.Events.NewWithdrawalDelay,
  1422. eth.WDelayerEventNewWithdrawalDelay{WithdrawalDelay: newWithdrawalDelay})
  1423. return w.addTransaction(c.newTransaction("changeWithdrawalDelay", newWithdrawalDelay)), nil
  1424. }
  1425. // WDelayerDepositInfo is the interface to call the smart contract function
  1426. func (c *Client) WDelayerDepositInfo(owner, token ethCommon.Address) (eth.DepositState, error) {
  1427. c.rw.RLock()
  1428. defer c.rw.RUnlock()
  1429. log.Error("TODO")
  1430. return eth.DepositState{}, tracerr.Wrap(errTODO)
  1431. }
  1432. // WDelayerDeposit is the interface to call the smart contract function
  1433. func (c *Client) WDelayerDeposit(onwer, token ethCommon.Address, amount *big.Int) (tx *types.Transaction, err error) {
  1434. c.rw.Lock()
  1435. defer c.rw.Unlock()
  1436. cpy := c.nextBlock().copy()
  1437. defer func() { c.revertIfErr(err, cpy) }()
  1438. if c.addr == nil {
  1439. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1440. }
  1441. log.Error("TODO")
  1442. return nil, tracerr.Wrap(errTODO)
  1443. }
  1444. // WDelayerWithdrawal is the interface to call the smart contract function
  1445. func (c *Client) WDelayerWithdrawal(owner, token ethCommon.Address) (tx *types.Transaction, err error) {
  1446. c.rw.Lock()
  1447. defer c.rw.Unlock()
  1448. cpy := c.nextBlock().copy()
  1449. defer func() { c.revertIfErr(err, cpy) }()
  1450. if c.addr == nil {
  1451. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1452. }
  1453. log.Error("TODO")
  1454. return nil, tracerr.Wrap(errTODO)
  1455. }
  1456. // WDelayerEscapeHatchWithdrawal is the interface to call the smart contract function
  1457. func (c *Client) WDelayerEscapeHatchWithdrawal(to, token ethCommon.Address, amount *big.Int) (tx *types.Transaction, err error) {
  1458. c.rw.Lock()
  1459. defer c.rw.Unlock()
  1460. cpy := c.nextBlock().copy()
  1461. defer func() { c.revertIfErr(err, cpy) }()
  1462. if c.addr == nil {
  1463. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1464. }
  1465. log.Error("TODO")
  1466. return nil, tracerr.Wrap(errTODO)
  1467. }
  1468. // WDelayerEventsByBlock returns the events in a block that happened in the WDelayer Contract
  1469. func (c *Client) WDelayerEventsByBlock(blockNum int64) (*eth.WDelayerEvents, *ethCommon.Hash, error) {
  1470. c.rw.RLock()
  1471. defer c.rw.RUnlock()
  1472. block, ok := c.blocks[blockNum]
  1473. if !ok {
  1474. return nil, nil, tracerr.Wrap(fmt.Errorf("Block %v doesn't exist", blockNum))
  1475. }
  1476. return &block.WDelayer.Events, &block.Eth.Hash, nil
  1477. }
  1478. // WDelayerConstants returns the Constants of the WDelayer Contract
  1479. func (c *Client) WDelayerConstants() (*common.WDelayerConstants, error) {
  1480. c.rw.RLock()
  1481. defer c.rw.RUnlock()
  1482. return c.wDelayerConstants, nil
  1483. }
  1484. // CtlAddBlocks adds block data to the smarts contracts. The added blocks will
  1485. // appear as mined. Not thread safe.
  1486. func (c *Client) CtlAddBlocks(blocks []common.BlockData) (err error) {
  1487. // NOTE: We don't lock because internally we call public functions that
  1488. // lock already.
  1489. for _, block := range blocks {
  1490. nextBlock := c.nextBlock()
  1491. rollup := nextBlock.Rollup
  1492. auction := nextBlock.Auction
  1493. for _, token := range block.Rollup.AddedTokens {
  1494. if _, err := c.RollupAddTokenSimple(token.EthAddr, rollup.Vars.FeeAddToken); err != nil {
  1495. return err
  1496. }
  1497. }
  1498. for _, tx := range block.Rollup.L1UserTxs {
  1499. c.CtlSetAddr(tx.FromEthAddr)
  1500. if _, err := c.RollupL1UserTxERC20ETH(tx.FromBJJ, int64(tx.FromIdx), tx.DepositAmount, tx.Amount,
  1501. uint32(tx.TokenID), int64(tx.ToIdx)); err != nil {
  1502. return err
  1503. }
  1504. }
  1505. c.CtlSetAddr(auction.Vars.BootCoordinator)
  1506. for _, batch := range block.Rollup.Batches {
  1507. if _, err := c.RollupForgeBatch(&eth.RollupForgeBatchArgs{
  1508. NewLastIdx: batch.Batch.LastIdx,
  1509. NewStRoot: batch.Batch.StateRoot,
  1510. NewExitRoot: batch.Batch.ExitRoot,
  1511. L1CoordinatorTxs: batch.L1CoordinatorTxs,
  1512. L1CoordinatorTxsAuths: [][]byte{}, // Intentionally empty
  1513. L2TxsData: batch.L2Txs,
  1514. FeeIdxCoordinator: batch.Batch.FeeIdxsCoordinator,
  1515. // Circuit selector
  1516. VerifierIdx: 0, // Intentionally empty
  1517. L1Batch: batch.L1Batch,
  1518. ProofA: [2]*big.Int{}, // Intentionally empty
  1519. ProofB: [2][2]*big.Int{}, // Intentionally empty
  1520. ProofC: [2]*big.Int{}, // Intentionally empty
  1521. }); err != nil {
  1522. return err
  1523. }
  1524. }
  1525. // Mine block and sync
  1526. c.CtlMineBlock()
  1527. }
  1528. return nil
  1529. }