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