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, "Idx: %v, ", a.Idx)
129 fmt.Fprintf(buf, "PublicKey: %s..., ", a.PublicKey.String()[:10])
130 fmt.Fprintf(buf, "EthAddr: %s..., ", a.EthAddr.String()[:10])
131 fmt.Fprintf(buf, "TokenID: %v, ", a.TokenID)
132 fmt.Fprintf(buf, "Nonce: %d, ", a.Nonce)
133 fmt.Fprintf(buf, "Balance: %s, ", a.Balance.String())
134 fmt.Fprintf(buf, "BatchNum: %v, ", a.BatchNum)
135 return buf.String()
136}
137
138// Bytes returns the bytes representing the Account, in a way that each BigInt
139// is represented by 32 bytes, in spite of the BigInt could be represented in
140// less bytes (due a small big.Int), so in this way each BigInt is always 32
141// bytes and can be automatically parsed from a byte array.
142func (a *Account) Bytes() ([32 * NLeafElems]byte, error) {
143 var b [32 * NLeafElems]byte
144
145 if a.Nonce > maxNonceValue {
146 return b, fmt.Errorf("%s Nonce", ErrNumOverflow)
147 }
148 if len(a.Balance.Bytes()) > maxBalanceBytes {
149 return b, fmt.Errorf("%s Balance", ErrNumOverflow)
150 }
151
152 nonceBytes, err := a.Nonce.Bytes()
153 if err != nil {
154 return b, err
155 }
156
157 copy(b[28:32], a.TokenID.Bytes())
158 copy(b[23:28], nonceBytes[:])
159
160 if a.PublicKey == nil {
161 return b, fmt.Errorf("Account.PublicKey can not be nil")
162 }
163 if babyjub.PointCoordSign(a.PublicKey.X) {
164 b[22] = 1
165 }
166 balanceBytes := a.Balance.Bytes()
167 copy(b[64-len(balanceBytes):64], balanceBytes)
168 ayBytes := a.PublicKey.Y.Bytes()
169 copy(b[96-len(ayBytes):96], ayBytes)
170 copy(b[108:128], a.EthAddr.Bytes())
171
172 return b, nil
173}
174
175// BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field
176func (a *Account) BigInts() ([NLeafElems]*big.Int, error) {
177 e := [NLeafElems]*big.Int{}
178
179 b, err := a.Bytes()
180 if err != nil {
181 return e, err
182 }
183
184 e[0] = new(big.Int).SetBytes(b[0:32])
185 e[1] = new(big.Int).SetBytes(b[32:64])
186 e[2] = new(big.Int).SetBytes(b[64:96])
187 e[3] = new(big.Int).SetBytes(b[96:128])
188
189 return e, nil
190}
191
192// HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation
193func (a *Account) HashValue() (*big.Int, error) {
194 bi, err := a.BigInts()
195 if err != nil {
196 return nil, err
197 }
198 return poseidon.Hash(bi[:])
199}
200
201// AccountFromBigInts returns a Account from a [5]*big.Int
202func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error) {
203 if !cryptoUtils.CheckBigIntArrayInField(e[:]) {
204 return nil, ErrNotInFF
205 }
206 e0B := e[0].Bytes()
207 e1B := e[1].Bytes()
208 e2B := e[2].Bytes()
209 e3B := e[3].Bytes()
210 var b [32 * NLeafElems]byte
211 copy(b[32-len(e0B):32], e0B)
212 copy(b[64-len(e1B):64], e1B)
213 copy(b[96-len(e2B):96], e2B)
214 copy(b[128-len(e3B):128], e3B)
215
216 return AccountFromBytes(b)
217}
218
219// AccountFromBytes returns a Account from a byte array
220func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
221 tokenID, err := TokenIDFromBytes(b[28:32])
222 if err != nil {
223 return nil, err
224 }
225 var nonceBytes5 [5]byte
226 copy(nonceBytes5[:], b[23:28])
227 nonce := NonceFromBytes(nonceBytes5)
228 sign := b[22] == 1
229
230 balance := new(big.Int).SetBytes(b[40:64])
231 // Balance is max of 192 bits (24 bytes)
232 if !bytes.Equal(b[32:40], []byte{0, 0, 0, 0, 0, 0, 0, 0}) {
233 return nil, fmt.Errorf("%s Balance", ErrNumOverflow)
234 }
235 ay := new(big.Int).SetBytes(b[64:96])
236 pkPoint, err := babyjub.PointFromSignAndY(sign, ay)
237 if err != nil {
238 return nil, err
239 }
240 publicKey := babyjub.PublicKey(*pkPoint)
241 ethAddr := ethCommon.BytesToAddress(b[108:128])
242
243 if !cryptoUtils.CheckBigIntInField(balance) {
244 return nil, ErrNotInFF
245 }
246 if !cryptoUtils.CheckBigIntInField(ay) {
247 return nil, ErrNotInFF
248 }
249
250 a := Account{
251 TokenID: TokenID(tokenID),
252 Nonce: nonce,
253 Balance: balance,
254 PublicKey: &publicKey,
255 EthAddr: ethAddr,
256 }
257 return &a, nil
258}