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.

1814 lines
55 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.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
  1. package 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. var buckets [common.RollupConstNumBuckets]common.BucketParams
  271. for i := range buckets {
  272. buckets[i] = common.BucketParams{
  273. CeilUSD: big.NewInt(0),
  274. Withdrawals: big.NewInt(0),
  275. BlockWithdrawalRate: big.NewInt(0),
  276. MaxWithdrawals: big.NewInt(0),
  277. }
  278. }
  279. rollupVariables := &common.RollupVariables{
  280. FeeAddToken: big.NewInt(11),
  281. ForgeL1L2BatchTimeout: 9,
  282. WithdrawalDelay: 80,
  283. Buckets: buckets,
  284. }
  285. auctionConstants := &common.AuctionConstants{
  286. BlocksPerSlot: 40,
  287. InitialMinimalBidding: initialMinimalBidding,
  288. GenesisBlockNum: 1,
  289. GovernanceAddress: governanceAddress,
  290. TokenHEZ: tokenHEZ,
  291. HermezRollup: ethCommon.HexToAddress("0x474B6e29852257491cf283EfB1A9C61eBFe48369"),
  292. }
  293. auctionVariables := &common.AuctionVariables{
  294. DonationAddress: ethCommon.HexToAddress("0x61Ed87CF0A1496b49A420DA6D84B58196b98f2e7"),
  295. BootCoordinator: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  296. BootCoordinatorURL: "https://boot.coordinator.com",
  297. DefaultSlotSetBid: [6]*big.Int{
  298. initialMinimalBidding, initialMinimalBidding, initialMinimalBidding,
  299. initialMinimalBidding, initialMinimalBidding, initialMinimalBidding,
  300. },
  301. ClosedAuctionSlots: 2,
  302. OpenAuctionSlots: 4320,
  303. AllocationRatio: [3]uint16{4000, 4000, 2000},
  304. Outbidding: 1000,
  305. SlotDeadline: 20,
  306. }
  307. wDelayerConstants := &common.WDelayerConstants{
  308. MaxWithdrawalDelay: 60 * 60 * 24 * 7 * 2, // 2 weeks
  309. MaxEmergencyModeTime: 60 * 60 * 24 * 7 * 26, // 26 weeks
  310. HermezRollup: auctionConstants.HermezRollup,
  311. }
  312. wDelayerVariables := &common.WDelayerVariables{
  313. HermezGovernanceAddress: ethCommon.HexToAddress("0xcfD0d163AE6432a72682323E2C3A5a69e6B37D12"),
  314. EmergencyCouncilAddress: ethCommon.HexToAddress("0x2730700932a4FDB97B9268A3Ca29f97Ea5fd7EA0"),
  315. WithdrawalDelay: 60,
  316. EmergencyModeStartingBlock: 0,
  317. EmergencyMode: false,
  318. }
  319. return &ClientSetup{
  320. RollupConstants: rollupConstants,
  321. RollupVariables: rollupVariables,
  322. AuctionConstants: auctionConstants,
  323. AuctionVariables: auctionVariables,
  324. WDelayerConstants: wDelayerConstants,
  325. WDelayerVariables: wDelayerVariables,
  326. }
  327. }
  328. // Timer is an interface to simulate a source of time, useful to advance time
  329. // virtually.
  330. type Timer interface {
  331. Time() int64
  332. }
  333. // type forgeBatchArgs struct {
  334. // ethTx *types.Transaction
  335. // blockNum int64
  336. // blockHash ethCommon.Hash
  337. // }
  338. type batch struct {
  339. ForgeBatchArgs eth.RollupForgeBatchArgs
  340. Sender ethCommon.Address
  341. }
  342. // Client implements the eth.ClientInterface interface, allowing to manipulate the
  343. // values for testing, working with deterministic results.
  344. type Client struct {
  345. rw *sync.RWMutex
  346. log bool
  347. addr *ethCommon.Address
  348. rollupConstants *common.RollupConstants
  349. auctionConstants *common.AuctionConstants
  350. wDelayerConstants *common.WDelayerConstants
  351. blocks map[int64]*Block
  352. // state state
  353. blockNum int64 // last mined block num
  354. maxBlockNum int64 // highest block num calculated
  355. timer Timer
  356. hasher hasher
  357. forgeBatchArgsPending map[ethCommon.Hash]*batch
  358. forgeBatchArgs map[ethCommon.Hash]*batch
  359. }
  360. // NewClient returns a new test Client that implements the eth.IClient
  361. // interface, at the given initialBlockNumber.
  362. func NewClient(l bool, timer Timer, addr *ethCommon.Address, setup *ClientSetup) *Client {
  363. blocks := make(map[int64]*Block)
  364. blockNum := int64(0)
  365. hasher := hasher{}
  366. // Add ethereum genesis block
  367. mapL1TxQueue := make(map[int64]*eth.QueueStruct)
  368. mapL1TxQueue[0] = eth.NewQueueStruct()
  369. mapL1TxQueue[1] = eth.NewQueueStruct()
  370. blockCurrent := &Block{
  371. Rollup: &RollupBlock{
  372. State: eth.RollupState{
  373. StateRoot: big.NewInt(0),
  374. ExitRoots: make([]*big.Int, 1),
  375. ExitNullifierMap: make(map[int64]map[int64]bool),
  376. // TokenID = 0 is ETH. Set first entry in TokenList with 0x0 address for ETH.
  377. TokenList: []ethCommon.Address{{}},
  378. TokenMap: make(map[ethCommon.Address]bool),
  379. MapL1TxQueue: mapL1TxQueue,
  380. LastL1L2Batch: 0,
  381. CurrentToForgeL1TxsNum: 0,
  382. LastToForgeL1TxsNum: 1,
  383. CurrentIdx: 0,
  384. },
  385. Vars: *setup.RollupVariables,
  386. Txs: make(map[ethCommon.Hash]*types.Transaction),
  387. Events: eth.NewRollupEvents(),
  388. Constants: setup.RollupConstants,
  389. },
  390. Auction: &AuctionBlock{
  391. State: eth.AuctionState{
  392. Slots: make(map[int64]*eth.SlotState),
  393. PendingBalances: make(map[ethCommon.Address]*big.Int),
  394. Coordinators: make(map[ethCommon.Address]*eth.Coordinator),
  395. },
  396. Vars: *setup.AuctionVariables,
  397. Txs: make(map[ethCommon.Hash]*types.Transaction),
  398. Events: eth.NewAuctionEvents(),
  399. Constants: setup.AuctionConstants,
  400. },
  401. WDelayer: &WDelayerBlock{
  402. // State: TODO
  403. Vars: *setup.WDelayerVariables,
  404. Txs: make(map[ethCommon.Hash]*types.Transaction),
  405. Events: eth.NewWDelayerEvents(),
  406. Constants: setup.WDelayerConstants,
  407. },
  408. Eth: &EthereumBlock{
  409. BlockNum: blockNum,
  410. Time: timer.Time(),
  411. Hash: hasher.Next(),
  412. ParentHash: ethCommon.Hash{},
  413. Tokens: make(map[ethCommon.Address]eth.ERC20Consts),
  414. },
  415. }
  416. blockCurrent.Rollup.Eth = blockCurrent.Eth
  417. blockCurrent.Auction.Eth = blockCurrent.Eth
  418. blocks[blockNum] = blockCurrent
  419. blockNext := blockCurrent.Next()
  420. blocks[blockNum+1] = blockNext
  421. c := Client{
  422. rw: &sync.RWMutex{},
  423. log: l,
  424. addr: addr,
  425. rollupConstants: setup.RollupConstants,
  426. auctionConstants: setup.AuctionConstants,
  427. wDelayerConstants: setup.WDelayerConstants,
  428. blocks: blocks,
  429. timer: timer,
  430. hasher: hasher,
  431. forgeBatchArgsPending: make(map[ethCommon.Hash]*batch),
  432. forgeBatchArgs: make(map[ethCommon.Hash]*batch),
  433. blockNum: blockNum,
  434. maxBlockNum: blockNum,
  435. }
  436. for i := int64(1); i < setup.AuctionConstants.GenesisBlockNum+1; i++ {
  437. c.CtlMineBlock()
  438. }
  439. return &c
  440. }
  441. //
  442. // Mock Control
  443. //
  444. func (c *Client) setNextBlock(block *Block) {
  445. c.blocks[c.blockNum+1] = block
  446. }
  447. func (c *Client) revertIfErr(err error, block *Block) {
  448. if err != nil {
  449. log.Infow("TestClient revert", "block", block.Eth.BlockNum, "err", err)
  450. c.setNextBlock(block)
  451. }
  452. }
  453. // Debugf calls log.Debugf if c.log is true
  454. func (c *Client) Debugf(template string, args ...interface{}) {
  455. if c.log {
  456. log.Debugf(template, args...)
  457. }
  458. }
  459. // Debugw calls log.Debugw if c.log is true
  460. func (c *Client) Debugw(template string, kv ...interface{}) {
  461. if c.log {
  462. log.Debugw(template, kv...)
  463. }
  464. }
  465. type hasher struct {
  466. counter uint64
  467. }
  468. // Next returns the next hash
  469. func (h *hasher) Next() ethCommon.Hash {
  470. var hash ethCommon.Hash
  471. binary.LittleEndian.PutUint64(hash[:], h.counter)
  472. h.counter++
  473. return hash
  474. }
  475. func (c *Client) nextBlock() *Block {
  476. return c.blocks[c.blockNum+1]
  477. }
  478. func (c *Client) currentBlock() *Block {
  479. return c.blocks[c.blockNum]
  480. }
  481. // CtlSetAddr sets the address of the client
  482. func (c *Client) CtlSetAddr(addr ethCommon.Address) {
  483. c.addr = &addr
  484. }
  485. // CtlMineBlock moves one block forward
  486. func (c *Client) CtlMineBlock() {
  487. c.rw.Lock()
  488. defer c.rw.Unlock()
  489. blockCurrent := c.nextBlock()
  490. c.blockNum++
  491. c.maxBlockNum = c.blockNum
  492. blockCurrent.Eth.Time = c.timer.Time()
  493. blockCurrent.Eth.Hash = c.hasher.Next()
  494. for ethTxHash, forgeBatchArgs := range c.forgeBatchArgsPending {
  495. c.forgeBatchArgs[ethTxHash] = forgeBatchArgs
  496. }
  497. c.forgeBatchArgsPending = make(map[ethCommon.Hash]*batch)
  498. blockNext := blockCurrent.Next()
  499. c.blocks[c.blockNum+1] = blockNext
  500. c.Debugw("TestClient mined block", "blockNum", c.blockNum)
  501. }
  502. // CtlRollback discards the last mined block. Use this to replace a mined
  503. // block to simulate reorgs.
  504. func (c *Client) CtlRollback() {
  505. c.rw.Lock()
  506. defer c.rw.Unlock()
  507. if c.blockNum == 0 {
  508. panic("Can't rollback at blockNum = 0")
  509. }
  510. delete(c.blocks, c.blockNum+1) // delete next block
  511. delete(c.blocks, c.blockNum) // delete current block
  512. c.blockNum--
  513. blockCurrent := c.blocks[c.blockNum]
  514. blockNext := blockCurrent.Next()
  515. c.blocks[c.blockNum+1] = blockNext
  516. }
  517. //
  518. // Ethereum
  519. //
  520. // CtlLastBlock returns the last blockNum without checks
  521. func (c *Client) CtlLastBlock() *common.Block {
  522. c.rw.RLock()
  523. defer c.rw.RUnlock()
  524. block := c.blocks[c.blockNum]
  525. return &common.Block{
  526. Num: c.blockNum,
  527. Timestamp: time.Unix(block.Eth.Time, 0),
  528. Hash: block.Eth.Hash,
  529. ParentHash: block.Eth.ParentHash,
  530. }
  531. }
  532. // CtlLastForgedBatch returns the last batchNum without checks
  533. func (c *Client) CtlLastForgedBatch() int64 {
  534. c.rw.RLock()
  535. defer c.rw.RUnlock()
  536. currentBlock := c.currentBlock()
  537. e := currentBlock.Rollup
  538. return int64(len(e.State.ExitRoots)) - 1
  539. }
  540. // EthLastBlock returns the last blockNum
  541. func (c *Client) EthLastBlock() (int64, error) {
  542. c.rw.RLock()
  543. defer c.rw.RUnlock()
  544. if c.blockNum < c.maxBlockNum {
  545. panic("blockNum has decreased. " +
  546. "After a rollback you must mine to reach the same or higher blockNum")
  547. }
  548. return c.blockNum, nil
  549. }
  550. // EthTransactionReceipt returns the transaction receipt of the given txHash
  551. func (c *Client) EthTransactionReceipt(ctx context.Context, txHash ethCommon.Hash) (*types.Receipt, error) {
  552. c.rw.RLock()
  553. defer c.rw.RUnlock()
  554. for i := int64(0); i < c.blockNum; i++ {
  555. b := c.blocks[i]
  556. _, ok := b.Rollup.Txs[txHash]
  557. if !ok {
  558. _, ok = b.Auction.Txs[txHash]
  559. }
  560. if ok {
  561. return &types.Receipt{
  562. TxHash: txHash,
  563. Status: types.ReceiptStatusSuccessful,
  564. BlockHash: b.Eth.Hash,
  565. BlockNumber: big.NewInt(b.Eth.BlockNum),
  566. }, nil
  567. }
  568. }
  569. return nil, nil
  570. }
  571. // CtlAddERC20 adds an ERC20 token to the blockchain.
  572. func (c *Client) CtlAddERC20(tokenAddr ethCommon.Address, constants eth.ERC20Consts) {
  573. nextBlock := c.nextBlock()
  574. e := nextBlock.Eth
  575. e.Tokens[tokenAddr] = constants
  576. }
  577. // EthERC20Consts returns the constants defined for a particular ERC20 Token instance.
  578. func (c *Client) EthERC20Consts(tokenAddr ethCommon.Address) (*eth.ERC20Consts, error) {
  579. currentBlock := c.currentBlock()
  580. e := currentBlock.Eth
  581. if constants, ok := e.Tokens[tokenAddr]; ok {
  582. return &constants, nil
  583. }
  584. return nil, tracerr.Wrap(fmt.Errorf("tokenAddr not found"))
  585. }
  586. // func newHeader(number *big.Int) *types.Header {
  587. // return &types.Header{
  588. // Number: number,
  589. // Time: uint64(number.Int64()),
  590. // }
  591. // }
  592. // EthHeaderByNumber returns the *types.Header for the given block number in a
  593. // deterministic way.
  594. // func (c *Client) EthHeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
  595. // return newHeader(number), nil
  596. // }
  597. // EthBlockByNumber returns the *common.Block for the given block number in a
  598. // deterministic way. If number == -1, the latests known block is returned.
  599. func (c *Client) EthBlockByNumber(ctx context.Context, blockNum int64) (*common.Block, error) {
  600. c.rw.RLock()
  601. defer c.rw.RUnlock()
  602. if blockNum > c.blockNum {
  603. return nil, ethereum.NotFound
  604. }
  605. if blockNum == -1 {
  606. blockNum = c.blockNum
  607. }
  608. block := c.blocks[blockNum]
  609. return &common.Block{
  610. Num: blockNum,
  611. Timestamp: time.Unix(block.Eth.Time, 0),
  612. Hash: block.Eth.Hash,
  613. ParentHash: block.Eth.ParentHash,
  614. }, nil
  615. }
  616. // EthAddress returns the ethereum address of the account loaded into the Client
  617. func (c *Client) EthAddress() (*ethCommon.Address, error) {
  618. if c.addr == nil {
  619. return nil, tracerr.Wrap(eth.ErrAccountNil)
  620. }
  621. return c.addr, nil
  622. }
  623. var errTODO = fmt.Errorf("TODO: Not implemented yet")
  624. //
  625. // Rollup
  626. //
  627. // CtlAddL1TxUser adds an L1TxUser to the L1UserTxs queue of the Rollup
  628. // func (c *Client) CtlAddL1TxUser(l1Tx *common.L1Tx) {
  629. // c.rw.Lock()
  630. // defer c.rw.Unlock()
  631. //
  632. // nextBlock := c.nextBlock()
  633. // r := nextBlock.Rollup
  634. // queue := r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  635. // if len(queue.L1TxQueue) >= eth.RollupConstMaxL1UserTx {
  636. // r.State.LastToForgeL1TxsNum++
  637. // r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
  638. // queue = r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  639. // }
  640. // if int64(l1Tx.FromIdx) > r.State.CurrentIdx {
  641. // panic("l1Tx.FromIdx > r.State.CurrentIdx")
  642. // }
  643. // if int(l1Tx.TokenID)+1 > len(r.State.TokenList) {
  644. // panic("l1Tx.TokenID + 1 > len(r.State.TokenList)")
  645. // }
  646. // queue.L1TxQueue = append(queue.L1TxQueue, *l1Tx)
  647. // r.Events.L1UserTx = append(r.Events.L1UserTx, eth.RollupEventL1UserTx{
  648. // L1Tx: *l1Tx,
  649. // ToForgeL1TxsNum: r.State.LastToForgeL1TxsNum,
  650. // Position: len(queue.L1TxQueue) - 1,
  651. // })
  652. // }
  653. // RollupL1UserTxERC20Permit is the interface to call the smart contract function
  654. 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) {
  655. log.Error("TODO")
  656. return nil, tracerr.Wrap(errTODO)
  657. }
  658. // RollupL1UserTxERC20ETH sends an L1UserTx to the Rollup.
  659. func (c *Client) RollupL1UserTxERC20ETH(
  660. fromBJJ *babyjub.PublicKey,
  661. fromIdx int64,
  662. depositAmount *big.Int,
  663. amount *big.Int,
  664. tokenID uint32,
  665. toIdx int64,
  666. ) (tx *types.Transaction, err error) {
  667. c.rw.Lock()
  668. defer c.rw.Unlock()
  669. cpy := c.nextBlock().copy()
  670. defer func() { c.revertIfErr(err, cpy) }()
  671. _, err = common.NewFloat16(amount)
  672. if err != nil {
  673. return nil, tracerr.Wrap(err)
  674. }
  675. _, err = common.NewFloat16(depositAmount)
  676. if err != nil {
  677. return nil, tracerr.Wrap(err)
  678. }
  679. nextBlock := c.nextBlock()
  680. r := nextBlock.Rollup
  681. queue := r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  682. if len(queue.L1TxQueue) >= common.RollupConstMaxL1UserTx {
  683. r.State.LastToForgeL1TxsNum++
  684. r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
  685. queue = r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum]
  686. }
  687. if fromIdx > r.State.CurrentIdx {
  688. panic("l1Tx.FromIdx > r.State.CurrentIdx")
  689. }
  690. if int(tokenID)+1 > len(r.State.TokenList) {
  691. panic("l1Tx.TokenID + 1 > len(r.State.TokenList)")
  692. }
  693. toForgeL1TxsNum := r.State.LastToForgeL1TxsNum
  694. l1Tx, err := common.NewL1Tx(&common.L1Tx{
  695. FromIdx: common.Idx(fromIdx),
  696. FromEthAddr: *c.addr,
  697. FromBJJ: fromBJJ,
  698. Amount: amount,
  699. DepositAmount: depositAmount,
  700. TokenID: common.TokenID(tokenID),
  701. ToIdx: common.Idx(toIdx),
  702. ToForgeL1TxsNum: &toForgeL1TxsNum,
  703. Position: len(queue.L1TxQueue),
  704. UserOrigin: true,
  705. })
  706. if err != nil {
  707. return nil, tracerr.Wrap(err)
  708. }
  709. queue.L1TxQueue = append(queue.L1TxQueue, *l1Tx)
  710. r.Events.L1UserTx = append(r.Events.L1UserTx, eth.RollupEventL1UserTx{
  711. L1UserTx: *l1Tx,
  712. })
  713. return r.addTransaction(c.newTransaction("l1UserTxERC20ETH", l1Tx)), nil
  714. }
  715. // RollupL1UserTxERC777 is the interface to call the smart contract function
  716. // func (c *Client) RollupL1UserTxERC777(fromBJJ *babyjub.PublicKey, fromIdx int64, depositAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error) {
  717. // log.Error("TODO")
  718. // return nil, errTODO
  719. // }
  720. // RollupRegisterTokensCount is the interface to call the smart contract function
  721. func (c *Client) RollupRegisterTokensCount() (*big.Int, error) {
  722. log.Error("TODO")
  723. return nil, tracerr.Wrap(errTODO)
  724. }
  725. // RollupLastForgedBatch is the interface to call the smart contract function
  726. func (c *Client) RollupLastForgedBatch() (int64, error) {
  727. c.rw.RLock()
  728. defer c.rw.RUnlock()
  729. currentBlock := c.currentBlock()
  730. e := currentBlock.Rollup
  731. return int64(len(e.State.ExitRoots)) - 1, nil
  732. }
  733. // RollupWithdrawCircuit is the interface to call the smart contract function
  734. 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) {
  735. log.Error("TODO")
  736. return nil, tracerr.Wrap(errTODO)
  737. }
  738. // RollupWithdrawMerkleProof is the interface to call the smart contract function
  739. 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) {
  740. c.rw.Lock()
  741. defer c.rw.Unlock()
  742. cpy := c.nextBlock().copy()
  743. defer func() { c.revertIfErr(err, cpy) }()
  744. nextBlock := c.nextBlock()
  745. r := nextBlock.Rollup
  746. if int(numExitRoot) >= len(r.State.ExitRoots) {
  747. return nil, tracerr.Wrap(fmt.Errorf("numExitRoot >= len(r.State.ExitRoots)"))
  748. }
  749. if _, ok := r.State.ExitNullifierMap[numExitRoot][idx]; ok {
  750. return nil, tracerr.Wrap(fmt.Errorf("exit already withdrawn"))
  751. }
  752. r.State.ExitNullifierMap[numExitRoot][idx] = true
  753. type data struct {
  754. BabyPubKey *babyjub.PublicKey
  755. TokenID uint32
  756. NumExitRoot int64
  757. Idx int64
  758. Amount *big.Int
  759. Siblings []*big.Int
  760. InstantWithdraw bool
  761. }
  762. tx = r.addTransaction(c.newTransaction("withdrawMerkleProof", data{
  763. BabyPubKey: babyPubKey,
  764. TokenID: tokenID,
  765. NumExitRoot: numExitRoot,
  766. Idx: idx,
  767. Amount: amount,
  768. Siblings: siblings,
  769. InstantWithdraw: instantWithdraw,
  770. }))
  771. r.Events.Withdraw = append(r.Events.Withdraw, eth.RollupEventWithdraw{
  772. Idx: uint64(idx),
  773. NumExitRoot: uint64(numExitRoot),
  774. InstantWithdraw: instantWithdraw,
  775. TxHash: tx.Hash(),
  776. })
  777. if !instantWithdraw {
  778. w := nextBlock.WDelayer
  779. w.deposit(tx.Hash(), *c.addr, r.State.TokenList[int(tokenID)], amount)
  780. }
  781. return tx, nil
  782. }
  783. type transactionData struct {
  784. Name string
  785. Value interface{}
  786. }
  787. func (c *Client) newTransaction(name string, value interface{}) *types.Transaction {
  788. eth := c.nextBlock().Eth
  789. nonce := eth.Nonce
  790. eth.Nonce++
  791. data, err := json.Marshal(transactionData{name, value})
  792. if err != nil {
  793. panic(err)
  794. }
  795. return types.NewTransaction(nonce, ethCommon.Address{}, nil, 0, nil,
  796. data)
  797. }
  798. // RollupForgeBatch is the interface to call the smart contract function
  799. func (c *Client) RollupForgeBatch(args *eth.RollupForgeBatchArgs) (tx *types.Transaction, err error) {
  800. c.rw.Lock()
  801. defer c.rw.Unlock()
  802. cpy := c.nextBlock().copy()
  803. defer func() { c.revertIfErr(err, cpy) }()
  804. if c.addr == nil {
  805. return nil, tracerr.Wrap(eth.ErrAccountNil)
  806. }
  807. a := c.nextBlock().Auction
  808. ok, err := a.canForge(*c.addr, a.Eth.BlockNum)
  809. if err != nil {
  810. return nil, tracerr.Wrap(err)
  811. }
  812. if !ok {
  813. return nil, tracerr.Wrap(fmt.Errorf(common.AuctionErrMsgCannotForge))
  814. }
  815. // TODO: Verify proof
  816. // Auction
  817. err = a.forge(*c.addr)
  818. if err != nil {
  819. return nil, tracerr.Wrap(err)
  820. }
  821. // TODO: If successful, store the tx in a successful array.
  822. // TODO: If failed, store the tx in a failed array.
  823. // TODO: Add method to move the tx to another block, reapply it there, and possibly go from successful to failed.
  824. return c.addBatch(args)
  825. }
  826. // CtlAddBatch adds forged batch to the Rollup, without checking any ZKProof
  827. func (c *Client) CtlAddBatch(args *eth.RollupForgeBatchArgs) {
  828. c.rw.Lock()
  829. defer c.rw.Unlock()
  830. if _, err := c.addBatch(args); err != nil {
  831. panic(err)
  832. }
  833. }
  834. func (c *Client) addBatch(args *eth.RollupForgeBatchArgs) (*types.Transaction, error) {
  835. nextBlock := c.nextBlock()
  836. r := nextBlock.Rollup
  837. r.State.StateRoot = args.NewStRoot
  838. if args.NewLastIdx < r.State.CurrentIdx {
  839. return nil, tracerr.Wrap(fmt.Errorf("args.NewLastIdx < r.State.CurrentIdx"))
  840. }
  841. r.State.CurrentIdx = args.NewLastIdx
  842. r.State.ExitNullifierMap[int64(len(r.State.ExitRoots))] = make(map[int64]bool)
  843. r.State.ExitRoots = append(r.State.ExitRoots, args.NewExitRoot)
  844. if args.L1Batch {
  845. r.State.CurrentToForgeL1TxsNum++
  846. if r.State.CurrentToForgeL1TxsNum == r.State.LastToForgeL1TxsNum {
  847. r.State.LastToForgeL1TxsNum++
  848. r.State.MapL1TxQueue[r.State.LastToForgeL1TxsNum] = eth.NewQueueStruct()
  849. }
  850. }
  851. ethTx := r.addTransaction(c.newTransaction("forgebatch", args))
  852. c.forgeBatchArgsPending[ethTx.Hash()] = &batch{*args, *c.addr}
  853. r.Events.ForgeBatch = append(r.Events.ForgeBatch, eth.RollupEventForgeBatch{
  854. BatchNum: int64(len(r.State.ExitRoots)) - 1,
  855. EthTxHash: ethTx.Hash(),
  856. L1UserTxsLen: uint16(len(args.L1UserTxs)),
  857. })
  858. return ethTx, nil
  859. }
  860. // RollupAddTokenSimple is a wrapper around RollupAddToken that automatically
  861. // sets `deadlie`.
  862. func (c *Client) RollupAddTokenSimple(tokenAddress ethCommon.Address, feeAddToken *big.Int) (tx *types.Transaction, err error) {
  863. return c.RollupAddToken(tokenAddress, feeAddToken, big.NewInt(9999)) //nolint:gomnd
  864. }
  865. // RollupAddToken is the interface to call the smart contract function
  866. func (c *Client) RollupAddToken(tokenAddress ethCommon.Address, feeAddToken *big.Int,
  867. deadline *big.Int) (tx *types.Transaction, err error) {
  868. c.rw.Lock()
  869. defer c.rw.Unlock()
  870. cpy := c.nextBlock().copy()
  871. defer func() { c.revertIfErr(err, cpy) }()
  872. if c.addr == nil {
  873. return nil, tracerr.Wrap(eth.ErrAccountNil)
  874. }
  875. nextBlock := c.nextBlock()
  876. r := nextBlock.Rollup
  877. if _, ok := r.State.TokenMap[tokenAddress]; ok {
  878. return nil, tracerr.Wrap(fmt.Errorf("Token %v already registered", tokenAddress))
  879. }
  880. if feeAddToken.Cmp(r.Vars.FeeAddToken) != 0 {
  881. return nil, tracerr.Wrap(fmt.Errorf("Expected fee: %v but got: %v", r.Vars.FeeAddToken, feeAddToken))
  882. }
  883. r.State.TokenMap[tokenAddress] = true
  884. r.State.TokenList = append(r.State.TokenList, tokenAddress)
  885. r.Events.AddToken = append(r.Events.AddToken, eth.RollupEventAddToken{TokenAddress: tokenAddress,
  886. TokenID: uint32(len(r.State.TokenList) - 1)})
  887. return r.addTransaction(c.newTransaction("addtoken", tokenAddress)), nil
  888. }
  889. // RollupGetCurrentTokens is the interface to call the smart contract function
  890. func (c *Client) RollupGetCurrentTokens() (*big.Int, error) {
  891. c.rw.RLock()
  892. defer c.rw.RUnlock()
  893. log.Error("TODO")
  894. return nil, tracerr.Wrap(errTODO)
  895. }
  896. // RollupUpdateForgeL1L2BatchTimeout is the interface to call the smart contract function
  897. func (c *Client) RollupUpdateForgeL1L2BatchTimeout(newForgeL1Timeout int64) (tx *types.Transaction, err error) {
  898. c.rw.Lock()
  899. defer c.rw.Unlock()
  900. cpy := c.nextBlock().copy()
  901. defer func() { c.revertIfErr(err, cpy) }()
  902. if c.addr == nil {
  903. return nil, tracerr.Wrap(eth.ErrAccountNil)
  904. }
  905. nextBlock := c.nextBlock()
  906. r := nextBlock.Rollup
  907. r.Vars.ForgeL1L2BatchTimeout = newForgeL1Timeout
  908. r.Events.UpdateForgeL1L2BatchTimeout = append(r.Events.UpdateForgeL1L2BatchTimeout,
  909. eth.RollupEventUpdateForgeL1L2BatchTimeout{NewForgeL1L2BatchTimeout: newForgeL1Timeout})
  910. return r.addTransaction(c.newTransaction("updateForgeL1L2BatchTimeout", newForgeL1Timeout)), nil
  911. }
  912. // RollupUpdateFeeAddToken is the interface to call the smart contract function
  913. func (c *Client) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (tx *types.Transaction, err error) {
  914. c.rw.Lock()
  915. defer c.rw.Unlock()
  916. cpy := c.nextBlock().copy()
  917. defer func() { c.revertIfErr(err, cpy) }()
  918. if c.addr == nil {
  919. return nil, tracerr.Wrap(eth.ErrAccountNil)
  920. }
  921. log.Error("TODO")
  922. return nil, tracerr.Wrap(errTODO)
  923. }
  924. // RollupUpdateTokensHEZ is the interface to call the smart contract function
  925. // func (c *Client) RollupUpdateTokensHEZ(newTokenHEZ ethCommon.Address) (tx *types.Transaction, err error) {
  926. // c.rw.Lock()
  927. // defer c.rw.Unlock()
  928. // cpy := c.nextBlock().copy()
  929. // defer func() { c.revertIfErr(err, cpy) }()
  930. //
  931. // log.Error("TODO")
  932. // return nil, errTODO
  933. // }
  934. // RollupUpdateGovernance is the interface to call the smart contract function
  935. // func (c *Client) RollupUpdateGovernance() (*types.Transaction, error) { // TODO (Not defined in Hermez.sol)
  936. // return nil, errTODO
  937. // }
  938. // RollupConstants returns the Constants of the Rollup Smart Contract
  939. func (c *Client) RollupConstants() (*common.RollupConstants, error) {
  940. c.rw.RLock()
  941. defer c.rw.RUnlock()
  942. return c.rollupConstants, nil
  943. }
  944. // RollupEventsByBlock returns the events in a block that happened in the Rollup Smart Contract
  945. func (c *Client) RollupEventsByBlock(blockNum int64) (*eth.RollupEvents, *ethCommon.Hash, error) {
  946. c.rw.RLock()
  947. defer c.rw.RUnlock()
  948. block, ok := c.blocks[blockNum]
  949. if !ok {
  950. return nil, nil, tracerr.Wrap(fmt.Errorf("Block %v doesn't exist", blockNum))
  951. }
  952. return &block.Rollup.Events, &block.Eth.Hash, nil
  953. }
  954. // RollupEventInit returns the initialize event with its corresponding block number
  955. func (c *Client) RollupEventInit() (*eth.RollupEventInitialize, int64, error) {
  956. vars := c.blocks[0].Rollup.Vars
  957. return &eth.RollupEventInitialize{
  958. ForgeL1L2BatchTimeout: uint8(vars.ForgeL1L2BatchTimeout),
  959. FeeAddToken: vars.FeeAddToken,
  960. WithdrawalDelay: vars.WithdrawalDelay,
  961. }, 1, nil
  962. }
  963. // RollupForgeBatchArgs returns the arguments used in a ForgeBatch call in the Rollup Smart Contract in the given transaction
  964. func (c *Client) RollupForgeBatchArgs(ethTxHash ethCommon.Hash, l1UserTxsLen uint16) (*eth.RollupForgeBatchArgs, *ethCommon.Address, error) {
  965. c.rw.RLock()
  966. defer c.rw.RUnlock()
  967. batch, ok := c.forgeBatchArgs[ethTxHash]
  968. if !ok {
  969. return nil, nil, tracerr.Wrap(fmt.Errorf("transaction not found"))
  970. }
  971. return &batch.ForgeBatchArgs, &batch.Sender, nil
  972. }
  973. //
  974. // Auction
  975. //
  976. // AuctionSetSlotDeadline is the interface to call the smart contract function
  977. func (c *Client) AuctionSetSlotDeadline(newDeadline uint8) (tx *types.Transaction, err error) {
  978. c.rw.Lock()
  979. defer c.rw.Unlock()
  980. cpy := c.nextBlock().copy()
  981. defer func() { c.revertIfErr(err, cpy) }()
  982. if c.addr == nil {
  983. return nil, tracerr.Wrap(eth.ErrAccountNil)
  984. }
  985. log.Error("TODO")
  986. return nil, tracerr.Wrap(errTODO)
  987. }
  988. // AuctionGetSlotDeadline is the interface to call the smart contract function
  989. func (c *Client) AuctionGetSlotDeadline() (uint8, error) {
  990. c.rw.RLock()
  991. defer c.rw.RUnlock()
  992. log.Error("TODO")
  993. return 0, tracerr.Wrap(errTODO)
  994. }
  995. // AuctionSetOpenAuctionSlots is the interface to call the smart contract function
  996. func (c *Client) AuctionSetOpenAuctionSlots(newOpenAuctionSlots uint16) (tx *types.Transaction, err error) {
  997. c.rw.Lock()
  998. defer c.rw.Unlock()
  999. cpy := c.nextBlock().copy()
  1000. defer func() { c.revertIfErr(err, cpy) }()
  1001. if c.addr == nil {
  1002. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1003. }
  1004. nextBlock := c.nextBlock()
  1005. a := nextBlock.Auction
  1006. a.Vars.OpenAuctionSlots = newOpenAuctionSlots
  1007. a.Events.NewOpenAuctionSlots = append(a.Events.NewOpenAuctionSlots,
  1008. eth.AuctionEventNewOpenAuctionSlots{NewOpenAuctionSlots: newOpenAuctionSlots})
  1009. return a.addTransaction(c.newTransaction("setOpenAuctionSlots", newOpenAuctionSlots)), nil
  1010. }
  1011. // AuctionGetOpenAuctionSlots is the interface to call the smart contract function
  1012. func (c *Client) AuctionGetOpenAuctionSlots() (uint16, error) {
  1013. c.rw.RLock()
  1014. defer c.rw.RUnlock()
  1015. log.Error("TODO")
  1016. return 0, tracerr.Wrap(errTODO)
  1017. }
  1018. // AuctionSetClosedAuctionSlots is the interface to call the smart contract function
  1019. func (c *Client) AuctionSetClosedAuctionSlots(newClosedAuctionSlots uint16) (tx *types.Transaction, err error) {
  1020. c.rw.Lock()
  1021. defer c.rw.Unlock()
  1022. cpy := c.nextBlock().copy()
  1023. defer func() { c.revertIfErr(err, cpy) }()
  1024. if c.addr == nil {
  1025. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1026. }
  1027. log.Error("TODO")
  1028. return nil, tracerr.Wrap(errTODO)
  1029. }
  1030. // AuctionGetClosedAuctionSlots is the interface to call the smart contract function
  1031. func (c *Client) AuctionGetClosedAuctionSlots() (uint16, error) {
  1032. c.rw.RLock()
  1033. defer c.rw.RUnlock()
  1034. log.Error("TODO")
  1035. return 0, tracerr.Wrap(errTODO)
  1036. }
  1037. // AuctionSetOutbidding is the interface to call the smart contract function
  1038. func (c *Client) AuctionSetOutbidding(newOutbidding uint16) (tx *types.Transaction, err error) {
  1039. c.rw.Lock()
  1040. defer c.rw.Unlock()
  1041. cpy := c.nextBlock().copy()
  1042. defer func() { c.revertIfErr(err, cpy) }()
  1043. if c.addr == nil {
  1044. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1045. }
  1046. log.Error("TODO")
  1047. return nil, tracerr.Wrap(errTODO)
  1048. }
  1049. // AuctionGetOutbidding is the interface to call the smart contract function
  1050. func (c *Client) AuctionGetOutbidding() (uint16, error) {
  1051. c.rw.RLock()
  1052. defer c.rw.RUnlock()
  1053. log.Error("TODO")
  1054. return 0, tracerr.Wrap(errTODO)
  1055. }
  1056. // AuctionSetAllocationRatio is the interface to call the smart contract function
  1057. func (c *Client) AuctionSetAllocationRatio(newAllocationRatio [3]uint16) (tx *types.Transaction, err error) {
  1058. c.rw.Lock()
  1059. defer c.rw.Unlock()
  1060. cpy := c.nextBlock().copy()
  1061. defer func() { c.revertIfErr(err, cpy) }()
  1062. if c.addr == nil {
  1063. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1064. }
  1065. log.Error("TODO")
  1066. return nil, tracerr.Wrap(errTODO)
  1067. }
  1068. // AuctionGetAllocationRatio is the interface to call the smart contract function
  1069. func (c *Client) AuctionGetAllocationRatio() ([3]uint16, error) {
  1070. c.rw.RLock()
  1071. defer c.rw.RUnlock()
  1072. log.Error("TODO")
  1073. return [3]uint16{}, tracerr.Wrap(errTODO)
  1074. }
  1075. // AuctionSetDonationAddress is the interface to call the smart contract function
  1076. func (c *Client) AuctionSetDonationAddress(newDonationAddress ethCommon.Address) (tx *types.Transaction, err error) {
  1077. c.rw.Lock()
  1078. defer c.rw.Unlock()
  1079. cpy := c.nextBlock().copy()
  1080. defer func() { c.revertIfErr(err, cpy) }()
  1081. if c.addr == nil {
  1082. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1083. }
  1084. log.Error("TODO")
  1085. return nil, tracerr.Wrap(errTODO)
  1086. }
  1087. // AuctionGetDonationAddress is the interface to call the smart contract function
  1088. func (c *Client) AuctionGetDonationAddress() (*ethCommon.Address, error) {
  1089. c.rw.RLock()
  1090. defer c.rw.RUnlock()
  1091. log.Error("TODO")
  1092. return nil, tracerr.Wrap(errTODO)
  1093. }
  1094. // AuctionSetBootCoordinator is the interface to call the smart contract function
  1095. func (c *Client) AuctionSetBootCoordinator(newBootCoordinator ethCommon.Address, newBootCoordinatorURL string) (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. // AuctionGetBootCoordinator is the interface to call the smart contract function
  1107. func (c *Client) AuctionGetBootCoordinator() (*ethCommon.Address, error) {
  1108. c.rw.RLock()
  1109. defer c.rw.RUnlock()
  1110. currentBlock := c.currentBlock()
  1111. a := currentBlock.Auction
  1112. return &a.Vars.BootCoordinator, nil
  1113. }
  1114. // AuctionChangeDefaultSlotSetBid is the interface to call the smart contract function
  1115. func (c *Client) AuctionChangeDefaultSlotSetBid(slotSet int64, newInitialMinBid *big.Int) (tx *types.Transaction, err error) {
  1116. c.rw.Lock()
  1117. defer c.rw.Unlock()
  1118. cpy := c.nextBlock().copy()
  1119. defer func() { c.revertIfErr(err, cpy) }()
  1120. if c.addr == nil {
  1121. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1122. }
  1123. log.Error("TODO")
  1124. return nil, tracerr.Wrap(errTODO)
  1125. }
  1126. // AuctionSetCoordinator is the interface to call the smart contract function
  1127. func (c *Client) AuctionSetCoordinator(forger ethCommon.Address, URL string) (tx *types.Transaction, err error) {
  1128. c.rw.Lock()
  1129. defer c.rw.Unlock()
  1130. cpy := c.nextBlock().copy()
  1131. defer func() { c.revertIfErr(err, cpy) }()
  1132. if c.addr == nil {
  1133. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1134. }
  1135. nextBlock := c.nextBlock()
  1136. a := nextBlock.Auction
  1137. a.State.Coordinators[*c.addr] = &eth.Coordinator{
  1138. Forger: forger,
  1139. URL: URL,
  1140. }
  1141. a.Events.SetCoordinator = append(a.Events.SetCoordinator,
  1142. eth.AuctionEventSetCoordinator{
  1143. BidderAddress: *c.addr,
  1144. ForgerAddress: forger,
  1145. CoordinatorURL: URL,
  1146. })
  1147. type data struct {
  1148. BidderAddress ethCommon.Address
  1149. ForgerAddress ethCommon.Address
  1150. URL string
  1151. }
  1152. return a.addTransaction(c.newTransaction("registercoordinator", data{*c.addr, forger, URL})), nil
  1153. }
  1154. // AuctionIsRegisteredCoordinator is the interface to call the smart contract function
  1155. func (c *Client) AuctionIsRegisteredCoordinator(forgerAddress ethCommon.Address) (bool, error) {
  1156. c.rw.RLock()
  1157. defer c.rw.RUnlock()
  1158. log.Error("TODO")
  1159. return false, tracerr.Wrap(errTODO)
  1160. }
  1161. // AuctionUpdateCoordinatorInfo is the interface to call the smart contract function
  1162. func (c *Client) AuctionUpdateCoordinatorInfo(forgerAddress ethCommon.Address, newWithdrawAddress ethCommon.Address, newURL string) (tx *types.Transaction, err error) {
  1163. c.rw.Lock()
  1164. defer c.rw.Unlock()
  1165. cpy := c.nextBlock().copy()
  1166. defer func() { c.revertIfErr(err, cpy) }()
  1167. if c.addr == nil {
  1168. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1169. }
  1170. log.Error("TODO")
  1171. return nil, tracerr.Wrap(errTODO)
  1172. }
  1173. // AuctionGetSlotNumber is the interface to call the smart contract function
  1174. func (c *Client) AuctionGetSlotNumber(blockNum int64) (int64, error) {
  1175. c.rw.RLock()
  1176. defer c.rw.RUnlock()
  1177. currentBlock := c.currentBlock()
  1178. a := currentBlock.Auction
  1179. return a.getSlotNumber(blockNum), nil
  1180. }
  1181. // AuctionGetCurrentSlotNumber is the interface to call the smart contract function
  1182. func (c *Client) AuctionGetCurrentSlotNumber() (int64, error) {
  1183. c.rw.RLock()
  1184. defer c.rw.RUnlock()
  1185. log.Error("TODO")
  1186. return 0, tracerr.Wrap(errTODO)
  1187. }
  1188. // AuctionGetMinBidBySlot is the interface to call the smart contract function
  1189. func (c *Client) AuctionGetMinBidBySlot(slot int64) (*big.Int, error) {
  1190. c.rw.RLock()
  1191. defer c.rw.RUnlock()
  1192. log.Error("TODO")
  1193. return nil, tracerr.Wrap(errTODO)
  1194. }
  1195. // AuctionGetDefaultSlotSetBid is the interface to call the smart contract function
  1196. func (c *Client) AuctionGetDefaultSlotSetBid(slotSet uint8) (*big.Int, error) {
  1197. c.rw.RLock()
  1198. defer c.rw.RUnlock()
  1199. log.Error("TODO")
  1200. return nil, tracerr.Wrap(errTODO)
  1201. }
  1202. // AuctionGetSlotSet is the interface to call the smart contract function
  1203. func (c *Client) AuctionGetSlotSet(slot int64) (*big.Int, error) {
  1204. c.rw.RLock()
  1205. defer c.rw.RUnlock()
  1206. log.Error("TODO")
  1207. return nil, tracerr.Wrap(errTODO)
  1208. }
  1209. // AuctionTokensReceived is the interface to call the smart contract function
  1210. // func (c *Client) AuctionTokensReceived(operator, from, to ethCommon.Address, amount *big.Int, userData, operatorData []byte) error {
  1211. // return errTODO
  1212. // }
  1213. // AuctionBidSimple is a wrapper around AuctionBid that automatically sets `amount` and `deadline`.
  1214. func (c *Client) AuctionBidSimple(slot int64, bidAmount *big.Int) (tx *types.Transaction, err error) {
  1215. return c.AuctionBid(bidAmount, slot, bidAmount, big.NewInt(99999)) //nolint:gomnd
  1216. }
  1217. // AuctionBid is the interface to call the smart contract function. This
  1218. // implementation behaves as if any address has infinite tokens.
  1219. func (c *Client) AuctionBid(amount *big.Int, slot int64, bidAmount *big.Int,
  1220. deadline *big.Int) (tx *types.Transaction, err error) {
  1221. c.rw.Lock()
  1222. defer c.rw.Unlock()
  1223. cpy := c.nextBlock().copy()
  1224. defer func() { func() { c.revertIfErr(err, cpy) }() }()
  1225. if c.addr == nil {
  1226. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1227. }
  1228. nextBlock := c.nextBlock()
  1229. a := nextBlock.Auction
  1230. if slot < a.getCurrentSlotNumber()+int64(a.Vars.ClosedAuctionSlots) {
  1231. return nil, tracerr.Wrap(errBidClosed)
  1232. }
  1233. if slot >= a.getCurrentSlotNumber()+int64(a.Vars.ClosedAuctionSlots)+int64(a.Vars.OpenAuctionSlots) {
  1234. return nil, tracerr.Wrap(errBidNotOpen)
  1235. }
  1236. minBid, err := a.getMinBidBySlot(slot)
  1237. if err != nil {
  1238. return nil, tracerr.Wrap(err)
  1239. }
  1240. if bidAmount.Cmp(minBid) == -1 {
  1241. return nil, tracerr.Wrap(errBidBelowMin)
  1242. }
  1243. if _, ok := a.State.Coordinators[*c.addr]; !ok {
  1244. return nil, tracerr.Wrap(errCoordNotReg)
  1245. }
  1246. slotState, ok := a.State.Slots[slot]
  1247. if !ok {
  1248. slotState = eth.NewSlotState()
  1249. a.State.Slots[slot] = slotState
  1250. }
  1251. slotState.Bidder = *c.addr
  1252. slotState.BidAmount = bidAmount
  1253. a.Events.NewBid = append(a.Events.NewBid,
  1254. eth.AuctionEventNewBid{Slot: slot, BidAmount: bidAmount, Bidder: *c.addr})
  1255. type data struct {
  1256. Slot int64
  1257. BidAmount *big.Int
  1258. Bidder ethCommon.Address
  1259. }
  1260. return a.addTransaction(c.newTransaction("bid", data{slot, bidAmount, *c.addr})), nil
  1261. }
  1262. // AuctionMultiBid is the interface to call the smart contract function. This
  1263. // implementation behaves as if any address has infinite tokens.
  1264. func (c *Client) AuctionMultiBid(amount *big.Int, startingSlot int64, endingSlot int64, slotSet [6]bool,
  1265. maxBid, closedMinBid, deadline *big.Int) (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. // AuctionCanForge is the interface to call the smart contract function
  1277. func (c *Client) AuctionCanForge(forger ethCommon.Address, blockNum int64) (bool, error) {
  1278. c.rw.RLock()
  1279. defer c.rw.RUnlock()
  1280. currentBlock := c.currentBlock()
  1281. a := currentBlock.Auction
  1282. return a.canForge(forger, blockNum)
  1283. }
  1284. // AuctionForge is the interface to call the smart contract function
  1285. func (c *Client) AuctionForge(forger ethCommon.Address) (tx *types.Transaction, err error) {
  1286. c.rw.Lock()
  1287. defer c.rw.Unlock()
  1288. cpy := c.nextBlock().copy()
  1289. defer func() { c.revertIfErr(err, cpy) }()
  1290. if c.addr == nil {
  1291. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1292. }
  1293. log.Error("TODO")
  1294. return nil, tracerr.Wrap(errTODO)
  1295. }
  1296. // AuctionClaimHEZ is the interface to call the smart contract function
  1297. func (c *Client) AuctionClaimHEZ() (tx *types.Transaction, err error) {
  1298. c.rw.Lock()
  1299. defer c.rw.Unlock()
  1300. cpy := c.nextBlock().copy()
  1301. defer func() { c.revertIfErr(err, cpy) }()
  1302. if c.addr == nil {
  1303. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1304. }
  1305. log.Error("TODO")
  1306. return nil, tracerr.Wrap(errTODO)
  1307. }
  1308. // AuctionGetClaimableHEZ is the interface to call the smart contract function
  1309. func (c *Client) AuctionGetClaimableHEZ(bidder ethCommon.Address) (*big.Int, error) {
  1310. c.rw.RLock()
  1311. defer c.rw.RUnlock()
  1312. log.Error("TODO")
  1313. return nil, tracerr.Wrap(errTODO)
  1314. }
  1315. // AuctionConstants returns the Constants of the Auction Smart Contract
  1316. func (c *Client) AuctionConstants() (*common.AuctionConstants, error) {
  1317. c.rw.RLock()
  1318. defer c.rw.RUnlock()
  1319. return c.auctionConstants, nil
  1320. }
  1321. // AuctionEventsByBlock returns the events in a block that happened in the Auction Smart Contract
  1322. func (c *Client) AuctionEventsByBlock(blockNum int64) (*eth.AuctionEvents, *ethCommon.Hash, error) {
  1323. c.rw.RLock()
  1324. defer c.rw.RUnlock()
  1325. block, ok := c.blocks[blockNum]
  1326. if !ok {
  1327. return nil, nil, tracerr.Wrap(fmt.Errorf("Block %v doesn't exist", blockNum))
  1328. }
  1329. return &block.Auction.Events, &block.Eth.Hash, nil
  1330. }
  1331. // AuctionEventInit returns the initialize event with its corresponding block number
  1332. func (c *Client) AuctionEventInit() (*eth.AuctionEventInitialize, int64, error) {
  1333. vars := c.blocks[0].Auction.Vars
  1334. return &eth.AuctionEventInitialize{
  1335. DonationAddress: vars.DonationAddress,
  1336. BootCoordinatorAddress: vars.BootCoordinator,
  1337. BootCoordinatorURL: vars.BootCoordinatorURL,
  1338. Outbidding: vars.Outbidding,
  1339. SlotDeadline: vars.SlotDeadline,
  1340. ClosedAuctionSlots: vars.ClosedAuctionSlots,
  1341. OpenAuctionSlots: vars.OpenAuctionSlots,
  1342. AllocationRatio: vars.AllocationRatio,
  1343. }, 1, nil
  1344. }
  1345. //
  1346. // WDelayer
  1347. //
  1348. // WDelayerGetHermezGovernanceAddress is the interface to call the smart contract function
  1349. func (c *Client) WDelayerGetHermezGovernanceAddress() (*ethCommon.Address, error) {
  1350. c.rw.RLock()
  1351. defer c.rw.RUnlock()
  1352. log.Error("TODO")
  1353. return nil, tracerr.Wrap(errTODO)
  1354. }
  1355. // WDelayerTransferGovernance is the interface to call the smart contract function
  1356. func (c *Client) WDelayerTransferGovernance(newAddress ethCommon.Address) (tx *types.Transaction, err error) {
  1357. c.rw.Lock()
  1358. defer c.rw.Unlock()
  1359. cpy := c.nextBlock().copy()
  1360. defer func() { c.revertIfErr(err, cpy) }()
  1361. if c.addr == nil {
  1362. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1363. }
  1364. log.Error("TODO")
  1365. return nil, tracerr.Wrap(errTODO)
  1366. }
  1367. // WDelayerClaimGovernance is the interface to call the smart contract function
  1368. func (c *Client) WDelayerClaimGovernance() (tx *types.Transaction, err error) {
  1369. c.rw.Lock()
  1370. defer c.rw.Unlock()
  1371. cpy := c.nextBlock().copy()
  1372. defer func() { c.revertIfErr(err, cpy) }()
  1373. if c.addr == nil {
  1374. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1375. }
  1376. log.Error("TODO")
  1377. return nil, tracerr.Wrap(errTODO)
  1378. }
  1379. // WDelayerGetEmergencyCouncil is the interface to call the smart contract function
  1380. func (c *Client) WDelayerGetEmergencyCouncil() (*ethCommon.Address, error) {
  1381. c.rw.RLock()
  1382. defer c.rw.RUnlock()
  1383. log.Error("TODO")
  1384. return nil, tracerr.Wrap(errTODO)
  1385. }
  1386. // WDelayerTransferEmergencyCouncil is the interface to call the smart contract function
  1387. func (c *Client) WDelayerTransferEmergencyCouncil(newAddress ethCommon.Address) (tx *types.Transaction, err error) {
  1388. c.rw.Lock()
  1389. defer c.rw.Unlock()
  1390. cpy := c.nextBlock().copy()
  1391. defer func() { c.revertIfErr(err, cpy) }()
  1392. if c.addr == nil {
  1393. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1394. }
  1395. log.Error("TODO")
  1396. return nil, tracerr.Wrap(errTODO)
  1397. }
  1398. // WDelayerClaimEmergencyCouncil is the interface to call the smart contract function
  1399. func (c *Client) WDelayerClaimEmergencyCouncil() (tx *types.Transaction, err error) {
  1400. c.rw.Lock()
  1401. defer c.rw.Unlock()
  1402. cpy := c.nextBlock().copy()
  1403. defer func() { c.revertIfErr(err, cpy) }()
  1404. if c.addr == nil {
  1405. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1406. }
  1407. log.Error("TODO")
  1408. return nil, tracerr.Wrap(errTODO)
  1409. }
  1410. // WDelayerIsEmergencyMode is the interface to call the smart contract function
  1411. func (c *Client) WDelayerIsEmergencyMode() (bool, error) {
  1412. c.rw.RLock()
  1413. defer c.rw.RUnlock()
  1414. log.Error("TODO")
  1415. return false, tracerr.Wrap(errTODO)
  1416. }
  1417. // WDelayerGetWithdrawalDelay is the interface to call the smart contract function
  1418. func (c *Client) WDelayerGetWithdrawalDelay() (int64, error) {
  1419. c.rw.RLock()
  1420. defer c.rw.RUnlock()
  1421. log.Error("TODO")
  1422. return 0, tracerr.Wrap(errTODO)
  1423. }
  1424. // WDelayerGetEmergencyModeStartingTime is the interface to call the smart contract function
  1425. func (c *Client) WDelayerGetEmergencyModeStartingTime() (int64, error) {
  1426. c.rw.RLock()
  1427. defer c.rw.RUnlock()
  1428. log.Error("TODO")
  1429. return 0, tracerr.Wrap(errTODO)
  1430. }
  1431. // WDelayerEnableEmergencyMode is the interface to call the smart contract function
  1432. func (c *Client) WDelayerEnableEmergencyMode() (tx *types.Transaction, err error) {
  1433. c.rw.Lock()
  1434. defer c.rw.Unlock()
  1435. cpy := c.nextBlock().copy()
  1436. defer func() { c.revertIfErr(err, cpy) }()
  1437. if c.addr == nil {
  1438. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1439. }
  1440. log.Error("TODO")
  1441. return nil, tracerr.Wrap(errTODO)
  1442. }
  1443. // WDelayerChangeWithdrawalDelay is the interface to call the smart contract function
  1444. func (c *Client) WDelayerChangeWithdrawalDelay(newWithdrawalDelay uint64) (tx *types.Transaction, err error) {
  1445. c.rw.Lock()
  1446. defer c.rw.Unlock()
  1447. cpy := c.nextBlock().copy()
  1448. defer func() { c.revertIfErr(err, cpy) }()
  1449. if c.addr == nil {
  1450. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1451. }
  1452. nextBlock := c.nextBlock()
  1453. w := nextBlock.WDelayer
  1454. w.Vars.WithdrawalDelay = newWithdrawalDelay
  1455. w.Events.NewWithdrawalDelay = append(w.Events.NewWithdrawalDelay,
  1456. eth.WDelayerEventNewWithdrawalDelay{WithdrawalDelay: newWithdrawalDelay})
  1457. return w.addTransaction(c.newTransaction("changeWithdrawalDelay", newWithdrawalDelay)), nil
  1458. }
  1459. // WDelayerDepositInfo is the interface to call the smart contract function
  1460. func (c *Client) WDelayerDepositInfo(owner, token ethCommon.Address) (eth.DepositState, error) {
  1461. c.rw.RLock()
  1462. defer c.rw.RUnlock()
  1463. log.Error("TODO")
  1464. return eth.DepositState{}, tracerr.Wrap(errTODO)
  1465. }
  1466. // WDelayerDeposit is the interface to call the smart contract function
  1467. func (c *Client) WDelayerDeposit(onwer, token ethCommon.Address, amount *big.Int) (tx *types.Transaction, err error) {
  1468. c.rw.Lock()
  1469. defer c.rw.Unlock()
  1470. cpy := c.nextBlock().copy()
  1471. defer func() { c.revertIfErr(err, cpy) }()
  1472. if c.addr == nil {
  1473. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1474. }
  1475. log.Error("TODO")
  1476. return nil, tracerr.Wrap(errTODO)
  1477. }
  1478. // WDelayerWithdrawal is the interface to call the smart contract function
  1479. func (c *Client) WDelayerWithdrawal(owner, token ethCommon.Address) (tx *types.Transaction, err error) {
  1480. c.rw.Lock()
  1481. defer c.rw.Unlock()
  1482. cpy := c.nextBlock().copy()
  1483. defer func() { c.revertIfErr(err, cpy) }()
  1484. if c.addr == nil {
  1485. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1486. }
  1487. log.Error("TODO")
  1488. return nil, tracerr.Wrap(errTODO)
  1489. }
  1490. // WDelayerEscapeHatchWithdrawal is the interface to call the smart contract function
  1491. func (c *Client) WDelayerEscapeHatchWithdrawal(to, token ethCommon.Address, amount *big.Int) (tx *types.Transaction, err error) {
  1492. c.rw.Lock()
  1493. defer c.rw.Unlock()
  1494. cpy := c.nextBlock().copy()
  1495. defer func() { c.revertIfErr(err, cpy) }()
  1496. if c.addr == nil {
  1497. return nil, tracerr.Wrap(eth.ErrAccountNil)
  1498. }
  1499. log.Error("TODO")
  1500. return nil, tracerr.Wrap(errTODO)
  1501. }
  1502. // WDelayerEventsByBlock returns the events in a block that happened in the WDelayer Contract
  1503. func (c *Client) WDelayerEventsByBlock(blockNum int64) (*eth.WDelayerEvents, *ethCommon.Hash, error) {
  1504. c.rw.RLock()
  1505. defer c.rw.RUnlock()
  1506. block, ok := c.blocks[blockNum]
  1507. if !ok {
  1508. return nil, nil, tracerr.Wrap(fmt.Errorf("Block %v doesn't exist", blockNum))
  1509. }
  1510. return &block.WDelayer.Events, &block.Eth.Hash, nil
  1511. }
  1512. // WDelayerConstants returns the Constants of the WDelayer Contract
  1513. func (c *Client) WDelayerConstants() (*common.WDelayerConstants, error) {
  1514. c.rw.RLock()
  1515. defer c.rw.RUnlock()
  1516. return c.wDelayerConstants, nil
  1517. }
  1518. // WDelayerEventInit returns the initialize event with its corresponding block number
  1519. func (c *Client) WDelayerEventInit() (*eth.WDelayerEventInitialize, int64, error) {
  1520. vars := c.blocks[0].WDelayer.Vars
  1521. return &eth.WDelayerEventInitialize{
  1522. InitialWithdrawalDelay: vars.WithdrawalDelay,
  1523. InitialHermezGovernanceAddress: vars.HermezGovernanceAddress,
  1524. InitialEmergencyCouncil: vars.EmergencyCouncilAddress,
  1525. }, 1, nil
  1526. }
  1527. // CtlAddBlocks adds block data to the smarts contracts. The added blocks will
  1528. // appear as mined. Not thread safe.
  1529. func (c *Client) CtlAddBlocks(blocks []common.BlockData) (err error) {
  1530. // NOTE: We don't lock because internally we call public functions that
  1531. // lock already.
  1532. for _, block := range blocks {
  1533. nextBlock := c.nextBlock()
  1534. rollup := nextBlock.Rollup
  1535. auction := nextBlock.Auction
  1536. for _, token := range block.Rollup.AddedTokens {
  1537. if _, err := c.RollupAddTokenSimple(token.EthAddr, rollup.Vars.FeeAddToken); err != nil {
  1538. return tracerr.Wrap(err)
  1539. }
  1540. }
  1541. for _, tx := range block.Rollup.L1UserTxs {
  1542. c.CtlSetAddr(tx.FromEthAddr)
  1543. if _, err := c.RollupL1UserTxERC20ETH(tx.FromBJJ, int64(tx.FromIdx), tx.DepositAmount, tx.Amount,
  1544. uint32(tx.TokenID), int64(tx.ToIdx)); err != nil {
  1545. return tracerr.Wrap(err)
  1546. }
  1547. }
  1548. c.CtlSetAddr(auction.Vars.BootCoordinator)
  1549. for _, batch := range block.Rollup.Batches {
  1550. if _, err := c.RollupForgeBatch(&eth.RollupForgeBatchArgs{
  1551. NewLastIdx: batch.Batch.LastIdx,
  1552. NewStRoot: batch.Batch.StateRoot,
  1553. NewExitRoot: batch.Batch.ExitRoot,
  1554. L1CoordinatorTxs: batch.L1CoordinatorTxs,
  1555. L1CoordinatorTxsAuths: [][]byte{}, // Intentionally empty
  1556. L2TxsData: batch.L2Txs,
  1557. FeeIdxCoordinator: batch.Batch.FeeIdxsCoordinator,
  1558. // Circuit selector
  1559. VerifierIdx: 0, // Intentionally empty
  1560. L1Batch: batch.L1Batch,
  1561. ProofA: [2]*big.Int{}, // Intentionally empty
  1562. ProofB: [2][2]*big.Int{}, // Intentionally empty
  1563. ProofC: [2]*big.Int{}, // Intentionally empty
  1564. }); err != nil {
  1565. return tracerr.Wrap(err)
  1566. }
  1567. }
  1568. // Mine block and sync
  1569. c.CtlMineBlock()
  1570. }
  1571. return nil
  1572. }