-
Notifications
You must be signed in to change notification settings - Fork 7
/
SigningUtils.go
293 lines (270 loc) · 9.02 KB
/
SigningUtils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package zksync
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/pkg/errors"
"math/big"
"strings"
)
const (
AmountExponentBitWidth int64 = 5
AmountMantissaBitWidth int64 = 35
FeeExponentBitWidth int64 = 5
FeeMantissaBitWidth int64 = 11
)
func Uint32ToBytes(v uint32) []byte {
res := make([]byte, 4)
binary.BigEndian.PutUint32(res, v)
return res
}
func Uint64ToBytes(v uint64) []byte {
res := make([]byte, 8)
binary.BigEndian.PutUint64(res, v)
return res
}
func BigIntToBytesBE(v *big.Int, numBytes int) []byte {
val := v.Bytes()
res := make([]byte, numBytes-len(val)) // left padded with 0 bytes to target length
return append(res, val...)
}
func pkhToBytes(pkh string) ([]byte, error) {
if pkh[:5] != "sync:" {
return nil, errors.New("PubKeyHash must start with 'sync:'")
}
res, err := hex.DecodeString(pkh[5:])
if err != nil {
return nil, err
}
if len(res) != 20 {
return nil, errors.New("pkh must be 20 bytes long")
}
return res, nil
}
func packFee(fee *big.Int) ([]byte, error) {
packedFee, err := integerToDecimalByteArray(fee, FeeExponentBitWidth, FeeMantissaBitWidth, 10)
if err != nil {
return nil, errors.Wrap(err, "failed to pack fee")
}
// check that unpacked fee still has same value
if unpackedFee, err := decimalByteArrayToInteger(packedFee, FeeExponentBitWidth, FeeMantissaBitWidth, 10); err != nil {
return nil, errors.Wrap(err, "failed to unpack fee")
} else if unpackedFee.Cmp(fee) != 0 {
return nil, errors.New("fee Amount is not packable")
}
return packedFee, nil
}
func packAmount(amount *big.Int) ([]byte, error) {
packedAmount, err := integerToDecimalByteArray(amount, AmountExponentBitWidth, AmountMantissaBitWidth, 10)
if err != nil {
return nil, errors.Wrap(err, "failed to pack amount")
}
// check that unpacked amount still has same value
if unpackedFee, err := decimalByteArrayToInteger(packedAmount, AmountExponentBitWidth, AmountMantissaBitWidth, 10); err != nil {
return nil, errors.Wrap(err, "failed to unpack amount")
} else if unpackedFee.Cmp(amount) != 0 {
return nil, errors.New("amount Amount is not packable")
}
return packedAmount, nil
}
func integerToDecimalByteArray(value *big.Int, expBits, mantissaBits, expBase int64) ([]byte, error) {
bigExpBase := big.NewInt(expBase)
// maxExponent = expBase ^ ((2 ^ expBits) - 1)
maxExpPow := big.NewInt(0).Sub(big.NewInt(0).Exp(big.NewInt(2), big.NewInt(expBits), nil), big.NewInt(1))
maxExponent := big.NewInt(0).Exp(bigExpBase, maxExpPow, nil)
// maxMantissa = (2 ^ mantissaBits) - 1
maxMantissa := big.NewInt(0).Sub(big.NewInt(0).Exp(big.NewInt(2), big.NewInt(mantissaBits), nil), big.NewInt(1))
// check for max possible value
if value.Cmp(big.NewInt(0).Mul(maxMantissa, maxExponent)) > 0 {
return nil, errors.New("Integer is too big")
}
exponent := uint64(0)
mantissa := big.NewInt(0).Set(value)
for mantissa.Cmp(maxMantissa) > 0 {
mantissa.Div(mantissa, bigExpBase)
exponent++
}
exponentData := uint64ToBitsLE(exponent, uint(expBits))
mantissaData := uint64ToBitsLE(mantissa.Uint64(), uint(mantissaBits))
combined := exponentData.Clone().Append(mantissaData)
reversed := combined.Reverse()
bytes, err := reversed.ToBytesBE()
if err != nil {
return nil, errors.Wrap(err, "failed to convert bits to bytes BE")
}
return bytes, nil
}
func decimalByteArrayToInteger(value []byte, expBits, mantissaBits, expBase int64) (*big.Int, error) {
if int64(len(value)*8) != expBits+mantissaBits {
return nil, errors.New("Decimal unpacking, incorrect input length")
}
bits := NewBits(uint(expBits + mantissaBits))
bits.FromBytesBE(value).Reverse()
exponent := big.NewInt(0)
expPow2 := big.NewInt(1)
for i := uint(0); i < uint(expBits); i++ {
if bits.GetBit(i) {
exponent.Add(exponent, expPow2)
}
expPow2.Mul(expPow2, big.NewInt(2))
}
exponent.Exp(big.NewInt(expBase), exponent, nil)
mantissa := big.NewInt(0)
mantissaPow2 := big.NewInt(1)
for i := uint(expBits); i < uint(expBits+mantissaBits); i++ {
if bits.GetBit(i) {
mantissa.Add(mantissa, mantissaPow2)
}
mantissaPow2.Mul(mantissaPow2, big.NewInt(2))
}
return exponent.Mul(exponent, mantissa), nil
}
func uint64ToBitsLE(v uint64, size uint) *Bits {
res := NewBits(size)
for i := uint(0); i < size; i++ {
res.SetBit(i, v&1 == 1)
v /= 2
}
return res
}
func GetSignMessage(tx ZksTransaction, token *Token, fee *big.Int) (string, error) {
switch tx.getType() {
case "Transfer":
if txData, ok := tx.(*Transfer); ok {
var tokenToUse *Token
if txData.Token != nil {
tokenToUse = txData.Token
} else {
tokenToUse = token
}
fee, ok := big.NewInt(0).SetString(txData.Fee, 10)
if !ok {
return "", errors.New("failed to convert string fee to big.Int")
}
msg, err := getTransferMessagePart(txData.To.String(), txData.Amount, fee, tokenToUse)
if err != nil {
return "", errors.Wrap(err, "failed to get Transfer message part")
}
return msg, nil
}
case "Withdraw":
if txData, ok := tx.(*Withdraw); ok {
msg, err := getWithdrawMessagePart(txData.To.String(), txData.Amount, fee, token)
if err != nil {
return "", errors.Wrap(err, "failed to get Withdraw message part")
}
return msg, nil
}
case "ForcedExit":
if txData, ok := tx.(*ForcedExit); ok {
msg, err := getForcedExitMessagePart(txData.Target.String(), fee, token)
if err != nil {
return "", errors.Wrap(err, "failed to get ForcedExit message part")
}
return msg, nil
}
case "MintNFT":
if txData, ok := tx.(*MintNFT); ok {
msg, err := getMintNFTMessagePart(txData.ContentHash, txData.Recipient.String(), fee, token)
if err != nil {
return "", errors.Wrap(err, "failed to get MintNFT message part")
}
return msg, nil
}
case "WithdrawNFT":
if txData, ok := tx.(*WithdrawNFT); ok {
msg, err := getWithdrawNFTMessagePart(txData.To.String(), txData.Token, fee, token)
if err != nil {
return "", errors.Wrap(err, "failed to get WithdrawNFT message part")
}
return msg, nil
}
case "Swap":
msg := getSwapMessagePart(token, fee)
return msg, nil
}
return "", errors.New("unknown tx type")
}
func GetChangePubKeyData(txData *ChangePubKey) ([]byte, error) {
buf := bytes.Buffer{}
pkhBytes, err := pkhToBytes(txData.NewPkHash)
if err != nil {
return nil, errors.Wrap(err, "failed to get pkh bytes")
}
buf.Write(pkhBytes)
buf.Write(Uint32ToBytes(txData.Nonce))
buf.Write(Uint32ToBytes(txData.AccountId))
buf.Write(txData.EthAuthData.getBytes())
return buf.Bytes(), nil
}
func getTransferMessagePart(to string, amount, fee *big.Int, token *Token) (string, error) {
var res string
if big.NewInt(0).Cmp(amount) != 0 {
res = fmt.Sprintf("Transfer %s %s to: %s", token.ToDecimalString(amount), token.Symbol, strings.ToLower(to))
}
if fee.Cmp(big.NewInt(0)) > 0 {
if len(res) > 0 {
res += "\n"
}
res += fmt.Sprintf("Fee: %s %s", token.ToDecimalString(fee), token.Symbol)
}
return res, nil
}
func getWithdrawMessagePart(to string, amount, fee *big.Int, token *Token) (string, error) {
var res string
if big.NewInt(0).Cmp(amount) != 0 {
res = fmt.Sprintf("Withdraw %s %s to: %s", token.ToDecimalString(amount), token.Symbol, strings.ToLower(to))
}
if fee.Cmp(big.NewInt(0)) > 0 {
if len(res) > 0 {
res += "\n"
}
res += fmt.Sprintf("Fee: %s %s", token.ToDecimalString(fee), token.Symbol)
}
return res, nil
}
func getForcedExitMessagePart(to string, fee *big.Int, token *Token) (string, error) {
var res string
res = fmt.Sprintf("ForcedExit %s to: %s", token.Symbol, strings.ToLower(to))
if fee.Cmp(big.NewInt(0)) > 0 {
res += fmt.Sprintf("\nFee: %s %s", token.ToDecimalString(fee), token.Symbol)
}
return res, nil
}
func getMintNFTMessagePart(contentHash common.Hash, to string, fee *big.Int, token *Token) (string, error) {
var res string
res = fmt.Sprintf("MintNFT %s for: %s", contentHash.String(), strings.ToLower(to))
if fee.Cmp(big.NewInt(0)) > 0 {
res += fmt.Sprintf("\nFee: %s %s", token.ToDecimalString(fee), token.Symbol)
}
return res, nil
}
func getWithdrawNFTMessagePart(to string, tokenId uint32, fee *big.Int, token *Token) (string, error) {
var res string
res = fmt.Sprintf("WithdrawNFT %d to: %s", tokenId, strings.ToLower(to))
if fee.Cmp(big.NewInt(0)) > 0 {
res += fmt.Sprintf("\nFee: %s %s", token.ToDecimalString(fee), token.Symbol)
}
return res, nil
}
func GetOrderMessagePart(recipient string, amount *big.Int, sell, buy *Token, ratio []*big.Int) (string, error) {
if len(ratio) != 2 {
return "", errors.New("invalid ratio")
}
var res string
if amount.Cmp(big.NewInt(0)) == 0 {
res = fmt.Sprintf("Limit order for %s -> %s", sell.Symbol, buy.Symbol)
} else {
res = fmt.Sprintf("Order for %s %s -> %s", sell.ToDecimalString(amount), sell.Symbol, buy.Symbol)
}
res += fmt.Sprintf("\nRatio: %s:%s\nAddress: %s", ratio[0].String(), ratio[1].String(), strings.ToLower(recipient))
return res, nil
}
func getSwapMessagePart(token *Token, fee *big.Int) string {
return fmt.Sprintf("Swap fee: %s %s", token.ToDecimalString(fee), token.Symbol)
}
func GetNonceMessagePart(nonce uint32) string {
return fmt.Sprintf("Nonce: %d", nonce)
}