hermez-node/api/accountcreationauths_test.go
api/accountcreationauths_test.goRaw
1package api
2
3import (
4 "bytes"
5 "encoding/hex"
6 "encoding/json"
7 "math/big"
8 "testing"
9 "time"
10
11 ethCommon "github.com/ethereum/go-ethereum/common"
12 "github.com/hermeznetwork/hermez-node/common"
13 "github.com/stretchr/testify/assert"
14)
15
16type testAuth struct {
17 EthAddr string `json:"hezEthereumAddress" binding:"required"`
18 BJJ string `json:"bjj" binding:"required"`
19 Signature string `json:"signature" binding:"required"`
20 Timestamp time.Time `json:"timestamp"`
21}
22
23func genTestAuths(auths []*common.AccountCreationAuth) []testAuth {
24 testAuths := []testAuth{}
25 for _, auth := range auths {
26 testAuths = append(testAuths, testAuth{
27 EthAddr: ethAddrToHez(auth.EthAddr),
28 BJJ: bjjToString(auth.BJJ),
29 Signature: "0x" + hex.EncodeToString(auth.Signature),
30 Timestamp: auth.Timestamp,
31 })
32 }
33 return testAuths
34}
35
36func TestAccountCreationAuth(t *testing.T) {
37 // POST
38 endpoint := apiURL + "account-creation-authorization"
39 for _, auth := range tc.auths {
40 jsonAuthBytes, err := json.Marshal(auth)
41 assert.NoError(t, err)
42 jsonAuthReader := bytes.NewReader(jsonAuthBytes)
43 assert.NoError(
44 t, doGoodReq(
45 "POST",
46 endpoint,
47 jsonAuthReader, nil,
48 ),
49 )
50 }
51 // GET
52 endpoint += "/"
53 for _, auth := range tc.auths {
54 fetchedAuth := testAuth{}
55 assert.NoError(
56 t, doGoodReq(
57 "GET",
58 endpoint+auth.EthAddr,
59 nil, &fetchedAuth,
60 ),
61 )
62 assertAuth(t, auth, fetchedAuth)
63 }
64 // POST
65 // 400
66 // Wrong addr
67 badAuth := tc.auths[0]
68 badAuth.EthAddr = ethAddrToHez(ethCommon.BigToAddress(big.NewInt(1)))
69 jsonAuthBytes, err := json.Marshal(badAuth)
70 assert.NoError(t, err)
71 jsonAuthReader := bytes.NewReader(jsonAuthBytes)
72 err = doBadReq("POST", endpoint, jsonAuthReader, 400)
73 assert.NoError(t, err)
74 // Wrong signature
75 badAuth = tc.auths[0]
76 badAuth.Signature = badAuth.Signature[:len(badAuth.Signature)-1]
77 badAuth.Signature += "F"
78 jsonAuthBytes, err = json.Marshal(badAuth)
79 assert.NoError(t, err)
80 jsonAuthReader = bytes.NewReader(jsonAuthBytes)
81 err = doBadReq("POST", endpoint, jsonAuthReader, 400)
82 assert.NoError(t, err)
83 // GET
84 // 400
85 err = doBadReq("GET", endpoint+"hez:0xFooBar", nil, 400)
86 assert.NoError(t, err)
87 // 404
88 err = doBadReq("GET", endpoint+"hez:0x0000000000000000000000000000000000000001", nil, 404)
89 assert.NoError(t, err)
90}
91
92func assertAuth(t *testing.T, expected, actual testAuth) {
93 // timestamp should be very close to now
94 assert.Less(t, time.Now().UTC().Unix()-3, actual.Timestamp.Unix())
95 expected.Timestamp = actual.Timestamp
96 assert.Equal(t, expected, actual)
97}