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.

787 lines
22 KiB

4 years ago
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
3 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
4 years ago
  1. package api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "math/big"
  10. "net/http"
  11. "os"
  12. "strconv"
  13. "testing"
  14. "time"
  15. ethCommon "github.com/ethereum/go-ethereum/common"
  16. swagger "github.com/getkin/kin-openapi/openapi3filter"
  17. "github.com/gin-gonic/gin"
  18. "github.com/hermeznetwork/hermez-node/common"
  19. "github.com/hermeznetwork/hermez-node/db"
  20. "github.com/hermeznetwork/hermez-node/db/historydb"
  21. "github.com/hermeznetwork/hermez-node/db/l2db"
  22. "github.com/hermeznetwork/hermez-node/db/statedb"
  23. "github.com/hermeznetwork/hermez-node/log"
  24. "github.com/hermeznetwork/hermez-node/test"
  25. "github.com/hermeznetwork/hermez-node/test/til"
  26. "github.com/hermeznetwork/hermez-node/test/txsets"
  27. "github.com/hermeznetwork/tracerr"
  28. )
  29. // Pendinger is an interface that allows getting last returned item ID and PendingItems to be used for building fromItem
  30. // when testing paginated endpoints.
  31. type Pendinger interface {
  32. GetPending() (pendingItems, lastItemID uint64)
  33. Len() int
  34. New() Pendinger
  35. }
  36. const apiPort = ":4010"
  37. const apiURL = "http://localhost" + apiPort + "/"
  38. var SetBlockchain = `
  39. Type: Blockchain
  40. AddToken(1)
  41. AddToken(2)
  42. AddToken(3)
  43. AddToken(4)
  44. AddToken(5)
  45. AddToken(6)
  46. AddToken(7)
  47. AddToken(8)
  48. > block
  49. // Coordinator accounts, Idxs: 256, 257
  50. CreateAccountCoordinator(0) Coord
  51. CreateAccountCoordinator(1) Coord
  52. // close Block:0, Batch:1
  53. > batch
  54. CreateAccountDeposit(0) A: 11111111100000000000
  55. CreateAccountDeposit(1) C: 22222222200000000000
  56. CreateAccountCoordinator(0) C
  57. // close Block:0, Batch:2
  58. > batchL1
  59. // Expected balances:
  60. // Coord(0): 0, Coord(1): 0
  61. // C(0): 0
  62. CreateAccountDeposit(1) A: 33333333300000000000
  63. // close Block:0, Batch:3
  64. > batchL1
  65. // close Block:0, Batch:4
  66. > batchL1
  67. CreateAccountDepositTransfer(0) B-A: 44444444400000000000, 123444444400000000000
  68. // close Block:0, Batch:5
  69. > batchL1
  70. CreateAccountDeposit(0) D: 55555555500000000000
  71. // close Block:0, Batch:6
  72. > batchL1
  73. CreateAccountCoordinator(1) B
  74. Transfer(1) A-B: 11111100000000000 (2)
  75. Transfer(0) B-C: 22222200000000000 (3)
  76. // close Block:0, Batch:7
  77. > batchL1 // forge L1User{1}, forge L1Coord{2}, forge L2{2}
  78. Deposit(0) C: 66666666600000000000
  79. DepositTransfer(0) C-D: 77777777700000000000, 12377777700000000000
  80. Transfer(0) A-B: 33333300000000000 (111)
  81. Transfer(0) C-A: 44444400000000000 (222)
  82. Transfer(1) B-C: 55555500000000000 (123)
  83. Exit(0) A: 66666600000000000 (44)
  84. ForceTransfer(0) D-B: 77777700000000000
  85. ForceExit(0) B: 88888800000000000
  86. // close Block:0, Batch:8
  87. > batchL1
  88. > block
  89. Transfer(0) D-A: 99999900000000000 (77)
  90. Transfer(0) B-D: 12312300000000000 (55)
  91. // close Block:1, Batch:1
  92. > batchL1
  93. CreateAccountCoordinator(0) F
  94. CreateAccountCoordinator(0) G
  95. CreateAccountCoordinator(0) H
  96. CreateAccountCoordinator(0) I
  97. CreateAccountCoordinator(0) J
  98. CreateAccountCoordinator(0) K
  99. CreateAccountCoordinator(0) L
  100. CreateAccountCoordinator(0) M
  101. CreateAccountCoordinator(0) N
  102. CreateAccountCoordinator(0) O
  103. CreateAccountCoordinator(0) P
  104. CreateAccountCoordinator(5) G
  105. CreateAccountCoordinator(5) H
  106. CreateAccountCoordinator(5) I
  107. CreateAccountCoordinator(5) J
  108. CreateAccountCoordinator(5) K
  109. CreateAccountCoordinator(5) L
  110. CreateAccountCoordinator(5) M
  111. CreateAccountCoordinator(5) N
  112. CreateAccountCoordinator(5) O
  113. CreateAccountCoordinator(5) P
  114. CreateAccountCoordinator(2) G
  115. CreateAccountCoordinator(2) H
  116. CreateAccountCoordinator(2) I
  117. CreateAccountCoordinator(2) J
  118. CreateAccountCoordinator(2) K
  119. CreateAccountCoordinator(2) L
  120. CreateAccountCoordinator(2) M
  121. CreateAccountCoordinator(2) N
  122. CreateAccountCoordinator(2) O
  123. CreateAccountCoordinator(2) P
  124. > batch
  125. > block
  126. > batch
  127. > block
  128. > batch
  129. > block
  130. `
  131. type testCommon struct {
  132. blocks []common.Block
  133. tokens []historydb.TokenWithUSD
  134. batches []testBatch
  135. fullBatches []testFullBatch
  136. coordinators []historydb.CoordinatorAPI
  137. accounts []testAccount
  138. txs []testTx
  139. exits []testExit
  140. poolTxsToSend []testPoolTxSend
  141. poolTxsToReceive []testPoolTxReceive
  142. auths []testAuth
  143. router *swagger.Router
  144. bids []testBid
  145. slots []testSlot
  146. auctionVars common.AuctionVariables
  147. rollupVars common.RollupVariables
  148. wdelayerVars common.WDelayerVariables
  149. nextForgers []NextForger
  150. }
  151. var tc testCommon
  152. var config configAPI
  153. var api *API
  154. // TestMain initializes the API server, and fill HistoryDB and StateDB with fake data,
  155. // emulating the task of the synchronizer in order to have data to be returned
  156. // by the API endpoints that will be tested
  157. func TestMain(m *testing.M) {
  158. // Initializations
  159. // Swagger
  160. router := swagger.NewRouter().WithSwaggerFromFile("./swagger.yml")
  161. // HistoryDB
  162. pass := os.Getenv("POSTGRES_PASS")
  163. database, err := db.InitSQLDB(5432, "localhost", "hermez", pass, "hermez")
  164. if err != nil {
  165. panic(err)
  166. }
  167. hdb := historydb.NewHistoryDB(database)
  168. if err != nil {
  169. panic(err)
  170. }
  171. // StateDB
  172. dir, err := ioutil.TempDir("", "tmpdb")
  173. if err != nil {
  174. panic(err)
  175. }
  176. defer func() {
  177. if err := os.RemoveAll(dir); err != nil {
  178. panic(err)
  179. }
  180. }()
  181. sdb, err := statedb.NewStateDB(dir, 128, statedb.TypeTxSelector, 0)
  182. if err != nil {
  183. panic(err)
  184. }
  185. // L2DB
  186. l2DB := l2db.NewL2DB(database, 10, 1000, 24*time.Hour)
  187. test.WipeDB(l2DB.DB()) // this will clean HistoryDB and L2DB
  188. // Config (smart contract constants)
  189. chainID := uint16(0)
  190. _config := getConfigTest(chainID)
  191. config = configAPI{
  192. RollupConstants: *newRollupConstants(_config.RollupConstants),
  193. AuctionConstants: _config.AuctionConstants,
  194. WDelayerConstants: _config.WDelayerConstants,
  195. }
  196. // API
  197. apiGin := gin.Default()
  198. api, err = NewAPI(
  199. true,
  200. true,
  201. apiGin,
  202. hdb,
  203. sdb,
  204. l2DB,
  205. &_config,
  206. )
  207. if err != nil {
  208. panic(err)
  209. }
  210. // Start server
  211. server := &http.Server{Addr: apiPort, Handler: apiGin}
  212. go func() {
  213. if err := server.ListenAndServe(); err != nil && tracerr.Unwrap(err) != http.ErrServerClosed {
  214. panic(err)
  215. }
  216. }()
  217. // Reset DB
  218. test.WipeDB(api.h.DB())
  219. // Genratre blockchain data with til
  220. tcc := til.NewContext(chainID, common.RollupConstMaxL1UserTx)
  221. tilCfgExtra := til.ConfigExtra{
  222. BootCoordAddr: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  223. CoordUser: "Coord",
  224. }
  225. blocksData, err := tcc.GenerateBlocks(SetBlockchain)
  226. if err != nil {
  227. panic(err)
  228. }
  229. err = tcc.FillBlocksExtra(blocksData, &tilCfgExtra)
  230. if err != nil {
  231. panic(err)
  232. }
  233. AddAditionalInformation(blocksData)
  234. // Generate L2 Txs with til
  235. commonPoolTxs, err := tcc.GeneratePoolL2Txs(txsets.SetPoolL2MinimumFlow0)
  236. if err != nil {
  237. panic(err)
  238. }
  239. // Extract til generated data, and add it to HistoryDB
  240. var commonBlocks []common.Block
  241. var commonBatches []common.Batch
  242. var commonAccounts []common.Account
  243. var commonExitTree []common.ExitInfo
  244. var commonL1Txs []common.L1Tx
  245. var commonL2Txs []common.L2Tx
  246. // Add ETH token at the beginning of the array
  247. testTokens := []historydb.TokenWithUSD{}
  248. ethUSD := float64(500)
  249. ethNow := time.Now()
  250. testTokens = append(testTokens, historydb.TokenWithUSD{
  251. TokenID: test.EthToken.TokenID,
  252. EthBlockNum: test.EthToken.EthBlockNum,
  253. EthAddr: test.EthToken.EthAddr,
  254. Name: test.EthToken.Name,
  255. Symbol: test.EthToken.Symbol,
  256. Decimals: test.EthToken.Decimals,
  257. USD: &ethUSD,
  258. USDUpdate: &ethNow,
  259. })
  260. err = api.h.UpdateTokenValue(test.EthToken.Symbol, ethUSD)
  261. if err != nil {
  262. panic(err)
  263. }
  264. for _, block := range blocksData {
  265. // Insert block into HistoryDB
  266. // nolint reason: block is used as read only in the function
  267. if err := api.h.AddBlockSCData(&block); err != nil { //nolint:gosec
  268. log.Error(err)
  269. panic(err)
  270. }
  271. // Extract data
  272. commonBlocks = append(commonBlocks, block.Block)
  273. for i, tkn := range block.Rollup.AddedTokens {
  274. token := historydb.TokenWithUSD{
  275. TokenID: tkn.TokenID,
  276. EthBlockNum: tkn.EthBlockNum,
  277. EthAddr: tkn.EthAddr,
  278. Name: tkn.Name,
  279. Symbol: tkn.Symbol,
  280. Decimals: tkn.Decimals,
  281. }
  282. value := float64(i + 423)
  283. now := time.Now().UTC()
  284. token.USD = &value
  285. token.USDUpdate = &now
  286. // Set value in DB
  287. err = api.h.UpdateTokenValue(token.Symbol, value)
  288. if err != nil {
  289. panic(err)
  290. }
  291. testTokens = append(testTokens, token)
  292. }
  293. // Set USD value for tokens in DB
  294. commonL1Txs = append(commonL1Txs, block.Rollup.L1UserTxs...)
  295. for _, batch := range block.Rollup.Batches {
  296. commonL2Txs = append(commonL2Txs, batch.L2Txs...)
  297. for i := range batch.CreatedAccounts {
  298. batch.CreatedAccounts[i].Nonce = common.Nonce(i)
  299. commonAccounts = append(commonAccounts, batch.CreatedAccounts[i])
  300. }
  301. commonBatches = append(commonBatches, batch.Batch)
  302. commonExitTree = append(commonExitTree, batch.ExitTree...)
  303. commonL1Txs = append(commonL1Txs, batch.L1CoordinatorTxs...)
  304. }
  305. }
  306. // lastBlockNum2 := blocksData[len(blocksData)-1].Block.EthBlockNum
  307. // Add accounts to StateDB
  308. for i := 0; i < len(commonAccounts); i++ {
  309. if _, err := api.s.CreateAccount(commonAccounts[i].Idx, &commonAccounts[i]); err != nil {
  310. panic(err)
  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. Bidder: ethCommon.HexToAddress("0x0111111111111111111111111111111111111111"),
  421. Forger: ethCommon.HexToAddress("0x0111111111111111111111111111111111111111"),
  422. URL: "https://bootCoordinator",
  423. },
  424. }
  425. // Set next forgers: set all as boot coordinator then replace the non boot coordinators
  426. nextForgers := []NextForger{}
  427. var initBlock int64 = 140
  428. var deltaBlocks int64 = 40
  429. for i := 1; i < int(auctionVars.ClosedAuctionSlots)+2; i++ {
  430. fromBlock := initBlock + deltaBlocks*int64(i-1)
  431. bootForger.Period = Period{
  432. SlotNum: int64(i),
  433. FromBlock: fromBlock,
  434. ToBlock: fromBlock + deltaBlocks - 1,
  435. }
  436. nextForgers = append(nextForgers, bootForger)
  437. }
  438. // Set next forgers that aren't the boot coordinator
  439. nonBootForger := historydb.CoordinatorAPI{
  440. Bidder: commonCoords[0].Bidder,
  441. Forger: commonCoords[0].Forger,
  442. URL: commonCoords[0].URL + ".new",
  443. }
  444. // Slot 4
  445. nextForgers[3].Coordinator = nonBootForger
  446. // Slot 7
  447. nextForgers[6].Coordinator = nonBootForger
  448. var buckets [common.RollupConstNumBuckets]common.BucketParams
  449. for i := range buckets {
  450. buckets[i].CeilUSD = big.NewInt(int64(i) * 10)
  451. buckets[i].Withdrawals = big.NewInt(int64(i) * 100)
  452. buckets[i].BlockWithdrawalRate = big.NewInt(int64(i) * 1000)
  453. buckets[i].MaxWithdrawals = big.NewInt(int64(i) * 10000)
  454. }
  455. // Generate SC vars and add them to HistoryDB (if needed)
  456. rollupVars := common.RollupVariables{
  457. EthBlockNum: int64(3),
  458. FeeAddToken: big.NewInt(100),
  459. ForgeL1L2BatchTimeout: int64(44),
  460. WithdrawalDelay: uint64(3000),
  461. Buckets: buckets,
  462. SafeMode: false,
  463. }
  464. wdelayerVars := common.WDelayerVariables{
  465. WithdrawalDelay: uint64(3000),
  466. }
  467. // Generate test data, as expected to be received/sended from/to the API
  468. testCoords := genTestCoordinators(commonCoords)
  469. testBids := genTestBids(commonBlocks, testCoords, bids)
  470. testExits := genTestExits(commonExitTree, testTokens, commonAccounts)
  471. testTxs := genTestTxs(commonL1Txs, commonL2Txs, commonAccounts, testTokens, commonBlocks)
  472. testBatches, testFullBatches := genTestBatches(commonBlocks, commonBatches, testTxs)
  473. poolTxsToSend, poolTxsToReceive := genTestPoolTxs(commonPoolTxs, testTokens, commonAccounts)
  474. tc = testCommon{
  475. blocks: commonBlocks,
  476. tokens: testTokens,
  477. batches: testBatches,
  478. fullBatches: testFullBatches,
  479. coordinators: testCoords,
  480. accounts: genTestAccounts(commonAccounts, testTokens),
  481. txs: testTxs,
  482. exits: testExits,
  483. poolTxsToSend: poolTxsToSend,
  484. poolTxsToReceive: poolTxsToReceive,
  485. auths: genTestAuths(test.GenAuths(5, _config.ChainID, _config.HermezAddress)),
  486. router: router,
  487. bids: testBids,
  488. slots: api.genTestSlots(
  489. 20,
  490. commonBlocks[len(commonBlocks)-1].Num,
  491. testBids,
  492. auctionVars,
  493. ),
  494. auctionVars: auctionVars,
  495. rollupVars: rollupVars,
  496. wdelayerVars: wdelayerVars,
  497. nextForgers: nextForgers,
  498. }
  499. // Run tests
  500. result := m.Run()
  501. // Fake server
  502. if os.Getenv("FAKE_SERVER") == "yes" {
  503. for {
  504. log.Info("Running fake server at " + apiURL + " until ^C is received")
  505. time.Sleep(30 * time.Second)
  506. }
  507. }
  508. // Stop server
  509. if err := server.Shutdown(context.Background()); err != nil {
  510. panic(err)
  511. }
  512. if err := database.Close(); err != nil {
  513. panic(err)
  514. }
  515. if err := os.RemoveAll(dir); err != nil {
  516. panic(err)
  517. }
  518. os.Exit(result)
  519. }
  520. func doGoodReqPaginated(
  521. path, order string,
  522. iterStruct Pendinger,
  523. appendIter func(res interface{}),
  524. ) error {
  525. var next uint64
  526. firstIte := true
  527. expectedTotal := 0
  528. totalReceived := 0
  529. for {
  530. // Calculate fromItem
  531. iterPath := path
  532. if !firstIte {
  533. iterPath += "&fromItem=" + strconv.Itoa(int(next))
  534. }
  535. // Call API to get this iteration items
  536. iterStruct = iterStruct.New()
  537. if err := doGoodReq(
  538. "GET", iterPath+"&order="+order, nil,
  539. iterStruct,
  540. ); err != nil {
  541. return tracerr.Wrap(err)
  542. }
  543. appendIter(iterStruct)
  544. // Keep iterating?
  545. remaining, lastID := iterStruct.GetPending()
  546. if remaining == 0 {
  547. break
  548. }
  549. if order == historydb.OrderDesc {
  550. next = lastID - 1
  551. } else {
  552. next = lastID + 1
  553. }
  554. // Check that the expected amount of items is consistent across iterations
  555. totalReceived += iterStruct.Len()
  556. if firstIte {
  557. firstIte = false
  558. expectedTotal = totalReceived + int(remaining)
  559. }
  560. if expectedTotal != totalReceived+int(remaining) {
  561. panic(fmt.Sprintf(
  562. "pagination error, totalReceived + remaining should be %d, but is %d",
  563. expectedTotal, totalReceived+int(remaining),
  564. ))
  565. }
  566. }
  567. return nil
  568. }
  569. func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{}) error {
  570. ctx := context.Background()
  571. client := &http.Client{}
  572. httpReq, err := http.NewRequest(method, path, reqBody)
  573. if err != nil {
  574. return tracerr.Wrap(err)
  575. }
  576. if reqBody != nil {
  577. httpReq.Header.Add("Content-Type", "application/json")
  578. }
  579. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  580. if err != nil {
  581. return tracerr.Wrap(err)
  582. }
  583. // Validate request against swagger spec
  584. requestValidationInput := &swagger.RequestValidationInput{
  585. Request: httpReq,
  586. PathParams: pathParams,
  587. Route: route,
  588. }
  589. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  590. return tracerr.Wrap(err)
  591. }
  592. // Do API call
  593. resp, err := client.Do(httpReq)
  594. if err != nil {
  595. return tracerr.Wrap(err)
  596. }
  597. if resp.Body == nil && returnStruct != nil {
  598. return tracerr.Wrap(errors.New("Nil body"))
  599. }
  600. //nolint
  601. defer resp.Body.Close()
  602. body, err := ioutil.ReadAll(resp.Body)
  603. if err != nil {
  604. return tracerr.Wrap(err)
  605. }
  606. if resp.StatusCode != 200 {
  607. return tracerr.Wrap(fmt.Errorf("%d response. Body: %s", resp.StatusCode, string(body)))
  608. }
  609. if returnStruct == nil {
  610. return nil
  611. }
  612. // Unmarshal body into return struct
  613. if err := json.Unmarshal(body, returnStruct); err != nil {
  614. log.Error("invalid json: " + string(body))
  615. log.Error(err)
  616. return tracerr.Wrap(err)
  617. }
  618. // log.Info(string(body))
  619. // Validate response against swagger spec
  620. responseValidationInput := &swagger.ResponseValidationInput{
  621. RequestValidationInput: requestValidationInput,
  622. Status: resp.StatusCode,
  623. Header: resp.Header,
  624. }
  625. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  626. return swagger.ValidateResponse(ctx, responseValidationInput)
  627. }
  628. func doBadReq(method, path string, reqBody io.Reader, expectedResponseCode int) error {
  629. ctx := context.Background()
  630. client := &http.Client{}
  631. httpReq, _ := http.NewRequest(method, path, reqBody)
  632. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  633. if err != nil {
  634. return tracerr.Wrap(err)
  635. }
  636. // Validate request against swagger spec
  637. requestValidationInput := &swagger.RequestValidationInput{
  638. Request: httpReq,
  639. PathParams: pathParams,
  640. Route: route,
  641. }
  642. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  643. if expectedResponseCode != 400 {
  644. return tracerr.Wrap(err)
  645. }
  646. log.Warn("The request does not match the API spec")
  647. }
  648. // Do API call
  649. resp, err := client.Do(httpReq)
  650. if err != nil {
  651. return tracerr.Wrap(err)
  652. }
  653. if resp.Body == nil {
  654. return tracerr.Wrap(errors.New("Nil body"))
  655. }
  656. //nolint
  657. defer resp.Body.Close()
  658. body, err := ioutil.ReadAll(resp.Body)
  659. if err != nil {
  660. return tracerr.Wrap(err)
  661. }
  662. if resp.StatusCode != expectedResponseCode {
  663. return tracerr.Wrap(fmt.Errorf("Unexpected response code: %d. Body: %s", resp.StatusCode, string(body)))
  664. }
  665. // Validate response against swagger spec
  666. responseValidationInput := &swagger.ResponseValidationInput{
  667. RequestValidationInput: requestValidationInput,
  668. Status: resp.StatusCode,
  669. Header: resp.Header,
  670. }
  671. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  672. return swagger.ValidateResponse(ctx, responseValidationInput)
  673. }
  674. // test helpers
  675. func getTimestamp(blockNum int64, blocks []common.Block) time.Time {
  676. for i := 0; i < len(blocks); i++ {
  677. if blocks[i].Num == blockNum {
  678. return blocks[i].Timestamp
  679. }
  680. }
  681. panic("timesamp not found")
  682. }
  683. func getTokenByID(id common.TokenID, tokens []historydb.TokenWithUSD) historydb.TokenWithUSD {
  684. for i := 0; i < len(tokens); i++ {
  685. if tokens[i].TokenID == id {
  686. return tokens[i]
  687. }
  688. }
  689. panic("token not found")
  690. }
  691. func getTokenByIdx(idx common.Idx, tokens []historydb.TokenWithUSD, accs []common.Account) historydb.TokenWithUSD {
  692. for _, acc := range accs {
  693. if idx == acc.Idx {
  694. return getTokenByID(acc.TokenID, tokens)
  695. }
  696. }
  697. panic("token not found")
  698. }
  699. func getAccountByIdx(idx common.Idx, accs []common.Account) *common.Account {
  700. for _, acc := range accs {
  701. if acc.Idx == idx {
  702. return &acc
  703. }
  704. }
  705. panic("account not found")
  706. }
  707. func getBlockByNum(ethBlockNum int64, blocks []common.Block) common.Block {
  708. for _, b := range blocks {
  709. if b.Num == ethBlockNum {
  710. return b
  711. }
  712. }
  713. panic("block not found")
  714. }
  715. func getCoordinatorByBidder(bidder ethCommon.Address, coordinators []historydb.CoordinatorAPI) historydb.CoordinatorAPI {
  716. var coordLastUpdate historydb.CoordinatorAPI
  717. found := false
  718. for _, c := range coordinators {
  719. if c.Bidder == bidder {
  720. coordLastUpdate = c
  721. found = true
  722. }
  723. }
  724. if !found {
  725. panic("coordinator not found")
  726. }
  727. return coordLastUpdate
  728. }