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