Skip to content

Commit

Permalink
* Update datase schema and API endpoints to include the id of the cha…
Browse files Browse the repository at this point in the history
…in of each token

* Delete chain id from service matadata on the database and remove the checks about the chain id
* Update the scanner and token related API endpoints to use the web3 provider associated to each token
* Handle a list of supported web3 providers as cmd/census3 entrypoint flag
  • Loading branch information
lucasmenendez committed Sep 1, 2023
1 parent dd64cf3 commit f56ac6e
Show file tree
Hide file tree
Showing 26 changed files with 194 additions and 192 deletions.
62 changes: 9 additions & 53 deletions api/api.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
package api

import (
"context"
"database/sql"
"errors"
"fmt"
"time"

"github.com/ethereum/go-ethereum/ethclient"
"github.com/vocdoni/census3/census"
queries "github.com/vocdoni/census3/db/sqlc"
"go.vocdoni.io/dvote/httprouter"
Expand All @@ -16,37 +11,34 @@ import (
)

type Census3APIConf struct {
Hostname string
Port int
DataDir string
Web3URI string
GroupKey string
Hostname string
Port int
DataDir string
GroupKey string
Web3Providers map[int64]string
}

type census3API struct {
conf Census3APIConf
web3 string
db *sql.DB
sqlc *queries.Queries
endpoint *api.API
censusDB *census.CensusDB
w3p map[int64]string
}

func Init(db *sql.DB, q *queries.Queries, conf Census3APIConf) error {
newAPI := &census3API{
conf: conf,
web3: conf.Web3URI,
db: db,
sqlc: q,
w3p: conf.Web3Providers,
}
// get the current chainID
chainID, err := newAPI.setupChainID()
if err != nil {
log.Fatal(err)
}
log.Infow("starting API", "chainID", chainID, "web3", conf.Web3URI)
log.Infow("starting API", "chainID-web3Providers", conf.Web3Providers)

// create a new http router with the hostname and port provided in the conf
var err error
r := httprouter.HTTProuter{}
if err = r.Init(conf.Hostname, conf.Port); err != nil {
return err
Expand Down Expand Up @@ -75,39 +67,3 @@ func Init(db *sql.DB, q *queries.Queries, conf Census3APIConf) error {
}
return nil
}

// setup function gets the chainID from the web3 uri and checks if it is
// registered in the database. If it is registered, the function compares both
// values and panics if they are not the same. If it is not registered, the
// function stores it.
func (capi *census3API) setupChainID() (int64, error) {
web3client, err := ethclient.Dial(capi.web3)
if err != nil {
return -1, fmt.Errorf("error dialing to the web3 endpoint: %w", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// get the chainID from the web3 endpoint
chainID, err := web3client.ChainID(ctx)
if err != nil {
return -1, fmt.Errorf("error getting the chainID from the web3 endpoint: %w", err)
}
// get the current chainID from the database
currentChainID, err := capi.sqlc.ChainID(ctx)
if err != nil {
// if it not exists register the value received from the web3 endpoint
if errors.Is(err, sql.ErrNoRows) {
_, err := capi.sqlc.SetChainID(ctx, chainID.Int64())
if err != nil {
return -1, fmt.Errorf("error setting the chainID in the database: %w", err)
}
return chainID.Int64(), nil
}
return -1, fmt.Errorf("error getting chainID from the database: %w", err)
}
// compare both values
if currentChainID != chainID.Int64() {
return -1, fmt.Errorf("received chainID is not the same that registered one: %w", err)
}
return currentChainID, nil
}
5 changes: 0 additions & 5 deletions api/censuses.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,18 +57,13 @@ func (capi *census3API) getCensus(msg *api.APIdata, ctx *httprouter.HTTPContext)
}
return ErrCantGetCensus
}
chainID, err := qtx.ChainID(internalCtx)
if err != nil {
return ErrCantGetCensus
}
res, err := json.Marshal(GetCensusResponse{
CensusID: uint64(censusID),
StrategyID: uint64(currentCensus.StrategyID),
MerkleRoot: common.Bytes2Hex(currentCensus.MerkleRoot),
URI: "ipfs://" + currentCensus.Uri.String,
Size: int32(currentCensus.Size),
Weight: new(big.Int).SetBytes(currentCensus.Weight).String(),
ChainID: uint64(chainID),
})
if err != nil {
return ErrEncodeCensus
Expand Down
5 changes: 5 additions & 0 deletions api/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ var (
HTTPstatus: http.StatusConflict,
Err: fmt.Errorf("token already created"),
}
ErrChainIDNotSupported = apirest.APIerror{
Code: 4013,
HTTPstatus: apirest.HTTPstatusBadRequest,
Err: fmt.Errorf("chain ID provided not supported"),
}
ErrCantCreateToken = apirest.APIerror{
Code: 5000,
HTTPstatus: apirest.HTTPstatusInternalErr,
Expand Down
16 changes: 14 additions & 2 deletions api/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,12 @@ func (capi *census3API) createToken(msg *api.APIdata, ctx *httprouter.HTTPContex
w3 := state.Web3{}
internalCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := w3.Init(internalCtx, capi.web3, addr, tokenType); err != nil {
// get correct web3 uri provider
w3uri, exists := capi.w3p[req.ChainID]
if !exists {
return ErrChainIDNotSupported.With("chain ID not supported")
}
if err := w3.Init(internalCtx, w3uri, addr, tokenType); err != nil {
log.Errorw(ErrInitializingWeb3, err.Error())
return ErrInitializingWeb3
}
Expand Down Expand Up @@ -139,6 +144,7 @@ func (capi *census3API) createToken(msg *api.APIdata, ctx *httprouter.HTTPContex
TypeID: int64(tokenType),
Synced: false,
Tag: *tag,
ChainID: req.ChainID,
})
if err != nil {
if strings.Contains(err.Error(), "UNIQUE constraint failed") {
Expand Down Expand Up @@ -194,9 +200,14 @@ func (capi *census3API) getToken(msg *api.APIdata, ctx *httprouter.HTTPContext)
// calculate the current scan progress
tokenProgress := uint64(100)
if !tokenData.Synced {
// get correct web3 uri provider
w3uri, exists := capi.w3p[tokenData.ChainID]
if !exists {
return ErrChainIDNotSupported.With("chain ID not supported")
}
// get last block of the network, if something fails return progress 0
w3 := state.Web3{}
if err := w3.Init(internalCtx, capi.web3, address, state.TokenType(tokenData.TypeID)); err != nil {
if err := w3.Init(internalCtx, w3uri, address, state.TokenType(tokenData.TypeID)); err != nil {
return ErrInitializingWeb3.WithErr(err)
}
// fetch the last block header and calculate progress
Expand Down Expand Up @@ -232,6 +243,7 @@ func (capi *census3API) getToken(msg *api.APIdata, ctx *httprouter.HTTPContext)
// TODO: Only for the MVP, consider to remove it
Tag: tokenData.Tag.String,
DefaultStrategy: defaultStrategyID,
ChainID: tokenData.ChainID,
}
if tokenData.CreationBlock.Valid {
tokenResponse.StartBlock = uint64(tokenData.CreationBlock.Int32)
Expand Down
11 changes: 7 additions & 4 deletions api/types.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package api

type CreateTokenRequest struct {
ID string `json:"id"`
Type string `json:"type"`
Tag string `json:"tag"`
ID string `json:"id"`
Type string `json:"type"`
Tag string `json:"tag"`
ChainID int64 `json:"chainID"`
}

type GetTokenStatusResponse struct {
Expand All @@ -24,6 +25,7 @@ type GetTokenResponse struct {
Size uint32 `json:"size"`
DefaultStrategy uint64 `json:"defaultStrategy,omitempty"`
Tag string `json:"tag,omitempty"`
ChainID int64 `json:"chainID"`
}

type GetTokensItem struct {
Expand All @@ -33,6 +35,7 @@ type GetTokensItem struct {
Name string `json:"name"`
Symbol string `json:"symbol"`
Tag string `json:"tag,omitempty"`
ChainID int `json:"chainID"`
}

type GetTokensResponse struct {
Expand Down Expand Up @@ -63,7 +66,7 @@ type GetCensusResponse struct {
URI string `json:"uri"`
Size int32 `json:"size"`
Weight string `json:"weight"`
ChainID uint64 `json:"chainId"`
// ChainID uint64 `json:"chainId"`
}

type GetCensusesResponse struct {
Expand Down
21 changes: 14 additions & 7 deletions cmd/census3/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/vocdoni/census3/api"
"github.com/vocdoni/census3/db"
"github.com/vocdoni/census3/service"
"github.com/vocdoni/census3/state"
"go.vocdoni.io/dvote/log"
)

Expand All @@ -20,11 +21,11 @@ func main() {
panic(err)
}
home += "/.census3"
url := flag.String("url", "", "ethereum web3 url")
dataDir := flag.String("dataDir", home, "data directory for persistent storage")
logLevel := flag.String("logLevel", "info", "log level (debug, info, warn, error)")
port := flag.Int("port", 7788, "HTTP port for the API")
connectKey := flag.String("connectKey", "", "connect group key for IPFS connect")
web3Providers := flag.StringArray("web3Providers", []string{}, "the list of URL's of available web3 providers")
flag.Parse()
log.Init(*logLevel, "stdout", nil)

Expand All @@ -33,19 +34,25 @@ func main() {
log.Fatal(err)
}

w3p, err := state.CheckWeb3Providers(*web3Providers)
if err != nil {
log.Fatal(err)
}
log.Info(w3p)

// Start the holder scanner
hc, err := service.NewHoldersScanner(db, q, *url)
hc, err := service.NewHoldersScanner(db, q, w3p)
if err != nil {
log.Fatal(err)
}

// Start the API
err = api.Init(db, q, api.Census3APIConf{
Hostname: "0.0.0.0",
Port: *port,
DataDir: *dataDir,
Web3URI: *url,
GroupKey: *connectKey,
Hostname: "0.0.0.0",
Port: *port,
DataDir: *dataDir,
Web3Providers: w3p,
GroupKey: *connectKey,
})
if err != nil {
log.Fatal(err)
Expand Down
6 changes: 2 additions & 4 deletions db/migrations/0001_census3.sql
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
-- +goose Up
CREATE TABLE metadata (
chainID INTEGER PRIMARY KEY
);

CREATE TABLE strategies (
id INTEGER PRIMARY KEY,
predicate TEXT NOT NULL
Expand Down Expand Up @@ -30,6 +26,8 @@ CREATE TABLE tokens (
type_id INTEGER NOT NULL,
synced BOOLEAN NOT NULL,
tag TEXT,
chain_id INTEGER NOT NULL,
UNIQUE (id, chain_id),
FOREIGN KEY (type_id) REFERENCES token_types(id) ON DELETE CASCADE
);
CREATE INDEX idx_tokens_type_id ON tokens(type_id);
Expand Down
12 changes: 0 additions & 12 deletions db/queries/metadata.sql

This file was deleted.

5 changes: 3 additions & 2 deletions db/queries/tokens.sql
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,11 @@ INSERT INTO tokens (
creation_block,
type_id,
synced,
tag
tag,
chain_id
)
VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?
?, ?, ?, ?, ?, ?, ?, ?, ?, ?
);

-- name: UpdateToken :execresult
Expand Down
2 changes: 1 addition & 1 deletion db/sqlc/blocks.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion db/sqlc/censuses.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion db/sqlc/db.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 5 additions & 3 deletions db/sqlc/holders.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit f56ac6e

Please sign in to comment.