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.

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