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.

785 lines
22 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/http"
  11. "os"
  12. "strconv"
  13. "testing"
  14. "time"
  15. ethCommon "github.com/ethereum/go-ethereum/common"
  16. swagger "github.com/getkin/kin-openapi/openapi3filter"
  17. "github.com/gin-gonic/gin"
  18. "github.com/hermeznetwork/hermez-node/common"
  19. "github.com/hermeznetwork/hermez-node/db"
  20. "github.com/hermeznetwork/hermez-node/db/historydb"
  21. "github.com/hermeznetwork/hermez-node/db/l2db"
  22. "github.com/hermeznetwork/hermez-node/db/statedb"
  23. "github.com/hermeznetwork/hermez-node/log"
  24. "github.com/hermeznetwork/hermez-node/test"
  25. "github.com/hermeznetwork/hermez-node/test/til"
  26. "github.com/hermeznetwork/tracerr"
  27. )
  28. // Pendinger is an interface that allows getting last returned item ID and PendingItems to be used for building fromItem
  29. // when testing paginated endpoints.
  30. type Pendinger interface {
  31. GetPending() (pendingItems, lastItemID uint64)
  32. Len() int
  33. New() Pendinger
  34. }
  35. const apiPort = ":4010"
  36. const apiURL = "http://localhost" + apiPort + "/"
  37. var SetBlockchain = `
  38. Type: Blockchain
  39. AddToken(1)
  40. AddToken(2)
  41. AddToken(3)
  42. AddToken(4)
  43. AddToken(5)
  44. AddToken(6)
  45. AddToken(7)
  46. AddToken(8)
  47. > block
  48. // Coordinator accounts, Idxs: 256, 257
  49. CreateAccountCoordinator(0) Coord
  50. CreateAccountCoordinator(1) Coord
  51. // close Block:0, Batch:0
  52. > batch
  53. CreateAccountDeposit(0) A: 11111111100000000000
  54. CreateAccountDeposit(1) C: 22222222200000000000
  55. CreateAccountCoordinator(0) C
  56. // close Block:0, Batch:1
  57. > batchL1
  58. // Expected balances:
  59. // Coord(0): 0, Coord(1): 0
  60. // C(0): 0
  61. CreateAccountDeposit(1) A: 33333333300000000000
  62. // close Block:0, Batch:2
  63. > batchL1
  64. // close Block:0, Batch:3
  65. > batchL1
  66. CreateAccountDepositTransfer(0) B-A: 44444444400000000000, 123444444400000000000
  67. // close Block:0, Batch:4
  68. > batchL1
  69. CreateAccountDeposit(0) D: 55555555500000000000
  70. // close Block:0, Batch:5
  71. > batchL1
  72. CreateAccountCoordinator(1) B
  73. Transfer(1) A-B: 11111100000000000 (2)
  74. Transfer(0) B-C: 22222200000000000 (3)
  75. // close Block:0, Batch:6
  76. > batchL1 // forge L1User{1}, forge L1Coord{2}, forge L2{2}
  77. Deposit(0) C: 66666666600000000000
  78. DepositTransfer(0) C-D: 77777777700000000000, 12377777700000000000
  79. Transfer(0) A-B: 33333300000000000 (111)
  80. Transfer(0) C-A: 44444400000000000 (222)
  81. Transfer(1) B-C: 55555500000000000 (123)
  82. Exit(0) A: 66666600000000000 (44)
  83. ForceTransfer(0) D-B: 77777700000000000
  84. ForceExit(0) B: 88888800000000000
  85. // close Block:0, Batch:7
  86. > batchL1
  87. > block
  88. Transfer(0) D-A: 99999900000000000 (77)
  89. Transfer(0) B-D: 12312300000000000 (55)
  90. // close Block:1, Batch:0
  91. > batchL1
  92. CreateAccountCoordinator(0) F
  93. CreateAccountCoordinator(0) G
  94. CreateAccountCoordinator(0) H
  95. CreateAccountCoordinator(0) I
  96. CreateAccountCoordinator(0) J
  97. CreateAccountCoordinator(0) K
  98. CreateAccountCoordinator(0) L
  99. CreateAccountCoordinator(0) M
  100. CreateAccountCoordinator(0) N
  101. CreateAccountCoordinator(0) O
  102. CreateAccountCoordinator(0) P
  103. CreateAccountCoordinator(5) G
  104. CreateAccountCoordinator(5) H
  105. CreateAccountCoordinator(5) I
  106. CreateAccountCoordinator(5) J
  107. CreateAccountCoordinator(5) K
  108. CreateAccountCoordinator(5) L
  109. CreateAccountCoordinator(5) M
  110. CreateAccountCoordinator(5) N
  111. CreateAccountCoordinator(5) O
  112. CreateAccountCoordinator(5) P
  113. CreateAccountCoordinator(2) G
  114. CreateAccountCoordinator(2) H
  115. CreateAccountCoordinator(2) I
  116. CreateAccountCoordinator(2) J
  117. CreateAccountCoordinator(2) K
  118. CreateAccountCoordinator(2) L
  119. CreateAccountCoordinator(2) M
  120. CreateAccountCoordinator(2) N
  121. CreateAccountCoordinator(2) O
  122. CreateAccountCoordinator(2) P
  123. > batch
  124. > block
  125. > batch
  126. > block
  127. > batch
  128. > block
  129. `
  130. type testCommon struct {
  131. blocks []common.Block
  132. tokens []historydb.TokenWithUSD
  133. batches []testBatch
  134. fullBatches []testFullBatch
  135. coordinators []historydb.CoordinatorAPI
  136. accounts []testAccount
  137. txs []testTx
  138. exits []testExit
  139. poolTxsToSend []testPoolTxSend
  140. poolTxsToReceive []testPoolTxReceive
  141. auths []testAuth
  142. router *swagger.Router
  143. bids []testBid
  144. slots []testSlot
  145. auctionVars common.AuctionVariables
  146. rollupVars common.RollupVariables
  147. wdelayerVars common.WDelayerVariables
  148. nextForgers []NextForger
  149. }
  150. var tc testCommon
  151. var config configAPI
  152. var api *API
  153. // TestMain initializes the API server, and fill HistoryDB and StateDB with fake data,
  154. // emulating the task of the synchronizer in order to have data to be returned
  155. // by the API endpoints that will be tested
  156. func TestMain(m *testing.M) {
  157. // Initializations
  158. // Swagger
  159. router := swagger.NewRouter().WithSwaggerFromFile("./swagger.yml")
  160. // HistoryDB
  161. pass := os.Getenv("POSTGRES_PASS")
  162. database, err := db.InitSQLDB(5432, "localhost", "hermez", pass, "hermez")
  163. if err != nil {
  164. panic(err)
  165. }
  166. hdb := historydb.NewHistoryDB(database)
  167. if err != nil {
  168. panic(err)
  169. }
  170. // StateDB
  171. dir, err := ioutil.TempDir("", "tmpdb")
  172. if err != nil {
  173. panic(err)
  174. }
  175. defer func() {
  176. if err := os.RemoveAll(dir); err != nil {
  177. panic(err)
  178. }
  179. }()
  180. sdb, err := statedb.NewStateDB(dir, 128, statedb.TypeTxSelector, 0)
  181. if err != nil {
  182. panic(err)
  183. }
  184. // L2DB
  185. l2DB := l2db.NewL2DB(database, 10, 1000, 24*time.Hour)
  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. sdb,
  203. l2DB,
  204. &_config,
  205. )
  206. if err != nil {
  207. panic(err)
  208. }
  209. // Start server
  210. server := &http.Server{Addr: apiPort, Handler: apiGin}
  211. go func() {
  212. if err := server.ListenAndServe(); err != nil && tracerr.Unwrap(err) != http.ErrServerClosed {
  213. panic(err)
  214. }
  215. }()
  216. // Reset DB
  217. test.WipeDB(api.h.DB())
  218. // Genratre blockchain data with til
  219. tcc := til.NewContext(chainID, common.RollupConstMaxL1UserTx)
  220. tilCfgExtra := til.ConfigExtra{
  221. BootCoordAddr: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  222. CoordUser: "Coord",
  223. }
  224. blocksData, err := tcc.GenerateBlocks(SetBlockchain)
  225. if err != nil {
  226. panic(err)
  227. }
  228. err = tcc.FillBlocksExtra(blocksData, &tilCfgExtra)
  229. if err != nil {
  230. panic(err)
  231. }
  232. AddAditionalInformation(blocksData)
  233. // Generate L2 Txs with til
  234. commonPoolTxs, err := tcc.GeneratePoolL2Txs(til.SetPoolL2MinimumFlow0)
  235. if err != nil {
  236. panic(err)
  237. }
  238. // Extract til generated data, and add it to HistoryDB
  239. var commonBlocks []common.Block
  240. var commonBatches []common.Batch
  241. var commonAccounts []common.Account
  242. var commonExitTree []common.ExitInfo
  243. var commonL1Txs []common.L1Tx
  244. var commonL2Txs []common.L2Tx
  245. // Add ETH token at the beginning of the array
  246. testTokens := []historydb.TokenWithUSD{}
  247. ethUSD := float64(500)
  248. ethNow := time.Now()
  249. testTokens = append(testTokens, historydb.TokenWithUSD{
  250. TokenID: test.EthToken.TokenID,
  251. EthBlockNum: test.EthToken.EthBlockNum,
  252. EthAddr: test.EthToken.EthAddr,
  253. Name: test.EthToken.Name,
  254. Symbol: test.EthToken.Symbol,
  255. Decimals: test.EthToken.Decimals,
  256. USD: &ethUSD,
  257. USDUpdate: &ethNow,
  258. })
  259. err = api.h.UpdateTokenValue(test.EthToken.Symbol, ethUSD)
  260. if err != nil {
  261. panic(err)
  262. }
  263. for _, block := range blocksData {
  264. // Insert block into HistoryDB
  265. // nolint reason: block is used as read only in the function
  266. if err := api.h.AddBlockSCData(&block); err != nil { //nolint:gosec
  267. panic(err)
  268. }
  269. // Extract data
  270. commonBlocks = append(commonBlocks, block.Block)
  271. for i, tkn := range block.Rollup.AddedTokens {
  272. token := historydb.TokenWithUSD{
  273. TokenID: tkn.TokenID,
  274. EthBlockNum: tkn.EthBlockNum,
  275. EthAddr: tkn.EthAddr,
  276. Name: tkn.Name,
  277. Symbol: tkn.Symbol,
  278. Decimals: tkn.Decimals,
  279. }
  280. value := float64(i + 423)
  281. now := time.Now().UTC()
  282. token.USD = &value
  283. token.USDUpdate = &now
  284. // Set value in DB
  285. err = api.h.UpdateTokenValue(token.Symbol, value)
  286. if err != nil {
  287. panic(err)
  288. }
  289. testTokens = append(testTokens, token)
  290. }
  291. // Set USD value for tokens in DB
  292. commonL1Txs = append(commonL1Txs, block.Rollup.L1UserTxs...)
  293. for _, batch := range block.Rollup.Batches {
  294. commonL2Txs = append(commonL2Txs, batch.L2Txs...)
  295. for i := range batch.CreatedAccounts {
  296. batch.CreatedAccounts[i].Nonce = common.Nonce(i)
  297. commonAccounts = append(commonAccounts, batch.CreatedAccounts[i])
  298. }
  299. commonBatches = append(commonBatches, batch.Batch)
  300. commonExitTree = append(commonExitTree, batch.ExitTree...)
  301. commonL1Txs = append(commonL1Txs, batch.L1CoordinatorTxs...)
  302. }
  303. }
  304. // lastBlockNum2 := blocksData[len(blocksData)-1].Block.EthBlockNum
  305. // Add accounts to StateDB
  306. for i := 0; i < len(commonAccounts); i++ {
  307. if _, err := api.s.CreateAccount(commonAccounts[i].Idx, &commonAccounts[i]); err != nil {
  308. panic(err)
  309. }
  310. }
  311. // Generate Coordinators and add them to HistoryDB
  312. const nCoords = 10
  313. commonCoords := test.GenCoordinators(nCoords, commonBlocks)
  314. // Update one coordinator to test behaviour when bidder address is repeated
  315. updatedCoordBlock := commonCoords[len(commonCoords)-1].EthBlockNum
  316. commonCoords = append(commonCoords, common.Coordinator{
  317. Bidder: commonCoords[0].Bidder,
  318. Forger: commonCoords[0].Forger,
  319. EthBlockNum: updatedCoordBlock,
  320. URL: commonCoords[0].URL + ".new",
  321. })
  322. if err := api.h.AddCoordinators(commonCoords); err != nil {
  323. panic(err)
  324. }
  325. // Test next forgers
  326. // Set auction vars
  327. // Slots 3 and 6 will have bids that will be invalidated because of minBid update
  328. // Slots 4 and 7 will have valid bids, the rest will be cordinator slots
  329. var slot3MinBid int64 = 3
  330. var slot4MinBid int64 = 4
  331. var slot6MinBid int64 = 6
  332. var slot7MinBid int64 = 7
  333. // First update will indicate how things behave from slot 0
  334. var defaultSlotSetBid [6]*big.Int = [6]*big.Int{
  335. big.NewInt(10), // Slot 0 min bid
  336. big.NewInt(10), // Slot 1 min bid
  337. big.NewInt(10), // Slot 2 min bid
  338. big.NewInt(slot3MinBid), // Slot 3 min bid
  339. big.NewInt(slot4MinBid), // Slot 4 min bid
  340. big.NewInt(10), // Slot 5 min bid
  341. }
  342. auctionVars := common.AuctionVariables{
  343. EthBlockNum: int64(2),
  344. DonationAddress: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  345. DefaultSlotSetBid: defaultSlotSetBid,
  346. DefaultSlotSetBidSlotNum: 0,
  347. Outbidding: uint16(1),
  348. SlotDeadline: uint8(20),
  349. BootCoordinator: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  350. BootCoordinatorURL: "https://boot.coordinator.io",
  351. ClosedAuctionSlots: uint16(10),
  352. OpenAuctionSlots: uint16(20),
  353. }
  354. if err := api.h.AddAuctionVars(&auctionVars); err != nil {
  355. panic(err)
  356. }
  357. // Last update in auction vars will indicate how things will behave from slot 5
  358. defaultSlotSetBid = [6]*big.Int{
  359. big.NewInt(10), // Slot 5 min bid
  360. big.NewInt(slot6MinBid), // Slot 6 min bid
  361. big.NewInt(slot7MinBid), // Slot 7 min bid
  362. big.NewInt(10), // Slot 8 min bid
  363. big.NewInt(10), // Slot 9 min bid
  364. big.NewInt(10), // Slot 10 min bid
  365. }
  366. auctionVars = common.AuctionVariables{
  367. EthBlockNum: int64(3),
  368. DonationAddress: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  369. DefaultSlotSetBid: defaultSlotSetBid,
  370. DefaultSlotSetBidSlotNum: 5,
  371. Outbidding: uint16(1),
  372. SlotDeadline: uint8(20),
  373. BootCoordinator: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  374. BootCoordinatorURL: "https://boot.coordinator.io",
  375. ClosedAuctionSlots: uint16(10),
  376. OpenAuctionSlots: uint16(20),
  377. }
  378. if err := api.h.AddAuctionVars(&auctionVars); err != nil {
  379. panic(err)
  380. }
  381. // Generate Bids and add them to HistoryDB
  382. bids := []common.Bid{}
  383. // Slot 1 and 2, no bids, wins boot coordinator
  384. // Slot 3, below what's going to be the minimum (wins boot coordinator)
  385. bids = append(bids, common.Bid{
  386. SlotNum: 3,
  387. BidValue: big.NewInt(slot3MinBid - 1),
  388. EthBlockNum: commonBlocks[0].Num,
  389. Bidder: commonCoords[0].Bidder,
  390. })
  391. // Slot 4, valid bid (wins bidder)
  392. bids = append(bids, common.Bid{
  393. SlotNum: 4,
  394. BidValue: big.NewInt(slot4MinBid),
  395. EthBlockNum: commonBlocks[0].Num,
  396. Bidder: commonCoords[0].Bidder,
  397. })
  398. // Slot 5 no bids, wins boot coordinator
  399. // Slot 6, below what's going to be the minimum (wins boot coordinator)
  400. bids = append(bids, common.Bid{
  401. SlotNum: 6,
  402. BidValue: big.NewInt(slot6MinBid - 1),
  403. EthBlockNum: commonBlocks[0].Num,
  404. Bidder: commonCoords[0].Bidder,
  405. })
  406. // Slot 7, valid bid (wins bidder)
  407. bids = append(bids, common.Bid{
  408. SlotNum: 7,
  409. BidValue: big.NewInt(slot7MinBid),
  410. EthBlockNum: commonBlocks[0].Num,
  411. Bidder: commonCoords[0].Bidder,
  412. })
  413. if err = api.h.AddBids(bids); err != nil {
  414. panic(err)
  415. }
  416. bootForger := NextForger{
  417. Coordinator: historydb.CoordinatorAPI{
  418. Bidder: ethCommon.HexToAddress("0x0111111111111111111111111111111111111111"),
  419. Forger: ethCommon.HexToAddress("0x0111111111111111111111111111111111111111"),
  420. URL: "https://bootCoordinator",
  421. },
  422. }
  423. // Set next forgers: set all as boot coordinator then replace the non boot coordinators
  424. nextForgers := []NextForger{}
  425. var initBlock int64 = 140
  426. var deltaBlocks int64 = 40
  427. for i := 1; i < int(auctionVars.ClosedAuctionSlots)+2; i++ {
  428. fromBlock := initBlock + deltaBlocks*int64(i-1)
  429. bootForger.Period = Period{
  430. SlotNum: int64(i),
  431. FromBlock: fromBlock,
  432. ToBlock: fromBlock + deltaBlocks - 1,
  433. }
  434. nextForgers = append(nextForgers, bootForger)
  435. }
  436. // Set next forgers that aren't the boot coordinator
  437. nonBootForger := historydb.CoordinatorAPI{
  438. Bidder: commonCoords[0].Bidder,
  439. Forger: commonCoords[0].Forger,
  440. URL: commonCoords[0].URL + ".new",
  441. }
  442. // Slot 4
  443. nextForgers[3].Coordinator = nonBootForger
  444. // Slot 7
  445. nextForgers[6].Coordinator = nonBootForger
  446. var buckets [common.RollupConstNumBuckets]common.BucketParams
  447. for i := range buckets {
  448. buckets[i].CeilUSD = big.NewInt(int64(i) * 10)
  449. buckets[i].Withdrawals = big.NewInt(int64(i) * 100)
  450. buckets[i].BlockWithdrawalRate = big.NewInt(int64(i) * 1000)
  451. buckets[i].MaxWithdrawals = big.NewInt(int64(i) * 10000)
  452. }
  453. // Generate SC vars and add them to HistoryDB (if needed)
  454. rollupVars := common.RollupVariables{
  455. EthBlockNum: int64(3),
  456. FeeAddToken: big.NewInt(100),
  457. ForgeL1L2BatchTimeout: int64(44),
  458. WithdrawalDelay: uint64(3000),
  459. Buckets: buckets,
  460. SafeMode: false,
  461. }
  462. wdelayerVars := common.WDelayerVariables{
  463. WithdrawalDelay: uint64(3000),
  464. }
  465. // Generate test data, as expected to be received/sended from/to the API
  466. testCoords := genTestCoordinators(commonCoords)
  467. testBids := genTestBids(commonBlocks, testCoords, bids)
  468. testExits := genTestExits(commonExitTree, testTokens, commonAccounts)
  469. testTxs := genTestTxs(commonL1Txs, commonL2Txs, commonAccounts, testTokens, commonBlocks)
  470. testBatches, testFullBatches := genTestBatches(commonBlocks, commonBatches, testTxs)
  471. poolTxsToSend, poolTxsToReceive := genTestPoolTxs(commonPoolTxs, testTokens, commonAccounts)
  472. tc = testCommon{
  473. blocks: commonBlocks,
  474. tokens: testTokens,
  475. batches: testBatches,
  476. fullBatches: testFullBatches,
  477. coordinators: testCoords,
  478. accounts: genTestAccounts(commonAccounts, testTokens),
  479. txs: testTxs,
  480. exits: testExits,
  481. poolTxsToSend: poolTxsToSend,
  482. poolTxsToReceive: poolTxsToReceive,
  483. auths: genTestAuths(test.GenAuths(5, _config.ChainID, _config.HermezAddress)),
  484. router: router,
  485. bids: testBids,
  486. slots: api.genTestSlots(
  487. 20,
  488. commonBlocks[len(commonBlocks)-1].Num,
  489. testBids,
  490. auctionVars,
  491. ),
  492. auctionVars: auctionVars,
  493. rollupVars: rollupVars,
  494. wdelayerVars: wdelayerVars,
  495. nextForgers: nextForgers,
  496. }
  497. // Run tests
  498. result := m.Run()
  499. // Fake server
  500. if os.Getenv("FAKE_SERVER") == "yes" {
  501. for {
  502. log.Info("Running fake server at " + apiURL + " until ^C is received")
  503. time.Sleep(30 * time.Second)
  504. }
  505. }
  506. // Stop server
  507. if err := server.Shutdown(context.Background()); err != nil {
  508. panic(err)
  509. }
  510. if err := database.Close(); err != nil {
  511. panic(err)
  512. }
  513. if err := os.RemoveAll(dir); err != nil {
  514. panic(err)
  515. }
  516. os.Exit(result)
  517. }
  518. func doGoodReqPaginated(
  519. path, order string,
  520. iterStruct Pendinger,
  521. appendIter func(res interface{}),
  522. ) error {
  523. var next uint64
  524. firstIte := true
  525. expectedTotal := 0
  526. totalReceived := 0
  527. for {
  528. // Calculate fromItem
  529. iterPath := path
  530. if !firstIte {
  531. iterPath += "&fromItem=" + strconv.Itoa(int(next))
  532. }
  533. // Call API to get this iteration items
  534. iterStruct = iterStruct.New()
  535. if err := doGoodReq(
  536. "GET", iterPath+"&order="+order, nil,
  537. iterStruct,
  538. ); err != nil {
  539. return tracerr.Wrap(err)
  540. }
  541. appendIter(iterStruct)
  542. // Keep iterating?
  543. remaining, lastID := iterStruct.GetPending()
  544. if remaining == 0 {
  545. break
  546. }
  547. if order == historydb.OrderDesc {
  548. next = lastID - 1
  549. } else {
  550. next = lastID + 1
  551. }
  552. // Check that the expected amount of items is consistent across iterations
  553. totalReceived += iterStruct.Len()
  554. if firstIte {
  555. firstIte = false
  556. expectedTotal = totalReceived + int(remaining)
  557. }
  558. if expectedTotal != totalReceived+int(remaining) {
  559. panic(fmt.Sprintf(
  560. "pagination error, totalReceived + remaining should be %d, but is %d",
  561. expectedTotal, totalReceived+int(remaining),
  562. ))
  563. }
  564. }
  565. return nil
  566. }
  567. func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{}) error {
  568. ctx := context.Background()
  569. client := &http.Client{}
  570. httpReq, err := http.NewRequest(method, path, reqBody)
  571. if err != nil {
  572. return tracerr.Wrap(err)
  573. }
  574. if reqBody != nil {
  575. httpReq.Header.Add("Content-Type", "application/json")
  576. }
  577. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  578. if err != nil {
  579. return tracerr.Wrap(err)
  580. }
  581. // Validate request against swagger spec
  582. requestValidationInput := &swagger.RequestValidationInput{
  583. Request: httpReq,
  584. PathParams: pathParams,
  585. Route: route,
  586. }
  587. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  588. return tracerr.Wrap(err)
  589. }
  590. // Do API call
  591. resp, err := client.Do(httpReq)
  592. if err != nil {
  593. return tracerr.Wrap(err)
  594. }
  595. if resp.Body == nil && returnStruct != nil {
  596. return tracerr.Wrap(errors.New("Nil body"))
  597. }
  598. //nolint
  599. defer resp.Body.Close()
  600. body, err := ioutil.ReadAll(resp.Body)
  601. if err != nil {
  602. return tracerr.Wrap(err)
  603. }
  604. if resp.StatusCode != 200 {
  605. return tracerr.Wrap(fmt.Errorf("%d response. Body: %s", resp.StatusCode, string(body)))
  606. }
  607. if returnStruct == nil {
  608. return nil
  609. }
  610. // Unmarshal body into return struct
  611. if err := json.Unmarshal(body, returnStruct); err != nil {
  612. log.Error("invalid json: " + string(body))
  613. log.Error(err)
  614. return tracerr.Wrap(err)
  615. }
  616. // log.Info(string(body))
  617. // Validate response against swagger spec
  618. responseValidationInput := &swagger.ResponseValidationInput{
  619. RequestValidationInput: requestValidationInput,
  620. Status: resp.StatusCode,
  621. Header: resp.Header,
  622. }
  623. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  624. return swagger.ValidateResponse(ctx, responseValidationInput)
  625. }
  626. func doBadReq(method, path string, reqBody io.Reader, expectedResponseCode int) error {
  627. ctx := context.Background()
  628. client := &http.Client{}
  629. httpReq, _ := http.NewRequest(method, path, reqBody)
  630. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  631. if err != nil {
  632. return tracerr.Wrap(err)
  633. }
  634. // Validate request against swagger spec
  635. requestValidationInput := &swagger.RequestValidationInput{
  636. Request: httpReq,
  637. PathParams: pathParams,
  638. Route: route,
  639. }
  640. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  641. if expectedResponseCode != 400 {
  642. return tracerr.Wrap(err)
  643. }
  644. log.Warn("The request does not match the API spec")
  645. }
  646. // Do API call
  647. resp, err := client.Do(httpReq)
  648. if err != nil {
  649. return tracerr.Wrap(err)
  650. }
  651. if resp.Body == nil {
  652. return tracerr.Wrap(errors.New("Nil body"))
  653. }
  654. //nolint
  655. defer resp.Body.Close()
  656. body, err := ioutil.ReadAll(resp.Body)
  657. if err != nil {
  658. return tracerr.Wrap(err)
  659. }
  660. if resp.StatusCode != expectedResponseCode {
  661. return tracerr.Wrap(fmt.Errorf("Unexpected response code: %d. Body: %s", resp.StatusCode, string(body)))
  662. }
  663. // Validate response against swagger spec
  664. responseValidationInput := &swagger.ResponseValidationInput{
  665. RequestValidationInput: requestValidationInput,
  666. Status: resp.StatusCode,
  667. Header: resp.Header,
  668. }
  669. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  670. return swagger.ValidateResponse(ctx, responseValidationInput)
  671. }
  672. // test helpers
  673. func getTimestamp(blockNum int64, blocks []common.Block) time.Time {
  674. for i := 0; i < len(blocks); i++ {
  675. if blocks[i].Num == blockNum {
  676. return blocks[i].Timestamp
  677. }
  678. }
  679. panic("timesamp not found")
  680. }
  681. func getTokenByID(id common.TokenID, tokens []historydb.TokenWithUSD) historydb.TokenWithUSD {
  682. for i := 0; i < len(tokens); i++ {
  683. if tokens[i].TokenID == id {
  684. return tokens[i]
  685. }
  686. }
  687. panic("token not found")
  688. }
  689. func getTokenByIdx(idx common.Idx, tokens []historydb.TokenWithUSD, accs []common.Account) historydb.TokenWithUSD {
  690. for _, acc := range accs {
  691. if idx == acc.Idx {
  692. return getTokenByID(acc.TokenID, tokens)
  693. }
  694. }
  695. panic("token not found")
  696. }
  697. func getAccountByIdx(idx common.Idx, accs []common.Account) *common.Account {
  698. for _, acc := range accs {
  699. if acc.Idx == idx {
  700. return &acc
  701. }
  702. }
  703. panic("account not found")
  704. }
  705. func getBlockByNum(ethBlockNum int64, blocks []common.Block) common.Block {
  706. for _, b := range blocks {
  707. if b.Num == ethBlockNum {
  708. return b
  709. }
  710. }
  711. panic("block not found")
  712. }
  713. func getCoordinatorByBidder(bidder ethCommon.Address, coordinators []historydb.CoordinatorAPI) historydb.CoordinatorAPI {
  714. var coordLastUpdate historydb.CoordinatorAPI
  715. found := false
  716. for _, c := range coordinators {
  717. if c.Bidder == bidder {
  718. coordLastUpdate = c
  719. found = true
  720. }
  721. }
  722. if !found {
  723. panic("coordinator not found")
  724. }
  725. return coordLastUpdate
  726. }