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