hermez-node/common/account.go
common/account.goRaw
1package common
2
3import (
4 "bytes"
5 "encoding/binary"
6 "fmt"
7 "math/big"
8 "strconv"
9
10 ethCommon "github.com/ethereum/go-ethereum/common"
11 "github.com/iden3/go-iden3-crypto/babyjub"
12 "github.com/iden3/go-iden3-crypto/poseidon"
13 cryptoUtils "github.com/iden3/go-iden3-crypto/utils"
14)
15
16const (
17 // NLeafElems is the number of elements for a leaf
18 NLeafElems = 4
19 // maxNonceValue is the maximum value that the Account.Nonce can have (40 bits: maxNonceValue=2**40-1)
20 maxNonceValue = 0xffffffffff
21 // maxBalanceBytes is the maximum bytes that can use the Account.Balance *big.Int
22 maxBalanceBytes = 24
23
24 idxBytesLen = 4
25 // maxIdxValue is the maximum value that Idx can have (32 bits: maxIdxValue=2**32-1)
26 maxIdxValue = 0xffffffff
27
28 // userThreshold determines the threshold from the User Idxs can be
29 userThreshold = 256
30 // IdxUserThreshold is a Idx type value that determines the threshold
31 // from the User Idxs can be
32 IdxUserThreshold = Idx(userThreshold)
33)
34
35var (
36 // FFAddr is used to check if an ethereum address is 0xff..ff
37 FFAddr = ethCommon.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff")
38 // EmptyAddr is used to check if an ethereum address is 0
39 EmptyAddr = ethCommon.HexToAddress("0x0000000000000000000000000000000000000000")
40)
41
42// Idx represents the account Index in the MerkleTree
43type Idx uint32
44
45// String returns a string representation of the Idx
46func (idx Idx) String() string {
47 return strconv.Itoa(int(idx))
48}
49
50// Bytes returns a byte array representing the Idx
51func (idx Idx) Bytes() []byte {
52 var b [4]byte
53 binary.BigEndian.PutUint32(b[:], uint32(idx))
54 return b[:]
55}
56
57// BigInt returns a *big.Int representing the Idx
58func (idx Idx) BigInt() *big.Int {
59 return big.NewInt(int64(idx))
60}
61
62// IdxFromBytes returns Idx from a byte array
63func IdxFromBytes(b []byte) (Idx, error) {
64 if len(b) != idxBytesLen {
65 return 0, fmt.Errorf("can not parse Idx, bytes len %d, expected 4", len(b))
66 }
67 idx := binary.BigEndian.Uint32(b[:4])
68 return Idx(idx), nil
69}
70
71// IdxFromBigInt converts a *big.Int to Idx type
72func IdxFromBigInt(b *big.Int) (Idx, error) {
73 if b.Int64() > maxIdxValue {
74 return 0, ErrNumOverflow
75 }
76 return Idx(uint32(b.Int64())), nil
77}
78
79// Account is a struct that gives information of the holdings of an address and a specific token. Is the data structure that generates the Value stored in the leaf of the MerkleTree
80type Account struct {
81 Idx Idx `meddler:"idx"`
82 TokenID TokenID `meddler:"token_id"`
83 BatchNum BatchNum `meddler:"batch_num"`
84 PublicKey *babyjub.PublicKey `meddler:"bjj"`
85 EthAddr ethCommon.Address `meddler:"eth_addr"`
86 Nonce Nonce `meddler:"-"` // max of 40 bits used
87 Balance *big.Int `meddler:"-"` // max of 192 bits used
88}
89
90func (a *Account) String() string {
91 buf := bytes.NewBufferString("")
92 fmt.Fprintf(buf, "PublicKey: %s..., ", a.PublicKey.String()[:10])
93 fmt.Fprintf(buf, "EthAddr: %s..., ", a.EthAddr.String()[:10])
94 fmt.Fprintf(buf, "TokenID: %v, ", a.TokenID)
95 fmt.Fprintf(buf, "Nonce: %d, ", a.Nonce)
96 fmt.Fprintf(buf, "Balance: %s, ", a.Balance.String())
97 return buf.String()
98}
99
100// Bytes returns the bytes representing the Account, in a way that each BigInt
101// is represented by 32 bytes, in spite of the BigInt could be represented in
102// less bytes (due a small big.Int), so in this way each BigInt is always 32
103// bytes and can be automatically parsed from a byte array.
104func (a *Account) Bytes() ([32 * NLeafElems]byte, error) {
105 var b [32 * NLeafElems]byte
106
107 if a.Nonce > maxNonceValue {
108 return b, fmt.Errorf("%s Nonce", ErrNumOverflow)
109 }
110 if len(a.Balance.Bytes()) > maxBalanceBytes {
111 return b, fmt.Errorf("%s Balance", ErrNumOverflow)
112 }
113
114 nonceBytes, err := a.Nonce.Bytes()
115 if err != nil {
116 return b, err
117 }
118
119 copy(b[0:4], a.TokenID.Bytes())
120 copy(b[4:9], nonceBytes[:])
121 if babyjub.PointCoordSign(a.PublicKey.X) {
122 b[10] = 1
123 }
124 copy(b[32:64], SwapEndianness(a.Balance.Bytes()))
125 copy(b[64:96], SwapEndianness(a.PublicKey.Y.Bytes()))
126 copy(b[96:116], a.EthAddr.Bytes())
127
128 return b, nil
129}
130
131// BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field
132func (a *Account) BigInts() ([NLeafElems]*big.Int, error) {
133 e := [NLeafElems]*big.Int{}
134
135 b, err := a.Bytes()
136 if err != nil {
137 return e, err
138 }
139
140 e[0] = new(big.Int).SetBytes(SwapEndianness(b[0:32]))
141 e[1] = new(big.Int).SetBytes(SwapEndianness(b[32:64]))
142 e[2] = new(big.Int).SetBytes(SwapEndianness(b[64:96]))
143 e[3] = new(big.Int).SetBytes(SwapEndianness(b[96:128]))
144
145 return e, nil
146}
147
148// HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation
149func (a *Account) HashValue() (*big.Int, error) {
150 b0 := big.NewInt(0)
151 toHash := []*big.Int{b0, b0, b0, b0, b0, b0}
152 lBI, err := a.BigInts()
153 if err != nil {
154 return nil, err
155 }
156 copy(toHash[:], lBI[:])
157
158 v, err := poseidon.Hash(toHash)
159 return v, err
160}
161
162// AccountFromBigInts returns a Account from a [5]*big.Int
163func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error) {
164 if !cryptoUtils.CheckBigIntArrayInField(e[:]) {
165 return nil, ErrNotInFF
166 }
167 var b [32 * NLeafElems]byte
168 copy(b[0:32], SwapEndianness(e[0].Bytes())) // SwapEndianness, as big.Int uses BigEndian
169 copy(b[32:64], SwapEndianness(e[1].Bytes()))
170 copy(b[64:96], SwapEndianness(e[2].Bytes()))
171 copy(b[96:128], SwapEndianness(e[3].Bytes()))
172
173 return AccountFromBytes(b)
174}
175
176// AccountFromBytes returns a Account from a byte array
177func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
178 tokenID, err := TokenIDFromBytes(b[0:4])
179 if err != nil {
180 return nil, err
181 }
182 var nonceBytes5 [5]byte
183 copy(nonceBytes5[:], b[4:9])
184 nonce := NonceFromBytes(nonceBytes5)
185 sign := b[10] == 1
186 balance := new(big.Int).SetBytes(SwapEndianness(b[32:56])) // b[32:56], as Balance is 192 bits (24 bytes)
187 if !bytes.Equal(b[56:64], []byte{0, 0, 0, 0, 0, 0, 0, 0}) {
188 return nil, fmt.Errorf("%s Balance", ErrNumOverflow)
189 }
190 ay := new(big.Int).SetBytes(SwapEndianness(b[64:96]))
191 pkPoint, err := babyjub.PointFromSignAndY(sign, ay)
192 if err != nil {
193 return nil, err
194 }
195 publicKey := babyjub.PublicKey(*pkPoint)
196 ethAddr := ethCommon.BytesToAddress(b[96:116])
197
198 if !cryptoUtils.CheckBigIntInField(balance) {
199 return nil, ErrNotInFF
200 }
201 if !cryptoUtils.CheckBigIntInField(ay) {
202 return nil, ErrNotInFF
203 }
204
205 a := Account{
206 TokenID: TokenID(tokenID),
207 Nonce: nonce,
208 Balance: balance,
209 PublicKey: &publicKey,
210 EthAddr: ethAddr,
211 }
212 return &a, nil
213}