mirror of
https://github.com/discountry/ritmex-bot.git
synced 2026-09-09 08:18:07 +00:00
feat: 添加 Lighter 适配器及相关功能,支持 trailing stops 和新的交易逻辑
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
.idea
|
||||
vendor
|
||||
build/*
|
||||
!build/.keep
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,9 @@
|
||||
# lighter-go
|
||||
|
||||
In its current form, this repo serves as a starting point for anyone who wants to trade on Lighter using GO.
|
||||
It covers all the signing procedures in order to trade on Lighter with an API key.
|
||||
Minimal HTTP calls are implemented
|
||||
On chain support, like depositing on Ethereum or modifying an API key directly with an Ethereum Tx are not supported yet.
|
||||
|
||||
At the moment, its main purpose is to offer visibility on the code behind the precompiled libraries used by the Python SDK.
|
||||
If you'd like to compile your own binaries, the commands are in the `justfile`
|
||||
@@ -0,0 +1,49 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
dialer = &net.Dialer{
|
||||
Timeout: 10 * time.Second,
|
||||
KeepAlive: 60 * time.Second,
|
||||
}
|
||||
transport = &http.Transport{
|
||||
DialContext: dialer.DialContext,
|
||||
MaxConnsPerHost: 1000,
|
||||
MaxIdleConnsPerHost: 100,
|
||||
IdleConnTimeout: 10 * time.Second,
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
}
|
||||
|
||||
httpClient = &http.Client{
|
||||
Timeout: time.Second * 30,
|
||||
Transport: transport,
|
||||
}
|
||||
)
|
||||
|
||||
type HTTPClient struct {
|
||||
endpoint string
|
||||
channelName string
|
||||
fatFingerProtection bool
|
||||
}
|
||||
|
||||
func NewHTTPClient(baseUrl string) *HTTPClient {
|
||||
if baseUrl == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &HTTPClient{
|
||||
endpoint: baseUrl,
|
||||
channelName: "",
|
||||
fatFingerProtection: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *HTTPClient) SetFatFingerProtection(enabled bool) {
|
||||
c.fatFingerProtection = enabled
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/elliottech/lighter-go/types/txtypes"
|
||||
)
|
||||
|
||||
func (c *HTTPClient) parseResultStatus(respBody []byte) error {
|
||||
resultStatus := &ResultCode{}
|
||||
if err := json.Unmarshal(respBody, resultStatus); err != nil {
|
||||
return err
|
||||
}
|
||||
if resultStatus.Code != CodeOK {
|
||||
return errors.New(resultStatus.Message)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *HTTPClient) getAndParseL2HTTPResponse(path string, params map[string]any, result interface{}) error {
|
||||
u, err := url.Parse(c.endpoint)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
u.Path = path
|
||||
|
||||
q := u.Query()
|
||||
for k, v := range params {
|
||||
q.Set(k, fmt.Sprintf("%v", v))
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
resp, err := httpClient.Get(u.String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return errors.New(string(body))
|
||||
}
|
||||
if err = c.parseResultStatus(body); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := json.Unmarshal(body, result); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *HTTPClient) GetNextNonce(accountIndex int64, apiKeyIndex uint8) (int64, error) {
|
||||
result := &NextNonce{}
|
||||
err := c.getAndParseL2HTTPResponse("api/v1/nextNonce", map[string]any{"account_index": accountIndex, "api_key_index": apiKeyIndex}, result)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
return result.Nonce, nil
|
||||
}
|
||||
|
||||
func (c *HTTPClient) GetApiKey(accountIndex int64, apiKeyIndex uint8) (*AccountApiKeys, error) {
|
||||
result := &AccountApiKeys{}
|
||||
err := c.getAndParseL2HTTPResponse("api/v1/apikeys", map[string]any{"account_index": accountIndex, "api_key_index": apiKeyIndex}, result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *HTTPClient) SendRawTx(tx txtypes.TxInfo) (string, error) {
|
||||
txType := tx.GetTxType()
|
||||
txInfo, err := tx.GetTxInfo()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
data := url.Values{"tx_type": {strconv.Itoa(int(txType))}, "tx_info": {txInfo}}
|
||||
|
||||
if c.fatFingerProtection == false {
|
||||
data.Add("price_protection", "false")
|
||||
}
|
||||
|
||||
req, _ := http.NewRequest("POST", c.endpoint+"/api/v1/sendTx", strings.NewReader(data.Encode()))
|
||||
req.Header.Set("Channel-Name", c.channelName)
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", errors.New(string(body))
|
||||
}
|
||||
if err = c.parseResultStatus(body); err != nil {
|
||||
return "", err
|
||||
}
|
||||
res := &TxHash{}
|
||||
if err := json.Unmarshal(body, res); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return res.TxHash, nil
|
||||
}
|
||||
|
||||
func (c *HTTPClient) GetTransferFeeInfo(accountIndex, toAccountIndex int64, auth string) (*TransferFeeInfo, error) {
|
||||
result := &TransferFeeInfo{}
|
||||
err := c.getAndParseL2HTTPResponse("api/v1/transferFeeInfo", map[string]any{
|
||||
"account_index": accountIndex,
|
||||
"to_account_index": toAccountIndex,
|
||||
"auth": auth,
|
||||
}, result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package client
|
||||
|
||||
const (
|
||||
CodeOK = 200
|
||||
)
|
||||
|
||||
type ResultCode struct {
|
||||
Code int32 `json:"code,example=200"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
type NextNonce struct {
|
||||
ResultCode
|
||||
Nonce int64 `json:"nonce,example=722"`
|
||||
}
|
||||
|
||||
type ApiKey struct {
|
||||
AccountIndex int64 `json:"account_index,example=3"`
|
||||
ApiKeyIndex uint8 `json:"api_key_index,example=0"`
|
||||
Nonce int64 `json:"nonce,example=722"`
|
||||
PublicKey string `json:"public_key"`
|
||||
}
|
||||
|
||||
type AccountApiKeys struct {
|
||||
ResultCode
|
||||
ApiKeys []*ApiKey `json:"api_keys"`
|
||||
}
|
||||
|
||||
type TxHash struct {
|
||||
ResultCode
|
||||
TxHash string `json:"tx_hash,example=0x70997970C51812dc3A010C7d01b50e0d17dc79C8"`
|
||||
}
|
||||
|
||||
type TransferFeeInfo struct {
|
||||
ResultCode
|
||||
TransferFee int64 `json:"transfer_fee_usdc"`
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/elliottech/lighter-go/signer"
|
||||
"github.com/elliottech/lighter-go/types"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultExpireTime = time.Minute*10 - time.Second // we need to give a second margin, to eliminate millisecond differences
|
||||
)
|
||||
|
||||
type TxClient struct {
|
||||
apiClient *HTTPClient
|
||||
chainId uint32
|
||||
keyManager signer.KeyManager
|
||||
accountIndex int64
|
||||
apiKeyIndex uint8
|
||||
}
|
||||
|
||||
// NewTxClient is linked to a specific (account, apiKey) pair
|
||||
// apiKeyPrivateKey should be hex-encoded bytes generated using `hexutil.Encode(TxClient.GetKeyManager().PrvKeyBytes())`
|
||||
func NewTxClient(apiClient *HTTPClient, apiKeyPrivateKey string, accountIndex int64, apiKeyIndex uint8, chainId uint32) (*TxClient, error) {
|
||||
// remove 0x from private key, if any, and parse to bytes
|
||||
if len(apiKeyPrivateKey) < 2 {
|
||||
return nil, fmt.Errorf("empty private key")
|
||||
}
|
||||
if apiKeyPrivateKey[:2] == "0x" {
|
||||
apiKeyPrivateKey = apiKeyPrivateKey[2:]
|
||||
}
|
||||
b, err := hex.DecodeString(apiKeyPrivateKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
keyManager, err := signer.NewKeyManager(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &TxClient{
|
||||
apiClient: apiClient,
|
||||
apiKeyIndex: apiKeyIndex,
|
||||
accountIndex: accountIndex,
|
||||
chainId: chainId,
|
||||
keyManager: keyManager,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) FullFillDefaultOps(ops *types.TransactOpts) (*types.TransactOpts, error) {
|
||||
if ops == nil {
|
||||
ops = new(types.TransactOpts)
|
||||
}
|
||||
if ops.ExpiredAt == 0 {
|
||||
ops.ExpiredAt = time.Now().Add(defaultExpireTime).UnixMilli()
|
||||
}
|
||||
if ops.FromAccountIndex == nil {
|
||||
ops.FromAccountIndex = &c.accountIndex
|
||||
}
|
||||
if ops.ApiKeyIndex == nil {
|
||||
ops.ApiKeyIndex = &c.apiKeyIndex
|
||||
}
|
||||
if ops.Nonce == nil {
|
||||
if c.apiClient == nil {
|
||||
return nil, fmt.Errorf("nonce was not provided & HTTPClient is nil. Either provide the nonce or enable HTTPClient to get the nonce from Lighter")
|
||||
}
|
||||
nonce, err := c.apiClient.GetNextNonce(*ops.FromAccountIndex, *ops.ApiKeyIndex)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
return ops, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetAccountIndex() int64 {
|
||||
return c.accountIndex
|
||||
}
|
||||
|
||||
func (c *TxClient) GetApiKeyIndex() uint8 {
|
||||
return c.apiKeyIndex
|
||||
}
|
||||
|
||||
func (c *TxClient) GetKeyManager() signer.KeyManager {
|
||||
return c.keyManager
|
||||
}
|
||||
|
||||
func (c *TxClient) GetAuthToken(deadline time.Time) (string, error) {
|
||||
if time.Until(deadline) > (7 * time.Hour) {
|
||||
return "", fmt.Errorf("deadline should be within 7 hours")
|
||||
}
|
||||
|
||||
return types.ConstructAuthToken(c.keyManager, deadline, &types.TransactOpts{
|
||||
ApiKeyIndex: &c.apiKeyIndex,
|
||||
FromAccountIndex: &c.accountIndex,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *TxClient) HTTP() *HTTPClient {
|
||||
return c.apiClient
|
||||
}
|
||||
|
||||
func (c *TxClient) SwitchAPIKey(apiKey uint8) {
|
||||
c.apiKeyIndex = apiKey
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/elliottech/lighter-go/types"
|
||||
"github.com/elliottech/lighter-go/types/txtypes"
|
||||
schnorr "github.com/elliottech/poseidon_crypto/signature/schnorr"
|
||||
)
|
||||
|
||||
func (c *TxClient) GetChangePubKeyTransaction(tx *types.ChangePubKeyReq, ops *types.TransactOpts) (*txtypes.L2ChangePubKeyTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructChangePubKeyTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pk := c.keyManager.PubKeyBytes()
|
||||
msgHash, _ := txInfo.Hash(c.chainId)
|
||||
|
||||
if err := schnorr.Validate(pk[:], msgHash, txInfo.Sig); err != nil {
|
||||
return nil, fmt.Errorf("failed to validate signature. error: %v", err)
|
||||
}
|
||||
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetCreateSubAccountTransaction(ops *types.TransactOpts) (*txtypes.L2CreateSubAccountTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructCreateSubAccountTx(c.keyManager, c.chainId, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetCreatePublicPoolTransaction(tx *types.CreatePublicPoolTxReq, ops *types.TransactOpts) (*txtypes.L2CreatePublicPoolTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructCreatePublicPoolTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetUpdatePublicPoolTransaction(tx *types.UpdatePublicPoolTxReq, ops *types.TransactOpts) (*txtypes.L2UpdatePublicPoolTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructUpdatePublicPoolTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetTransferTransaction(tx *types.TransferTxReq, ops *types.TransactOpts) (*txtypes.L2TransferTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructTransferTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetWithdrawTransaction(tx *types.WithdrawTxReq, ops *types.TransactOpts) (*txtypes.L2WithdrawTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructWithdrawTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetCreateOrderTransaction(tx *types.CreateOrderTxReq, ops *types.TransactOpts) (*txtypes.L2CreateOrderTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructCreateOrderTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetCancelOrderTransaction(tx *types.CancelOrderTxReq, ops *types.TransactOpts) (*txtypes.L2CancelOrderTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructL2CancelOrderTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetModifyOrderTransaction(tx *types.ModifyOrderTxReq, ops *types.TransactOpts) (*txtypes.L2ModifyOrderTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
txInfo, err := types.ConstructL2ModifyOrderTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetCancelAllOrdersTransaction(tx *types.CancelAllOrdersTxReq, ops *types.TransactOpts) (*txtypes.L2CancelAllOrdersTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructL2CancelAllOrdersTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetMintSharesTransaction(tx *types.MintSharesTxReq, ops *types.TransactOpts) (*txtypes.L2MintSharesTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructMintSharesTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetBurnSharesTransaction(tx *types.BurnSharesTxReq, ops *types.TransactOpts) (*txtypes.L2BurnSharesTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructBurnSharesTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetUpdateLeverageTransaction(tx *types.UpdateLeverageTxReq, ops *types.TransactOpts) (*txtypes.L2UpdateLeverageTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructUpdateLeverageTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetUpdateMarginTransaction(tx *types.UpdateMarginTxReq, ops *types.TransactOpts) (*txtypes.L2UpdateMarginTxInfo, error) {
|
||||
if c.keyManager == nil {
|
||||
return nil, fmt.Errorf("key manager is nil")
|
||||
}
|
||||
|
||||
if ops == nil {
|
||||
ops = new(types.TransactOpts)
|
||||
}
|
||||
|
||||
txInfo, err := types.ConstructUpdateMarginTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
module github.com/elliottech/lighter-go
|
||||
|
||||
go 1.23.0
|
||||
|
||||
toolchain go1.23.1
|
||||
|
||||
require (
|
||||
github.com/elliottech/poseidon_crypto v0.0.11
|
||||
github.com/ethereum/go-ethereum v1.15.6
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bits-and-blooms/bitset v1.17.0 // indirect
|
||||
github.com/consensys/gnark-crypto v0.14.0 // indirect
|
||||
github.com/holiman/uint256 v1.3.2 // indirect
|
||||
golang.org/x/crypto v0.35.0 // indirect
|
||||
golang.org/x/sys v0.30.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,24 @@
|
||||
github.com/bits-and-blooms/bitset v1.17.0 h1:1X2TS7aHz1ELcC0yU1y2stUs/0ig5oMU6STFZGrhvHI=
|
||||
github.com/bits-and-blooms/bitset v1.17.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
|
||||
github.com/consensys/gnark-crypto v0.14.0 h1:DDBdl4HaBtdQsq/wfMwJvZNE80sHidrK3Nfrefatm0E=
|
||||
github.com/consensys/gnark-crypto v0.14.0/go.mod h1:CU4UijNPsHawiVGNxe9co07FkzCeWHHrb1li/n1XoU0=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/elliottech/poseidon_crypto v0.0.11 h1:iX4rCg0m1XIX/7mhXVUEYUJIdQD57zNGNLeb6RZRl7g=
|
||||
github.com/elliottech/poseidon_crypto v0.0.11/go.mod h1:NhWxSjPGr5JXRuB2Aepl/+ZrbmUG3hvku/GarB1JR8c=
|
||||
github.com/ethereum/go-ethereum v1.15.6 h1:jgLoUM6/pNjp0uEnXyWcWikDwa4j1wZlcqkX8Pm8A+I=
|
||||
github.com/ethereum/go-ethereum v1.15.6/go.mod h1:+S9k+jFzlyVTNcYGvqFhzN/SFhI6vA+aOY4T5tLSPL0=
|
||||
github.com/holiman/uint256 v1.3.2 h1:a9EgMPSC1AAaj1SZL5zIQD3WbwTuHrMGOerLjGmM/TA=
|
||||
github.com/holiman/uint256 v1.3.2/go.mod h1:EOMSn4q6Nyt9P6efbI3bueV4e1b3dGlUCXeiRV4ng7E=
|
||||
github.com/leanovate/gopter v0.2.11 h1:vRjThO1EKPb/1NsDXuDrzldR28RLkBflWYcU9CvzWu4=
|
||||
github.com/leanovate/gopter v0.2.11/go.mod h1:aK3tzZP/C+p1m3SPRE4SYZFGP7jjkuSI4f7Xvpt0S9c=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
golang.org/x/crypto v0.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs=
|
||||
golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ=
|
||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,12 @@
|
||||
build-darwin-local:
|
||||
go mod vendor
|
||||
go build -buildmode=c-shared -trimpath -o ./build/signer-arm64.dylib ./sharedlib/sharedlib.go
|
||||
|
||||
build-linux-local:
|
||||
go mod vendor
|
||||
go build -buildmode=c-shared -trimpath -o ./build/signer-amd64.so ./sharedlib/sharedlib.go
|
||||
|
||||
build-linux-docker:
|
||||
go mod vendor
|
||||
docker run --platform linux/amd64 -v $(pwd):/go/src/sdk golang:1.23.2-bullseye /bin/sh -c "cd /go/src/sdk && go build -buildmode=c-shared -trimpath -o ./build/signer-amd64.so ./sharedlib/sharedlib.go"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,54 @@
|
||||
package signer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"hash"
|
||||
|
||||
curve "github.com/elliottech/poseidon_crypto/curve/ecgfp5"
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
schnorr "github.com/elliottech/poseidon_crypto/signature/schnorr"
|
||||
)
|
||||
|
||||
type Signer interface {
|
||||
Sign(message []byte, hFunc hash.Hash) ([]byte, error)
|
||||
}
|
||||
|
||||
type KeyManager interface {
|
||||
Signer
|
||||
PubKey() gFp5.Element
|
||||
PubKeyBytes() [40]byte
|
||||
PrvKeyBytes() []byte
|
||||
}
|
||||
|
||||
type keyManager struct {
|
||||
key curve.ECgFp5Scalar
|
||||
}
|
||||
|
||||
func NewKeyManager(b []byte) (KeyManager, error) {
|
||||
if len(b) != 40 {
|
||||
return nil, fmt.Errorf("invalid private key length. expected: 40 got: %v", len(b))
|
||||
}
|
||||
return &keyManager{key: curve.ScalarElementFromLittleEndianBytes(b)}, nil
|
||||
}
|
||||
|
||||
func (key *keyManager) Sign(hashedMessage []byte, hFunc hash.Hash) ([]byte, error) {
|
||||
hashedMessageAsQuinticExtension, err := gFp5.FromCanonicalLittleEndianBytes(hashedMessage)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse message while signing. message: %v err: %w", hashedMessage, err)
|
||||
}
|
||||
return schnorr.SchnorrSignHashedMessage(hashedMessageAsQuinticExtension, key.key).ToBytes(), nil
|
||||
}
|
||||
|
||||
func (key *keyManager) PubKey() gFp5.Element {
|
||||
return schnorr.SchnorrPkFromSk(key.key)
|
||||
}
|
||||
|
||||
func (key *keyManager) PubKeyBytes() (res [40]byte) {
|
||||
bytes := key.PubKey().ToLittleEndianBytes()
|
||||
copy(res[:], bytes[:])
|
||||
return
|
||||
}
|
||||
|
||||
func (key *keyManager) PrvKeyBytes() []byte {
|
||||
return key.key.ToLittleEndianBytes()
|
||||
}
|
||||
@@ -0,0 +1,659 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/elliottech/lighter-go/signer"
|
||||
"github.com/elliottech/lighter-go/types/txtypes"
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
ethCommon "github.com/ethereum/go-ethereum/common"
|
||||
)
|
||||
|
||||
type TransactOpts struct {
|
||||
FromAccountIndex *int64
|
||||
ApiKeyIndex *uint8
|
||||
ExpiredAt int64
|
||||
Nonce *int64
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
type PublicKey = gFp5.Element
|
||||
|
||||
type ChangePubKeyReq struct {
|
||||
PubKey [40]byte
|
||||
}
|
||||
|
||||
type TransferTxReq struct {
|
||||
ToAccountIndex int64
|
||||
USDCAmount int64
|
||||
Fee int64
|
||||
Memo [32]byte
|
||||
}
|
||||
|
||||
type WithdrawTxReq struct {
|
||||
USDCAmount uint64
|
||||
}
|
||||
|
||||
type CreateOrderTxReq struct {
|
||||
MarketIndex uint8
|
||||
ClientOrderIndex int64
|
||||
BaseAmount int64
|
||||
Price uint32
|
||||
IsAsk uint8
|
||||
Type uint8
|
||||
TimeInForce uint8
|
||||
ReduceOnly uint8
|
||||
TriggerPrice uint32
|
||||
OrderExpiry int64
|
||||
}
|
||||
|
||||
type CreateGroupedOrdersTxReq struct {
|
||||
GroupingType uint8
|
||||
Orders []*CreateOrderTxReq
|
||||
}
|
||||
|
||||
type ModifyOrderTxReq struct {
|
||||
MarketIndex uint8
|
||||
Index int64
|
||||
BaseAmount int64
|
||||
Price uint32
|
||||
TriggerPrice uint32
|
||||
}
|
||||
|
||||
type CancelOrderTxReq struct {
|
||||
MarketIndex uint8
|
||||
Index int64
|
||||
}
|
||||
|
||||
type CancelAllOrdersTxReq struct {
|
||||
TimeInForce uint8
|
||||
Time int64
|
||||
}
|
||||
|
||||
type CreatePublicPoolTxReq struct {
|
||||
OperatorFee int64
|
||||
InitialTotalShares int64
|
||||
MinOperatorShareRate int64
|
||||
}
|
||||
|
||||
type UpdatePublicPoolTxReq struct {
|
||||
PublicPoolIndex int64
|
||||
Status uint8
|
||||
OperatorFee int64
|
||||
MinOperatorShareRate int64
|
||||
}
|
||||
|
||||
type MintSharesTxReq struct {
|
||||
PublicPoolIndex int64
|
||||
ShareAmount int64
|
||||
}
|
||||
|
||||
type BurnSharesTxReq struct {
|
||||
PublicPoolIndex int64
|
||||
ShareAmount int64
|
||||
}
|
||||
|
||||
type UpdateLeverageTxReq struct {
|
||||
MarketIndex uint8
|
||||
InitialMarginFraction uint16
|
||||
MarginMode uint8
|
||||
}
|
||||
|
||||
type UpdateMarginTxReq struct {
|
||||
MarketIndex uint8
|
||||
USDCAmount int64
|
||||
Direction uint8
|
||||
}
|
||||
|
||||
func ConstructAuthToken(key signer.Signer, deadline time.Time, ops *TransactOpts) (string, error) {
|
||||
if ops.FromAccountIndex == nil {
|
||||
return "", fmt.Errorf("missing FromAccountIndex")
|
||||
}
|
||||
if ops.ApiKeyIndex == nil {
|
||||
return "", fmt.Errorf("missing ApiKeyIndex")
|
||||
}
|
||||
message := fmt.Sprintf("%v:%v:%v", deadline.Unix(), *ops.FromAccountIndex, *ops.ApiKeyIndex)
|
||||
|
||||
msgInField, err := g.ArrayFromCanonicalLittleEndianBytes([]byte(message))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to convert bytes to field element. message: %s, error: %w", message, err)
|
||||
}
|
||||
|
||||
msgHash := p2.HashToQuinticExtension(msgInField).ToLittleEndianBytes()
|
||||
|
||||
signatureBytes, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
signature := ethCommon.Bytes2Hex(signatureBytes)
|
||||
|
||||
return fmt.Sprintf("%v:%v", message, signature), err
|
||||
}
|
||||
|
||||
func ConstructChangePubKeyTx(key signer.Signer, lighterChainId uint32, tx *ChangePubKeyReq, ops *TransactOpts) (*txtypes.L2ChangePubKeyTxInfo, error) {
|
||||
convertedTx := ConvertChangePubKeyTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructCreateSubAccountTx(key signer.Signer, lighterChainId uint32, ops *TransactOpts) (*txtypes.L2CreateSubAccountTxInfo, error) {
|
||||
convertedTx := ConvertCreateSubAccountTx(ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructCreatePublicPoolTx(key signer.Signer, lighterChainId uint32, tx *CreatePublicPoolTxReq, ops *TransactOpts) (*txtypes.L2CreatePublicPoolTxInfo, error) {
|
||||
convertedTx := ConvertCreatePublicPoolTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructUpdatePublicPoolTx(key signer.Signer, lighterChainId uint32, tx *UpdatePublicPoolTxReq, ops *TransactOpts) (*txtypes.L2UpdatePublicPoolTxInfo, error) {
|
||||
convertedTx := ConvertUpdatePublicPoolTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructWithdrawTx(key signer.Signer, lighterChainId uint32, tx *WithdrawTxReq, ops *TransactOpts) (*txtypes.L2WithdrawTxInfo, error) {
|
||||
convertedTx := ConvertWithdrawTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructCreateOrderTx(key signer.Signer, lighterChainId uint32, tx *CreateOrderTxReq, ops *TransactOpts) (*txtypes.L2CreateOrderTxInfo, error) {
|
||||
convertedTx := ConvertCreateOrderTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructL2CreateGroupedOrdersTx(key signer.Signer, lighterChainId uint32, tx *CreateGroupedOrdersTxReq, ops *TransactOpts) (*txtypes.L2CreateGroupedOrdersTxInfo, error) {
|
||||
convertedTx := ConvertCreateGroupedOrdersTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructL2CancelOrderTx(key signer.Signer, lighterChainId uint32, tx *CancelOrderTxReq, ops *TransactOpts) (*txtypes.L2CancelOrderTxInfo, error) {
|
||||
convertedTx := ConvertCancelOrderTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructL2ModifyOrderTx(key signer.Signer, lighterChainId uint32, tx *ModifyOrderTxReq, ops *TransactOpts) (*txtypes.L2ModifyOrderTxInfo, error) {
|
||||
convertedTx := ConvertModifyOrderTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructL2CancelAllOrdersTx(key signer.Signer, lighterChainId uint32, tx *CancelAllOrdersTxReq, ops *TransactOpts) (*txtypes.L2CancelAllOrdersTxInfo, error) {
|
||||
convertedTx := ConvertCancelAllOrdersTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructTransferTx(key signer.Signer, lighterChainId uint32, tx *TransferTxReq, ops *TransactOpts) (*txtypes.L2TransferTxInfo, error) {
|
||||
convertedTx := ConvertTransferTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructMintSharesTx(key signer.Signer, lighterChainId uint32, tx *MintSharesTxReq, ops *TransactOpts) (*txtypes.L2MintSharesTxInfo, error) {
|
||||
convertedTx := ConvertMintSharesTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructBurnSharesTx(key signer.Signer, lighterChainId uint32, tx *BurnSharesTxReq, ops *TransactOpts) (*txtypes.L2BurnSharesTxInfo, error) {
|
||||
convertedTx := ConvertBurnSharesTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructUpdateLeverageTx(key signer.Signer, lighterChainId uint32, tx *UpdateLeverageTxReq, ops *TransactOpts) (*txtypes.L2UpdateLeverageTxInfo, error) {
|
||||
convertedTx := ConvertUpdateLeverageTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructUpdateMarginTx(key signer.Signer, lighterChainId uint32, tx *UpdateMarginTxReq, ops *TransactOpts) (*txtypes.L2UpdateMarginTxInfo, error) {
|
||||
convertedTx := ConvertUpdateMarginTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConvertTransferTx(tx *TransferTxReq, ops *TransactOpts) *txtypes.L2TransferTxInfo {
|
||||
return &txtypes.L2TransferTxInfo{
|
||||
FromAccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
ToAccountIndex: tx.ToAccountIndex,
|
||||
USDCAmount: tx.USDCAmount,
|
||||
Fee: tx.Fee,
|
||||
Memo: tx.Memo,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertCreateOrderTx(tx *CreateOrderTxReq, ops *TransactOpts) *txtypes.L2CreateOrderTxInfo {
|
||||
return &txtypes.L2CreateOrderTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
OrderInfo: &txtypes.OrderInfo{MarketIndex: tx.MarketIndex,
|
||||
ClientOrderIndex: tx.ClientOrderIndex,
|
||||
BaseAmount: tx.BaseAmount,
|
||||
Price: tx.Price,
|
||||
IsAsk: tx.IsAsk,
|
||||
Type: tx.Type,
|
||||
TimeInForce: tx.TimeInForce,
|
||||
ReduceOnly: tx.ReduceOnly,
|
||||
TriggerPrice: tx.TriggerPrice,
|
||||
OrderExpiry: tx.OrderExpiry,
|
||||
},
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertCreateGroupedOrdersTx(tx *CreateGroupedOrdersTxReq, ops *TransactOpts) *txtypes.L2CreateGroupedOrdersTxInfo {
|
||||
ret := &txtypes.L2CreateGroupedOrdersTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
GroupingType: tx.GroupingType,
|
||||
Orders: []*txtypes.OrderInfo{},
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
|
||||
for _, order := range tx.Orders {
|
||||
ret.Orders = append(ret.Orders, &txtypes.OrderInfo{
|
||||
MarketIndex: order.MarketIndex,
|
||||
ClientOrderIndex: order.ClientOrderIndex,
|
||||
BaseAmount: order.BaseAmount,
|
||||
Price: order.Price,
|
||||
IsAsk: order.IsAsk,
|
||||
Type: order.Type,
|
||||
TimeInForce: order.TimeInForce,
|
||||
ReduceOnly: order.ReduceOnly,
|
||||
TriggerPrice: order.TriggerPrice,
|
||||
OrderExpiry: order.OrderExpiry,
|
||||
})
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func ConvertCancelOrderTx(tx *CancelOrderTxReq, ops *TransactOpts) *txtypes.L2CancelOrderTxInfo {
|
||||
return &txtypes.L2CancelOrderTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
MarketIndex: tx.MarketIndex,
|
||||
Index: tx.Index,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertModifyOrderTx(tx *ModifyOrderTxReq, ops *TransactOpts) *txtypes.L2ModifyOrderTxInfo {
|
||||
return &txtypes.L2ModifyOrderTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
MarketIndex: tx.MarketIndex,
|
||||
Index: tx.Index,
|
||||
BaseAmount: tx.BaseAmount,
|
||||
Price: tx.Price,
|
||||
TriggerPrice: tx.TriggerPrice,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertCancelAllOrdersTx(tx *CancelAllOrdersTxReq, ops *TransactOpts) *txtypes.L2CancelAllOrdersTxInfo {
|
||||
return &txtypes.L2CancelAllOrdersTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
TimeInForce: tx.TimeInForce,
|
||||
Time: tx.Time,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertWithdrawTx(tx *WithdrawTxReq, ops *TransactOpts) *txtypes.L2WithdrawTxInfo {
|
||||
return &txtypes.L2WithdrawTxInfo{
|
||||
FromAccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
USDCAmount: tx.USDCAmount,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertChangePubKeyTx(tx *ChangePubKeyReq, ops *TransactOpts) *txtypes.L2ChangePubKeyTxInfo {
|
||||
return &txtypes.L2ChangePubKeyTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
PubKey: tx.PubKey[:],
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertCreateSubAccountTx(ops *TransactOpts) *txtypes.L2CreateSubAccountTxInfo {
|
||||
return &txtypes.L2CreateSubAccountTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertCreatePublicPoolTx(tx *CreatePublicPoolTxReq, ops *TransactOpts) *txtypes.L2CreatePublicPoolTxInfo {
|
||||
return &txtypes.L2CreatePublicPoolTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
OperatorFee: tx.OperatorFee,
|
||||
InitialTotalShares: tx.InitialTotalShares,
|
||||
MinOperatorShareRate: tx.MinOperatorShareRate,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertUpdatePublicPoolTx(tx *UpdatePublicPoolTxReq, ops *TransactOpts) *txtypes.L2UpdatePublicPoolTxInfo {
|
||||
return &txtypes.L2UpdatePublicPoolTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
PublicPoolIndex: tx.PublicPoolIndex,
|
||||
Status: tx.Status,
|
||||
OperatorFee: tx.OperatorFee,
|
||||
MinOperatorShareRate: tx.MinOperatorShareRate,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertMintSharesTx(tx *MintSharesTxReq, ops *TransactOpts) *txtypes.L2MintSharesTxInfo {
|
||||
return &txtypes.L2MintSharesTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
PublicPoolIndex: tx.PublicPoolIndex,
|
||||
ShareAmount: tx.ShareAmount,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertBurnSharesTx(tx *BurnSharesTxReq, ops *TransactOpts) *txtypes.L2BurnSharesTxInfo {
|
||||
return &txtypes.L2BurnSharesTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
PublicPoolIndex: tx.PublicPoolIndex,
|
||||
ShareAmount: tx.ShareAmount,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertUpdateLeverageTx(tx *UpdateLeverageTxReq, ops *TransactOpts) *txtypes.L2UpdateLeverageTxInfo {
|
||||
return &txtypes.L2UpdateLeverageTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
MarketIndex: tx.MarketIndex,
|
||||
InitialMarginFraction: tx.InitialMarginFraction,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertUpdateMarginTx(tx *UpdateMarginTxReq, ops *TransactOpts) *txtypes.L2UpdateMarginTxInfo {
|
||||
return &txtypes.L2UpdateMarginTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
MarketIndex: tx.MarketIndex,
|
||||
USDCAmount: tx.USDCAmount,
|
||||
Direction: tx.Direction,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2BurnSharesTxInfo)(nil)
|
||||
|
||||
type L2BurnSharesTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
PublicPoolIndex int64
|
||||
ShareAmount int64
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2BurnSharesTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2BurnShares
|
||||
}
|
||||
|
||||
func (txInfo *L2BurnSharesTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2BurnSharesTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2BurnSharesTxInfo) Validate() error {
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// PublicPoolIndex
|
||||
if txInfo.PublicPoolIndex < MinAccountIndex {
|
||||
return ErrPublicPoolIndexTooLow
|
||||
}
|
||||
if txInfo.PublicPoolIndex > MaxAccountIndex {
|
||||
return ErrPublicPoolIndexTooHigh
|
||||
}
|
||||
|
||||
if txInfo.ShareAmount < MinPoolSharesToMintOrBurn {
|
||||
return ErrPoolBurnShareAmountTooLow
|
||||
}
|
||||
if txInfo.ShareAmount > MaxPoolSharesToMintOrBurn {
|
||||
return ErrPoolBurnShareAmountTooHigh
|
||||
}
|
||||
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2BurnSharesTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 8)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2BurnShares))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.PublicPoolIndex))
|
||||
elems = append(elems, g.FromInt64(txInfo.ShareAmount))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2CancelAllOrdersTxInfo)(nil)
|
||||
|
||||
type L2CancelAllOrdersTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
TimeInForce uint8
|
||||
Time int64
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelAllOrdersTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2CancelAllOrders
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelAllOrdersTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelAllOrdersTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelAllOrdersTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrAccountIndexTooHigh
|
||||
}
|
||||
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex && txInfo.ApiKeyIndex != NilApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
// TimeInForce and Time
|
||||
switch txInfo.TimeInForce {
|
||||
case ImmediateCancelAll:
|
||||
if txInfo.Time != NilOrderExpiry {
|
||||
return ErrCancelAllTimeisNotNill
|
||||
}
|
||||
case ScheduledCancelAll:
|
||||
if txInfo.Time < MinOrderExpiry || txInfo.Time > MaxOrderExpiry {
|
||||
return ErrCancelAllTimeIsNotInRange
|
||||
}
|
||||
case AbortScheduledCancelAll:
|
||||
if txInfo.Time != 0 {
|
||||
return ErrCancelAllTimeIsNotInRange
|
||||
}
|
||||
default:
|
||||
return ErrInvalidCancelAllTimeInForce
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelAllOrdersTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 8)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2CancelAllOrders))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.TimeInForce)))
|
||||
elems = append(elems, g.FromInt64(txInfo.Time))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2CancelOrderTxInfo)(nil)
|
||||
|
||||
type L2CancelOrderTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
MarketIndex uint8
|
||||
Index int64 // Client Order Index or Order Index of the order to cancel
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelOrderTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2CancelOrder
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelOrderTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelOrderTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelOrderTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// MarketIndex
|
||||
if txInfo.MarketIndex < MinMarketIndex {
|
||||
return ErrMarketIndexTooLow
|
||||
}
|
||||
if txInfo.MarketIndex > MaxMarketIndex {
|
||||
return ErrMarketIndexTooHigh
|
||||
}
|
||||
|
||||
// Index
|
||||
if txInfo.Index < MinClientOrderIndex && txInfo.Index < MinOrderIndex {
|
||||
return ErrOrderIndexTooLow
|
||||
}
|
||||
if txInfo.Index > MaxClientOrderIndex && txInfo.Index > MaxOrderIndex {
|
||||
return ErrOrderIndexTooHigh
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelOrderTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 7)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2CancelOrder))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.MarketIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.Index))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
)
|
||||
|
||||
const (
|
||||
templateChangePubKey = "Register Lighter Account\n\npubkey: 0x%s\nnonce: %s\naccount index: %s\napi key index: %s\nOnly sign this message for a trusted client!"
|
||||
)
|
||||
|
||||
func getHex10FromUint64(value uint64) string {
|
||||
v := hexutil.EncodeUint64(value)
|
||||
v = strings.Replace(v, "0x", "", 1)
|
||||
|
||||
// Make sure result has fixed bytes
|
||||
vBytes := []byte(v)
|
||||
if len(vBytes) < 16 {
|
||||
toAppend := make([]byte, 16-len(vBytes))
|
||||
for i := range toAppend {
|
||||
toAppend[i] = 48
|
||||
}
|
||||
vBytes = append(toAppend, vBytes...)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("0x%s", string(vBytes))
|
||||
}
|
||||
|
||||
var _ TxInfo = (*L2ChangePubKeyTxInfo)(nil)
|
||||
|
||||
type L2ChangePubKeyTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
PubKey []byte
|
||||
L1Sig string
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2ChangePubKeyTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2ChangePubKey
|
||||
}
|
||||
|
||||
func (txInfo *L2ChangePubKeyTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2ChangePubKeyTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2ChangePubKeyTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
if !IsValidPubKey(txInfo.PubKey) {
|
||||
return ErrPubKeyInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2ChangePubKeyTxInfo) GetL1SignatureBody() string {
|
||||
signatureBody := fmt.Sprintf(templateChangePubKey,
|
||||
common.Bytes2Hex(txInfo.PubKey),
|
||||
getHex10FromUint64(uint64(txInfo.Nonce)),
|
||||
getHex10FromUint64(uint64(txInfo.AccountIndex)),
|
||||
getHex10FromUint64(uint64(txInfo.ApiKeyIndex)),
|
||||
)
|
||||
return signatureBody
|
||||
}
|
||||
|
||||
func (txInfo *L2ChangePubKeyTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 11)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2ChangePubKey))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
|
||||
pubKeyFieldElems, err := g.ArrayFromCanonicalLittleEndianBytes(txInfo.PubKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to convert bytes to field element. bytes: %v, error: %w", txInfo.PubKey, err)
|
||||
}
|
||||
elems = append(elems, pubKeyFieldElems...)
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
curve "github.com/elliottech/poseidon_crypto/curve/ecgfp5"
|
||||
schnorr "github.com/elliottech/poseidon_crypto/signature/schnorr"
|
||||
)
|
||||
|
||||
type (
|
||||
Signature = schnorr.Signature
|
||||
PrivateKey = curve.ECgFp5Scalar
|
||||
)
|
||||
|
||||
const (
|
||||
NilApiKeyIndex = MaxApiKeyIndex + 1
|
||||
)
|
||||
|
||||
const (
|
||||
TxTypeL2ChangePubKey = 8
|
||||
TxTypeL2CreateSubAccount = 9
|
||||
TxTypeL2CreatePublicPool = 10
|
||||
TxTypeL2UpdatePublicPool = 11
|
||||
TxTypeL2Transfer = 12
|
||||
TxTypeL2Withdraw = 13
|
||||
TxTypeL2CreateOrder = 14
|
||||
TxTypeL2CancelOrder = 15
|
||||
TxTypeL2CancelAllOrders = 16
|
||||
TxTypeL2ModifyOrder = 17
|
||||
TxTypeL2MintShares = 18
|
||||
TxTypeL2BurnShares = 19
|
||||
TxTypeL2UpdateLeverage = 20
|
||||
|
||||
TxTypeInternalClaimOrder = 21
|
||||
TxTypeInternalCancelOrder = 22
|
||||
TxTypeInternalDeleverage = 23
|
||||
TxTypeInternalExitPosition = 24
|
||||
TxTypeInternalCancelAllOrders = 25
|
||||
TxTypeInternalLiquidatePosition = 26
|
||||
TxTypeInternalCreateOrder = 27
|
||||
|
||||
TxTypeL2CreateGroupedOrders = 28
|
||||
TxTypeL2UpdateMargin = 29
|
||||
)
|
||||
|
||||
// Order Type
|
||||
const (
|
||||
// User set order types
|
||||
LimitOrder = iota
|
||||
MarketOrder = 1
|
||||
StopLossOrder = 2
|
||||
StopLossLimitOrder = 3
|
||||
TakeProfitOrder = 4
|
||||
TakeProfitLimitOrder = 5
|
||||
TWAPOrder = 6
|
||||
|
||||
// Internal order types
|
||||
TWAPSubOrder = 7
|
||||
LiquidationOrder = 8
|
||||
|
||||
ApiMaxOrderType = TWAPOrder
|
||||
)
|
||||
|
||||
// Order Time-In-Force
|
||||
const (
|
||||
ImmediateOrCancel = iota
|
||||
GoodTillTime = 1
|
||||
PostOnly = 2
|
||||
)
|
||||
|
||||
// Grouping Type
|
||||
const (
|
||||
GroupingType = 0
|
||||
GroupingType_OneTriggersTheOther = 1
|
||||
GroupingType_OneCancelsTheOther = 2
|
||||
GroupingType_OneTriggersAOneCancelsTheOther = 3
|
||||
)
|
||||
|
||||
// Cancel All Orders Time-In-Force
|
||||
const (
|
||||
ImmediateCancelAll = iota
|
||||
ScheduledCancelAll = 1
|
||||
AbortScheduledCancelAll = 2
|
||||
)
|
||||
|
||||
const (
|
||||
HashLength int = 32
|
||||
|
||||
OneUSDC = 1000000
|
||||
|
||||
FeeTick int64 = 1_000_000
|
||||
MarginFractionTick int64 = 10_000
|
||||
ShareTick int64 = 10_000
|
||||
|
||||
MinAccountIndex int64 = 0
|
||||
MaxAccountIndex int64 = 281474976710654 // (1 << 48) - 2
|
||||
MinApiKeyIndex uint8 = 0
|
||||
MaxApiKeyIndex uint8 = 254 // (1 << 8) - 2
|
||||
MaxMasterAccountIndex int64 = 140737488355327 // (1 << 47) - 1
|
||||
|
||||
MinMarketIndex uint8 = 0
|
||||
MaxMarketIndex uint8 = 254 // (1 << 8) - 2
|
||||
|
||||
MaxInvestedPublicPoolCount int64 = 16
|
||||
InitialPoolShareValue int64 = 1_000 // 0.001 USDC
|
||||
MinInitialTotalShares int64 = 1_000 * (OneUSDC / InitialPoolShareValue) // 1,000 USDC worth of shares
|
||||
MaxInitialTotalShares int64 = 1_000_000_000 * (OneUSDC / InitialPoolShareValue) // 1,000,000,000 USDC worth of shares
|
||||
MaxPoolShares int64 = (1 << 60) - 1
|
||||
MaxBurntShareUSDCValue int64 = (1 << 60) - 1
|
||||
|
||||
MaxPoolEntryUSDC = (1 << 56) - 1 // 2^56 - 1 max USDC to invest in a pool
|
||||
MinPoolSharesToMintOrBurn int64 = 1
|
||||
MaxPoolSharesToMintOrBurn int64 = (1 << 60) - 1
|
||||
|
||||
MinNonce int64 = 0
|
||||
|
||||
MinOrderNonce int64 = 0
|
||||
MaxOrderNonce int64 = (1 << 48) - 1
|
||||
|
||||
NilClientOrderIndex int64 = 0
|
||||
NilOrderIndex int64 = 0
|
||||
|
||||
MinClientOrderIndex int64 = 1
|
||||
MaxClientOrderIndex int64 = (1 << 48) - 1
|
||||
|
||||
MinOrderIndex int64 = MaxClientOrderIndex + 1
|
||||
MaxOrderIndex int64 = (1 << 56) - 1
|
||||
|
||||
MinOrderBaseAmount int64 = 1
|
||||
MaxOrderBaseAmount int64 = (1 << 48) - 1
|
||||
NilOrderBaseAmount int64 = 0
|
||||
|
||||
NilOrderPrice uint32 = 0
|
||||
MinOrderPrice uint32 = 1
|
||||
MaxOrderPrice uint32 = (1 << 32) - 1
|
||||
|
||||
MinOrderCancelAllPeriod int64 = 1000 * 60 * 5 // 5 minutes
|
||||
MaxOrderCancelAllPeriod int64 = 1000 * 60 * 60 * 24 * 15 // 15 days
|
||||
|
||||
NilOrderExpiry int64 = 0
|
||||
MinOrderExpiry int64 = 1
|
||||
MaxOrderExpiry int64 = math.MaxInt64
|
||||
|
||||
MinOrderExpiryPeriod int64 = 1000 * 60 * 5 // 5 minutes
|
||||
MaxOrderExpiryPeriod int64 = 1000 * 60 * 60 * 24 * 30 // 30 days
|
||||
|
||||
NilOrderTriggerPrice uint32 = 0
|
||||
MinOrderTriggerPrice uint32 = 1
|
||||
MaxOrderTriggerPrice uint32 = (1 << 32) - 1
|
||||
|
||||
MaxGroupedOrderCount int64 = 3
|
||||
|
||||
MaxTimestamp = (1 << 48) - 1
|
||||
)
|
||||
|
||||
const (
|
||||
MaxExchangeUSDC = (1 << 60) - 1
|
||||
|
||||
MinTransferAmount int64 = 1
|
||||
MaxTransferAmount int64 = MaxExchangeUSDC
|
||||
|
||||
MinWithdrawalAmount uint64 = 1
|
||||
MaxWithdrawalAmount uint64 = MaxExchangeUSDC
|
||||
)
|
||||
|
||||
// Margin Modes
|
||||
const (
|
||||
CrossMargin = iota
|
||||
IsolatedMargin = 1
|
||||
)
|
||||
|
||||
const (
|
||||
RemoveFromIsolatedMargin = 0
|
||||
AddToIsolatedMargin = 1
|
||||
)
|
||||
@@ -0,0 +1,336 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2CreateGroupedOrdersTxInfo)(nil)
|
||||
|
||||
// !!! Ensure that if primary order is reduce only, all child orders are also reduce only
|
||||
// !!! Otherwise CancelPositionTiedAccountOrders flow breaks
|
||||
type L2CreateGroupedOrdersTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
GroupingType uint8
|
||||
|
||||
Orders []*OrderInfo
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2CreateGroupedOrders
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrAccountIndexTooHigh
|
||||
}
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
if len(txInfo.Orders) == 0 || len(txInfo.Orders) > int(MaxGroupedOrderCount) {
|
||||
return ErrOrderGroupSizeInvalid
|
||||
}
|
||||
|
||||
// MarketIndex for first order
|
||||
if txInfo.Orders[0].MarketIndex < MinMarketIndex {
|
||||
return ErrMarketIndexTooLow
|
||||
}
|
||||
if txInfo.Orders[0].MarketIndex > MaxMarketIndex {
|
||||
return ErrMarketIndexTooHigh
|
||||
}
|
||||
|
||||
// Perform range checks for all orders
|
||||
for _, order := range txInfo.Orders {
|
||||
// MarketIndex
|
||||
if order.MarketIndex != txInfo.Orders[0].MarketIndex {
|
||||
return ErrMarketIndexMismatch
|
||||
}
|
||||
|
||||
// ClientOrderIndex
|
||||
if order.ClientOrderIndex != NilClientOrderIndex {
|
||||
return ErrClientOrderIndexNotNil
|
||||
}
|
||||
|
||||
// BaseAmount
|
||||
if order.ReduceOnly != 1 && order.BaseAmount == NilOrderBaseAmount {
|
||||
return ErrBaseAmountTooLow
|
||||
}
|
||||
if order.BaseAmount != NilOrderBaseAmount && order.BaseAmount < MinOrderBaseAmount {
|
||||
return ErrBaseAmountTooLow
|
||||
}
|
||||
if order.BaseAmount > MaxOrderBaseAmount {
|
||||
return ErrBaseAmountTooHigh
|
||||
}
|
||||
|
||||
// Price
|
||||
if order.Price < MinOrderPrice {
|
||||
return ErrPriceTooLow
|
||||
}
|
||||
if order.Price > MaxOrderPrice {
|
||||
return ErrPriceTooHigh
|
||||
}
|
||||
|
||||
// IsAsk
|
||||
if order.IsAsk != 0 && order.IsAsk != 1 {
|
||||
return ErrIsAskInvalid
|
||||
}
|
||||
|
||||
// TimeInForce
|
||||
if order.TimeInForce != ImmediateOrCancel && order.TimeInForce != GoodTillTime && order.TimeInForce != PostOnly {
|
||||
return ErrOrderTimeInForceInvalid
|
||||
}
|
||||
|
||||
// ReduceOnly
|
||||
if order.ReduceOnly != 0 && order.ReduceOnly != 1 {
|
||||
return ErrOrderReduceOnlyInvalid
|
||||
}
|
||||
|
||||
// OrderExpiry
|
||||
if (order.OrderExpiry < MinOrderExpiry || order.OrderExpiry > MaxOrderExpiry) && order.OrderExpiry != NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
|
||||
// TriggerPrice
|
||||
if (order.TriggerPrice < MinOrderTriggerPrice || order.TriggerPrice > MaxOrderTriggerPrice) && order.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
}
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
switch txInfo.GroupingType {
|
||||
case GroupingType_OneCancelsTheOther:
|
||||
return txInfo.ValidateOCO()
|
||||
case GroupingType_OneTriggersTheOther:
|
||||
return txInfo.ValidateOTO()
|
||||
case GroupingType_OneTriggersAOneCancelsTheOther:
|
||||
return txInfo.ValidateOTOCO()
|
||||
default:
|
||||
return ErrGroupingTypeInvalid
|
||||
}
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateParentOrder(order *OrderInfo) error {
|
||||
switch order.Type {
|
||||
case MarketOrder:
|
||||
if order.TimeInForce != ImmediateOrCancel {
|
||||
return ErrOrderTimeInForceInvalid
|
||||
} else if order.OrderExpiry != NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
} else if order.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
}
|
||||
case LimitOrder:
|
||||
if order.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
} else if order.TimeInForce == ImmediateOrCancel && order.OrderExpiry != NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
} else if order.TimeInForce != ImmediateOrCancel && order.OrderExpiry == NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
default:
|
||||
return ErrOrderTypeInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateChildOrder(order *OrderInfo) error {
|
||||
switch order.Type {
|
||||
case StopLossOrder, TakeProfitOrder:
|
||||
if order.TimeInForce != ImmediateOrCancel {
|
||||
return ErrOrderTimeInForceInvalid
|
||||
} else if order.TriggerPrice == NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
} else if order.OrderExpiry == NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
case StopLossLimitOrder, TakeProfitLimitOrder:
|
||||
if order.TriggerPrice == NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
} else if order.OrderExpiry == NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
default:
|
||||
return ErrOrderTypeInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateSiblingOrders(orders []*OrderInfo) error {
|
||||
if len(orders) != 2 {
|
||||
return ErrOrderGroupSizeInvalid
|
||||
}
|
||||
slFlag := false
|
||||
tpFlag := false
|
||||
for _, order := range orders {
|
||||
err := txInfo.ValidateChildOrder(order)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if order.Type == StopLossOrder || order.Type == StopLossLimitOrder {
|
||||
slFlag = true
|
||||
} else if order.Type == TakeProfitOrder || order.Type == TakeProfitLimitOrder {
|
||||
tpFlag = true
|
||||
}
|
||||
}
|
||||
if !slFlag || !tpFlag {
|
||||
return ErrOrderTypeInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateOCO() error {
|
||||
if len(txInfo.Orders) != 2 {
|
||||
return ErrOrderGroupSizeInvalid
|
||||
}
|
||||
|
||||
// Ensure both orders base sizes are same
|
||||
if txInfo.Orders[0].BaseAmount != txInfo.Orders[1].BaseAmount {
|
||||
return ErrBaseAmountsNotEqual
|
||||
}
|
||||
|
||||
// Orders should be in the same direction
|
||||
if txInfo.Orders[0].IsAsk != txInfo.Orders[1].IsAsk {
|
||||
return ErrIsAskInvalid
|
||||
}
|
||||
|
||||
// Ensure both orders are reduce only
|
||||
if txInfo.Orders[0].ReduceOnly != 1 || txInfo.Orders[1].ReduceOnly != 1 {
|
||||
return ErrOrderReduceOnlyInvalid
|
||||
}
|
||||
|
||||
// Ensure both orders have the same non-nil expiry
|
||||
if txInfo.Orders[0].OrderExpiry != txInfo.Orders[1].OrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
|
||||
return txInfo.ValidateSiblingOrders(txInfo.Orders)
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateOTO() error {
|
||||
if len(txInfo.Orders) != 2 {
|
||||
return ErrOrderGroupSizeInvalid
|
||||
}
|
||||
|
||||
// Ensure child order base size is 0
|
||||
if txInfo.Orders[1].BaseAmount != NilOrderBaseAmount {
|
||||
return ErrBaseAmountNotNil
|
||||
}
|
||||
|
||||
// Orders should be in the opposite direction
|
||||
if txInfo.Orders[0].IsAsk == txInfo.Orders[1].IsAsk {
|
||||
return ErrIsAskInvalid
|
||||
}
|
||||
|
||||
// Ensure if expiries are not nil, they are the same
|
||||
if txInfo.Orders[0].OrderExpiry != NilOrderExpiry &&
|
||||
txInfo.Orders[0].OrderExpiry != txInfo.Orders[1].OrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
|
||||
err := txInfo.ValidateParentOrder(txInfo.Orders[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return txInfo.ValidateChildOrder(txInfo.Orders[1])
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateOTOCO() error {
|
||||
if len(txInfo.Orders) != 3 {
|
||||
return ErrOrderGroupSizeInvalid
|
||||
}
|
||||
|
||||
// Ensure child orders base size is 0
|
||||
if txInfo.Orders[1].BaseAmount != NilOrderBaseAmount || txInfo.Orders[2].BaseAmount != NilOrderBaseAmount {
|
||||
return ErrBaseAmountNotNil
|
||||
}
|
||||
|
||||
// Primary and child orders should be in the oppsite direction
|
||||
if txInfo.Orders[0].IsAsk == txInfo.Orders[1].IsAsk || txInfo.Orders[0].IsAsk == txInfo.Orders[2].IsAsk {
|
||||
return ErrIsAskInvalid
|
||||
}
|
||||
|
||||
// Ensure child orders has the same expiry
|
||||
if txInfo.Orders[1].OrderExpiry != txInfo.Orders[2].OrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
|
||||
// Ensure if expiries are not nil, they are the same
|
||||
if txInfo.Orders[0].OrderExpiry != NilOrderExpiry &&
|
||||
txInfo.Orders[0].OrderExpiry != txInfo.Orders[1].OrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
|
||||
err := txInfo.ValidateParentOrder(txInfo.Orders[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return txInfo.ValidateSiblingOrders(txInfo.Orders[1:])
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 11)
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2CreateGroupedOrders))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.GroupingType)))
|
||||
|
||||
aggregatedOrderHash := p2.EmptyHashOut()
|
||||
for index, order := range txInfo.Orders {
|
||||
orderHash := p2.HashNoPad([]g.Element{
|
||||
g.FromUint32(uint32(order.MarketIndex)),
|
||||
g.FromInt64(order.ClientOrderIndex),
|
||||
g.FromInt64(order.BaseAmount),
|
||||
g.FromUint32(order.Price),
|
||||
g.FromUint32(uint32(order.IsAsk)),
|
||||
g.FromUint32(uint32(order.Type)),
|
||||
g.FromUint32(uint32(order.TimeInForce)),
|
||||
g.FromUint32(uint32(order.ReduceOnly)),
|
||||
g.FromUint32(order.TriggerPrice),
|
||||
g.FromInt64(order.OrderExpiry),
|
||||
})
|
||||
if index == 0 {
|
||||
aggregatedOrderHash = orderHash
|
||||
} else {
|
||||
aggregatedOrderHash = p2.HashNToOne([]p2.HashOut{aggregatedOrderHash, orderHash})
|
||||
}
|
||||
}
|
||||
elems = append(elems, aggregatedOrderHash[:]...)
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2CreateOrderTxInfo)(nil)
|
||||
|
||||
type L2CreateOrderTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
*OrderInfo
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateOrderTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2CreateOrder
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateOrderTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateOrderTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateOrderTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrAccountIndexTooHigh
|
||||
}
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// MarketIndex
|
||||
if txInfo.MarketIndex < MinMarketIndex {
|
||||
return ErrMarketIndexTooLow
|
||||
}
|
||||
if txInfo.MarketIndex > MaxMarketIndex {
|
||||
return ErrMarketIndexTooHigh
|
||||
}
|
||||
|
||||
// ClientOrderIndex
|
||||
if txInfo.ClientOrderIndex != NilClientOrderIndex {
|
||||
if txInfo.ClientOrderIndex < MinClientOrderIndex {
|
||||
return ErrClientOrderIndexTooLow
|
||||
}
|
||||
if txInfo.ClientOrderIndex > MaxClientOrderIndex {
|
||||
return ErrClientOrderIndexTooHigh
|
||||
}
|
||||
}
|
||||
|
||||
// BaseAmount
|
||||
if txInfo.ReduceOnly != 1 && txInfo.BaseAmount == NilOrderBaseAmount {
|
||||
return ErrBaseAmountTooLow
|
||||
}
|
||||
if txInfo.BaseAmount != NilOrderBaseAmount && txInfo.BaseAmount < MinOrderBaseAmount {
|
||||
return ErrBaseAmountTooLow
|
||||
}
|
||||
if txInfo.BaseAmount > MaxOrderBaseAmount {
|
||||
return ErrBaseAmountTooHigh
|
||||
}
|
||||
|
||||
// Price
|
||||
if txInfo.Price < MinOrderPrice {
|
||||
return ErrPriceTooLow
|
||||
}
|
||||
if txInfo.Price > MaxOrderPrice {
|
||||
return ErrPriceTooHigh
|
||||
}
|
||||
|
||||
// IsAsk
|
||||
if txInfo.IsAsk != 0 && txInfo.IsAsk != 1 {
|
||||
return ErrIsAskInvalid
|
||||
}
|
||||
|
||||
if txInfo.TimeInForce != ImmediateOrCancel && txInfo.TimeInForce != GoodTillTime && txInfo.TimeInForce != PostOnly {
|
||||
return ErrOrderTimeInForceInvalid
|
||||
}
|
||||
|
||||
if txInfo.ReduceOnly != 0 && txInfo.ReduceOnly != 1 {
|
||||
return ErrOrderReduceOnlyInvalid
|
||||
}
|
||||
|
||||
if (txInfo.OrderExpiry < MinOrderExpiry || txInfo.OrderExpiry > MaxOrderExpiry) && txInfo.OrderExpiry != NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
|
||||
switch txInfo.Type {
|
||||
case MarketOrder:
|
||||
if txInfo.TimeInForce != ImmediateOrCancel {
|
||||
return ErrOrderTimeInForceInvalid
|
||||
} else if txInfo.OrderExpiry != NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
} else if txInfo.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
}
|
||||
case LimitOrder:
|
||||
if txInfo.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
} else if txInfo.TimeInForce == ImmediateOrCancel && txInfo.OrderExpiry != NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
} else if txInfo.TimeInForce != ImmediateOrCancel && txInfo.OrderExpiry == NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
case StopLossOrder, TakeProfitOrder:
|
||||
if txInfo.TimeInForce != ImmediateOrCancel {
|
||||
return ErrOrderTimeInForceInvalid
|
||||
} else if txInfo.TriggerPrice == NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
} else if txInfo.OrderExpiry == NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
case StopLossLimitOrder, TakeProfitLimitOrder:
|
||||
if txInfo.TriggerPrice == NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
} else if txInfo.OrderExpiry == NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
case TWAPOrder:
|
||||
if txInfo.TimeInForce != GoodTillTime {
|
||||
return ErrOrderTimeInForceInvalid
|
||||
} else if txInfo.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
} else if txInfo.OrderExpiry == NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
default:
|
||||
return ErrOrderTypeInvalid
|
||||
}
|
||||
|
||||
// TriggerPrice
|
||||
if (txInfo.TriggerPrice < MinOrderTriggerPrice || txInfo.TriggerPrice > MaxOrderTriggerPrice) && txInfo.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateOrderTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 16)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2CreateOrder))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.MarketIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.ClientOrderIndex))
|
||||
elems = append(elems, g.FromInt64(txInfo.BaseAmount))
|
||||
elems = append(elems, g.FromUint32(txInfo.Price))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.IsAsk)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.Type)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.TimeInForce)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ReduceOnly)))
|
||||
elems = append(elems, g.FromUint32(txInfo.TriggerPrice))
|
||||
elems = append(elems, g.FromInt64(txInfo.OrderExpiry))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2CreatePublicPoolTxInfo)(nil)
|
||||
|
||||
type L2CreatePublicPoolTxInfo struct {
|
||||
AccountIndex int64 // Master account index
|
||||
ApiKeyIndex uint8
|
||||
|
||||
OperatorFee int64
|
||||
InitialTotalShares int64
|
||||
MinOperatorShareRate int64
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2CreatePublicPoolTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2CreatePublicPool
|
||||
}
|
||||
|
||||
func (txInfo *L2CreatePublicPoolTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2CreatePublicPoolTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2CreatePublicPoolTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxMasterAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// OperatorFee
|
||||
if txInfo.OperatorFee < 0 || txInfo.OperatorFee > FeeTick {
|
||||
return ErrInvalidPoolOperatorFee
|
||||
}
|
||||
|
||||
// InitialTotalShares
|
||||
if txInfo.InitialTotalShares <= 0 {
|
||||
return ErrPoolInitialTotalSharesTooLow
|
||||
}
|
||||
if txInfo.InitialTotalShares > MaxInitialTotalShares {
|
||||
return ErrPoolInitialTotalSharesTooHigh
|
||||
}
|
||||
|
||||
// MinOperatorShareRate
|
||||
if txInfo.MinOperatorShareRate < 0 {
|
||||
return ErrPoolMinOperatorShareRateTooLow
|
||||
}
|
||||
if txInfo.MinOperatorShareRate > ShareTick {
|
||||
return ErrPoolMinOperatorShareRateTooHigh
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CreatePublicPoolTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 9)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2CreatePublicPool))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.OperatorFee))
|
||||
elems = append(elems, g.FromInt64(txInfo.InitialTotalShares))
|
||||
elems = append(elems, g.FromInt64(txInfo.MinOperatorShareRate))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2CreateSubAccountTxInfo)(nil)
|
||||
|
||||
type L2CreateSubAccountTxInfo struct {
|
||||
AccountIndex int64 // Master account index
|
||||
ApiKeyIndex uint8
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateSubAccountTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2CreateSubAccount
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateSubAccountTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateSubAccountTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateSubAccountTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateSubAccountTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 6)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2CreateSubAccount))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package txtypes
|
||||
|
||||
import "fmt"
|
||||
|
||||
var (
|
||||
ErrAccountIndexTooLow = fmt.Errorf("AccountIndex should not be less than %d", MinAccountIndex)
|
||||
ErrAccountIndexTooHigh = fmt.Errorf("AccountIndex should not be larger than %d", MaxAccountIndex)
|
||||
ErrNonceTooLow = fmt.Errorf("AccountNonce should not be less than %d", MinNonce)
|
||||
ErrInvalidCancelAllTimeInForce = fmt.Errorf("CancelAllTimeInForce is invalid")
|
||||
ErrOrderReduceOnlyInvalid = fmt.Errorf("ReduceOnly is invalid")
|
||||
ErrOrderTriggerPriceInvalid = fmt.Errorf("TriggerPrice is invalid")
|
||||
ErrOrderExpiryInvalid = fmt.Errorf("OrderExpiry is invalid")
|
||||
ErrExpiredAtInvalid = fmt.Errorf("ExpiredAt is invalid")
|
||||
ErrCancelAllTimeIsNotInRange = fmt.Errorf("CancelAllTime should be larger than 0 and not larger than %d", MaxOrderExpiry)
|
||||
ErrCancelAllTimeisNotNill = fmt.Errorf("CancelAllTime should be nil")
|
||||
ErrPubKeyInvalid = fmt.Errorf("PubKey is invalid")
|
||||
ErrToAccountIndexTooLow = fmt.Errorf("ToAccountIndex should not be less than %d", MinAccountIndex)
|
||||
ErrToAccountIndexTooHigh = fmt.Errorf("ToAccountIndex should not be larger than %d", MaxAccountIndex)
|
||||
ErrFromAccountIndexTooLow = fmt.Errorf("FromAccountIndex should not be less than %d", MinAccountIndex)
|
||||
ErrFromAccountIndexTooHigh = fmt.Errorf("FromAccountIndex should not be larger than %d", MaxAccountIndex)
|
||||
ErrApiKeyIndexTooLow = fmt.Errorf("ApiKeyIndex should not be less than %d", MinApiKeyIndex)
|
||||
ErrApiKeyIndexTooHigh = fmt.Errorf("ApiKeyIndex should not be larger than %d", MaxApiKeyIndex)
|
||||
ErrPublicPoolIndexTooLow = fmt.Errorf("PublicPoolIndex should not be less than %d", MinAccountIndex)
|
||||
ErrPublicPoolIndexTooHigh = fmt.Errorf("PublicPoolIndex should not be larger than %d", MaxAccountIndex)
|
||||
ErrInvalidPoolOperatorFee = fmt.Errorf("PoolOperatorFee should be larger than 0 and not larger than %d", FeeTick)
|
||||
ErrInvalidPoolStatus = fmt.Errorf("PoolStatus should be either 0 or 1")
|
||||
ErrPoolInitialTotalSharesTooLow = fmt.Errorf("PoolInitialTotalShares should be larger than %d", MinInitialTotalShares)
|
||||
ErrPoolInitialTotalSharesTooHigh = fmt.Errorf("PoolInitialTotalShares should not be larger than %d", MaxInitialTotalShares)
|
||||
ErrPoolMinOperatorShareRateTooLow = fmt.Errorf("PoolMinOperatorShareRate should be larger than 0")
|
||||
ErrPoolMinOperatorShareRateTooHigh = fmt.Errorf("PoolMinOperatorShareRate should not be larger than %d", ShareTick)
|
||||
ErrPoolMintShareAmountTooLow = fmt.Errorf("PoolMintShareAmount should be larger than %d", MinPoolSharesToMintOrBurn)
|
||||
ErrPoolMintShareAmountTooHigh = fmt.Errorf("PoolMintShareAmount should not be larger than %d", MaxPoolSharesToMintOrBurn)
|
||||
ErrPoolBurnShareAmountTooLow = fmt.Errorf("PoolBurnShareAmount should be larger than %d", MinPoolSharesToMintOrBurn)
|
||||
ErrPoolBurnShareAmountTooHigh = fmt.Errorf("PoolBurnShareAmount should not be larger than %d", MaxPoolSharesToMintOrBurn)
|
||||
ErrWithdrawalAmountTooLow = fmt.Errorf("WithdrawalAmount should be larger than %d", MinWithdrawalAmount)
|
||||
ErrWithdrawalAmountTooHigh = fmt.Errorf("WithdrawalAmount should not be larger than %d", MaxWithdrawalAmount)
|
||||
ErrTransferAmountTooLow = fmt.Errorf("TransferAmount should be larger than %d", MinTransferAmount)
|
||||
ErrTransferAmountTooHigh = fmt.Errorf("TransferAmount should not be larger than %d", MaxTransferAmount)
|
||||
ErrMarketIndexTooLow = fmt.Errorf("MarketIndex should not be less than %d", MinMarketIndex)
|
||||
ErrMarketIndexTooHigh = fmt.Errorf("MarketIndex should not be larger than %d", MaxMarketIndex)
|
||||
ErrMarketIndexMismatch = fmt.Errorf("MarketIndex should match the market index of the order")
|
||||
ErrInitialMarginFractionTooLow = fmt.Errorf("InitialMarginFraction should not be less than %d", 0)
|
||||
ErrInitialMarginFractionTooHigh = fmt.Errorf("InitialMarginFraction should not be larger than %d", MarginFractionTick)
|
||||
ErrClientOrderIndexTooLow = fmt.Errorf("ClientOrderIndex should not be less than %d", MinClientOrderIndex)
|
||||
ErrClientOrderIndexTooHigh = fmt.Errorf("ClientOrderIndex should not be larger than %d", MaxClientOrderIndex)
|
||||
ErrClientOrderIndexNotNil = fmt.Errorf("ClientOrderIndex should be nil")
|
||||
ErrOrderIndexTooLow = fmt.Errorf("OrderIndex should not be less than %d", MinOrderIndex)
|
||||
ErrOrderIndexTooHigh = fmt.Errorf("OrderIndex should not be larger than %d", MaxOrderIndex)
|
||||
ErrBaseAmountTooLow = fmt.Errorf("BaseAmount should not be less than %d", MinOrderBaseAmount)
|
||||
ErrBaseAmountTooHigh = fmt.Errorf("BaseAmount should not be larger than %d", MaxOrderBaseAmount)
|
||||
ErrBaseAmountsNotEqual = fmt.Errorf("BaseAmounts should be equal")
|
||||
ErrBaseAmountNotNil = fmt.Errorf("BaseAmount should be nil")
|
||||
ErrPriceTooLow = fmt.Errorf("OrderPrice should not be less than %d", MinOrderPrice)
|
||||
ErrPriceTooHigh = fmt.Errorf("OrderPrice should not be larger than %d", MaxOrderPrice)
|
||||
ErrIsAskInvalid = fmt.Errorf("IsAsk should be 0 or 1")
|
||||
ErrOrderTypeInvalid = fmt.Errorf("OrderType is not valid")
|
||||
ErrOrderTimeInForceInvalid = fmt.Errorf("OrderTimeInForce is not valid")
|
||||
ErrGroupingTypeInvalid = fmt.Errorf("GroupingType is not valid")
|
||||
ErrOrderGroupSizeInvalid = fmt.Errorf("OrderGroupSize is not valid")
|
||||
ErrInvalidSignature = fmt.Errorf("TxSignature is invalid")
|
||||
ErrInvalidMarginMode = fmt.Errorf("MarginMode is not valid")
|
||||
ErrCancelModeInvalid = fmt.Errorf("CancelMode is not valid")
|
||||
ErrInvalidUpdateMarginDirection = fmt.Errorf("Margin movement direction is not valid")
|
||||
ErrTransferFeeNegative = fmt.Errorf("Transfer fee is negative")
|
||||
ErrTransferFeeTooHigh = fmt.Errorf("Transfer fee is higher than %d", MaxTransferAmount)
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
package txtypes
|
||||
|
||||
import g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
|
||||
type TxInfo interface {
|
||||
GetTxType() uint8
|
||||
|
||||
GetTxInfo() (string, error)
|
||||
|
||||
// GetTxHash returns the hash that was signed when creating this transaction.
|
||||
// The hash coincides with the TxHash received from Lighter after submitting this Tx.
|
||||
// It can be used to get the TxHash in advance, or to double-check the correctness of the SDK.
|
||||
// As this hash is signed by the ApiKey, if the value differs than the one computed by the server,
|
||||
// it'll result in an invalid signature.
|
||||
// Returns empty string if the Tx is not signed.
|
||||
GetTxHash() string
|
||||
|
||||
Validate() error
|
||||
|
||||
Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error)
|
||||
}
|
||||
|
||||
type OrderInfo struct {
|
||||
MarketIndex uint8
|
||||
|
||||
ClientOrderIndex int64
|
||||
|
||||
BaseAmount int64
|
||||
Price uint32
|
||||
IsAsk uint8
|
||||
|
||||
Type uint8
|
||||
TimeInForce uint8
|
||||
ReduceOnly uint8
|
||||
TriggerPrice uint32
|
||||
OrderExpiry int64
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2MintSharesTxInfo)(nil)
|
||||
|
||||
type L2MintSharesTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
PublicPoolIndex int64
|
||||
ShareAmount int64
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2MintSharesTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2MintShares
|
||||
}
|
||||
|
||||
func (txInfo *L2MintSharesTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2MintSharesTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2MintSharesTxInfo) Validate() error {
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// PublicPoolIndex
|
||||
if txInfo.PublicPoolIndex < MinAccountIndex {
|
||||
return ErrPublicPoolIndexTooLow
|
||||
}
|
||||
if txInfo.PublicPoolIndex > MaxAccountIndex {
|
||||
return ErrPublicPoolIndexTooHigh
|
||||
}
|
||||
|
||||
if txInfo.ShareAmount < MinPoolSharesToMintOrBurn {
|
||||
return ErrPoolMintShareAmountTooLow
|
||||
}
|
||||
if txInfo.ShareAmount > MaxPoolSharesToMintOrBurn {
|
||||
return ErrPoolMintShareAmountTooHigh
|
||||
}
|
||||
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2MintSharesTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 8)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2MintShares))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.PublicPoolIndex))
|
||||
elems = append(elems, g.FromInt64(txInfo.ShareAmount))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2ModifyOrderTxInfo)(nil)
|
||||
|
||||
type L2ModifyOrderTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
MarketIndex uint8
|
||||
Index int64 // Client Order Index or Order Index of the order to modify
|
||||
BaseAmount int64
|
||||
Price uint32
|
||||
TriggerPrice uint32
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2ModifyOrderTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2ModifyOrder
|
||||
}
|
||||
|
||||
func (txInfo *L2ModifyOrderTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2ModifyOrderTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2ModifyOrderTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrAccountIndexTooHigh
|
||||
}
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// MarketIndex
|
||||
if txInfo.MarketIndex < MinMarketIndex {
|
||||
return ErrMarketIndexTooLow
|
||||
}
|
||||
if txInfo.MarketIndex > MaxMarketIndex {
|
||||
return ErrMarketIndexTooHigh
|
||||
}
|
||||
|
||||
// Index
|
||||
if txInfo.Index < MinClientOrderIndex && txInfo.Index < MinOrderIndex {
|
||||
return ErrClientOrderIndexTooLow
|
||||
}
|
||||
if txInfo.Index > MaxClientOrderIndex && txInfo.Index > MaxOrderIndex {
|
||||
return ErrClientOrderIndexTooHigh
|
||||
}
|
||||
|
||||
// BaseAmount
|
||||
if txInfo.BaseAmount != NilOrderBaseAmount && txInfo.BaseAmount < MinOrderBaseAmount {
|
||||
return ErrBaseAmountTooLow
|
||||
}
|
||||
if txInfo.BaseAmount > MaxOrderBaseAmount {
|
||||
return ErrBaseAmountTooHigh
|
||||
}
|
||||
|
||||
// Price
|
||||
if txInfo.Price < MinOrderPrice {
|
||||
return ErrPriceTooLow
|
||||
}
|
||||
if txInfo.Price > MaxOrderPrice {
|
||||
return ErrPriceTooHigh
|
||||
}
|
||||
|
||||
// TriggerPrice
|
||||
if (txInfo.TriggerPrice < MinOrderTriggerPrice || txInfo.TriggerPrice > MaxOrderTriggerPrice) && txInfo.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2ModifyOrderTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 11)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2ModifyOrder))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.MarketIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.Index))
|
||||
elems = append(elems, g.FromInt64(txInfo.BaseAmount))
|
||||
elems = append(elems, g.FromUint32(txInfo.Price))
|
||||
elems = append(elems, g.FromUint32(txInfo.TriggerPrice))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
const templateTransfer = "Transfer\n\nnonce: %s\nfrom: %s\napi key: %s\nto: %s\namount: %s\nfee: %s\nmemo: %s\nOnly sign this message for a trusted client!"
|
||||
|
||||
var _ TxInfo = (*L2TransferTxInfo)(nil)
|
||||
|
||||
type L2TransferTxInfo struct {
|
||||
FromAccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
ToAccountIndex int64
|
||||
USDCAmount int64 // USDCAmount is given with 6 decimals
|
||||
Fee int64
|
||||
Memo [32]byte
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2TransferTxInfo) Validate() error {
|
||||
// plus one for treasury account
|
||||
if txInfo.FromAccountIndex < MinAccountIndex+1 {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.FromAccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
if txInfo.ToAccountIndex < MinAccountIndex+1 {
|
||||
return ErrToAccountIndexTooLow
|
||||
}
|
||||
if txInfo.ToAccountIndex > MaxAccountIndex {
|
||||
return ErrToAccountIndexTooHigh
|
||||
}
|
||||
|
||||
if txInfo.USDCAmount <= 0 {
|
||||
return ErrTransferAmountTooLow
|
||||
}
|
||||
if txInfo.USDCAmount > MaxTransferAmount {
|
||||
return ErrTransferAmountTooHigh
|
||||
}
|
||||
|
||||
if txInfo.Fee < 0 {
|
||||
return ErrTransferFeeNegative
|
||||
}
|
||||
if txInfo.Fee > MaxTransferAmount {
|
||||
return ErrTransferFeeTooHigh
|
||||
}
|
||||
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2TransferTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2Transfer
|
||||
}
|
||||
|
||||
func (txInfo *L2TransferTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2TransferTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2TransferTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 11)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2Transfer))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.FromAccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.ToAccountIndex))
|
||||
elems = append(elems, g.FromUint64(uint64(txInfo.USDCAmount)&0xFFFFFFFF)) //nolint:gosec
|
||||
elems = append(elems, g.FromUint64(uint64(txInfo.USDCAmount)>>32)) //nolint:gosec
|
||||
elems = append(elems, g.FromUint64(uint64(txInfo.Fee)&0xFFFFFFFF)) //nolint:gosec
|
||||
elems = append(elems, g.FromUint64(uint64(txInfo.Fee)>>32)) //nolint:gosec
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
|
||||
func (txInfo *L2TransferTxInfo) GetL1SignatureBody() string {
|
||||
hexMemo := hex.EncodeToString(txInfo.Memo[:])
|
||||
hexMemo = strings.Replace(hexMemo, "0x", "", 1)
|
||||
|
||||
signatureBody := fmt.Sprintf(
|
||||
templateTransfer,
|
||||
|
||||
getHex10FromUint64(uint64(txInfo.Nonce)),
|
||||
getHex10FromUint64(uint64(txInfo.FromAccountIndex)),
|
||||
getHex10FromUint64(uint64(txInfo.ApiKeyIndex)),
|
||||
getHex10FromUint64(uint64(txInfo.ToAccountIndex)),
|
||||
getHex10FromUint64(uint64(txInfo.USDCAmount)),
|
||||
getHex10FromUint64(uint64(txInfo.Fee)),
|
||||
hexMemo,
|
||||
)
|
||||
return signatureBody
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2UpdateLeverageTxInfo)(nil)
|
||||
|
||||
type L2UpdateLeverageTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
MarketIndex uint8
|
||||
InitialMarginFraction uint16
|
||||
MarginMode uint8
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateLeverageTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2UpdateLeverage
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateLeverageTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateLeverageTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateLeverageTxInfo) Validate() error {
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// MarketIndex
|
||||
if txInfo.MarketIndex < MinMarketIndex {
|
||||
return ErrMarketIndexTooLow
|
||||
}
|
||||
if txInfo.MarketIndex > MaxMarketIndex {
|
||||
return ErrMarketIndexTooHigh
|
||||
}
|
||||
|
||||
// InitialMarginFraction
|
||||
if txInfo.InitialMarginFraction <= 0 {
|
||||
return ErrInitialMarginFractionTooLow
|
||||
}
|
||||
if txInfo.InitialMarginFraction > uint16(MarginFractionTick) { //nolint:gosec
|
||||
return ErrInitialMarginFractionTooHigh
|
||||
}
|
||||
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
if txInfo.MarginMode != CrossMargin && txInfo.MarginMode != IsolatedMargin {
|
||||
return ErrInvalidMarginMode
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateLeverageTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 9)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2UpdateLeverage))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromInt64(int64(txInfo.MarketIndex)))
|
||||
elems = append(elems, g.FromInt64(int64(txInfo.InitialMarginFraction)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.MarginMode)))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2UpdateMarginTxInfo)(nil)
|
||||
|
||||
type L2UpdateMarginTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
MarketIndex uint8
|
||||
USDCAmount int64
|
||||
Direction uint8
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateMarginTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2UpdateMargin
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateMarginTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateMarginTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateMarginTxInfo) Validate() error {
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// MarketIndex
|
||||
if txInfo.MarketIndex < MinMarketIndex {
|
||||
return ErrMarketIndexTooLow
|
||||
}
|
||||
if txInfo.MarketIndex > MaxMarketIndex {
|
||||
return ErrMarketIndexTooHigh
|
||||
}
|
||||
|
||||
if txInfo.USDCAmount <= 0 {
|
||||
return ErrTransferAmountTooLow
|
||||
}
|
||||
if txInfo.USDCAmount > MaxTransferAmount {
|
||||
return ErrTransferAmountTooHigh
|
||||
}
|
||||
|
||||
if txInfo.Direction != RemoveFromIsolatedMargin && txInfo.Direction != AddToIsolatedMargin {
|
||||
return ErrInvalidUpdateMarginDirection
|
||||
}
|
||||
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateMarginTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 10)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2UpdateMargin))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromInt64(int64(txInfo.MarketIndex)))
|
||||
elems = append(elems, g.FromUint64(uint64(txInfo.USDCAmount)&0xFFFFFFFF)) //nolint:gosec
|
||||
elems = append(elems, g.FromUint64(uint64(txInfo.USDCAmount)>>32)) //nolint:gosec
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.Direction)))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2UpdatePublicPoolTxInfo)(nil)
|
||||
|
||||
type L2UpdatePublicPoolTxInfo struct {
|
||||
AccountIndex int64 // Master account index
|
||||
ApiKeyIndex uint8
|
||||
|
||||
PublicPoolIndex int64
|
||||
|
||||
Status uint8
|
||||
OperatorFee int64
|
||||
MinOperatorShareRate int64
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdatePublicPoolTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2UpdatePublicPool
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdatePublicPoolTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdatePublicPoolTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdatePublicPoolTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// PublicPoolIndex
|
||||
if txInfo.PublicPoolIndex < MinAccountIndex {
|
||||
return ErrPublicPoolIndexTooLow
|
||||
}
|
||||
if txInfo.PublicPoolIndex > MaxAccountIndex {
|
||||
return ErrPublicPoolIndexTooHigh
|
||||
}
|
||||
|
||||
// Status
|
||||
if txInfo.Status != 0 && txInfo.Status != 1 {
|
||||
return ErrInvalidPoolStatus
|
||||
}
|
||||
|
||||
// OperatorFee
|
||||
if txInfo.OperatorFee < 0 || txInfo.OperatorFee > FeeTick {
|
||||
return ErrInvalidPoolOperatorFee
|
||||
}
|
||||
|
||||
// MinOperatorShareRate
|
||||
if txInfo.MinOperatorShareRate < 0 {
|
||||
return ErrPoolMinOperatorShareRateTooLow
|
||||
}
|
||||
if txInfo.MinOperatorShareRate > ShareTick {
|
||||
return ErrPoolMinOperatorShareRateTooHigh
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdatePublicPoolTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 10)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2UpdatePublicPool))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.PublicPoolIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.Status)))
|
||||
elems = append(elems, g.FromInt64(txInfo.OperatorFee))
|
||||
elems = append(elems, g.FromInt64(txInfo.MinOperatorShareRate))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package txtypes
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
func IsValidPubKey(bytes []byte) bool {
|
||||
if len(bytes) != 40 {
|
||||
return false
|
||||
}
|
||||
|
||||
return !isZeroByteSlice(bytes)
|
||||
}
|
||||
|
||||
func isZeroByteSlice(bytes []byte) bool {
|
||||
for _, s := range bytes {
|
||||
if s != 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func getTxInfo(tx interface{}) (string, error) {
|
||||
txInfoBytes, err := json.Marshal(tx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(txInfoBytes), nil
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2WithdrawTxInfo)(nil)
|
||||
|
||||
type L2WithdrawTxInfo struct {
|
||||
FromAccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
USDCAmount uint64 // USDCAmount is given with 6 decimals
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2WithdrawTxInfo) Validate() error {
|
||||
if txInfo.FromAccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.FromAccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
if txInfo.USDCAmount == 0 {
|
||||
return ErrWithdrawalAmountTooLow
|
||||
}
|
||||
if txInfo.USDCAmount > MaxWithdrawalAmount {
|
||||
return ErrWithdrawalAmountTooHigh
|
||||
}
|
||||
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2WithdrawTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2Withdraw
|
||||
}
|
||||
|
||||
func (txInfo *L2WithdrawTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2WithdrawTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2WithdrawTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 8)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2Withdraw))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.FromAccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromUint64(uint64(txInfo.USDCAmount)&0xFFFFFFFF)) //nolint:gosec
|
||||
elems = append(elems, g.FromUint64(uint64(txInfo.USDCAmount)>>32)) //nolint:gosec
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,31 @@
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
pull_request: {}
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
unit:
|
||||
name: Unit tests
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: ['1.22.x', '1.23.x']
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
|
||||
- name: Setup Go ${{ matrix.go-version }}
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ${{ matrix.go-version }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
go get ./...
|
||||
|
||||
- name: Run tests
|
||||
run: go test ./...
|
||||
@@ -0,0 +1,25 @@
|
||||
# If you prefer the allow list template instead of the deny list, see community template:
|
||||
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
||||
#
|
||||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
# Dependency directories (remove the comment below to include it)
|
||||
vendor/
|
||||
|
||||
# Go workspace file
|
||||
go.work
|
||||
go.work.sum
|
||||
|
||||
# env file
|
||||
.env
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1 @@
|
||||
Poseidon & Poseidon2 hash implementations
|
||||
@@ -0,0 +1,83 @@
|
||||
package ecgfp5
|
||||
|
||||
import (
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
)
|
||||
|
||||
// A curve point in affine (x,u) coordinates. This is used internally
|
||||
// to make "windows" that speed up point multiplications.
|
||||
type AffinePoint struct {
|
||||
x, u gFp5.Element
|
||||
}
|
||||
|
||||
var AFFINE_NEUTRAL = AffinePoint{
|
||||
x: gFp5.FP5_ZERO,
|
||||
u: gFp5.FP5_ZERO,
|
||||
}
|
||||
|
||||
func (p AffinePoint) ToPoint() ECgFp5Point {
|
||||
return ECgFp5Point{
|
||||
x: p.x,
|
||||
z: gFp5.FP5_ONE,
|
||||
u: p.u,
|
||||
t: gFp5.FP5_ONE,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *AffinePoint) SetNeg() {
|
||||
p.u = gFp5.Neg(p.u)
|
||||
}
|
||||
|
||||
// Lookup a point in a window. The win[] slice must contain values
|
||||
// i*P for i = 1 to n (win[0] contains P, win[1] contains 2*P, and
|
||||
// so on). Index value k is an integer in the -n to n range; returned
|
||||
// point is k*P.
|
||||
func (p *AffinePoint) SetLookup(win []AffinePoint, k int32) {
|
||||
// sign = 0xFFFFFFFF if k < 0, 0x00000000 otherwise
|
||||
sign := uint32(k >> 31)
|
||||
// ka = abs(k)
|
||||
ka := (uint32(k) ^ sign) - sign
|
||||
// km1 = ka - 1
|
||||
km1 := ka - 1
|
||||
|
||||
x := gFp5.FP5_ZERO
|
||||
u := gFp5.FP5_ZERO
|
||||
for i := 0; i < len(win); i++ {
|
||||
m := km1 - uint32(i)
|
||||
c_1 := (m | (^m + 1)) >> 31
|
||||
c := uint64(c_1) - 1
|
||||
if c != 0 {
|
||||
x = win[i].x
|
||||
u = win[i].u
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// If k < 0, then we must negate the point.
|
||||
c := uint64(sign) | (uint64(sign) << 32)
|
||||
p.x = x
|
||||
p.u = u
|
||||
|
||||
if c != 0 {
|
||||
p.u = gFp5.Neg(p.u)
|
||||
}
|
||||
}
|
||||
|
||||
func Lookup(win []AffinePoint, k int32) AffinePoint {
|
||||
r := AFFINE_NEUTRAL
|
||||
r.SetLookup(win, k)
|
||||
return r
|
||||
}
|
||||
|
||||
// Same as lookup(), except this implementation is variable-time.
|
||||
func LookupVarTime(win []AffinePoint, k int32) AffinePoint {
|
||||
if k == 0 {
|
||||
return AFFINE_NEUTRAL
|
||||
} else if k > 0 {
|
||||
return win[k-1]
|
||||
} else {
|
||||
res := win[-k-1]
|
||||
res.SetNeg()
|
||||
return res
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,441 @@
|
||||
package ecgfp5
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
)
|
||||
|
||||
// A curve point.
|
||||
type ECgFp5Point struct {
|
||||
// Internally, we use the (x,u) fractional coordinates: for curve
|
||||
// point (x,y), we have (x,u) = (x,x/y) = (X/Z,U/T) (for the neutral
|
||||
// N, the u coordinate is 0).
|
||||
x, z, u, t gFp5.Element
|
||||
}
|
||||
|
||||
// Constants for ECgFp5Point
|
||||
var (
|
||||
A_ECgFp5Point = gFp5.FromUint64Array([5]uint64{2, 0, 0, 0, 0})
|
||||
|
||||
B1 = uint64(263)
|
||||
B_ECgFp5Point = gFp5.FromUint64Array([5]uint64{0, B1, 0, 0, 0})
|
||||
B_MUL2_ECgFp5Point = gFp5.FromUint64Array([5]uint64{0, 2 * B1, 0, 0, 0})
|
||||
B_MUL4_ECgFp5Point = gFp5.FromUint64Array([5]uint64{0, 4 * B1, 0, 0, 0})
|
||||
B_MUL16_ECgFp5Point = gFp5.FromUint64Array([5]uint64{0, 16 * B1, 0, 0, 0})
|
||||
|
||||
NEUTRAL_ECgFp5Point = ECgFp5Point{
|
||||
x: gFp5.FP5_ZERO,
|
||||
z: gFp5.FP5_ONE,
|
||||
u: gFp5.FP5_ZERO,
|
||||
t: gFp5.FP5_ONE,
|
||||
}
|
||||
|
||||
GENERATOR_ECgFp5Point = ECgFp5Point{
|
||||
x: gFp5.FromUint64Array([5]uint64{
|
||||
12883135586176881569,
|
||||
4356519642755055268,
|
||||
5248930565894896907,
|
||||
2165973894480315022,
|
||||
2448410071095648785,
|
||||
},
|
||||
),
|
||||
z: gFp5.FP5_ONE,
|
||||
u: gFp5.FP5_ONE,
|
||||
t: gFp5.FromUint64Array([5]uint64{4, 0, 0, 0, 0}),
|
||||
}
|
||||
)
|
||||
|
||||
func (p ECgFp5Point) Equals(rhs ECgFp5Point) bool {
|
||||
return gFp5.Equals(
|
||||
gFp5.Mul(p.u, rhs.t),
|
||||
gFp5.Mul(rhs.u, p.t),
|
||||
)
|
||||
}
|
||||
|
||||
func CanBeDecodedIntoPoint(w gFp5.Element) bool {
|
||||
// Value w can be decoded if and only if it is zero, or
|
||||
// (w^2 - a)^2 - 4*b is a quadratic residue.
|
||||
e := gFp5.Sub(gFp5.Square(w), A_ECgFp5Point)
|
||||
delta := gFp5.Sub(gFp5.Square(e), B_MUL4_ECgFp5Point)
|
||||
deltaLegendre := gFp5.Legendre(delta)
|
||||
return gFp5.IsZero(w) || deltaLegendre.IsOne()
|
||||
}
|
||||
|
||||
func (p ECgFp5Point) Encode() gFp5.Element {
|
||||
return gFp5.Mul(p.t, gFp5.InverseOrZero(p.u))
|
||||
}
|
||||
|
||||
// Attempt to decode a point from an gFp5 element
|
||||
func Decode(w gFp5.Element) (ECgFp5Point, bool) {
|
||||
// Curve equation is y^2 = x*(x^2 + a*x + b); encoded value
|
||||
// is w = y/x. Dividing by x, we get the equation:
|
||||
// x^2 - (w^2 - a)*x + b = 0
|
||||
// We solve for x and keep the solution which is not itself a
|
||||
// square (if there are solutions, exactly one of them will be
|
||||
// a square, and the other will not be a square).
|
||||
|
||||
e := gFp5.Sub(gFp5.Square(w), A_ECgFp5Point)
|
||||
delta := gFp5.Sub(gFp5.Square(e), B_MUL4_ECgFp5Point)
|
||||
r, c := gFp5.CanonicalSqrt(delta)
|
||||
if !c {
|
||||
r = gFp5.FP5_ZERO
|
||||
}
|
||||
|
||||
x1 := gFp5.Div(gFp5.Add(e, r), gFp5.FP5_TWO)
|
||||
x2 := gFp5.Div(gFp5.Sub(e, r), gFp5.FP5_TWO)
|
||||
x := x2
|
||||
|
||||
x1Legendre := gFp5.Legendre(x1)
|
||||
one := g.One()
|
||||
if !one.Equal(&x1Legendre) {
|
||||
x = x1
|
||||
}
|
||||
|
||||
// If c == true (delta is not a sqrt) then we want to get the neutral here; note that if
|
||||
// w == 0, then delta = a^2 - 4*b, which is not a square, and
|
||||
// thus we also get c == 0.
|
||||
if !c {
|
||||
x = gFp5.FP5_ZERO
|
||||
}
|
||||
z := gFp5.FP5_ONE
|
||||
u := gFp5.FP5_ONE
|
||||
if !c {
|
||||
u = gFp5.FP5_ZERO
|
||||
}
|
||||
t := w
|
||||
if !c {
|
||||
t = gFp5.FP5_ONE
|
||||
}
|
||||
|
||||
// If w == 0 then this is in fact a success.
|
||||
if c || gFp5.IsZero(w) {
|
||||
return ECgFp5Point{x: x, z: z, u: u, t: t}, true
|
||||
}
|
||||
|
||||
return ECgFp5Point{}, false
|
||||
}
|
||||
|
||||
func (p ECgFp5Point) IsNeutral() bool {
|
||||
return gFp5.IsZero(p.u)
|
||||
}
|
||||
|
||||
// General point addition. formulas are complete (no special case).
|
||||
func (p ECgFp5Point) Add(rhs ECgFp5Point) ECgFp5Point {
|
||||
// cost: 10M
|
||||
|
||||
x1 := p.x
|
||||
z1 := p.z
|
||||
u1 := p.u
|
||||
_t1 := p.t
|
||||
|
||||
x2 := rhs.x
|
||||
z2 := rhs.z
|
||||
u2 := rhs.u
|
||||
_t2 := rhs.t
|
||||
|
||||
// let t1 = x1 * x2;
|
||||
t1 := gFp5.Mul(x1, x2)
|
||||
// let t2 = z1 * z2;
|
||||
t2 := gFp5.Mul(z1, z2)
|
||||
// let t3 = u1 * u2;
|
||||
t3 := gFp5.Mul(u1, u2)
|
||||
// let t4 = _t1 * _t2;
|
||||
t4 := gFp5.Mul(_t1, _t2)
|
||||
// let t5 = (x1 + z1) * (x2 + z2) - t1 - t2;
|
||||
t5 := gFp5.Sub(
|
||||
gFp5.Mul(gFp5.Add(x1, z1), gFp5.Add(x2, z2)),
|
||||
gFp5.Add(t1, t2),
|
||||
)
|
||||
// let t6 = (u1 + _t1) * (u2 + _t2) - t3 - t4;
|
||||
t6 := gFp5.Sub(
|
||||
gFp5.Mul(gFp5.Add(u1, _t1), gFp5.Add(u2, _t2)),
|
||||
gFp5.Add(t3, t4),
|
||||
)
|
||||
// let t7 = t1 + t2 * Self::B;
|
||||
t7 := gFp5.Add(t1, gFp5.Mul(t2, B_ECgFp5Point))
|
||||
// let t8 = t4 * t7;
|
||||
t8 := gFp5.Mul(t4, t7)
|
||||
// let t9 = t3 * (t5 * Self::B_MUL2 + t7.double());
|
||||
t9 := gFp5.Mul(
|
||||
t3,
|
||||
gFp5.Add(gFp5.Mul(t5, B_MUL2_ECgFp5Point), gFp5.Double(t7)),
|
||||
)
|
||||
// let t10 = (t4 + t3.double()) * (t5 + t7);
|
||||
t10 := gFp5.Mul(
|
||||
gFp5.Add(t4, gFp5.Double(t3)),
|
||||
gFp5.Add(t5, t7),
|
||||
)
|
||||
|
||||
xNew := gFp5.Mul(gFp5.Sub(t10, t8), B_ECgFp5Point)
|
||||
zNew := gFp5.Sub(t8, t9)
|
||||
uNew := gFp5.Mul(t6, gFp5.Sub(gFp5.Mul(t2, B_ECgFp5Point), t1))
|
||||
tNew := gFp5.Add(t8, t9)
|
||||
|
||||
return ECgFp5Point{x: xNew, z: zNew, u: uNew, t: tNew}
|
||||
}
|
||||
|
||||
func (p ECgFp5Point) Double() ECgFp5Point {
|
||||
newPoint := p
|
||||
newPoint.SetDouble()
|
||||
return newPoint
|
||||
}
|
||||
|
||||
func (p *ECgFp5Point) SetDouble() {
|
||||
// cost: 4M+5S
|
||||
x := p.x
|
||||
z := p.z
|
||||
u := p.u
|
||||
t := p.t
|
||||
|
||||
t1 := gFp5.Mul(z, t)
|
||||
t2 := gFp5.Mul(t1, t)
|
||||
x1 := gFp5.Square(t2)
|
||||
z1 := gFp5.Mul(t1, u)
|
||||
t3 := gFp5.Square(u)
|
||||
w1 := gFp5.Sub(
|
||||
t2,
|
||||
gFp5.Mul(
|
||||
t3,
|
||||
gFp5.Double(gFp5.Add(x, z)),
|
||||
),
|
||||
)
|
||||
t4 := gFp5.Square(z1)
|
||||
|
||||
xNew := gFp5.Mul(t4, B_MUL4_ECgFp5Point)
|
||||
zNew := gFp5.Square(w1)
|
||||
uNew := gFp5.Sub(
|
||||
gFp5.Square(gFp5.Add(w1, z1)),
|
||||
gFp5.Add(t4, zNew),
|
||||
)
|
||||
tNew := gFp5.Sub(
|
||||
gFp5.Double(x1),
|
||||
gFp5.Add(
|
||||
gFp5.Mul(t4, gFp5.FromUint64Array([5]uint64{4, 0, 0, 0, 0})),
|
||||
zNew,
|
||||
),
|
||||
)
|
||||
|
||||
p.x = xNew
|
||||
p.z = zNew
|
||||
p.u = uNew
|
||||
p.t = tNew
|
||||
}
|
||||
|
||||
func (p *ECgFp5Point) MDouble(n uint32) ECgFp5Point {
|
||||
newPoint := ECgFp5Point{x: p.x, z: p.z, u: p.u, t: p.t}
|
||||
newPoint.SetMDouble(n)
|
||||
return newPoint
|
||||
}
|
||||
|
||||
func (p *ECgFp5Point) SetMDouble(n uint32) {
|
||||
if n == 0 {
|
||||
return
|
||||
}
|
||||
if n == 1 {
|
||||
p.SetDouble()
|
||||
return
|
||||
}
|
||||
|
||||
// cost: n*(2M+5S) + 2M+1S
|
||||
x0 := p.x
|
||||
z0 := p.z
|
||||
u0 := p.u
|
||||
t0 := p.t
|
||||
|
||||
t1 := gFp5.Mul(z0, t0)
|
||||
t2 := gFp5.Mul(t1, t0)
|
||||
x1 := gFp5.Square(t2)
|
||||
z1 := gFp5.Mul(t1, u0)
|
||||
t3 := gFp5.Square(u0)
|
||||
w1 := gFp5.Sub(
|
||||
t2,
|
||||
gFp5.Mul(
|
||||
gFp5.Double(gFp5.Add(x0, z0)),
|
||||
t3,
|
||||
),
|
||||
)
|
||||
t4 := gFp5.Square(w1)
|
||||
t5 := gFp5.Square(z1)
|
||||
x := gFp5.Mul(gFp5.Square(t5), B_MUL16_ECgFp5Point)
|
||||
w := gFp5.Sub(
|
||||
gFp5.Double(x1),
|
||||
gFp5.Add(
|
||||
gFp5.Mul(t5, gFp5.FromUint64Array([5]uint64{4, 0, 0, 0, 0})),
|
||||
t4,
|
||||
),
|
||||
)
|
||||
z := gFp5.Sub(
|
||||
gFp5.Square(gFp5.Add(w1, z1)),
|
||||
gFp5.Add(t4, t5),
|
||||
)
|
||||
|
||||
for i := 2; i < int(n); i++ {
|
||||
t1 = gFp5.Square(z)
|
||||
t2 = gFp5.Square(t1)
|
||||
t3 = gFp5.Square(w)
|
||||
t4 = gFp5.Square(t3)
|
||||
t5 = gFp5.Sub(
|
||||
gFp5.Square(gFp5.Add(w, z)),
|
||||
gFp5.Add(t1, t3),
|
||||
)
|
||||
z = gFp5.Mul(
|
||||
t5,
|
||||
gFp5.Sub(
|
||||
gFp5.Double(gFp5.Add(x, t1)),
|
||||
t3,
|
||||
),
|
||||
)
|
||||
x = gFp5.Mul(gFp5.Mul(t2, t4), B_MUL16_ECgFp5Point)
|
||||
w = gFp5.Neg(
|
||||
gFp5.Add(
|
||||
t4,
|
||||
gFp5.Mul(
|
||||
t2,
|
||||
gFp5.Sub(
|
||||
B_MUL4_ECgFp5Point,
|
||||
gFp5.FromUint64Array([5]uint64{4, 0, 0, 0, 0}),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
t1 = gFp5.Square(w)
|
||||
t2 = gFp5.Square(z)
|
||||
t3 = gFp5.Sub(
|
||||
gFp5.Square(gFp5.Add(w, z)),
|
||||
gFp5.Add(t1, t2),
|
||||
)
|
||||
w1 = gFp5.Sub(
|
||||
t1,
|
||||
gFp5.Double(gFp5.Add(x, t2)),
|
||||
)
|
||||
|
||||
p.x = gFp5.Mul(gFp5.Square(t3), B_ECgFp5Point)
|
||||
p.z = gFp5.Square(w1)
|
||||
p.u = gFp5.Mul(t3, w1)
|
||||
p.t = gFp5.Sub(
|
||||
gFp5.Mul(
|
||||
gFp5.Double(t1),
|
||||
gFp5.Sub(t1, gFp5.Double(t2)),
|
||||
),
|
||||
p.z,
|
||||
)
|
||||
}
|
||||
|
||||
// Add a point in affine coordinates to this one.
|
||||
func (p ECgFp5Point) AddAffine(rhs AffinePoint) ECgFp5Point {
|
||||
// cost: 8M
|
||||
x1, z1, u1, _t1 := p.x, p.z, p.u, p.t
|
||||
x2, u2 := rhs.x, rhs.u
|
||||
|
||||
t1 := gFp5.Mul(x1, x2)
|
||||
t2 := z1
|
||||
t3 := gFp5.Mul(u1, u2)
|
||||
t4 := _t1
|
||||
t5 := gFp5.Add(x1, gFp5.Mul(x2, z1))
|
||||
t6 := gFp5.Add(u1, gFp5.Mul(u2, _t1))
|
||||
t7 := gFp5.Add(t1, gFp5.Mul(t2, B_ECgFp5Point))
|
||||
t8 := gFp5.Mul(t4, t7)
|
||||
t9 := gFp5.Mul(t3, gFp5.Add(gFp5.Mul(t5, B_MUL2_ECgFp5Point), gFp5.Double(t7)))
|
||||
t10 := gFp5.Mul(gFp5.Add(t4, gFp5.Double(t3)), gFp5.Add(t5, t7))
|
||||
|
||||
return ECgFp5Point{
|
||||
x: gFp5.Mul(gFp5.Sub(t10, t8), B_ECgFp5Point),
|
||||
u: gFp5.Mul(t6, gFp5.Sub(gFp5.Mul(t2, B_ECgFp5Point), t1)),
|
||||
z: gFp5.Sub(t8, t9),
|
||||
t: gFp5.Add(t8, t9),
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
WINDOW = 5
|
||||
WIN_SIZE = 1 << (WINDOW - 1)
|
||||
)
|
||||
|
||||
// Convert points to affine coordinates.
|
||||
func BatchToAffine(src []ECgFp5Point) []AffinePoint {
|
||||
// We use a trick due to Montgomery: to compute the inverse of
|
||||
// x and of y, a single inversion suffices, with:
|
||||
// 1/x = y*(1/(x*y))
|
||||
// 1/y = x*(1/(x*y))
|
||||
// This extends to the case of inverting n values, with a total
|
||||
// cost of 1 inversion and 3*(n-1) multiplications.
|
||||
n := len(src)
|
||||
if n == 0 {
|
||||
return []AffinePoint{}
|
||||
}
|
||||
if n == 1 {
|
||||
p := src[0]
|
||||
m1 := gFp5.InverseOrZero(gFp5.Mul(p.z, p.t))
|
||||
return []AffinePoint{
|
||||
{
|
||||
x: gFp5.Mul(gFp5.Mul(p.x, p.t), m1),
|
||||
u: gFp5.Mul(gFp5.Mul(p.u, p.z), m1),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
res := make([]AffinePoint, n)
|
||||
// Compute product of all values to invert, and invert it.
|
||||
// We also use the x and u coordinates of the points in the
|
||||
// destination slice to keep track of the partial products.
|
||||
m := gFp5.Mul(src[0].z, src[0].t)
|
||||
for i := 1; i < n; i++ {
|
||||
x := m
|
||||
m = gFp5.Mul(m, src[i].z)
|
||||
u := m
|
||||
m = gFp5.Mul(m, src[i].t)
|
||||
|
||||
res[i] = AffinePoint{x: x, u: u}
|
||||
}
|
||||
|
||||
m = gFp5.InverseOrZero(m)
|
||||
|
||||
// Propagate back inverses.
|
||||
for i := n - 1; i > 0; i-- {
|
||||
res[i].u = gFp5.Mul(gFp5.Mul(src[i].u, res[i].u), m)
|
||||
m = gFp5.Mul(m, src[i].t)
|
||||
res[i].x = gFp5.Mul(gFp5.Mul(src[i].x, res[i].x), m)
|
||||
m = gFp5.Mul(m, src[i].z)
|
||||
}
|
||||
res[0].u = gFp5.Mul(gFp5.Mul(src[0].u, src[0].z), m)
|
||||
m = gFp5.Mul(m, src[0].t)
|
||||
res[0].x = gFp5.Mul(src[0].x, m)
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
func (p ECgFp5Point) MakeWindowAffine() []AffinePoint {
|
||||
tmp := make([]ECgFp5Point, WIN_SIZE)
|
||||
tmp[0] = p
|
||||
for i := 1; i < WIN_SIZE; i++ {
|
||||
if (i & 1) == 0 {
|
||||
tmp[i] = tmp[i-1].Add(p)
|
||||
} else {
|
||||
tmp[i] = tmp[i>>1].Double()
|
||||
}
|
||||
}
|
||||
return BatchToAffine(tmp)
|
||||
}
|
||||
|
||||
// Multiply this point by a scalar.
|
||||
func (p *ECgFp5Point) SetMul(s *ECgFp5Scalar) {
|
||||
// Make a window with affine points.
|
||||
win := p.MakeWindowAffine()
|
||||
digits := make([]int32, (319+WINDOW)/WINDOW)
|
||||
s.RecodeSigned(digits, int32(WINDOW))
|
||||
|
||||
*p = LookupVarTime(win, digits[len(digits)-1]).ToPoint()
|
||||
for i := len(digits) - 2; i >= 0; i-- {
|
||||
p.SetMDouble(uint32(WINDOW))
|
||||
lookup := Lookup(win, digits[i])
|
||||
*p = p.AddAffine(lookup)
|
||||
}
|
||||
}
|
||||
|
||||
func (p ECgFp5Point) Mul(s *ECgFp5Scalar) ECgFp5Point {
|
||||
newPoint := p
|
||||
newPoint.SetMul(s)
|
||||
return newPoint
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
package ecgfp5
|
||||
|
||||
import (
|
||||
cryptorand "crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"math/big"
|
||||
"math/rand"
|
||||
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
)
|
||||
|
||||
// ECgFp5Scalar represents the scalar field of the ECgFP5 elliptic curve where
|
||||
// p = 1067993516717146951041484916571792702745057740581727230159139685185762082554198619328292418486241
|
||||
type ECgFp5Scalar [5]uint64
|
||||
|
||||
func (s *ECgFp5Scalar) DeepCopy() ECgFp5Scalar {
|
||||
return ECgFp5Scalar{s[0], s[1], s[2], s[3], s[4]}
|
||||
}
|
||||
|
||||
func (s ECgFp5Scalar) ToLittleEndianBytes() []byte {
|
||||
var result [40]byte
|
||||
for i := 0; i < 5; i++ {
|
||||
binary.LittleEndian.PutUint64(result[i*8:], s[i])
|
||||
}
|
||||
return result[:]
|
||||
}
|
||||
|
||||
func ScalarElementFromLittleEndianBytes(data []byte) ECgFp5Scalar {
|
||||
if len(data) != 40 {
|
||||
panic("invalid length")
|
||||
}
|
||||
|
||||
var value ECgFp5Scalar
|
||||
for i := 0; i < 5; i++ {
|
||||
value[i] = binary.LittleEndian.Uint64(data[i*8:])
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func (s ECgFp5Scalar) SplitTo4BitLimbs() [80]uint8 {
|
||||
limbs := s[:]
|
||||
var result [80]uint8
|
||||
for i := 0; i < 5; i++ {
|
||||
for j := 0; j < 16; j++ {
|
||||
result[i*16+j] = uint8((limbs[i] >> uint(j*4)) & 0xF)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func SampleScalarCrypto() ECgFp5Scalar {
|
||||
rng, err := cryptorand.Int(cryptorand.Reader, ORDER)
|
||||
if err != nil {
|
||||
panic("failed to read random bytes into buffer")
|
||||
}
|
||||
return FromNonCanonicalBigInt(rng)
|
||||
}
|
||||
|
||||
func SampleScalar(seed *string) ECgFp5Scalar {
|
||||
var rng *rand.Rand
|
||||
if seed == nil {
|
||||
return SampleScalarCrypto()
|
||||
}
|
||||
|
||||
hash := sha256.Sum256([]byte(*seed))
|
||||
var intSeed int64
|
||||
for _, b := range hash[:8] {
|
||||
intSeed = (intSeed << 8) | int64(b)
|
||||
}
|
||||
rng = rand.New(rand.NewSource(intSeed))
|
||||
|
||||
return FromNonCanonicalBigInt(new(big.Int).Rand(rng, ORDER))
|
||||
}
|
||||
|
||||
var (
|
||||
ORDER, _ = new(big.Int).SetString("1067993516717146951041484916571792702745057740581727230159139685185762082554198619328292418486241", 10)
|
||||
ZERO = ECgFp5Scalar{}
|
||||
ONE = ECgFp5Scalar{1, 0, 0, 0, 0}
|
||||
TWO = ECgFp5Scalar{2, 0, 0, 0, 0}
|
||||
NEG_ONE = ECgFp5Scalar{
|
||||
0xE80FD996948BFFE0,
|
||||
0xE8885C39D724A09C,
|
||||
0x7FFFFFE6CFB80639,
|
||||
0x7FFFFFF100000016,
|
||||
0x7FFFFFFD80000007,
|
||||
}
|
||||
)
|
||||
|
||||
func (s ECgFp5Scalar) Order() *big.Int {
|
||||
return ORDER
|
||||
}
|
||||
|
||||
var (
|
||||
// Group order n is slightly below 2^319. We store values over five
|
||||
// 64-bit limbs. We use Montgomery multiplication to perform
|
||||
// computations; however, we keep the limbs in normal
|
||||
// (non-Montgomery) representation, so that operations that do not
|
||||
// require any multiplication of scalars, just encoding and
|
||||
// decoding, are fastest.
|
||||
|
||||
// The modulus itself, stored in a Scalar structure (which
|
||||
// contravenes to the rules of a Scalar; this constant MUST NOT leak
|
||||
// outside the API).
|
||||
N = ECgFp5Scalar{
|
||||
0xE80FD996948BFFE1,
|
||||
0xE8885C39D724A09C,
|
||||
0x7FFFFFE6CFB80639,
|
||||
0x7FFFFFF100000016,
|
||||
0x7FFFFFFD80000007,
|
||||
}
|
||||
// -1/N[0] mod 2^64
|
||||
N0I = uint64(0xD78BEF72057B7BDF)
|
||||
// 2^640 mod n
|
||||
R2 = ECgFp5Scalar{
|
||||
0xA01001DCE33DC739,
|
||||
0x6C3228D33F62ACCF,
|
||||
0xD1D796CC91CF8525,
|
||||
0xAADFFF5D1574C1D8,
|
||||
0x4ACA13B28CA251F5,
|
||||
}
|
||||
// 2^632 mod n
|
||||
T632 = ECgFp5Scalar{
|
||||
0x2B0266F317CA91B3,
|
||||
0xEC1D26528E984773,
|
||||
0x8651D7865E12DB94,
|
||||
0xDA2ADFF5941574D0,
|
||||
0x53CACA12110CA256,
|
||||
}
|
||||
)
|
||||
|
||||
func (s *ECgFp5Scalar) IsZero() bool {
|
||||
for i := 0; i < 5; i++ {
|
||||
if s[i] != 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *ECgFp5Scalar) Equals(rhs *ECgFp5Scalar) bool {
|
||||
for i := 0; i < 5; i++ {
|
||||
if s[i] != rhs[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// raw addition (no reduction)
|
||||
func (s ECgFp5Scalar) AddInner(a ECgFp5Scalar) ECgFp5Scalar {
|
||||
var r ECgFp5Scalar
|
||||
var c uint64 = 0
|
||||
for i := 0; i < 5; i++ {
|
||||
z := U128From64(s[i]).Add64(a[i]).Add64(c)
|
||||
|
||||
r[i] = z.Lo
|
||||
c = z.Hi
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// raw subtraction (no reduction)
|
||||
// Final borrow is returned (0xFFFFFFFFFFFFFFFF if borrow, 0 otherwise).
|
||||
func (s *ECgFp5Scalar) SubInner(a *ECgFp5Scalar) (*ECgFp5Scalar, uint64) {
|
||||
r := new(ECgFp5Scalar)
|
||||
c := uint64(0)
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
z := U128From64(s[i]).Sub64(a[i]).Sub64(c)
|
||||
r[i] = z.Lo
|
||||
c = z.Hi & 1
|
||||
}
|
||||
|
||||
if c != 0 {
|
||||
return r, 0xFFFFFFFFFFFFFFFF
|
||||
}
|
||||
return r, 0
|
||||
}
|
||||
|
||||
// If c == 0, return a0.
|
||||
// If c == 0xFFFFFFFFFFFFFFFF, return a1.
|
||||
// c MUST be equal to 0 or 0xFFFFFFFFFFFFFFFF.
|
||||
func Select(c uint64, a0, a1 *ECgFp5Scalar) *ECgFp5Scalar {
|
||||
return &ECgFp5Scalar{
|
||||
a0[0] ^ (c & (a0[0] ^ a1[0])),
|
||||
a0[1] ^ (c & (a0[1] ^ a1[1])),
|
||||
a0[2] ^ (c & (a0[2] ^ a1[2])),
|
||||
a0[3] ^ (c & (a0[3] ^ a1[3])),
|
||||
a0[4] ^ (c & (a0[4] ^ a1[4])),
|
||||
}
|
||||
}
|
||||
|
||||
func (s ECgFp5Scalar) Add(rhs ECgFp5Scalar) ECgFp5Scalar {
|
||||
r0 := s.AddInner(rhs)
|
||||
r1, c := r0.SubInner(&N)
|
||||
return *Select(c, r1, &r0)
|
||||
}
|
||||
|
||||
func (s ECgFp5Scalar) Sub(rhs ECgFp5Scalar) ECgFp5Scalar {
|
||||
r0, c := s.SubInner(&rhs)
|
||||
r1 := r0.AddInner(N)
|
||||
return *Select(c, r0, &r1)
|
||||
}
|
||||
|
||||
func (s ECgFp5Scalar) Neg() ECgFp5Scalar {
|
||||
return ZERO.Sub(s)
|
||||
}
|
||||
|
||||
func (s *ECgFp5Scalar) Mul(rhs *ECgFp5Scalar) *ECgFp5Scalar {
|
||||
res := s.MontyMul(&R2).MontyMul(rhs)
|
||||
return res
|
||||
}
|
||||
|
||||
func (s *ECgFp5Scalar) Square() *ECgFp5Scalar {
|
||||
return s.Mul(s)
|
||||
}
|
||||
|
||||
// Montgomery multiplication.
|
||||
// Returns (self*rhs)/2^320 mod n.
|
||||
// 'self' MUST be less than n (the other operand can be up to 2^320-1).
|
||||
func (s *ECgFp5Scalar) MontyMul(rhs *ECgFp5Scalar) *ECgFp5Scalar {
|
||||
r := new(ECgFp5Scalar)
|
||||
for i := 0; i < 5; i++ {
|
||||
// Iteration i computes r <- (r + self*rhs_i + f*n)/2^64.
|
||||
// Factor f is at most 2^64-1 and set so that the division
|
||||
// is exact.
|
||||
// On input:
|
||||
// r <= 2^320 - 1
|
||||
// self <= n - 1
|
||||
// rhs_i <= 2^64 - 1
|
||||
// f <= 2^64 - 1
|
||||
// Therefore:
|
||||
// r + self*rhs_i + f*n <= 2^320-1 + (2^64 - 1) * (n - 1)
|
||||
// + (2^64 - 1) * n
|
||||
// < 2^384
|
||||
// Thus, the new r fits on 320 bits.
|
||||
m := rhs[i]
|
||||
f := (s[0]*m + r[0]) * N0I
|
||||
|
||||
cc1, cc2 := uint64(0), uint64(0)
|
||||
for j := 0; j < 5; j++ {
|
||||
z := U128From64(s[j]).Mul64(m).Add64(r[j]).Add64(cc1)
|
||||
cc1 = z.Hi
|
||||
z = U128From64(f).Mul64(N[j]).Add64(z.Lo).Add64(cc2)
|
||||
cc2 = z.Hi
|
||||
if j > 0 {
|
||||
r[j-1] = z.Lo
|
||||
}
|
||||
}
|
||||
// No overflow here since the new r fits on 320 bits.
|
||||
r[4] = cc1 + cc2
|
||||
}
|
||||
// We computed (self*rhs + ff*n) / 2^320, with:
|
||||
// self < n
|
||||
// rhs < 2^320
|
||||
// ff < 2^320
|
||||
// Thus, the value we obtained is lower than 2*n. Subtracting n
|
||||
// once (conditionally) is sufficient to achieve full reduction.
|
||||
r2, c := r.SubInner(&N)
|
||||
return Select(c, r2, r)
|
||||
}
|
||||
|
||||
func (s ECgFp5Scalar) expPowerOf2(exp int) ECgFp5Scalar {
|
||||
result := s
|
||||
for i := 0; i < exp; i++ {
|
||||
result = *result.Square()
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func FromGfp5(fp5 gFp5.Element) ECgFp5Scalar {
|
||||
return FromNonCanonicalBigInt(BigIntFromArray([5]uint64{
|
||||
fp5[0].Uint64(), fp5[1].Uint64(), fp5[2].Uint64(), fp5[3].Uint64(), fp5[4].Uint64(),
|
||||
}))
|
||||
}
|
||||
|
||||
func BigIntFromArray(arr [5]uint64) *big.Int {
|
||||
result := new(big.Int)
|
||||
for i := 4; i >= 0; i-- {
|
||||
result.Lsh(result, 64)
|
||||
result.Or(result, new(big.Int).SetUint64(arr[i]))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func FromNonCanonicalBigInt(val *big.Int) ECgFp5Scalar {
|
||||
limbs := new(big.Int).Mod(val, ORDER).Bits()
|
||||
if len(limbs) < 5 {
|
||||
limbs = append(limbs, 0)
|
||||
}
|
||||
return ECgFp5Scalar{uint64(limbs[0]), uint64(limbs[1]), uint64(limbs[2]), uint64(limbs[3]), uint64(limbs[4])}
|
||||
}
|
||||
|
||||
func (s ECgFp5Scalar) ToCanonicalBigInt() *big.Int {
|
||||
result := BigIntFromArray(s)
|
||||
|
||||
order := ORDER
|
||||
if result.Cmp(order) >= 0 {
|
||||
result.Sub(result, order)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Recode a scalar into signed integers. For a window width of w
|
||||
// bits, returned integers are in the -(2^w-1) to +2^w range. The
|
||||
// provided slice is filled; if w*len(ss) >= 320, then the output
|
||||
// encodes the complete scalar value, and the top (last) signed
|
||||
// integer is nonnegative.
|
||||
// Window width MUST be between 2 and 10.
|
||||
func (s ECgFp5Scalar) RecodeSigned(ss []int32, w int32) {
|
||||
RecodeSignedFromLimbs(s[:], ss, w)
|
||||
}
|
||||
|
||||
func RecodeSignedFromLimbs(limbs []uint64, ss []int32, w int32) {
|
||||
var acc uint64 = 0
|
||||
var accLen int32 = 0
|
||||
var j int = 0
|
||||
mw := (uint32(1) << w) - 1
|
||||
hw := uint32(1) << (w - 1)
|
||||
var cc uint32 = 0
|
||||
for i := 0; i < len(ss); i++ {
|
||||
// Get next w-bit chunk in bb.
|
||||
var bb uint32
|
||||
if accLen < w {
|
||||
if j < len(limbs) {
|
||||
nl := limbs[j]
|
||||
j++
|
||||
bb = (uint32(acc | (nl << accLen))) & mw
|
||||
acc = nl >> (w - accLen)
|
||||
} else {
|
||||
bb = uint32(acc) & mw
|
||||
acc = 0
|
||||
}
|
||||
accLen += 64 - w
|
||||
} else {
|
||||
bb = uint32(acc) & mw
|
||||
accLen -= w
|
||||
acc >>= w
|
||||
}
|
||||
|
||||
// If bb is greater than 2^(w-1), subtract 2^w and propagate a carry.
|
||||
bb += cc
|
||||
|
||||
cc = (hw - bb) >> 31
|
||||
ss[i] = int32(bb) - int32(cc<<w)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,729 @@
|
||||
package ecgfp5
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
)
|
||||
|
||||
func TestSerdes(t *testing.T) {
|
||||
scalar := ECgFp5Scalar{
|
||||
6950590877883398434,
|
||||
17178336263794770543,
|
||||
11012823478139181320,
|
||||
16445091359523510936,
|
||||
5882925226143600273,
|
||||
}
|
||||
|
||||
leBytes := scalar.ToLittleEndianBytes()
|
||||
result := ScalarElementFromLittleEndianBytes(leBytes)
|
||||
|
||||
if !scalar.Equals(&result) {
|
||||
t.Fatalf("Expected %v, but got %v", scalar, result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitTo4LimbBits(t *testing.T) {
|
||||
scalar := ECgFp5Scalar{
|
||||
6950590877883398434,
|
||||
17178336263794770543,
|
||||
11012823478139181320,
|
||||
16445091359523510936,
|
||||
5882925226143600273,
|
||||
}
|
||||
|
||||
limbs := scalar.SplitTo4BitLimbs()
|
||||
|
||||
expectedValues := map[int]uint8{
|
||||
0: 2, 1: 2, 2: 9, 3: 7, 4: 15, 5: 4, 6: 15, 7: 13,
|
||||
8: 3, 9: 9, 10: 5, 11: 7, 12: 5, 13: 7, 14: 0, 15: 6,
|
||||
16: 15, 17: 6, 18: 2, 19: 12, 20: 2, 21: 11, 22: 3, 23: 3,
|
||||
24: 1, 25: 13, 26: 5, 27: 11, 28: 5, 29: 6, 30: 14, 31: 14,
|
||||
32: 8, 33: 0, 34: 9, 35: 5, 36: 1, 37: 9, 38: 12, 39: 13,
|
||||
40: 10, 41: 9, 42: 8, 43: 6, 44: 5, 45: 13, 46: 8, 47: 9,
|
||||
48: 8, 49: 9, 50: 10, 51: 9, 52: 14, 53: 3, 54: 15, 55: 2,
|
||||
56: 6, 57: 7, 58: 3, 59: 11, 60: 8, 61: 3, 62: 4, 63: 14,
|
||||
64: 1, 65: 9, 66: 14, 67: 4, 68: 9, 69: 7, 70: 8, 71: 15,
|
||||
72: 2, 73: 5, 74: 9, 75: 5, 76: 4, 77: 10, 78: 1, 79: 5,
|
||||
}
|
||||
|
||||
for i, expected := range expectedValues {
|
||||
if limbs[i] != expected {
|
||||
t.Fatalf("Expected limbs[%d] to be %d, but got %d", i, expected, limbs[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddInner(t *testing.T) {
|
||||
scalar1 := ECgFp5Scalar{
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
}
|
||||
|
||||
scalar2 := ECgFp5Scalar{
|
||||
0xFFFFFFFFFeeFFF,
|
||||
12312321312,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFacdFFFFF,
|
||||
0xbcaFFFFFFFFFFFFF,
|
||||
}
|
||||
|
||||
result := scalar1.AddInner(scalar2)
|
||||
expectedValues := ECgFp5Scalar{
|
||||
0xfffffffffeeffe,
|
||||
0x2dddf1d20,
|
||||
0xffffffffffffffff,
|
||||
0xffffffacdfffff,
|
||||
0xbcafffffffffffff,
|
||||
}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
if result[i] != expectedValues[i] {
|
||||
t.Fatalf("Expected %v but got %v at index %d", expectedValues[i], result[i], i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubInner(t *testing.T) {
|
||||
scalar1 := ECgFp5Scalar{0, 0, 0, 0, 0}
|
||||
scalar2 := ECgFp5Scalar{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}
|
||||
|
||||
result, carry := scalar1.SubInner(&scalar2)
|
||||
expectedValues := ECgFp5Scalar{1, 0, 0, 0, 0}
|
||||
expectedCarry := uint64(18446744073709551615)
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
if result[i] != expectedValues[i] {
|
||||
t.Fatalf("Expected result[%d] to be %d, but got %d", i, expectedValues[i], result[i])
|
||||
}
|
||||
}
|
||||
if carry != expectedCarry {
|
||||
t.Fatalf("Expected carry to be %d, but got %d", expectedCarry, carry)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddScalar(t *testing.T) {
|
||||
scalar1 := ECgFp5Scalar{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}
|
||||
scalar2 := ECgFp5Scalar{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}
|
||||
|
||||
result := scalar1.AddInner(scalar2)
|
||||
expectedValues := ECgFp5Scalar{0xFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
if result[i] != expectedValues[i] {
|
||||
t.Fatalf("Expected %v but got %v at index %d", expectedValues[i], result[i], i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSub(t *testing.T) {
|
||||
scalar1 := ECgFp5Scalar{1, 2, 0, 0, 0}
|
||||
scalar2 := ECgFp5Scalar{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}
|
||||
|
||||
result := scalar1.Sub(scalar2)
|
||||
expectedValues := ECgFp5Scalar{0xe80fd996948bffe3, 0xe8885c39d724a09e, 0x7fffffe6cfb80639, 0x7ffffff100000016, 0x7ffffffd80000007}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
if result[i] != expectedValues[i] {
|
||||
t.Fatalf("Expected result[%d] to be %d, but got %d", i, expectedValues[i], result[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelect(t *testing.T) {
|
||||
a0 := ECgFp5Scalar{1, 2, 3, 4, 5}
|
||||
a1 := ECgFp5Scalar{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFFFD, 0xFFFFFFFFFFFFFFFC, 0xFFFFFFFFFFFFFFFB}
|
||||
|
||||
result := Select(uint64(0), &a0, &a1)
|
||||
for i := 0; i < 5; i++ {
|
||||
if result[i] != a0[i] {
|
||||
t.Fatalf("Expected result[%d] to be %d, but got %d", i, a0[i], result[i])
|
||||
}
|
||||
}
|
||||
|
||||
result = Select(uint64(0xFFFFFFFFFFFFFFFF), &a0, &a1)
|
||||
for i := 0; i < 5; i++ {
|
||||
if result[i] != a1[i] {
|
||||
t.Fatalf("Expected result[%d] to be %d, but got %d", i, a1[i], result[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMontyMul(t *testing.T) {
|
||||
scalar1 := ECgFp5Scalar{1, 2, 3, 4, 5}
|
||||
scalar2 := ECgFp5Scalar{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}
|
||||
|
||||
result := scalar1.MontyMul(&scalar2)
|
||||
expectedValues := ECgFp5Scalar{10974894505036100890, 7458803775930281466, 744239893213209819, 3396127080529349464, 5979369289905897562}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
if result[i] != expectedValues[i] {
|
||||
t.Fatalf("Expected result[%d] to be %d, but got %d", i, expectedValues[i], result[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMul(t *testing.T) {
|
||||
scalar := ECgFp5Scalar{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}
|
||||
|
||||
result := scalar.Mul(&scalar)
|
||||
expectedValues := ECgFp5Scalar{471447996674510360, 3520142298321118626, 17240611161823899731, 5610669884293437850, 1193611606749909414}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
if result[i] != expectedValues[i] {
|
||||
t.Fatalf("Expected result[%d] to be %d, but got %d", i, expectedValues[i], result[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecodeSigned(t *testing.T) {
|
||||
var ss [50]int32
|
||||
scalar := ECgFp5Scalar{
|
||||
g.Modulus() - 1,
|
||||
g.Modulus() - 2,
|
||||
g.Modulus() - 3,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
g.Modulus() - 5,
|
||||
}
|
||||
|
||||
scalar.RecodeSigned(ss[:], 5)
|
||||
|
||||
expectedValues := map[int]int32{
|
||||
6: -4,
|
||||
19: -2,
|
||||
25: -8,
|
||||
32: -1,
|
||||
}
|
||||
|
||||
for i, elem := range ss {
|
||||
if expected, exists := expectedValues[i]; exists {
|
||||
if elem != expected {
|
||||
t.Fatalf("Expected ss[%d] to be %d, but got %d", i, expected, elem)
|
||||
}
|
||||
} else if elem != 0 {
|
||||
t.Fatalf("Expected ss[%d] to be 0, but got %d", i, elem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromQuinticExtension(t *testing.T) {
|
||||
scalar := FromGfp5(gFp5.Element{*g.NegOne(), *g.NegOne(), *g.NegOne(), *g.NegOne(), *g.NegOne()})
|
||||
|
||||
expectedValues := ECgFp5Scalar{
|
||||
3449841778703204414,
|
||||
3382000508875488967,
|
||||
212073444237,
|
||||
124554051540,
|
||||
17179869170,
|
||||
}
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
if scalar[i] != expectedValues[i] {
|
||||
t.Fatalf("Expected scalar[%d] to be %d, but got %d", i, expectedValues[i], scalar[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddShiftedSmall161(t *testing.T) {
|
||||
scalar := Signed161{
|
||||
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
}
|
||||
|
||||
scalar.AddShiftedSmall([]uint64{1, 0xFFFFFFFFFFFFDDBB, 0xFFFFAACFFFFFDDBB}, 1231233)
|
||||
expectedValues := [3]uint64{
|
||||
1,
|
||||
18446744073709534070,
|
||||
18446556744415951735,
|
||||
}
|
||||
|
||||
for i, elem := range scalar {
|
||||
if elem != expectedValues[i] {
|
||||
t.Fatalf("Expected scalar[%d] to be %d, but got %d", i, expectedValues[i], elem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdd161(t *testing.T) {
|
||||
scalar := Signed161{
|
||||
|
||||
0x10FFFFabcdFF1213,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
}
|
||||
|
||||
scalar.Add([]uint64{0x10FFFFabcdFF1213, 0xFFFFFFFFFFFFDDBB, 0xFFFFAACFFFFFDDBB})
|
||||
|
||||
expectedValues := [3]uint64{
|
||||
2449957474057200678,
|
||||
18446744073709542842,
|
||||
18446650409062751675,
|
||||
}
|
||||
|
||||
for i, elem := range scalar {
|
||||
if elem != expectedValues[i] {
|
||||
t.Fatalf("Expected scalar[%d] to be %d, but got %d", i, expectedValues[i], elem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddShifted161(t *testing.T) {
|
||||
scalar1 := Signed161{
|
||||
|
||||
0x10FFFFabcdFF1213,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
}
|
||||
scalar2 := Signed161{
|
||||
0xabcdabcdabcdabcd,
|
||||
0xdef0def0def0def0,
|
||||
0x1234123412341234,
|
||||
}
|
||||
scalar1.AddShifted(&scalar2, 21423423)
|
||||
|
||||
expectedValues := [3]uint64{
|
||||
1224978737028600339,
|
||||
18446744073709551615,
|
||||
18446744073709551615,
|
||||
}
|
||||
for i, elem := range scalar1 {
|
||||
if elem != expectedValues[i] {
|
||||
t.Fatalf("Expected scalar1[%d] to be %d, but got %d", i, expectedValues[i], elem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecodeSigned5_161(t *testing.T) {
|
||||
scalar1 := Signed161{
|
||||
0x1234567890abcdef,
|
||||
0xfedcba0987654321,
|
||||
0x0fedcba987654321,
|
||||
}
|
||||
|
||||
expectedValues := [33]int32{
|
||||
15, 15, -13, -8, 11, 8, 2, 15, -10, 3, 13, 4, -15, -15, 13, 8, 5, -5, 2, -13, 1, -3, -13, -4, -1, 16, 8, 6, -12, -13, -2, -15, 0,
|
||||
}
|
||||
for i, elem := range scalar1.RecodeSigned5() {
|
||||
if elem != expectedValues[i] {
|
||||
t.Fatalf("Expected ss[%d] to be %d, but got %d", i, expectedValues[i], elem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSub161(t *testing.T) {
|
||||
scalar := Signed161{
|
||||
|
||||
0x1010111112121313,
|
||||
0x10FFFFabcdFF1213,
|
||||
0xabcdef12345abcde,
|
||||
}
|
||||
|
||||
scalar.Sub([]uint64{0xFFFFFFFFFFFFFFFF, 0x10FFFFabcdFF1213, 0xFFFFFFFFFFFFFFFF})
|
||||
|
||||
expectedValues := [3]uint64{
|
||||
1157443869249508116,
|
||||
18446744073709551615,
|
||||
12379813812178173150,
|
||||
}
|
||||
|
||||
for i, elem := range scalar {
|
||||
if elem != expectedValues[i] {
|
||||
t.Fatalf("Expected scalar[%d] to be %d, but got %d", i, expectedValues[i], elem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubShiftedSmall161(t *testing.T) {
|
||||
scalar := Signed161{
|
||||
|
||||
0x1010111112121313,
|
||||
0x10FFFFabcdFF1213,
|
||||
0xabcdef12345abcde,
|
||||
}
|
||||
|
||||
scalar.SubShiftedSmall([]uint64{0xFFFFFFFFFFFFFFFF, 0x10FFFFabcdFF1213, 0xFFFFFFFFFFFFFFFF}, 5123142)
|
||||
|
||||
expectedValues := [3]uint64{
|
||||
1157443869249508179,
|
||||
15060059935745936659,
|
||||
12379813812178173209,
|
||||
}
|
||||
|
||||
for i, elem := range scalar {
|
||||
if elem != expectedValues[i] {
|
||||
t.Fatalf("Expected scalar[%d] to be %d, but got %d", i, expectedValues[i], elem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubShifted161(t *testing.T) {
|
||||
scalar1 := Signed161{
|
||||
|
||||
0x1010111112121313,
|
||||
0x10FFFFabcdFF1213,
|
||||
0xabcdef12345abcde,
|
||||
}
|
||||
|
||||
scalar2 := Signed161{
|
||||
|
||||
0xabcdabcdabcdabcd,
|
||||
0xdef0def0def0def0,
|
||||
0x1234123412341234,
|
||||
}
|
||||
|
||||
scalar1.SubShifted(&scalar2, 12315523)
|
||||
|
||||
expectedValues := [3]uint64{
|
||||
1157443869249508115,
|
||||
1224978737028600339,
|
||||
12379813812178173150,
|
||||
}
|
||||
|
||||
for i, elem := range scalar1 {
|
||||
if elem != expectedValues[i] {
|
||||
t.Fatalf("Expected scalar1[%d] to be %d, but got %d", i, expectedValues[i], elem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromNsquared(t *testing.T) {
|
||||
expected := Signed640{
|
||||
10262430419493848001,
|
||||
781583365610726095,
|
||||
1685487855950207164,
|
||||
0x90465B4214B27B1C,
|
||||
0xD308FECCB1878B88,
|
||||
0x3CC55EB2EAC07502,
|
||||
0x59F038FB784335CE,
|
||||
0xBFFFFE954FB808EA,
|
||||
13835057829796380825,
|
||||
4611686007689969677,
|
||||
}
|
||||
|
||||
for i, limb := range FromNsquared() {
|
||||
if limb != expected[i] {
|
||||
t.Fatalf("Expected limb %d to be %x, but got %x", i, expected[i], limb)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromMulScalars(t *testing.T) {
|
||||
a := ECgFp5Scalar{
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
}
|
||||
b := ECgFp5Scalar{
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
}
|
||||
result := FromMulScalars(&a, &b)
|
||||
|
||||
expectedValues := [10]uint64{
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
18446744073709551614,
|
||||
18446744073709551615,
|
||||
18446744073709551615,
|
||||
18446744073709551615,
|
||||
18446744073709551615,
|
||||
}
|
||||
for i := 0; i < 10; i++ {
|
||||
if result[i] != expectedValues[i] {
|
||||
t.Fatalf("Expected result[%d] to be %d, but got %d", i, expectedValues[i], result[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestAdd1_640(t *testing.T) {
|
||||
a := Signed640{
|
||||
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
}
|
||||
|
||||
a.Add1()
|
||||
|
||||
expected := Signed640{
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
}
|
||||
|
||||
for i, limb := range a {
|
||||
if limb != expected[i] {
|
||||
t.Fatalf("Test case 2: Expected limb %d to be %x, but got %x", i, expected[i], limb)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsNonnegative640(t *testing.T) {
|
||||
nonnegativeTest := Signed640{
|
||||
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0x7FFFFFFFFFFFFFFF,
|
||||
}
|
||||
|
||||
if !nonnegativeTest.IsNonnegative() {
|
||||
t.Fatalf("Expected nonnegativeTest to be nonnegative, but it is not")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLtUnsigned640(t *testing.T) {
|
||||
ltTest1 := Signed640{
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
}
|
||||
ltTest2 := Signed640{
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
|
||||
}
|
||||
|
||||
if !ltTest1.LtUnsigned(<Test2) {
|
||||
t.Fatalf("Expected ltTest1 to be less than ltTest2, but it is not")
|
||||
}
|
||||
if ltTest2.LtUnsigned(<Test1) {
|
||||
t.Fatalf("Expected ltTest2 to be greater than ltTest1, but it is not")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBitlength(t *testing.T) {
|
||||
bitlengthTest := Signed640{
|
||||
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0x8000000000000000,
|
||||
}
|
||||
|
||||
bitlength := bitlengthTest.Bitlength()
|
||||
|
||||
expectedBitlength := int32(639)
|
||||
if bitlength != expectedBitlength {
|
||||
t.Fatalf("Expected bit length to be %d, but got %d", expectedBitlength, bitlength)
|
||||
}
|
||||
|
||||
bitlengthTest = Signed640{
|
||||
|
||||
0xFFFFFFFFFFFFFaFF,
|
||||
0xFFFFFFFFFFFFFaFF,
|
||||
0xFFFFFFFFFFFFFaFF,
|
||||
0xFFFFFFFFFFFFFaFF,
|
||||
0xFFFFFFFFFFFFFaFF,
|
||||
0xFFFFFFFFFFFFFaFF,
|
||||
0xFFFFFFFFFFFFFaFF,
|
||||
0xFFFFFFFFFFFFFaFF,
|
||||
0xFFFFFFFFFFFFFaFF,
|
||||
0xFFFFFFFFFFFFFaFF,
|
||||
}
|
||||
|
||||
bitlength = bitlengthTest.Bitlength()
|
||||
|
||||
expectedBitlength = int32(587)
|
||||
if bitlength != expectedBitlength {
|
||||
t.Fatalf("Expected bit length to be %d, but got %d", expectedBitlength, bitlength)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdd640(t *testing.T) {
|
||||
a := Signed640{
|
||||
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFaaaF,
|
||||
}
|
||||
|
||||
b := Signed640{
|
||||
|
||||
0xFFFFFabcdFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFF1234FFFFF,
|
||||
0,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFF1234FFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFF1234FFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
}
|
||||
|
||||
a.AddShifted(&b, 5543242)
|
||||
|
||||
expected := Signed640{
|
||||
|
||||
18446744073709551615,
|
||||
0,
|
||||
18446744073709551615,
|
||||
0,
|
||||
18446744073709551615,
|
||||
0,
|
||||
18446744073709551615,
|
||||
0,
|
||||
18446744073709551615,
|
||||
18446744073709529775,
|
||||
}
|
||||
|
||||
for i, limb := range a {
|
||||
if limb != expected[i] {
|
||||
t.Fatalf("Expected limb %d to be %x, but got %x", i, expected[i], limb)
|
||||
}
|
||||
}
|
||||
|
||||
a.AddShifted(&b, 63)
|
||||
|
||||
expected = Signed640{
|
||||
|
||||
9223372036854775807,
|
||||
18446741180780642304,
|
||||
18446744073709551614,
|
||||
0,
|
||||
9223372004938743807,
|
||||
9223372036854775809,
|
||||
18446744073709551614,
|
||||
18446744041793519616,
|
||||
18446744073709551614,
|
||||
18446744041793497775,
|
||||
}
|
||||
|
||||
for i, limb := range a {
|
||||
if limb != expected[i] {
|
||||
t.Fatalf("Expected limb %d to be %x, but got %x", i, expected[i], limb)
|
||||
}
|
||||
}
|
||||
|
||||
a.AddShifted(&b, 0)
|
||||
|
||||
expected = Signed640{
|
||||
|
||||
9223366250996957182,
|
||||
18446741180780642304,
|
||||
18446744073709551614,
|
||||
18446744009877487616,
|
||||
9223372004938743807,
|
||||
9223372036854775808,
|
||||
18446744009877487614,
|
||||
18446744041793519616,
|
||||
18446744009877487614,
|
||||
18446744041793497775,
|
||||
}
|
||||
|
||||
for i, limb := range a {
|
||||
if limb != expected[i] {
|
||||
t.Fatalf("Expected limb %d to be %x, but got %x", i, expected[i], limb)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubShifted640(t *testing.T) {
|
||||
// Create two Signed640 instances for the test
|
||||
a := Signed640{
|
||||
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFaaaF,
|
||||
}
|
||||
|
||||
b := Signed640{
|
||||
|
||||
0xFFFFFabcdFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFF1234FFFFF,
|
||||
0,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFF1234FFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
0xFFFFFFF1234FFFFF,
|
||||
0xFFFFFFFFFFFFFFFF,
|
||||
}
|
||||
|
||||
a.SubShifted(&b, 313)
|
||||
expectedLargeShift := Signed640{
|
||||
|
||||
18446744073709551615,
|
||||
0,
|
||||
18446744073709551615,
|
||||
0,
|
||||
18446744073709551615,
|
||||
144115188075855872,
|
||||
18446744073709551615,
|
||||
498688000,
|
||||
18446744073709551615,
|
||||
498666159,
|
||||
}
|
||||
|
||||
for i, limb := range a {
|
||||
if limb != expectedLargeShift[i] {
|
||||
t.Fatalf("sub_shifted (large shift): Expected limb %d to be %x, but got %x", i, expectedLargeShift[i], limb)
|
||||
}
|
||||
}
|
||||
|
||||
a.SubShifted(&b, 63)
|
||||
expectedSmallShift := Signed640{
|
||||
|
||||
9223372036854775807,
|
||||
2892928909313,
|
||||
18446744073709551615,
|
||||
0,
|
||||
9223372068770807807,
|
||||
9367487224930631680,
|
||||
18446744073709551615,
|
||||
32414720000,
|
||||
18446744073709551615,
|
||||
32414698159,
|
||||
}
|
||||
|
||||
for i, limb := range a {
|
||||
if limb != expectedSmallShift[i] {
|
||||
t.Fatalf("sub_shifted (small shift): Expected limb %d to be %x, but got %x", i, expectedSmallShift[i], limb)
|
||||
}
|
||||
}
|
||||
|
||||
a.SubShifted(&b, 0)
|
||||
expectedZeroShift := Signed640{
|
||||
|
||||
9223377822712594432,
|
||||
2892928909313,
|
||||
18446744073709551615,
|
||||
63832064000,
|
||||
9223372068770807806,
|
||||
9367487224930631681,
|
||||
63832063999,
|
||||
32414720001,
|
||||
63832063999,
|
||||
32414698160,
|
||||
}
|
||||
|
||||
for i, limb := range a {
|
||||
if limb != expectedZeroShift[i] {
|
||||
t.Fatalf("sub: Expected limb %d to be %x, but got %x", i, expectedZeroShift[i], limb)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package ecgfp5
|
||||
|
||||
// A custom 161-bit integer type; used for splitting a scalar into a
|
||||
// fraction. Negative values use two's complement notation; the value
|
||||
// is truncated to 161 bits (upper bits in the top limb are ignored).
|
||||
// Elements are mutable containers.
|
||||
// WARNING: everything in here is vartime; do not use on secret values.
|
||||
type Signed161 [3]uint64
|
||||
|
||||
// Export this value as a 192-bit integer (three 64-bit limbs, in little-endian order).
|
||||
func (s Signed161) ToU192() [3]uint64 {
|
||||
x := s[2] & 0x00000001FFFFFFFF
|
||||
x |= (^(x >> 32) + 1) << 33
|
||||
return [3]uint64{s[0], s[1], x}
|
||||
}
|
||||
|
||||
// Recode this integer into 33 signed digits for a 5-bit window.
|
||||
func (s Signed161) RecodeSigned5() [33]int32 {
|
||||
// We first sign-extend the value to 192 bits, then add
|
||||
// 2^160 to get a nonnegative value in the 0 to 2^161-1
|
||||
// range. We then recode that value; and finally we fix
|
||||
// the result by subtracting 1 from the top digit.
|
||||
tmp := s.ToU192()
|
||||
tmp[2] += 0x0000000100000000
|
||||
var ss [33]int32
|
||||
RecodeSignedFromLimbs(tmp[:], ss[:], 5)
|
||||
ss[32] -= 1
|
||||
return ss
|
||||
}
|
||||
|
||||
// Add v*2^s to this value.
|
||||
func (s *Signed161) AddShifted(v *Signed161, shift int32) {
|
||||
if shift == 0 {
|
||||
s.Add(v[:])
|
||||
} else if shift < 64 {
|
||||
s.AddShiftedSmall(v[:], shift)
|
||||
} else if shift < 161 {
|
||||
s.AddShiftedSmall(v[(shift>>6):], shift&63)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Signed161) AddShiftedSmall(v []uint64, shift int32) {
|
||||
cc, vbits, j := uint64(0), uint64(0), 3-len(v)
|
||||
for i := j; i < 3; i++ {
|
||||
vw := v[i-j]
|
||||
|
||||
vws := (vw << (uint32(shift) % 64)) | vbits
|
||||
vbits = vw >> ((64 - uint32(shift)) % 64)
|
||||
|
||||
z := U128From64(s[i]).Add64(vws).Add64(cc)
|
||||
s[i] = z.Lo
|
||||
cc = z.Hi
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Signed161) Add(v []uint64) {
|
||||
cc, j := uint64(0), 3-len(v)
|
||||
for i := j; i < 3; i++ {
|
||||
z := U128From64(s[i]).Add64(v[i-j]).Add64(cc)
|
||||
s[i] = z.Lo
|
||||
cc = z.Hi
|
||||
}
|
||||
}
|
||||
|
||||
// Subtract v*2^s from this value.
|
||||
func (s *Signed161) SubShifted(v *Signed161, shift int32) {
|
||||
if shift == 0 {
|
||||
s.Sub(v[:])
|
||||
} else if shift < 64 {
|
||||
s.SubShiftedSmall(v[:], shift)
|
||||
} else if shift < 161 {
|
||||
s.SubShiftedSmall(v[(shift>>6):], shift&63)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Signed161) SubShiftedSmall(v []uint64, shift int32) {
|
||||
cc, vbits, j := uint64(0), uint64(0), 3-len(v)
|
||||
for i := j; i < 3; i++ {
|
||||
vw := v[i-j]
|
||||
vws := (vw << (uint32(shift) % 64)) | vbits
|
||||
vbits = vw >> ((64 - uint32(shift)) % 64)
|
||||
|
||||
z := U128From64(s[i]).Sub64(vws).Sub64(cc)
|
||||
s[i] = z.Lo
|
||||
cc = z.Hi & 1
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Signed161) Sub(v []uint64) {
|
||||
cc, j := uint64(0), 3-len(v)
|
||||
for i := j; i < 3; i++ {
|
||||
z := U128From64(s[i]).Sub64(v[i-j]).Sub64(cc)
|
||||
s[i] = z.Lo
|
||||
cc = z.Hi & 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package ecgfp5
|
||||
|
||||
// A custom 640-bit integer type (signed).
|
||||
// Elements are mutable containers.
|
||||
// WARNING: everything in here is vartime; do not use on secret values.
|
||||
type Signed640 [10]uint64
|
||||
|
||||
// Obtain an instance containing n^2.
|
||||
func FromNsquared() *Signed640 {
|
||||
return &Signed640{
|
||||
0x8E6B7A18061803C1,
|
||||
0x0AD8BDEE1594E2CF,
|
||||
0x17640E465F2598BC,
|
||||
0x90465B4214B27B1C,
|
||||
0xD308FECCB1878B88,
|
||||
0x3CC55EB2EAC07502,
|
||||
0x59F038FB784335CE,
|
||||
0xBFFFFE954FB808EA,
|
||||
0xBFFFFFCB80000099,
|
||||
0x3FFFFFFD8000000D,
|
||||
}
|
||||
}
|
||||
|
||||
// Obtain an instance containing a*b (both a and b are interpreted
|
||||
// as integers in the 0..n-1 range).
|
||||
func FromMulScalars(a, b *ECgFp5Scalar) *Signed640 {
|
||||
var r Signed640
|
||||
for i := 0; i < 5; i++ {
|
||||
aw := a[i]
|
||||
cc := uint64(0)
|
||||
for j := 0; j < 5; j++ {
|
||||
z := U128From64(aw).Mul64(b[j]).Add64(r[i+j]).Add64(cc)
|
||||
r[i+j] = z.Lo
|
||||
cc = z.Hi
|
||||
}
|
||||
r[i+5] = cc
|
||||
}
|
||||
return &r
|
||||
}
|
||||
|
||||
// Add 1 to this instance.
|
||||
func (s *Signed640) Add1() {
|
||||
for i := 0; i < 10; i++ {
|
||||
s[i]++
|
||||
if s[i] != 0 {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Signed640) IsNonnegative() bool {
|
||||
return (s[9] >> 63) == 0
|
||||
}
|
||||
|
||||
func (s *Signed640) LtUnsigned(rhs *Signed640) bool {
|
||||
for i := 9; i >= 0; i-- {
|
||||
aw := s[i]
|
||||
bw := rhs[i]
|
||||
if aw < bw {
|
||||
return true
|
||||
}
|
||||
if aw > bw {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Get the bit length of this value. The bit length is defined as the
|
||||
// minimal size of the binary representation in two's complement,
|
||||
// _excluding_ the sign bit (thus, -2^k has bit length k, whereas +2^k
|
||||
// has bit length k+1).
|
||||
func (s *Signed640) Bitlength() int32 {
|
||||
sm := (^(s[9] >> 63) + 1)
|
||||
for i := 9; i >= 0; i-- {
|
||||
w := s[i] ^ sm
|
||||
if w != 0 {
|
||||
return (int32(i) << 6) + U64Bitlength(w)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func U64Bitlength(w uint64) int32 {
|
||||
// We use here a portable algorithm; some architectures have
|
||||
// dedicated opcodes that could speed up this operation
|
||||
// greatly (e.g. lzcnt on recent x86).
|
||||
var x = w
|
||||
var r int32
|
||||
if x > 0xFFFFFFFF {
|
||||
x >>= 32
|
||||
r += 32
|
||||
}
|
||||
if x > 0x0000FFFF {
|
||||
x >>= 16
|
||||
r += 16
|
||||
}
|
||||
if x > 0x000000FF {
|
||||
x >>= 8
|
||||
r += 8
|
||||
}
|
||||
if x > 0x0000000F {
|
||||
x >>= 4
|
||||
r += 4
|
||||
}
|
||||
if x > 0x00000003 {
|
||||
x >>= 2
|
||||
r += 2
|
||||
}
|
||||
return r + int32(x) - int32((x+1)>>2)
|
||||
}
|
||||
|
||||
// Add v*2^s to this instance.
|
||||
func (s *Signed640) AddShifted(v *Signed640, shift int32) {
|
||||
if shift == 0 {
|
||||
s.Add(v[:])
|
||||
} else if shift < 64 {
|
||||
s.AddShiftedSmall(v[:], shift)
|
||||
} else if shift < 640 {
|
||||
s.AddShiftedSmall(v[(shift>>6):], shift&63)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Signed640) AddShiftedSmall(v []uint64, shift int32) {
|
||||
cc := uint64(0)
|
||||
j := 10 - len(v)
|
||||
vbits := uint64(0)
|
||||
for i := j; i < 10; i++ {
|
||||
vw := v[i-j]
|
||||
|
||||
vws := (vw << (uint32(shift) % 64)) | vbits
|
||||
vbits = vw >> ((64 - uint32(shift)) % 64)
|
||||
|
||||
z := U128From64(s[i]).Add64(vws).Add64(cc)
|
||||
s[i] = z.Lo
|
||||
cc = z.Hi
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Signed640) Add(v []uint64) {
|
||||
cc := uint64(0)
|
||||
j := 10 - len(v)
|
||||
for i := j; i < 10; i++ {
|
||||
z := U128From64(s[i]).Add64(v[i-j]).Add64(cc)
|
||||
s[i] = z.Lo
|
||||
cc = z.Hi
|
||||
}
|
||||
}
|
||||
|
||||
// Subtract v*2^s from this instance.
|
||||
func (s *Signed640) SubShifted(v *Signed640, shift int32) {
|
||||
if shift == 0 {
|
||||
s.Sub(v[:])
|
||||
} else if shift < 64 {
|
||||
s.SubShiftedSmall(v[:], shift)
|
||||
} else if shift < 640 {
|
||||
s.SubShiftedSmall(v[(shift>>6):], shift&63)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Signed640) SubShiftedSmall(v []uint64, shift int32) {
|
||||
cc, vbits, j := uint64(0), uint64(0), 10-len(v)
|
||||
for i := j; i < 10; i++ {
|
||||
vw := v[i-j]
|
||||
|
||||
vws := (vw << (uint32(shift) % 64)) | vbits
|
||||
vbits = vw >> ((64 - uint32(shift)) % 64)
|
||||
|
||||
z := U128From64(s[i]).Sub64(vws).Sub64(cc)
|
||||
s[i] = z.Lo
|
||||
cc = z.Hi & 1
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Signed640) Sub(v []uint64) {
|
||||
cc, j := uint64(0), 10-len(v)
|
||||
for i := j; i < 10; i++ {
|
||||
z := U128From64(s[i]).Sub64(v[i-j]).Sub64(cc)
|
||||
s[i] = z.Lo
|
||||
cc = z.Hi & 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package ecgfp5
|
||||
|
||||
import (
|
||||
"math/bits"
|
||||
)
|
||||
|
||||
type U128 struct{ Hi, Lo uint64 }
|
||||
|
||||
func U128From64(v uint64) U128 { return U128{Lo: v} }
|
||||
|
||||
func (u U128) Add64(n uint64) (v U128) {
|
||||
var carry uint64
|
||||
v.Lo, carry = bits.Add64(u.Lo, n, 0)
|
||||
v.Hi = u.Hi + carry
|
||||
return v
|
||||
}
|
||||
|
||||
func (u U128) Sub64(n uint64) (v U128) {
|
||||
var borrowed uint64
|
||||
v.Lo, borrowed = bits.Sub64(u.Lo, n, 0)
|
||||
v.Hi = u.Hi - borrowed
|
||||
return v
|
||||
}
|
||||
|
||||
func (u U128) Mul64(n uint64) (dest U128) {
|
||||
dest.Hi, dest.Lo = bits.Mul64(u.Lo, n)
|
||||
dest.Hi += u.Hi * n
|
||||
return dest
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package ecgfp5
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
)
|
||||
|
||||
// A curve point in short Weirstrass form (x, y). This is used by the in-circuit representation
|
||||
type WeierstrassPoint struct {
|
||||
X gFp5.Element
|
||||
Y gFp5.Element
|
||||
IsInf bool
|
||||
}
|
||||
|
||||
var (
|
||||
GENERATOR_WEIERSTRASS = WeierstrassPoint{
|
||||
X: gFp5.Element{
|
||||
g.FromUint64(11712523173042564207),
|
||||
g.FromUint64(14090224426659529053),
|
||||
g.FromUint64(13197813503519687414),
|
||||
g.FromUint64(16280770174934269299),
|
||||
g.FromUint64(15998333998318935536),
|
||||
},
|
||||
Y: gFp5.Element{
|
||||
g.FromUint64(14639054205878357578),
|
||||
g.FromUint64(17426078571020221072),
|
||||
g.FromUint64(2548978194165003307),
|
||||
g.FromUint64(8663895577921260088),
|
||||
g.FromUint64(9793640284382595140),
|
||||
},
|
||||
IsInf: false,
|
||||
}
|
||||
|
||||
A_WEIERSTRASS = gFp5.Element{
|
||||
g.FromUint64(6148914689804861439),
|
||||
g.FromUint64(263),
|
||||
g.FromUint64(0),
|
||||
g.FromUint64(0),
|
||||
g.FromUint64(0),
|
||||
}
|
||||
|
||||
NEUTRAL_WEIERSTRASS = WeierstrassPoint{
|
||||
X: gFp5.FP5_ZERO,
|
||||
Y: gFp5.FP5_ZERO,
|
||||
IsInf: true,
|
||||
}
|
||||
)
|
||||
|
||||
func (p WeierstrassPoint) Equals(q WeierstrassPoint) bool {
|
||||
if p.IsInf && q.IsInf {
|
||||
return true
|
||||
}
|
||||
return gFp5.Equals(p.X, q.X) && gFp5.Equals(p.Y, q.Y)
|
||||
}
|
||||
|
||||
func (p WeierstrassPoint) Encode() gFp5.Element {
|
||||
return gFp5.Div(p.Y, gFp5.Sub(gFp5.Div(A_ECgFp5Point, gFp5.FromUint64(3)), p.X))
|
||||
}
|
||||
|
||||
func DecodeFp5AsWeierstrass(w gFp5.Element) (WeierstrassPoint, bool) {
|
||||
e := gFp5.Sub(gFp5.Square(w), A_ECgFp5Point)
|
||||
delta := gFp5.Sub(gFp5.Square(e), B_MUL4_ECgFp5Point)
|
||||
r, success := gFp5.CanonicalSqrt(delta)
|
||||
if !success {
|
||||
r = gFp5.FP5_ZERO
|
||||
}
|
||||
|
||||
x1 := gFp5.Div(gFp5.Add(e, r), gFp5.FP5_TWO)
|
||||
x2 := gFp5.Div(gFp5.Sub(e, r), gFp5.FP5_TWO)
|
||||
|
||||
x := x1
|
||||
x1Legendre := gFp5.Legendre(x1)
|
||||
if !x1Legendre.IsOne() {
|
||||
x = x2
|
||||
}
|
||||
|
||||
y := gFp5.Neg(gFp5.Mul(w, x))
|
||||
if success {
|
||||
x = gFp5.Add(x, gFp5.Div(A_ECgFp5Point, gFp5.FromUint64(3)))
|
||||
} else {
|
||||
x = gFp5.FP5_ZERO
|
||||
}
|
||||
|
||||
isInf := !success
|
||||
|
||||
// If w == 0 then this is in fact a success.
|
||||
if success || gFp5.IsZero(w) {
|
||||
return WeierstrassPoint{X: x, Y: y, IsInf: isInf}, true
|
||||
}
|
||||
return WeierstrassPoint{}, false
|
||||
}
|
||||
|
||||
func (p WeierstrassPoint) Add(q WeierstrassPoint) WeierstrassPoint {
|
||||
if p.IsInf {
|
||||
return q
|
||||
}
|
||||
if q.IsInf {
|
||||
return p
|
||||
}
|
||||
|
||||
x1, y1 := p.X, p.Y
|
||||
x2, y2 := q.X, q.Y
|
||||
|
||||
// note: paper has a typo. sx == 1 when x1 != x2, not when x1 == x2
|
||||
xSame := gFp5.Equals(x1, x2)
|
||||
yDiff := !gFp5.Equals(y1, y2)
|
||||
|
||||
var lambda0, lambda1 gFp5.Element
|
||||
if xSame {
|
||||
lambda0 = gFp5.Add(gFp5.Triple(gFp5.Square(x1)), A_WEIERSTRASS)
|
||||
lambda1 = gFp5.Double(y1)
|
||||
} else {
|
||||
lambda0 = gFp5.Sub(y2, y1)
|
||||
lambda1 = gFp5.Sub(x2, x1)
|
||||
}
|
||||
lambda := gFp5.Div(lambda0, lambda1)
|
||||
|
||||
x3 := gFp5.Sub(gFp5.Sub(gFp5.Square(lambda), x1), x2)
|
||||
y3 := gFp5.Sub(gFp5.Mul(lambda, gFp5.Sub(x1, x3)), y1)
|
||||
|
||||
return WeierstrassPoint{X: x3, Y: y3, IsInf: xSame && yDiff}
|
||||
}
|
||||
|
||||
func (p WeierstrassPoint) Double() WeierstrassPoint {
|
||||
x := p.X
|
||||
y := p.Y
|
||||
is_inf := p.IsInf
|
||||
|
||||
if is_inf {
|
||||
return p
|
||||
}
|
||||
|
||||
lambda0 := gFp5.Square(x)
|
||||
lambda0 = gFp5.Triple(lambda0)
|
||||
lambda0 = gFp5.Add(lambda0, A_WEIERSTRASS)
|
||||
|
||||
lambda1 := gFp5.Double(y)
|
||||
|
||||
lambda := gFp5.Div(lambda0, lambda1)
|
||||
|
||||
x2 := gFp5.Square(lambda)
|
||||
two_x := gFp5.Double(x)
|
||||
x2 = gFp5.Sub(x2, two_x)
|
||||
|
||||
y2 := gFp5.Sub(x, x2)
|
||||
y2 = gFp5.Mul(lambda, y2)
|
||||
y2 = gFp5.Sub(y2, y)
|
||||
|
||||
return WeierstrassPoint{X: x2, Y: y2, IsInf: is_inf}
|
||||
}
|
||||
|
||||
func (p WeierstrassPoint) PrecomputeWindow(windowBits uint32) []WeierstrassPoint {
|
||||
if windowBits < 2 {
|
||||
panic("windowBits in PrecomputeWindow for WeierstrassPoint must be at least 2")
|
||||
}
|
||||
multiples := []WeierstrassPoint{NEUTRAL_WEIERSTRASS, p, p.Double()}
|
||||
for i := 3; i < 1<<windowBits; i++ {
|
||||
multiples = append(multiples, p.Add(multiples[len(multiples)-1]))
|
||||
}
|
||||
return multiples
|
||||
}
|
||||
|
||||
func MulAdd2(a, b WeierstrassPoint, scalarA, scalarB ECgFp5Scalar) WeierstrassPoint {
|
||||
aWindow := a.PrecomputeWindow(4)
|
||||
aFourBitLimbs := scalarA.SplitTo4BitLimbs()
|
||||
|
||||
bWindow := b.PrecomputeWindow(4)
|
||||
bFourBitLimbs := scalarB.SplitTo4BitLimbs()
|
||||
|
||||
numLimbs := len(aFourBitLimbs)
|
||||
|
||||
res := aWindow[aFourBitLimbs[numLimbs-1]].Add(bWindow[bFourBitLimbs[numLimbs-1]])
|
||||
for i := numLimbs - 2; i >= 0; i-- {
|
||||
for j := 0; j < 4; j++ {
|
||||
res = res.Double()
|
||||
}
|
||||
res = res.Add(aWindow[aFourBitLimbs[i]].Add(bWindow[bFourBitLimbs[i]]))
|
||||
}
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
package field
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
|
||||
"math/big"
|
||||
"math/rand/v2"
|
||||
)
|
||||
|
||||
func TestBytes(t *testing.T) {
|
||||
e1 := g.Sample()
|
||||
|
||||
leBytes := g.ToLittleEndianBytes(e1)
|
||||
beBytes := e1.Bytes()
|
||||
for i := 0; i < g.Bytes; i++ {
|
||||
if beBytes[i] != leBytes[g.Bytes-i-1] {
|
||||
t.Fatalf("Big endian and little endian bytes are not reversed")
|
||||
}
|
||||
}
|
||||
|
||||
e1ReconstructedLE, _ := g.FromCanonicalLittleEndianBytes(leBytes)
|
||||
if !g.Equals(&e1, e1ReconstructedLE) {
|
||||
t.Fatalf("bytes do not match")
|
||||
}
|
||||
|
||||
r := rand.Uint64N(g.ORDER)
|
||||
|
||||
leBytesUint64 := make([]byte, 8)
|
||||
binary.LittleEndian.PutUint64(leBytesUint64, r)
|
||||
|
||||
leBytesElem := g.ToLittleEndianBytes(g.FromUint64(r))
|
||||
for i := 0; i < 8; i++ {
|
||||
if leBytesUint64[i] != leBytesElem[i] {
|
||||
t.Fatalf("Little-endian bytes do not match at index %d: expected %x, got %x", i, leBytesUint64[i], leBytesElem[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBytesF(t *testing.T) {
|
||||
r := rand.Uint64N(g.ORDER)
|
||||
f := g.GoldilocksField(r)
|
||||
|
||||
rBytes := make([]byte, 8)
|
||||
binary.LittleEndian.PutUint64(rBytes, r)
|
||||
|
||||
fBytes := g.ToLittleEndianBytesF(f)
|
||||
for i := 0; i < 8; i++ {
|
||||
if rBytes[i] != fBytes[i] {
|
||||
t.Fatalf("Little-endian bytes do not match at index %d: expected %x, got %x", i, rBytes[i], fBytes[i])
|
||||
}
|
||||
}
|
||||
|
||||
ff := g.FromCanonicalLittleEndianBytesF(fBytes)
|
||||
if ff != f {
|
||||
t.Fatalf("bytes do not match")
|
||||
}
|
||||
}
|
||||
|
||||
// Goldilocks field tests
|
||||
|
||||
// Inputs that covers several input ranges
|
||||
var inputs = []uint64{
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2147483638, 2147483639, 2147483640, 2147483641, 2147483642, 2147483643, 2147483644, 2147483645, 2147483646, 2147483647, 2147483648, 2147483649,
|
||||
2147483650, 2147483651, 2147483652, 2147483653, 2147483654, 2147483655, 2147483656, 2147483657, 4294967286, 4294967287, 4294967288, 4294967289, 4294967290, 4294967291,
|
||||
4294967292, 4294967293, 4294967294, 4294967295, 4294967296, 4294967297, 4294967298, 4294967299, 4294967300, 4294967301, 4294967302, 4294967303, 4294967304, 4294967305,
|
||||
9223372036854775798, 9223372036854775799, 9223372036854775800, 9223372036854775801, 9223372036854775802, 9223372036854775803, 9223372036854775804, 9223372036854775805,
|
||||
9223372036854775806, 9223372036854775807, 9223372036854775808, 9223372036854775809, 9223372036854775810, 9223372036854775811, 9223372036854775812, 9223372036854775813,
|
||||
9223372036854775814, 9223372036854775815, 9223372036854775816, 9223372036854775817, 18446744069414584311, 18446744069414584312, 18446744069414584313, 18446744069414584314,
|
||||
18446744069414584315, 18446744069414584316, 18446744069414584317, 18446744069414584318, 18446744069414584319, 18446744069414584320,
|
||||
}
|
||||
|
||||
func NewBigInt(x uint64) *big.Int {
|
||||
return big.NewInt(0).SetUint64(x)
|
||||
}
|
||||
|
||||
func SumMod(x, y uint64) uint64 {
|
||||
sum := NewBigInt(x).Add(NewBigInt(x), NewBigInt(y))
|
||||
res := sum.Mod(sum, NewBigInt(g.ORDER))
|
||||
if !res.IsUint64() {
|
||||
panic("sum is not uint64")
|
||||
}
|
||||
return res.Uint64()
|
||||
}
|
||||
|
||||
func SubMod(x, y uint64) uint64 {
|
||||
sub := NewBigInt(x).Sub(NewBigInt(x), NewBigInt(y))
|
||||
res := sub.Mod(sub, NewBigInt(g.ORDER))
|
||||
if !res.IsUint64() {
|
||||
panic("difference is not uint64")
|
||||
}
|
||||
return res.Uint64()
|
||||
}
|
||||
|
||||
func MulMod(x, y uint64) uint64 {
|
||||
mul := NewBigInt(x).Mul(NewBigInt(x), NewBigInt(y))
|
||||
res := mul.Mod(mul, NewBigInt(g.ORDER))
|
||||
if !res.IsUint64() {
|
||||
panic("product is not uint64")
|
||||
}
|
||||
return res.Uint64()
|
||||
}
|
||||
|
||||
func NegMod(x uint64) uint64 {
|
||||
neg := NewBigInt(x).Neg(NewBigInt(x))
|
||||
res := neg.Mod(neg, NewBigInt(g.ORDER))
|
||||
if !res.IsUint64() {
|
||||
panic("negative number is not uint64")
|
||||
}
|
||||
return res.Uint64()
|
||||
}
|
||||
|
||||
func SquareMod(x uint64) uint64 {
|
||||
square := NewBigInt(x).Mul(NewBigInt(x), NewBigInt(x))
|
||||
res := square.Mod(square, NewBigInt(g.ORDER))
|
||||
if !res.IsUint64() {
|
||||
panic("square is not uint64")
|
||||
}
|
||||
return res.Uint64()
|
||||
}
|
||||
|
||||
func TestAddF(t *testing.T) {
|
||||
for _, lhs := range inputs {
|
||||
for _, rhs := range inputs {
|
||||
fLhs := g.GoldilocksField(lhs)
|
||||
fRhs := g.GoldilocksField(rhs)
|
||||
sum := g.AddF(fLhs, fRhs).ToCanonicalUint64()
|
||||
expected := SumMod(lhs, rhs)
|
||||
if sum != expected {
|
||||
t.Fatalf("Expected %d + %d = %d, but got %d", lhs, rhs, expected, sum)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubF(t *testing.T) {
|
||||
for _, lhs := range inputs {
|
||||
for _, rhs := range inputs {
|
||||
fLhs := g.GoldilocksField(lhs)
|
||||
fRhs := g.GoldilocksField(rhs)
|
||||
diff := g.SubF(fLhs, fRhs).ToCanonicalUint64()
|
||||
expected := SubMod(lhs, rhs)
|
||||
if diff != expected {
|
||||
t.Fatalf("Expected %d - %d = %d, but got %d", lhs, rhs, expected, diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMulF(t *testing.T) {
|
||||
for _, lhs := range inputs {
|
||||
for _, rhs := range inputs {
|
||||
fLhs := g.GoldilocksField(lhs)
|
||||
fRhs := g.GoldilocksField(rhs)
|
||||
mul := g.MulF(fLhs, fRhs).ToCanonicalUint64()
|
||||
expected := MulMod(lhs, rhs)
|
||||
if mul != expected {
|
||||
t.Fatalf("Expected %d * %d = %d, but got %d", lhs, rhs, expected, mul)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNegF(t *testing.T) {
|
||||
for _, lhs := range inputs {
|
||||
fLhs := g.GoldilocksField(lhs)
|
||||
neg := g.NegF(fLhs).ToCanonicalUint64()
|
||||
expected := NegMod(lhs)
|
||||
if neg != expected {
|
||||
t.Fatalf("Expected Neg(%d) = %d, but got %d", lhs, expected, neg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSquareF(t *testing.T) {
|
||||
for _, lhs := range inputs {
|
||||
fLhs := g.GoldilocksField(lhs)
|
||||
sqr := g.SquareF(fLhs).ToCanonicalUint64()
|
||||
expected := SquareMod(lhs)
|
||||
if sqr != expected {
|
||||
t.Fatalf("Expected (%d)^2 = %d, but got %d", lhs, expected, sqr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubFDoubleWraparound(t *testing.T) {
|
||||
/*
|
||||
let (a, b) = (F::from_canonical_u64((F::ORDER + 1u64) / 2u64), F::TWO);
|
||||
let x = a * b;
|
||||
assert_eq!(x, F::ONE);
|
||||
assert_eq!(F::ZERO - x, F::NEG_ONE);
|
||||
*/
|
||||
|
||||
a := g.GoldilocksField((g.ORDER + 1) / 2)
|
||||
b := g.GoldilocksField(2)
|
||||
x := g.MulF(a, b)
|
||||
if x.ToCanonicalUint64() != g.OneF().ToCanonicalUint64() {
|
||||
t.Fatalf("Expected a*b to be 1, but got %v", x)
|
||||
}
|
||||
if g.SubF(g.ZeroF(), x).ToCanonicalUint64() != g.NegOneF().ToCanonicalUint64() {
|
||||
t.Fatalf("Expected 0 - x to be -1, but got %v", g.SubF(g.ZeroF(), x))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddFDoubleWraparound(t *testing.T) {
|
||||
/*
|
||||
let a = F::from_canonical_u64(u64::MAX - F::ORDER);
|
||||
let b = F::NEG_ONE;
|
||||
|
||||
let c = (a + a) + (b + b);
|
||||
let d = (a + b) + (a + b);
|
||||
|
||||
assert_eq!(c, d);
|
||||
*/
|
||||
|
||||
a := g.GoldilocksField(math.MaxUint64 - g.ORDER)
|
||||
b := g.NegOneF()
|
||||
|
||||
c := g.AddF(g.AddF(a, a), g.AddF(b, b))
|
||||
d := g.AddF(g.AddF(a, b), g.AddF(a, b))
|
||||
|
||||
if c.ToCanonicalUint64() != d.ToCanonicalUint64() {
|
||||
t.Fatalf("Expected c to be equal to d, but got %v and %v", c, d)
|
||||
}
|
||||
}
|
||||
|
||||
// Quintic extension tests
|
||||
|
||||
func TestQuinticExtensionAddSubMulSquare(t *testing.T) {
|
||||
val1 := gFp5.Element{
|
||||
g.FromUint64(0x1234567890ABCDEF),
|
||||
g.FromUint64(0x0FEDCBA987654321),
|
||||
g.FromUint64(0x1122334455667788),
|
||||
g.FromUint64(0x8877665544332211),
|
||||
g.FromUint64(0xAABBCCDDEEFF0011),
|
||||
}
|
||||
val2 := gFp5.Element{
|
||||
g.FromUint64(0xFFFFFFFFFFFFFFFF),
|
||||
g.FromUint64(0xFFFFFFFFFFFFFFFF),
|
||||
g.FromUint64(0xFFFFFFFFFFFFFFFF),
|
||||
g.FromUint64(0xFFFFFFFFFFFFFFFF),
|
||||
g.FromUint64(0xFFFFFFFFFFFFFFFF),
|
||||
}
|
||||
|
||||
add := gFp5.Add(val1, val2)
|
||||
expectedAdd := [5]uint64{1311768471589866989, 1147797413325783839, 1234605620731475846, 9833440832084189711, 12302652064957136911}
|
||||
for i := 0; i < 5; i++ {
|
||||
if add[i].Uint64() != expectedAdd[i] {
|
||||
t.Fatalf("Addition: Expected limb %d to be %x, but got %x", i, expectedAdd[i], add[i])
|
||||
}
|
||||
}
|
||||
|
||||
sub := gFp5.Sub(val1, val2)
|
||||
expectedSub := [5]uint64{1311768462999932401, 1147797404735849251, 1234605612141541258, 9833440823494255123, 12302652056367202323}
|
||||
for i := 0; i < 5; i++ {
|
||||
if sub[i].Uint64() != expectedSub[i] {
|
||||
t.Fatalf("Subtraction: Expected limb %d to be %x, but got %x", i, expectedSub[i], sub[i])
|
||||
}
|
||||
}
|
||||
|
||||
mul := gFp5.Mul(val1, val2)
|
||||
expectedMul := [5]uint64{12801331769143413385, 14031114708135177824, 4192851210753422088, 14031114723597060086, 4193451712464626164}
|
||||
for i := 0; i < 5; i++ {
|
||||
if mul[i].Uint64() != expectedMul[i] {
|
||||
t.Fatalf("Multiplication: Expected limb %d to be %x, but got %x", i, expectedMul[i], mul[i])
|
||||
}
|
||||
}
|
||||
|
||||
square := gFp5.Square(val1)
|
||||
expectedSquare := [5]uint64{
|
||||
2711468769317614959,
|
||||
15562737284369360677,
|
||||
48874032493986270,
|
||||
11211402278708723253,
|
||||
2864528669572451733,
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
if square[i].Uint64() != expectedSquare[i] {
|
||||
t.Fatalf("Square: Expected limb %d to be %x, but got %x", i, expectedSquare[i], square[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuinticExtensionAddSubMulSquareF(t *testing.T) {
|
||||
val1 := gFp5.FromPlonky2GoldilocksField([]g.GoldilocksField{
|
||||
g.GoldilocksField(0x1234567890ABCDEF),
|
||||
g.GoldilocksField(0x0FEDCBA987654321),
|
||||
g.GoldilocksField(0x1122334455667788),
|
||||
g.GoldilocksField(0x8877665544332211),
|
||||
g.GoldilocksField(0xAABBCCDDEEFF0011),
|
||||
})
|
||||
val2 := gFp5.FromPlonky2GoldilocksField([]g.GoldilocksField{
|
||||
g.GoldilocksField(0xFFFFFFFFFFFFFFFF),
|
||||
g.GoldilocksField(0xFFFFFFFFFFFFFFFF),
|
||||
g.GoldilocksField(0xFFFFFFFFFFFFFFFF),
|
||||
g.GoldilocksField(0xFFFFFFFFFFFFFFFF),
|
||||
g.GoldilocksField(0xFFFFFFFFFFFFFFFF),
|
||||
})
|
||||
|
||||
add := gFp5.Add(val1, val2)
|
||||
expectedAdd := [5]uint64{1311768471589866989, 1147797413325783839, 1234605620731475846, 9833440832084189711, 12302652064957136911}
|
||||
for i := 0; i < 5; i++ {
|
||||
if add[i].Uint64() != expectedAdd[i] {
|
||||
t.Fatalf("Addition: Expected limb %d to be %x, but got %x", i, expectedAdd[i], add[i])
|
||||
}
|
||||
}
|
||||
|
||||
sub := gFp5.Sub(val1, val2)
|
||||
expectedSub := [5]uint64{1311768462999932401, 1147797404735849251, 1234605612141541258, 9833440823494255123, 12302652056367202323}
|
||||
for i := 0; i < 5; i++ {
|
||||
if sub[i].Uint64() != expectedSub[i] {
|
||||
t.Fatalf("Subtraction: Expected limb %d to be %x, but got %x", i, expectedSub[i], sub[i])
|
||||
}
|
||||
}
|
||||
|
||||
mul := gFp5.Mul(val1, val2)
|
||||
expectedMul := [5]uint64{12801331769143413385, 14031114708135177824, 4192851210753422088, 14031114723597060086, 4193451712464626164}
|
||||
for i := 0; i < 5; i++ {
|
||||
if mul[i].Uint64() != expectedMul[i] {
|
||||
t.Fatalf("Multiplication: Expected limb %d to be %x, but got %x", i, expectedMul[i], mul[i])
|
||||
}
|
||||
}
|
||||
|
||||
square := gFp5.Square(val1)
|
||||
expectedSquare := [5]uint64{
|
||||
2711468769317614959,
|
||||
15562737284369360677,
|
||||
48874032493986270,
|
||||
11211402278708723253,
|
||||
2864528669572451733,
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
if square[i].Uint64() != expectedSquare[i] {
|
||||
t.Fatalf("Square: Expected limb %d to be %x, but got %x", i, expectedSquare[i], square[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepeatedFrobeniusgFp5(t *testing.T) {
|
||||
val := gFp5.Element{
|
||||
g.FromUint64(0x1234567890ABCDEF),
|
||||
g.FromUint64(0x0FEDCBA987654321),
|
||||
g.FromUint64(0x1122334455667788),
|
||||
g.FromUint64(0x8877665544332211),
|
||||
g.FromUint64(0xAABBCCDDEEFF0011),
|
||||
}
|
||||
|
||||
res := gFp5.RepeatedFrobenius(val, 1)
|
||||
|
||||
expected := [5]uint64{
|
||||
1311768467294899695,
|
||||
5234265561494296110,
|
||||
6204816484784411482,
|
||||
8858034429214283719,
|
||||
17855579289599571296,
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
if res[i] != g.FromUint64(expected[i]) {
|
||||
t.Fatalf("Assertion failed at index %d: expected %d, got %d", i, expected[i], res[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTryInverse(t *testing.T) {
|
||||
val := gFp5.Element{
|
||||
g.FromUint64(0x1234567890ABCDEF),
|
||||
g.FromUint64(0x0FEDCBA987654321),
|
||||
g.FromUint64(0x1122334455667788),
|
||||
g.FromUint64(0x8877665544332211),
|
||||
g.FromUint64(0xAABBCCDDEEFF0011),
|
||||
}
|
||||
result := gFp5.InverseOrZero(val)
|
||||
|
||||
// Expected values
|
||||
expected := [5]uint64{
|
||||
10760985268447604442,
|
||||
1770001646280707407,
|
||||
826117924202660585,
|
||||
45414427571889187,
|
||||
8256636258983026155,
|
||||
}
|
||||
|
||||
for i, elem := range result.ToBasefieldArray() {
|
||||
if elem.Uint64() != expected[i] {
|
||||
t.Fatalf("Assertion failed at index %d: expected %d, got %d", i, expected[i], elem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuinticExtSgn0(t *testing.T) {
|
||||
if !gFp5.Sgn0(gFp5.Element{
|
||||
g.FromUint64(7146494650688613286),
|
||||
g.FromUint64(2524706331227574337),
|
||||
g.FromUint64(2805008444831673606),
|
||||
g.FromUint64(10342159727506097401),
|
||||
g.FromUint64(5582307593199735986),
|
||||
}) {
|
||||
t.Fatalf("Expected sign to be true, but got false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSqrtFunctions(t *testing.T) {
|
||||
x := gFp5.Element{
|
||||
g.FromUint64(17397692312497920520),
|
||||
g.FromUint64(4597259071399531684),
|
||||
g.FromUint64(15835726694542307225),
|
||||
g.FromUint64(16979717054676631815),
|
||||
g.FromUint64(12876043227925845432),
|
||||
}
|
||||
|
||||
expected := gFp5.Element{
|
||||
g.FromUint64(16260118390353633405),
|
||||
g.FromUint64(2204473665618140400),
|
||||
g.FromUint64(10421517006653550782),
|
||||
g.FromUint64(4618467884536173852),
|
||||
g.FromUint64(15556190572415033139),
|
||||
}
|
||||
|
||||
result, exists := gFp5.CanonicalSqrt(x)
|
||||
if !exists {
|
||||
t.Fatalf("Expected canonical sqrt to exist, but it does not")
|
||||
}
|
||||
|
||||
if !gFp5.Equals(result, expected) {
|
||||
t.Fatalf("Expected canonical sqrt to be %v, but got %v", expected, result)
|
||||
}
|
||||
|
||||
result2, exists2 := gFp5.Sqrt(x)
|
||||
if !exists2 {
|
||||
t.Fatalf("Expected sqrt to exist, but it does not")
|
||||
}
|
||||
|
||||
if !gFp5.Equals(result2, expected) {
|
||||
t.Fatalf("Expected sqrt to be %v, but got %v", expected, result2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSqrtNonExistent(t *testing.T) {
|
||||
_, exists := gFp5.Sqrt(gFp5.Element{
|
||||
g.FromUint64(3558249639744866495),
|
||||
g.FromUint64(2615658757916804776),
|
||||
g.FromUint64(14375546700029059319),
|
||||
g.FromUint64(16160052538060569780),
|
||||
g.FromUint64(8366525948816396307),
|
||||
})
|
||||
if exists {
|
||||
t.Fatalf("Expected sqrt not to exist, but it does")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegendre(t *testing.T) {
|
||||
// Test zero
|
||||
zeroLegendre := gFp5.Legendre(gFp5.FP5_ZERO)
|
||||
if !zeroLegendre.IsZero() {
|
||||
t.Fatalf("Expected Legendre symbol of zero to be zero")
|
||||
}
|
||||
|
||||
// Test non-squares
|
||||
for i := 0; i < 32; i++ {
|
||||
var x gFp5.Element
|
||||
for {
|
||||
attempt := gFp5.Sample()
|
||||
if _, exists := gFp5.Sqrt(attempt); !exists {
|
||||
x = attempt
|
||||
break
|
||||
}
|
||||
}
|
||||
legendreSym := gFp5.Legendre(x)
|
||||
|
||||
negOne := g.NegOne()
|
||||
|
||||
if !negOne.Equal(&legendreSym) {
|
||||
t.Fatalf("Expected Legendre symbol of non-square to be -1, but got %v", legendreSym)
|
||||
}
|
||||
}
|
||||
|
||||
// Test squares
|
||||
for i := 0; i < 32; i++ {
|
||||
x := gFp5.Sample()
|
||||
square := gFp5.Square(x)
|
||||
legendreSym := gFp5.Legendre(square)
|
||||
|
||||
if !legendreSym.IsOne() {
|
||||
t.Fatalf("Expected Legendre symbol of square to be 1, but got %v", legendreSym)
|
||||
}
|
||||
}
|
||||
|
||||
// Test zero again
|
||||
x := gFp5.FP5_ZERO
|
||||
square := gFp5.Mul(x, x)
|
||||
legendreSym := gFp5.Legendre(square)
|
||||
if !legendreSym.IsZero() {
|
||||
t.Fatalf("Expected Legendre symbol of zero to be zero")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package goldilocks
|
||||
|
||||
//go:noescape
|
||||
func branchHint()
|
||||
@@ -0,0 +1,3 @@
|
||||
TEXT ·branchHint(SB),$0
|
||||
NOP
|
||||
RET
|
||||
@@ -0,0 +1,198 @@
|
||||
package goldilocks
|
||||
|
||||
// Partially wraps and extends the functionality of the goldilocks field package.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
g "github.com/consensys/gnark-crypto/field/goldilocks"
|
||||
)
|
||||
|
||||
type Element = g.Element
|
||||
|
||||
const Bytes = 8
|
||||
|
||||
func NewElement(value uint64) Element {
|
||||
return g.NewElement(value)
|
||||
}
|
||||
|
||||
func reverseBytes(b []byte) []byte {
|
||||
res := make([]byte, len(b))
|
||||
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
|
||||
res[i], res[j] = b[j], b[i]
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func ArrayFromCanonicalLittleEndianBytes(in []byte) ([]Element, error) {
|
||||
missing := 8 - len(in)%8
|
||||
if missing == 8 {
|
||||
missing = 0
|
||||
}
|
||||
|
||||
ret := make([]Element, 0)
|
||||
for i := 0; i < len(in); {
|
||||
nextStart := i + 8
|
||||
|
||||
if nextStart > len(in) {
|
||||
nextStart = len(in)
|
||||
}
|
||||
|
||||
slice := make([]byte, 8)
|
||||
copy(slice[:], in[i:nextStart])
|
||||
if len(slice) < 8 {
|
||||
slice = append(slice, make([]byte, missing)...)
|
||||
}
|
||||
|
||||
elem, err := FromCanonicalLittleEndianBytes(slice)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to convert bytes to field element. bytes: %v, error: %w", slice, err)
|
||||
}
|
||||
ret = append(ret, *elem)
|
||||
i = nextStart
|
||||
}
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
func ToLittleEndianBytes(e ...Element) []byte {
|
||||
res := make([]byte, 0)
|
||||
for _, elem := range e {
|
||||
bytes := elem.Bytes()
|
||||
res = append(res, reverseBytes(bytes[:])...)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func FromCanonicalLittleEndianBytes(in []byte) (*Element, error) {
|
||||
elem := g.NewElement(0)
|
||||
err := elem.SetBytesCanonical(reverseBytes(in))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to convert bytes to field element: %w", err)
|
||||
}
|
||||
return &elem, nil
|
||||
}
|
||||
|
||||
func ArrayToLittleEndianBytes(e []Element) []byte {
|
||||
res := make([]byte, 0)
|
||||
for _, elem := range e {
|
||||
res = append(res, ToLittleEndianBytes(elem)...)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func ToString(e ...Element) string {
|
||||
res := ""
|
||||
for _, elem := range e {
|
||||
res += elem.String() + " "
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func FromBool(value bool) Element {
|
||||
if value {
|
||||
return One()
|
||||
}
|
||||
return Zero()
|
||||
}
|
||||
|
||||
func FromInt64Abs(value int64) Element {
|
||||
return FromUint64(uint64(value & 0x7FFFFFFFFFFFFFFF))
|
||||
}
|
||||
|
||||
func FromInt64(value int64) Element {
|
||||
elem := g.NewElement(0)
|
||||
elem.SetInt64(value)
|
||||
return elem
|
||||
}
|
||||
|
||||
func FromUint64(value uint64) Element {
|
||||
elem := g.NewElement(0)
|
||||
elem.SetUint64(value)
|
||||
return elem
|
||||
}
|
||||
|
||||
func FromUint32(value uint32) Element {
|
||||
return FromUint64(uint64(value))
|
||||
}
|
||||
|
||||
func Equals(a, b *Element) bool {
|
||||
return a.Equal(b)
|
||||
}
|
||||
|
||||
func Modulus() uint64 {
|
||||
return g.Modulus().Uint64()
|
||||
}
|
||||
|
||||
func Zero() Element {
|
||||
return g.NewElement(0)
|
||||
}
|
||||
|
||||
func One() Element {
|
||||
return g.NewElement(1)
|
||||
}
|
||||
|
||||
func Neg(e Element) Element {
|
||||
res := g.NewElement(0)
|
||||
res.Neg(&e)
|
||||
return res
|
||||
}
|
||||
|
||||
func NegOne() *Element {
|
||||
res := Neg(One())
|
||||
return &res
|
||||
}
|
||||
|
||||
func Sample() Element {
|
||||
elem := g.NewElement(0)
|
||||
elem.SetRandom()
|
||||
return elem
|
||||
}
|
||||
|
||||
func RandArray(count int) []Element {
|
||||
ret := make([]Element, count)
|
||||
for i := 0; i < count; i++ {
|
||||
ret[i] = Sample()
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func Add(elems ...Element) Element {
|
||||
res := g.NewElement(0)
|
||||
for _, elem := range elems {
|
||||
res.Add(&res, &elem)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func Sub(a, b *Element) Element {
|
||||
res := g.NewElement(0)
|
||||
res.Sub(a, b)
|
||||
return res
|
||||
}
|
||||
|
||||
func Mul(elems ...*Element) Element {
|
||||
res := g.NewElement(1)
|
||||
for _, elem := range elems {
|
||||
res.Mul(&res, elem)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func Sqrt(elem *Element) *Element {
|
||||
elemCopy := DeepCopy(elem)
|
||||
return elemCopy.Sqrt(&elemCopy)
|
||||
}
|
||||
|
||||
// Powers starting from 1
|
||||
func Powers(e *Element, count int) []Element {
|
||||
ret := make([]Element, count)
|
||||
ret[0] = g.One()
|
||||
for i := 1; i < int(count); i++ {
|
||||
ret[i].Mul(&ret[i-1], e)
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func DeepCopy(source *Element) Element {
|
||||
return Element{source[0]}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package goldilocks
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"math/big"
|
||||
"math/bits"
|
||||
)
|
||||
|
||||
type GoldilocksField uint64
|
||||
|
||||
const EPSILON = uint64((1 << 32) - 1)
|
||||
const ORDER = uint64(0xffffffff00000001)
|
||||
|
||||
var ORDER_BIG, _ = new(big.Int).SetString("0xffffffff00000001", 16)
|
||||
|
||||
func NonCannonicalGoldilocksField(x int64) GoldilocksField {
|
||||
if x < 0 {
|
||||
return NegF(GoldilocksField(-x))
|
||||
}
|
||||
|
||||
return GoldilocksField(x)
|
||||
}
|
||||
|
||||
func ZeroF() GoldilocksField {
|
||||
return 0
|
||||
}
|
||||
|
||||
func OneF() GoldilocksField {
|
||||
return 1
|
||||
}
|
||||
|
||||
func NegOneF() GoldilocksField {
|
||||
return GoldilocksField(ORDER - 1)
|
||||
}
|
||||
|
||||
func (z GoldilocksField) IsZero() bool {
|
||||
return z.ToCanonicalUint64() == 0
|
||||
}
|
||||
|
||||
func (z GoldilocksField) ToCanonicalUint64() uint64 {
|
||||
x := uint64(z)
|
||||
if x >= ORDER {
|
||||
x -= ORDER
|
||||
}
|
||||
|
||||
return x
|
||||
}
|
||||
|
||||
func AddF(lhs, rhs GoldilocksField) GoldilocksField {
|
||||
sum, over := bits.Add64(uint64(lhs), uint64(rhs), 0)
|
||||
sum, over = bits.Add64(sum, over*EPSILON, 0)
|
||||
if over == 1 {
|
||||
branchHint()
|
||||
sum += EPSILON // this can't overflow
|
||||
}
|
||||
|
||||
return GoldilocksField(sum)
|
||||
}
|
||||
|
||||
func DoubleF(lhs GoldilocksField) GoldilocksField {
|
||||
return AddF(lhs, lhs)
|
||||
}
|
||||
|
||||
func SubF(lhs, rhs GoldilocksField) GoldilocksField {
|
||||
diff, borrow := bits.Sub64(uint64(lhs), uint64(rhs), 0)
|
||||
diff, borrow = bits.Sub64(diff, borrow*EPSILON, 0)
|
||||
if borrow == 1 {
|
||||
branchHint()
|
||||
diff -= EPSILON // this can't underflow
|
||||
}
|
||||
|
||||
return GoldilocksField(diff)
|
||||
}
|
||||
|
||||
func MulF(lhs, rhs GoldilocksField) GoldilocksField {
|
||||
x_hi, x_lo := bits.Mul64(uint64(lhs), uint64(rhs))
|
||||
|
||||
x_hi_hi := x_hi >> 32
|
||||
x_hi_lo := x_hi & EPSILON
|
||||
|
||||
t0, borrow := bits.Sub64(x_lo, x_hi_hi, 0)
|
||||
if borrow == 1 {
|
||||
branchHint()
|
||||
t0 -= EPSILON
|
||||
}
|
||||
t1 := x_hi_lo * EPSILON
|
||||
|
||||
sum, over := bits.Add64(t0, t1, 0)
|
||||
t2 := sum + EPSILON*over
|
||||
return GoldilocksField(t2)
|
||||
}
|
||||
|
||||
func SquareF(x GoldilocksField) GoldilocksField {
|
||||
return MulF(x, x)
|
||||
}
|
||||
|
||||
func ExpPowerOf2(x GoldilocksField, n uint) GoldilocksField {
|
||||
z := x
|
||||
for i := uint(0); i < n; i++ {
|
||||
z = SquareF(z)
|
||||
}
|
||||
|
||||
return z
|
||||
}
|
||||
|
||||
func NegF(x GoldilocksField) GoldilocksField {
|
||||
z := GoldilocksField(0)
|
||||
if !x.IsZero() {
|
||||
z = GoldilocksField(ORDER - x.ToCanonicalUint64())
|
||||
}
|
||||
|
||||
return z
|
||||
}
|
||||
|
||||
func SampleF() GoldilocksField {
|
||||
rng, err := rand.Int(rand.Reader, ORDER_BIG)
|
||||
if err != nil {
|
||||
panic("failed to read random bytes into buffer")
|
||||
}
|
||||
return GoldilocksField(rng.Uint64())
|
||||
}
|
||||
|
||||
func ToLittleEndianBytesF(z GoldilocksField) []byte {
|
||||
res := make([]byte, Bytes)
|
||||
binary.LittleEndian.PutUint64(res, z.ToCanonicalUint64())
|
||||
return res
|
||||
}
|
||||
|
||||
func FromCanonicalLittleEndianBytesF(b []byte) GoldilocksField {
|
||||
return GoldilocksField(binary.LittleEndian.Uint64(b))
|
||||
}
|
||||
|
||||
// func (z *GoldilocksField) Inverse(x *GoldilocksField) *GoldilocksField {
|
||||
// if x.IsZero() {
|
||||
// z.SetZero()
|
||||
// return z
|
||||
// }
|
||||
|
||||
// var tmp *GoldilocksField
|
||||
|
||||
// t2 := *tmp.Square(x).Mul(tmp, x)
|
||||
// t3 := *tmp.Square(&t2).Mul(tmp, x)
|
||||
// t6 := *tmp.ExpPowerOf2(&t3, 3).Mul(tmp, &t3)
|
||||
// t12 := *tmp.ExpPowerOf2(&t6, 6).Mul(tmp, &t6)
|
||||
// t24 := *tmp.ExpPowerOf2(&t12, 12).Mul(tmp, &t12)
|
||||
// t30 := *tmp.ExpPowerOf2(&t24, 6).Mul(tmp, &t6)
|
||||
// t31 := *tmp.Square(&t30).Mul(tmp, x)
|
||||
// t63 := *tmp.ExpPowerOf2(&t31, 32).Mul(tmp, &t31)
|
||||
|
||||
// z.Square(&t63).Mul(z, x)
|
||||
|
||||
// return z
|
||||
// }
|
||||
+393
@@ -0,0 +1,393 @@
|
||||
package goldilocks_quintic_extension
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
)
|
||||
|
||||
type Element [5]g.Element
|
||||
|
||||
type NumericalElement [5]uint64
|
||||
|
||||
const Bytes = g.Bytes * 5
|
||||
|
||||
var (
|
||||
FP5_D = 5
|
||||
|
||||
FP5_ZERO = Element{g.Zero(), g.Zero(), g.Zero(), g.Zero(), g.Zero()}
|
||||
FP5_ONE = Element{g.One(), g.Zero(), g.Zero(), g.Zero(), g.Zero()}
|
||||
FP5_TWO = FromF(g.FromUint64(2))
|
||||
|
||||
FP5_W = g.FromUint64(3)
|
||||
FP5_DTH_ROOT = g.FromUint64(1041288259238279555)
|
||||
)
|
||||
|
||||
func (e *Element) ToString() string {
|
||||
return fmt.Sprintf("%d,%d,%d,%d,%d", e[0].Uint64(), e[1].Uint64(), e[2].Uint64(), e[3].Uint64(), e[4].Uint64())
|
||||
}
|
||||
|
||||
func (e Element) ToUint64Array() [5]uint64 {
|
||||
return [5]uint64{e[0].Uint64(), e[1].Uint64(), e[2].Uint64(), e[3].Uint64(), e[4].Uint64()}
|
||||
}
|
||||
|
||||
func gFp5FromUint64Array(arr [5]uint64) Element {
|
||||
return Element{g.FromUint64(arr[0]), g.FromUint64(arr[1]), g.FromUint64(arr[2]), g.FromUint64(arr[3]), g.FromUint64(arr[4])}
|
||||
}
|
||||
|
||||
func (e Element) ToBasefieldArray() [5]g.Element {
|
||||
return [5]g.Element{e[0], e[1], e[2], e[3], e[4]}
|
||||
}
|
||||
|
||||
func gFp5FromBasefieldArray(arr [5]g.Element) Element {
|
||||
return Element{arr[0], arr[1], arr[2], arr[3], arr[4]}
|
||||
}
|
||||
|
||||
func (e Element) ToLittleEndianBytes() []byte {
|
||||
elemBytes := [Bytes]byte{}
|
||||
for i, limb := range e {
|
||||
copy(elemBytes[i*g.Bytes:], g.ToLittleEndianBytes(limb))
|
||||
}
|
||||
return elemBytes[:]
|
||||
}
|
||||
|
||||
func FromCanonicalLittleEndianBytes(in []byte) (Element, error) {
|
||||
if len(in) != Bytes {
|
||||
return Element{}, fmt.Errorf("input bytes len should be 40 but is %d", len(in))
|
||||
}
|
||||
|
||||
elemBytesLittleEndian := [5][]byte{
|
||||
{in[0], in[1], in[2], in[3], in[4], in[5], in[6], in[7]},
|
||||
{in[8], in[9], in[10], in[11], in[12], in[13], in[14], in[15]},
|
||||
{in[16], in[17], in[18], in[19], in[20], in[21], in[22], in[23]},
|
||||
{in[24], in[25], in[26], in[27], in[28], in[29], in[30], in[31]},
|
||||
{in[32], in[33], in[34], in[35], in[36], in[37], in[38], in[39]},
|
||||
}
|
||||
|
||||
e1, err := g.FromCanonicalLittleEndianBytes(elemBytesLittleEndian[0])
|
||||
if err != nil {
|
||||
return Element{}, fmt.Errorf("failed to convert bytes to field element: %w", err)
|
||||
}
|
||||
e2, err := g.FromCanonicalLittleEndianBytes(elemBytesLittleEndian[1])
|
||||
if err != nil {
|
||||
return Element{}, fmt.Errorf("failed to convert bytes to field element: %w", err)
|
||||
}
|
||||
e3, err := g.FromCanonicalLittleEndianBytes(elemBytesLittleEndian[2])
|
||||
if err != nil {
|
||||
return Element{}, fmt.Errorf("failed to convert bytes to field element: %w", err)
|
||||
}
|
||||
e4, err := g.FromCanonicalLittleEndianBytes(elemBytesLittleEndian[3])
|
||||
if err != nil {
|
||||
return Element{}, fmt.Errorf("failed to convert bytes to field element: %w", err)
|
||||
}
|
||||
e5, err := g.FromCanonicalLittleEndianBytes(elemBytesLittleEndian[4])
|
||||
if err != nil {
|
||||
return Element{}, fmt.Errorf("failed to convert bytes to field element: %w", err)
|
||||
}
|
||||
|
||||
return Element{*e1, *e2, *e3, *e4, *e5}, nil
|
||||
}
|
||||
|
||||
func Sample() Element {
|
||||
arr := g.RandArray(5)
|
||||
return Element{arr[0], arr[1], arr[2], arr[3], arr[4]}
|
||||
}
|
||||
|
||||
func Equals(a, b Element) bool {
|
||||
return a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3] && a[4] == b[4]
|
||||
}
|
||||
|
||||
func IsZero(e Element) bool {
|
||||
return e[0].IsZero() && e[1].IsZero() && e[2].IsZero() && e[3].IsZero() && e[4].IsZero()
|
||||
}
|
||||
|
||||
func FromF(elem g.Element) Element {
|
||||
return Element{elem, g.Zero(), g.Zero(), g.Zero(), g.Zero()}
|
||||
}
|
||||
|
||||
func FromUint64(a uint64) Element {
|
||||
return Element{g.FromUint64(a), g.Zero(), g.Zero(), g.Zero(), g.Zero()}
|
||||
}
|
||||
|
||||
func FromUint64Array(elems [5]uint64) Element {
|
||||
return Element{
|
||||
g.FromUint64(elems[0]),
|
||||
g.FromUint64(elems[1]),
|
||||
g.FromUint64(elems[2]),
|
||||
g.FromUint64(elems[3]),
|
||||
g.FromUint64(elems[4]),
|
||||
}
|
||||
}
|
||||
|
||||
func Neg(e Element) Element {
|
||||
return Element{g.Neg(e[0]), g.Neg(e[1]), g.Neg(e[2]), g.Neg(e[3]), g.Neg(e[4])}
|
||||
}
|
||||
|
||||
func Add(a, b Element) Element {
|
||||
return Element{
|
||||
g.Add(a[0], b[0]),
|
||||
g.Add(a[1], b[1]),
|
||||
g.Add(a[2], b[2]),
|
||||
g.Add(a[3], b[3]),
|
||||
g.Add(a[4], b[4]),
|
||||
}
|
||||
}
|
||||
|
||||
func Sub(a, b Element) Element {
|
||||
return Element{
|
||||
g.Sub(&a[0], &b[0]),
|
||||
g.Sub(&a[1], &b[1]),
|
||||
g.Sub(&a[2], &b[2]),
|
||||
g.Sub(&a[3], &b[3]),
|
||||
g.Sub(&a[4], &b[4]),
|
||||
}
|
||||
}
|
||||
|
||||
func Mul(a, b Element) Element {
|
||||
w := FP5_W
|
||||
|
||||
a0b0 := g.Mul(&a[0], &b[0])
|
||||
a1b4 := g.Mul(&a[1], &b[4])
|
||||
a2b3 := g.Mul(&a[2], &b[3])
|
||||
a3b2 := g.Mul(&a[3], &b[2])
|
||||
a4b1 := g.Mul(&a[4], &b[1])
|
||||
added := g.Add(a1b4, a2b3, a3b2, a4b1)
|
||||
muld := g.Mul(&w, &added)
|
||||
c0 := g.Add(a0b0, muld)
|
||||
|
||||
a0b1 := g.Mul(&a[0], &b[1])
|
||||
a1b0 := g.Mul(&a[1], &b[0])
|
||||
a2b4 := g.Mul(&a[2], &b[4])
|
||||
a3b3 := g.Mul(&a[3], &b[3])
|
||||
a4b2 := g.Mul(&a[4], &b[2])
|
||||
added = g.Add(a2b4, a3b3, a4b2)
|
||||
muld = g.Mul(&w, &added)
|
||||
c1 := g.Add(a0b1, a1b0, muld)
|
||||
|
||||
a0b2 := g.Mul(&a[0], &b[2])
|
||||
a1b1 := g.Mul(&a[1], &b[1])
|
||||
a2b0 := g.Mul(&a[2], &b[0])
|
||||
a3b4 := g.Mul(&a[3], &b[4])
|
||||
a4b3 := g.Mul(&a[4], &b[3])
|
||||
added = g.Add(a3b4, a4b3)
|
||||
muld = g.Mul(&w, &added)
|
||||
c2 := g.Add(a0b2, a1b1, a2b0, muld)
|
||||
|
||||
a0b3 := g.Mul(&a[0], &b[3])
|
||||
a1b2 := g.Mul(&a[1], &b[2])
|
||||
a2b1 := g.Mul(&a[2], &b[1])
|
||||
a3b0 := g.Mul(&a[3], &b[0])
|
||||
a4b4 := g.Mul(&a[4], &b[4])
|
||||
muld = g.Mul(&w, &a4b4)
|
||||
c3 := g.Add(a0b3, a1b2, a2b1, a3b0, muld)
|
||||
|
||||
a0b4 := g.Mul(&a[0], &b[4])
|
||||
a1b3 := g.Mul(&a[1], &b[3])
|
||||
a2b2 := g.Mul(&a[2], &b[2])
|
||||
a3b1 := g.Mul(&a[3], &b[1])
|
||||
a4b0 := g.Mul(&a[4], &b[0])
|
||||
c4 := g.Add(a0b4, a1b3, a2b2, a3b1, a4b0)
|
||||
|
||||
return Element{c0, c1, c2, c3, c4}
|
||||
}
|
||||
|
||||
func Div(a, b Element) Element {
|
||||
bInv := InverseOrZero(b)
|
||||
if IsZero(bInv) {
|
||||
panic("division by zero")
|
||||
}
|
||||
return Mul(a, bInv)
|
||||
}
|
||||
|
||||
func ExpPowerOf2(x Element, power int) Element {
|
||||
res := Element{x[0], x[1], x[2], x[3], x[4]}
|
||||
for i := 0; i < power; i++ {
|
||||
res = Square(res)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func Square(a Element) Element {
|
||||
w := FP5_W
|
||||
double_w := g.Add(w, w)
|
||||
|
||||
a0s := g.Mul(&a[0], &a[0])
|
||||
a1a4 := g.Mul(&a[1], &a[4])
|
||||
a2a3 := g.Mul(&a[2], &a[3])
|
||||
added := g.Add(a1a4, a2a3)
|
||||
muld := g.Mul(&double_w, &added)
|
||||
c0 := g.Add(a0s, muld)
|
||||
|
||||
a0Double := g.Add(a[0], a[0])
|
||||
a0Doublea1 := g.Mul(&a0Double, &a[1])
|
||||
a2a4DoubleW := g.Mul(&a[2], &a[4], &double_w)
|
||||
a3a3w := g.Mul(&a[3], &a[3], &w)
|
||||
c1 := g.Add(a0Doublea1, a2a4DoubleW, a3a3w)
|
||||
|
||||
a0Doublea2 := g.Mul(&a0Double, &a[2])
|
||||
a1Square := g.Mul(&a[1], &a[1])
|
||||
a4a3DoubleW := g.Mul(&a[4], &a[3], &double_w)
|
||||
c2 := g.Add(a0Doublea2, a1Square, a4a3DoubleW)
|
||||
|
||||
a1Double := g.Add(a[1], a[1])
|
||||
a0Doublea3 := g.Mul(&a0Double, &a[3])
|
||||
a1Doublea2 := g.Mul(&a1Double, &a[2])
|
||||
a4SquareW := g.Mul(&a[4], &a[4], &w)
|
||||
c3 := g.Add(a0Doublea3, a1Doublea2, a4SquareW)
|
||||
|
||||
a0Doublea4 := g.Mul(&a0Double, &a[4])
|
||||
a1Doublea3 := g.Mul(&a1Double, &a[3])
|
||||
a2Square := g.Mul(&a[2], &a[2])
|
||||
c4 := g.Add(a0Doublea4, a1Doublea3, a2Square)
|
||||
|
||||
return Element{c0, c1, c2, c3, c4}
|
||||
}
|
||||
|
||||
func Triple(a Element) Element {
|
||||
three := g.FromUint64(3)
|
||||
return Element{
|
||||
g.Mul(&a[0], &three),
|
||||
g.Mul(&a[1], &three),
|
||||
g.Mul(&a[2], &three),
|
||||
g.Mul(&a[3], &three),
|
||||
g.Mul(&a[4], &three),
|
||||
}
|
||||
}
|
||||
|
||||
func Sqrt(x Element) (Element, bool) {
|
||||
v := ExpPowerOf2(x, 31)
|
||||
d := Mul(Mul(x, ExpPowerOf2(v, 32)), InverseOrZero(v))
|
||||
e := Frobenius(Mul(d, RepeatedFrobenius(d, 2)))
|
||||
_f := Square(e)
|
||||
|
||||
x1f4 := g.Mul(&x[1], &_f[4])
|
||||
x2f3 := g.Mul(&x[2], &_f[3])
|
||||
x3f2 := g.Mul(&x[3], &_f[2])
|
||||
x4f1 := g.Mul(&x[4], &_f[1])
|
||||
added := g.Add(x1f4, x2f3, x3f2, x4f1)
|
||||
three := g.FromUint64(3)
|
||||
muld := g.Mul(&three, &added)
|
||||
x0f0 := g.Mul(&x[0], &_f[0])
|
||||
_g := g.Add(x0f0, muld)
|
||||
s := g.Sqrt(&_g)
|
||||
if s == nil {
|
||||
return Element{}, false
|
||||
}
|
||||
|
||||
eInv := InverseOrZero(e)
|
||||
sFp5 := FromF(*s)
|
||||
|
||||
return Mul(sFp5, eInv), true
|
||||
}
|
||||
|
||||
func Sgn0(x Element) bool {
|
||||
sign := false
|
||||
zero := true
|
||||
for _, limb := range x {
|
||||
sign_i := (limb.Uint64() & 1) == 0
|
||||
zero_i := limb.IsZero()
|
||||
sign = sign || (zero && sign_i)
|
||||
zero = zero && zero_i
|
||||
}
|
||||
return sign
|
||||
}
|
||||
|
||||
func CanonicalSqrt(x Element) (Element, bool) {
|
||||
sqrtX, exists := Sqrt(x)
|
||||
if !exists {
|
||||
return Element{}, false
|
||||
}
|
||||
|
||||
if Sgn0(sqrtX) {
|
||||
return Neg(sqrtX), true
|
||||
}
|
||||
return sqrtX, true
|
||||
}
|
||||
|
||||
func ScalarMul(a Element, scalar g.Element) Element {
|
||||
return Element{
|
||||
g.Mul(&a[0], &scalar),
|
||||
g.Mul(&a[1], &scalar),
|
||||
g.Mul(&a[2], &scalar),
|
||||
g.Mul(&a[3], &scalar),
|
||||
g.Mul(&a[4], &scalar),
|
||||
}
|
||||
}
|
||||
|
||||
func Double(a Element) Element {
|
||||
return Add(a, a)
|
||||
}
|
||||
|
||||
func InverseOrZero(a Element) Element {
|
||||
if IsZero(a) {
|
||||
return FP5_ZERO
|
||||
}
|
||||
|
||||
d := Frobenius(a)
|
||||
e := Mul(d, Frobenius(d))
|
||||
f := Mul(e, RepeatedFrobenius(e, 2))
|
||||
|
||||
a0b0 := g.Mul(&a[0], &f[0])
|
||||
a1b4 := g.Mul(&a[1], &f[4])
|
||||
a2b3 := g.Mul(&a[2], &f[3])
|
||||
a3b2 := g.Mul(&a[3], &f[2])
|
||||
a4b1 := g.Mul(&a[4], &f[1])
|
||||
added := g.Add(a1b4, a2b3, a3b2, a4b1)
|
||||
muld := g.Mul(&FP5_W, &added)
|
||||
g := g.Add(a0b0, muld)
|
||||
|
||||
return ScalarMul(f, *g.Inverse(&g))
|
||||
}
|
||||
|
||||
func Frobenius(x Element) Element {
|
||||
return RepeatedFrobenius(x, 1)
|
||||
}
|
||||
|
||||
func RepeatedFrobenius(x Element, count int) Element {
|
||||
if count == 0 {
|
||||
return x
|
||||
} else if count >= FP5_D {
|
||||
return RepeatedFrobenius(x, count%FP5_D)
|
||||
}
|
||||
|
||||
z0 := FP5_DTH_ROOT
|
||||
for i := 1; i < count; i++ {
|
||||
z0 = g.Mul(&FP5_DTH_ROOT, &z0)
|
||||
}
|
||||
|
||||
res := Element{}
|
||||
for i, z := range g.Powers(&z0, FP5_D) {
|
||||
res[i] = g.Mul(&x[i], &z)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func Legendre(x Element) g.Element {
|
||||
frob1 := Frobenius(x)
|
||||
frob2 := Frobenius(frob1)
|
||||
|
||||
frob1TimesFrob2 := Mul(frob1, frob2)
|
||||
frob2Frob1TimesFrob2 := RepeatedFrobenius(frob1TimesFrob2, 2)
|
||||
|
||||
xrExt := Mul(Mul(x, frob1TimesFrob2), frob2Frob1TimesFrob2)
|
||||
xr := g.FromUint64(xrExt[0].Uint64())
|
||||
|
||||
xr31 := xr.Exp(xr, new(big.Int).SetUint64(1<<31))
|
||||
xr31InvOrZero := g.FromUint64(0)
|
||||
xr31InvOrZero = *xr31InvOrZero.Inverse(xr31)
|
||||
|
||||
xr63 := xr31.Exp(*xr31, new(big.Int).SetUint64(1<<32))
|
||||
|
||||
return g.Mul(xr63, &xr31InvOrZero)
|
||||
}
|
||||
|
||||
func FromPlonky2GoldilocksField(f []g.GoldilocksField) Element {
|
||||
return Element{
|
||||
g.NewElement(uint64(f[0])),
|
||||
g.NewElement(uint64(f[1])),
|
||||
g.NewElement(uint64(f[2])),
|
||||
g.NewElement(uint64(f[3])),
|
||||
g.NewElement(uint64(f[4])),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
module github.com/elliottech/poseidon_crypto
|
||||
|
||||
go 1.22
|
||||
|
||||
require (
|
||||
github.com/consensys/gnark-crypto v0.12.2-0.20240215234832-d72fcb379d3e
|
||||
github.com/stretchr/testify v1.9.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bits-and-blooms/bitset v1.14.2 // indirect
|
||||
github.com/consensys/bavard v0.1.13 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/mmcloughlin/addchain v0.4.0 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/rogpeppe/go-internal v1.11.0 // indirect
|
||||
golang.org/x/sys v0.24.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
rsc.io/tmplfunc v0.0.3 // indirect
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
github.com/bits-and-blooms/bitset v1.14.2 h1:YXVoyPndbdvcEVcseEovVfp0qjJp7S+i5+xgp/Nfbdc=
|
||||
github.com/bits-and-blooms/bitset v1.14.2/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
|
||||
github.com/consensys/bavard v0.1.13 h1:oLhMLOFGTLdlda/kma4VOJazblc7IM5y5QPd2A/YjhQ=
|
||||
github.com/consensys/bavard v0.1.13/go.mod h1:9ItSMtA/dXMAiL7BG6bqW2m3NdSEObYWoH223nGHukI=
|
||||
github.com/consensys/gnark-crypto v0.12.2-0.20240215234832-d72fcb379d3e h1:MKdOuCiy2DAX1tMp2YsmtNDaqdigpY6B5cZQDJ9BvEo=
|
||||
github.com/consensys/gnark-crypto v0.12.2-0.20240215234832-d72fcb379d3e/go.mod h1:wKqwsieaKPThcFkHe0d0zMsbHEUWFmZcG7KBCse210o=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leanovate/gopter v0.2.9 h1:fQjYxZaynp97ozCzfOyOuAGOU4aU/z37zf/tOujFk7c=
|
||||
github.com/leanovate/gopter v0.2.9/go.mod h1:U2L/78B+KVFIx2VmW6onHJQzXtFb+p5y3y2Sh+Jxxv8=
|
||||
github.com/mmcloughlin/addchain v0.4.0 h1:SobOdjm2xLj1KkXN5/n0xTIWyZA2+s99UCY1iPfkHRY=
|
||||
github.com/mmcloughlin/addchain v0.4.0/go.mod h1:A86O+tHqZLMNO4w6ZZ4FlVQEadcoqkyU72HC5wJ4RlU=
|
||||
github.com/mmcloughlin/profile v0.1.1/go.mod h1:IhHD7q1ooxgwTgjxQYkACGA77oFTDdFVejUS1/tS/qU=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
|
||||
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
|
||||
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
rsc.io/tmplfunc v0.0.3 h1:53XFQh69AfOa8Tw0Jm7t+GV7KZhOi6jzsCzTtKbMvzU=
|
||||
rsc.io/tmplfunc v0.0.3/go.mod h1:AG3sTPzElb1Io3Yg4voV9AGZJuleGAwaVRxL9M49PhA=
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,174 @@
|
||||
package poseidon2
|
||||
|
||||
import g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
|
||||
const (
|
||||
WIDTH = 12
|
||||
RATE = 8
|
||||
OUT = 4
|
||||
D = 7
|
||||
// Generated by `poseidon2_round_numbers_128`
|
||||
ROUNDS_F = 8
|
||||
ROUNDS_F_HALF = 4
|
||||
ROUNDS_P = 22
|
||||
)
|
||||
|
||||
var (
|
||||
// Generated randomly for ROUNDS_F
|
||||
EXTERNAL_CONSTANTS = [ROUNDS_F][WIDTH]g.Element{
|
||||
{
|
||||
g.NewElement(15492826721047263190),
|
||||
g.NewElement(11728330187201910315),
|
||||
g.NewElement(8836021247773420868),
|
||||
g.NewElement(16777404051263952451),
|
||||
g.NewElement(5510875212538051896),
|
||||
g.NewElement(6173089941271892285),
|
||||
g.NewElement(2927757366422211339),
|
||||
g.NewElement(10340958981325008808),
|
||||
g.NewElement(8541987352684552425),
|
||||
g.NewElement(9739599543776434497),
|
||||
g.NewElement(15073950188101532019),
|
||||
g.NewElement(12084856431752384512),
|
||||
},
|
||||
{
|
||||
g.NewElement(4584713381960671270),
|
||||
g.NewElement(8807052963476652830),
|
||||
g.NewElement(54136601502601741),
|
||||
g.NewElement(4872702333905478703),
|
||||
g.NewElement(5551030319979516287),
|
||||
g.NewElement(12889366755535460989),
|
||||
g.NewElement(16329242193178844328),
|
||||
g.NewElement(412018088475211848),
|
||||
g.NewElement(10505784623379650541),
|
||||
g.NewElement(9758812378619434837),
|
||||
g.NewElement(7421979329386275117),
|
||||
g.NewElement(375240370024755551),
|
||||
},
|
||||
{
|
||||
g.NewElement(3331431125640721931),
|
||||
g.NewElement(15684937309956309981),
|
||||
g.NewElement(578521833432107983),
|
||||
g.NewElement(14379242000670861838),
|
||||
g.NewElement(17922409828154900976),
|
||||
g.NewElement(8153494278429192257),
|
||||
g.NewElement(15904673920630731971),
|
||||
g.NewElement(11217863998460634216),
|
||||
g.NewElement(3301540195510742136),
|
||||
g.NewElement(9937973023749922003),
|
||||
g.NewElement(3059102938155026419),
|
||||
g.NewElement(1895288289490976132),
|
||||
},
|
||||
{
|
||||
g.NewElement(5580912693628927540),
|
||||
g.NewElement(10064804080494788323),
|
||||
g.NewElement(9582481583369602410),
|
||||
g.NewElement(10186259561546797986),
|
||||
g.NewElement(247426333829703916),
|
||||
g.NewElement(13193193905461376067),
|
||||
g.NewElement(6386232593701758044),
|
||||
g.NewElement(17954717245501896472),
|
||||
g.NewElement(1531720443376282699),
|
||||
g.NewElement(2455761864255501970),
|
||||
g.NewElement(11234429217864304495),
|
||||
g.NewElement(4746959618548874102),
|
||||
},
|
||||
{
|
||||
g.NewElement(13571697342473846203),
|
||||
g.NewElement(17477857865056504753),
|
||||
g.NewElement(15963032953523553760),
|
||||
g.NewElement(16033593225279635898),
|
||||
g.NewElement(14252634232868282405),
|
||||
g.NewElement(8219748254835277737),
|
||||
g.NewElement(7459165569491914711),
|
||||
g.NewElement(15855939513193752003),
|
||||
g.NewElement(16788866461340278896),
|
||||
g.NewElement(7102224659693946577),
|
||||
g.NewElement(3024718005636976471),
|
||||
g.NewElement(13695468978618890430),
|
||||
},
|
||||
{
|
||||
g.NewElement(8214202050877825436),
|
||||
g.NewElement(2670727992739346204),
|
||||
g.NewElement(16259532062589659211),
|
||||
g.NewElement(11869922396257088411),
|
||||
g.NewElement(3179482916972760137),
|
||||
g.NewElement(13525476046633427808),
|
||||
g.NewElement(3217337278042947412),
|
||||
g.NewElement(14494689598654046340),
|
||||
g.NewElement(15837379330312175383),
|
||||
g.NewElement(8029037639801151344),
|
||||
g.NewElement(2153456285263517937),
|
||||
g.NewElement(8301106462311849241),
|
||||
},
|
||||
{
|
||||
g.NewElement(13294194396455217955),
|
||||
g.NewElement(17394768489610594315),
|
||||
g.NewElement(12847609130464867455),
|
||||
g.NewElement(14015739446356528640),
|
||||
g.NewElement(5879251655839607853),
|
||||
g.NewElement(9747000124977436185),
|
||||
g.NewElement(8950393546890284269),
|
||||
g.NewElement(10765765936405694368),
|
||||
g.NewElement(14695323910334139959),
|
||||
g.NewElement(16366254691123000864),
|
||||
g.NewElement(15292774414889043182),
|
||||
g.NewElement(10910394433429313384),
|
||||
},
|
||||
{
|
||||
g.NewElement(17253424460214596184),
|
||||
g.NewElement(3442854447664030446),
|
||||
g.NewElement(3005570425335613727),
|
||||
g.NewElement(10859158614900201063),
|
||||
g.NewElement(9763230642109343539),
|
||||
g.NewElement(6647722546511515039),
|
||||
g.NewElement(909012944955815706),
|
||||
g.NewElement(18101204076790399111),
|
||||
g.NewElement(11588128829349125809),
|
||||
g.NewElement(15863878496612806566),
|
||||
g.NewElement(5201119062417750399),
|
||||
g.NewElement(176665553780565743),
|
||||
},
|
||||
}
|
||||
|
||||
// Generated randomly for ROUNDS_P
|
||||
INTERNAL_CONSTANTS = [ROUNDS_P]g.Element{
|
||||
g.NewElement(11921381764981422944),
|
||||
g.NewElement(10318423381711320787),
|
||||
g.NewElement(8291411502347000766),
|
||||
g.NewElement(229948027109387563),
|
||||
g.NewElement(9152521390190983261),
|
||||
g.NewElement(7129306032690285515),
|
||||
g.NewElement(15395989607365232011),
|
||||
g.NewElement(8641397269074305925),
|
||||
g.NewElement(17256848792241043600),
|
||||
g.NewElement(6046475228902245682),
|
||||
g.NewElement(12041608676381094092),
|
||||
g.NewElement(12785542378683951657),
|
||||
g.NewElement(14546032085337914034),
|
||||
g.NewElement(3304199118235116851),
|
||||
g.NewElement(16499627707072547655),
|
||||
g.NewElement(10386478025625759321),
|
||||
g.NewElement(13475579315436919170),
|
||||
g.NewElement(16042710511297532028),
|
||||
g.NewElement(1411266850385657080),
|
||||
g.NewElement(9024840976168649958),
|
||||
g.NewElement(14047056970978379368),
|
||||
g.NewElement(838728605080212101),
|
||||
}
|
||||
|
||||
// Taken from Plonk3 Poseidon2 implementation. https://github.com/Plonky3/Plonky3/blob/eeb4e37b20127c4daa871b2bad0df30a7c7380db/goldilocks/src/poseidon2.rs#L28
|
||||
MATRIX_DIAG_12_U64 = [WIDTH]g.Element{
|
||||
g.NewElement(0xc3b6c08e23ba9300),
|
||||
g.NewElement(0xd84b5de94a324fb6),
|
||||
g.NewElement(0x0d0c371c5b35b84f),
|
||||
g.NewElement(0x7964f570e7188037),
|
||||
g.NewElement(0x5daf18bbd996604b),
|
||||
g.NewElement(0x6743bc47b9595257),
|
||||
g.NewElement(0x5528b9362c59bb70),
|
||||
g.NewElement(0xac45e25b7127b68b),
|
||||
g.NewElement(0xa2077d7dfbb606b5),
|
||||
g.NewElement(0xf3faac6faee378ae),
|
||||
g.NewElement(0x0c6388b51545e883),
|
||||
g.NewElement(0xd27dbb6944917b60),
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,237 @@
|
||||
package poseidon2
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"hash"
|
||||
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
)
|
||||
|
||||
type HashOut [4]g.Element
|
||||
|
||||
type NumericalHashOut [4]uint64
|
||||
|
||||
func (h HashOut) ToLittleEndianBytes() []byte {
|
||||
return g.ArrayToLittleEndianBytes([]g.Element{h[0], h[1], h[2], h[3]})
|
||||
}
|
||||
|
||||
func (h HashOut) ToUint64Array() [4]uint64 {
|
||||
return [4]uint64{h[0].Uint64(), h[1].Uint64(), h[2].Uint64(), h[3].Uint64()}
|
||||
}
|
||||
|
||||
func HashToQuinticExtension(m []g.Element) gFp5.Element {
|
||||
res := HashNToMNoPad(m, 5)
|
||||
return gFp5.Element(res[:])
|
||||
}
|
||||
|
||||
func HashOutFromUint64Array(arr [4]uint64) HashOut {
|
||||
return HashOut{g.FromUint64(arr[0]), g.FromUint64(arr[1]), g.FromUint64(arr[2]), g.FromUint64(arr[3])}
|
||||
}
|
||||
|
||||
func HashOutFromLittleEndianBytes(b []byte) (HashOut, error) {
|
||||
if len(b) != 4*g.Bytes {
|
||||
return HashOut{}, fmt.Errorf("input bytes len should be 32 but is %d", len(b))
|
||||
}
|
||||
|
||||
gArr, err := g.ArrayFromCanonicalLittleEndianBytes(b)
|
||||
if err != nil {
|
||||
return HashOut{}, fmt.Errorf("failed to convert bytes to field element. bytes: %v, error: %w", b, err)
|
||||
}
|
||||
|
||||
return HashOut{gArr[0], gArr[1], gArr[2], gArr[3]}, nil
|
||||
}
|
||||
|
||||
func EmptyHashOut() HashOut {
|
||||
return HashOut{g.Zero(), g.Zero(), g.Zero(), g.Zero()}
|
||||
}
|
||||
|
||||
type Poseidon2 struct{}
|
||||
|
||||
func HashNoPad(input []g.Element) HashOut {
|
||||
return HashNToHashNoPad(input)
|
||||
}
|
||||
|
||||
func HashNToOne(input []HashOut) HashOut {
|
||||
if len(input) == 1 {
|
||||
return input[0]
|
||||
}
|
||||
|
||||
res := HashTwoToOne(input[0], input[1])
|
||||
for i := 2; i < len(input); i++ {
|
||||
res = HashTwoToOne(res, input[i])
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
func HashTwoToOne(input1, input2 HashOut) HashOut {
|
||||
return HashNToHashNoPad([]g.Element{input1[0], input1[1], input1[2], input1[3], input2[0], input2[1], input2[2], input2[3]})
|
||||
}
|
||||
|
||||
func HashNToHashNoPad(input []g.Element) HashOut {
|
||||
res := HashNToMNoPad(input, 4)
|
||||
return HashOut{res[0], res[1], res[2], res[3]}
|
||||
}
|
||||
|
||||
func HashNToMNoPad(input []g.Element, numOutputs int) []g.Element {
|
||||
var perm [WIDTH]g.Element
|
||||
for i := 0; i < len(input); i += RATE {
|
||||
for j := 0; j < RATE && i+j < len(input); j++ {
|
||||
perm[j].Set(&input[i+j])
|
||||
}
|
||||
Permute(&perm)
|
||||
}
|
||||
|
||||
outputs := make([]g.Element, 0, numOutputs)
|
||||
for {
|
||||
for i := 0; i < RATE; i++ {
|
||||
outputs = append(outputs, perm[i])
|
||||
if len(outputs) == numOutputs {
|
||||
return outputs
|
||||
}
|
||||
}
|
||||
Permute(&perm)
|
||||
}
|
||||
}
|
||||
|
||||
func Permute(input *[WIDTH]g.Element) {
|
||||
externalLinearLayer(input)
|
||||
fullRounds(input, 0)
|
||||
partialRounds(input)
|
||||
fullRounds(input, ROUNDS_F_HALF)
|
||||
}
|
||||
|
||||
func fullRounds(state *[WIDTH]g.Element, start int) {
|
||||
for r := start; r < start+ROUNDS_F_HALF; r++ {
|
||||
addRC(state, r)
|
||||
sbox(state)
|
||||
externalLinearLayer(state)
|
||||
}
|
||||
}
|
||||
|
||||
func partialRounds(state *[WIDTH]g.Element) {
|
||||
for r := 0; r < ROUNDS_P; r++ {
|
||||
addRCI(state, r)
|
||||
sboxP(0, state)
|
||||
internalLinearLayer(state)
|
||||
}
|
||||
}
|
||||
|
||||
func externalLinearLayer(s *[WIDTH]g.Element) {
|
||||
for i := 0; i < 3; i++ { // 4 size window
|
||||
var t0, t1, t2, t3, t4, t5, t6 g.Element
|
||||
t0.Add(&s[4*i], &s[4*i+1]) // s0+s1
|
||||
t1.Add(&s[4*i+2], &s[4*i+3]) // s2+s3
|
||||
t2.Add(&t0, &t1) // t0+t1 = s0+s1+s2+s3
|
||||
t3.Add(&t2, &s[4*i+1]) // t2+s1 = s0+2s1+s2+s3
|
||||
t4.Add(&t2, &s[4*i+3]) // t2+s3 = s0+s1+s2+2s3
|
||||
t5.Double(&s[4*i]) // 2s0
|
||||
t6.Double(&s[4*i+2]) // 2s2
|
||||
s[4*i].Add(&t3, &t0)
|
||||
s[4*i+1].Add(&t6, &t3)
|
||||
s[4*i+2].Add(&t1, &t4)
|
||||
s[4*i+3].Add(&t5, &t4)
|
||||
}
|
||||
|
||||
sums := [4]g.Element{}
|
||||
for k := 0; k < 4; k++ {
|
||||
for j := 0; j < WIDTH; j += 4 {
|
||||
sums[k].Add(&sums[k], &s[j+k])
|
||||
}
|
||||
}
|
||||
for i := 0; i < WIDTH; i++ {
|
||||
s[i].Add(&s[i], &sums[i%4])
|
||||
}
|
||||
}
|
||||
|
||||
func internalLinearLayer(state *[WIDTH]g.Element) {
|
||||
var sum g.Element
|
||||
sum.Set(&state[0])
|
||||
for i := 1; i < WIDTH; i++ {
|
||||
sum.Add(&sum, &state[i])
|
||||
}
|
||||
for i := 0; i < WIDTH; i++ {
|
||||
state[i].Mul(&state[i], &MATRIX_DIAG_12_U64[i]).
|
||||
Add(&state[i], &sum)
|
||||
}
|
||||
}
|
||||
|
||||
func addRC(state *[WIDTH]g.Element, externalRound int) {
|
||||
for i := 0; i < WIDTH; i++ {
|
||||
state[i].Add(&state[i], &EXTERNAL_CONSTANTS[externalRound][i])
|
||||
}
|
||||
}
|
||||
|
||||
func addRCI(state *[WIDTH]g.Element, round int) {
|
||||
state[0].Add(&state[0], &INTERNAL_CONSTANTS[round])
|
||||
}
|
||||
|
||||
func sbox(state *[WIDTH]g.Element) {
|
||||
for i := range state {
|
||||
sboxP(i, state)
|
||||
}
|
||||
}
|
||||
|
||||
func sboxP(index int, state *[WIDTH]g.Element) {
|
||||
var tmp g.Element
|
||||
tmp.Set(&state[index])
|
||||
|
||||
var tmpSquare g.Element
|
||||
tmpSquare.Square(&tmp)
|
||||
|
||||
var tmpSixth g.Element
|
||||
tmpSixth.Mul(&tmpSquare, &tmp)
|
||||
tmpSixth.Square(&tmpSixth)
|
||||
|
||||
state[index].Mul(&tmpSixth, &tmp)
|
||||
}
|
||||
|
||||
const BlockSize = g.Bytes // BlockSize size that poseidon consumes
|
||||
|
||||
type digest struct {
|
||||
data []g.Element
|
||||
}
|
||||
|
||||
func NewPoseidon2() hash.Hash {
|
||||
d := new(digest)
|
||||
d.Reset()
|
||||
return d
|
||||
}
|
||||
|
||||
// Reset resets the Hash to its initial state.
|
||||
func (d *digest) Reset() {
|
||||
d.data = nil
|
||||
}
|
||||
|
||||
// Get element by element.
|
||||
func (d *digest) Write(p []byte) (n int, err error) {
|
||||
if len(p)%g.Bytes != 0 {
|
||||
return 0, fmt.Errorf("input bytes len should be multiple of 8 but is %d", len(p))
|
||||
}
|
||||
|
||||
gArr, err := g.ArrayFromCanonicalLittleEndianBytes(p)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to convert bytes to field element. bytes: %v, error: %w", p, err)
|
||||
}
|
||||
|
||||
d.data = append(d.data, gArr...)
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (d *digest) Size() int {
|
||||
return BlockSize
|
||||
}
|
||||
|
||||
// BlockSize returns the number of bytes Sum will return.
|
||||
func (d *digest) BlockSize() int {
|
||||
return BlockSize
|
||||
}
|
||||
|
||||
// Sum appends the current hash to b and returns the resulting slice.
|
||||
// It does not change the underlying hash state.
|
||||
func (d *digest) Sum(b []byte) []byte {
|
||||
b = append(b, HashNToHashNoPad(d.data).ToLittleEndianBytes()...)
|
||||
d.data = nil
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package poseidon2
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
)
|
||||
|
||||
func TestPermute(t *testing.T) {
|
||||
inp := [WIDTH]g.Element{
|
||||
g.FromUint64(5417613058500526590),
|
||||
g.FromUint64(2481548824842427254),
|
||||
g.FromUint64(6473243198879784792),
|
||||
g.FromUint64(1720313757066167274),
|
||||
g.FromUint64(2806320291675974571),
|
||||
g.FromUint64(7407976414706455446),
|
||||
g.FromUint64(1105257841424046885),
|
||||
g.FromUint64(7613435757403328049),
|
||||
g.FromUint64(3376066686066811538),
|
||||
g.FromUint64(5888575799323675710),
|
||||
g.FromUint64(6689309723188675948),
|
||||
g.FromUint64(2468250420241012720),
|
||||
}
|
||||
|
||||
Permute(&inp)
|
||||
|
||||
expected := [WIDTH]g.Element{
|
||||
g.FromUint64(5364184781011389007),
|
||||
g.FromUint64(15309475861242939136),
|
||||
g.FromUint64(5983386513087443499),
|
||||
g.FromUint64(886942118604446276),
|
||||
g.FromUint64(14903657885227062600),
|
||||
g.FromUint64(7742650891575941298),
|
||||
g.FromUint64(1962182278500985790),
|
||||
g.FromUint64(10213480816595178755),
|
||||
g.FromUint64(3510799061817443836),
|
||||
g.FromUint64(4610029967627506430),
|
||||
g.FromUint64(7566382334276534836),
|
||||
g.FromUint64(2288460879362380348),
|
||||
}
|
||||
|
||||
for i := 0; i < WIDTH; i++ {
|
||||
if inp[i] != expected[i] {
|
||||
t.Logf("Expected: %d, got: %d\n", expected[i], inp[i])
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashNToMNoPad(t *testing.T) {
|
||||
inp := [WIDTH]g.Element{
|
||||
g.FromUint64(2963773914414780088),
|
||||
g.FromUint64(8389525300242074234),
|
||||
g.FromUint64(3700959901615818008),
|
||||
g.FromUint64(6116199383751757212),
|
||||
g.FromUint64(3418607418699599889),
|
||||
g.FromUint64(8793277256263635044),
|
||||
g.FromUint64(448623437464918480),
|
||||
g.FromUint64(1857310021116627925),
|
||||
g.FromUint64(6145634616307237342),
|
||||
g.FromUint64(1548353948794474539),
|
||||
g.FromUint64(2318110128254703527),
|
||||
g.FromUint64(8347759953730634762),
|
||||
}
|
||||
|
||||
res := HashNToMNoPad(inp[:], 12)
|
||||
|
||||
expected := [WIDTH]g.Element{
|
||||
g.FromUint64(3627923032009111551),
|
||||
g.FromUint64(1460752551327577353),
|
||||
g.FromUint64(1084214837491058067),
|
||||
g.FromUint64(1841622875286057462),
|
||||
g.FromUint64(3996252440506437984),
|
||||
g.FromUint64(1276718204392552803),
|
||||
g.FromUint64(8564515621134952155),
|
||||
g.FromUint64(9252927025993202701),
|
||||
g.FromUint64(1147435538714642916),
|
||||
g.FromUint64(16407277821156164797),
|
||||
g.FromUint64(11997661877740155273),
|
||||
g.FromUint64(12485021000320141292),
|
||||
}
|
||||
|
||||
for i := 0; i < 12; i++ {
|
||||
if res[i] != expected[i] {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDigest(t *testing.T) {
|
||||
hFunc := NewPoseidon2()
|
||||
|
||||
inputs := make([][]byte, 2)
|
||||
inputs[0] = make([]byte, 8)
|
||||
inputs[0][0] = 1
|
||||
inputs[0][1] = 2
|
||||
inputs[0][2] = 3
|
||||
inputs[0][3] = 4
|
||||
inputs[0][4] = 5
|
||||
inputs[0][5] = 6
|
||||
inputs[0][6] = 7
|
||||
inputs[0][7] = 0
|
||||
inputs[1] = make([]byte, 8)
|
||||
inputs[1][0] = 7
|
||||
inputs[1][1] = 6
|
||||
inputs[1][2] = 5
|
||||
inputs[1][3] = 4
|
||||
inputs[1][4] = 3
|
||||
inputs[1][5] = 2
|
||||
inputs[1][6] = 1
|
||||
inputs[1][7] = 0
|
||||
|
||||
g1, _ := g.FromCanonicalLittleEndianBytes(inputs[0]) // 289077004332300282
|
||||
g2, _ := g.FromCanonicalLittleEndianBytes(inputs[1]) // 289644378102298614
|
||||
|
||||
hFunc.Write(inputs[0])
|
||||
hFunc.Write(inputs[1])
|
||||
|
||||
hash := hFunc.Sum(nil)
|
||||
|
||||
hash2Elems := HashNoPad([]g.Element{*g1, *g2})
|
||||
hash2 := hash2Elems.ToLittleEndianBytes()
|
||||
|
||||
for i := 0; i < len(hash); i++ {
|
||||
if hash[i] != hash2[i] {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
|
||||
reconstructed, _ := HashOutFromLittleEndianBytes(hash)
|
||||
for i := 0; i < 4; i++ {
|
||||
if hash2Elems[i] != reconstructed[i] {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashNToHashNoPad(t *testing.T) {
|
||||
res := HashNToHashNoPad([]g.Element{
|
||||
g.FromUint64(11295517158488612626),
|
||||
g.FromUint64(10669470463693797151),
|
||||
g.FromUint64(17232114065640264171),
|
||||
g.FromUint64(4175927072186299193),
|
||||
g.FromUint64(13985285184240204531),
|
||||
g.FromUint64(7901017084268693144),
|
||||
g.FromUint64(4326299618263946178),
|
||||
g.FromUint64(14787024750292535041),
|
||||
g.FromUint64(894520636503353046),
|
||||
g.FromUint64(12556655399058578835),
|
||||
g.FromUint64(3097737892474696200),
|
||||
g.FromUint64(7515335668060050861),
|
||||
})
|
||||
|
||||
expected := HashOut{
|
||||
g.FromUint64(15396602476382546759),
|
||||
g.FromUint64(12422280135166335470),
|
||||
g.FromUint64(8165681190607828974),
|
||||
g.FromUint64(3475588160239961712),
|
||||
}
|
||||
|
||||
for i := 0; i < 4; i++ {
|
||||
if res[i] != expected[i] {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashNToHashNoPadLarge(t *testing.T) {
|
||||
res := HashNToHashNoPad([]g.Element{
|
||||
g.FromUint64(g.ORDER + 1),
|
||||
g.FromUint64(g.ORDER + 2),
|
||||
g.FromUint64(g.ORDER + 3),
|
||||
g.FromUint64(math.MaxUint64),
|
||||
g.FromUint64(math.MaxUint64 - 1),
|
||||
})
|
||||
|
||||
expected := HashOut{
|
||||
g.FromUint64(14216040864787980138),
|
||||
g.FromUint64(17275303675000904868),
|
||||
g.FromUint64(11831395338463193314),
|
||||
g.FromUint64(281267649235863375),
|
||||
}
|
||||
|
||||
for i := 0; i < 4; i++ {
|
||||
if res[i] != expected[i] {
|
||||
t.Logf("Expected: [%v], got: [%v]\n", g.ToString(expected[:]...), g.ToString(res[:]...))
|
||||
t.FailNow()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashTwoToOne(t *testing.T) {
|
||||
input1 := HashOut{
|
||||
g.FromUint64(3777312593917610528),
|
||||
g.FromUint64(6858608920877200812),
|
||||
g.FromUint64(5269611035257552853),
|
||||
g.FromUint64(10607733449481270434),
|
||||
}
|
||||
|
||||
input2 := HashOut{
|
||||
g.FromUint64(10355703322562521155),
|
||||
g.FromUint64(1039917189921776884),
|
||||
g.FromUint64(10844249567941924238),
|
||||
g.FromUint64(14291130953945924124),
|
||||
}
|
||||
|
||||
expected := HashOut{
|
||||
g.FromUint64(1453933811752520343),
|
||||
g.FromUint64(16186418140372484281),
|
||||
g.FromUint64(9207215809524681813),
|
||||
g.FromUint64(10182182911172027974),
|
||||
}
|
||||
|
||||
res := HashTwoToOne(input1, input2)
|
||||
for i := 0; i < 4; i++ {
|
||||
if res[i] != expected[i] {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashNToOne(t *testing.T) {
|
||||
hashIns := []HashOut{HashNToHashNoPad([]g.Element{
|
||||
g.FromUint64(18231458557829081414),
|
||||
g.FromUint64(16449039301999856654),
|
||||
g.FromUint64(14758090268883299362),
|
||||
g.FromUint64(10271725147130672875),
|
||||
g.FromUint64(6253304685402495037),
|
||||
g.FromUint64(16079709420464120062),
|
||||
g.FromUint64(10838593640248082543),
|
||||
g.FromUint64(2974225335734585509),
|
||||
g.FromUint64(6365466669981419503),
|
||||
g.FromUint64(12964544245312854826),
|
||||
g.FromUint64(3161534615047618958),
|
||||
g.FromUint64(15109271288782125222),
|
||||
})}
|
||||
for i := 1; i < 12; i++ {
|
||||
hashIns = append(hashIns, HashTwoToOne(hashIns[i-1], hashIns[i-1]))
|
||||
}
|
||||
|
||||
res := HashNToOne(hashIns)
|
||||
expected := HashOut{
|
||||
g.FromUint64(3346041518891302234),
|
||||
g.FromUint64(10181430332820953144),
|
||||
g.FromUint64(14852547783810217847),
|
||||
g.FromUint64(17043509806476508794),
|
||||
}
|
||||
for i := 0; i < 4; i++ {
|
||||
if res[i] != expected[i] {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashToQuinticExtension(t *testing.T) {
|
||||
result := HashToQuinticExtension([]g.Element{
|
||||
g.FromUint64(3451004116618606032),
|
||||
g.FromUint64(11263134342958518251),
|
||||
g.FromUint64(10957204882857370932),
|
||||
g.FromUint64(5369763041201481933),
|
||||
g.FromUint64(7695734348563036858),
|
||||
g.FromUint64(1393419330378128434),
|
||||
g.FromUint64(7387917082382606332),
|
||||
})
|
||||
expected := [5]uint64{
|
||||
17992684813643984528,
|
||||
5243896189906434327,
|
||||
7705560276311184368,
|
||||
2785244775876017560,
|
||||
14449776097783372302,
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
if result[i] != g.FromUint64(expected[i]) {
|
||||
t.Logf("Expected limb %d to be %x, but got %x", i, expected[i], result[i])
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package poseidon2_plonky2
|
||||
|
||||
import g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
|
||||
const (
|
||||
WIDTH = 12
|
||||
RATE = 8
|
||||
OUT = 4
|
||||
D = 7
|
||||
// Generated by `poseidon2_round_numbers_128`
|
||||
ROUNDS_F = 8
|
||||
ROUNDS_F_HALF = 4
|
||||
ROUNDS_P = 22
|
||||
)
|
||||
|
||||
var (
|
||||
// Generated randomly for ROUNDS_F
|
||||
EXTERNAL_CONSTANTS = [ROUNDS_F][WIDTH]g.GoldilocksField{
|
||||
{
|
||||
15492826721047263190,
|
||||
11728330187201910315,
|
||||
8836021247773420868,
|
||||
16777404051263952451,
|
||||
5510875212538051896,
|
||||
6173089941271892285,
|
||||
2927757366422211339,
|
||||
10340958981325008808,
|
||||
8541987352684552425,
|
||||
9739599543776434497,
|
||||
15073950188101532019,
|
||||
12084856431752384512,
|
||||
},
|
||||
{
|
||||
4584713381960671270,
|
||||
8807052963476652830,
|
||||
54136601502601741,
|
||||
4872702333905478703,
|
||||
5551030319979516287,
|
||||
12889366755535460989,
|
||||
16329242193178844328,
|
||||
412018088475211848,
|
||||
10505784623379650541,
|
||||
9758812378619434837,
|
||||
7421979329386275117,
|
||||
375240370024755551,
|
||||
},
|
||||
{
|
||||
3331431125640721931,
|
||||
15684937309956309981,
|
||||
578521833432107983,
|
||||
14379242000670861838,
|
||||
17922409828154900976,
|
||||
8153494278429192257,
|
||||
15904673920630731971,
|
||||
11217863998460634216,
|
||||
3301540195510742136,
|
||||
9937973023749922003,
|
||||
3059102938155026419,
|
||||
1895288289490976132,
|
||||
},
|
||||
{
|
||||
5580912693628927540,
|
||||
10064804080494788323,
|
||||
9582481583369602410,
|
||||
10186259561546797986,
|
||||
247426333829703916,
|
||||
13193193905461376067,
|
||||
6386232593701758044,
|
||||
17954717245501896472,
|
||||
1531720443376282699,
|
||||
2455761864255501970,
|
||||
11234429217864304495,
|
||||
4746959618548874102,
|
||||
},
|
||||
{
|
||||
13571697342473846203,
|
||||
17477857865056504753,
|
||||
15963032953523553760,
|
||||
16033593225279635898,
|
||||
14252634232868282405,
|
||||
8219748254835277737,
|
||||
7459165569491914711,
|
||||
15855939513193752003,
|
||||
16788866461340278896,
|
||||
7102224659693946577,
|
||||
3024718005636976471,
|
||||
13695468978618890430,
|
||||
},
|
||||
{
|
||||
8214202050877825436,
|
||||
2670727992739346204,
|
||||
16259532062589659211,
|
||||
11869922396257088411,
|
||||
3179482916972760137,
|
||||
13525476046633427808,
|
||||
3217337278042947412,
|
||||
14494689598654046340,
|
||||
15837379330312175383,
|
||||
8029037639801151344,
|
||||
2153456285263517937,
|
||||
8301106462311849241,
|
||||
},
|
||||
{
|
||||
13294194396455217955,
|
||||
17394768489610594315,
|
||||
12847609130464867455,
|
||||
14015739446356528640,
|
||||
5879251655839607853,
|
||||
9747000124977436185,
|
||||
8950393546890284269,
|
||||
10765765936405694368,
|
||||
14695323910334139959,
|
||||
16366254691123000864,
|
||||
15292774414889043182,
|
||||
10910394433429313384,
|
||||
},
|
||||
{
|
||||
17253424460214596184,
|
||||
3442854447664030446,
|
||||
3005570425335613727,
|
||||
10859158614900201063,
|
||||
9763230642109343539,
|
||||
6647722546511515039,
|
||||
909012944955815706,
|
||||
18101204076790399111,
|
||||
11588128829349125809,
|
||||
15863878496612806566,
|
||||
5201119062417750399,
|
||||
176665553780565743,
|
||||
},
|
||||
}
|
||||
|
||||
// Generated randomly for ROUNDS_P
|
||||
INTERNAL_CONSTANTS = [ROUNDS_P]g.GoldilocksField{
|
||||
11921381764981422944,
|
||||
10318423381711320787,
|
||||
8291411502347000766,
|
||||
229948027109387563,
|
||||
9152521390190983261,
|
||||
7129306032690285515,
|
||||
15395989607365232011,
|
||||
8641397269074305925,
|
||||
17256848792241043600,
|
||||
6046475228902245682,
|
||||
12041608676381094092,
|
||||
12785542378683951657,
|
||||
14546032085337914034,
|
||||
3304199118235116851,
|
||||
16499627707072547655,
|
||||
10386478025625759321,
|
||||
13475579315436919170,
|
||||
16042710511297532028,
|
||||
1411266850385657080,
|
||||
9024840976168649958,
|
||||
14047056970978379368,
|
||||
838728605080212101,
|
||||
}
|
||||
|
||||
// Taken from Plonk3 Poseidon2 implementation. https://github.com/Plonky3/Plonky3/blob/eeb4e37b20127c4daa871b2bad0df30a7c7380db/goldilocks/src/poseidon2.rs#L28
|
||||
MATRIX_DIAG_12_U64 = [WIDTH]g.GoldilocksField{
|
||||
0xc3b6c08e23ba9300,
|
||||
0xd84b5de94a324fb6,
|
||||
0x0d0c371c5b35b84f,
|
||||
0x7964f570e7188037,
|
||||
0x5daf18bbd996604b,
|
||||
0x6743bc47b9595257,
|
||||
0x5528b9362c59bb70,
|
||||
0xac45e25b7127b68b,
|
||||
0xa2077d7dfbb606b5,
|
||||
0xf3faac6faee378ae,
|
||||
0x0c6388b51545e883,
|
||||
0xd27dbb6944917b60,
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,262 @@
|
||||
package poseidon2_plonky2
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"hash"
|
||||
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
)
|
||||
|
||||
type HashOut [4]g.GoldilocksField
|
||||
type NumericalHashOut [4]uint64
|
||||
|
||||
func EmptyHashOut() HashOut {
|
||||
return HashOut{g.ZeroF(), g.ZeroF(), g.ZeroF(), g.ZeroF()}
|
||||
}
|
||||
|
||||
func (h HashOut) ToLittleEndianBytes() []byte {
|
||||
res := make([]byte, 0, 4*g.Bytes)
|
||||
for _, elem := range h {
|
||||
res = append(res, g.ToLittleEndianBytesF(elem)...)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func HashOutFromLittleEndianBytes(b []byte) (HashOut, error) {
|
||||
if len(b) != 4*g.Bytes {
|
||||
return HashOut{}, fmt.Errorf("input bytes len should be 32 but is %d", len(b))
|
||||
}
|
||||
var res HashOut
|
||||
for i := 0; i < 4; i++ {
|
||||
res[i] = g.FromCanonicalLittleEndianBytesF(b[i*g.Bytes : (i+1)*g.Bytes])
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (h HashOut) ToUint64Array() [4]uint64 {
|
||||
return [4]uint64{uint64(h[0]), uint64(h[1]), uint64(h[2]), uint64(h[3])}
|
||||
}
|
||||
|
||||
func HashOutFromUint64Array(arr [4]uint64) HashOut {
|
||||
return HashOut{g.GoldilocksField(arr[0]), g.GoldilocksField(arr[1]), g.GoldilocksField(arr[2]), g.GoldilocksField(arr[3])}
|
||||
}
|
||||
|
||||
func HashToQuinticExtension(m []g.GoldilocksField) gFp5.Element {
|
||||
res := HashNToMNoPad(m, 5)
|
||||
return gFp5.FromPlonky2GoldilocksField(res[:])
|
||||
}
|
||||
|
||||
type Poseidon2 struct{}
|
||||
|
||||
func HashNoPad(input []g.GoldilocksField) HashOut {
|
||||
return HashNToHashNoPad(input)
|
||||
}
|
||||
|
||||
func HashNToOne(input []HashOut) HashOut {
|
||||
if len(input) == 1 {
|
||||
return input[0]
|
||||
}
|
||||
|
||||
res := HashTwoToOne(input[0], input[1])
|
||||
for i := 2; i < len(input); i++ {
|
||||
res = HashTwoToOne(res, input[i])
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
func HashTwoToOne(input1, input2 HashOut) HashOut {
|
||||
return HashNToHashNoPad([]g.GoldilocksField{input1[0], input1[1], input1[2], input1[3], input2[0], input2[1], input2[2], input2[3]})
|
||||
}
|
||||
|
||||
func HashNToHashNoPad(input []g.GoldilocksField) HashOut {
|
||||
res := HashNToMNoPad(input, 4)
|
||||
return HashOut{res[0], res[1], res[2], res[3]}
|
||||
}
|
||||
|
||||
func HashNToMNoPad(input []g.GoldilocksField, numOutputs int) []g.GoldilocksField {
|
||||
var perm [WIDTH]g.GoldilocksField
|
||||
for i := 0; i < len(input); i += RATE {
|
||||
for j := 0; j < RATE && i+j < len(input); j++ {
|
||||
perm[j] = input[i+j]
|
||||
}
|
||||
Permute(&perm)
|
||||
}
|
||||
|
||||
outputs := make([]g.GoldilocksField, 0, numOutputs)
|
||||
for {
|
||||
for i := 0; i < RATE; i++ {
|
||||
outputs = append(outputs, perm[i])
|
||||
if len(outputs) == numOutputs {
|
||||
return outputs
|
||||
}
|
||||
}
|
||||
Permute(&perm)
|
||||
}
|
||||
}
|
||||
|
||||
func HashNToMNoPadBytes(input []byte, numOutputs int) []g.GoldilocksField {
|
||||
if len(input)%g.Bytes != 0 {
|
||||
panic("input length should be multiple of 8")
|
||||
}
|
||||
|
||||
inputLen := len(input) / g.Bytes
|
||||
|
||||
var perm [WIDTH]g.GoldilocksField
|
||||
for i := 0; i < inputLen; i += RATE {
|
||||
for j := 0; j < RATE && i+j < inputLen; j++ {
|
||||
index := (i + j) * g.Bytes
|
||||
perm[j] = g.FromCanonicalLittleEndianBytesF(input[index : index+g.Bytes])
|
||||
}
|
||||
Permute(&perm)
|
||||
}
|
||||
|
||||
outputs := make([]g.GoldilocksField, 0, numOutputs)
|
||||
for {
|
||||
for i := 0; i < RATE; i++ {
|
||||
outputs = append(outputs, perm[i])
|
||||
if len(outputs) == numOutputs {
|
||||
return outputs
|
||||
}
|
||||
}
|
||||
Permute(&perm)
|
||||
}
|
||||
}
|
||||
|
||||
func Permute(input *[WIDTH]g.GoldilocksField) {
|
||||
externalLinearLayer(input)
|
||||
fullRounds(input, 0)
|
||||
partialRounds(input)
|
||||
fullRounds(input, ROUNDS_F_HALF)
|
||||
}
|
||||
|
||||
func fullRounds(state *[WIDTH]g.GoldilocksField, start int) {
|
||||
for r := start; r < start+ROUNDS_F_HALF; r++ {
|
||||
addRC(state, r)
|
||||
sbox(state)
|
||||
externalLinearLayer(state)
|
||||
}
|
||||
}
|
||||
|
||||
func partialRounds(state *[WIDTH]g.GoldilocksField) {
|
||||
for r := 0; r < ROUNDS_P; r++ {
|
||||
addRCI(state, r)
|
||||
sboxP(0, state)
|
||||
internalLinearLayer(state)
|
||||
}
|
||||
}
|
||||
|
||||
func externalLinearLayer(s *[WIDTH]g.GoldilocksField) {
|
||||
for i := 0; i < 3; i++ { // 4 size window
|
||||
var t0, t1, t2, t3, t4, t5, t6 g.GoldilocksField
|
||||
t0 = g.AddF(s[4*i], s[4*i+1]) // s0+s1
|
||||
t1 = g.AddF(s[4*i+2], s[4*i+3]) // s2+s3
|
||||
t2 = g.AddF(t0, t1) // t0+t1 = s0+s1+s2+s3
|
||||
t3 = g.AddF(t2, s[4*i+1]) // t2+s1 = s0+2s1+s2+s3
|
||||
t4 = g.AddF(t2, s[4*i+3]) // t2+s3 = s0+s1+s2+2s3
|
||||
t5 = g.DoubleF(s[4*i]) // 2s0
|
||||
t6 = g.DoubleF(s[4*i+2]) // 2s2
|
||||
s[4*i] = g.AddF(t3, t0)
|
||||
s[4*i+1] = g.AddF(t6, t3)
|
||||
s[4*i+2] = g.AddF(t1, t4)
|
||||
s[4*i+3] = g.AddF(t5, t4)
|
||||
}
|
||||
|
||||
sums := [4]g.GoldilocksField{}
|
||||
for k := 0; k < 4; k++ {
|
||||
for j := 0; j < WIDTH; j += 4 {
|
||||
sums[k] = g.AddF(sums[k], s[j+k])
|
||||
}
|
||||
}
|
||||
for i := 0; i < WIDTH; i++ {
|
||||
s[i] = g.AddF(s[i], sums[i%4])
|
||||
}
|
||||
}
|
||||
|
||||
func internalLinearLayer(state *[WIDTH]g.GoldilocksField) {
|
||||
sum := state[0]
|
||||
for i := 1; i < WIDTH; i++ {
|
||||
sum = g.AddF(sum, state[i])
|
||||
}
|
||||
for i := 0; i < WIDTH; i++ {
|
||||
state[i] = g.MulF(state[i], MATRIX_DIAG_12_U64[i])
|
||||
state[i] = g.AddF(state[i], sum)
|
||||
}
|
||||
}
|
||||
|
||||
func addRC(state *[WIDTH]g.GoldilocksField, externalRound int) {
|
||||
for i := 0; i < WIDTH; i++ {
|
||||
state[i] = g.AddF(state[i], EXTERNAL_CONSTANTS[externalRound][i])
|
||||
}
|
||||
}
|
||||
|
||||
func addRCI(state *[WIDTH]g.GoldilocksField, round int) {
|
||||
state[0] = g.AddF(state[0], INTERNAL_CONSTANTS[round])
|
||||
}
|
||||
|
||||
func sbox(state *[WIDTH]g.GoldilocksField) {
|
||||
for i := range state {
|
||||
sboxP(i, state)
|
||||
}
|
||||
}
|
||||
|
||||
func sboxP(index int, state *[WIDTH]g.GoldilocksField) {
|
||||
tmp := state[index]
|
||||
tmpSquare := g.SquareF(tmp)
|
||||
|
||||
var tmpSixth g.GoldilocksField
|
||||
tmpSixth = g.MulF(tmpSquare, tmp)
|
||||
tmpSixth = g.SquareF(tmpSixth)
|
||||
|
||||
state[index] = g.MulF(tmpSixth, tmp)
|
||||
}
|
||||
|
||||
const BlockSize = g.Bytes * WIDTH // BlockSize size that poseidon consumes
|
||||
|
||||
type digest struct {
|
||||
data []byte
|
||||
len int
|
||||
}
|
||||
|
||||
func NewPoseidon2() hash.Hash {
|
||||
d := new(digest)
|
||||
return d
|
||||
}
|
||||
|
||||
// Reset resets the Hash to its initial state.
|
||||
func (d *digest) Reset() {
|
||||
d.data = d.data[:0]
|
||||
d.len = 0
|
||||
}
|
||||
|
||||
// Get element by element.
|
||||
func (d *digest) Write(p []byte) (n int, err error) {
|
||||
d.data = append(d.data, p...)
|
||||
d.len += len(p)
|
||||
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// Sum appends the current hash to b and returns the resulting slice.
|
||||
// It does not change the underlying hash state.
|
||||
func (d *digest) Sum(b []byte) []byte {
|
||||
h := HashNToMNoPadBytes(d.data, 4)
|
||||
d.Reset()
|
||||
|
||||
for _, elem := range h {
|
||||
b = append(b, g.ToLittleEndianBytesF(elem)...)
|
||||
}
|
||||
|
||||
return b
|
||||
}
|
||||
|
||||
func (d *digest) Size() int {
|
||||
return BlockSize
|
||||
}
|
||||
|
||||
// BlockSize returns the number of bytes Sum will return.
|
||||
func (d *digest) BlockSize() int {
|
||||
return BlockSize
|
||||
}
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
package poseidon2_plonky2
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
)
|
||||
|
||||
func TestPermute(t *testing.T) {
|
||||
inp := [WIDTH]g.GoldilocksField{
|
||||
5417613058500526590,
|
||||
2481548824842427254,
|
||||
6473243198879784792,
|
||||
1720313757066167274,
|
||||
2806320291675974571,
|
||||
7407976414706455446,
|
||||
1105257841424046885,
|
||||
7613435757403328049,
|
||||
3376066686066811538,
|
||||
5888575799323675710,
|
||||
6689309723188675948,
|
||||
2468250420241012720,
|
||||
}
|
||||
|
||||
Permute(&inp)
|
||||
|
||||
expected := [WIDTH]g.GoldilocksField{
|
||||
5364184781011389007,
|
||||
15309475861242939136,
|
||||
5983386513087443499,
|
||||
886942118604446276,
|
||||
14903657885227062600,
|
||||
7742650891575941298,
|
||||
1962182278500985790,
|
||||
10213480816595178755,
|
||||
3510799061817443836,
|
||||
4610029967627506430,
|
||||
7566382334276534836,
|
||||
2288460879362380348,
|
||||
}
|
||||
|
||||
for i := 0; i < WIDTH; i++ {
|
||||
if inp[i] != expected[i] {
|
||||
t.Logf("Expected: %d, got: %d\n", expected[i], inp[i])
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashNToMNoPad(t *testing.T) {
|
||||
inp := [WIDTH]g.GoldilocksField{
|
||||
2963773914414780088,
|
||||
8389525300242074234,
|
||||
3700959901615818008,
|
||||
6116199383751757212,
|
||||
3418607418699599889,
|
||||
8793277256263635044,
|
||||
448623437464918480,
|
||||
1857310021116627925,
|
||||
6145634616307237342,
|
||||
1548353948794474539,
|
||||
2318110128254703527,
|
||||
8347759953730634762,
|
||||
}
|
||||
|
||||
res := HashNToMNoPad(inp[:], 12)
|
||||
|
||||
expected := [WIDTH]g.GoldilocksField{
|
||||
3627923032009111551,
|
||||
1460752551327577353,
|
||||
1084214837491058067,
|
||||
1841622875286057462,
|
||||
3996252440506437984,
|
||||
1276718204392552803,
|
||||
8564515621134952155,
|
||||
9252927025993202701,
|
||||
1147435538714642916,
|
||||
16407277821156164797,
|
||||
11997661877740155273,
|
||||
12485021000320141292,
|
||||
}
|
||||
|
||||
for i := 0; i < 12; i++ {
|
||||
if res[i] != expected[i] {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDigest(t *testing.T) {
|
||||
hFunc := NewPoseidon2()
|
||||
|
||||
inputs := make([][]byte, 2)
|
||||
inputs[0] = make([]byte, 8)
|
||||
inputs[0][0] = 1
|
||||
inputs[0][1] = 2
|
||||
inputs[0][2] = 3
|
||||
inputs[0][3] = 4
|
||||
inputs[0][4] = 5
|
||||
inputs[0][5] = 6
|
||||
inputs[0][6] = 7
|
||||
inputs[0][7] = 0
|
||||
inputs[1] = make([]byte, 8)
|
||||
inputs[1][0] = 7
|
||||
inputs[1][1] = 6
|
||||
inputs[1][2] = 5
|
||||
inputs[1][3] = 4
|
||||
inputs[1][4] = 3
|
||||
inputs[1][5] = 2
|
||||
inputs[1][6] = 1
|
||||
inputs[1][7] = 0
|
||||
|
||||
g1 := g.FromCanonicalLittleEndianBytesF(inputs[0]) // 289077004332300282
|
||||
g2 := g.FromCanonicalLittleEndianBytesF(inputs[1]) // 289644378102298614
|
||||
|
||||
hFunc.Write(inputs[0])
|
||||
hFunc.Write(inputs[1])
|
||||
|
||||
hash := hFunc.Sum(nil)
|
||||
|
||||
hash2Elems := HashNoPad([]g.GoldilocksField{g1, g2})
|
||||
hash2 := hash2Elems.ToLittleEndianBytes()
|
||||
|
||||
if !bytes.Equal(hash, hash2) {
|
||||
t.Logf("Expected: %v, got: %v\n", hash2, hash)
|
||||
t.Fail()
|
||||
}
|
||||
|
||||
reconstructed, err := HashOutFromLittleEndianBytes(hash)
|
||||
if err != nil {
|
||||
t.Logf("Error: %v\n", err)
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
for i := 0; i < 4; i++ {
|
||||
if hash2Elems[i] != reconstructed[i] {
|
||||
t.Logf("Expected: %d, got: %d\n", hash2Elems[i], reconstructed[i])
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashNToHashNoPad(t *testing.T) {
|
||||
res := HashNToHashNoPad([]g.GoldilocksField{
|
||||
11295517158488612626,
|
||||
10669470463693797151,
|
||||
17232114065640264171,
|
||||
4175927072186299193,
|
||||
13985285184240204531,
|
||||
7901017084268693144,
|
||||
4326299618263946178,
|
||||
14787024750292535041,
|
||||
894520636503353046,
|
||||
12556655399058578835,
|
||||
3097737892474696200,
|
||||
7515335668060050861,
|
||||
})
|
||||
|
||||
expected := HashOut{
|
||||
15396602476382546759,
|
||||
12422280135166335470,
|
||||
8165681190607828974,
|
||||
3475588160239961712,
|
||||
}
|
||||
|
||||
for i := 0; i < 4; i++ {
|
||||
if res[i] != expected[i] {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashNToHashNoPadLarge(t *testing.T) {
|
||||
res := HashNToHashNoPad([]g.GoldilocksField{
|
||||
g.GoldilocksField(g.ORDER + 1),
|
||||
g.GoldilocksField(g.ORDER + 2),
|
||||
g.GoldilocksField(g.ORDER + 3),
|
||||
g.GoldilocksField(math.MaxUint64),
|
||||
g.GoldilocksField(math.MaxUint64 - 1),
|
||||
})
|
||||
|
||||
expected := HashOut{
|
||||
14216040864787980138,
|
||||
17275303675000904868,
|
||||
11831395338463193314,
|
||||
281267649235863375,
|
||||
}
|
||||
|
||||
for i := 0; i < 4; i++ {
|
||||
if res[i] != expected[i] {
|
||||
t.Logf("Expected: %v, got: %v\n", expected, res)
|
||||
t.FailNow()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashTwoToOne(t *testing.T) {
|
||||
input1 := HashOut{
|
||||
3777312593917610528,
|
||||
6858608920877200812,
|
||||
5269611035257552853,
|
||||
10607733449481270434,
|
||||
}
|
||||
|
||||
input2 := HashOut{
|
||||
10355703322562521155,
|
||||
1039917189921776884,
|
||||
10844249567941924238,
|
||||
14291130953945924124,
|
||||
}
|
||||
|
||||
expected := HashOut{
|
||||
1453933811752520343,
|
||||
16186418140372484281,
|
||||
9207215809524681813,
|
||||
10182182911172027974,
|
||||
}
|
||||
|
||||
res := HashTwoToOne(input1, input2)
|
||||
for i := 0; i < 4; i++ {
|
||||
if res[i] != expected[i] {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashNToOne(t *testing.T) {
|
||||
hashIns := []HashOut{HashNToHashNoPad([]g.GoldilocksField{
|
||||
18231458557829081414,
|
||||
16449039301999856654,
|
||||
14758090268883299362,
|
||||
10271725147130672875,
|
||||
6253304685402495037,
|
||||
16079709420464120062,
|
||||
10838593640248082543,
|
||||
2974225335734585509,
|
||||
6365466669981419503,
|
||||
12964544245312854826,
|
||||
3161534615047618958,
|
||||
15109271288782125222,
|
||||
})}
|
||||
for i := 1; i < 12; i++ {
|
||||
hashIns = append(hashIns, HashTwoToOne(hashIns[i-1], hashIns[i-1]))
|
||||
}
|
||||
|
||||
res := HashNToOne(hashIns)
|
||||
expected := HashOut{
|
||||
3346041518891302234,
|
||||
10181430332820953144,
|
||||
14852547783810217847,
|
||||
17043509806476508794,
|
||||
}
|
||||
for i := 0; i < 4; i++ {
|
||||
if res[i] != expected[i] {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashToQuinticExtension(t *testing.T) {
|
||||
result := HashToQuinticExtension([]g.GoldilocksField{
|
||||
3451004116618606032,
|
||||
11263134342958518251,
|
||||
10957204882857370932,
|
||||
5369763041201481933,
|
||||
7695734348563036858,
|
||||
1393419330378128434,
|
||||
7387917082382606332,
|
||||
})
|
||||
expected := [5]uint64{
|
||||
17992684813643984528,
|
||||
5243896189906434327,
|
||||
7705560276311184368,
|
||||
2785244775876017560,
|
||||
14449776097783372302,
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
if result[i] != g.FromUint64(expected[i]) {
|
||||
t.Logf("Expected limb %d to be %x, but got %x", i, expected[i], result[i])
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package hash
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
poseidon2_gnark "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
poseidon2_plonky2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks_plonky2"
|
||||
)
|
||||
|
||||
func TestLongRunningCompare(t *testing.T) {
|
||||
run := os.Getenv("LONG_RUNNING_TESTS")
|
||||
if run != "true" {
|
||||
t.Skip("Skipping long running test")
|
||||
}
|
||||
|
||||
file := os.Getenv("LONG_RUNNING_TESTS_FILE")
|
||||
|
||||
// Generate random 12 inputs
|
||||
for j := 0; j < 1_000_000_000; j++ {
|
||||
inputs := make([]uint64, 12)
|
||||
for i := 0; i < 12; i++ {
|
||||
inputs[i] = rand.Uint64N(g.ORDER)
|
||||
}
|
||||
|
||||
// Convert to GoldilocksField
|
||||
gInputs := make([]g.GoldilocksField, 0, 12)
|
||||
for _, input := range inputs {
|
||||
gInputs = append(gInputs, g.GoldilocksField(input))
|
||||
}
|
||||
gOutputs := poseidon2_plonky2.HashNToMNoPad(gInputs, 12)
|
||||
|
||||
// Convert to Element
|
||||
eInputs := make([]g.Element, 0, 12)
|
||||
for _, input := range inputs {
|
||||
eInputs = append(eInputs, g.NewElement(input))
|
||||
}
|
||||
eOutputs := poseidon2_gnark.HashNToMNoPad(eInputs, 12)
|
||||
|
||||
// Compare
|
||||
for i := 0; i < 12; i++ {
|
||||
if gOutputs[i].ToCanonicalUint64() != eOutputs[i].Uint64() {
|
||||
if file != "" {
|
||||
f, err := os.OpenFile(file, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
t.Logf("Error: %v\n", err)
|
||||
t.FailNow()
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
_, err = f.WriteString("<--- Mismatch --->\n")
|
||||
if err != nil {
|
||||
t.Logf("Error: %v\n", err)
|
||||
t.FailNow()
|
||||
}
|
||||
_, err = f.WriteString(fmt.Sprintf("Inputs: %v; %v; [%v]\n", inputs, gInputs, g.ToString(eInputs...)))
|
||||
if err != nil {
|
||||
t.Logf("Error: %v\n", err)
|
||||
t.FailNow()
|
||||
}
|
||||
_, err = f.WriteString(fmt.Sprintf("Outputs: %v; [%v]\n\n", gOutputs, g.ToString(eOutputs...)))
|
||||
if err != nil {
|
||||
t.Logf("Error: %v\n", err)
|
||||
t.FailNow()
|
||||
}
|
||||
f.Close()
|
||||
} else {
|
||||
t.Log("<--- Mismatch --->")
|
||||
t.Logf("Inputs: %v; %v; [%v]", inputs, gInputs, g.ToString(eInputs...))
|
||||
t.Logf("Outputs: %v; [%v]", gOutputs, g.ToString(eOutputs...))
|
||||
t.FailNow()
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t.Log("Completed long-running comparison.")
|
||||
}
|
||||
|
||||
func TestPoseidon2Bench(t *testing.T) {
|
||||
inputs, err := readBenchInputs("bench_vector")
|
||||
totalInputs := len(inputs)
|
||||
if err != nil {
|
||||
t.Logf("Error: %v\n", err)
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
PrintMemUsage()
|
||||
|
||||
results := make([]g.GoldilocksField, 0, 4*len(inputs))
|
||||
start := time.Now()
|
||||
for _, input := range inputs {
|
||||
res := poseidon2_plonky2.HashNToHashNoPad(input)
|
||||
results = append(results, res[:]...)
|
||||
}
|
||||
duration := time.Since(start)
|
||||
t.Logf("HashNToHashNoPad plonky2 took %s for %d inputs", duration, totalInputs)
|
||||
|
||||
sha2 := sha256.New()
|
||||
for _, res := range results {
|
||||
sha2.Write(g.ToLittleEndianBytesF(res))
|
||||
}
|
||||
t.Logf("Hash: %x\n", sha2.Sum(nil))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoseidon2HasherBench(t *testing.T) {
|
||||
inputs, err := readBenchInputsBytes("bench_vector")
|
||||
totalInputs := len(inputs)
|
||||
if err != nil {
|
||||
t.Logf("Error: %v\n", err)
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
hasher := poseidon2_plonky2.NewPoseidon2()
|
||||
start1 := time.Now()
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
PrintMemUsage()
|
||||
|
||||
results := make([]byte, 0, 4*8*len(inputs))
|
||||
start := time.Now()
|
||||
for _, input := range inputs {
|
||||
for _, b := range input {
|
||||
hasher.Write(b)
|
||||
}
|
||||
res := hasher.Sum(nil)
|
||||
hasher.Reset()
|
||||
results = append(results, res...)
|
||||
}
|
||||
duration := time.Since(start)
|
||||
t.Logf("Hasher plonky2 took %s for %d inputs", duration, totalInputs)
|
||||
|
||||
sha2 := sha256.New()
|
||||
sha2.Write(results)
|
||||
t.Logf("Hash: %x\n", sha2.Sum(nil))
|
||||
}
|
||||
|
||||
duration := time.Since(start1)
|
||||
t.Logf("===> Hasher plonky2 took %s", duration)
|
||||
}
|
||||
|
||||
func TestPoseidon2BenchOld(t *testing.T) {
|
||||
inputs, err := readBenchInputsOld("bench_vector")
|
||||
totalInputs := len(inputs)
|
||||
if err != nil {
|
||||
t.Logf("Error: %v\n", err)
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
results := make([]g.Element, 0, 4*len(inputs))
|
||||
start := time.Now()
|
||||
for _, input := range inputs {
|
||||
res := poseidon2_gnark.HashNToHashNoPad(input)
|
||||
results = append(results, res[:]...)
|
||||
}
|
||||
duration := time.Since(start)
|
||||
t.Logf("HashNToHashNoPadPure gnark took %s for %d inputs", duration, totalInputs)
|
||||
|
||||
sha2 := sha256.New()
|
||||
for _, res := range results {
|
||||
sha2.Write(g.ToLittleEndianBytes(res))
|
||||
}
|
||||
hash := sha2.Sum(nil)
|
||||
t.Logf("Hash: %x\n", hash)
|
||||
}
|
||||
|
||||
func readBenchInputs(filename string) ([][]g.GoldilocksField, error) {
|
||||
file, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
var inputs [][]g.GoldilocksField
|
||||
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
strVals := strings.Split(line, ",")
|
||||
var input []g.GoldilocksField
|
||||
for _, strVal := range strVals {
|
||||
val, err := strconv.ParseUint(strVal, 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse uint64: %v", err)
|
||||
}
|
||||
input = append(input, g.GoldilocksField(val))
|
||||
}
|
||||
inputs = append(inputs, input)
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, fmt.Errorf("failed to read file: %v", err)
|
||||
}
|
||||
|
||||
return inputs, nil
|
||||
}
|
||||
|
||||
func readBenchInputsBytes(filename string) ([][][]byte, error) {
|
||||
file, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
var inputs [][][]byte
|
||||
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
strVals := strings.Split(line, ",")
|
||||
var input [][]byte
|
||||
for _, strVal := range strVals {
|
||||
val, err := strconv.ParseUint(strVal, 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse uint64: %v", err)
|
||||
}
|
||||
input = append(input, g.ToLittleEndianBytesF(g.GoldilocksField(val)))
|
||||
}
|
||||
inputs = append(inputs, input)
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, fmt.Errorf("failed to read file: %v", err)
|
||||
}
|
||||
|
||||
return inputs, nil
|
||||
}
|
||||
|
||||
func readBenchInputsOld(filename string) ([][]g.Element, error) {
|
||||
file, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
var inputs [][]g.Element
|
||||
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
strVals := strings.Split(line, ",")
|
||||
var input []g.Element
|
||||
for _, strVal := range strVals {
|
||||
val, err := strconv.ParseUint(strVal, 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse uint64: %v", err)
|
||||
}
|
||||
input = append(input, g.NewElement(val))
|
||||
}
|
||||
inputs = append(inputs, input)
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, fmt.Errorf("failed to read file: %v", err)
|
||||
}
|
||||
|
||||
return inputs, nil
|
||||
}
|
||||
|
||||
func PrintMemUsage() {
|
||||
var m runtime.MemStats
|
||||
runtime.ReadMemStats(&m)
|
||||
// For info on each, see: https://golang.org/pkg/runtime/#MemStats
|
||||
fmt.Printf("Alloc = %v Bytes", m.Alloc)
|
||||
fmt.Printf("\tTotalAlloc = %v Bytes", m.TotalAlloc)
|
||||
fmt.Printf("\tSys = %v Bytes", m.Sys)
|
||||
fmt.Printf("\tNumGC = %v\n", m.NumGC)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package poseidon_bn254
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
|
||||
"github.com/consensys/gnark-crypto/ecc/bn254/fr"
|
||||
"github.com/elliottech/poseidon_crypto/hash/poseidon_bn254/constants"
|
||||
)
|
||||
|
||||
// Number of full rounds
|
||||
const rf = 8
|
||||
|
||||
var alpha = big.NewInt(5)
|
||||
|
||||
// Number of partial rounds rounded up to nearest integer that divides by t in [2, 13]
|
||||
var rp = []int{56, 57, 56, 60, 60, 63, 64, 63, 60, 66, 60, 65, 70, 60, 64, 68}
|
||||
|
||||
// Round constants and matrices
|
||||
var (
|
||||
c, s [][]*fr.Element
|
||||
m, p [][][]*fr.Element
|
||||
)
|
||||
|
||||
func toElement(value string) *fr.Element {
|
||||
n, success := new(big.Int).SetString(value, 16)
|
||||
if !success {
|
||||
panic("Error parsing hex number")
|
||||
}
|
||||
e := fr.Element{0, 0, 0, 0}
|
||||
e.SetBigInt(n)
|
||||
return &e
|
||||
}
|
||||
|
||||
func init() {
|
||||
var size = len(rp)
|
||||
c = make([][]*fr.Element, size)
|
||||
s = make([][]*fr.Element, size)
|
||||
m = make([][][]*fr.Element, size)
|
||||
p = make([][][]*fr.Element, size)
|
||||
|
||||
for i := 0; i < size; i++ {
|
||||
// initialize round constants and matrices
|
||||
c[i] = make([]*fr.Element, len(constants.CStr[i]))
|
||||
s[i] = make([]*fr.Element, len(constants.SStr[i]))
|
||||
m[i] = make([][]*fr.Element, len(constants.MStr[i]))
|
||||
p[i] = make([][]*fr.Element, len(constants.PStr[i]))
|
||||
|
||||
for j := 0; j < len(c[i]); j++ {
|
||||
c[i][j] = toElement(constants.CStr[i][j])
|
||||
}
|
||||
for j := 0; j < len(s[i]); j++ {
|
||||
s[i][j] = toElement(constants.SStr[i][j])
|
||||
}
|
||||
for j := 0; j < len(m[i]); j++ {
|
||||
m[i][j] = make([]*fr.Element, len(constants.MStr[i][j]))
|
||||
for k := 0; k < len(m[i][j]); k++ {
|
||||
m[i][j][k] = toElement(constants.MStr[i][j][k])
|
||||
}
|
||||
}
|
||||
for j := 0; j < len(p[i]); j++ {
|
||||
p[i][j] = make([]*fr.Element, len(constants.PStr[i][j]))
|
||||
for k := 0; k < len(p[i][j]); k++ {
|
||||
p[i][j][k] = toElement(constants.PStr[i][j][k])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,208 @@
|
||||
package poseidon_bn254
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"hash"
|
||||
"math/big"
|
||||
|
||||
"github.com/consensys/gnark-crypto/ecc/bn254/fr"
|
||||
)
|
||||
|
||||
const (
|
||||
BlockSize = fr.Bytes // BlockSize size that poseidon consumes
|
||||
)
|
||||
|
||||
func zeroElement() *fr.Element {
|
||||
return &fr.Element{0, 0, 0, 0}
|
||||
}
|
||||
|
||||
func deepCopy(dst, src []*fr.Element) {
|
||||
if len(src) > len(dst) {
|
||||
panic("Cannot copy to a smaller destination")
|
||||
}
|
||||
for i := 0; i < len(src); i++ {
|
||||
v := *src[i]
|
||||
dst[i] = &v
|
||||
}
|
||||
}
|
||||
|
||||
// Add round constants
|
||||
func arc(state []*fr.Element, C []*fr.Element, t, offset int) {
|
||||
for i := 0; i < t; i++ {
|
||||
state[i].Add(state[i], C[offset+i])
|
||||
}
|
||||
}
|
||||
|
||||
// power 5 as s-box for full state
|
||||
func sbox(state []*fr.Element, t int) {
|
||||
for i := 0; i < t; i++ {
|
||||
state[i].Exp(*state[i], alpha)
|
||||
}
|
||||
}
|
||||
|
||||
// Matrix vector multiplication
|
||||
func mix(state []*fr.Element, M [][]*fr.Element, t int) []*fr.Element {
|
||||
newState := make([]*fr.Element, t)
|
||||
|
||||
for i := 0; i < t; i++ {
|
||||
newState[i] = zeroElement()
|
||||
for j := 0; j < t; j++ {
|
||||
newState[i].Add(newState[i], zeroElement().Mul(M[j][i], state[j]))
|
||||
}
|
||||
}
|
||||
return newState
|
||||
}
|
||||
|
||||
func permutation(state []*fr.Element) []*fr.Element {
|
||||
// Minimum length of state = nInput + nOutput = 2
|
||||
t := len(state)
|
||||
index := t - 2
|
||||
RP := rp[index]
|
||||
C := c[index]
|
||||
M := m[index]
|
||||
S := s[index]
|
||||
P := p[index]
|
||||
|
||||
// 1. Pre-step to the first-half of full rounds: add round constant for round=0
|
||||
arc(state, C, t, 0)
|
||||
|
||||
// 2. First-half of full rounds starting at roundNumber = 1 except last round
|
||||
for i := 0; i < rf/2-1; i++ {
|
||||
sbox(state, t)
|
||||
arc(state, C, t, (i+1)*t)
|
||||
state = mix(state, M, t)
|
||||
}
|
||||
|
||||
// 3. Last round of first-half of full rounds
|
||||
sbox(state, t)
|
||||
arc(state, C, t, (rf/2)*t)
|
||||
state = mix(state, P, t)
|
||||
|
||||
// 4. Partial rounds
|
||||
for i := 0; i < RP; i++ {
|
||||
state[0].Exp(*state[0], alpha)
|
||||
state[0].Add(state[0], C[(rf/2+1)*t+i])
|
||||
// S[i] is a vector of [t*2-1] elements where first t elements are used to compute state[0]
|
||||
// and the remaining elements starting at [t] are used to compute state[1,..,t-1]
|
||||
offset := (t*2 - 1) * i
|
||||
newState0 := zeroElement()
|
||||
for j := 0; j < len(state); j++ {
|
||||
newState0.Add(newState0, zeroElement().Mul(state[j], S[offset+j]))
|
||||
}
|
||||
offset += t - 1
|
||||
for k := 1; k < t; k++ {
|
||||
state[k].Add(state[k], zeroElement().Mul(state[0], S[offset+k]))
|
||||
}
|
||||
state[0] = newState0
|
||||
}
|
||||
|
||||
// 5. Second-half of full rounds except last round
|
||||
for i := 0; i < rf/2-1; i++ {
|
||||
sbox(state, t)
|
||||
arc(state, C, t, (rf/2+1)*t+RP+i*t)
|
||||
state = mix(state, M, t)
|
||||
}
|
||||
|
||||
// 6. Last round of the second-half of full rounds
|
||||
sbox(state, t)
|
||||
state = mix(state, M, t)
|
||||
return state
|
||||
}
|
||||
|
||||
func Poseidon(input ...*fr.Element) *fr.Element {
|
||||
inputLength := len(input)
|
||||
if inputLength == 0 {
|
||||
panic("No support for dummy input")
|
||||
}
|
||||
|
||||
const maxLength = 16
|
||||
state := make([]*fr.Element, maxLength+1)
|
||||
state[0] = zeroElement()
|
||||
startIndex := 0
|
||||
lastIndex := 0
|
||||
|
||||
// Make a hash chain of the input if its length > maxLength
|
||||
if inputLength > maxLength {
|
||||
count := inputLength / maxLength
|
||||
for i := 0; i < count; i++ {
|
||||
lastIndex = (i + 1) * maxLength
|
||||
deepCopy(state[1:], input[startIndex:lastIndex])
|
||||
state = permutation(state)
|
||||
startIndex = lastIndex
|
||||
}
|
||||
}
|
||||
|
||||
// For the remaining part of the input OR if 1 <= inputLength <= 16
|
||||
if lastIndex < inputLength {
|
||||
lastIndex = inputLength
|
||||
remainigLength := lastIndex - startIndex
|
||||
deepCopy(state[1:], input[startIndex:lastIndex])
|
||||
state = permutation(state[:remainigLength+1])
|
||||
}
|
||||
// Return capacity element 1
|
||||
return state[1]
|
||||
}
|
||||
|
||||
func PoseidonBytes(input ...[]byte) []byte {
|
||||
inputElements := make([]*fr.Element, len(input))
|
||||
for i, ele := range input {
|
||||
num := new(big.Int).SetBytes(ele)
|
||||
if num.Cmp(fr.Modulus()) >= 0 {
|
||||
panic("not support bytes bigger than modulus")
|
||||
}
|
||||
e := fr.Element{0, 0, 0, 0}
|
||||
e.SetBigInt(num)
|
||||
inputElements[i] = &e
|
||||
}
|
||||
res := Poseidon(inputElements...).Bytes()
|
||||
return res[:]
|
||||
}
|
||||
|
||||
type digest struct {
|
||||
h fr.Element
|
||||
data [][]byte // data to hash
|
||||
}
|
||||
|
||||
func NewPoseidon() hash.Hash {
|
||||
d := new(digest)
|
||||
d.Reset()
|
||||
return d
|
||||
}
|
||||
|
||||
// Reset resets the Hash to its initial state.
|
||||
func (d *digest) Reset() {
|
||||
d.data = nil
|
||||
d.h = fr.Element{0, 0, 0, 0}
|
||||
}
|
||||
|
||||
// Only receive byte slice less than fr.Modulus()
|
||||
func (d *digest) Write(p []byte) (n int, err error) {
|
||||
n = len(p)
|
||||
num := new(big.Int).SetBytes(p)
|
||||
if num.Cmp(fr.Modulus()) >= 0 {
|
||||
return 0, errors.New("not support bytes bigger than modulus")
|
||||
}
|
||||
d.data = append(d.data, p)
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (d *digest) Size() int {
|
||||
return BlockSize
|
||||
}
|
||||
|
||||
// BlockSize returns the number of bytes Sum will return.
|
||||
func (d *digest) BlockSize() int {
|
||||
return BlockSize
|
||||
}
|
||||
|
||||
// Sum appends the current hash to b and returns the resulting slice.
|
||||
// It does not change the underlying hash state.
|
||||
func (d *digest) Sum(b []byte) []byte {
|
||||
e := fr.Element{0, 0, 0, 0}
|
||||
e.SetBigInt(new(big.Int).SetBytes(PoseidonBytes(d.data...)))
|
||||
d.h = e
|
||||
d.data = nil // flush the data already hashed
|
||||
hash := d.h.Bytes()
|
||||
b = append(b, hash[:]...)
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package poseidon_bn254_test
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
"testing"
|
||||
|
||||
"github.com/consensys/gnark-crypto/ecc/bn254/fr"
|
||||
"github.com/elliottech/poseidon_crypto/hash/poseidon_bn254"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func elementFromString(v string) *fr.Element {
|
||||
n, success := new(big.Int).SetString(v, 10)
|
||||
if !success {
|
||||
panic("Error parsing hex number")
|
||||
}
|
||||
var e fr.Element
|
||||
e.SetBigInt(n)
|
||||
return &e
|
||||
}
|
||||
|
||||
func elementFromStringHex(v string) *fr.Element {
|
||||
n, success := new(big.Int).SetString(v, 16)
|
||||
if !success {
|
||||
panic("Error parsing hex number")
|
||||
}
|
||||
var e fr.Element
|
||||
e.SetBigInt(n)
|
||||
return &e
|
||||
}
|
||||
|
||||
func TestPoseidon1(t *testing.T) {
|
||||
// WARNING: No test vector to compare with
|
||||
expectedHash := elementFromString("7764075183688725171230668857402392634761334547267776368103645048439717572548")
|
||||
length := 1
|
||||
inputs := make([]*fr.Element, length)
|
||||
for i := 0; i < length; i++ {
|
||||
e := fr.NewElement((uint64)(i + 1))
|
||||
inputs[i] = &e
|
||||
}
|
||||
actualHash := poseidon_bn254.Poseidon(inputs...)
|
||||
assert.True(t, actualHash.Equal(expectedHash), "%s != %s", actualHash, expectedHash)
|
||||
}
|
||||
|
||||
func TestPoseidon2(t *testing.T) {
|
||||
// WARNING: No test vector to compare with
|
||||
expectedHash := elementFromString("7142104613055408817911962100316808866448378443474503659992478482890339429929")
|
||||
length := 2
|
||||
inputs := make([]*fr.Element, length)
|
||||
for i := 0; i < length; i++ {
|
||||
e := fr.NewElement((uint64)(i + 1))
|
||||
inputs[i] = &e
|
||||
}
|
||||
actualHash := poseidon_bn254.Poseidon(inputs...)
|
||||
assert.True(t, actualHash.Equal(expectedHash), "%s != %s", actualHash, expectedHash)
|
||||
}
|
||||
|
||||
func TestPoseidon4(t *testing.T) {
|
||||
// WARNING: No test vector to compare with
|
||||
expectedHash := elementFromString("7817711165059374331357136443537800893307845083525445872661165200086166013245")
|
||||
length := 4
|
||||
inputs := make([]*fr.Element, length)
|
||||
for i := 0; i < length; i++ {
|
||||
e := fr.NewElement((uint64)(i + 1))
|
||||
inputs[i] = &e
|
||||
}
|
||||
actualHash := poseidon_bn254.Poseidon(inputs...)
|
||||
assert.True(t, actualHash.Equal(expectedHash), "%s != %s", actualHash, expectedHash)
|
||||
}
|
||||
|
||||
func TestPoseidon13(t *testing.T) {
|
||||
// WARNING: No test vector to compare with
|
||||
expectedHash := elementFromString("1709610050961943784828399921362905178787999827108026634048665681910636069934")
|
||||
length := 13
|
||||
inputs := make([]*fr.Element, length)
|
||||
for i := 0; i < length; i++ {
|
||||
e := fr.NewElement((uint64)(i + 1))
|
||||
inputs[i] = &e
|
||||
}
|
||||
actualHash := poseidon_bn254.Poseidon(inputs...)
|
||||
assert.True(t, actualHash.Equal(expectedHash), "%s != %s", actualHash, expectedHash)
|
||||
}
|
||||
|
||||
func TestPoseidon16(t *testing.T) {
|
||||
// WARNING: No test vector to compare with
|
||||
expectedHash := elementFromString("8319791455060392555425392842391403897548969645190976863995973180967774875286")
|
||||
length := 16
|
||||
inputs := make([]*fr.Element, length)
|
||||
for i := 0; i < length; i++ {
|
||||
e := fr.NewElement((uint64)(i + 1))
|
||||
inputs[i] = &e
|
||||
}
|
||||
actualHash := poseidon_bn254.Poseidon(inputs...)
|
||||
assert.True(t, actualHash.Equal(expectedHash), "%s != %s", actualHash, expectedHash)
|
||||
}
|
||||
|
||||
func TestPoseidon24(t *testing.T) {
|
||||
// WARNING: No test vector to compare with
|
||||
expectedHash := elementFromString("14281896993318141900551144554156181598834585543901557749703302979893059224887")
|
||||
length := 24
|
||||
inputs := make([]*fr.Element, length)
|
||||
for i := 0; i < length; i++ {
|
||||
e := fr.NewElement((uint64)(i + 1))
|
||||
inputs[i] = &e
|
||||
}
|
||||
actualHash := poseidon_bn254.Poseidon(inputs...)
|
||||
assert.True(t, actualHash.Equal(expectedHash), "%s != %s", actualHash, expectedHash)
|
||||
}
|
||||
|
||||
func TestPoseidon30(t *testing.T) {
|
||||
// WARNING: No test vector to compare with
|
||||
expectedHash := elementFromString("3706864405066113783363062549980271879113588784557216652303342540436728346372")
|
||||
length := 30
|
||||
inputs := make([]*fr.Element, length)
|
||||
for i := 0; i < length; i++ {
|
||||
e := fr.NewElement((uint64)(i + 1))
|
||||
inputs[i] = &e
|
||||
}
|
||||
actualHash := poseidon_bn254.Poseidon(inputs...)
|
||||
assert.True(t, actualHash.Equal(expectedHash), "%s != %s", actualHash, expectedHash)
|
||||
}
|
||||
|
||||
func TestPoseidon256(t *testing.T) {
|
||||
// WARNING: No test vector to compare with
|
||||
expectedHash := elementFromString("3889232958018785041730045800798978544000060048890444628344970190264245196615")
|
||||
length := 256
|
||||
inputs := make([]*fr.Element, length)
|
||||
for i := 0; i < length; i++ {
|
||||
e := fr.NewElement((uint64)(i + 1))
|
||||
inputs[i] = &e
|
||||
}
|
||||
actualHash := poseidon_bn254.Poseidon(inputs...)
|
||||
assert.True(t, actualHash.Equal(expectedHash), "%s != %s", actualHash, expectedHash)
|
||||
}
|
||||
|
||||
func TestConsistency(t *testing.T) {
|
||||
// Check whether Poseidon returns the same value for the same input
|
||||
// Test vector https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/master/code/test_vectors.txt
|
||||
inputsStr := []string{"1", "2", "3", "4"}
|
||||
inputs := make([]*fr.Element, len(inputsStr))
|
||||
for i := 0; i < len(inputsStr); i++ {
|
||||
inputs[i] = elementFromString(inputsStr[i])
|
||||
}
|
||||
actualHash1 := poseidon_bn254.Poseidon(inputs...)
|
||||
actualHash2 := poseidon_bn254.Poseidon(inputs...)
|
||||
assert.True(t, actualHash1.Equal(actualHash2), "%s != %s", actualHash1, actualHash2)
|
||||
}
|
||||
|
||||
func TestPoseidonBytes(t *testing.T) {
|
||||
// Test vector https://extgit.iaik.tugraz.at/krypto/hadeshash/-/blob/master/code/test_vectors.txt
|
||||
expectedHash := elementFromStringHex("FCA49B798923AB0239DE1C9E7A4A9A2210312B6A2F616D18B5A87F9B628AE29")
|
||||
inputs := make([][]byte, 2)
|
||||
inputs[0] = make([]byte, 1)
|
||||
inputs[0][0] = 1
|
||||
inputs[1] = make([]byte, 1)
|
||||
inputs[1][0] = 2
|
||||
actualHash := poseidon_bn254.PoseidonBytes(inputs...)
|
||||
actualHashEle := fr.Element{0, 0, 0, 0}
|
||||
actualHashEle.SetBytes(actualHash)
|
||||
assert.True(t, actualHashEle.Equal(expectedHash), "%s != %s", actualHashEle, expectedHash)
|
||||
}
|
||||
|
||||
func TestDigest(t *testing.T) {
|
||||
expectedHash := elementFromStringHex("FCA49B798923AB0239DE1C9E7A4A9A2210312B6A2F616D18B5A87F9B628AE29")
|
||||
hFunc := poseidon_bn254.NewPoseidon()
|
||||
inputs := make([][]byte, 2)
|
||||
inputs[0] = make([]byte, 1)
|
||||
inputs[0][0] = 1
|
||||
inputs[1] = make([]byte, 1)
|
||||
inputs[1][0] = 2
|
||||
hFunc.Write(inputs[0])
|
||||
hFunc.Write(inputs[1])
|
||||
actualHash := hFunc.Sum(nil)
|
||||
actualHashEle := fr.Element{0, 0, 0, 0}
|
||||
actualHashEle.SetBytes(actualHash)
|
||||
assert.True(t, actualHashEle.Equal(expectedHash), "%s != %s", actualHashEle, expectedHash)
|
||||
|
||||
hFunc.Reset()
|
||||
bigNumber, _ := new(big.Int).SetString("21888242871839275222246405745257275088548364400416034343698204186575808495617", 10)
|
||||
inputs[0] = bigNumber.Bytes()
|
||||
n, err := hFunc.Write(inputs[0])
|
||||
assert.EqualError(t, err, "not support bytes bigger than modulus")
|
||||
assert.Equal(t, n, 0)
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package signature
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
curve "github.com/elliottech/poseidon_crypto/curve/ecgfp5"
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
type Signature struct {
|
||||
S curve.ECgFp5Scalar
|
||||
E curve.ECgFp5Scalar
|
||||
}
|
||||
|
||||
type NumericalSignature [10]uint64
|
||||
|
||||
func (s Signature) ToNumericalSignature() NumericalSignature {
|
||||
return NumericalSignature{
|
||||
s.S[0], s.S[1], s.S[2], s.S[3], s.S[4],
|
||||
s.E[0], s.E[1], s.E[2], s.E[3], s.E[4],
|
||||
}
|
||||
}
|
||||
|
||||
func (s Signature) DeepCopy() Signature {
|
||||
return Signature{
|
||||
S: s.S.DeepCopy(),
|
||||
E: s.E.DeepCopy(),
|
||||
}
|
||||
}
|
||||
|
||||
// (s little endian) || (e little endian)
|
||||
func (s Signature) ToBytes() []byte {
|
||||
sBytes := s.S.ToLittleEndianBytes()
|
||||
eBytes := s.E.ToLittleEndianBytes()
|
||||
res := make([]byte, 80)
|
||||
copy(res[:40], sBytes[:])
|
||||
copy(res[40:], eBytes[:])
|
||||
return res
|
||||
}
|
||||
|
||||
func SigFromBytes(b []byte) (Signature, error) {
|
||||
if len(b) != 80 {
|
||||
return ZERO_SIG, fmt.Errorf("signature length should be 80 but is %d", len(b))
|
||||
}
|
||||
|
||||
return Signature{
|
||||
S: curve.ScalarElementFromLittleEndianBytes(b[:40]),
|
||||
E: curve.ScalarElementFromLittleEndianBytes(b[40:]),
|
||||
}, nil
|
||||
}
|
||||
|
||||
var ZERO_SIG = Signature{
|
||||
S: curve.ZERO,
|
||||
E: curve.ZERO,
|
||||
}
|
||||
|
||||
var ONE_SK = curve.ONE
|
||||
|
||||
// Public key is actually an EC point (4 Fp5 elements), but it can be encoded as a single Fp5 element.
|
||||
func SchnorrPkFromSk(sk curve.ECgFp5Scalar) gFp5.Element {
|
||||
return curve.GENERATOR_ECgFp5Point.Mul(&sk).Encode()
|
||||
}
|
||||
|
||||
func SchnorrSignHashedMessage(hashedMsg gFp5.Element, sk curve.ECgFp5Scalar) Signature {
|
||||
// Sample random scalar `k` and compute `r = k * G`
|
||||
k := curve.SampleScalarCrypto()
|
||||
r := curve.GENERATOR_ECgFp5Point.Mul(&k).Encode()
|
||||
|
||||
// Compute `e = H(r || H(m))`, which is a scalar point
|
||||
preImage := make([]g.Element, 5+5)
|
||||
for i, elem := range r.ToBasefieldArray() {
|
||||
preImage[i] = elem
|
||||
}
|
||||
for i, elem := range hashedMsg.ToBasefieldArray() {
|
||||
preImage[i+5] = elem
|
||||
}
|
||||
|
||||
e := curve.FromGfp5(p2.HashToQuinticExtension(preImage))
|
||||
return Signature{
|
||||
S: k.Sub(*e.Mul(&sk)),
|
||||
E: e,
|
||||
}
|
||||
}
|
||||
|
||||
func SchnorrSignHashedMessage2(hashedMsg gFp5.Element, sk, k curve.ECgFp5Scalar) Signature {
|
||||
r := curve.GENERATOR_ECgFp5Point.Mul(&k).Encode()
|
||||
// Compute `e = H(r || H(m))`, which is a scalar point
|
||||
preImage := make([]g.Element, 5+5)
|
||||
for i, elem := range r.ToBasefieldArray() {
|
||||
preImage[i] = elem
|
||||
}
|
||||
for i, elem := range hashedMsg.ToBasefieldArray() {
|
||||
preImage[i+5] = elem
|
||||
}
|
||||
|
||||
e := curve.FromGfp5(p2.HashToQuinticExtension(preImage))
|
||||
return Signature{
|
||||
S: k.Sub(*e.Mul(&sk)),
|
||||
E: e,
|
||||
}
|
||||
}
|
||||
|
||||
func Validate(pubKey, hashedMsg, sig []byte) error {
|
||||
pk, err := gFp5.FromCanonicalLittleEndianBytes(pubKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to convert public key bytes to field element: %w", err)
|
||||
}
|
||||
hashedMsgElem, err := gFp5.FromCanonicalLittleEndianBytes(hashedMsg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to convert hashed message bytes to field element: %w", err)
|
||||
}
|
||||
s, err := SigFromBytes(sig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to convert signature bytes to Schnorr signature: %w", err)
|
||||
}
|
||||
|
||||
valid := IsSchnorrSignatureValid(&pk, &hashedMsgElem, s)
|
||||
if !valid {
|
||||
return fmt.Errorf("signature is invalid")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func IsSchnorrSignatureValid(pubKey, hashedMsg *gFp5.Element, sig Signature) bool {
|
||||
pubKeyWs, ok := curve.DecodeFp5AsWeierstrass(*pubKey)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
rV := curve.MulAdd2(curve.GENERATOR_WEIERSTRASS, pubKeyWs, sig.S, sig.E).Encode() // r_v = s*G + e*pk
|
||||
|
||||
preImage := make([]g.Element, 5+5)
|
||||
for i, elem := range rV.ToBasefieldArray() {
|
||||
preImage[i] = elem
|
||||
}
|
||||
for i, elem := range hashedMsg.ToBasefieldArray() {
|
||||
preImage[i+5] = elem
|
||||
}
|
||||
eV := curve.FromGfp5(p2.HashToQuinticExtension(preImage))
|
||||
|
||||
return eV.Equals(&sig.E) // e_v == e
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package signature
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
curve "github.com/elliottech/poseidon_crypto/curve/ecgfp5"
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
func TestSchnorrSignAndVerify(t *testing.T) {
|
||||
sk := curve.SampleScalarCrypto() // Sample a secret key
|
||||
msg := g.RandArray(244)
|
||||
hashedMsg := p2.HashToQuinticExtension(msg)
|
||||
k := curve.SampleScalarCrypto()
|
||||
|
||||
sig := SchnorrSignHashedMessage2(hashedMsg, sk, k)
|
||||
pk := SchnorrPkFromSk(sk)
|
||||
if !IsSchnorrSignatureValid(&pk, &hashedMsg, sig) {
|
||||
t.Fatalf("Signature is invalid")
|
||||
}
|
||||
}
|
||||
|
||||
func TestComparativeSchnorrSignAndVerify(t *testing.T) {
|
||||
sks := []curve.ECgFp5Scalar{
|
||||
curve.ECgFp5Scalar{
|
||||
12235002942052073545,
|
||||
1175977464658719998,
|
||||
8536934969147463310,
|
||||
6524687619313720391,
|
||||
2922072024880609112,
|
||||
},
|
||||
curve.ECgFp5Scalar{
|
||||
14609471659974493146,
|
||||
15558617123161593410,
|
||||
853367204868339037,
|
||||
17594253198278631904,
|
||||
368396584122947478,
|
||||
},
|
||||
curve.ECgFp5Scalar{
|
||||
846395111423676945, 1354180063821346280, 5751371120309175011, 4898038106472090654, 1076345918732914302,
|
||||
},
|
||||
}
|
||||
hashedMessages := []gFp5.Element{
|
||||
gFp5.Element{
|
||||
g.FromUint64(8398652514106806347),
|
||||
g.FromUint64(11069112711939986896),
|
||||
g.FromUint64(9732488227085561369),
|
||||
g.FromUint64(18076754337204438535),
|
||||
g.FromUint64(17155407358725346236),
|
||||
},
|
||||
gFp5.Element{
|
||||
g.FromUint64(14569490467507212064),
|
||||
g.FromUint64(2707063505563578676),
|
||||
g.FromUint64(7506743487465742335),
|
||||
g.FromUint64(12569771346154554175),
|
||||
g.FromUint64(4305083698940175790),
|
||||
},
|
||||
gFp5.Element{
|
||||
g.FromUint64(17529153479246803593),
|
||||
g.FromUint64(1743712677205511695),
|
||||
g.FromUint64(4834285972617397460),
|
||||
g.FromUint64(5486672566342530358),
|
||||
g.FromUint64(7254989001695704129),
|
||||
},
|
||||
}
|
||||
ks := []curve.ECgFp5Scalar{
|
||||
curve.ECgFp5Scalar{
|
||||
5245666847777449560,
|
||||
15178169970799106939,
|
||||
4403065012435293749,
|
||||
15306540389399388999,
|
||||
8935555081913173844,
|
||||
},
|
||||
curve.ECgFp5Scalar{
|
||||
1980123857560067020,
|
||||
10696795398834097509,
|
||||
3211831869376171671,
|
||||
6194822139276031840,
|
||||
3482023782412490864,
|
||||
},
|
||||
curve.ECgFp5Scalar{
|
||||
10299597990997564957, 8547298489021408803, 12250978550108858722, 5282281975236198197, 5328603554431393061,
|
||||
},
|
||||
}
|
||||
expectedSs := [][5]uint64{
|
||||
[5]uint64{
|
||||
6950590877883398434,
|
||||
17178336263794770543,
|
||||
11012823478139181320,
|
||||
16445091359523510936,
|
||||
5882925226143600273,
|
||||
},
|
||||
[5]uint64{
|
||||
15189311883262425203,
|
||||
16924634885527914505,
|
||||
11098200095411565797,
|
||||
11441434601417451505,
|
||||
2245797172600273048,
|
||||
},
|
||||
[5]uint64{
|
||||
1747989245728027396, 18083435619737379521, 18276259610811995786, 15101757397705334408, 5007814817019340642,
|
||||
},
|
||||
}
|
||||
expectedEs := [][5]uint64{
|
||||
[5]uint64{
|
||||
4544744459434870309,
|
||||
4180764085957612004,
|
||||
3024669018778978615,
|
||||
15433417688859446606,
|
||||
6775027260348937828,
|
||||
},
|
||||
[5]uint64{
|
||||
4905460437060282008,
|
||||
9275377852059362729,
|
||||
10383772785796962929,
|
||||
6858067464918579610,
|
||||
7078247668913970626,
|
||||
},
|
||||
[5]uint64{
|
||||
4911725746357568132, 12205663641120664338, 16433506899074513700, 14763562571101437023, 2547950465160283358,
|
||||
},
|
||||
}
|
||||
|
||||
for i := 0; i < len(sks); i++ {
|
||||
sig := SchnorrSignHashedMessage2(hashedMessages[i], sks[i], ks[i])
|
||||
for j := 0; j < 5; j++ {
|
||||
if sig.S[j] != expectedSs[i][j] {
|
||||
t.Fatalf("sig.S[%d]: Expected %d, but got %d", j, expectedSs[i][j], sig.S[j])
|
||||
}
|
||||
if sig.E[j] != expectedEs[i][j] {
|
||||
t.Fatalf("sig.E[%d]: Expected %d, but got %d", j, expectedEs[i][j], sig.E[j])
|
||||
}
|
||||
}
|
||||
|
||||
pk := SchnorrPkFromSk(sks[i])
|
||||
if !IsSchnorrSignatureValid(&pk, &hashedMessages[i], sig) {
|
||||
t.Fatalf("Signature is invalid")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBytes(t *testing.T) {
|
||||
sk := curve.SampleScalarCrypto() // Sample a secret key
|
||||
msg := g.RandArray(244) // Random message of 244 field elements (big)
|
||||
hashedMsg := p2.HashToQuinticExtension(msg)
|
||||
|
||||
sig := SchnorrSignHashedMessage(hashedMsg, sk)
|
||||
sig2, _ := SigFromBytes(sig.ToBytes())
|
||||
if !sig2.S.Equals(&sig.S) || !sig2.E.Equals(&sig.E) {
|
||||
t.Fatalf("bytes do not match")
|
||||
}
|
||||
|
||||
pk, _ := gFp5.FromCanonicalLittleEndianBytes(SchnorrPkFromSk(sk).ToLittleEndianBytes())
|
||||
|
||||
if err := Validate(pk.ToLittleEndianBytes(), hashedMsg.ToLittleEndianBytes(), sig2.ToBytes()); err != nil {
|
||||
t.Fatalf("Signature is invalid")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user