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.

771 lines
22 KiB

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