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.

374 lines
14 KiB

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 txselector
  2. import (
  3. "crypto/ecdsa"
  4. "fmt"
  5. "io/ioutil"
  6. "math/big"
  7. "os"
  8. "strconv"
  9. "testing"
  10. "time"
  11. ethCommon "github.com/ethereum/go-ethereum/common"
  12. ethCrypto "github.com/ethereum/go-ethereum/crypto"
  13. "github.com/hermeznetwork/hermez-node/common"
  14. dbUtils "github.com/hermeznetwork/hermez-node/db"
  15. "github.com/hermeznetwork/hermez-node/db/historydb"
  16. "github.com/hermeznetwork/hermez-node/db/l2db"
  17. "github.com/hermeznetwork/hermez-node/db/statedb"
  18. "github.com/hermeznetwork/hermez-node/log"
  19. "github.com/hermeznetwork/hermez-node/test"
  20. "github.com/hermeznetwork/hermez-node/test/til"
  21. "github.com/hermeznetwork/hermez-node/test/txsets"
  22. "github.com/hermeznetwork/hermez-node/txprocessor"
  23. "github.com/iden3/go-iden3-crypto/babyjub"
  24. "github.com/jmoiron/sqlx"
  25. "github.com/stretchr/testify/assert"
  26. "github.com/stretchr/testify/require"
  27. )
  28. func initTest(t *testing.T, chainID uint16, hermezContractAddr ethCommon.Address, testSet string) (*TxSelector, *til.Context) {
  29. pass := os.Getenv("POSTGRES_PASS")
  30. db, err := dbUtils.InitSQLDB(5432, "localhost", "hermez", pass, "hermez")
  31. require.NoError(t, err)
  32. l2DB := l2db.NewL2DB(db, 10, 100, 24*time.Hour)
  33. dir, err := ioutil.TempDir("", "tmpdb")
  34. require.NoError(t, err)
  35. defer assert.NoError(t, os.RemoveAll(dir))
  36. sdb, err := statedb.NewStateDB(dir, 128, statedb.TypeTxSelector, 0)
  37. require.NoError(t, err)
  38. txselDir, err := ioutil.TempDir("", "tmpTxSelDB")
  39. require.NoError(t, err)
  40. defer assert.NoError(t, os.RemoveAll(dir))
  41. // coordinator keys
  42. var ethSk ecdsa.PrivateKey
  43. ethSk.D = big.NewInt(int64(1)) // only for testing
  44. ethSk.PublicKey.X, ethSk.PublicKey.Y = ethCrypto.S256().ScalarBaseMult(ethSk.D.Bytes())
  45. ethSk.Curve = ethCrypto.S256()
  46. addr := ethCrypto.PubkeyToAddress(ethSk.PublicKey)
  47. var bjj babyjub.PublicKeyComp
  48. err = bjj.UnmarshalText([]byte("c433f7a696b7aa3a5224efb3993baf0ccd9e92eecee0c29a3f6c8208a9e81d9e"))
  49. require.NoError(t, err)
  50. coordAccount := &CoordAccount{
  51. Addr: addr,
  52. BJJ: bjj,
  53. AccountCreationAuth: nil,
  54. }
  55. auth := common.AccountCreationAuth{
  56. EthAddr: addr,
  57. BJJ: bjj,
  58. }
  59. err = auth.Sign(func(hash []byte) ([]byte, error) {
  60. return ethCrypto.Sign(hash, &ethSk)
  61. }, chainID, hermezContractAddr)
  62. assert.NoError(t, err)
  63. coordAccount.AccountCreationAuth = auth.Signature
  64. txsel, err := NewTxSelector(coordAccount, txselDir, sdb, l2DB)
  65. require.NoError(t, err)
  66. test.WipeDB(txsel.l2db.DB())
  67. tc := til.NewContext(chainID, common.RollupConstMaxL1UserTx)
  68. return txsel, tc
  69. }
  70. func addAccCreationAuth(t *testing.T, tc *til.Context, txsel *TxSelector, chainID uint16, hermezContractAddr ethCommon.Address, username string) []byte {
  71. user := tc.Users[username]
  72. auth := &common.AccountCreationAuth{
  73. EthAddr: user.Addr,
  74. BJJ: user.BJJ.Public().Compress(),
  75. }
  76. err := auth.Sign(func(hash []byte) ([]byte, error) {
  77. return ethCrypto.Sign(hash, user.EthSk)
  78. }, chainID, hermezContractAddr)
  79. assert.NoError(t, err)
  80. err = txsel.l2db.AddAccountCreationAuth(auth)
  81. assert.NoError(t, err)
  82. return auth.Signature
  83. }
  84. func addL2Txs(t *testing.T, txsel *TxSelector, poolL2Txs []common.PoolL2Tx) {
  85. for i := 0; i < len(poolL2Txs); i++ {
  86. err := txsel.l2db.AddTxTest(&poolL2Txs[i])
  87. if err != nil {
  88. log.Error(err)
  89. }
  90. require.NoError(t, err)
  91. }
  92. }
  93. func addTokens(t *testing.T, tc *til.Context, db *sqlx.DB) {
  94. var tokens []common.Token
  95. for i := 0; i < int(tc.LastRegisteredTokenID); i++ {
  96. tokens = append(tokens, common.Token{
  97. TokenID: common.TokenID(i + 1),
  98. EthBlockNum: 1,
  99. EthAddr: ethCommon.BytesToAddress([]byte{byte(i + 1)}),
  100. Name: strconv.Itoa(i),
  101. Symbol: strconv.Itoa(i),
  102. Decimals: 18,
  103. })
  104. }
  105. hdb := historydb.NewHistoryDB(db)
  106. assert.NoError(t, hdb.AddBlock(&common.Block{
  107. Num: 1,
  108. }))
  109. assert.NoError(t, hdb.AddTokens(tokens))
  110. }
  111. func checkBalance(t *testing.T, tc *til.Context, txsel *TxSelector, username string, tokenid int, expected string) {
  112. // Accounts.Idx does not match with the TxSelector tests as we are not
  113. // using the Til L1CoordinatorTxs (as are generated by the TxSelector
  114. // itself when processing the txs, so the Idxs does not match the Til
  115. // idxs). But the Idx is obtained through StateDB.GetIdxByEthAddrBJJ
  116. user := tc.Users[username]
  117. idx, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(user.Addr, user.BJJ.Public().Compress(), common.TokenID(tokenid))
  118. require.NoError(t, err)
  119. checkBalanceByIdx(t, txsel, idx, expected)
  120. }
  121. func checkBalanceByIdx(t *testing.T, txsel *TxSelector, idx common.Idx, expected string) {
  122. acc, err := txsel.localAccountsDB.GetAccount(idx)
  123. require.NoError(t, err)
  124. assert.Equal(t, expected, acc.Balance.String())
  125. }
  126. // checkSortedByNonce takes as input testAccNonces map, and the array of
  127. // common.PoolL2Txs, and checks if the nonces correspond to the accumulated
  128. // values of the map. Also increases the Nonces computed on the map.
  129. func checkSortedByNonce(t *testing.T, testAccNonces map[common.Idx]common.Nonce, txs []common.PoolL2Tx) {
  130. for _, tx := range txs {
  131. assert.True(t, testAccNonces[tx.FromIdx] == tx.Nonce,
  132. fmt.Sprintf("Idx: %d, expected: %d, tx.Nonce: %d",
  133. tx.FromIdx, testAccNonces[tx.FromIdx], tx.Nonce))
  134. testAccNonces[tx.FromIdx] = testAccNonces[tx.FromIdx] + 1
  135. }
  136. }
  137. func TestGetL2TxSelectionMinimumFlow0(t *testing.T) {
  138. chainID := uint16(0)
  139. hermezContractAddr := ethCommon.HexToAddress("0xc344E203a046Da13b0B4467EB7B3629D0C99F6E6")
  140. txsel, tc := initTest(t, chainID, hermezContractAddr, txsets.SetPool0)
  141. // generate test transactions, the L1CoordinatorTxs generated by Til
  142. // will be ignored at this test, as will be the TxSelector who
  143. // generates them when needed
  144. blocks, err := tc.GenerateBlocks(txsets.SetBlockchainMinimumFlow0)
  145. assert.NoError(t, err)
  146. // restart nonces of TilContext, as will be set by generating directly
  147. // the PoolL2Txs for each specific batch with tc.GeneratePoolL2Txs
  148. tc.RestartNonces()
  149. testAccNonces := make(map[common.Idx]common.Nonce)
  150. // add tokens to HistoryDB to avoid breaking FK constrains
  151. addTokens(t, tc, txsel.l2db.DB())
  152. tpc := txprocessor.Config{
  153. NLevels: 16,
  154. MaxFeeTx: 10,
  155. MaxTx: 20,
  156. MaxL1Tx: 10,
  157. ChainID: chainID,
  158. }
  159. selectionConfig := &SelectionConfig{
  160. MaxL1UserTxs: 5,
  161. TxProcessorConfig: tpc,
  162. }
  163. // coordIdxs, accAuths, l1UserTxs, l1CoordTxs, l2Txs, err
  164. log.Debug("block:0 batch:1")
  165. l1UserTxs := []common.L1Tx{}
  166. _, _, oL1UserTxs, oL1CoordTxs, oL2Txs, err := txsel.GetL1L2TxSelection(selectionConfig, l1UserTxs)
  167. require.NoError(t, err)
  168. assert.Equal(t, 0, len(oL1UserTxs))
  169. assert.Equal(t, 0, len(oL1CoordTxs))
  170. assert.Equal(t, 0, len(oL2Txs))
  171. assert.Equal(t, common.BatchNum(1), txsel.localAccountsDB.CurrentBatch())
  172. assert.Equal(t, common.Idx(255), txsel.localAccountsDB.CurrentIdx())
  173. log.Debug("block:0 batch:2")
  174. l1UserTxs = []common.L1Tx{}
  175. _, _, oL1UserTxs, oL1CoordTxs, oL2Txs, err = txsel.GetL1L2TxSelection(selectionConfig, l1UserTxs)
  176. require.NoError(t, err)
  177. assert.Equal(t, 0, len(oL1UserTxs))
  178. assert.Equal(t, 0, len(oL1CoordTxs))
  179. assert.Equal(t, 0, len(oL2Txs))
  180. assert.Equal(t, common.BatchNum(2), txsel.localAccountsDB.CurrentBatch())
  181. assert.Equal(t, common.Idx(255), txsel.localAccountsDB.CurrentIdx())
  182. log.Debug("block:0 batch:3")
  183. l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[0].Rollup.Batches[2].Batch.ForgeL1TxsNum])
  184. _, _, oL1UserTxs, oL1CoordTxs, oL2Txs, err = txsel.GetL1L2TxSelection(selectionConfig, l1UserTxs)
  185. require.NoError(t, err)
  186. assert.Equal(t, 2, len(oL1UserTxs))
  187. assert.Equal(t, 0, len(oL1CoordTxs))
  188. assert.Equal(t, 0, len(oL2Txs))
  189. assert.Equal(t, common.BatchNum(3), txsel.localAccountsDB.CurrentBatch())
  190. assert.Equal(t, common.Idx(257), txsel.localAccountsDB.CurrentIdx())
  191. checkBalance(t, tc, txsel, "A", 0, "500")
  192. checkBalance(t, tc, txsel, "C", 1, "0")
  193. log.Debug("block:0 batch:4")
  194. l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[0].Rollup.Batches[3].Batch.ForgeL1TxsNum])
  195. _, _, oL1UserTxs, oL1CoordTxs, oL2Txs, err = txsel.GetL1L2TxSelection(selectionConfig, l1UserTxs)
  196. require.NoError(t, err)
  197. assert.Equal(t, 1, len(oL1UserTxs))
  198. assert.Equal(t, 0, len(oL1CoordTxs))
  199. assert.Equal(t, 0, len(oL2Txs))
  200. assert.Equal(t, common.BatchNum(4), txsel.localAccountsDB.CurrentBatch())
  201. assert.Equal(t, common.Idx(258), txsel.localAccountsDB.CurrentIdx())
  202. checkBalance(t, tc, txsel, "A", 0, "500")
  203. checkBalance(t, tc, txsel, "A", 1, "500")
  204. checkBalance(t, tc, txsel, "C", 1, "0")
  205. log.Debug("block:0 batch:5")
  206. l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[0].Rollup.Batches[4].Batch.ForgeL1TxsNum])
  207. _, _, oL1UserTxs, oL1CoordTxs, oL2Txs, err = txsel.GetL1L2TxSelection(selectionConfig, l1UserTxs)
  208. require.NoError(t, err)
  209. assert.Equal(t, 0, len(oL1UserTxs))
  210. assert.Equal(t, 0, len(oL1CoordTxs))
  211. assert.Equal(t, 0, len(oL2Txs))
  212. assert.Equal(t, common.BatchNum(5), txsel.localAccountsDB.CurrentBatch())
  213. assert.Equal(t, common.Idx(258), txsel.localAccountsDB.CurrentIdx())
  214. checkBalance(t, tc, txsel, "A", 0, "500")
  215. checkBalance(t, tc, txsel, "A", 1, "500")
  216. checkBalance(t, tc, txsel, "C", 1, "0")
  217. log.Debug("block:0 batch:6")
  218. l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[0].Rollup.Batches[5].Batch.ForgeL1TxsNum])
  219. _, _, oL1UserTxs, oL1CoordTxs, oL2Txs, err = txsel.GetL1L2TxSelection(selectionConfig, l1UserTxs)
  220. require.NoError(t, err)
  221. assert.Equal(t, 1, len(oL1UserTxs))
  222. assert.Equal(t, 0, len(oL1CoordTxs))
  223. assert.Equal(t, 0, len(oL2Txs))
  224. assert.Equal(t, common.BatchNum(6), txsel.localAccountsDB.CurrentBatch())
  225. assert.Equal(t, common.Idx(259), txsel.localAccountsDB.CurrentIdx())
  226. checkBalance(t, tc, txsel, "A", 0, "600")
  227. checkBalance(t, tc, txsel, "A", 1, "500")
  228. checkBalance(t, tc, txsel, "B", 0, "400")
  229. checkBalance(t, tc, txsel, "C", 1, "0")
  230. log.Debug("block:0 batch:7")
  231. // simulate the PoolL2Txs of the batch7
  232. batchPoolL2 := `
  233. Type: PoolL2
  234. PoolTransfer(1) A-B: 200 (126)
  235. PoolTransfer(0) B-C: 100 (126)`
  236. poolL2Txs, err := tc.GeneratePoolL2Txs(batchPoolL2)
  237. require.NoError(t, err)
  238. // add AccountCreationAuths that will be used at the next batch
  239. accAuthSig0 := addAccCreationAuth(t, tc, txsel, chainID, hermezContractAddr, "B")
  240. accAuthSig1 := addAccCreationAuth(t, tc, txsel, chainID, hermezContractAddr, "C")
  241. // add ToEthAddr for the corresponent ToIdx, and remove ToIdx for Batches[6].L2Tx
  242. poolL2Txs[0].ToEthAddr = tc.Users["B"].Addr
  243. poolL2Txs[0].ToIdx = common.Idx(0)
  244. poolL2Txs[1].ToEthAddr = tc.Users["C"].Addr
  245. poolL2Txs[1].ToIdx = common.Idx(0)
  246. // add the PoolL2Txs to the l2DB
  247. addL2Txs(t, txsel, poolL2Txs)
  248. l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[0].Rollup.Batches[6].Batch.ForgeL1TxsNum])
  249. coordIdxs, accAuths, oL1UserTxs, oL1CoordTxs, oL2Txs, err := txsel.GetL1L2TxSelection(selectionConfig, l1UserTxs)
  250. require.NoError(t, err)
  251. assert.Equal(t, []common.Idx{261, 262}, coordIdxs)
  252. assert.Equal(t, txsel.coordAccount.AccountCreationAuth, accAuths[0])
  253. assert.Equal(t, txsel.coordAccount.AccountCreationAuth, accAuths[1])
  254. assert.Equal(t, accAuthSig0, accAuths[2])
  255. assert.Equal(t, accAuthSig1, accAuths[3])
  256. assert.Equal(t, 1, len(oL1UserTxs))
  257. assert.Equal(t, 4, len(oL1CoordTxs))
  258. assert.Equal(t, 2, len(oL2Txs))
  259. assert.Equal(t, len(oL1CoordTxs), len(accAuths))
  260. assert.Equal(t, common.BatchNum(7), txsel.localAccountsDB.CurrentBatch())
  261. assert.Equal(t, common.Idx(264), txsel.localAccountsDB.CurrentIdx())
  262. checkBalanceByIdx(t, txsel, 261, "20") // CoordIdx for TokenID=1
  263. checkBalanceByIdx(t, txsel, 262, "10") // CoordIdx for TokenID=0
  264. checkBalance(t, tc, txsel, "A", 0, "600")
  265. checkBalance(t, tc, txsel, "A", 1, "280")
  266. checkBalance(t, tc, txsel, "B", 0, "290")
  267. checkBalance(t, tc, txsel, "B", 1, "200")
  268. checkBalance(t, tc, txsel, "C", 0, "100")
  269. checkBalance(t, tc, txsel, "D", 0, "800")
  270. checkSortedByNonce(t, testAccNonces, oL2Txs)
  271. err = txsel.l2db.StartForging(common.TxIDsFromPoolL2Txs(poolL2Txs), txsel.localAccountsDB.CurrentBatch())
  272. require.NoError(t, err)
  273. log.Debug("block:0 batch:8")
  274. // simulate the PoolL2Txs of the batch8
  275. batchPoolL2 = `
  276. Type: PoolL2
  277. PoolTransfer(0) A-B: 100 (126)
  278. PoolTransfer(0) C-A: 50 (126)
  279. PoolTransfer(1) B-C: 100 (126)
  280. PoolExit(0) A: 100 (126)`
  281. poolL2Txs, err = tc.GeneratePoolL2Txs(batchPoolL2)
  282. require.NoError(t, err)
  283. addL2Txs(t, txsel, poolL2Txs)
  284. l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[0].Rollup.Batches[7].Batch.ForgeL1TxsNum])
  285. coordIdxs, accAuths, oL1UserTxs, oL1CoordTxs, oL2Txs, err = txsel.GetL1L2TxSelection(selectionConfig, l1UserTxs)
  286. require.NoError(t, err)
  287. assert.Equal(t, []common.Idx{261, 262}, coordIdxs)
  288. assert.Equal(t, 0, len(accAuths))
  289. assert.Equal(t, 0, len(oL1UserTxs))
  290. assert.Equal(t, 0, len(oL1CoordTxs))
  291. assert.Equal(t, 4, len(oL2Txs))
  292. assert.Equal(t, len(oL1CoordTxs), len(accAuths))
  293. assert.Equal(t, common.BatchNum(8), txsel.localAccountsDB.CurrentBatch())
  294. assert.Equal(t, common.Idx(264), txsel.localAccountsDB.CurrentIdx())
  295. checkBalanceByIdx(t, txsel, 261, "30")
  296. checkBalanceByIdx(t, txsel, 262, "35")
  297. checkBalance(t, tc, txsel, "A", 0, "430")
  298. checkBalance(t, tc, txsel, "A", 1, "280")
  299. checkBalance(t, tc, txsel, "B", 0, "390")
  300. checkBalance(t, tc, txsel, "B", 1, "90")
  301. checkBalance(t, tc, txsel, "C", 0, "45")
  302. checkBalance(t, tc, txsel, "C", 1, "100")
  303. checkBalance(t, tc, txsel, "D", 0, "800")
  304. checkSortedByNonce(t, testAccNonces, oL2Txs)
  305. err = txsel.l2db.StartForging(common.TxIDsFromPoolL2Txs(poolL2Txs), txsel.localAccountsDB.CurrentBatch())
  306. require.NoError(t, err)
  307. log.Debug("(batch9)block:1 batch:1")
  308. // simulate the PoolL2Txs of the batch9
  309. batchPoolL2 = `
  310. Type: PoolL2
  311. PoolTransfer(0) D-A: 300 (126)
  312. PoolTransfer(0) B-D: 100 (126)
  313. `
  314. poolL2Txs, err = tc.GeneratePoolL2Txs(batchPoolL2)
  315. require.NoError(t, err)
  316. addL2Txs(t, txsel, poolL2Txs)
  317. l1UserTxs = til.L1TxsToCommonL1Txs(tc.Queues[*blocks[1].Rollup.Batches[0].Batch.ForgeL1TxsNum])
  318. coordIdxs, accAuths, oL1UserTxs, oL1CoordTxs, oL2Txs, err = txsel.GetL1L2TxSelection(selectionConfig, l1UserTxs)
  319. require.NoError(t, err)
  320. assert.Equal(t, []common.Idx{262}, coordIdxs)
  321. assert.Equal(t, 0, len(accAuths))
  322. assert.Equal(t, 4, len(oL1UserTxs))
  323. assert.Equal(t, 0, len(oL1CoordTxs))
  324. assert.Equal(t, 2, len(oL2Txs))
  325. assert.Equal(t, len(oL1CoordTxs), len(accAuths))
  326. assert.Equal(t, common.BatchNum(9), txsel.localAccountsDB.CurrentBatch())
  327. assert.Equal(t, common.Idx(264), txsel.localAccountsDB.CurrentIdx())
  328. checkBalanceByIdx(t, txsel, 261, "30")
  329. checkBalanceByIdx(t, txsel, 262, "75")
  330. checkBalance(t, tc, txsel, "A", 0, "730")
  331. checkBalance(t, tc, txsel, "A", 1, "280")
  332. checkBalance(t, tc, txsel, "B", 0, "380")
  333. checkBalance(t, tc, txsel, "B", 1, "90")
  334. checkBalance(t, tc, txsel, "C", 0, "845")
  335. checkBalance(t, tc, txsel, "C", 1, "100")
  336. checkBalance(t, tc, txsel, "D", 0, "470")
  337. checkSortedByNonce(t, testAccNonces, oL2Txs)
  338. err = txsel.l2db.StartForging(common.TxIDsFromPoolL2Txs(poolL2Txs), txsel.localAccountsDB.CurrentBatch())
  339. require.NoError(t, err)
  340. }