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.

469 lines
13 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
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
Update missing parts, improve til, and more - Node - Updated configuration to initialize the interface to all the smart contracts - Common - Moved BlockData and BatchData types to common so that they can be shared among: historydb, til and synchronizer - Remove hash.go (it was never used) - Remove slot.go (it was never used) - Remove smartcontractparams.go (it was never used, and appropriate structs are defined in `eth/`) - Comment state / status method until requirements of this method are properly defined, and move it to Synchronizer - Synchronizer - Simplify `Sync` routine to only sync one block per call, and return useful information. - Use BlockData and BatchData from common - Check that events belong to the expected block hash - In L1Batch, query L1UserTxs from HistoryDB - Fill ERC20 token information - Test AddTokens with test.Client - HistryDB - Use BlockData and BatchData from common - Add `GetAllTokens` method - Uncomment and update GetL1UserTxs (with corresponding tests) - Til - Rename all instances of RegisterToken to AddToken (to follow the smart contract implementation naming) - Use BlockData and BatchData from common - Move testL1CoordinatorTxs and testL2Txs to a separate struct from BatchData in Context - Start Context with BatchNum = 1 (which the protocol defines to be the first batchNum) - In every Batch, set StateRoot and ExitRoot to a non-nil big.Int (zero). - In all L1Txs, if LoadAmount is not used, set it to 0; if Amount is not used, set it to 0; so that no *big.Int is nil. - In L1UserTx, don't set BatchNum, because when L1UserTxs are created and obtained by the synchronizer, the BatchNum is not known yet (it's a synchronizer job to set it) - In L1UserTxs, set `UserOrigin` and set `ToForgeL1TxsNum`.
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.
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
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 test
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/big"
  6. "time"
  7. ethCommon "github.com/ethereum/go-ethereum/common"
  8. "github.com/hermeznetwork/hermez-node/common"
  9. "github.com/hermeznetwork/tracerr"
  10. "github.com/iden3/go-iden3-crypto/babyjub"
  11. "github.com/iden3/go-merkletree"
  12. )
  13. // Block0 represents Ethereum's genesis block,
  14. // which is stored by default at HistoryDB
  15. var Block0 common.Block = common.Block{
  16. Num: 0,
  17. Hash: ethCommon.Hash([32]byte{
  18. 212, 229, 103, 64, 248, 118, 174, 248,
  19. 192, 16, 184, 106, 64, 213, 245, 103,
  20. 69, 161, 24, 208, 144, 106, 52, 230,
  21. 154, 236, 140, 13, 177, 203, 143, 163,
  22. }), // 0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3
  23. Timestamp: time.Date(2015, time.July, 30, 3, 26, 13, 0, time.UTC), // 2015-07-30 03:26:13
  24. }
  25. // EthToken represents the Ether coin, which is stored by default in the DB
  26. // with TokenID = 0
  27. var EthToken common.Token = common.Token{
  28. TokenID: 0,
  29. Name: "Ether",
  30. Symbol: "ETH",
  31. Decimals: 18, //nolint:gomnd
  32. EthBlockNum: 0,
  33. EthAddr: ethCommon.BigToAddress(big.NewInt(0)),
  34. }
  35. // WARNING: the generators in this file doesn't necessary follow the protocol
  36. // they are intended to check that the parsers between struct <==> DB are correct
  37. // GenBlocks generates block from, to block numbers. WARNING: This is meant for DB/API testing, and may not be fully consistent with the protocol.
  38. func GenBlocks(from, to int64) []common.Block {
  39. var blocks []common.Block
  40. for i := from; i < to; i++ {
  41. blocks = append(blocks, common.Block{
  42. Num: i,
  43. //nolint:gomnd
  44. Timestamp: time.Now().Add(time.Second * 13).UTC(),
  45. Hash: ethCommon.BigToHash(big.NewInt(int64(i))),
  46. })
  47. }
  48. return blocks
  49. }
  50. // GenTokens generates tokens. WARNING: This is meant for DB/API testing, and may not be fully consistent with the protocol.
  51. func GenTokens(nTokens int, blocks []common.Block) (tokensToAddInDB []common.Token, ethToken common.Token) {
  52. tokensToAddInDB = []common.Token{}
  53. for i := 1; i < nTokens; i++ {
  54. token := common.Token{
  55. TokenID: common.TokenID(i),
  56. Name: "NAME" + fmt.Sprint(i),
  57. Symbol: fmt.Sprint(i),
  58. Decimals: uint64(i + 1),
  59. EthBlockNum: blocks[i%len(blocks)].Num,
  60. EthAddr: ethCommon.BigToAddress(big.NewInt(int64(i))),
  61. }
  62. tokensToAddInDB = append(tokensToAddInDB, token)
  63. }
  64. return tokensToAddInDB, common.Token{
  65. TokenID: 0,
  66. Name: "Ether",
  67. Symbol: "ETH",
  68. Decimals: 18, //nolint:gomnd
  69. EthBlockNum: 0,
  70. EthAddr: ethCommon.BigToAddress(big.NewInt(0)),
  71. }
  72. }
  73. // GenBatches generates batches. WARNING: This is meant for DB/API testing, and may not be fully consistent with the protocol.
  74. func GenBatches(nBatches int, blocks []common.Block) []common.Batch {
  75. batches := []common.Batch{}
  76. collectedFees := make(map[common.TokenID]*big.Int)
  77. for i := 0; i < 64; i++ {
  78. collectedFees[common.TokenID(i)] = big.NewInt(int64(i))
  79. }
  80. for i := 0; i < nBatches; i++ {
  81. batch := common.Batch{
  82. BatchNum: common.BatchNum(i + 1),
  83. EthBlockNum: blocks[i%len(blocks)].Num,
  84. //nolint:gomnd
  85. ForgerAddr: ethCommon.BigToAddress(big.NewInt(6886723)),
  86. CollectedFees: collectedFees,
  87. StateRoot: big.NewInt(int64(i+1) * 5), //nolint:gomnd
  88. //nolint:gomnd
  89. NumAccounts: 30,
  90. ExitRoot: big.NewInt(int64(i+1) * 16), //nolint:gomnd
  91. SlotNum: int64(i),
  92. }
  93. if i%2 == 0 {
  94. toForge := new(int64)
  95. *toForge = int64(i + 1)
  96. batch.ForgeL1TxsNum = toForge
  97. }
  98. batches = append(batches, batch)
  99. }
  100. return batches
  101. }
  102. // GenAccounts generates accounts. WARNING: This is meant for DB/API testing, and may not be fully consistent with the protocol.
  103. func GenAccounts(totalAccounts, userAccounts int, tokens []common.Token, userAddr *ethCommon.Address, userBjj *babyjub.PublicKey, batches []common.Batch) []common.Account {
  104. if totalAccounts < userAccounts {
  105. panic("totalAccounts must be greater than userAccounts")
  106. }
  107. accs := []common.Account{}
  108. for i := 256; i < 256+totalAccounts; i++ {
  109. var addr ethCommon.Address
  110. var pubK *babyjub.PublicKey
  111. if i < 256+userAccounts {
  112. addr = *userAddr
  113. pubK = userBjj
  114. } else {
  115. addr = ethCommon.BigToAddress(big.NewInt(int64(i)))
  116. privK := babyjub.NewRandPrivKey()
  117. pubK = privK.Public()
  118. }
  119. accs = append(accs, common.Account{
  120. Idx: common.Idx(i),
  121. TokenID: tokens[i%len(tokens)].TokenID,
  122. EthAddr: addr,
  123. BatchNum: batches[i%len(batches)].BatchNum,
  124. BJJ: pubK.Compress(),
  125. Balance: big.NewInt(int64(i * 10000000)), //nolint:gomnd
  126. })
  127. }
  128. return accs
  129. }
  130. // GenL1Txs generates L1 txs. WARNING: This is meant for DB/API testing, and may not be fully consistent with the protocol.
  131. func GenL1Txs(
  132. fromIdx int,
  133. totalTxs, nUserTxs int,
  134. userAddr *ethCommon.Address,
  135. accounts []common.Account,
  136. tokens []common.Token,
  137. blocks []common.Block,
  138. batches []common.Batch,
  139. ) ([]common.L1Tx, []common.L1Tx) {
  140. if totalTxs < nUserTxs {
  141. panic("totalTxs must be greater than userTxs")
  142. }
  143. userTxs := []common.L1Tx{}
  144. othersTxs := []common.L1Tx{}
  145. _, nextTxsNum := GetNextToForgeNumAndBatch(batches)
  146. for i := fromIdx; i < fromIdx+totalTxs; i++ {
  147. token := tokens[i%len(tokens)]
  148. amount := big.NewInt(int64(i + 1))
  149. tx := common.L1Tx{
  150. Position: i - fromIdx,
  151. UserOrigin: i%2 == 0,
  152. TokenID: token.TokenID,
  153. Amount: amount,
  154. DepositAmount: amount,
  155. EthBlockNum: blocks[i%len(blocks)].Num,
  156. }
  157. if tx.UserOrigin {
  158. n := nextTxsNum
  159. tx.ToForgeL1TxsNum = &n
  160. } else {
  161. tx.BatchNum = &batches[i%len(batches)].BatchNum
  162. }
  163. nTx, err := common.NewL1Tx(&tx)
  164. if err != nil {
  165. panic(err)
  166. }
  167. tx = *nTx
  168. if !tx.UserOrigin {
  169. tx.BatchNum = &batches[i%len(batches)].BatchNum
  170. } else if batches[i%len(batches)].ForgeL1TxsNum != nil {
  171. // Add already forged txs
  172. tx.BatchNum = &batches[i%len(batches)].BatchNum
  173. setFromToAndAppend(fromIdx, tx, i, nUserTxs, userAddr, accounts, &userTxs, &othersTxs)
  174. } else {
  175. // Add unforged txs
  176. n := nextTxsNum
  177. tx.ToForgeL1TxsNum = &n
  178. tx.UserOrigin = true
  179. setFromToAndAppend(fromIdx, tx, i, nUserTxs, userAddr, accounts, &userTxs, &othersTxs)
  180. }
  181. }
  182. return userTxs, othersTxs
  183. }
  184. // GetNextToForgeNumAndBatch returns the next BatchNum and ForgeL1TxsNum to be added
  185. func GetNextToForgeNumAndBatch(batches []common.Batch) (common.BatchNum, int64) {
  186. batchNum := batches[len(batches)-1].BatchNum + 1
  187. var toForgeL1TxsNum int64
  188. found := false
  189. for i := len(batches) - 1; i >= 0; i-- {
  190. if batches[i].ForgeL1TxsNum != nil {
  191. toForgeL1TxsNum = *batches[i].ForgeL1TxsNum + 1
  192. found = true
  193. break
  194. }
  195. }
  196. if !found {
  197. panic("toForgeL1TxsNum not found")
  198. }
  199. return batchNum, toForgeL1TxsNum
  200. }
  201. func setFromToAndAppend(
  202. fromIdx int,
  203. tx common.L1Tx,
  204. i, nUserTxs int,
  205. userAddr *ethCommon.Address,
  206. accounts []common.Account,
  207. userTxs *[]common.L1Tx,
  208. othersTxs *[]common.L1Tx,
  209. ) {
  210. if i < fromIdx+nUserTxs {
  211. var from, to *common.Account
  212. var err error
  213. if i%2 == 0 {
  214. from, err = randomAccount(i, true, userAddr, accounts)
  215. if err != nil {
  216. panic(err)
  217. }
  218. to, err = randomAccount(i, false, userAddr, accounts)
  219. if err != nil {
  220. panic(err)
  221. }
  222. } else {
  223. from, err = randomAccount(i, false, userAddr, accounts)
  224. if err != nil {
  225. panic(err)
  226. }
  227. to, err = randomAccount(i, true, userAddr, accounts)
  228. if err != nil {
  229. panic(err)
  230. }
  231. }
  232. tx.FromIdx = from.Idx
  233. tx.FromEthAddr = from.EthAddr
  234. tx.FromBJJ = from.BJJ
  235. tx.ToIdx = to.Idx
  236. *userTxs = append(*userTxs, tx)
  237. } else {
  238. from, err := randomAccount(i, false, userAddr, accounts)
  239. if err != nil {
  240. panic(err)
  241. }
  242. to, err := randomAccount(i, false, userAddr, accounts)
  243. if err != nil {
  244. panic(err)
  245. }
  246. tx.FromIdx = from.Idx
  247. tx.FromEthAddr = from.EthAddr
  248. tx.FromBJJ = from.BJJ
  249. tx.ToIdx = to.Idx
  250. *othersTxs = append(*othersTxs, tx)
  251. }
  252. }
  253. // GenL2Txs generates L2 txs. WARNING: This is meant for DB/API testing, and may not be fully consistent with the protocol.
  254. func GenL2Txs(
  255. fromIdx int,
  256. totalTxs, nUserTxs int,
  257. userAddr *ethCommon.Address,
  258. accounts []common.Account,
  259. tokens []common.Token,
  260. blocks []common.Block,
  261. batches []common.Batch,
  262. ) ([]common.L2Tx, []common.L2Tx) {
  263. if totalTxs < nUserTxs {
  264. panic("totalTxs must be greater than userTxs")
  265. }
  266. userTxs := []common.L2Tx{}
  267. othersTxs := []common.L2Tx{}
  268. for i := fromIdx; i < fromIdx+totalTxs; i++ {
  269. amount := big.NewInt(int64(i + 1))
  270. fee := common.FeeSelector(i % 256) //nolint:gomnd
  271. tx := common.L2Tx{
  272. TxID: common.TxID([12]byte{2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, byte(i)}), // only for testing purposes
  273. BatchNum: batches[i%len(batches)].BatchNum,
  274. Position: i - fromIdx,
  275. Amount: amount,
  276. Fee: fee,
  277. Nonce: common.Nonce(i + 1),
  278. EthBlockNum: blocks[i%len(blocks)].Num,
  279. Type: randomTxType(i),
  280. }
  281. if i < nUserTxs {
  282. var from, to *common.Account
  283. var err error
  284. if i%2 == 0 {
  285. from, err = randomAccount(i, true, userAddr, accounts)
  286. if err != nil {
  287. panic(err)
  288. }
  289. to, err = randomAccount(i, false, userAddr, accounts)
  290. if err != nil {
  291. panic(err)
  292. }
  293. } else {
  294. from, err = randomAccount(i, false, userAddr, accounts)
  295. if err != nil {
  296. panic(err)
  297. }
  298. to, err = randomAccount(i, true, userAddr, accounts)
  299. if err != nil {
  300. panic(err)
  301. }
  302. }
  303. tx.FromIdx = from.Idx
  304. tx.ToIdx = to.Idx
  305. } else {
  306. from, err := randomAccount(i, false, userAddr, accounts)
  307. if err != nil {
  308. panic(err)
  309. }
  310. to, err := randomAccount(i, false, userAddr, accounts)
  311. if err != nil {
  312. panic(err)
  313. }
  314. tx.FromIdx = from.Idx
  315. tx.ToIdx = to.Idx
  316. }
  317. if i < nUserTxs {
  318. userTxs = append(userTxs, tx)
  319. } else {
  320. othersTxs = append(othersTxs, tx)
  321. }
  322. }
  323. return userTxs, othersTxs
  324. }
  325. // GenCoordinators generates coordinators. WARNING: This is meant for DB/API testing, and may not be fully consistent with the protocol.
  326. func GenCoordinators(nCoords int, blocks []common.Block) []common.Coordinator {
  327. coords := []common.Coordinator{}
  328. for i := 0; i < nCoords; i++ {
  329. coords = append(coords, common.Coordinator{
  330. EthBlockNum: blocks[i%len(blocks)].Num,
  331. Forger: ethCommon.BigToAddress(big.NewInt(int64(i))),
  332. Bidder: ethCommon.BigToAddress(big.NewInt(int64(i))),
  333. URL: fmt.Sprintf("https://%d.coord", i),
  334. })
  335. }
  336. return coords
  337. }
  338. // GenBids generates bids. WARNING: This is meant for DB/API testing, and may not be fully consistent with the protocol.
  339. func GenBids(nBids int, blocks []common.Block, coords []common.Coordinator) []common.Bid {
  340. bids := []common.Bid{}
  341. for i := 0; i < nBids*2; i = i + 2 { //nolint:gomnd
  342. var slotNum int64
  343. if i < nBids {
  344. slotNum = int64(i)
  345. } else {
  346. slotNum = int64(i - nBids)
  347. }
  348. bids = append(bids, common.Bid{
  349. SlotNum: slotNum,
  350. BidValue: big.NewInt(int64(i)),
  351. EthBlockNum: blocks[i%len(blocks)].Num,
  352. Bidder: coords[i%len(blocks)].Bidder,
  353. })
  354. }
  355. return bids
  356. }
  357. // GenExitTree generates an exitTree (as an array of Exits)
  358. //nolint:gomnd
  359. func GenExitTree(n int, batches []common.Batch, accounts []common.Account, blocks []common.Block) []common.ExitInfo {
  360. exitTree := make([]common.ExitInfo, n)
  361. for i := 0; i < n; i++ {
  362. exitTree[i] = common.ExitInfo{
  363. BatchNum: batches[i%len(batches)].BatchNum,
  364. InstantWithdrawn: nil,
  365. DelayedWithdrawRequest: nil,
  366. DelayedWithdrawn: nil,
  367. AccountIdx: accounts[i%len(accounts)].Idx,
  368. MerkleProof: &merkletree.CircomVerifierProof{
  369. Root: &merkletree.Hash{byte(i), byte(i + 1)},
  370. Siblings: []*merkletree.Hash{
  371. merkletree.NewHashFromBigInt(big.NewInt(int64(i) * 10)),
  372. merkletree.NewHashFromBigInt(big.NewInt(int64(i)*100 + 1)),
  373. merkletree.NewHashFromBigInt(big.NewInt(int64(i)*1000 + 2))},
  374. OldKey: &merkletree.Hash{byte(i * 1), byte(i*1 + 1)},
  375. OldValue: &merkletree.Hash{byte(i * 2), byte(i*2 + 1)},
  376. IsOld0: i%2 == 0,
  377. Key: &merkletree.Hash{byte(i * 3), byte(i*3 + 1)},
  378. Value: &merkletree.Hash{byte(i * 4), byte(i*4 + 1)},
  379. Fnc: i % 2,
  380. },
  381. Balance: big.NewInt(int64(i) * 1000),
  382. }
  383. if i%2 == 0 {
  384. instant := int64(blocks[i%len(blocks)].Num)
  385. exitTree[i].InstantWithdrawn = &instant
  386. } else if i%3 == 0 {
  387. delayedReq := int64(blocks[i%len(blocks)].Num)
  388. exitTree[i].DelayedWithdrawRequest = &delayedReq
  389. if i%9 == 0 {
  390. delayed := int64(blocks[i%len(blocks)].Num)
  391. exitTree[i].DelayedWithdrawn = &delayed
  392. }
  393. }
  394. }
  395. return exitTree
  396. }
  397. func randomAccount(seed int, userAccount bool, userAddr *ethCommon.Address, accs []common.Account) (*common.Account, error) {
  398. i := seed % len(accs)
  399. firstI := i
  400. for {
  401. acc := accs[i]
  402. if userAccount && *userAddr == acc.EthAddr {
  403. return &acc, nil
  404. }
  405. if !userAccount && (userAddr == nil || *userAddr != acc.EthAddr) {
  406. return &acc, nil
  407. }
  408. i++
  409. i = i % len(accs)
  410. if i == firstI {
  411. return &acc, tracerr.Wrap(errors.New("Didnt found any account matchinng the criteria"))
  412. }
  413. }
  414. }
  415. func randomTxType(seed int) common.TxType {
  416. //nolint:gomnd
  417. switch seed % 11 {
  418. case 0:
  419. return common.TxTypeExit
  420. //nolint:gomnd
  421. case 2:
  422. return common.TxTypeTransfer
  423. //nolint:gomnd
  424. case 3:
  425. return common.TxTypeDeposit
  426. //nolint:gomnd
  427. case 4:
  428. return common.TxTypeCreateAccountDeposit
  429. //nolint:gomnd
  430. case 5:
  431. return common.TxTypeCreateAccountDepositTransfer
  432. //nolint:gomnd
  433. case 6:
  434. return common.TxTypeDepositTransfer
  435. //nolint:gomnd
  436. case 7:
  437. return common.TxTypeForceTransfer
  438. //nolint:gomnd
  439. case 8:
  440. return common.TxTypeForceExit
  441. //nolint:gomnd
  442. case 9:
  443. return common.TxTypeTransferToEthAddr
  444. //nolint:gomnd
  445. case 10:
  446. return common.TxTypeTransferToBJJ
  447. default:
  448. return common.TxTypeTransfer
  449. }
  450. }