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.

791 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/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. err = tcc.FillBlocksForgedL1UserTxs(blocksData)
  234. if err != nil {
  235. panic(err)
  236. }
  237. AddAditionalInformation(blocksData)
  238. // Generate L2 Txs with til
  239. commonPoolTxs, err := tcc.GeneratePoolL2Txs(txsets.SetPoolL2MinimumFlow0)
  240. if err != nil {
  241. panic(err)
  242. }
  243. // Extract til generated data, and add it to HistoryDB
  244. var commonBlocks []common.Block
  245. var commonBatches []common.Batch
  246. var commonAccounts []common.Account
  247. var commonExitTree []common.ExitInfo
  248. var commonL1Txs []common.L1Tx
  249. var commonL2Txs []common.L2Tx
  250. // Add ETH token at the beginning of the array
  251. testTokens := []historydb.TokenWithUSD{}
  252. ethUSD := float64(500)
  253. ethNow := time.Now()
  254. testTokens = append(testTokens, historydb.TokenWithUSD{
  255. TokenID: test.EthToken.TokenID,
  256. EthBlockNum: test.EthToken.EthBlockNum,
  257. EthAddr: test.EthToken.EthAddr,
  258. Name: test.EthToken.Name,
  259. Symbol: test.EthToken.Symbol,
  260. Decimals: test.EthToken.Decimals,
  261. USD: &ethUSD,
  262. USDUpdate: &ethNow,
  263. })
  264. err = api.h.UpdateTokenValue(test.EthToken.Symbol, ethUSD)
  265. if err != nil {
  266. panic(err)
  267. }
  268. for _, block := range blocksData {
  269. // Insert block into HistoryDB
  270. // nolint reason: block is used as read only in the function
  271. if err := api.h.AddBlockSCData(&block); err != nil { //nolint:gosec
  272. log.Error(err)
  273. panic(err)
  274. }
  275. // Extract data
  276. commonBlocks = append(commonBlocks, block.Block)
  277. for i, tkn := range block.Rollup.AddedTokens {
  278. token := historydb.TokenWithUSD{
  279. TokenID: tkn.TokenID,
  280. EthBlockNum: tkn.EthBlockNum,
  281. EthAddr: tkn.EthAddr,
  282. Name: tkn.Name,
  283. Symbol: tkn.Symbol,
  284. Decimals: tkn.Decimals,
  285. }
  286. value := float64(i + 423)
  287. now := time.Now().UTC()
  288. token.USD = &value
  289. token.USDUpdate = &now
  290. // Set value in DB
  291. err = api.h.UpdateTokenValue(token.Symbol, value)
  292. if err != nil {
  293. panic(err)
  294. }
  295. testTokens = append(testTokens, token)
  296. }
  297. // Set USD value for tokens in DB
  298. for _, batch := range block.Rollup.Batches {
  299. commonL2Txs = append(commonL2Txs, batch.L2Txs...)
  300. for i := range batch.CreatedAccounts {
  301. batch.CreatedAccounts[i].Nonce = common.Nonce(i)
  302. commonAccounts = append(commonAccounts, batch.CreatedAccounts[i])
  303. }
  304. commonBatches = append(commonBatches, batch.Batch)
  305. commonExitTree = append(commonExitTree, batch.ExitTree...)
  306. commonL1Txs = append(commonL1Txs, batch.L1UserTxs...)
  307. commonL1Txs = append(commonL1Txs, batch.L1CoordinatorTxs...)
  308. }
  309. }
  310. // lastBlockNum2 := blocksData[len(blocksData)-1].Block.EthBlockNum
  311. // Add accounts to StateDB
  312. for i := 0; i < len(commonAccounts); i++ {
  313. if _, err := api.s.CreateAccount(commonAccounts[i].Idx, &commonAccounts[i]); err != nil {
  314. panic(err)
  315. }
  316. }
  317. // Generate Coordinators and add them to HistoryDB
  318. const nCoords = 10
  319. commonCoords := test.GenCoordinators(nCoords, commonBlocks)
  320. // Update one coordinator to test behaviour when bidder address is repeated
  321. updatedCoordBlock := commonCoords[len(commonCoords)-1].EthBlockNum
  322. commonCoords = append(commonCoords, common.Coordinator{
  323. Bidder: commonCoords[0].Bidder,
  324. Forger: commonCoords[0].Forger,
  325. EthBlockNum: updatedCoordBlock,
  326. URL: commonCoords[0].URL + ".new",
  327. })
  328. if err := api.h.AddCoordinators(commonCoords); err != nil {
  329. panic(err)
  330. }
  331. // Test next forgers
  332. // Set auction vars
  333. // Slots 3 and 6 will have bids that will be invalidated because of minBid update
  334. // Slots 4 and 7 will have valid bids, the rest will be cordinator slots
  335. var slot3MinBid int64 = 3
  336. var slot4MinBid int64 = 4
  337. var slot6MinBid int64 = 6
  338. var slot7MinBid int64 = 7
  339. // First update will indicate how things behave from slot 0
  340. var defaultSlotSetBid [6]*big.Int = [6]*big.Int{
  341. big.NewInt(10), // Slot 0 min bid
  342. big.NewInt(10), // Slot 1 min bid
  343. big.NewInt(10), // Slot 2 min bid
  344. big.NewInt(slot3MinBid), // Slot 3 min bid
  345. big.NewInt(slot4MinBid), // Slot 4 min bid
  346. big.NewInt(10), // Slot 5 min bid
  347. }
  348. auctionVars := common.AuctionVariables{
  349. EthBlockNum: int64(2),
  350. DonationAddress: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  351. DefaultSlotSetBid: defaultSlotSetBid,
  352. DefaultSlotSetBidSlotNum: 0,
  353. Outbidding: uint16(1),
  354. SlotDeadline: uint8(20),
  355. BootCoordinator: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  356. BootCoordinatorURL: "https://boot.coordinator.io",
  357. ClosedAuctionSlots: uint16(10),
  358. OpenAuctionSlots: uint16(20),
  359. }
  360. if err := api.h.AddAuctionVars(&auctionVars); err != nil {
  361. panic(err)
  362. }
  363. // Last update in auction vars will indicate how things will behave from slot 5
  364. defaultSlotSetBid = [6]*big.Int{
  365. big.NewInt(10), // Slot 5 min bid
  366. big.NewInt(slot6MinBid), // Slot 6 min bid
  367. big.NewInt(slot7MinBid), // Slot 7 min bid
  368. big.NewInt(10), // Slot 8 min bid
  369. big.NewInt(10), // Slot 9 min bid
  370. big.NewInt(10), // Slot 10 min bid
  371. }
  372. auctionVars = common.AuctionVariables{
  373. EthBlockNum: int64(3),
  374. DonationAddress: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  375. DefaultSlotSetBid: defaultSlotSetBid,
  376. DefaultSlotSetBidSlotNum: 5,
  377. Outbidding: uint16(1),
  378. SlotDeadline: uint8(20),
  379. BootCoordinator: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  380. BootCoordinatorURL: "https://boot.coordinator.io",
  381. ClosedAuctionSlots: uint16(10),
  382. OpenAuctionSlots: uint16(20),
  383. }
  384. if err := api.h.AddAuctionVars(&auctionVars); err != nil {
  385. panic(err)
  386. }
  387. // Generate Bids and add them to HistoryDB
  388. bids := []common.Bid{}
  389. // Slot 1 and 2, no bids, wins boot coordinator
  390. // Slot 3, below what's going to be the minimum (wins boot coordinator)
  391. bids = append(bids, common.Bid{
  392. SlotNum: 3,
  393. BidValue: big.NewInt(slot3MinBid - 1),
  394. EthBlockNum: commonBlocks[0].Num,
  395. Bidder: commonCoords[0].Bidder,
  396. })
  397. // Slot 4, valid bid (wins bidder)
  398. bids = append(bids, common.Bid{
  399. SlotNum: 4,
  400. BidValue: big.NewInt(slot4MinBid),
  401. EthBlockNum: commonBlocks[0].Num,
  402. Bidder: commonCoords[0].Bidder,
  403. })
  404. // Slot 5 no bids, wins boot coordinator
  405. // Slot 6, below what's going to be the minimum (wins boot coordinator)
  406. bids = append(bids, common.Bid{
  407. SlotNum: 6,
  408. BidValue: big.NewInt(slot6MinBid - 1),
  409. EthBlockNum: commonBlocks[0].Num,
  410. Bidder: commonCoords[0].Bidder,
  411. })
  412. // Slot 7, valid bid (wins bidder)
  413. bids = append(bids, common.Bid{
  414. SlotNum: 7,
  415. BidValue: big.NewInt(slot7MinBid),
  416. EthBlockNum: commonBlocks[0].Num,
  417. Bidder: commonCoords[0].Bidder,
  418. })
  419. if err = api.h.AddBids(bids); err != nil {
  420. panic(err)
  421. }
  422. bootForger := NextForger{
  423. Coordinator: historydb.CoordinatorAPI{
  424. Bidder: ethCommon.HexToAddress("0x0111111111111111111111111111111111111111"),
  425. Forger: ethCommon.HexToAddress("0x0111111111111111111111111111111111111111"),
  426. URL: "https://bootCoordinator",
  427. },
  428. }
  429. // Set next forgers: set all as boot coordinator then replace the non boot coordinators
  430. nextForgers := []NextForger{}
  431. var initBlock int64 = 140
  432. var deltaBlocks int64 = 40
  433. for i := 1; i < int(auctionVars.ClosedAuctionSlots)+2; i++ {
  434. fromBlock := initBlock + deltaBlocks*int64(i-1)
  435. bootForger.Period = Period{
  436. SlotNum: int64(i),
  437. FromBlock: fromBlock,
  438. ToBlock: fromBlock + deltaBlocks - 1,
  439. }
  440. nextForgers = append(nextForgers, bootForger)
  441. }
  442. // Set next forgers that aren't the boot coordinator
  443. nonBootForger := historydb.CoordinatorAPI{
  444. Bidder: commonCoords[0].Bidder,
  445. Forger: commonCoords[0].Forger,
  446. URL: commonCoords[0].URL + ".new",
  447. }
  448. // Slot 4
  449. nextForgers[3].Coordinator = nonBootForger
  450. // Slot 7
  451. nextForgers[6].Coordinator = nonBootForger
  452. var buckets [common.RollupConstNumBuckets]common.BucketParams
  453. for i := range buckets {
  454. buckets[i].CeilUSD = big.NewInt(int64(i) * 10)
  455. buckets[i].Withdrawals = big.NewInt(int64(i) * 100)
  456. buckets[i].BlockWithdrawalRate = big.NewInt(int64(i) * 1000)
  457. buckets[i].MaxWithdrawals = big.NewInt(int64(i) * 10000)
  458. }
  459. // Generate SC vars and add them to HistoryDB (if needed)
  460. rollupVars := common.RollupVariables{
  461. EthBlockNum: int64(3),
  462. FeeAddToken: big.NewInt(100),
  463. ForgeL1L2BatchTimeout: int64(44),
  464. WithdrawalDelay: uint64(3000),
  465. Buckets: buckets,
  466. SafeMode: false,
  467. }
  468. wdelayerVars := common.WDelayerVariables{
  469. WithdrawalDelay: uint64(3000),
  470. }
  471. // Generate test data, as expected to be received/sended from/to the API
  472. testCoords := genTestCoordinators(commonCoords)
  473. testBids := genTestBids(commonBlocks, testCoords, bids)
  474. testExits := genTestExits(commonExitTree, testTokens, commonAccounts)
  475. testTxs := genTestTxs(commonL1Txs, commonL2Txs, commonAccounts, testTokens, commonBlocks)
  476. testBatches, testFullBatches := genTestBatches(commonBlocks, commonBatches, testTxs)
  477. poolTxsToSend, poolTxsToReceive := genTestPoolTxs(commonPoolTxs, testTokens, commonAccounts)
  478. tc = testCommon{
  479. blocks: commonBlocks,
  480. tokens: testTokens,
  481. batches: testBatches,
  482. fullBatches: testFullBatches,
  483. coordinators: testCoords,
  484. accounts: genTestAccounts(commonAccounts, testTokens),
  485. txs: testTxs,
  486. exits: testExits,
  487. poolTxsToSend: poolTxsToSend,
  488. poolTxsToReceive: poolTxsToReceive,
  489. auths: genTestAuths(test.GenAuths(5, _config.ChainID, _config.HermezAddress)),
  490. router: router,
  491. bids: testBids,
  492. slots: api.genTestSlots(
  493. 20,
  494. commonBlocks[len(commonBlocks)-1].Num,
  495. testBids,
  496. auctionVars,
  497. ),
  498. auctionVars: auctionVars,
  499. rollupVars: rollupVars,
  500. wdelayerVars: wdelayerVars,
  501. nextForgers: nextForgers,
  502. }
  503. // Run tests
  504. result := m.Run()
  505. // Fake server
  506. if os.Getenv("FAKE_SERVER") == "yes" {
  507. for {
  508. log.Info("Running fake server at " + apiURL + " until ^C is received")
  509. time.Sleep(30 * time.Second)
  510. }
  511. }
  512. // Stop server
  513. if err := server.Shutdown(context.Background()); err != nil {
  514. panic(err)
  515. }
  516. if err := database.Close(); err != nil {
  517. panic(err)
  518. }
  519. if err := os.RemoveAll(dir); err != nil {
  520. panic(err)
  521. }
  522. os.Exit(result)
  523. }
  524. func doGoodReqPaginated(
  525. path, order string,
  526. iterStruct Pendinger,
  527. appendIter func(res interface{}),
  528. ) error {
  529. var next uint64
  530. firstIte := true
  531. expectedTotal := 0
  532. totalReceived := 0
  533. for {
  534. // Calculate fromItem
  535. iterPath := path
  536. if !firstIte {
  537. iterPath += "&fromItem=" + strconv.Itoa(int(next))
  538. }
  539. // Call API to get this iteration items
  540. iterStruct = iterStruct.New()
  541. if err := doGoodReq(
  542. "GET", iterPath+"&order="+order, nil,
  543. iterStruct,
  544. ); err != nil {
  545. return tracerr.Wrap(err)
  546. }
  547. appendIter(iterStruct)
  548. // Keep iterating?
  549. remaining, lastID := iterStruct.GetPending()
  550. if remaining == 0 {
  551. break
  552. }
  553. if order == historydb.OrderDesc {
  554. next = lastID - 1
  555. } else {
  556. next = lastID + 1
  557. }
  558. // Check that the expected amount of items is consistent across iterations
  559. totalReceived += iterStruct.Len()
  560. if firstIte {
  561. firstIte = false
  562. expectedTotal = totalReceived + int(remaining)
  563. }
  564. if expectedTotal != totalReceived+int(remaining) {
  565. panic(fmt.Sprintf(
  566. "pagination error, totalReceived + remaining should be %d, but is %d",
  567. expectedTotal, totalReceived+int(remaining),
  568. ))
  569. }
  570. }
  571. return nil
  572. }
  573. func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{}) error {
  574. ctx := context.Background()
  575. client := &http.Client{}
  576. httpReq, err := http.NewRequest(method, path, reqBody)
  577. if err != nil {
  578. return tracerr.Wrap(err)
  579. }
  580. if reqBody != nil {
  581. httpReq.Header.Add("Content-Type", "application/json")
  582. }
  583. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  584. if err != nil {
  585. return tracerr.Wrap(err)
  586. }
  587. // Validate request against swagger spec
  588. requestValidationInput := &swagger.RequestValidationInput{
  589. Request: httpReq,
  590. PathParams: pathParams,
  591. Route: route,
  592. }
  593. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  594. return tracerr.Wrap(err)
  595. }
  596. // Do API call
  597. resp, err := client.Do(httpReq)
  598. if err != nil {
  599. return tracerr.Wrap(err)
  600. }
  601. if resp.Body == nil && returnStruct != nil {
  602. return tracerr.Wrap(errors.New("Nil body"))
  603. }
  604. //nolint
  605. defer resp.Body.Close()
  606. body, err := ioutil.ReadAll(resp.Body)
  607. if err != nil {
  608. return tracerr.Wrap(err)
  609. }
  610. if resp.StatusCode != 200 {
  611. return tracerr.Wrap(fmt.Errorf("%d response. Body: %s", resp.StatusCode, string(body)))
  612. }
  613. if returnStruct == nil {
  614. return nil
  615. }
  616. // Unmarshal body into return struct
  617. if err := json.Unmarshal(body, returnStruct); err != nil {
  618. log.Error("invalid json: " + string(body))
  619. log.Error(err)
  620. return tracerr.Wrap(err)
  621. }
  622. // log.Info(string(body))
  623. // Validate response against swagger spec
  624. responseValidationInput := &swagger.ResponseValidationInput{
  625. RequestValidationInput: requestValidationInput,
  626. Status: resp.StatusCode,
  627. Header: resp.Header,
  628. }
  629. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  630. return swagger.ValidateResponse(ctx, responseValidationInput)
  631. }
  632. func doBadReq(method, path string, reqBody io.Reader, expectedResponseCode int) error {
  633. ctx := context.Background()
  634. client := &http.Client{}
  635. httpReq, _ := http.NewRequest(method, path, reqBody)
  636. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  637. if err != nil {
  638. return tracerr.Wrap(err)
  639. }
  640. // Validate request against swagger spec
  641. requestValidationInput := &swagger.RequestValidationInput{
  642. Request: httpReq,
  643. PathParams: pathParams,
  644. Route: route,
  645. }
  646. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  647. if expectedResponseCode != 400 {
  648. return tracerr.Wrap(err)
  649. }
  650. log.Warn("The request does not match the API spec")
  651. }
  652. // Do API call
  653. resp, err := client.Do(httpReq)
  654. if err != nil {
  655. return tracerr.Wrap(err)
  656. }
  657. if resp.Body == nil {
  658. return tracerr.Wrap(errors.New("Nil body"))
  659. }
  660. //nolint
  661. defer resp.Body.Close()
  662. body, err := ioutil.ReadAll(resp.Body)
  663. if err != nil {
  664. return tracerr.Wrap(err)
  665. }
  666. if resp.StatusCode != expectedResponseCode {
  667. return tracerr.Wrap(fmt.Errorf("Unexpected response code: %d. Body: %s", resp.StatusCode, string(body)))
  668. }
  669. // Validate response against swagger spec
  670. responseValidationInput := &swagger.ResponseValidationInput{
  671. RequestValidationInput: requestValidationInput,
  672. Status: resp.StatusCode,
  673. Header: resp.Header,
  674. }
  675. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  676. return swagger.ValidateResponse(ctx, responseValidationInput)
  677. }
  678. // test helpers
  679. func getTimestamp(blockNum int64, blocks []common.Block) time.Time {
  680. for i := 0; i < len(blocks); i++ {
  681. if blocks[i].Num == blockNum {
  682. return blocks[i].Timestamp
  683. }
  684. }
  685. panic("timesamp not found")
  686. }
  687. func getTokenByID(id common.TokenID, tokens []historydb.TokenWithUSD) historydb.TokenWithUSD {
  688. for i := 0; i < len(tokens); i++ {
  689. if tokens[i].TokenID == id {
  690. return tokens[i]
  691. }
  692. }
  693. panic("token not found")
  694. }
  695. func getTokenByIdx(idx common.Idx, tokens []historydb.TokenWithUSD, accs []common.Account) historydb.TokenWithUSD {
  696. for _, acc := range accs {
  697. if idx == acc.Idx {
  698. return getTokenByID(acc.TokenID, tokens)
  699. }
  700. }
  701. panic("token not found")
  702. }
  703. func getAccountByIdx(idx common.Idx, accs []common.Account) *common.Account {
  704. for _, acc := range accs {
  705. if acc.Idx == idx {
  706. return &acc
  707. }
  708. }
  709. panic("account not found")
  710. }
  711. func getBlockByNum(ethBlockNum int64, blocks []common.Block) common.Block {
  712. for _, b := range blocks {
  713. if b.Num == ethBlockNum {
  714. return b
  715. }
  716. }
  717. panic("block not found")
  718. }
  719. func getCoordinatorByBidder(bidder ethCommon.Address, coordinators []historydb.CoordinatorAPI) historydb.CoordinatorAPI {
  720. var coordLastUpdate historydb.CoordinatorAPI
  721. found := false
  722. for _, c := range coordinators {
  723. if c.Bidder == bidder {
  724. coordLastUpdate = c
  725. found = true
  726. }
  727. }
  728. if !found {
  729. panic("coordinator not found")
  730. }
  731. return coordLastUpdate
  732. }