arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/common/accountcreationauths.go
common/accountcreationauths.goRaw
 1package common
 2
 3import (
 4	"time"
 5
 6	ethCommon "github.com/ethereum/go-ethereum/common"
 7	ethCrypto "github.com/ethereum/go-ethereum/crypto"
 8	"github.com/iden3/go-iden3-crypto/babyjub"
 9)
10
11// AccountCreationAuth authorizations sent by users to the L2DB, to be used for account creations when necessary
12type AccountCreationAuth struct {
13	EthAddr   ethCommon.Address  `meddler:"eth_addr"`
14	BJJ       *babyjub.PublicKey `meddler:"bjj"`
15	Signature []byte             `meddler:"signature"`
16	Timestamp time.Time          `meddler:"timestamp,utctime"`
17}
18
19// HashToSign builds the hash to be signed using BJJ pub key and the constant message
20func (a *AccountCreationAuth) HashToSign() ([]byte, error) {
21	// Calculate message to be signed
22	const msg = "I authorize this babyjubjub key for hermez rollup account creation"
23	comp, err := a.BJJ.Compress().MarshalText()
24	if err != nil {
25		return nil, err
26	}
27	// Hash message (msg || compressed-bjj)
28	return ethCrypto.Keccak256Hash([]byte(msg), comp).Bytes(), nil
29}
30
31// VerifySignature ensures that the Signature is done with the specified EthAddr
32func (a *AccountCreationAuth) VerifySignature() bool {
33	// Calculate hash to be signed
34	msg, err := a.HashToSign()
35	if err != nil {
36		return false
37	}
38	// Get public key from Signature
39	pubKBytes, err := ethCrypto.Ecrecover(msg, a.Signature)
40	if err != nil {
41		return false
42	}
43	pubK, err := ethCrypto.UnmarshalPubkey(pubKBytes)
44	if err != nil {
45		return false
46	}
47	// Get addr from pubK
48	addr := ethCrypto.PubkeyToAddress(*pubK)
49	return addr == a.EthAddr
50}