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.

890 lines
25 KiB

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