Impl account creation auth endpoints

This commit is contained in:
Arnau B
2020-10-21 16:40:31 +02:00
parent 721e5e8bf0
commit ede6c33a18
10 changed files with 271 additions and 26 deletions

View File

@@ -11,7 +11,6 @@ import (
var h *historydb.HistoryDB
var cg *configAPI
var s *statedb.StateDB
var l2 *l2db.L2DB

View File

@@ -51,6 +51,7 @@ type testCommon struct {
usrExits []exitAPI
poolTxsToSend []receivedPoolTx
poolTxsToReceive []sendPoolTx
auths []accountCreationAuthAPI
router *swagger.Router
}
@@ -637,6 +638,15 @@ func TestMain(m *testing.M) {
if err != nil {
panic(err)
}
// Account creation auth
const nAuths = 5
auths := test.GenAuths(nAuths)
// Transform auths to API format
apiAuths := []accountCreationAuthAPI{}
for _, auth := range auths {
apiAuth := accountCreationAuthToAPI(auth)
apiAuths = append(apiAuths, *apiAuth)
}
// Set testCommon
tc = testCommon{
blocks: blocks,
@@ -652,6 +662,7 @@ func TestMain(m *testing.M) {
usrExits: usrExits,
poolTxsToSend: poolTxsToSend,
poolTxsToReceive: poolTxsToReceive,
auths: apiAuths,
router: router,
}
// Fake server
@@ -1325,6 +1336,69 @@ func TestGetCoordinators(t *testing.T) {
err = doBadReq("GET", path, nil, 404)
assert.NoError(t, err)
}
func TestAccountCreationAuth(t *testing.T) {
// POST
endpoint := apiURL + "account-creation-authorization"
for _, auth := range tc.auths {
jsonAuthBytes, err := json.Marshal(auth)
assert.NoError(t, err)
jsonAuthReader := bytes.NewReader(jsonAuthBytes)
fmt.Println(string(jsonAuthBytes))
assert.NoError(
t, doGoodReq(
"POST",
endpoint,
jsonAuthReader, nil,
),
)
}
// GET
endpoint += "/"
for _, auth := range tc.auths {
fetchedAuth := accountCreationAuthAPI{}
assert.NoError(
t, doGoodReq(
"GET",
endpoint+auth.EthAddr,
nil, &fetchedAuth,
),
)
assertAuth(t, auth, fetchedAuth)
}
// POST
// 400
// Wrong addr
badAuth := tc.auths[0]
badAuth.EthAddr = ethAddrToHez(ethCommon.BigToAddress(big.NewInt(1)))
jsonAuthBytes, err := json.Marshal(badAuth)
assert.NoError(t, err)
jsonAuthReader := bytes.NewReader(jsonAuthBytes)
err = doBadReq("POST", endpoint, jsonAuthReader, 400)
assert.NoError(t, err)
// Wrong signature
badAuth = tc.auths[0]
badAuth.Signature = badAuth.Signature[:len(badAuth.Signature)-1]
badAuth.Signature += "F"
jsonAuthBytes, err = json.Marshal(badAuth)
assert.NoError(t, err)
jsonAuthReader = bytes.NewReader(jsonAuthBytes)
err = doBadReq("POST", endpoint, jsonAuthReader, 400)
assert.NoError(t, err)
// GET
// 400
err = doBadReq("GET", endpoint+"hez:0xFooBar", nil, 400)
assert.NoError(t, err)
// 404
err = doBadReq("GET", endpoint+"hez:0x0000000000000000000000000000000000000001", nil, 404)
assert.NoError(t, err)
}
func assertAuth(t *testing.T, expected, actual accountCreationAuthAPI) {
// timestamp should be very close to now
assert.Less(t, time.Now().UTC().Unix()-3, actual.Timestamp.Unix())
expected.Timestamp = actual.Timestamp
assert.Equal(t, expected, actual)
}
func doGoodReqPaginated(
path, order string,
@@ -1393,7 +1467,7 @@ func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{})
if err != nil {
return err
}
if resp.Body == nil {
if resp.Body == nil && returnStruct != nil {
return errors.New("Nil body")
}
//nolint
@@ -1403,10 +1477,14 @@ func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{})
return err
}
if resp.StatusCode != 200 {
return fmt.Errorf("%d response: %s", resp.StatusCode, string(body))
return fmt.Errorf("%d response. Body: %s", resp.StatusCode, string(body))
}
if returnStruct == nil {
return nil
}
// Unmarshal body into return struct
if err := json.Unmarshal(body, returnStruct); err != nil {
log.Error("invalid json: " + string(body))
return err
}
// Validate response against swagger spec

View File

@@ -2,10 +2,12 @@ package api
import (
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"math/big"
"strconv"
"strings"
"time"
ethCommon "github.com/ethereum/go-ethereum/common"
@@ -665,3 +667,47 @@ func coordinatorsToAPI(dbCoordinators []historydb.HistoryCoordinator) []coordina
}
return apiCoordinators
}
// AccountCreationAuth
type accountCreationAuthAPI struct {
EthAddr string `json:"hezEthereumAddress" binding:"required"`
BJJ string `json:"bjj" binding:"required"`
Signature string `json:"signature" binding:"required"`
Timestamp time.Time `json:"timestamp"`
}
func accountCreationAuthToAPI(dbAuth *common.AccountCreationAuth) *accountCreationAuthAPI {
return &accountCreationAuthAPI{
EthAddr: ethAddrToHez(dbAuth.EthAddr),
BJJ: bjjToString(dbAuth.BJJ),
Signature: "0x" + hex.EncodeToString(dbAuth.Signature),
Timestamp: dbAuth.Timestamp,
}
}
func accountCreationAuthAPIToCommon(apiAuth *accountCreationAuthAPI) (*common.AccountCreationAuth, error) {
ethAddr, err := hezStringToEthAddr(apiAuth.EthAddr, "hezEthereumAddress")
if err != nil {
return nil, err
}
bjj, err := hezStringToBJJ(apiAuth.BJJ, "bjj")
if err != nil {
return nil, err
}
without0x := strings.TrimPrefix(apiAuth.Signature, "0x")
s, err := hex.DecodeString(without0x)
if err != nil {
return nil, err
}
auth := &common.AccountCreationAuth{
EthAddr: *ethAddr,
BJJ: bjj,
Signature: s,
Timestamp: apiAuth.Timestamp,
}
if !auth.VerifySignature() {
return nil, errors.New("invalid signature")
}
return auth, nil
}

View File

@@ -30,10 +30,43 @@ var (
)
func postAccountCreationAuth(c *gin.Context) {
// Parse body
var apiAuth accountCreationAuthAPI
if err := c.ShouldBindJSON(&apiAuth); err != nil {
retBadReq(err, c)
return
}
// API to common + verify signature
dbAuth, err := accountCreationAuthAPIToCommon(&apiAuth)
if err != nil {
retBadReq(err, c)
return
}
// Insert to DB
if err := l2.AddAccountCreationAuth(dbAuth); err != nil {
retSQLErr(err, c)
return
}
// Return OK
c.Status(http.StatusOK)
}
func getAccountCreationAuth(c *gin.Context) {
// Get hezEthereumAddress
addr, err := parseParamHezEthAddr(c)
if err != nil {
retBadReq(err, c)
return
}
// Fetch auth from l2DB
dbAuth, err := l2.GetAccountCreationAuth(*addr)
if err != nil {
retSQLErr(err, c)
return
}
apiAuth := accountCreationAuthToAPI(dbAuth)
// Build succesfull response
c.JSON(http.StatusOK, apiAuth)
}
func postPoolTx(c *gin.Context) {

View File

@@ -310,6 +310,7 @@ func hezStringToBJJ(bjjStr, name string) (*babyjub.PublicKey, error) {
}
return bjj, nil
}
func parseEthAddr(c paramer, name string) (*ethCommon.Address, error) {
addrStr := c.Param(name)
if addrStr == "" {
@@ -319,3 +320,9 @@ func parseEthAddr(c paramer, name string) (*ethCommon.Address, error) {
err := addr.UnmarshalText([]byte(addrStr))
return &addr, err
}
func parseParamHezEthAddr(c paramer) (*ethCommon.Address, error) {
const name = "hermezEthereumAddress"
addrStr := c.Param(name)
return hezStringToEthAddr(addrStr, name)
}

View File

@@ -76,7 +76,7 @@ paths:
content:
application/json:
schema:
$ref: '#/components/schemas/AccountCreationAuthorization'
$ref: '#/components/schemas/AccountCreationAuthorizationPost'
responses:
'200':
description: Successful operation.
@@ -1251,7 +1251,7 @@ components:
$ref: '#/components/schemas/Nonce'
signature:
allOf:
- $ref: '#/components/schemas/Signature'
- $ref: '#/components/schemas/BJJSignature'
- description: Signature of the transaction. More info [here](https://idocs.hermez.io/#/spec/zkrollup/README?id=l2a-idl2).
- example: "72024a43f546b0e1d9d5d7c4c30c259102a9726363adcc4ec7b6aea686bcb5116f485c5542d27c4092ae0ceaf38e3bb44417639bd2070a58ba1aa1aab9d92c03"
requestFromAccountIndex:
@@ -1346,7 +1346,7 @@ components:
$ref: '#/components/schemas/PoolL2TransactionState'
signature:
allOf:
- $ref: '#/components/schemas/Signature'
- $ref: '#/components/schemas/BJJSignature'
- description: Signature of the transaction. More info [here](https://idocs.hermez.io/#/spec/zkrollup/README?id=l2a-idl2).
- example: "72024a43f546b0e1d9d5d7c4c30c259102a9726363adcc4ec7b6aea686bcb5116f485c5542d27c4092ae0ceaf38e3bb44417639bd2070a58ba1aa1aab9d92c03"
timestamp:
@@ -1517,7 +1517,12 @@ components:
- fing
- fged
- invl
Signature:
ETHSignature:
type: string
description: Ethereum signature.
pattern: "^0x[a-fA-F0-9]{130}$"
example: "0xf9161cd688394772d93aa3e7b3f8f9553ca4f94f65b7cece93ed4a239d5c0b4677dca6d1d459e3a5c271a34de735d4664a43e5a8960a9a6e027d12c562dd448e1c"
BJJSignature:
type: string
description: BabyJubJub compressed signature.
pattern: "^[a-fA-F0-9]{128}$"
@@ -1528,6 +1533,19 @@ components:
minimum: 0
maximum: 4294967295
example: 5432
AccountCreationAuthorizationPost:
type: object
properties:
hezEthereumAddress:
$ref: '#/components/schemas/HezEthereumAddress'
bjj:
$ref: '#/components/schemas/BJJ'
signature:
$ref: '#/components/schemas/ETHSignature'
required:
- hezEthereumAddress
- bjj
- signature
AccountCreationAuthorization:
type: object
properties:
@@ -1539,12 +1557,10 @@ components:
bjj:
$ref: '#/components/schemas/BJJ'
signature:
allOf:
- $ref: '#/components/schemas/Signature'
- description: Signature of the auth message. More info [here](https://idocs.hermez.io/#/spec/zkrollup/README?id=regular-rollup-account).
- example: "72024a43f546b0e1d9d5d7c4c30c259102a9726363adcc4ec7b6aea686bcb5116f485c5542d27c4092ae0ceaf38e3bb44417639bd2070a58ba1aa1aab9d92c03"
$ref: '#/components/schemas/ETHSignature'
required:
- ethereumAddress
- timestamp
- hezEthereumAddress
- bjj
- signature
HistoryTransaction: