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.

664 lines
17 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
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. )
  27. // Pendinger is an interface that allows getting last returned item ID and PendingItems to be used for building fromItem
  28. // when testing paginated endpoints.
  29. type Pendinger interface {
  30. GetPending() (pendingItems, lastItemID uint64)
  31. Len() int
  32. New() Pendinger
  33. }
  34. const apiPort = ":4010"
  35. const apiURL = "http://localhost" + apiPort + "/"
  36. var SetBlockchain = `
  37. Type: Blockchain
  38. AddToken(1)
  39. AddToken(2)
  40. AddToken(3)
  41. AddToken(4)
  42. AddToken(5)
  43. AddToken(6)
  44. AddToken(7)
  45. AddToken(8)
  46. > block
  47. // Coordinator accounts, Idxs: 256, 257
  48. CreateAccountCoordinator(0) Coord
  49. CreateAccountCoordinator(1) Coord
  50. // close Block:0, Batch:0
  51. > batch
  52. CreateAccountDeposit(0) A: 11111111100000000000
  53. CreateAccountDeposit(1) C: 22222222200000000000
  54. CreateAccountCoordinator(0) C
  55. // close Block:0, Batch:1
  56. > batchL1
  57. // Expected balances:
  58. // Coord(0): 0, Coord(1): 0
  59. // C(0): 0
  60. CreateAccountDeposit(1) A: 33333333300000000000
  61. // close Block:0, Batch:2
  62. > batchL1
  63. // close Block:0, Batch:3
  64. > batchL1
  65. CreateAccountDepositTransfer(0) B-A: 44444444400000000000, 123444444400000000000
  66. // close Block:0, Batch:4
  67. > batchL1
  68. CreateAccountDeposit(0) D: 55555555500000000000
  69. // close Block:0, Batch:5
  70. > batchL1
  71. CreateAccountCoordinator(1) B
  72. Transfer(1) A-B: 11111100000000000 (2)
  73. Transfer(0) B-C: 22222200000000000 (3)
  74. // close Block:0, Batch:6
  75. > batchL1 // forge L1User{1}, forge L1Coord{2}, forge L2{2}
  76. Deposit(0) C: 66666666600000000000
  77. DepositTransfer(0) C-D: 77777777700000000000, 12377777700000000000
  78. Transfer(0) A-B: 33333300000000000 (111)
  79. Transfer(0) C-A: 44444400000000000 (222)
  80. Transfer(1) B-C: 55555500000000000 (123)
  81. Exit(0) A: 66666600000000000 (44)
  82. ForceTransfer(0) D-B: 77777700000000000
  83. ForceExit(0) B: 88888800000000000
  84. // close Block:0, Batch:7
  85. > batchL1
  86. > block
  87. Transfer(0) D-A: 99999900000000000 (77)
  88. Transfer(0) B-D: 12312300000000000 (55)
  89. // close Block:1, Batch:0
  90. > batchL1
  91. CreateAccountCoordinator(0) F
  92. CreateAccountCoordinator(0) G
  93. CreateAccountCoordinator(0) H
  94. CreateAccountCoordinator(0) I
  95. CreateAccountCoordinator(0) J
  96. CreateAccountCoordinator(0) K
  97. CreateAccountCoordinator(0) L
  98. CreateAccountCoordinator(0) M
  99. CreateAccountCoordinator(0) N
  100. CreateAccountCoordinator(0) O
  101. CreateAccountCoordinator(0) P
  102. CreateAccountCoordinator(5) G
  103. CreateAccountCoordinator(5) H
  104. CreateAccountCoordinator(5) I
  105. CreateAccountCoordinator(5) J
  106. CreateAccountCoordinator(5) K
  107. CreateAccountCoordinator(5) L
  108. CreateAccountCoordinator(5) M
  109. CreateAccountCoordinator(5) N
  110. CreateAccountCoordinator(5) O
  111. CreateAccountCoordinator(5) P
  112. CreateAccountCoordinator(2) G
  113. CreateAccountCoordinator(2) H
  114. CreateAccountCoordinator(2) I
  115. CreateAccountCoordinator(2) J
  116. CreateAccountCoordinator(2) K
  117. CreateAccountCoordinator(2) L
  118. CreateAccountCoordinator(2) M
  119. CreateAccountCoordinator(2) N
  120. CreateAccountCoordinator(2) O
  121. CreateAccountCoordinator(2) P
  122. > batch
  123. > block
  124. > batch
  125. > block
  126. > batch
  127. > block
  128. `
  129. type testCommon struct {
  130. blocks []common.Block
  131. tokens []historydb.TokenWithUSD
  132. batches []testBatch
  133. fullBatches []testFullBatch
  134. coordinators []historydb.CoordinatorAPI
  135. accounts []testAccount
  136. txs []testTx
  137. exits []testExit
  138. poolTxsToSend []testPoolTxSend
  139. poolTxsToReceive []testPoolTxReceive
  140. auths []testAuth
  141. router *swagger.Router
  142. bids []testBid
  143. slots []testSlot
  144. auctionVars common.AuctionVariables
  145. rollupVars common.RollupVariables
  146. wdelayerVars common.WDelayerVariables
  147. }
  148. var tc testCommon
  149. var config configAPI
  150. var api *API
  151. // TestMain initializes the API server, and fill HistoryDB and StateDB with fake data,
  152. // emulating the task of the synchronizer in order to have data to be returned
  153. // by the API endpoints that will be tested
  154. func TestMain(m *testing.M) {
  155. // Initializations
  156. // Swagger
  157. router := swagger.NewRouter().WithSwaggerFromFile("./swagger.yml")
  158. // HistoryDB
  159. pass := os.Getenv("POSTGRES_PASS")
  160. database, err := db.InitSQLDB(5432, "localhost", "hermez", pass, "hermez")
  161. if err != nil {
  162. panic(err)
  163. }
  164. hdb := historydb.NewHistoryDB(database)
  165. if err != nil {
  166. panic(err)
  167. }
  168. // StateDB
  169. dir, err := ioutil.TempDir("", "tmpdb")
  170. if err != nil {
  171. panic(err)
  172. }
  173. defer func() {
  174. if err := os.RemoveAll(dir); err != nil {
  175. panic(err)
  176. }
  177. }()
  178. sdb, err := statedb.NewStateDB(dir, statedb.TypeTxSelector, 0)
  179. if err != nil {
  180. panic(err)
  181. }
  182. // L2DB
  183. l2DB := l2db.NewL2DB(database, 10, 100, 24*time.Hour)
  184. test.WipeDB(l2DB.DB()) // this will clean HistoryDB and L2DB
  185. // Config (smart contract constants)
  186. _config := getConfigTest()
  187. config = configAPI{
  188. RollupConstants: *newRollupConstants(_config.RollupConstants),
  189. AuctionConstants: _config.AuctionConstants,
  190. WDelayerConstants: _config.WDelayerConstants,
  191. }
  192. // API
  193. apiGin := gin.Default()
  194. api, err = NewAPI(
  195. true,
  196. true,
  197. apiGin,
  198. hdb,
  199. sdb,
  200. l2DB,
  201. &_config,
  202. )
  203. if err != nil {
  204. panic(err)
  205. }
  206. // Start server
  207. server := &http.Server{Addr: apiPort, Handler: apiGin}
  208. go func() {
  209. if err := server.ListenAndServe(); err != nil &&
  210. 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. commonAccounts = append(commonAccounts, batch.CreatedAccounts...)
  294. commonBatches = append(commonBatches, batch.Batch)
  295. commonExitTree = append(commonExitTree, batch.ExitTree...)
  296. commonL1Txs = append(commonL1Txs, batch.L1CoordinatorTxs...)
  297. }
  298. }
  299. // lastBlockNum2 := blocksData[len(blocksData)-1].Block.EthBlockNum
  300. // Add accounts to StateDB
  301. for i := 0; i < len(commonAccounts); i++ {
  302. if _, err := api.s.CreateAccount(commonAccounts[i].Idx, &commonAccounts[i]); err != nil {
  303. panic(err)
  304. }
  305. }
  306. // Generate Coordinators and add them to HistoryDB
  307. const nCoords = 10
  308. commonCoords := test.GenCoordinators(nCoords, commonBlocks)
  309. if err := api.h.AddCoordinators(commonCoords); err != nil {
  310. panic(err)
  311. }
  312. // Generate Bids and add them to HistoryDB
  313. const nBids = 20
  314. commonBids := test.GenBids(nBids, commonBlocks, commonCoords)
  315. if err = api.h.AddBids(commonBids); err != nil {
  316. panic(err)
  317. }
  318. // Generate SC vars and add them to HistoryDB (if needed)
  319. 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)}
  320. auctionVars := common.AuctionVariables{
  321. EthBlockNum: int64(2),
  322. DonationAddress: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  323. DefaultSlotSetBid: defaultSlotSetBid,
  324. Outbidding: uint16(1),
  325. SlotDeadline: uint8(20),
  326. BootCoordinator: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  327. ClosedAuctionSlots: uint16(2),
  328. OpenAuctionSlots: uint16(5),
  329. }
  330. rollupVars := common.RollupVariables{
  331. EthBlockNum: int64(3),
  332. FeeAddToken: big.NewInt(100),
  333. ForgeL1L2BatchTimeout: int64(44),
  334. WithdrawalDelay: uint64(3000),
  335. }
  336. wdelayerVars := common.WDelayerVariables{
  337. WithdrawalDelay: uint64(3000),
  338. }
  339. err = api.h.AddAuctionVars(&auctionVars)
  340. if err != nil {
  341. panic(err)
  342. }
  343. // Generate test data, as expected to be received/sended from/to the API
  344. testCoords := genTestCoordinators(commonCoords)
  345. testBids := genTestBids(commonBlocks, testCoords, commonBids)
  346. testExits := genTestExits(commonExitTree, testTokens, commonAccounts)
  347. testTxs := genTestTxs(commonL1Txs, commonL2Txs, commonAccounts, testTokens, commonBlocks)
  348. testBatches, testFullBatches := genTestBatches(commonBlocks, commonBatches, testTxs)
  349. poolTxsToSend, poolTxsToReceive := genTestPoolTxs(commonPoolTxs, testTokens, commonAccounts)
  350. tc = testCommon{
  351. blocks: commonBlocks,
  352. tokens: testTokens,
  353. batches: testBatches,
  354. fullBatches: testFullBatches,
  355. coordinators: testCoords,
  356. accounts: genTestAccounts(commonAccounts, testTokens),
  357. txs: testTxs,
  358. exits: testExits,
  359. poolTxsToSend: poolTxsToSend,
  360. poolTxsToReceive: poolTxsToReceive,
  361. auths: genTestAuths(test.GenAuths(5)),
  362. router: router,
  363. bids: testBids,
  364. slots: api.genTestSlots(
  365. 20,
  366. commonBlocks[len(commonBlocks)-1].Num,
  367. testBids,
  368. auctionVars,
  369. ),
  370. auctionVars: auctionVars,
  371. rollupVars: rollupVars,
  372. wdelayerVars: wdelayerVars,
  373. }
  374. // Fake server
  375. if os.Getenv("FAKE_SERVER") == "yes" {
  376. for {
  377. log.Info("Running fake server at " + apiURL + " until ^C is received")
  378. time.Sleep(30 * time.Second)
  379. }
  380. }
  381. // Run tests
  382. result := m.Run()
  383. // Stop server
  384. if err := server.Shutdown(context.Background()); err != nil {
  385. panic(err)
  386. }
  387. if err := database.Close(); err != nil {
  388. panic(err)
  389. }
  390. if err := os.RemoveAll(dir); err != nil {
  391. panic(err)
  392. }
  393. os.Exit(result)
  394. }
  395. func doGoodReqPaginated(
  396. path, order string,
  397. iterStruct Pendinger,
  398. appendIter func(res interface{}),
  399. ) error {
  400. var next uint64
  401. firstIte := true
  402. expectedTotal := 0
  403. totalReceived := 0
  404. for {
  405. // Calculate fromItem
  406. iterPath := path
  407. if firstIte {
  408. if order == historydb.OrderDesc {
  409. // Fetch first item in reverse order
  410. iterPath += "99999" // Asumption that for testing there won't be any itemID > 99999
  411. } else {
  412. iterPath += "0"
  413. }
  414. } else {
  415. iterPath += strconv.Itoa(int(next))
  416. }
  417. // Call API to get this iteration items
  418. iterStruct = iterStruct.New()
  419. if err := doGoodReq(
  420. "GET", iterPath+"&order="+order, nil,
  421. iterStruct,
  422. ); err != nil {
  423. return err
  424. }
  425. appendIter(iterStruct)
  426. // Keep iterating?
  427. remaining, lastID := iterStruct.GetPending()
  428. if remaining == 0 {
  429. break
  430. }
  431. if order == historydb.OrderDesc {
  432. next = lastID - 1
  433. } else {
  434. next = lastID + 1
  435. }
  436. // Check that the expected amount of items is consistent across iterations
  437. totalReceived += iterStruct.Len()
  438. if firstIte {
  439. firstIte = false
  440. expectedTotal = totalReceived + int(remaining)
  441. }
  442. if expectedTotal != totalReceived+int(remaining) {
  443. panic(fmt.Sprintf(
  444. "pagination error, totalReceived + remaining should be %d, but is %d",
  445. expectedTotal, totalReceived+int(remaining),
  446. ))
  447. }
  448. }
  449. return nil
  450. }
  451. func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{}) error {
  452. ctx := context.Background()
  453. client := &http.Client{}
  454. httpReq, err := http.NewRequest(method, path, reqBody)
  455. if err != nil {
  456. return err
  457. }
  458. if reqBody != nil {
  459. httpReq.Header.Add("Content-Type", "application/json")
  460. }
  461. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  462. if err != nil {
  463. return err
  464. }
  465. // Validate request against swagger spec
  466. requestValidationInput := &swagger.RequestValidationInput{
  467. Request: httpReq,
  468. PathParams: pathParams,
  469. Route: route,
  470. }
  471. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  472. return err
  473. }
  474. // Do API call
  475. resp, err := client.Do(httpReq)
  476. if err != nil {
  477. return err
  478. }
  479. if resp.Body == nil && returnStruct != nil {
  480. return errors.New("Nil body")
  481. }
  482. //nolint
  483. defer resp.Body.Close()
  484. body, err := ioutil.ReadAll(resp.Body)
  485. if err != nil {
  486. return err
  487. }
  488. if resp.StatusCode != 200 {
  489. return fmt.Errorf("%d response. Body: %s", resp.StatusCode, string(body))
  490. }
  491. if returnStruct == nil {
  492. return nil
  493. }
  494. // Unmarshal body into return struct
  495. if err := json.Unmarshal(body, returnStruct); err != nil {
  496. log.Error("invalid json: " + string(body))
  497. log.Error(err)
  498. return err
  499. }
  500. // log.Info(string(body))
  501. // Validate response against swagger spec
  502. responseValidationInput := &swagger.ResponseValidationInput{
  503. RequestValidationInput: requestValidationInput,
  504. Status: resp.StatusCode,
  505. Header: resp.Header,
  506. }
  507. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  508. return swagger.ValidateResponse(ctx, responseValidationInput)
  509. }
  510. func doBadReq(method, path string, reqBody io.Reader, expectedResponseCode int) error {
  511. ctx := context.Background()
  512. client := &http.Client{}
  513. httpReq, _ := http.NewRequest(method, path, reqBody)
  514. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  515. if err != nil {
  516. return err
  517. }
  518. // Validate request against swagger spec
  519. requestValidationInput := &swagger.RequestValidationInput{
  520. Request: httpReq,
  521. PathParams: pathParams,
  522. Route: route,
  523. }
  524. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  525. if expectedResponseCode != 400 {
  526. return err
  527. }
  528. log.Warn("The request does not match the API spec")
  529. }
  530. // Do API call
  531. resp, err := client.Do(httpReq)
  532. if err != nil {
  533. return err
  534. }
  535. if resp.Body == nil {
  536. return errors.New("Nil body")
  537. }
  538. //nolint
  539. defer resp.Body.Close()
  540. body, err := ioutil.ReadAll(resp.Body)
  541. if err != nil {
  542. return err
  543. }
  544. if resp.StatusCode != expectedResponseCode {
  545. return fmt.Errorf("Unexpected response code: %d. Body: %s", resp.StatusCode, string(body))
  546. }
  547. // Validate response against swagger spec
  548. responseValidationInput := &swagger.ResponseValidationInput{
  549. RequestValidationInput: requestValidationInput,
  550. Status: resp.StatusCode,
  551. Header: resp.Header,
  552. }
  553. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  554. return swagger.ValidateResponse(ctx, responseValidationInput)
  555. }
  556. // test helpers
  557. func getTimestamp(blockNum int64, blocks []common.Block) time.Time {
  558. for i := 0; i < len(blocks); i++ {
  559. if blocks[i].Num == blockNum {
  560. return blocks[i].Timestamp
  561. }
  562. }
  563. panic("timesamp not found")
  564. }
  565. func getTokenByID(id common.TokenID, tokens []historydb.TokenWithUSD) historydb.TokenWithUSD {
  566. for i := 0; i < len(tokens); i++ {
  567. if tokens[i].TokenID == id {
  568. return tokens[i]
  569. }
  570. }
  571. panic("token not found")
  572. }
  573. func getTokenByIdx(idx common.Idx, tokens []historydb.TokenWithUSD, accs []common.Account) historydb.TokenWithUSD {
  574. for _, acc := range accs {
  575. if idx == acc.Idx {
  576. return getTokenByID(acc.TokenID, tokens)
  577. }
  578. }
  579. panic("token not found")
  580. }
  581. func getAccountByIdx(idx common.Idx, accs []common.Account) *common.Account {
  582. for _, acc := range accs {
  583. if acc.Idx == idx {
  584. return &acc
  585. }
  586. }
  587. panic("account not found")
  588. }
  589. func getBlockByNum(ethBlockNum int64, blocks []common.Block) common.Block {
  590. for _, b := range blocks {
  591. if b.Num == ethBlockNum {
  592. return b
  593. }
  594. }
  595. panic("block not found")
  596. }
  597. func getCoordinatorByBidder(bidder ethCommon.Address, coordinators []historydb.CoordinatorAPI) historydb.CoordinatorAPI {
  598. for _, c := range coordinators {
  599. if c.Bidder == bidder {
  600. return c
  601. }
  602. }
  603. panic("coordinator not found")
  604. }