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.

902 lines
25 KiB

4 years ago
3 years ago
3 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
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
3 years ago
3 years ago
3 years ago
3 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
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
  1. package api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "math/big"
  10. "net"
  11. "net/http"
  12. "os"
  13. "strconv"
  14. "sync"
  15. "testing"
  16. "time"
  17. ethCommon "github.com/ethereum/go-ethereum/common"
  18. swagger "github.com/getkin/kin-openapi/openapi3filter"
  19. "github.com/gin-gonic/gin"
  20. "github.com/hermeznetwork/hermez-node/common"
  21. "github.com/hermeznetwork/hermez-node/db"
  22. "github.com/hermeznetwork/hermez-node/db/historydb"
  23. "github.com/hermeznetwork/hermez-node/db/l2db"
  24. "github.com/hermeznetwork/hermez-node/log"
  25. "github.com/hermeznetwork/hermez-node/test"
  26. "github.com/hermeznetwork/hermez-node/test/til"
  27. "github.com/hermeznetwork/hermez-node/test/txsets"
  28. "github.com/hermeznetwork/tracerr"
  29. "github.com/stretchr/testify/require"
  30. )
  31. // Pendinger is an interface that allows getting last returned item ID and PendingItems to be used for building fromItem
  32. // when testing paginated endpoints.
  33. type Pendinger interface {
  34. GetPending() (pendingItems, lastItemID uint64)
  35. Len() int
  36. New() Pendinger
  37. }
  38. const apiAddr = ":4010"
  39. const apiURL = "http://localhost" + apiAddr + "/"
  40. var SetBlockchain = `
  41. Type: Blockchain
  42. AddToken(1)
  43. AddToken(2)
  44. AddToken(3)
  45. AddToken(4)
  46. AddToken(5)
  47. AddToken(6)
  48. AddToken(7)
  49. AddToken(8)
  50. > block
  51. // Coordinator accounts, Idxs: 256, 257
  52. CreateAccountCoordinator(0) Coord
  53. CreateAccountCoordinator(1) Coord
  54. // close Block:0, Batch:1
  55. > batch
  56. CreateAccountDeposit(0) A: 11100000000000000
  57. CreateAccountDeposit(1) C: 22222222200000000000
  58. CreateAccountCoordinator(0) C
  59. // close Block:0, Batch:2
  60. > batchL1
  61. // Expected balances:
  62. // Coord(0): 0, Coord(1): 0
  63. // C(0): 0
  64. CreateAccountDeposit(1) A: 33333333300000000000
  65. // close Block:0, Batch:3
  66. > batchL1
  67. // close Block:0, Batch:4
  68. > batchL1
  69. CreateAccountDepositTransfer(0) B-A: 44444444400000000000, 123444444400000000000
  70. // close Block:0, Batch:5
  71. > batchL1
  72. CreateAccountDeposit(0) D: 55555555500000000000
  73. // close Block:0, Batch:6
  74. > batchL1
  75. CreateAccountCoordinator(1) B
  76. Transfer(1) A-B: 11100000000000000 (2)
  77. Transfer(0) B-C: 22200000000000000 (3)
  78. // close Block:0, Batch:7
  79. > batchL1 // forge L1User{1}, forge L1Coord{2}, forge L2{2}
  80. Deposit(0) C: 66666666600000000000
  81. DepositTransfer(0) C-D: 77777777700000000000, 12377777700000000000
  82. Transfer(0) A-B: 33350000000000000 (111)
  83. Transfer(0) C-A: 44450000000000000 (222)
  84. Transfer(1) B-C: 55550000000000000 (123)
  85. Exit(0) A: 66650000000000000 (44)
  86. ForceTransfer(0) D-B: 77777700000000000
  87. ForceExit(0) B: 88888800000000000
  88. // close Block:0, Batch:8
  89. > batchL1
  90. > block
  91. Transfer(0) D-A: 99950000000000000 (77)
  92. Transfer(0) B-D: 12300000000000000 (55)
  93. // close Block:1, Batch:1
  94. > batchL1
  95. CreateAccountCoordinator(0) F
  96. CreateAccountCoordinator(0) G
  97. CreateAccountCoordinator(0) H
  98. CreateAccountCoordinator(0) I
  99. CreateAccountCoordinator(0) J
  100. CreateAccountCoordinator(0) K
  101. CreateAccountCoordinator(0) L
  102. CreateAccountCoordinator(0) M
  103. CreateAccountCoordinator(0) N
  104. CreateAccountCoordinator(0) O
  105. CreateAccountCoordinator(0) P
  106. CreateAccountCoordinator(5) G
  107. CreateAccountCoordinator(5) H
  108. CreateAccountCoordinator(5) I
  109. CreateAccountCoordinator(5) J
  110. CreateAccountCoordinator(5) K
  111. CreateAccountCoordinator(5) L
  112. CreateAccountCoordinator(5) M
  113. CreateAccountCoordinator(5) N
  114. CreateAccountCoordinator(5) O
  115. CreateAccountCoordinator(5) P
  116. CreateAccountCoordinator(2) G
  117. CreateAccountCoordinator(2) H
  118. CreateAccountCoordinator(2) I
  119. CreateAccountCoordinator(2) J
  120. CreateAccountCoordinator(2) K
  121. CreateAccountCoordinator(2) L
  122. CreateAccountCoordinator(2) M
  123. CreateAccountCoordinator(2) N
  124. CreateAccountCoordinator(2) O
  125. CreateAccountCoordinator(2) P
  126. > batch
  127. > block
  128. > batch
  129. > block
  130. > batch
  131. > block
  132. `
  133. type testCommon struct {
  134. blocks []common.Block
  135. tokens []historydb.TokenWithUSD
  136. batches []testBatch
  137. fullBatches []testFullBatch
  138. coordinators []historydb.CoordinatorAPI
  139. accounts []testAccount
  140. txs []testTx
  141. exits []testExit
  142. poolTxsToSend []testPoolTxSend
  143. poolTxsToReceive []testPoolTxReceive
  144. auths []testAuth
  145. router *swagger.Router
  146. bids []testBid
  147. slots []testSlot
  148. auctionVars common.AuctionVariables
  149. rollupVars common.RollupVariables
  150. wdelayerVars common.WDelayerVariables
  151. nextForgers []historydb.NextForgerAPI
  152. }
  153. var tc testCommon
  154. var config configAPI
  155. var api *API
  156. var stateAPIUpdater *StateAPIUpdater
  157. // TestMain initializes the API server, and fill HistoryDB and StateDB with fake data,
  158. // emulating the task of the synchronizer in order to have data to be returned
  159. // by the API endpoints that will be tested
  160. func TestMain(m *testing.M) {
  161. // Initializations
  162. // Swagger
  163. router := swagger.NewRouter().WithSwaggerFromFile("./swagger.yml")
  164. // HistoryDB
  165. pass := os.Getenv("POSTGRES_PASS")
  166. database, err := db.InitSQLDB(5432, "localhost", "hermez", pass, "hermez")
  167. if err != nil {
  168. panic(err)
  169. }
  170. apiConnCon := db.NewAPICnnectionController(1, time.Second)
  171. hdb := historydb.NewHistoryDB(database, database, apiConnCon)
  172. if err != nil {
  173. panic(err)
  174. }
  175. // L2DB
  176. l2DB := l2db.NewL2DB(database, database, 10, 1000, 0.0, 24*time.Hour, apiConnCon)
  177. test.WipeDB(l2DB.DB()) // this will clean HistoryDB and L2DB
  178. // Config (smart contract constants)
  179. chainID := uint16(0)
  180. _config := getConfigTest(chainID)
  181. config = configAPI{
  182. RollupConstants: *newRollupConstants(_config.RollupConstants),
  183. AuctionConstants: _config.AuctionConstants,
  184. WDelayerConstants: _config.WDelayerConstants,
  185. }
  186. // API
  187. apiGin := gin.Default()
  188. // Reset DB
  189. test.WipeDB(hdb.DB())
  190. constants := &historydb.Constants{
  191. SCConsts: common.SCConsts{
  192. Rollup: _config.RollupConstants,
  193. Auction: _config.AuctionConstants,
  194. WDelayer: _config.WDelayerConstants,
  195. },
  196. ChainID: chainID,
  197. HermezAddress: _config.HermezAddress,
  198. }
  199. if err := hdb.SetConstants(constants); err != nil {
  200. panic(err)
  201. }
  202. nodeConfig := &historydb.NodeConfig{
  203. MaxPoolTxs: 10,
  204. MinFeeUSD: 0,
  205. }
  206. if err := hdb.SetNodeConfig(nodeConfig); err != nil {
  207. panic(err)
  208. }
  209. api, err = NewAPI(
  210. true,
  211. true,
  212. apiGin,
  213. hdb,
  214. l2DB,
  215. )
  216. if err != nil {
  217. log.Error(err)
  218. panic(err)
  219. }
  220. // Start server
  221. listener, err := net.Listen("tcp", apiAddr) //nolint:gosec
  222. if err != nil {
  223. panic(err)
  224. }
  225. server := &http.Server{Handler: apiGin}
  226. go func() {
  227. if err := server.Serve(listener); err != nil &&
  228. tracerr.Unwrap(err) != http.ErrServerClosed {
  229. panic(err)
  230. }
  231. }()
  232. // Genratre blockchain data with til
  233. tcc := til.NewContext(chainID, common.RollupConstMaxL1UserTx)
  234. tilCfgExtra := til.ConfigExtra{
  235. BootCoordAddr: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  236. CoordUser: "Coord",
  237. }
  238. blocksData, err := tcc.GenerateBlocks(SetBlockchain)
  239. if err != nil {
  240. panic(err)
  241. }
  242. err = tcc.FillBlocksExtra(blocksData, &tilCfgExtra)
  243. if err != nil {
  244. panic(err)
  245. }
  246. err = tcc.FillBlocksForgedL1UserTxs(blocksData)
  247. if err != nil {
  248. panic(err)
  249. }
  250. AddAditionalInformation(blocksData)
  251. // Generate L2 Txs with til
  252. commonPoolTxs, err := tcc.GeneratePoolL2Txs(txsets.SetPoolL2MinimumFlow0)
  253. if err != nil {
  254. panic(err)
  255. }
  256. // Extract til generated data, and add it to HistoryDB
  257. var commonBlocks []common.Block
  258. var commonBatches []common.Batch
  259. var commonAccounts []common.Account
  260. var commonExitTree []common.ExitInfo
  261. var commonL1Txs []common.L1Tx
  262. var commonL2Txs []common.L2Tx
  263. // Add ETH token at the beginning of the array
  264. testTokens := []historydb.TokenWithUSD{}
  265. ethUSD := float64(500)
  266. ethNow := time.Now()
  267. testTokens = append(testTokens, historydb.TokenWithUSD{
  268. TokenID: test.EthToken.TokenID,
  269. EthBlockNum: test.EthToken.EthBlockNum,
  270. EthAddr: test.EthToken.EthAddr,
  271. Name: test.EthToken.Name,
  272. Symbol: test.EthToken.Symbol,
  273. Decimals: test.EthToken.Decimals,
  274. USD: &ethUSD,
  275. USDUpdate: &ethNow,
  276. })
  277. err = api.h.UpdateTokenValue(test.EthToken.Symbol, ethUSD)
  278. if err != nil {
  279. panic(err)
  280. }
  281. for _, block := range blocksData {
  282. // Insert block into HistoryDB
  283. // nolint reason: block is used as read only in the function
  284. if err := api.h.AddBlockSCData(&block); err != nil { //nolint:gosec
  285. log.Error(err)
  286. panic(err)
  287. }
  288. // Extract data
  289. commonBlocks = append(commonBlocks, block.Block)
  290. for i, tkn := range block.Rollup.AddedTokens {
  291. token := historydb.TokenWithUSD{
  292. TokenID: tkn.TokenID,
  293. EthBlockNum: tkn.EthBlockNum,
  294. EthAddr: tkn.EthAddr,
  295. Name: tkn.Name,
  296. Symbol: tkn.Symbol,
  297. Decimals: tkn.Decimals,
  298. }
  299. value := float64(i + 423)
  300. now := time.Now().UTC()
  301. token.USD = &value
  302. token.USDUpdate = &now
  303. // Set value in DB
  304. err = api.h.UpdateTokenValue(token.Symbol, value)
  305. if err != nil {
  306. panic(err)
  307. }
  308. testTokens = append(testTokens, token)
  309. }
  310. // Set USD value for tokens in DB
  311. for _, batch := range block.Rollup.Batches {
  312. commonL2Txs = append(commonL2Txs, batch.L2Txs...)
  313. for i := range batch.CreatedAccounts {
  314. batch.CreatedAccounts[i].Nonce = common.Nonce(i)
  315. commonAccounts = append(commonAccounts, batch.CreatedAccounts[i])
  316. }
  317. commonBatches = append(commonBatches, batch.Batch)
  318. commonExitTree = append(commonExitTree, batch.ExitTree...)
  319. commonL1Txs = append(commonL1Txs, batch.L1UserTxs...)
  320. commonL1Txs = append(commonL1Txs, batch.L1CoordinatorTxs...)
  321. }
  322. }
  323. // Generate Coordinators and add them to HistoryDB
  324. const nCoords = 10
  325. commonCoords := test.GenCoordinators(nCoords, commonBlocks)
  326. // Update one coordinator to test behaviour when bidder address is repeated
  327. updatedCoordBlock := commonCoords[len(commonCoords)-1].EthBlockNum
  328. commonCoords = append(commonCoords, common.Coordinator{
  329. Bidder: commonCoords[0].Bidder,
  330. Forger: commonCoords[0].Forger,
  331. EthBlockNum: updatedCoordBlock,
  332. URL: commonCoords[0].URL + ".new",
  333. })
  334. if err := api.h.AddCoordinators(commonCoords); err != nil {
  335. panic(err)
  336. }
  337. // Test next forgers
  338. // Set auction vars
  339. // Slots 3 and 6 will have bids that will be invalidated because of minBid update
  340. // Slots 4 and 7 will have valid bids, the rest will be cordinator slots
  341. var slot3MinBid int64 = 3
  342. var slot4MinBid int64 = 4
  343. var slot6MinBid int64 = 6
  344. var slot7MinBid int64 = 7
  345. // First update will indicate how things behave from slot 0
  346. var defaultSlotSetBid [6]*big.Int = [6]*big.Int{
  347. big.NewInt(10), // Slot 0 min bid
  348. big.NewInt(10), // Slot 1 min bid
  349. big.NewInt(10), // Slot 2 min bid
  350. big.NewInt(slot3MinBid), // Slot 3 min bid
  351. big.NewInt(slot4MinBid), // Slot 4 min bid
  352. big.NewInt(10), // Slot 5 min bid
  353. }
  354. auctionVars := common.AuctionVariables{
  355. EthBlockNum: int64(2),
  356. DonationAddress: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  357. DefaultSlotSetBid: defaultSlotSetBid,
  358. DefaultSlotSetBidSlotNum: 0,
  359. Outbidding: uint16(1),
  360. SlotDeadline: uint8(20),
  361. BootCoordinator: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  362. BootCoordinatorURL: "https://boot.coordinator.io",
  363. ClosedAuctionSlots: uint16(10),
  364. OpenAuctionSlots: uint16(20),
  365. }
  366. if err := api.h.AddAuctionVars(&auctionVars); err != nil {
  367. panic(err)
  368. }
  369. // Last update in auction vars will indicate how things will behave from slot 5
  370. defaultSlotSetBid = [6]*big.Int{
  371. big.NewInt(10), // Slot 5 min bid
  372. big.NewInt(slot6MinBid), // Slot 6 min bid
  373. big.NewInt(slot7MinBid), // Slot 7 min bid
  374. big.NewInt(10), // Slot 8 min bid
  375. big.NewInt(10), // Slot 9 min bid
  376. big.NewInt(10), // Slot 10 min bid
  377. }
  378. auctionVars = common.AuctionVariables{
  379. EthBlockNum: int64(3),
  380. DonationAddress: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  381. DefaultSlotSetBid: defaultSlotSetBid,
  382. DefaultSlotSetBidSlotNum: 5,
  383. Outbidding: uint16(1),
  384. SlotDeadline: uint8(20),
  385. BootCoordinator: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  386. BootCoordinatorURL: "https://boot.coordinator.io",
  387. ClosedAuctionSlots: uint16(10),
  388. OpenAuctionSlots: uint16(20),
  389. }
  390. if err := api.h.AddAuctionVars(&auctionVars); err != nil {
  391. panic(err)
  392. }
  393. // Generate Bids and add them to HistoryDB
  394. bids := []common.Bid{}
  395. // Slot 1 and 2, no bids, wins boot coordinator
  396. // Slot 3, below what's going to be the minimum (wins boot coordinator)
  397. bids = append(bids, common.Bid{
  398. SlotNum: 3,
  399. BidValue: big.NewInt(slot3MinBid - 1),
  400. EthBlockNum: commonBlocks[0].Num,
  401. Bidder: commonCoords[0].Bidder,
  402. })
  403. // Slot 4, valid bid (wins bidder)
  404. bids = append(bids, common.Bid{
  405. SlotNum: 4,
  406. BidValue: big.NewInt(slot4MinBid),
  407. EthBlockNum: commonBlocks[0].Num,
  408. Bidder: commonCoords[0].Bidder,
  409. })
  410. // Slot 5 no bids, wins boot coordinator
  411. // Slot 6, below what's going to be the minimum (wins boot coordinator)
  412. bids = append(bids, common.Bid{
  413. SlotNum: 6,
  414. BidValue: big.NewInt(slot6MinBid - 1),
  415. EthBlockNum: commonBlocks[0].Num,
  416. Bidder: commonCoords[0].Bidder,
  417. })
  418. // Slot 7, valid bid (wins bidder)
  419. bids = append(bids, common.Bid{
  420. SlotNum: 7,
  421. BidValue: big.NewInt(slot7MinBid),
  422. EthBlockNum: commonBlocks[0].Num,
  423. Bidder: commonCoords[0].Bidder,
  424. })
  425. if err = api.h.AddBids(bids); err != nil {
  426. panic(err)
  427. }
  428. bootForger := historydb.NextForgerAPI{
  429. Coordinator: historydb.CoordinatorAPI{
  430. Forger: auctionVars.BootCoordinator,
  431. URL: auctionVars.BootCoordinatorURL,
  432. },
  433. }
  434. // Set next forgers: set all as boot coordinator then replace the non boot coordinators
  435. nextForgers := []historydb.NextForgerAPI{}
  436. var initBlock int64 = 140
  437. var deltaBlocks int64 = 40
  438. for i := 1; i < int(auctionVars.ClosedAuctionSlots)+2; i++ {
  439. fromBlock := initBlock + deltaBlocks*int64(i-1)
  440. bootForger.Period = historydb.Period{
  441. SlotNum: int64(i),
  442. FromBlock: fromBlock,
  443. ToBlock: fromBlock + deltaBlocks - 1,
  444. }
  445. nextForgers = append(nextForgers, bootForger)
  446. }
  447. // Set next forgers that aren't the boot coordinator
  448. nonBootForger := historydb.CoordinatorAPI{
  449. Bidder: commonCoords[0].Bidder,
  450. Forger: commonCoords[0].Forger,
  451. URL: commonCoords[0].URL + ".new",
  452. }
  453. // Slot 4
  454. nextForgers[3].Coordinator = nonBootForger
  455. // Slot 7
  456. nextForgers[6].Coordinator = nonBootForger
  457. var buckets [common.RollupConstNumBuckets]common.BucketParams
  458. for i := range buckets {
  459. buckets[i].CeilUSD = big.NewInt(int64(i) * 10)
  460. buckets[i].Withdrawals = big.NewInt(int64(i) * 100)
  461. buckets[i].BlockWithdrawalRate = big.NewInt(int64(i) * 1000)
  462. buckets[i].MaxWithdrawals = big.NewInt(int64(i) * 10000)
  463. }
  464. // Generate SC vars and add them to HistoryDB (if needed)
  465. rollupVars := common.RollupVariables{
  466. EthBlockNum: int64(3),
  467. FeeAddToken: big.NewInt(100),
  468. ForgeL1L2BatchTimeout: int64(44),
  469. WithdrawalDelay: uint64(3000),
  470. Buckets: buckets,
  471. SafeMode: false,
  472. }
  473. wdelayerVars := common.WDelayerVariables{
  474. WithdrawalDelay: uint64(3000),
  475. }
  476. stateAPIUpdater = NewStateAPIUpdater(hdb, nodeConfig, &common.SCVariables{
  477. Rollup: rollupVars,
  478. Auction: auctionVars,
  479. WDelayer: wdelayerVars,
  480. }, constants)
  481. // Generate test data, as expected to be received/sended from/to the API
  482. testCoords := genTestCoordinators(commonCoords)
  483. testBids := genTestBids(commonBlocks, testCoords, bids)
  484. testExits := genTestExits(commonExitTree, testTokens, commonAccounts)
  485. testTxs := genTestTxs(commonL1Txs, commonL2Txs, commonAccounts, testTokens, commonBlocks)
  486. testBatches, testFullBatches := genTestBatches(commonBlocks, commonBatches, testTxs)
  487. poolTxsToSend, poolTxsToReceive := genTestPoolTxs(commonPoolTxs, testTokens, commonAccounts)
  488. // Add balance and nonce to historyDB
  489. accounts := genTestAccounts(commonAccounts, testTokens)
  490. accUpdates := []common.AccountUpdate{}
  491. for i := 0; i < len(accounts); i++ {
  492. balance := new(big.Int)
  493. balance.SetString(string(*accounts[i].Balance), 10)
  494. idx, err := stringToIdx(string(accounts[i].Idx), "foo")
  495. if err != nil {
  496. panic(err)
  497. }
  498. accUpdates = append(accUpdates, common.AccountUpdate{
  499. EthBlockNum: 0,
  500. BatchNum: 1,
  501. Idx: *idx,
  502. Nonce: 0,
  503. Balance: balance,
  504. })
  505. accUpdates = append(accUpdates, common.AccountUpdate{
  506. EthBlockNum: 0,
  507. BatchNum: 1,
  508. Idx: *idx,
  509. Nonce: accounts[i].Nonce,
  510. Balance: balance,
  511. })
  512. }
  513. if err := api.h.AddAccountUpdates(accUpdates); err != nil {
  514. panic(err)
  515. }
  516. tc = testCommon{
  517. blocks: commonBlocks,
  518. tokens: testTokens,
  519. batches: testBatches,
  520. fullBatches: testFullBatches,
  521. coordinators: testCoords,
  522. accounts: accounts,
  523. txs: testTxs,
  524. exits: testExits,
  525. poolTxsToSend: poolTxsToSend,
  526. poolTxsToReceive: poolTxsToReceive,
  527. auths: genTestAuths(test.GenAuths(5, _config.ChainID, _config.HermezAddress)),
  528. router: router,
  529. bids: testBids,
  530. slots: api.genTestSlots(
  531. 20,
  532. commonBlocks[len(commonBlocks)-1].Num,
  533. testBids,
  534. auctionVars,
  535. ),
  536. auctionVars: auctionVars,
  537. rollupVars: rollupVars,
  538. wdelayerVars: wdelayerVars,
  539. nextForgers: nextForgers,
  540. }
  541. // Run tests
  542. result := m.Run()
  543. // Fake server
  544. if os.Getenv("FAKE_SERVER") == "yes" {
  545. for {
  546. log.Info("Running fake server at " + apiURL + " until ^C is received")
  547. time.Sleep(30 * time.Second)
  548. }
  549. }
  550. // Stop server
  551. if err := server.Shutdown(context.Background()); err != nil {
  552. panic(err)
  553. }
  554. if err := database.Close(); err != nil {
  555. panic(err)
  556. }
  557. os.Exit(result)
  558. }
  559. func TestTimeout(t *testing.T) {
  560. pass := os.Getenv("POSTGRES_PASS")
  561. databaseTO, err := db.ConnectSQLDB(5432, "localhost", "hermez", pass, "hermez")
  562. require.NoError(t, err)
  563. apiConnConTO := db.NewAPICnnectionController(1, 100*time.Millisecond)
  564. hdbTO := historydb.NewHistoryDB(databaseTO, databaseTO, apiConnConTO)
  565. require.NoError(t, err)
  566. // L2DB
  567. l2DBTO := l2db.NewL2DB(databaseTO, databaseTO, 10, 1000, 1.0, 24*time.Hour, apiConnConTO)
  568. // API
  569. apiGinTO := gin.Default()
  570. finishWait := make(chan interface{})
  571. startWait := make(chan interface{})
  572. apiGinTO.GET("/wait", func(c *gin.Context) {
  573. cancel, err := apiConnConTO.Acquire()
  574. defer cancel()
  575. require.NoError(t, err)
  576. defer apiConnConTO.Release()
  577. startWait <- nil
  578. <-finishWait
  579. })
  580. // Start server
  581. serverTO := &http.Server{Handler: apiGinTO}
  582. listener, err := net.Listen("tcp", ":4444") //nolint:gosec
  583. require.NoError(t, err)
  584. go func() {
  585. if err := serverTO.Serve(listener); err != nil &&
  586. tracerr.Unwrap(err) != http.ErrServerClosed {
  587. require.NoError(t, err)
  588. }
  589. }()
  590. _, err = NewAPI(
  591. true,
  592. true,
  593. apiGinTO,
  594. hdbTO,
  595. l2DBTO,
  596. )
  597. require.NoError(t, err)
  598. client := &http.Client{}
  599. httpReq, err := http.NewRequest("GET", "http://localhost:4444/tokens", nil)
  600. require.NoError(t, err)
  601. httpReqWait, err := http.NewRequest("GET", "http://localhost:4444/wait", nil)
  602. require.NoError(t, err)
  603. // Request that will get timed out
  604. var wg sync.WaitGroup
  605. wg.Add(1)
  606. go func() {
  607. // Request that will make the API busy
  608. _, err = client.Do(httpReqWait)
  609. require.NoError(t, err)
  610. wg.Done()
  611. }()
  612. <-startWait
  613. resp, err := client.Do(httpReq)
  614. require.NoError(t, err)
  615. require.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
  616. defer resp.Body.Close() //nolint
  617. body, err := ioutil.ReadAll(resp.Body)
  618. require.NoError(t, err)
  619. // Unmarshal body into return struct
  620. msg := &errorMsg{}
  621. err = json.Unmarshal(body, msg)
  622. require.NoError(t, err)
  623. // Check that the error was the expected down
  624. require.Equal(t, errSQLTimeout, msg.Message)
  625. finishWait <- nil
  626. // Stop server
  627. wg.Wait()
  628. require.NoError(t, serverTO.Shutdown(context.Background()))
  629. require.NoError(t, databaseTO.Close())
  630. }
  631. func doGoodReqPaginated(
  632. path, order string,
  633. iterStruct Pendinger,
  634. appendIter func(res interface{}),
  635. ) error {
  636. var next uint64
  637. firstIte := true
  638. expectedTotal := 0
  639. totalReceived := 0
  640. for {
  641. // Calculate fromItem
  642. iterPath := path
  643. if !firstIte {
  644. iterPath += "&fromItem=" + strconv.Itoa(int(next))
  645. }
  646. // Call API to get this iteration items
  647. iterStruct = iterStruct.New()
  648. if err := doGoodReq(
  649. "GET", iterPath+"&order="+order, nil,
  650. iterStruct,
  651. ); err != nil {
  652. return tracerr.Wrap(err)
  653. }
  654. appendIter(iterStruct)
  655. // Keep iterating?
  656. remaining, lastID := iterStruct.GetPending()
  657. if remaining == 0 {
  658. break
  659. }
  660. if order == historydb.OrderDesc {
  661. next = lastID - 1
  662. } else {
  663. next = lastID + 1
  664. }
  665. // Check that the expected amount of items is consistent across iterations
  666. totalReceived += iterStruct.Len()
  667. if firstIte {
  668. firstIte = false
  669. expectedTotal = totalReceived + int(remaining)
  670. }
  671. if expectedTotal != totalReceived+int(remaining) {
  672. panic(fmt.Sprintf(
  673. "pagination error, totalReceived + remaining should be %d, but is %d",
  674. expectedTotal, totalReceived+int(remaining),
  675. ))
  676. }
  677. }
  678. return nil
  679. }
  680. func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{}) error {
  681. ctx := context.Background()
  682. client := &http.Client{}
  683. httpReq, err := http.NewRequest(method, path, reqBody)
  684. if err != nil {
  685. return tracerr.Wrap(err)
  686. }
  687. if reqBody != nil {
  688. httpReq.Header.Add("Content-Type", "application/json")
  689. }
  690. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  691. if err != nil {
  692. return tracerr.Wrap(err)
  693. }
  694. // Validate request against swagger spec
  695. requestValidationInput := &swagger.RequestValidationInput{
  696. Request: httpReq,
  697. PathParams: pathParams,
  698. Route: route,
  699. }
  700. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  701. return tracerr.Wrap(err)
  702. }
  703. // Do API call
  704. resp, err := client.Do(httpReq)
  705. if err != nil {
  706. return tracerr.Wrap(err)
  707. }
  708. if resp.Body == nil && returnStruct != nil {
  709. return tracerr.Wrap(errors.New("Nil body"))
  710. }
  711. //nolint
  712. defer resp.Body.Close()
  713. body, err := ioutil.ReadAll(resp.Body)
  714. if err != nil {
  715. return tracerr.Wrap(err)
  716. }
  717. if resp.StatusCode != 200 {
  718. return tracerr.Wrap(fmt.Errorf("%d response. Body: %s", resp.StatusCode, string(body)))
  719. }
  720. if returnStruct == nil {
  721. return nil
  722. }
  723. // Unmarshal body into return struct
  724. if err := json.Unmarshal(body, returnStruct); err != nil {
  725. log.Error("invalid json: " + string(body))
  726. log.Error(err)
  727. return tracerr.Wrap(err)
  728. }
  729. // log.Info(string(body))
  730. // Validate response against swagger spec
  731. responseValidationInput := &swagger.ResponseValidationInput{
  732. RequestValidationInput: requestValidationInput,
  733. Status: resp.StatusCode,
  734. Header: resp.Header,
  735. }
  736. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  737. return swagger.ValidateResponse(ctx, responseValidationInput)
  738. }
  739. func doBadReq(method, path string, reqBody io.Reader, expectedResponseCode int) error {
  740. ctx := context.Background()
  741. client := &http.Client{}
  742. httpReq, _ := http.NewRequest(method, path, reqBody)
  743. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  744. if err != nil {
  745. return tracerr.Wrap(err)
  746. }
  747. // Validate request against swagger spec
  748. requestValidationInput := &swagger.RequestValidationInput{
  749. Request: httpReq,
  750. PathParams: pathParams,
  751. Route: route,
  752. }
  753. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  754. if expectedResponseCode != 400 {
  755. return tracerr.Wrap(err)
  756. }
  757. log.Warn("The request does not match the API spec")
  758. }
  759. // Do API call
  760. resp, err := client.Do(httpReq)
  761. if err != nil {
  762. return tracerr.Wrap(err)
  763. }
  764. if resp.Body == nil {
  765. return tracerr.Wrap(errors.New("Nil body"))
  766. }
  767. //nolint
  768. defer resp.Body.Close()
  769. body, err := ioutil.ReadAll(resp.Body)
  770. if err != nil {
  771. return tracerr.Wrap(err)
  772. }
  773. if resp.StatusCode != expectedResponseCode {
  774. return tracerr.Wrap(fmt.Errorf("Unexpected response code: %d. Body: %s", resp.StatusCode, string(body)))
  775. }
  776. // Validate response against swagger spec
  777. responseValidationInput := &swagger.ResponseValidationInput{
  778. RequestValidationInput: requestValidationInput,
  779. Status: resp.StatusCode,
  780. Header: resp.Header,
  781. }
  782. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  783. return swagger.ValidateResponse(ctx, responseValidationInput)
  784. }
  785. // test helpers
  786. func getTimestamp(blockNum int64, blocks []common.Block) time.Time {
  787. for i := 0; i < len(blocks); i++ {
  788. if blocks[i].Num == blockNum {
  789. return blocks[i].Timestamp
  790. }
  791. }
  792. panic("timesamp not found")
  793. }
  794. func getTokenByID(id common.TokenID, tokens []historydb.TokenWithUSD) historydb.TokenWithUSD {
  795. for i := 0; i < len(tokens); i++ {
  796. if tokens[i].TokenID == id {
  797. return tokens[i]
  798. }
  799. }
  800. panic("token not found")
  801. }
  802. func getTokenByIdx(idx common.Idx, tokens []historydb.TokenWithUSD, accs []common.Account) historydb.TokenWithUSD {
  803. for _, acc := range accs {
  804. if idx == acc.Idx {
  805. return getTokenByID(acc.TokenID, tokens)
  806. }
  807. }
  808. panic("token not found")
  809. }
  810. func getAccountByIdx(idx common.Idx, accs []common.Account) *common.Account {
  811. for _, acc := range accs {
  812. if acc.Idx == idx {
  813. return &acc
  814. }
  815. }
  816. panic("account not found")
  817. }
  818. func getBlockByNum(ethBlockNum int64, blocks []common.Block) common.Block {
  819. for _, b := range blocks {
  820. if b.Num == ethBlockNum {
  821. return b
  822. }
  823. }
  824. panic("block not found")
  825. }
  826. func getCoordinatorByBidder(bidder ethCommon.Address, coordinators []historydb.CoordinatorAPI) historydb.CoordinatorAPI {
  827. var coordLastUpdate historydb.CoordinatorAPI
  828. found := false
  829. for _, c := range coordinators {
  830. if c.Bidder == bidder {
  831. coordLastUpdate = c
  832. found = true
  833. }
  834. }
  835. if !found {
  836. panic("coordinator not found")
  837. }
  838. return coordLastUpdate
  839. }