Skip to content

Commit 2a0c7ae

Browse files
colinlyguogeorgehao0xmountaintop
authored
refactor(coordinator & prover): RESTful API (scroll-tech#696)
Co-authored-by: georgehao <[email protected]> Co-authored-by: HAOYUatHZ <[email protected]>
1 parent b0b6a3d commit 2a0c7ae

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

69 files changed

+2709
-15612
lines changed

common/cmd/cmd.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ func (c *Cmd) Write(data []byte) (int, error) {
8383
out := string(data)
8484
if verbose || c.openLog {
8585
fmt.Printf("%s:\n\t%v", c.name, out)
86-
} else if strings.Contains(out, "error") || strings.Contains(out, "warning") {
86+
} else if strings.Contains(strings.ToLower(out), "error") || strings.Contains(strings.ToLower(out), "warning") || strings.Contains(strings.ToLower(out), "info") {
8787
fmt.Printf("%s:\n\t%v", c.name, out)
8888
}
8989
go c.checkFuncs.IterCb(func(_ string, value interface{}) {

common/types/errno.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package types
2+
3+
const (
4+
// Success shows OK.
5+
Success = 0
6+
7+
// ErrJWTCommonErr jwt common error
8+
ErrJWTCommonErr = 50000
9+
// ErrJWTTokenExpired jwt token expired
10+
ErrJWTTokenExpired = 50001
11+
12+
// ErrCoordinatorParameterInvalidNo is invalid params
13+
ErrCoordinatorParameterInvalidNo = 20001
14+
// ErrCoordinatorGetTaskFailure is getting prover task error
15+
ErrCoordinatorGetTaskFailure = 20002
16+
// ErrCoordinatorHandleZkProofFailure is handle submit proof error
17+
ErrCoordinatorHandleZkProofFailure = 20003
18+
// ErrCoordinatorEmptyProofData get empty proof data
19+
ErrCoordinatorEmptyProofData = 20004
20+
)

common/types/message/message.go

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -58,15 +58,12 @@ type AuthMsg struct {
5858

5959
// Identity contains all the fields to be signed by the prover.
6060
type Identity struct {
61-
// Prover name
62-
Name string `json:"name"`
63-
// Prover ProverType
64-
ProverType ProofType `json:"prover_type,omitempty"`
65-
// Version is common.Version+ZkVersion. Use the following to check the latest ZkVersion version.
66-
// curl -sL https://api.github.com/repos/scroll-tech/scroll-prover/commits | jq -r ".[0].sha"
67-
Version string `json:"version"`
68-
// Random unique token generated by manager
69-
Token string `json:"token"`
61+
// ProverName the prover name
62+
ProverName string `json:"prover_name"`
63+
// ProverVersion the prover version
64+
ProverVersion string `json:"prover_version"`
65+
// Challenge unique challenge generated by manager
66+
Challenge string `json:"challenge"`
7067
}
7168

7269
// GenerateToken generates token

common/types/message/message_test.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ func TestAuthMessageSignAndVerify(t *testing.T) {
1515

1616
authMsg := &AuthMsg{
1717
Identity: &Identity{
18-
Name: "testName",
19-
Version: "testVersion",
20-
Token: "testToken",
18+
Challenge: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2OTEwMzgxNzUsIm9yaWdfaWF0IjoxNjkxMDM0NTc1fQ.HybBMsEJFhyZqtIa2iVcHUP7CEFttf708jmTMAImAWA",
19+
ProverName: "test",
20+
ProverVersion: "v1.0.0",
2121
},
2222
}
2323
assert.NoError(t, authMsg.SignWithKey(privkey))
@@ -46,15 +46,15 @@ func TestGenerateToken(t *testing.T) {
4646

4747
func TestIdentityHash(t *testing.T) {
4848
identity := &Identity{
49-
Name: "testName",
50-
ProverType: ProofTypeChunk,
51-
Version: "testVersion",
52-
Token: "testToken",
49+
Challenge: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2OTEwMzM0MTksIm9yaWdfaWF0IjoxNjkxMDI5ODE5fQ.EhkLZsj__rNPVC3ZDYBtvdh0nB8mmM_Hl82hObaIWOs",
50+
ProverName: "test",
51+
ProverVersion: "v1.0.0",
5352
}
53+
5454
hash, err := identity.Hash()
5555
assert.NoError(t, err)
5656

57-
expectedHash := "c0411a19531fb8c6133b2bae91f361c14e65f2d318aef72b83519e6061cad001"
57+
expectedHash := "83f5e0ad023e9c1de639ab07b9b4cb972ec9dbbd2524794c533a420a5b137721"
5858
assert.Equal(t, expectedHash, hex.EncodeToString(hash))
5959
}
6060

common/version/version.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import (
55
"runtime/debug"
66
)
77

8-
var tag = "v4.0.43"
8+
var tag = "v4.1.0"
99

1010
var commit = func() string {
1111
if info, ok := debug.ReadBuildInfo(); ok {

coordinator/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ make lint
3737

3838
## Configure
3939

40-
The coordinator behavior can be configured using [`config.json`](config.json). Check the code comments under `ProverManagerConfig` in [`config/config.go`](config/config.go) for more details.
40+
The coordinator behavior can be configured using [`config.json`](config.json). Check the code comments under `ProverManager` in [`config/config.go`](config/config.go) for more details.
4141

4242

4343
## Start

coordinator/client/client.go

Lines changed: 0 additions & 51 deletions
This file was deleted.

coordinator/cmd/app/app.go

Lines changed: 30 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,17 @@ package app
22

33
import (
44
"context"
5+
"errors"
56
"fmt"
7+
"net/http"
68
"os"
79
"os/signal"
10+
"time"
811

912
// enable the pprof
1013
_ "net/http/pprof"
1114

15+
"github.com/gin-gonic/gin"
1216
"github.com/scroll-tech/go-ethereum/log"
1317
"github.com/urfave/cli/v2"
1418

@@ -20,7 +24,7 @@ import (
2024
"scroll-tech/coordinator/internal/config"
2125
"scroll-tech/coordinator/internal/controller/api"
2226
"scroll-tech/coordinator/internal/controller/cron"
23-
"scroll-tech/coordinator/internal/logic/provermanager"
27+
"scroll-tech/coordinator/internal/route"
2428
)
2529

2630
var app *cli.App
@@ -49,15 +53,12 @@ func action(ctx *cli.Context) error {
4953
}
5054

5155
subCtx, cancel := context.WithCancel(ctx.Context)
52-
db, err := database.InitDB(cfg.DBConfig)
56+
db, err := database.InitDB(cfg.DB)
5357
if err != nil {
5458
log.Crit("failed to init db connection", "err", err)
5559
}
5660

5761
proofCollector := cron.NewCollector(subCtx, db, cfg)
58-
59-
provermanager.InitProverManager(db)
60-
6162
defer func() {
6263
proofCollector.Stop()
6364
cancel()
@@ -66,42 +67,42 @@ func action(ctx *cli.Context) error {
6667
}
6768
}()
6869

70+
router := gin.Default()
71+
api.InitController(cfg, db)
72+
route.Route(router, cfg)
73+
port := ctx.String(httpPortFlag.Name)
74+
srv := &http.Server{
75+
Addr: fmt.Sprintf(":%s", port),
76+
Handler: router,
77+
ReadHeaderTimeout: time.Minute,
78+
}
79+
6980
// Start metrics server.
7081
metrics.Serve(subCtx, ctx)
7182

72-
apis := api.RegisterAPIs(cfg, db)
73-
// Register api and start rpc service.
74-
if ctx.Bool(httpEnabledFlag.Name) {
75-
handler, addr, err := utils.StartHTTPEndpoint(fmt.Sprintf("%s:%d", ctx.String(httpListenAddrFlag.Name), ctx.Int(httpPortFlag.Name)), apis)
76-
if err != nil {
77-
log.Crit("Could not start RPC api", "error", err)
78-
}
79-
defer func() {
80-
_ = handler.Shutdown(ctx.Context)
81-
log.Info("HTTP endpoint closed", "url", fmt.Sprintf("http://%v/", addr))
82-
}()
83-
log.Info("HTTP endpoint opened", "url", fmt.Sprintf("http://%v/", addr))
84-
}
85-
// Register api and start ws service.
86-
if ctx.Bool(wsEnabledFlag.Name) {
87-
handler, addr, err := utils.StartWSEndpoint(fmt.Sprintf("%s:%d", ctx.String(wsListenAddrFlag.Name), ctx.Int(wsPortFlag.Name)), apis, cfg.ProverManagerConfig.CompressionLevel)
88-
if err != nil {
89-
log.Crit("Could not start WS api", "error", err)
83+
go func() {
84+
if runServerErr := srv.ListenAndServe(); err != nil && !errors.Is(runServerErr, http.ErrServerClosed) {
85+
log.Crit("run coordinator http server failure", "error", runServerErr)
9086
}
91-
defer func() {
92-
_ = handler.Shutdown(ctx.Context)
93-
log.Info("WS endpoint closed", "url", fmt.Sprintf("ws://%v/", addr))
94-
}()
95-
log.Info("WS endpoint opened", "url", fmt.Sprintf("ws://%v/", addr))
96-
}
87+
}()
9788

9889
// Catch CTRL-C to ensure a graceful shutdown.
9990
interrupt := make(chan os.Signal, 1)
10091
signal.Notify(interrupt, os.Interrupt)
10192

10293
// Wait until the interrupt signal is received from an OS signal.
10394
<-interrupt
95+
log.Info("start shutdown coordinator server ...")
96+
97+
closeCtx, cancelExit := context.WithTimeout(context.Background(), 5*time.Second)
98+
defer cancelExit()
99+
if err = srv.Shutdown(closeCtx); err != nil {
100+
log.Warn("shutdown coordinator server failure", "error", err)
101+
return nil
102+
}
104103

104+
<-closeCtx.Done()
105+
log.Info("coordinator server exiting success")
105106
return nil
106107
}
107108

coordinator/cmd/app/mock_app.go

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import (
1818
)
1919

2020
var (
21-
wsStartPort int64 = 40000
21+
httpStartPort int64 = 40000
2222
)
2323

2424
// CoordinatorApp coordinator-test client manager.
@@ -29,7 +29,7 @@ type CoordinatorApp struct {
2929

3030
originFile string
3131
coordinatorFile string
32-
WSPort int64
32+
HTTPPort int64
3333

3434
args []string
3535
docker.AppAPI
@@ -39,13 +39,13 @@ type CoordinatorApp struct {
3939
func NewCoordinatorApp(base *docker.App, file string) *CoordinatorApp {
4040
coordinatorFile := fmt.Sprintf("/tmp/%d_coordinator-config.json", base.Timestamp)
4141
port, _ := rand.Int(rand.Reader, big.NewInt(2000))
42-
wsPort := port.Int64() + wsStartPort
42+
httpPort := port.Int64() + httpStartPort
4343
coordinatorApp := &CoordinatorApp{
4444
base: base,
4545
originFile: file,
4646
coordinatorFile: coordinatorFile,
47-
WSPort: wsPort,
48-
args: []string{"--log.debug", "--config", coordinatorFile, "--ws", "--ws.port", strconv.Itoa(int(wsPort))},
47+
HTTPPort: httpPort,
48+
args: []string{"--log.debug", "--config", coordinatorFile, "--http", "--http.port", strconv.Itoa(int(httpPort))},
4949
}
5050
if err := coordinatorApp.MockConfig(true); err != nil {
5151
panic(err)
@@ -67,9 +67,9 @@ func (c *CoordinatorApp) Free() {
6767
_ = os.Remove(c.coordinatorFile)
6868
}
6969

70-
// WSEndpoint returns ws endpoint.
71-
func (c *CoordinatorApp) WSEndpoint() string {
72-
return fmt.Sprintf("ws://localhost:%d", c.WSPort)
70+
// HTTPEndpoint returns ws endpoint.
71+
func (c *CoordinatorApp) HTTPEndpoint() string {
72+
return fmt.Sprintf("http://localhost:%d", c.HTTPPort)
7373
}
7474

7575
// MockConfig creates a new coordinator config.
@@ -80,14 +80,13 @@ func (c *CoordinatorApp) MockConfig(store bool) error {
8080
return err
8181
}
8282
// Reset prover manager config for manager test cases.
83-
cfg.ProverManagerConfig = &coordinatorConfig.ProverManagerConfig{
83+
cfg.ProverManager = &coordinatorConfig.ProverManager{
8484
ProversPerSession: 1,
8585
Verifier: &coordinatorConfig.VerifierConfig{MockMode: true},
86-
CollectionTime: 1,
87-
TokenTimeToLive: 1,
86+
CollectionTimeSec: 60,
8887
}
89-
cfg.DBConfig.DSN = base.DBImg.Endpoint()
90-
cfg.L2Config.ChainID = 111
88+
cfg.DB.DSN = base.DBImg.Endpoint()
89+
cfg.L2.ChainID = 111
9190
c.Config = cfg
9291

9392
if !store {

coordinator/conf/config.json

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,27 @@
11
{
2-
"prover_manager_config": {
3-
"compression_level": 9,
2+
"prover_manager": {
43
"provers_per_session": 1,
54
"session_attempts": 2,
6-
"collection_time": 180,
7-
"token_time_to_live": 60,
5+
"collection_time_sec": 180,
86
"verifier": {
97
"mock_mode": true,
108
"params_path": "",
119
"assets_path": ""
1210
},
13-
"max_verifier_workers": 10,
14-
"order_session": "ASC"
11+
"max_verifier_workers": 10
1512
},
16-
"db_config": {
13+
"db": {
1714
"driver_name": "postgres",
1815
"dsn": "postgres://admin:123456@localhost/test?sslmode=disable",
1916
"maxOpenNum": 200,
2017
"maxIdleNum": 20
2118
},
22-
"l2_config": {
19+
"l2": {
2320
"chain_id": 111
21+
},
22+
"auth": {
23+
"secret": "prover secret key",
24+
"challenge_expire_duration_sec": 3600,
25+
"login_expire_duration_sec": 3600
2426
}
2527
}

0 commit comments

Comments
 (0)