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 idx bytes
25 IdxBytesLen = 6
26 // maxIdxValue is the maximum value that Idx can have (48 bits: maxIdxValue=2**48-1)
27 maxIdxValue = 0xffffffffffff
28
29 // UserThreshold determines the threshold from the User Idxs can be
30 UserThreshold = 256
31 // IdxUserThreshold is a Idx type value that determines the threshold
32 // from the User Idxs can be
33 IdxUserThreshold = Idx(UserThreshold)
34)
35
36var (
37 // FFAddr is used to check if an ethereum address is 0xff..ff
38 FFAddr = ethCommon.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff")
39 // EmptyAddr is used to check if an ethereum address is 0
40 EmptyAddr = ethCommon.HexToAddress("0x0000000000000000000000000000000000000000")
41)
42
43// Idx represents the account Index in the MerkleTree
44type Idx uint64
45
46// String returns a string representation of the Idx
47func (idx Idx) String() string {
48 return strconv.Itoa(int(idx))
49}
50
51// Bytes returns a byte array representing the Idx
52func (idx Idx) Bytes() ([6]byte, error) {
53 if idx > maxIdxValue {
54 return [6]byte{}, ErrIdxOverflow
55 }
56 var idxBytes [8]byte
57 binary.BigEndian.PutUint64(idxBytes[:], uint64(idx))
58 var b [6]byte
59 copy(b[:], idxBytes[2:])
60 return b, nil
61}
62
63// BigInt returns a *big.Int representing the Idx
64func (idx Idx) BigInt() *big.Int {
65 return big.NewInt(int64(idx))
66}
67
68// IdxFromBytes returns Idx from a byte array
69func IdxFromBytes(b []byte) (Idx, error) {
70 if len(b) != IdxBytesLen {
71 return 0, fmt.Errorf("can not parse Idx, bytes len %d, expected %d", len(b), IdxBytesLen)
72 }
73 var idxBytes [8]byte
74 copy(idxBytes[2:], b[:])
75 idx := binary.BigEndian.Uint64(idxBytes[:])
76 return Idx(idx), nil
77}
78
79// IdxFromBigInt converts a *big.Int to Idx type
80func IdxFromBigInt(b *big.Int) (Idx, error) {
81 if b.Int64() > maxIdxValue {
82 return 0, ErrNumOverflow
83 }
84 return Idx(uint64(b.Int64())), nil
85}
86
87// Nonce represents the nonce value in a uint64, which has the method Bytes that returns a byte array of length 5 (40 bits).
88type Nonce uint64
89
90// Bytes returns a byte array of length 5 representing the Nonce
91func (n Nonce) Bytes() ([5]byte, error) {
92 if n > maxNonceValue {
93 return [5]byte{}, ErrNonceOverflow
94 }
95 var nonceBytes [8]byte
96 binary.BigEndian.PutUint64(nonceBytes[:], uint64(n))
97 var b [5]byte
98 copy(b[:], nonceBytes[3:])
99 return b, nil
100}
101
102// BigInt returns the *big.Int representation of the Nonce value
103func (n Nonce) BigInt() *big.Int {
104 return big.NewInt(int64(n))
105}
106
107// NonceFromBytes returns Nonce from a [5]byte
108func NonceFromBytes(b [5]byte) Nonce {
109 var nonceBytes [8]byte
110 copy(nonceBytes[3:], b[:])
111 nonce := binary.BigEndian.Uint64(nonceBytes[:])
112 return Nonce(nonce)
113}
114
115// 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
116type Account struct {
117 Idx Idx `meddler:"idx"`
118 TokenID TokenID `meddler:"token_id"`
119 BatchNum BatchNum `meddler:"batch_num"`
120 PublicKey *babyjub.PublicKey `meddler:"bjj"`
121 EthAddr ethCommon.Address `meddler:"eth_addr"`
122 Nonce Nonce `meddler:"-"` // max of 40 bits used
123 Balance *big.Int `meddler:"-"` // max of 192 bits used
124}
125
126func (a *Account) String() string {
127 buf := bytes.NewBufferString("")
128 fmt.Fprintf(buf, "PublicKey: %s..., ", a.PublicKey.String()[:10])
129 fmt.Fprintf(buf, "EthAddr: %s..., ", a.EthAddr.String()[:10])
130 fmt.Fprintf(buf, "TokenID: %v, ", a.TokenID)
131 fmt.Fprintf(buf, "Nonce: %d, ", a.Nonce)
132 fmt.Fprintf(buf, "Balance: %s, ", a.Balance.String())
133 return buf.String()
134}
135
136// Bytes returns the bytes representing the Account, in a way that each BigInt
137// is represented by 32 bytes, in spite of the BigInt could be represented in
138// less bytes (due a small big.Int), so in this way each BigInt is always 32
139// bytes and can be automatically parsed from a byte array.
140func (a *Account) Bytes() ([32 * NLeafElems]byte, error) {
141 var b [32 * NLeafElems]byte
142
143 if a.Nonce > maxNonceValue {
144 return b, fmt.Errorf("%s Nonce", ErrNumOverflow)
145 }
146 if len(a.Balance.Bytes()) > maxBalanceBytes {
147 return b, fmt.Errorf("%s Balance", ErrNumOverflow)
148 }
149
150 nonceBytes, err := a.Nonce.Bytes()
151 if err != nil {
152 return b, err
153 }
154
155 copy(b[28:32], a.TokenID.Bytes())
156 copy(b[23:28], nonceBytes[:])
157
158 if a.PublicKey == nil {
159 return b, fmt.Errorf("Account.PublicKey can not be nil")
160 }
161 if babyjub.PointCoordSign(a.PublicKey.X) {
162 b[22] = 1
163 }
164 balanceBytes := a.Balance.Bytes()
165 copy(b[64-len(balanceBytes):64], balanceBytes)
166 ayBytes := a.PublicKey.Y.Bytes()
167 copy(b[96-len(ayBytes):96], ayBytes)
168 copy(b[108:128], a.EthAddr.Bytes())
169
170 return b, nil
171}
172
173// BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field
174func (a *Account) BigInts() ([NLeafElems]*big.Int, error) {
175 e := [NLeafElems]*big.Int{}
176
177 b, err := a.Bytes()
178 if err != nil {
179 return e, err
180 }
181
182 e[0] = new(big.Int).SetBytes(b[0:32])
183 e[1] = new(big.Int).SetBytes(b[32:64])
184 e[2] = new(big.Int).SetBytes(b[64:96])
185 e[3] = new(big.Int).SetBytes(b[96:128])
186
187 return e, nil
188}
189
190// HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation
191func (a *Account) HashValue() (*big.Int, error) {
192 bi, err := a.BigInts()
193 if err != nil {
194 return nil, err
195 }
196 return poseidon.Hash(bi[:])
197}
198
199// AccountFromBigInts returns a Account from a [5]*big.Int
200func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error) {
201 if !cryptoUtils.CheckBigIntArrayInField(e[:]) {
202 return nil, ErrNotInFF
203 }
204 e0B := e[0].Bytes()
205 e1B := e[1].Bytes()
206 e2B := e[2].Bytes()
207 e3B := e[3].Bytes()
208 var b [32 * NLeafElems]byte
209 copy(b[32-len(e0B):32], e0B)
210 copy(b[64-len(e1B):64], e1B)
211 copy(b[96-len(e2B):96], e2B)
212 copy(b[128-len(e3B):128], e3B)
213
214 return AccountFromBytes(b)
215}
216
217// AccountFromBytes returns a Account from a byte array
218func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
219 tokenID, err := TokenIDFromBytes(b[28:32])
220 if err != nil {
221 return nil, err
222 }
223 var nonceBytes5 [5]byte
224 copy(nonceBytes5[:], b[23:28])
225 nonce := NonceFromBytes(nonceBytes5)
226 sign := b[22] == 1
227
228 balance := new(big.Int).SetBytes(b[40:64])
229 // Balance is max of 192 bits (24 bytes)
230 if !bytes.Equal(b[32:40], []byte{0, 0, 0, 0, 0, 0, 0, 0}) {
231 return nil, fmt.Errorf("%s Balance", ErrNumOverflow)
232 }
233 ay := new(big.Int).SetBytes(b[64:96])
234 pkPoint, err := babyjub.PointFromSignAndY(sign, ay)
235 if err != nil {
236 return nil, err
237 }
238 publicKey := babyjub.PublicKey(*pkPoint)
239 ethAddr := ethCommon.BytesToAddress(b[108:128])
240
241 if !cryptoUtils.CheckBigIntInField(balance) {
242 return nil, ErrNotInFF
243 }
244 if !cryptoUtils.CheckBigIntInField(ay) {
245 return nil, ErrNotInFF
246 }
247
248 a := Account{
249 TokenID: TokenID(tokenID),
250 Nonce: nonce,
251 Balance: balance,
252 PublicKey: &publicKey,
253 EthAddr: ethAddr,
254 }
255 return &a, nil
256}