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.

790 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. 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. Forger: auctionVars.BootCoordinator,
  425. URL: auctionVars.BootCoordinatorURL,
  426. },
  427. }
  428. // Set next forgers: set all as boot coordinator then replace the non boot coordinators
  429. nextForgers := []NextForger{}
  430. var initBlock int64 = 140
  431. var deltaBlocks int64 = 40
  432. for i := 1; i < int(auctionVars.ClosedAuctionSlots)+2; i++ {
  433. fromBlock := initBlock + deltaBlocks*int64(i-1)
  434. bootForger.Period = Period{
  435. SlotNum: int64(i),
  436. FromBlock: fromBlock,
  437. ToBlock: fromBlock + deltaBlocks - 1,
  438. }
  439. nextForgers = append(nextForgers, bootForger)
  440. }
  441. // Set next forgers that aren't the boot coordinator
  442. nonBootForger := historydb.CoordinatorAPI{
  443. Bidder: commonCoords[0].Bidder,
  444. Forger: commonCoords[0].Forger,
  445. URL: commonCoords[0].URL + ".new",
  446. }
  447. // Slot 4
  448. nextForgers[3].Coordinator = nonBootForger
  449. // Slot 7
  450. nextForgers[6].Coordinator = nonBootForger
  451. var buckets [common.RollupConstNumBuckets]common.BucketParams
  452. for i := range buckets {
  453. buckets[i].CeilUSD = big.NewInt(int64(i) * 10)
  454. buckets[i].Withdrawals = big.NewInt(int64(i) * 100)
  455. buckets[i].BlockWithdrawalRate = big.NewInt(int64(i) * 1000)
  456. buckets[i].MaxWithdrawals = big.NewInt(int64(i) * 10000)
  457. }
  458. // Generate SC vars and add them to HistoryDB (if needed)
  459. rollupVars := common.RollupVariables{
  460. EthBlockNum: int64(3),
  461. FeeAddToken: big.NewInt(100),
  462. ForgeL1L2BatchTimeout: int64(44),
  463. WithdrawalDelay: uint64(3000),
  464. Buckets: buckets,
  465. SafeMode: false,
  466. }
  467. wdelayerVars := common.WDelayerVariables{
  468. WithdrawalDelay: uint64(3000),
  469. }
  470. // Generate test data, as expected to be received/sended from/to the API
  471. testCoords := genTestCoordinators(commonCoords)
  472. testBids := genTestBids(commonBlocks, testCoords, bids)
  473. testExits := genTestExits(commonExitTree, testTokens, commonAccounts)
  474. testTxs := genTestTxs(commonL1Txs, commonL2Txs, commonAccounts, testTokens, commonBlocks)
  475. testBatches, testFullBatches := genTestBatches(commonBlocks, commonBatches, testTxs)
  476. poolTxsToSend, poolTxsToReceive := genTestPoolTxs(commonPoolTxs, testTokens, commonAccounts)
  477. tc = testCommon{
  478. blocks: commonBlocks,
  479. tokens: testTokens,
  480. batches: testBatches,
  481. fullBatches: testFullBatches,
  482. coordinators: testCoords,
  483. accounts: genTestAccounts(commonAccounts, testTokens),
  484. txs: testTxs,
  485. exits: testExits,
  486. poolTxsToSend: poolTxsToSend,
  487. poolTxsToReceive: poolTxsToReceive,
  488. auths: genTestAuths(test.GenAuths(5, _config.ChainID, _config.HermezAddress)),
  489. router: router,
  490. bids: testBids,
  491. slots: api.genTestSlots(
  492. 20,
  493. commonBlocks[len(commonBlocks)-1].Num,
  494. testBids,
  495. auctionVars,
  496. ),
  497. auctionVars: auctionVars,
  498. rollupVars: rollupVars,
  499. wdelayerVars: wdelayerVars,
  500. nextForgers: nextForgers,
  501. }
  502. // Run tests
  503. result := m.Run()
  504. // Fake server
  505. if os.Getenv("FAKE_SERVER") == "yes" {
  506. for {
  507. log.Info("Running fake server at " + apiURL + " until ^C is received")
  508. time.Sleep(30 * time.Second)
  509. }
  510. }
  511. // Stop server
  512. if err := server.Shutdown(context.Background()); err != nil {
  513. panic(err)
  514. }
  515. if err := database.Close(); err != nil {
  516. panic(err)
  517. }
  518. if err := os.RemoveAll(dir); err != nil {
  519. panic(err)
  520. }
  521. os.Exit(result)
  522. }
  523. func doGoodReqPaginated(
  524. path, order string,
  525. iterStruct Pendinger,
  526. appendIter func(res interface{}),
  527. ) error {
  528. var next uint64
  529. firstIte := true
  530. expectedTotal := 0
  531. totalReceived := 0
  532. for {
  533. // Calculate fromItem
  534. iterPath := path
  535. if !firstIte {
  536. iterPath += "&fromItem=" + strconv.Itoa(int(next))
  537. }
  538. // Call API to get this iteration items
  539. iterStruct = iterStruct.New()
  540. if err := doGoodReq(
  541. "GET", iterPath+"&order="+order, nil,
  542. iterStruct,
  543. ); err != nil {
  544. return tracerr.Wrap(err)
  545. }
  546. appendIter(iterStruct)
  547. // Keep iterating?
  548. remaining, lastID := iterStruct.GetPending()
  549. if remaining == 0 {
  550. break
  551. }
  552. if order == historydb.OrderDesc {
  553. next = lastID - 1
  554. } else {
  555. next = lastID + 1
  556. }
  557. // Check that the expected amount of items is consistent across iterations
  558. totalReceived += iterStruct.Len()
  559. if firstIte {
  560. firstIte = false
  561. expectedTotal = totalReceived + int(remaining)
  562. }
  563. if expectedTotal != totalReceived+int(remaining) {
  564. panic(fmt.Sprintf(
  565. "pagination error, totalReceived + remaining should be %d, but is %d",
  566. expectedTotal, totalReceived+int(remaining),
  567. ))
  568. }
  569. }
  570. return nil
  571. }
  572. func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{}) error {
  573. ctx := context.Background()
  574. client := &http.Client{}
  575. httpReq, err := http.NewRequest(method, path, reqBody)
  576. if err != nil {
  577. return tracerr.Wrap(err)
  578. }
  579. if reqBody != nil {
  580. httpReq.Header.Add("Content-Type", "application/json")
  581. }
  582. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  583. if err != nil {
  584. return tracerr.Wrap(err)
  585. }
  586. // Validate request against swagger spec
  587. requestValidationInput := &swagger.RequestValidationInput{
  588. Request: httpReq,
  589. PathParams: pathParams,
  590. Route: route,
  591. }
  592. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  593. return tracerr.Wrap(err)
  594. }
  595. // Do API call
  596. resp, err := client.Do(httpReq)
  597. if err != nil {
  598. return tracerr.Wrap(err)
  599. }
  600. if resp.Body == nil && returnStruct != nil {
  601. return tracerr.Wrap(errors.New("Nil body"))
  602. }
  603. //nolint
  604. defer resp.Body.Close()
  605. body, err := ioutil.ReadAll(resp.Body)
  606. if err != nil {
  607. return tracerr.Wrap(err)
  608. }
  609. if resp.StatusCode != 200 {
  610. return tracerr.Wrap(fmt.Errorf("%d response. Body: %s", resp.StatusCode, string(body)))
  611. }
  612. if returnStruct == nil {
  613. return nil
  614. }
  615. // Unmarshal body into return struct
  616. if err := json.Unmarshal(body, returnStruct); err != nil {
  617. log.Error("invalid json: " + string(body))
  618. log.Error(err)
  619. return tracerr.Wrap(err)
  620. }
  621. // log.Info(string(body))
  622. // Validate response against swagger spec
  623. responseValidationInput := &swagger.ResponseValidationInput{
  624. RequestValidationInput: requestValidationInput,
  625. Status: resp.StatusCode,
  626. Header: resp.Header,
  627. }
  628. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  629. return swagger.ValidateResponse(ctx, responseValidationInput)
  630. }
  631. func doBadReq(method, path string, reqBody io.Reader, expectedResponseCode int) error {
  632. ctx := context.Background()
  633. client := &http.Client{}
  634. httpReq, _ := http.NewRequest(method, path, reqBody)
  635. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  636. if err != nil {
  637. return tracerr.Wrap(err)
  638. }
  639. // Validate request against swagger spec
  640. requestValidationInput := &swagger.RequestValidationInput{
  641. Request: httpReq,
  642. PathParams: pathParams,
  643. Route: route,
  644. }
  645. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  646. if expectedResponseCode != 400 {
  647. return tracerr.Wrap(err)
  648. }
  649. log.Warn("The request does not match the API spec")
  650. }
  651. // Do API call
  652. resp, err := client.Do(httpReq)
  653. if err != nil {
  654. return tracerr.Wrap(err)
  655. }
  656. if resp.Body == nil {
  657. return tracerr.Wrap(errors.New("Nil body"))
  658. }
  659. //nolint
  660. defer resp.Body.Close()
  661. body, err := ioutil.ReadAll(resp.Body)
  662. if err != nil {
  663. return tracerr.Wrap(err)
  664. }
  665. if resp.StatusCode != expectedResponseCode {
  666. return tracerr.Wrap(fmt.Errorf("Unexpected response code: %d. Body: %s", resp.StatusCode, string(body)))
  667. }
  668. // Validate response against swagger spec
  669. responseValidationInput := &swagger.ResponseValidationInput{
  670. RequestValidationInput: requestValidationInput,
  671. Status: resp.StatusCode,
  672. Header: resp.Header,
  673. }
  674. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  675. return swagger.ValidateResponse(ctx, responseValidationInput)
  676. }
  677. // test helpers
  678. func getTimestamp(blockNum int64, blocks []common.Block) time.Time {
  679. for i := 0; i < len(blocks); i++ {
  680. if blocks[i].Num == blockNum {
  681. return blocks[i].Timestamp
  682. }
  683. }
  684. panic("timesamp not found")
  685. }
  686. func getTokenByID(id common.TokenID, tokens []historydb.TokenWithUSD) historydb.TokenWithUSD {
  687. for i := 0; i < len(tokens); i++ {
  688. if tokens[i].TokenID == id {
  689. return tokens[i]
  690. }
  691. }
  692. panic("token not found")
  693. }
  694. func getTokenByIdx(idx common.Idx, tokens []historydb.TokenWithUSD, accs []common.Account) historydb.TokenWithUSD {
  695. for _, acc := range accs {
  696. if idx == acc.Idx {
  697. return getTokenByID(acc.TokenID, tokens)
  698. }
  699. }
  700. panic("token not found")
  701. }
  702. func getAccountByIdx(idx common.Idx, accs []common.Account) *common.Account {
  703. for _, acc := range accs {
  704. if acc.Idx == idx {
  705. return &acc
  706. }
  707. }
  708. panic("account not found")
  709. }
  710. func getBlockByNum(ethBlockNum int64, blocks []common.Block) common.Block {
  711. for _, b := range blocks {
  712. if b.Num == ethBlockNum {
  713. return b
  714. }
  715. }
  716. panic("block not found")
  717. }
  718. func getCoordinatorByBidder(bidder ethCommon.Address, coordinators []historydb.CoordinatorAPI) historydb.CoordinatorAPI {
  719. var coordLastUpdate historydb.CoordinatorAPI
  720. found := false
  721. for _, c := range coordinators {
  722. if c.Bidder == bidder {
  723. coordLastUpdate = c
  724. found = true
  725. }
  726. }
  727. if !found {
  728. panic("coordinator not found")
  729. }
  730. return coordLastUpdate
  731. }