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.

279 lines
8.7 KiB

  1. package coordinator
  2. import (
  3. "fmt"
  4. ethCommon "github.com/ethereum/go-ethereum/common"
  5. "github.com/hermeznetwork/hermez-node/batchbuilder"
  6. "github.com/hermeznetwork/hermez-node/common"
  7. "github.com/hermeznetwork/hermez-node/db/historydb"
  8. "github.com/hermeznetwork/hermez-node/eth"
  9. "github.com/hermeznetwork/hermez-node/log"
  10. "github.com/hermeznetwork/hermez-node/txselector"
  11. kvdb "github.com/iden3/go-merkletree/db"
  12. "github.com/iden3/go-merkletree/db/memory"
  13. )
  14. // ErrStop is returned when the function is stopped asynchronously via the stop
  15. // channel. It doesn't indicate an error.
  16. var ErrStop = fmt.Errorf("Stopped")
  17. // Config contains the Coordinator configuration
  18. type Config struct {
  19. ForgerAddress ethCommon.Address
  20. }
  21. // Coordinator implements the Coordinator type
  22. type Coordinator struct {
  23. forging bool
  24. isForgeSeq bool // WIP just for testing while implementing
  25. config Config
  26. batchNum common.BatchNum
  27. serverProofPool ServerProofPool
  28. // synchronizer *synchronizer.Synchronizer
  29. hdb *historydb.HistoryDB
  30. txsel *txselector.TxSelector
  31. batchBuilder *batchbuilder.BatchBuilder
  32. ethClient eth.ClientInterface
  33. ethTxStore kvdb.Storage
  34. }
  35. // NewCoordinator creates a new Coordinator
  36. func NewCoordinator(conf Config,
  37. hdb *historydb.HistoryDB,
  38. txsel *txselector.TxSelector,
  39. bb *batchbuilder.BatchBuilder,
  40. ethClient *eth.Client) *Coordinator { // once synchronizer is ready, synchronizer.Synchronizer will be passed as parameter here
  41. c := Coordinator{
  42. config: conf,
  43. hdb: hdb,
  44. txsel: txsel,
  45. batchBuilder: bb,
  46. ethClient: ethClient,
  47. ethTxStore: memory.NewMemoryStorage(),
  48. }
  49. return &c
  50. }
  51. // ForgeLoopFn is the function ran in a loop that checks if it's time to forge
  52. // and forges a batch if so and sends it to outBatchCh. Returns true if it's
  53. // the coordinator turn to forge.
  54. func (c *Coordinator) ForgeLoopFn(outBatchCh chan *BatchInfo, stopCh chan bool) (bool, error) {
  55. if !c.isForgeSequence() {
  56. if c.forging {
  57. log.Info("stop forging")
  58. c.forging = false
  59. }
  60. log.Debug("not in forge time")
  61. return false, nil
  62. }
  63. log.Debug("forge time")
  64. if !c.forging {
  65. log.Info("start forging")
  66. // c.batchNum = c.hdb.GetLastBatchNum() // uncomment when HistoryDB is ready
  67. err := c.txsel.Reset(c.batchNum)
  68. if err != nil {
  69. log.Errorw("TxSelector.Reset", "error", err)
  70. return true, err
  71. }
  72. err = c.batchBuilder.Reset(c.batchNum, true)
  73. if err != nil {
  74. log.Errorw("BatchBuilder.Reset", "error", err)
  75. return true, err
  76. }
  77. // c.batchQueue = NewBatchQueue()
  78. c.forging = true
  79. }
  80. // TODO once synchronizer has this method ready:
  81. // If there's been a reorg, handle it
  82. // handleReorg() function decides if the reorg must restart the pipeline or not
  83. // if c.synchronizer.Reorg():
  84. _ = c.handleReorg()
  85. // 0. If there's an available server proof: Start pipeline for batchNum = batchNum + 1.
  86. // non-blocking call, returns nil if a server proof is
  87. // not available, or non-nil otherwise.
  88. serverProofInfo, err := c.serverProofPool.GetNextAvailable(stopCh)
  89. if err != nil {
  90. return true, err
  91. }
  92. log.Debugw("start forge")
  93. batchInfo, err := c.forge(serverProofInfo)
  94. if err != nil {
  95. log.Errorw("forge", "error", err)
  96. return true, err
  97. }
  98. log.Debugw("end forge", "batchNum", batchInfo.batchNum)
  99. outBatchCh <- batchInfo
  100. return true, nil
  101. }
  102. // GetProofCallForgeLoopFn is the function ran in a loop that gets a forged
  103. // batch via inBatchCh, waits for the proof server to finish, calls the ForgeBatch
  104. // function in the Rollup Smart Contract, and sends the batch to outBatchCh.
  105. func (c *Coordinator) GetProofCallForgeLoopFn(inBatchCh, outBatchCh chan *BatchInfo, stopCh chan bool) error {
  106. select {
  107. case <-stopCh:
  108. log.Info("forgeLoopFn stopped")
  109. return ErrStop
  110. case batchInfo := <-inBatchCh:
  111. log.Debugw("start getProofCallForge", "batchNum", batchInfo.batchNum)
  112. if err := c.getProofCallForge(batchInfo); err != nil {
  113. return err
  114. }
  115. log.Debugw("end getProofCallForge", "batchNum", batchInfo.batchNum)
  116. outBatchCh <- batchInfo
  117. }
  118. return nil
  119. }
  120. // ForgeCallConfirmLoopFn is the function ran in a loop that gets a batch that
  121. // has been sent to the Rollup Smart Contract via inBatchCh and waits for the
  122. // ethereum transaction confirmation.
  123. func (c *Coordinator) ForgeCallConfirmLoopFn(inBatchCh chan *BatchInfo, stopCh chan bool) error {
  124. select {
  125. case <-stopCh:
  126. log.Info("forgeConfirmLoopFn stopped")
  127. return ErrStop
  128. case batchInfo := <-inBatchCh:
  129. log.Debugw("start forgeCallConfirm", "batchNum", batchInfo.batchNum)
  130. if err := c.forgeCallConfirm(batchInfo); err != nil {
  131. return err
  132. }
  133. log.Debugw("end forgeCallConfirm", "batchNum", batchInfo.batchNum)
  134. }
  135. return nil
  136. }
  137. func (c *Coordinator) forge(serverProofInfo *ServerProofInfo) (*BatchInfo, error) {
  138. // remove transactions from the pool that have been there for too long
  139. err := c.purgeRemoveByTimeout()
  140. if err != nil {
  141. return nil, err
  142. }
  143. c.batchNum = c.batchNum + 1
  144. batchInfo := NewBatchInfo(c.batchNum, serverProofInfo) // to accumulate metadata of the batch
  145. var poolL2Txs []*common.PoolL2Tx
  146. // var feesInfo
  147. var l1UserTxsExtra, l1OperatorTxs []*common.L1Tx
  148. // 1. Decide if we forge L2Tx or L1+L2Tx
  149. if c.shouldL1L2Batch() {
  150. // 2a: L1+L2 txs
  151. // l1UserTxs, toForgeL1TxsNumber := c.hdb.GetNextL1UserTxs() // TODO once HistoryDB is ready, uncomment
  152. var l1UserTxs []*common.L1Tx = nil // tmp, depends on HistoryDB
  153. l1UserTxsExtra, l1OperatorTxs, poolL2Txs, err = c.txsel.GetL1L2TxSelection(c.batchNum, l1UserTxs) // TODO once feesInfo is added to method return, add the var
  154. if err != nil {
  155. return nil, err
  156. }
  157. } else {
  158. // 2b: only L2 txs
  159. poolL2Txs, err = c.txsel.GetL2TxSelection(c.batchNum) // TODO once feesInfo is added to method return, add the var
  160. if err != nil {
  161. return nil, err
  162. }
  163. l1UserTxsExtra = nil
  164. l1OperatorTxs = nil
  165. }
  166. // Run purger to invalidate transactions that become invalid beause of
  167. // the poolL2Txs selected. Will mark as invalid the txs that have a
  168. // (fromIdx, nonce) which already appears in the selected txs (includes
  169. // all the nonces smaller than the current one)
  170. err = c.purgeInvalidDueToL2TxsSelection(poolL2Txs)
  171. if err != nil {
  172. return nil, err
  173. }
  174. // 3. Save metadata from TxSelector output for BatchNum
  175. batchInfo.SetTxsInfo(l1UserTxsExtra, l1OperatorTxs, poolL2Txs) // TODO feesInfo
  176. // 4. Call BatchBuilder with TxSelector output
  177. configBatch := &batchbuilder.ConfigBatch{
  178. ForgerAddress: c.config.ForgerAddress,
  179. }
  180. zkInputs, err := c.batchBuilder.BuildBatch(configBatch, l1UserTxsExtra, l1OperatorTxs, poolL2Txs, nil) // TODO []common.TokenID --> feesInfo
  181. if err != nil {
  182. return nil, err
  183. }
  184. // 5. Save metadata from BatchBuilder output for BatchNum
  185. batchInfo.SetZKInputs(zkInputs)
  186. // 6. Call an idle server proof with BatchBuilder output, save server proof info for batchNum
  187. err = batchInfo.serverProof.CalculateProof(zkInputs)
  188. if err != nil {
  189. return nil, err
  190. }
  191. return &batchInfo, nil
  192. }
  193. // getProofCallForge gets the generated zkProof & sends it to the SmartContract
  194. func (c *Coordinator) getProofCallForge(batchInfo *BatchInfo) error {
  195. serverProofInfo := batchInfo.serverProof
  196. proof, err := serverProofInfo.GetProof() // blocking call, until not resolved don't continue. Returns when the proof server has calculated the proof
  197. if err != nil {
  198. return err
  199. }
  200. batchInfo.SetProof(proof)
  201. forgeBatchArgs := c.prepareForgeBatchArgs(batchInfo)
  202. _, err = c.ethClient.RollupForgeBatch(forgeBatchArgs)
  203. if err != nil {
  204. return err
  205. }
  206. log.Debugf("ethClient ForgeCall sent, batchNum: %d", c.batchNum)
  207. // TODO once tx data type is defined, store ethTx (returned by ForgeCall)
  208. // TBD if use ethTxStore as a disk k-v database, or use a Queue
  209. // tx, err := c.ethTxStore.NewTx()
  210. // if err != nil {
  211. // return err
  212. // }
  213. // tx.Put(ethTx.Hash(), ethTx.Bytes())
  214. // if err := tx.Commit(); err!=nil {
  215. // return nil
  216. // }
  217. return nil
  218. }
  219. func (c *Coordinator) forgeCallConfirm(batchInfo *BatchInfo) error {
  220. // TODO strategy of this sequence TBD
  221. // confirm eth txs and mark them as accepted sequence
  222. // ethTx := ethTxStore.GetFirstPending()
  223. // waitForAccepted(ethTx) // blocking call, returns once the ethTx is mined
  224. // ethTxStore.MarkAccepted(ethTx)
  225. return nil
  226. }
  227. func (c *Coordinator) handleReorg() error {
  228. return nil
  229. }
  230. // isForgeSequence returns true if the node is the Forger in the current ethereum block
  231. func (c *Coordinator) isForgeSequence() bool {
  232. return c.isForgeSeq
  233. }
  234. func (c *Coordinator) purgeRemoveByTimeout() error {
  235. return nil
  236. }
  237. func (c *Coordinator) purgeInvalidDueToL2TxsSelection(l2Txs []*common.PoolL2Tx) error {
  238. return nil
  239. }
  240. func (c *Coordinator) shouldL1L2Batch() bool {
  241. return false
  242. }
  243. func (c *Coordinator) prepareForgeBatchArgs(batchInfo *BatchInfo) *eth.RollupForgeBatchArgs {
  244. return nil
  245. }