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.

302 lines
9.6 KiB

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