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