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.

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