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.

671 lines
18 KiB

4 years ago
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
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.
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 api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "math/big"
  10. "net/http"
  11. "os"
  12. "strconv"
  13. "testing"
  14. "time"
  15. ethCommon "github.com/ethereum/go-ethereum/common"
  16. swagger "github.com/getkin/kin-openapi/openapi3filter"
  17. "github.com/gin-gonic/gin"
  18. "github.com/hermeznetwork/hermez-node/common"
  19. "github.com/hermeznetwork/hermez-node/db"
  20. "github.com/hermeznetwork/hermez-node/db/historydb"
  21. "github.com/hermeznetwork/hermez-node/db/l2db"
  22. "github.com/hermeznetwork/hermez-node/db/statedb"
  23. "github.com/hermeznetwork/hermez-node/log"
  24. "github.com/hermeznetwork/hermez-node/test"
  25. "github.com/hermeznetwork/hermez-node/test/til"
  26. "github.com/hermeznetwork/tracerr"
  27. )
  28. // Pendinger is an interface that allows getting last returned item ID and PendingItems to be used for building fromItem
  29. // when testing paginated endpoints.
  30. type Pendinger interface {
  31. GetPending() (pendingItems, lastItemID uint64)
  32. Len() int
  33. New() Pendinger
  34. }
  35. const apiPort = ":4010"
  36. const apiURL = "http://localhost" + apiPort + "/"
  37. var SetBlockchain = `
  38. Type: Blockchain
  39. AddToken(1)
  40. AddToken(2)
  41. AddToken(3)
  42. AddToken(4)
  43. AddToken(5)
  44. AddToken(6)
  45. AddToken(7)
  46. AddToken(8)
  47. > block
  48. // Coordinator accounts, Idxs: 256, 257
  49. CreateAccountCoordinator(0) Coord
  50. CreateAccountCoordinator(1) Coord
  51. // close Block:0, Batch:0
  52. > batch
  53. CreateAccountDeposit(0) A: 11111111100000000000
  54. CreateAccountDeposit(1) C: 22222222200000000000
  55. CreateAccountCoordinator(0) C
  56. // close Block:0, Batch:1
  57. > batchL1
  58. // Expected balances:
  59. // Coord(0): 0, Coord(1): 0
  60. // C(0): 0
  61. CreateAccountDeposit(1) A: 33333333300000000000
  62. // close Block:0, Batch:2
  63. > batchL1
  64. // close Block:0, Batch:3
  65. > batchL1
  66. CreateAccountDepositTransfer(0) B-A: 44444444400000000000, 123444444400000000000
  67. // close Block:0, Batch:4
  68. > batchL1
  69. CreateAccountDeposit(0) D: 55555555500000000000
  70. // close Block:0, Batch:5
  71. > batchL1
  72. CreateAccountCoordinator(1) B
  73. Transfer(1) A-B: 11111100000000000 (2)
  74. Transfer(0) B-C: 22222200000000000 (3)
  75. // close Block:0, Batch:6
  76. > batchL1 // forge L1User{1}, forge L1Coord{2}, forge L2{2}
  77. Deposit(0) C: 66666666600000000000
  78. DepositTransfer(0) C-D: 77777777700000000000, 12377777700000000000
  79. Transfer(0) A-B: 33333300000000000 (111)
  80. Transfer(0) C-A: 44444400000000000 (222)
  81. Transfer(1) B-C: 55555500000000000 (123)
  82. Exit(0) A: 66666600000000000 (44)
  83. ForceTransfer(0) D-B: 77777700000000000
  84. ForceExit(0) B: 88888800000000000
  85. // close Block:0, Batch:7
  86. > batchL1
  87. > block
  88. Transfer(0) D-A: 99999900000000000 (77)
  89. Transfer(0) B-D: 12312300000000000 (55)
  90. // close Block:1, Batch:0
  91. > batchL1
  92. CreateAccountCoordinator(0) F
  93. CreateAccountCoordinator(0) G
  94. CreateAccountCoordinator(0) H
  95. CreateAccountCoordinator(0) I
  96. CreateAccountCoordinator(0) J
  97. CreateAccountCoordinator(0) K
  98. CreateAccountCoordinator(0) L
  99. CreateAccountCoordinator(0) M
  100. CreateAccountCoordinator(0) N
  101. CreateAccountCoordinator(0) O
  102. CreateAccountCoordinator(0) P
  103. CreateAccountCoordinator(5) G
  104. CreateAccountCoordinator(5) H
  105. CreateAccountCoordinator(5) I
  106. CreateAccountCoordinator(5) J
  107. CreateAccountCoordinator(5) K
  108. CreateAccountCoordinator(5) L
  109. CreateAccountCoordinator(5) M
  110. CreateAccountCoordinator(5) N
  111. CreateAccountCoordinator(5) O
  112. CreateAccountCoordinator(5) P
  113. CreateAccountCoordinator(2) G
  114. CreateAccountCoordinator(2) H
  115. CreateAccountCoordinator(2) I
  116. CreateAccountCoordinator(2) J
  117. CreateAccountCoordinator(2) K
  118. CreateAccountCoordinator(2) L
  119. CreateAccountCoordinator(2) M
  120. CreateAccountCoordinator(2) N
  121. CreateAccountCoordinator(2) O
  122. CreateAccountCoordinator(2) P
  123. > batch
  124. > block
  125. > batch
  126. > block
  127. > batch
  128. > block
  129. `
  130. type testCommon struct {
  131. blocks []common.Block
  132. tokens []historydb.TokenWithUSD
  133. batches []testBatch
  134. fullBatches []testFullBatch
  135. coordinators []historydb.CoordinatorAPI
  136. accounts []testAccount
  137. txs []testTx
  138. exits []testExit
  139. poolTxsToSend []testPoolTxSend
  140. poolTxsToReceive []testPoolTxReceive
  141. auths []testAuth
  142. router *swagger.Router
  143. bids []testBid
  144. slots []testSlot
  145. auctionVars common.AuctionVariables
  146. rollupVars common.RollupVariables
  147. wdelayerVars common.WDelayerVariables
  148. }
  149. var tc testCommon
  150. var config configAPI
  151. var api *API
  152. // TestMain initializes the API server, and fill HistoryDB and StateDB with fake data,
  153. // emulating the task of the synchronizer in order to have data to be returned
  154. // by the API endpoints that will be tested
  155. func TestMain(m *testing.M) {
  156. // Initializations
  157. // Swagger
  158. router := swagger.NewRouter().WithSwaggerFromFile("./swagger.yml")
  159. // HistoryDB
  160. pass := os.Getenv("POSTGRES_PASS")
  161. database, err := db.InitSQLDB(5432, "localhost", "hermez", pass, "hermez")
  162. if err != nil {
  163. panic(err)
  164. }
  165. hdb := historydb.NewHistoryDB(database)
  166. if err != nil {
  167. panic(err)
  168. }
  169. // StateDB
  170. dir, err := ioutil.TempDir("", "tmpdb")
  171. if err != nil {
  172. panic(err)
  173. }
  174. defer func() {
  175. if err := os.RemoveAll(dir); err != nil {
  176. panic(err)
  177. }
  178. }()
  179. sdb, err := statedb.NewStateDB(dir, statedb.TypeTxSelector, 0)
  180. if err != nil {
  181. panic(err)
  182. }
  183. // L2DB
  184. l2DB := l2db.NewL2DB(database, 10, 100, 24*time.Hour)
  185. test.WipeDB(l2DB.DB()) // this will clean HistoryDB and L2DB
  186. // Config (smart contract constants)
  187. _config := getConfigTest()
  188. config = configAPI{
  189. RollupConstants: *newRollupConstants(_config.RollupConstants),
  190. AuctionConstants: _config.AuctionConstants,
  191. WDelayerConstants: _config.WDelayerConstants,
  192. }
  193. // API
  194. apiGin := gin.Default()
  195. api, err = NewAPI(
  196. true,
  197. true,
  198. apiGin,
  199. hdb,
  200. sdb,
  201. l2DB,
  202. &_config,
  203. )
  204. if err != nil {
  205. panic(err)
  206. }
  207. // Start server
  208. server := &http.Server{Addr: apiPort, Handler: apiGin}
  209. go func() {
  210. if err := server.ListenAndServe(); err != nil && tracerr.Unwrap(err) != http.ErrServerClosed {
  211. panic(err)
  212. }
  213. }()
  214. // Reset DB
  215. test.WipeDB(api.h.DB())
  216. // Genratre blockchain data with til
  217. tcc := til.NewContext(common.RollupConstMaxL1UserTx)
  218. tilCfgExtra := til.ConfigExtra{
  219. BootCoordAddr: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  220. CoordUser: "Coord",
  221. }
  222. blocksData, err := tcc.GenerateBlocks(SetBlockchain)
  223. if err != nil {
  224. panic(err)
  225. }
  226. err = tcc.FillBlocksExtra(blocksData, &tilCfgExtra)
  227. if err != nil {
  228. panic(err)
  229. }
  230. AddAditionalInformation(blocksData)
  231. // Generate L2 Txs with til
  232. commonPoolTxs, err := tcc.GeneratePoolL2Txs(til.SetPoolL2MinimumFlow0)
  233. if err != nil {
  234. panic(err)
  235. }
  236. // Extract til generated data, and add it to HistoryDB
  237. var commonBlocks []common.Block
  238. var commonBatches []common.Batch
  239. var commonAccounts []common.Account
  240. var commonExitTree []common.ExitInfo
  241. var commonL1Txs []common.L1Tx
  242. var commonL2Txs []common.L2Tx
  243. // Add ETH token at the beginning of the array
  244. testTokens := []historydb.TokenWithUSD{}
  245. ethUSD := float64(500)
  246. ethNow := time.Now()
  247. testTokens = append(testTokens, historydb.TokenWithUSD{
  248. TokenID: test.EthToken.TokenID,
  249. EthBlockNum: test.EthToken.EthBlockNum,
  250. EthAddr: test.EthToken.EthAddr,
  251. Name: test.EthToken.Name,
  252. Symbol: test.EthToken.Symbol,
  253. Decimals: test.EthToken.Decimals,
  254. USD: &ethUSD,
  255. USDUpdate: &ethNow,
  256. })
  257. err = api.h.UpdateTokenValue(test.EthToken.Symbol, ethUSD)
  258. if err != nil {
  259. panic(err)
  260. }
  261. for _, block := range blocksData {
  262. // Insert block into HistoryDB
  263. // nolint reason: block is used as read only in the function
  264. if err := api.h.AddBlockSCData(&block); err != nil { //nolint:gosec
  265. panic(err)
  266. }
  267. // Extract data
  268. commonBlocks = append(commonBlocks, block.Block)
  269. for i, tkn := range block.Rollup.AddedTokens {
  270. token := historydb.TokenWithUSD{
  271. TokenID: tkn.TokenID,
  272. EthBlockNum: tkn.EthBlockNum,
  273. EthAddr: tkn.EthAddr,
  274. Name: tkn.Name,
  275. Symbol: tkn.Symbol,
  276. Decimals: tkn.Decimals,
  277. }
  278. value := float64(i + 423)
  279. now := time.Now().UTC()
  280. token.USD = &value
  281. token.USDUpdate = &now
  282. // Set value in DB
  283. err = api.h.UpdateTokenValue(token.Symbol, value)
  284. if err != nil {
  285. panic(err)
  286. }
  287. testTokens = append(testTokens, token)
  288. }
  289. // Set USD value for tokens in DB
  290. commonL1Txs = append(commonL1Txs, block.Rollup.L1UserTxs...)
  291. for _, batch := range block.Rollup.Batches {
  292. commonL2Txs = append(commonL2Txs, batch.L2Txs...)
  293. for i := range batch.CreatedAccounts {
  294. batch.CreatedAccounts[i].Nonce = common.Nonce(i)
  295. commonAccounts = append(commonAccounts, batch.CreatedAccounts[i])
  296. }
  297. commonBatches = append(commonBatches, batch.Batch)
  298. commonExitTree = append(commonExitTree, batch.ExitTree...)
  299. commonL1Txs = append(commonL1Txs, batch.L1CoordinatorTxs...)
  300. }
  301. }
  302. // lastBlockNum2 := blocksData[len(blocksData)-1].Block.EthBlockNum
  303. // Add accounts to StateDB
  304. for i := 0; i < len(commonAccounts); i++ {
  305. if _, err := api.s.CreateAccount(commonAccounts[i].Idx, &commonAccounts[i]); err != nil {
  306. panic(err)
  307. }
  308. }
  309. // Generate Coordinators and add them to HistoryDB
  310. const nCoords = 10
  311. commonCoords := test.GenCoordinators(nCoords, commonBlocks)
  312. if err := api.h.AddCoordinators(commonCoords); err != nil {
  313. panic(err)
  314. }
  315. // Generate Bids and add them to HistoryDB
  316. const nBids = 20
  317. commonBids := test.GenBids(nBids, commonBlocks, commonCoords)
  318. if err = api.h.AddBids(commonBids); err != nil {
  319. panic(err)
  320. }
  321. // Generate SC vars and add them to HistoryDB (if needed)
  322. var defaultSlotSetBid [6]*big.Int = [6]*big.Int{big.NewInt(10), big.NewInt(10), big.NewInt(10), big.NewInt(10), big.NewInt(10), big.NewInt(10)}
  323. auctionVars := common.AuctionVariables{
  324. EthBlockNum: int64(2),
  325. DonationAddress: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  326. DefaultSlotSetBid: defaultSlotSetBid,
  327. Outbidding: uint16(1),
  328. SlotDeadline: uint8(20),
  329. BootCoordinator: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  330. BootCoordinatorURL: "https://boot.coordinator.io",
  331. ClosedAuctionSlots: uint16(2),
  332. OpenAuctionSlots: uint16(5),
  333. }
  334. var buckets [common.RollupConstNumBuckets]common.BucketParams
  335. for i := range buckets {
  336. buckets[i].CeilUSD = big.NewInt(int64(i) * 10)
  337. buckets[i].Withdrawals = big.NewInt(int64(i) * 100)
  338. buckets[i].BlockWithdrawalRate = big.NewInt(int64(i) * 1000)
  339. buckets[i].MaxWithdrawals = big.NewInt(int64(i) * 10000)
  340. }
  341. rollupVars := common.RollupVariables{
  342. EthBlockNum: int64(3),
  343. FeeAddToken: big.NewInt(100),
  344. ForgeL1L2BatchTimeout: int64(44),
  345. WithdrawalDelay: uint64(3000),
  346. Buckets: buckets,
  347. SafeMode: false,
  348. }
  349. wdelayerVars := common.WDelayerVariables{
  350. WithdrawalDelay: uint64(3000),
  351. }
  352. err = api.h.AddAuctionVars(&auctionVars)
  353. if err != nil {
  354. panic(err)
  355. }
  356. // Generate test data, as expected to be received/sended from/to the API
  357. testCoords := genTestCoordinators(commonCoords)
  358. testBids := genTestBids(commonBlocks, testCoords, commonBids)
  359. testExits := genTestExits(commonExitTree, testTokens, commonAccounts)
  360. testTxs := genTestTxs(commonL1Txs, commonL2Txs, commonAccounts, testTokens, commonBlocks)
  361. testBatches, testFullBatches := genTestBatches(commonBlocks, commonBatches, testTxs)
  362. poolTxsToSend, poolTxsToReceive := genTestPoolTxs(commonPoolTxs, testTokens, commonAccounts)
  363. tc = testCommon{
  364. blocks: commonBlocks,
  365. tokens: testTokens,
  366. batches: testBatches,
  367. fullBatches: testFullBatches,
  368. coordinators: testCoords,
  369. accounts: genTestAccounts(commonAccounts, testTokens),
  370. txs: testTxs,
  371. exits: testExits,
  372. poolTxsToSend: poolTxsToSend,
  373. poolTxsToReceive: poolTxsToReceive,
  374. auths: genTestAuths(test.GenAuths(5)),
  375. router: router,
  376. bids: testBids,
  377. slots: api.genTestSlots(
  378. 20,
  379. commonBlocks[len(commonBlocks)-1].Num,
  380. testBids,
  381. auctionVars,
  382. ),
  383. auctionVars: auctionVars,
  384. rollupVars: rollupVars,
  385. wdelayerVars: wdelayerVars,
  386. }
  387. // Fake server
  388. if os.Getenv("FAKE_SERVER") == "yes" {
  389. for {
  390. log.Info("Running fake server at " + apiURL + " until ^C is received")
  391. time.Sleep(30 * time.Second)
  392. }
  393. }
  394. // Run tests
  395. result := m.Run()
  396. // Stop server
  397. if err := server.Shutdown(context.Background()); err != nil {
  398. panic(err)
  399. }
  400. if err := database.Close(); err != nil {
  401. panic(err)
  402. }
  403. if err := os.RemoveAll(dir); err != nil {
  404. panic(err)
  405. }
  406. os.Exit(result)
  407. }
  408. func doGoodReqPaginated(
  409. path, order string,
  410. iterStruct Pendinger,
  411. appendIter func(res interface{}),
  412. ) error {
  413. var next uint64
  414. firstIte := true
  415. expectedTotal := 0
  416. totalReceived := 0
  417. for {
  418. // Calculate fromItem
  419. iterPath := path
  420. if !firstIte {
  421. iterPath += "&fromItem=" + strconv.Itoa(int(next))
  422. }
  423. // Call API to get this iteration items
  424. iterStruct = iterStruct.New()
  425. if err := doGoodReq(
  426. "GET", iterPath+"&order="+order, nil,
  427. iterStruct,
  428. ); err != nil {
  429. return tracerr.Wrap(err)
  430. }
  431. appendIter(iterStruct)
  432. // Keep iterating?
  433. remaining, lastID := iterStruct.GetPending()
  434. if remaining == 0 {
  435. break
  436. }
  437. if order == historydb.OrderDesc {
  438. next = lastID - 1
  439. } else {
  440. next = lastID + 1
  441. }
  442. // Check that the expected amount of items is consistent across iterations
  443. totalReceived += iterStruct.Len()
  444. if firstIte {
  445. firstIte = false
  446. expectedTotal = totalReceived + int(remaining)
  447. }
  448. if expectedTotal != totalReceived+int(remaining) {
  449. panic(fmt.Sprintf(
  450. "pagination error, totalReceived + remaining should be %d, but is %d",
  451. expectedTotal, totalReceived+int(remaining),
  452. ))
  453. }
  454. }
  455. return nil
  456. }
  457. func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{}) error {
  458. ctx := context.Background()
  459. client := &http.Client{}
  460. httpReq, err := http.NewRequest(method, path, reqBody)
  461. if err != nil {
  462. return tracerr.Wrap(err)
  463. }
  464. if reqBody != nil {
  465. httpReq.Header.Add("Content-Type", "application/json")
  466. }
  467. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  468. if err != nil {
  469. return tracerr.Wrap(err)
  470. }
  471. // Validate request against swagger spec
  472. requestValidationInput := &swagger.RequestValidationInput{
  473. Request: httpReq,
  474. PathParams: pathParams,
  475. Route: route,
  476. }
  477. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  478. return tracerr.Wrap(err)
  479. }
  480. // Do API call
  481. resp, err := client.Do(httpReq)
  482. if err != nil {
  483. return tracerr.Wrap(err)
  484. }
  485. if resp.Body == nil && returnStruct != nil {
  486. return tracerr.Wrap(errors.New("Nil body"))
  487. }
  488. //nolint
  489. defer resp.Body.Close()
  490. body, err := ioutil.ReadAll(resp.Body)
  491. if err != nil {
  492. return tracerr.Wrap(err)
  493. }
  494. if resp.StatusCode != 200 {
  495. return tracerr.Wrap(fmt.Errorf("%d response. Body: %s", resp.StatusCode, string(body)))
  496. }
  497. if returnStruct == nil {
  498. return nil
  499. }
  500. // Unmarshal body into return struct
  501. if err := json.Unmarshal(body, returnStruct); err != nil {
  502. log.Error("invalid json: " + string(body))
  503. log.Error(err)
  504. return tracerr.Wrap(err)
  505. }
  506. // log.Info(string(body))
  507. // Validate response against swagger spec
  508. responseValidationInput := &swagger.ResponseValidationInput{
  509. RequestValidationInput: requestValidationInput,
  510. Status: resp.StatusCode,
  511. Header: resp.Header,
  512. }
  513. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  514. return swagger.ValidateResponse(ctx, responseValidationInput)
  515. }
  516. func doBadReq(method, path string, reqBody io.Reader, expectedResponseCode int) error {
  517. ctx := context.Background()
  518. client := &http.Client{}
  519. httpReq, _ := http.NewRequest(method, path, reqBody)
  520. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  521. if err != nil {
  522. return tracerr.Wrap(err)
  523. }
  524. // Validate request against swagger spec
  525. requestValidationInput := &swagger.RequestValidationInput{
  526. Request: httpReq,
  527. PathParams: pathParams,
  528. Route: route,
  529. }
  530. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  531. if expectedResponseCode != 400 {
  532. return tracerr.Wrap(err)
  533. }
  534. log.Warn("The request does not match the API spec")
  535. }
  536. // Do API call
  537. resp, err := client.Do(httpReq)
  538. if err != nil {
  539. return tracerr.Wrap(err)
  540. }
  541. if resp.Body == nil {
  542. return tracerr.Wrap(errors.New("Nil body"))
  543. }
  544. //nolint
  545. defer resp.Body.Close()
  546. body, err := ioutil.ReadAll(resp.Body)
  547. if err != nil {
  548. return tracerr.Wrap(err)
  549. }
  550. if resp.StatusCode != expectedResponseCode {
  551. return tracerr.Wrap(fmt.Errorf("Unexpected response code: %d. Body: %s", resp.StatusCode, string(body)))
  552. }
  553. // Validate response against swagger spec
  554. responseValidationInput := &swagger.ResponseValidationInput{
  555. RequestValidationInput: requestValidationInput,
  556. Status: resp.StatusCode,
  557. Header: resp.Header,
  558. }
  559. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  560. return swagger.ValidateResponse(ctx, responseValidationInput)
  561. }
  562. // test helpers
  563. func getTimestamp(blockNum int64, blocks []common.Block) time.Time {
  564. for i := 0; i < len(blocks); i++ {
  565. if blocks[i].Num == blockNum {
  566. return blocks[i].Timestamp
  567. }
  568. }
  569. panic("timesamp not found")
  570. }
  571. func getTokenByID(id common.TokenID, tokens []historydb.TokenWithUSD) historydb.TokenWithUSD {
  572. for i := 0; i < len(tokens); i++ {
  573. if tokens[i].TokenID == id {
  574. return tokens[i]
  575. }
  576. }
  577. panic("token not found")
  578. }
  579. func getTokenByIdx(idx common.Idx, tokens []historydb.TokenWithUSD, accs []common.Account) historydb.TokenWithUSD {
  580. for _, acc := range accs {
  581. if idx == acc.Idx {
  582. return getTokenByID(acc.TokenID, tokens)
  583. }
  584. }
  585. panic("token not found")
  586. }
  587. func getAccountByIdx(idx common.Idx, accs []common.Account) *common.Account {
  588. for _, acc := range accs {
  589. if acc.Idx == idx {
  590. return &acc
  591. }
  592. }
  593. panic("account not found")
  594. }
  595. func getBlockByNum(ethBlockNum int64, blocks []common.Block) common.Block {
  596. for _, b := range blocks {
  597. if b.Num == ethBlockNum {
  598. return b
  599. }
  600. }
  601. panic("block not found")
  602. }
  603. func getCoordinatorByBidder(bidder ethCommon.Address, coordinators []historydb.CoordinatorAPI) historydb.CoordinatorAPI {
  604. for _, c := range coordinators {
  605. if c.Bidder == bidder {
  606. return c
  607. }
  608. }
  609. panic("coordinator not found")
  610. }