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.

313 lines
8.6 KiB

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