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:
@@ -50,3 +50,15 @@ GRVT_ENV=prod
|
||||
# GRVT_COOKIE="gravity=..." # Pre-provisioned session cookie (auto-refresh uses API key when absent)
|
||||
# GRVT_ACCOUNT_ID= # Populated automatically after login
|
||||
# GRVT_SIGNER_PATH=./grvt-signer.cjs # Custom signature provider module
|
||||
|
||||
# Lighter authentication (set when EXCHANGE=lighter)
|
||||
LIGHTER_ACCOUNT_INDEX=
|
||||
LIGHTER_API_PRIVATE_KEY= # 40-byte hex private key (e.g., 0x...)
|
||||
LIGHTER_API_KEY_INDEX=0 # API key slot (default 0)
|
||||
LIGHTER_SYMBOL=BTCUSDT # Trading pair (defaults to TRADE_SYMBOL when omitted)
|
||||
LIGHTER_ENV=testnet # mainnet | testnet | staging | dev
|
||||
# LIGHTER_BASE_URL=https://testnet.zklighter.elliot.ai
|
||||
# LIGHTER_CHAIN_ID=300 # Override inferred chain id when needed
|
||||
# LIGHTER_MARKET_ID=1 # Prefer explicit market id when symbols differ
|
||||
# LIGHTER_PRICE_DECIMALS=3 # Manual override for price decimals (optional)
|
||||
# LIGHTER_SIZE_DECIMALS=3 # Manual override for size decimals (optional)
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -160,6 +160,33 @@ function createAdapterOrThrow(symbol: string): ExchangeAdapter {
|
||||
aster: { apiKey, apiSecret },
|
||||
});
|
||||
}
|
||||
if (exchangeId === "lighter") {
|
||||
const accountIndex = parseInt(process.env.LIGHTER_ACCOUNT_INDEX ?? "", 10);
|
||||
const privateKey = process.env.LIGHTER_API_PRIVATE_KEY;
|
||||
if (!Number.isFinite(accountIndex) || !privateKey) {
|
||||
throw new Error("LIGHTER_ACCOUNT_INDEX and LIGHTER_API_PRIVATE_KEY environment variables are required for Lighter exchange");
|
||||
}
|
||||
const apiKeyIndex = process.env.LIGHTER_API_KEY_INDEX ? Number(process.env.LIGHTER_API_KEY_INDEX) : 0;
|
||||
const lighterSymbol = process.env.LIGHTER_SYMBOL ?? symbol;
|
||||
const marketId = process.env.LIGHTER_MARKET_ID ? Number(process.env.LIGHTER_MARKET_ID) : undefined;
|
||||
const priceDecimals = process.env.LIGHTER_PRICE_DECIMALS ? Number(process.env.LIGHTER_PRICE_DECIMALS) : undefined;
|
||||
const sizeDecimals = process.env.LIGHTER_SIZE_DECIMALS ? Number(process.env.LIGHTER_SIZE_DECIMALS) : undefined;
|
||||
return createExchangeAdapter({
|
||||
exchange: exchangeId,
|
||||
symbol,
|
||||
lighter: {
|
||||
marketSymbol: lighterSymbol,
|
||||
accountIndex,
|
||||
apiPrivateKey: privateKey,
|
||||
apiKeyIndex,
|
||||
baseUrl: process.env.LIGHTER_BASE_URL,
|
||||
environment: process.env.LIGHTER_ENV,
|
||||
marketId,
|
||||
priceDecimals,
|
||||
sizeDecimals,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return createExchangeAdapter({
|
||||
exchange: exchangeId,
|
||||
|
||||
@@ -29,6 +29,7 @@ export interface KlineListener {
|
||||
|
||||
export interface ExchangeAdapter {
|
||||
readonly id: string;
|
||||
supportsTrailingStops(): boolean;
|
||||
watchAccount(cb: AccountListener): void;
|
||||
watchOrders(cb: OrderListener): void;
|
||||
watchDepth(symbol: string, cb: DepthListener): void;
|
||||
|
||||
@@ -31,6 +31,10 @@ export class AsterExchangeAdapter implements ExchangeAdapter {
|
||||
this.symbol = (credentials.symbol ?? process.env.TRADE_SYMBOL ?? "BTCUSDT").toUpperCase();
|
||||
}
|
||||
|
||||
supportsTrailingStops(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
private safeInvoke<T extends (...args: any[]) => void>(context: string, cb: T): T {
|
||||
const wrapped = ((...args: any[]) => {
|
||||
try {
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import type { ExchangeAdapter } from "./adapter";
|
||||
import { AsterExchangeAdapter, type AsterCredentials } from "./aster-adapter";
|
||||
import { GrvtExchangeAdapter, type GrvtCredentials } from "./grvt/adapter";
|
||||
import { LighterExchangeAdapter, type LighterCredentials } from "./lighter/adapter";
|
||||
|
||||
export interface ExchangeFactoryOptions {
|
||||
symbol: string;
|
||||
exchange?: string;
|
||||
aster?: AsterCredentials;
|
||||
grvt?: GrvtCredentials;
|
||||
lighter?: LighterCredentials;
|
||||
}
|
||||
|
||||
export type SupportedExchangeId = "aster" | "grvt";
|
||||
export type SupportedExchangeId = "aster" | "grvt" | "lighter";
|
||||
|
||||
export function resolveExchangeId(value?: string | null): SupportedExchangeId {
|
||||
const fallback = (value ?? process.env.EXCHANGE ?? process.env.TRADE_EXCHANGE ?? "aster")
|
||||
@@ -17,11 +19,14 @@ export function resolveExchangeId(value?: string | null): SupportedExchangeId {
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (fallback === "grvt") return "grvt";
|
||||
if (fallback === "lighter") return "lighter";
|
||||
return "aster";
|
||||
}
|
||||
|
||||
export function getExchangeDisplayName(id: SupportedExchangeId): string {
|
||||
return id === "grvt" ? "GRVT" : "AsterDex";
|
||||
if (id === "grvt") return "GRVT";
|
||||
if (id === "lighter") return "Lighter";
|
||||
return "AsterDex";
|
||||
}
|
||||
|
||||
export function createExchangeAdapter(options: ExchangeFactoryOptions): ExchangeAdapter {
|
||||
@@ -29,5 +34,8 @@ export function createExchangeAdapter(options: ExchangeFactoryOptions): Exchange
|
||||
if (id === "grvt") {
|
||||
return new GrvtExchangeAdapter({ ...options.grvt, symbol: options.symbol });
|
||||
}
|
||||
if (id === "lighter") {
|
||||
return new LighterExchangeAdapter({ ...options.lighter, displaySymbol: options.symbol });
|
||||
}
|
||||
return new AsterExchangeAdapter({ ...options.aster, symbol: options.symbol });
|
||||
}
|
||||
|
||||
@@ -93,6 +93,10 @@ export class GrvtExchangeAdapter implements ExchangeAdapter {
|
||||
});
|
||||
}
|
||||
|
||||
supportsTrailingStops(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
watchAccount(cb: AccountListener): void {
|
||||
void this.ensureInitialized("watchAccount");
|
||||
this.gateway.onAccount(this.safeInvoke("watchAccount", cb));
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import type {
|
||||
AccountListener,
|
||||
DepthListener,
|
||||
ExchangeAdapter,
|
||||
KlineListener,
|
||||
OrderListener,
|
||||
TickerListener,
|
||||
} from "../adapter";
|
||||
import type { AsterOrder, CreateOrderParams } from "../types";
|
||||
import { extractMessage } from "../../utils/errors";
|
||||
import { LighterGateway, type LighterGatewayOptions } from "./gateway";
|
||||
|
||||
export interface LighterCredentials {
|
||||
displaySymbol?: string;
|
||||
marketSymbol?: string;
|
||||
symbol?: string; // fallback alias
|
||||
accountIndex?: number;
|
||||
l1Address?: string;
|
||||
apiKeys?: Record<number, string>;
|
||||
apiPrivateKey?: string;
|
||||
apiKeyIndex?: number;
|
||||
environment?: string;
|
||||
baseUrl?: string;
|
||||
marketId?: number;
|
||||
priceDecimals?: number;
|
||||
sizeDecimals?: number;
|
||||
chainId?: number;
|
||||
tickerPollMs?: number;
|
||||
klinePollMs?: number;
|
||||
}
|
||||
|
||||
export class LighterExchangeAdapter implements ExchangeAdapter {
|
||||
readonly id = "lighter";
|
||||
private readonly gateway: LighterGateway;
|
||||
private initPromise: Promise<void> | null = null;
|
||||
private readonly initContexts = new Set<string>();
|
||||
|
||||
constructor(credentials: LighterCredentials = {}) {
|
||||
const displaySymbolSource = credentials.displaySymbol ?? process.env.TRADE_SYMBOL ?? "";
|
||||
if (!displaySymbolSource) {
|
||||
throw new Error("TRADE_SYMBOL environment variable is required");
|
||||
}
|
||||
const displaySymbol = displaySymbolSource;
|
||||
const marketSymbolSource = credentials.marketSymbol ?? credentials.symbol ?? process.env.LIGHTER_SYMBOL ?? displaySymbol;
|
||||
const marketSymbol = marketSymbolSource.toUpperCase();
|
||||
const accountIndex = credentials.accountIndex ?? parseInt(process.env.LIGHTER_ACCOUNT_INDEX ?? "", 10);
|
||||
if (!Number.isFinite(accountIndex)) {
|
||||
throw new Error("LIGHTER_ACCOUNT_INDEX environment variable is required");
|
||||
}
|
||||
const apiKeys = resolveApiKeys(credentials);
|
||||
const environment = credentials.environment ?? process.env.LIGHTER_ENV;
|
||||
const marketId = credentials.marketId ?? (process.env.LIGHTER_MARKET_ID ? Number(process.env.LIGHTER_MARKET_ID) : undefined);
|
||||
const priceDecimals = credentials.priceDecimals ?? (process.env.LIGHTER_PRICE_DECIMALS ? Number(process.env.LIGHTER_PRICE_DECIMALS) : undefined);
|
||||
const sizeDecimals = credentials.sizeDecimals ?? (process.env.LIGHTER_SIZE_DECIMALS ? Number(process.env.LIGHTER_SIZE_DECIMALS) : undefined);
|
||||
const l1Address = credentials.l1Address ?? process.env.LIGHTER_L1_ADDRESS ?? null;
|
||||
const gatewayOptions: LighterGatewayOptions = {
|
||||
symbol: displaySymbol,
|
||||
marketSymbol,
|
||||
accountIndex,
|
||||
apiKeys,
|
||||
baseUrl: credentials.baseUrl ?? process.env.LIGHTER_BASE_URL,
|
||||
environment: environment as LighterGatewayOptions["environment"],
|
||||
marketId,
|
||||
priceDecimals,
|
||||
sizeDecimals,
|
||||
chainId: credentials.chainId ?? (process.env.LIGHTER_CHAIN_ID ? Number(process.env.LIGHTER_CHAIN_ID) : undefined),
|
||||
tickerPollMs: credentials.tickerPollMs,
|
||||
klinePollMs: credentials.klinePollMs,
|
||||
logger: (context, error) => this.logError(context, error),
|
||||
l1Address: l1Address ?? undefined,
|
||||
};
|
||||
this.gateway = new LighterGateway(gatewayOptions);
|
||||
}
|
||||
|
||||
supportsTrailingStops(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
watchAccount(handler: AccountListener): void {
|
||||
void this.ensureInitialized("watchAccount");
|
||||
this.gateway.onAccount(handler);
|
||||
}
|
||||
|
||||
watchOrders(handler: OrderListener): void {
|
||||
void this.ensureInitialized("watchOrders");
|
||||
this.gateway.onOrders(handler);
|
||||
}
|
||||
|
||||
watchDepth(_symbol: string, handler: DepthListener): void {
|
||||
void this.ensureInitialized("watchDepth");
|
||||
this.gateway.onDepth(handler);
|
||||
}
|
||||
|
||||
watchTicker(_symbol: string, handler: TickerListener): void {
|
||||
void this.ensureInitialized("watchTicker");
|
||||
this.gateway.onTicker(handler);
|
||||
}
|
||||
|
||||
watchKlines(_symbol: string, interval: string, handler: KlineListener): void {
|
||||
void this.ensureInitialized(`watchKlines:${interval}`);
|
||||
this.gateway.watchKlines(interval, handler);
|
||||
}
|
||||
|
||||
async createOrder(params: CreateOrderParams): Promise<AsterOrder> {
|
||||
await this.ensureInitialized("createOrder");
|
||||
return this.gateway.createOrder(params);
|
||||
}
|
||||
|
||||
async cancelOrder(params: { symbol: string; orderId: number | string }): Promise<void> {
|
||||
await this.ensureInitialized("cancelOrder");
|
||||
await this.gateway.cancelOrder({ orderId: params.orderId });
|
||||
}
|
||||
|
||||
async cancelOrders(params: { symbol: string; orderIdList: Array<number | string> }): Promise<void> {
|
||||
await this.ensureInitialized("cancelOrders");
|
||||
for (const orderId of params.orderIdList) {
|
||||
await this.gateway.cancelOrder({ orderId });
|
||||
}
|
||||
}
|
||||
|
||||
async cancelAllOrders(_params: { symbol: string }): Promise<void> {
|
||||
await this.ensureInitialized("cancelAllOrders");
|
||||
await this.gateway.cancelAllOrders();
|
||||
}
|
||||
|
||||
private ensureInitialized(context?: string): Promise<void> {
|
||||
if (!this.initPromise) {
|
||||
this.initContexts.clear();
|
||||
this.initPromise = this.gateway.ensureInitialized().catch((error) => {
|
||||
this.logError("initialize", error);
|
||||
this.initPromise = null;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
if (context && !this.initContexts.has(context)) {
|
||||
this.initContexts.add(context);
|
||||
this.initPromise.catch((error) => this.logError(context, error));
|
||||
}
|
||||
return this.initPromise;
|
||||
}
|
||||
|
||||
private logError(context: string, error: unknown): void {
|
||||
console.error(`[LighterExchangeAdapter] ${context} failed: ${extractMessage(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function resolveApiKeys(credentials: LighterCredentials): Record<number, string> {
|
||||
if (credentials.apiKeys && Object.keys(credentials.apiKeys).length) {
|
||||
return credentials.apiKeys;
|
||||
}
|
||||
const privateKey = credentials.apiPrivateKey ?? process.env.LIGHTER_API_PRIVATE_KEY;
|
||||
if (!privateKey) {
|
||||
throw new Error("LIGHTER_API_PRIVATE_KEY environment variable is required");
|
||||
}
|
||||
const apiKeyIndex = credentials.apiKeyIndex ?? (process.env.LIGHTER_API_KEY_INDEX ? Number(process.env.LIGHTER_API_KEY_INDEX) : 0);
|
||||
if (!Number.isInteger(apiKeyIndex) || apiKeyIndex < 0) {
|
||||
throw new Error("Invalid LIGHTER_API_KEY_INDEX value");
|
||||
}
|
||||
return { [apiKeyIndex]: privateKey };
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
export function normalizeHex(input: string): string {
|
||||
const trimmed = input.trim();
|
||||
return trimmed.startsWith("0x") || trimmed.startsWith("0X") ? trimmed.slice(2) : trimmed;
|
||||
}
|
||||
|
||||
export function hexToBytes(hex: string): Uint8Array {
|
||||
const normalized = normalizeHex(hex);
|
||||
if (normalized.length % 2 !== 0) {
|
||||
throw new Error("Hex string must have even length");
|
||||
}
|
||||
const out = new Uint8Array(normalized.length / 2);
|
||||
for (let i = 0; i < normalized.length; i += 2) {
|
||||
const byte = normalized.slice(i, i + 2);
|
||||
const value = Number.parseInt(byte, 16);
|
||||
if (Number.isNaN(value)) {
|
||||
throw new Error(`Invalid hex byte: ${byte}`);
|
||||
}
|
||||
out[i / 2] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function bytesToHex(bytes: Uint8Array, withPrefix = false): string {
|
||||
const hex = Array.from(bytes)
|
||||
.map((byte) => byte.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
return withPrefix ? `0x${hex}` : hex;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
export type LighterEnvironment = "mainnet" | "testnet" | "staging" | "dev";
|
||||
|
||||
export interface LighterHostConfig {
|
||||
rest: string;
|
||||
ws: string;
|
||||
}
|
||||
|
||||
export const LIGHTER_HOSTS: Record<LighterEnvironment, LighterHostConfig> = {
|
||||
mainnet: {
|
||||
rest: "https://mainnet.zklighter.elliot.ai",
|
||||
ws: "wss://mainnet.zklighter.elliot.ai/stream",
|
||||
},
|
||||
testnet: {
|
||||
rest: "https://testnet.zklighter.elliot.ai",
|
||||
ws: "wss://testnet.zklighter.elliot.ai/stream",
|
||||
},
|
||||
staging: {
|
||||
rest: "https://staging.zklighter.elliot.ai",
|
||||
ws: "wss://staging.zklighter.elliot.ai/stream",
|
||||
},
|
||||
dev: {
|
||||
rest: "https://dev.zklighter.elliot.ai",
|
||||
ws: "wss://dev.zklighter.elliot.ai/stream",
|
||||
},
|
||||
};
|
||||
|
||||
export const LIGHTER_CHAIN_IDS: Record<LighterEnvironment, number> = {
|
||||
mainnet: 304,
|
||||
testnet: 300,
|
||||
staging: 300,
|
||||
dev: 300,
|
||||
};
|
||||
|
||||
export const DEFAULT_LIGHTER_ENVIRONMENT: LighterEnvironment = "testnet";
|
||||
|
||||
export const DEFAULT_TRANSACTION_EXPIRY_BUFFER_MS = 10 * 60 * 1000 - 1000; // 10 min minus 1s
|
||||
export const DEFAULT_AUTH_TOKEN_HORIZON_MS = 10 * 60 * 1000; // server default is 10 minutes
|
||||
export const DEFAULT_AUTH_TOKEN_BUFFER_MS = 60 * 1000; // refresh one minute before expiry
|
||||
|
||||
export const DEFAULT_ORDER_EXPIRY_PLACEHOLDER = -1; // signer converts -1 -> 28 days
|
||||
export const IMMEDIATE_OR_CANCEL_EXPIRY_PLACEHOLDER = 0; // signer treats 0 as immediate
|
||||
|
||||
export const LIGHTER_ORDER_TYPE = {
|
||||
LIMIT: 0,
|
||||
MARKET: 1,
|
||||
STOP_LOSS: 2,
|
||||
STOP_LOSS_LIMIT: 3,
|
||||
TAKE_PROFIT: 4,
|
||||
TAKE_PROFIT_LIMIT: 5,
|
||||
TWAP: 6,
|
||||
} as const;
|
||||
|
||||
export const LIGHTER_TIME_IN_FORCE = {
|
||||
IMMEDIATE_OR_CANCEL: 0,
|
||||
GOOD_TILL_TIME: 1,
|
||||
POST_ONLY: 2,
|
||||
} as const;
|
||||
|
||||
export const LIGHTER_CANCEL_ALL_TIME_IN_FORCE = {
|
||||
IMMEDIATE: 0,
|
||||
SCHEDULED: 1,
|
||||
ABORT: 2,
|
||||
} as const;
|
||||
|
||||
export type LighterOrderType = (typeof LIGHTER_ORDER_TYPE)[keyof typeof LIGHTER_ORDER_TYPE];
|
||||
export type LighterTimeInForce = (typeof LIGHTER_TIME_IN_FORCE)[keyof typeof LIGHTER_TIME_IN_FORCE];
|
||||
export type LighterCancelAllTimeInForce =
|
||||
(typeof LIGHTER_CANCEL_ALL_TIME_IN_FORCE)[keyof typeof LIGHTER_CANCEL_ALL_TIME_IN_FORCE];
|
||||
|
||||
export const LIGHTER_TX_TYPE = {
|
||||
CREATE_ORDER: 14,
|
||||
CANCEL_ORDER: 15,
|
||||
CANCEL_ALL_ORDERS: 16,
|
||||
} as const;
|
||||
|
||||
export const NIL_TRIGGER_PRICE = 0;
|
||||
export const NIL_CLIENT_ORDER_INDEX = 0;
|
||||
@@ -0,0 +1,144 @@
|
||||
import { Fp } from "./goldilocks";
|
||||
import {
|
||||
Fp5,
|
||||
FP5_ZERO,
|
||||
FP5_ONE,
|
||||
FP5_TWO,
|
||||
FP5_W,
|
||||
fp5Add,
|
||||
fp5Mul,
|
||||
fp5ScalarMul,
|
||||
fp5Double,
|
||||
fp5InverseOrZero,
|
||||
} from "./goldilocks-fp5";
|
||||
import { Scalar } from "./scalar";
|
||||
|
||||
const B1 = 263n;
|
||||
const B = Fp5.fromUint64Array([0n, B1, 0n, 0n, 0n]);
|
||||
const B_MUL2 = Fp5.fromUint64Array([0n, 2n * B1, 0n, 0n, 0n]);
|
||||
const B_MUL4 = Fp5.fromUint64Array([0n, 4n * B1, 0n, 0n, 0n]);
|
||||
const B_MUL16 = Fp5.fromUint64Array([0n, 16n * B1, 0n, 0n, 0n]);
|
||||
const A = Fp5.fromUint64Array([2n, 0n, 0n, 0n, 0n]);
|
||||
const FOUR_CONST = Fp5.fromUint64Array([4n, 0n, 0n, 0n, 0n]);
|
||||
|
||||
export class ECPoint {
|
||||
constructor(
|
||||
readonly x: Fp5,
|
||||
readonly z: Fp5,
|
||||
readonly u: Fp5,
|
||||
readonly t: Fp5,
|
||||
) {}
|
||||
|
||||
clone(): ECPoint {
|
||||
return new ECPoint(this.x.clone(), this.z.clone(), this.u.clone(), this.t.clone());
|
||||
}
|
||||
|
||||
static neutral(): ECPoint {
|
||||
return new ECPoint(FP5_ZERO, FP5_ONE, FP5_ZERO, FP5_ONE);
|
||||
}
|
||||
|
||||
static generator(): ECPoint {
|
||||
return new ECPoint(
|
||||
Fp5.fromUint64Array([
|
||||
12883135586176881569n,
|
||||
4356519642755055268n,
|
||||
5248930565894896907n,
|
||||
2165973894480315022n,
|
||||
2448410071095648785n,
|
||||
]),
|
||||
FP5_ONE,
|
||||
FP5_ONE,
|
||||
Fp5.fromUint64Array([4n, 0n, 0n, 0n, 0n]),
|
||||
);
|
||||
}
|
||||
|
||||
isNeutral(): boolean {
|
||||
return this.u.equals(FP5_ZERO);
|
||||
}
|
||||
|
||||
encode(): Fp5 {
|
||||
return fp5Mul(this.t, fp5InverseOrZero(this.u));
|
||||
}
|
||||
|
||||
add(other: ECPoint): ECPoint {
|
||||
if (this.isNeutral()) return other.clone();
|
||||
if (other.isNeutral()) return this.clone();
|
||||
|
||||
const x1 = this.x;
|
||||
const z1 = this.z;
|
||||
const u1 = this.u;
|
||||
const t1 = this.t;
|
||||
|
||||
const x2 = other.x;
|
||||
const z2 = other.z;
|
||||
const u2 = other.u;
|
||||
const t2 = other.t;
|
||||
|
||||
const t1_ = fp5Mul(x1, x2);
|
||||
const t2_ = fp5Mul(z1, z2);
|
||||
const t3 = fp5Mul(u1, u2);
|
||||
const t4 = fp5Mul(t1, t2);
|
||||
const t5 = fp5SubMul(fp5Add(x1, z1), fp5Add(x2, z2), fp5Add(t1_, t2_));
|
||||
const t6 = fp5SubMul(fp5Add(u1, t1), fp5Add(u2, t2), fp5Add(t3, t4));
|
||||
const t7 = fp5Add(t1_, fp5Mul(t2_, B));
|
||||
const t8 = fp5Mul(t4, t7);
|
||||
const t9 = fp5Mul(t3, fp5Add(fp5Mul(t5, B_MUL2), fp5Double(t7)));
|
||||
const t10 = fp5Mul(fp5Add(t4, fp5Double(t3)), fp5Add(t5, t7));
|
||||
|
||||
const xNew = fp5Mul(fp5Sub(t10, t8), B);
|
||||
const zNew = fp5Sub(t8, t9);
|
||||
const uNew = fp5Mul(t6, fp5Sub(fp5Mul(t2_, B), t1_));
|
||||
const tNew = fp5Add(t8, t9);
|
||||
|
||||
return new ECPoint(xNew, zNew, uNew, tNew);
|
||||
}
|
||||
|
||||
double(): ECPoint {
|
||||
if (this.isNeutral()) return this.clone();
|
||||
|
||||
const x = this.x;
|
||||
const z = this.z;
|
||||
const u = this.u;
|
||||
const t = this.t;
|
||||
|
||||
const t1 = fp5Mul(z, t);
|
||||
const t2 = fp5Mul(t1, t);
|
||||
const x1 = fp5Mul(t2, t2);
|
||||
const z1 = fp5Mul(t1, u);
|
||||
const t3 = fp5Mul(u, u);
|
||||
const w1 = fp5Sub(t2, fp5Mul(fp5Double(fp5Add(x, z)), t3));
|
||||
const t4 = fp5Mul(z1, z1);
|
||||
|
||||
const xNew = fp5Mul(t4, B_MUL4);
|
||||
const zNew = fp5Mul(w1, w1);
|
||||
const uNew = fp5Sub(fp5Mul(fp5Add(w1, z1), fp5Add(w1, z1)), fp5Add(t4, zNew));
|
||||
const tNew = fp5Sub(
|
||||
fp5Double(x1),
|
||||
fp5Add(fp5Mul(t4, FOUR_CONST), zNew),
|
||||
);
|
||||
|
||||
return new ECPoint(xNew, zNew, uNew, tNew);
|
||||
}
|
||||
|
||||
mul(scalar: Scalar): ECPoint {
|
||||
let result = ECPoint.neutral();
|
||||
let addend = this.clone();
|
||||
let k = scalar.toBigInt();
|
||||
while (k > 0n) {
|
||||
if (k & 1n) {
|
||||
result = result.add(addend);
|
||||
}
|
||||
addend = addend.double();
|
||||
k >>= 1n;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
function fp5Sub(a: Fp5, b: Fp5): Fp5 {
|
||||
return a.sub(b);
|
||||
}
|
||||
|
||||
function fp5SubMul(a: Fp5, b: Fp5, subtract: Fp5): Fp5 {
|
||||
return fp5Mul(a, b).sub(subtract);
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
import { Fp, GOLDILOCKS_MODULUS, addMany, powers as fpPowers } from "./goldilocks";
|
||||
|
||||
export type Fp5Tuple = [Fp, Fp, Fp, Fp, Fp];
|
||||
|
||||
function expectLength(bytes: Uint8Array, expected: number): void {
|
||||
if (bytes.length !== expected) {
|
||||
throw new Error(`Expected ${expected} bytes, got ${bytes.length}`);
|
||||
}
|
||||
}
|
||||
|
||||
const BYTE_LENGTH = 5 * 8;
|
||||
|
||||
export const FP5_W = new Fp(3n);
|
||||
export const FP5_DTH_ROOT = new Fp(1041288259238279555n);
|
||||
const THREE = new Fp(3n);
|
||||
|
||||
export class Fp5 {
|
||||
readonly c0: Fp;
|
||||
readonly c1: Fp;
|
||||
readonly c2: Fp;
|
||||
readonly c3: Fp;
|
||||
readonly c4: Fp;
|
||||
|
||||
constructor(coeffs: Fp5Tuple) {
|
||||
[this.c0, this.c1, this.c2, this.c3, this.c4] = coeffs;
|
||||
}
|
||||
|
||||
static ZERO = new Fp5([Fp.ZERO, Fp.ZERO, Fp.ZERO, Fp.ZERO, Fp.ZERO]);
|
||||
static ONE = new Fp5([Fp.ONE, Fp.ZERO, Fp.ZERO, Fp.ZERO, Fp.ZERO]);
|
||||
|
||||
static fromFp(value: Fp): Fp5 {
|
||||
return new Fp5([value.clone(), Fp.ZERO, Fp.ZERO, Fp.ZERO, Fp.ZERO]);
|
||||
}
|
||||
|
||||
static fromUint64Array(values: ArrayLike<bigint | number>): Fp5 {
|
||||
if (values.length !== 5) {
|
||||
throw new Error("Fp5.fromUint64Array expects 5 values");
|
||||
}
|
||||
const get = (index: number): bigint | number => {
|
||||
const value = values[index];
|
||||
if (value === undefined) {
|
||||
throw new Error("Fp5.fromUint64Array missing value");
|
||||
}
|
||||
return value;
|
||||
};
|
||||
const arr: [bigint | number, bigint | number, bigint | number, bigint | number, bigint | number] = [
|
||||
get(0),
|
||||
get(1),
|
||||
get(2),
|
||||
get(3),
|
||||
get(4),
|
||||
];
|
||||
return new Fp5([
|
||||
new Fp(arr[0]),
|
||||
new Fp(arr[1]),
|
||||
new Fp(arr[2]),
|
||||
new Fp(arr[3]),
|
||||
new Fp(arr[4]),
|
||||
]);
|
||||
}
|
||||
|
||||
toTuple(): Fp5Tuple {
|
||||
return [this.c0, this.c1, this.c2, this.c3, this.c4];
|
||||
}
|
||||
|
||||
toBytes(): Uint8Array {
|
||||
const out = new Uint8Array(BYTE_LENGTH);
|
||||
out.set(this.c0.toBytesLE(), 0);
|
||||
out.set(this.c1.toBytesLE(), 8);
|
||||
out.set(this.c2.toBytesLE(), 16);
|
||||
out.set(this.c3.toBytesLE(), 24);
|
||||
out.set(this.c4.toBytesLE(), 32);
|
||||
return out;
|
||||
}
|
||||
|
||||
static fromBytes(bytes: Uint8Array): Fp5 {
|
||||
expectLength(bytes, BYTE_LENGTH);
|
||||
return new Fp5([
|
||||
Fp.fromBytesLE(bytes.subarray(0, 8)),
|
||||
Fp.fromBytesLE(bytes.subarray(8, 16)),
|
||||
Fp.fromBytesLE(bytes.subarray(16, 24)),
|
||||
Fp.fromBytesLE(bytes.subarray(24, 32)),
|
||||
Fp.fromBytesLE(bytes.subarray(32, 40)),
|
||||
]);
|
||||
}
|
||||
|
||||
equals(other: Fp5): boolean {
|
||||
return (
|
||||
this.c0.equals(other.c0) &&
|
||||
this.c1.equals(other.c1) &&
|
||||
this.c2.equals(other.c2) &&
|
||||
this.c3.equals(other.c3) &&
|
||||
this.c4.equals(other.c4)
|
||||
);
|
||||
}
|
||||
|
||||
isZero(): boolean {
|
||||
return this.equals(Fp5.ZERO);
|
||||
}
|
||||
|
||||
clone(): Fp5 {
|
||||
return new Fp5([
|
||||
this.c0.clone(),
|
||||
this.c1.clone(),
|
||||
this.c2.clone(),
|
||||
this.c3.clone(),
|
||||
this.c4.clone(),
|
||||
]);
|
||||
}
|
||||
|
||||
add(other: Fp5): Fp5 {
|
||||
return new Fp5([
|
||||
this.c0.add(other.c0),
|
||||
this.c1.add(other.c1),
|
||||
this.c2.add(other.c2),
|
||||
this.c3.add(other.c3),
|
||||
this.c4.add(other.c4),
|
||||
]);
|
||||
}
|
||||
|
||||
sub(other: Fp5): Fp5 {
|
||||
return new Fp5([
|
||||
this.c0.sub(other.c0),
|
||||
this.c1.sub(other.c1),
|
||||
this.c2.sub(other.c2),
|
||||
this.c3.sub(other.c3),
|
||||
this.c4.sub(other.c4),
|
||||
]);
|
||||
}
|
||||
|
||||
neg(): Fp5 {
|
||||
return new Fp5([
|
||||
this.c0.neg(),
|
||||
this.c1.neg(),
|
||||
this.c2.neg(),
|
||||
this.c3.neg(),
|
||||
this.c4.neg(),
|
||||
]);
|
||||
}
|
||||
|
||||
mul(other: Fp5): Fp5 {
|
||||
const w = FP5_W;
|
||||
|
||||
const a0b0 = this.c0.mul(other.c0);
|
||||
const a1b4 = this.c1.mul(other.c4);
|
||||
const a2b3 = this.c2.mul(other.c3);
|
||||
const a3b2 = this.c3.mul(other.c2);
|
||||
const a4b1 = this.c4.mul(other.c1);
|
||||
const added0 = addMany([a1b4, a2b3, a3b2, a4b1]);
|
||||
const muld0 = added0.mul(w);
|
||||
const c0 = a0b0.add(muld0);
|
||||
|
||||
const a0b1 = this.c0.mul(other.c1);
|
||||
const a1b0 = this.c1.mul(other.c0);
|
||||
const a2b4 = this.c2.mul(other.c4);
|
||||
const a3b3 = this.c3.mul(other.c3);
|
||||
const a4b2 = this.c4.mul(other.c2);
|
||||
const added1 = addMany([a2b4, a3b3, a4b2]);
|
||||
const muld1 = added1.mul(w);
|
||||
const c1 = addMany([a0b1, a1b0, muld1]);
|
||||
|
||||
const a0b2 = this.c0.mul(other.c2);
|
||||
const a1b1 = this.c1.mul(other.c1);
|
||||
const a2b0 = this.c2.mul(other.c0);
|
||||
const a3b4 = this.c3.mul(other.c4);
|
||||
const a4b3 = this.c4.mul(other.c3);
|
||||
const added2 = addMany([a3b4, a4b3]);
|
||||
const muld2 = added2.mul(w);
|
||||
const c2 = addMany([a0b2, a1b1, a2b0, muld2]);
|
||||
|
||||
const a0b3 = this.c0.mul(other.c3);
|
||||
const a1b2 = this.c1.mul(other.c2);
|
||||
const a2b1 = this.c2.mul(other.c1);
|
||||
const a3b0 = this.c3.mul(other.c0);
|
||||
const a4b4 = this.c4.mul(other.c4);
|
||||
const muld3 = a4b4.mul(w);
|
||||
const c3 = addMany([a0b3, a1b2, a2b1, a3b0, muld3]);
|
||||
|
||||
const a0b4 = this.c0.mul(other.c4);
|
||||
const a1b3 = this.c1.mul(other.c3);
|
||||
const a2b2 = this.c2.mul(other.c2);
|
||||
const a3b1 = this.c3.mul(other.c1);
|
||||
const a4b0 = this.c4.mul(other.c0);
|
||||
const c4 = addMany([a0b4, a1b3, a2b2, a3b1, a4b0]);
|
||||
|
||||
return new Fp5([c0, c1, c2, c3, c4]);
|
||||
}
|
||||
|
||||
square(): Fp5 {
|
||||
const w = FP5_W;
|
||||
const doubleW = FP5_W.add(FP5_W);
|
||||
|
||||
const a0s = this.c0.mul(this.c0);
|
||||
const a1a4 = this.c1.mul(this.c4);
|
||||
const a2a3 = this.c2.mul(this.c3);
|
||||
const added0 = addMany([a1a4, a2a3]);
|
||||
const muld0 = added0.mul(doubleW);
|
||||
const c0 = a0s.add(muld0);
|
||||
|
||||
const a0Double = this.c0.add(this.c0);
|
||||
const a0Doublea1 = a0Double.mul(this.c1);
|
||||
const a2a4DoubleW = this.c2.mul(this.c4).mul(doubleW);
|
||||
const a3a3w = this.c3.mul(this.c3).mul(w);
|
||||
const c1 = addMany([a0Doublea1, a2a4DoubleW, a3a3w]);
|
||||
|
||||
const a0Doublea2 = a0Double.mul(this.c2);
|
||||
const a1Square = this.c1.mul(this.c1);
|
||||
const a4a3DoubleW = this.c4.mul(this.c3).mul(doubleW);
|
||||
const c2 = addMany([a0Doublea2, a1Square, a4a3DoubleW]);
|
||||
|
||||
const a1Double = this.c1.add(this.c1);
|
||||
const a0Doublea3 = a0Double.mul(this.c3);
|
||||
const a1Doublea2 = a1Double.mul(this.c2);
|
||||
const a4SquareW = this.c4.mul(this.c4).mul(w);
|
||||
const c3 = addMany([a0Doublea3, a1Doublea2, a4SquareW]);
|
||||
|
||||
const a0Doublea4 = a0Double.mul(this.c4);
|
||||
const a1Doublea3 = a1Double.mul(this.c3);
|
||||
const a2Square = this.c2.mul(this.c2);
|
||||
const c4 = addMany([a0Doublea4, a1Doublea3, a2Square]);
|
||||
|
||||
return new Fp5([c0, c1, c2, c3, c4]);
|
||||
}
|
||||
|
||||
expPowerOf2(power: number): Fp5 {
|
||||
let result = this.clone();
|
||||
for (let i = 0; i < power; i++) {
|
||||
result = result.square();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
double(): Fp5 {
|
||||
return this.add(this);
|
||||
}
|
||||
|
||||
triple(): Fp5 {
|
||||
return new Fp5([
|
||||
this.c0.mul(THREE),
|
||||
this.c1.mul(THREE),
|
||||
this.c2.mul(THREE),
|
||||
this.c3.mul(THREE),
|
||||
this.c4.mul(THREE),
|
||||
]);
|
||||
}
|
||||
|
||||
scalarMul(scalar: Fp): Fp5 {
|
||||
return new Fp5([
|
||||
this.c0.mul(scalar),
|
||||
this.c1.mul(scalar),
|
||||
this.c2.mul(scalar),
|
||||
this.c3.mul(scalar),
|
||||
this.c4.mul(scalar),
|
||||
]);
|
||||
}
|
||||
|
||||
inverseOrZero(): Fp5 {
|
||||
if (this.isZero()) return Fp5.ZERO;
|
||||
|
||||
const d = this.frobenius();
|
||||
const e = this.mul(d.frobenius());
|
||||
const f = e.mul(e.repeatedFrobenius(2));
|
||||
|
||||
const a0b0 = this.c0.mul(f.c0);
|
||||
const a1b4 = this.c1.mul(f.c4);
|
||||
const a2b3 = this.c2.mul(f.c3);
|
||||
const a3b2 = this.c3.mul(f.c2);
|
||||
const a4b1 = this.c4.mul(f.c1);
|
||||
const added = addMany([a1b4, a2b3, a3b2, a4b1]);
|
||||
const muld = added.mul(FP5_W);
|
||||
const g = a0b0.add(muld);
|
||||
|
||||
const gInv = g.inverse();
|
||||
return f.scalarMul(gInv);
|
||||
}
|
||||
|
||||
div(other: Fp5): Fp5 {
|
||||
const inv = other.inverseOrZero();
|
||||
if (inv.isZero()) {
|
||||
throw new Error("Division by zero in Fp5");
|
||||
}
|
||||
return this.mul(inv);
|
||||
}
|
||||
|
||||
frobenius(): Fp5 {
|
||||
return this.repeatedFrobenius(1);
|
||||
}
|
||||
|
||||
repeatedFrobenius(count: number): Fp5 {
|
||||
if (count === 0) return this;
|
||||
const reduced = count % 5;
|
||||
if (reduced === 0) return this;
|
||||
|
||||
let z0 = FP5_DTH_ROOT;
|
||||
for (let i = 1; i < reduced; i++) {
|
||||
z0 = z0.mul(FP5_DTH_ROOT);
|
||||
}
|
||||
|
||||
const powerArray = fpPowers(z0, 5) as [Fp, Fp, Fp, Fp, Fp];
|
||||
const [p0, p1, p2, p3, p4] = powerArray;
|
||||
return new Fp5([
|
||||
this.c0.mul(p0),
|
||||
this.c1.mul(p1),
|
||||
this.c2.mul(p2),
|
||||
this.c3.mul(p3),
|
||||
this.c4.mul(p4),
|
||||
]);
|
||||
}
|
||||
|
||||
legendre(): Fp {
|
||||
const frob1 = this.frobenius();
|
||||
const frob2 = frob1.frobenius();
|
||||
const frob1TimesFrob2 = frob1.mul(frob2);
|
||||
const frob2Frob1TimesFrob2 = frob1TimesFrob2.repeatedFrobenius(2);
|
||||
const xrExt = this.mul(frob1TimesFrob2).mul(frob2Frob1TimesFrob2);
|
||||
const xr = new Fp(xrExt.c0.toBigInt());
|
||||
const xr31 = xr.pow(1n << 31n);
|
||||
const xr31Inv = xr31.isZero() ? Fp.ZERO : xr31.inverse();
|
||||
const xr63 = xr31.pow(1n << 32n);
|
||||
return xr63.mul(xr31Inv);
|
||||
}
|
||||
|
||||
sqrt(): { value: Fp5; exists: boolean } {
|
||||
const v = this.expPowerOf2(31);
|
||||
const d = this.mul(v.expPowerOf2(32)).mul(v.inverseOrZero());
|
||||
const e = d.mul(d.repeatedFrobenius(2)).frobenius();
|
||||
const f = e.square();
|
||||
|
||||
const x1f4 = this.c1.mul(f.c4);
|
||||
const x2f3 = this.c2.mul(f.c3);
|
||||
const x3f2 = this.c3.mul(f.c2);
|
||||
const x4f1 = this.c4.mul(f.c1);
|
||||
const added = addMany([x1f4, x2f3, x3f2, x4f1]);
|
||||
const muld = added.mul(THREE);
|
||||
const x0f0 = this.c0.mul(f.c0);
|
||||
const g = x0f0.add(muld);
|
||||
const s = sqrtFp(g);
|
||||
if (!s) {
|
||||
return { value: Fp5.ZERO, exists: false };
|
||||
}
|
||||
const eInv = e.inverseOrZero();
|
||||
const sFp5 = Fp5.fromFp(s);
|
||||
return { value: sFp5.mul(eInv), exists: true };
|
||||
}
|
||||
|
||||
canonicalSqrt(): { value: Fp5; exists: boolean } {
|
||||
const { value, exists } = this.sqrt();
|
||||
if (!exists) return { value: Fp5.ZERO, exists: false };
|
||||
return { value: sgn0(value) ? value.neg() : value, exists: true };
|
||||
}
|
||||
}
|
||||
|
||||
function sgn0(x: Fp5): boolean {
|
||||
let sign = false;
|
||||
let zero = true;
|
||||
for (const limb of [x.c0, x.c1, x.c2, x.c3, x.c4]) {
|
||||
const limbSign = (limb.toBigInt() & 1n) === 0n;
|
||||
const limbZero = limb.isZero();
|
||||
sign = sign || (zero && limbSign);
|
||||
zero = zero && limbZero;
|
||||
}
|
||||
return sign;
|
||||
}
|
||||
|
||||
function sqrtFp(value: Fp): Fp | null {
|
||||
if (value.isZero()) return Fp.ZERO;
|
||||
const p = GOLDILOCKS_MODULUS;
|
||||
const leg = value.pow((p - 1n) / 2n);
|
||||
if (leg.isZero()) return Fp.ZERO;
|
||||
const legVal = leg.toBigInt();
|
||||
if (legVal === p - 1n) return null;
|
||||
|
||||
let q = p - 1n;
|
||||
let s = 0n;
|
||||
while ((q & 1n) === 0n) {
|
||||
q >>= 1n;
|
||||
s += 1n;
|
||||
}
|
||||
|
||||
let z = 2n;
|
||||
while (true) {
|
||||
const zLeg = new Fp(z).pow((p - 1n) / 2n).toBigInt();
|
||||
if (zLeg === p - 1n) break;
|
||||
z += 1n;
|
||||
}
|
||||
|
||||
let c = new Fp(z).pow(q);
|
||||
let x = value.pow((q + 1n) >> 1n);
|
||||
let t = value.pow(q);
|
||||
let m = s;
|
||||
|
||||
while (t.toBigInt() !== 1n) {
|
||||
let i = 1n;
|
||||
let t2i = t.mul(t);
|
||||
while (t2i.toBigInt() !== 1n) {
|
||||
t2i = t2i.mul(t2i);
|
||||
i += 1n;
|
||||
if (i === m) return null;
|
||||
}
|
||||
const b = c.pow(1n << (m - i - 1n));
|
||||
x = x.mul(b);
|
||||
c = b.mul(b);
|
||||
t = t.mul(c);
|
||||
m = i;
|
||||
}
|
||||
|
||||
return x;
|
||||
}
|
||||
|
||||
export const FP5_ZERO = Fp5.ZERO;
|
||||
export const FP5_ONE = Fp5.ONE;
|
||||
export const FP5_TWO = Fp5.fromFp(new Fp(2n));
|
||||
|
||||
export function fp5Add(a: Fp5, ...others: Fp5[]): Fp5 {
|
||||
let acc = a;
|
||||
for (const other of others) {
|
||||
acc = acc.add(other);
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
export function fp5Sub(a: Fp5, b: Fp5): Fp5 {
|
||||
return a.sub(b);
|
||||
}
|
||||
|
||||
export function fp5Mul(a: Fp5, b: Fp5): Fp5 {
|
||||
return a.mul(b);
|
||||
}
|
||||
|
||||
export function fp5Square(a: Fp5): Fp5 {
|
||||
return a.square();
|
||||
}
|
||||
|
||||
export function fp5Double(a: Fp5): Fp5 {
|
||||
return a.double();
|
||||
}
|
||||
|
||||
export function fp5ScalarMul(a: Fp5, scalar: Fp): Fp5 {
|
||||
return a.scalarMul(scalar);
|
||||
}
|
||||
|
||||
export function fp5InverseOrZero(a: Fp5): Fp5 {
|
||||
return a.inverseOrZero();
|
||||
}
|
||||
|
||||
export function fp5Frobenius(a: Fp5): Fp5 {
|
||||
return a.frobenius();
|
||||
}
|
||||
|
||||
export function fp5RepeatedFrobenius(a: Fp5, count: number): Fp5 {
|
||||
return a.repeatedFrobenius(count);
|
||||
}
|
||||
|
||||
export function fp5Legendre(a: Fp5): Fp {
|
||||
return a.legendre();
|
||||
}
|
||||
|
||||
export function fp5CanonicalSqrt(a: Fp5): { value: Fp5; exists: boolean } {
|
||||
return a.canonicalSqrt();
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { randomBytes } from "crypto";
|
||||
|
||||
const TWO_POW_32 = 1n << 32n;
|
||||
const TWO_POW_64 = 1n << 64n;
|
||||
export const GOLDILOCKS_MODULUS = TWO_POW_64 - TWO_POW_32 + 1n;
|
||||
const BYTE_LENGTH = 8;
|
||||
|
||||
function mod(value: bigint): bigint {
|
||||
let v = value % GOLDILOCKS_MODULUS;
|
||||
if (v < 0n) v += GOLDILOCKS_MODULUS;
|
||||
return v;
|
||||
}
|
||||
|
||||
export class Fp {
|
||||
readonly value: bigint;
|
||||
|
||||
constructor(value: bigint | number) {
|
||||
this.value = mod(typeof value === "number" ? BigInt(value) : value);
|
||||
}
|
||||
|
||||
static readonly ZERO = new Fp(0n);
|
||||
static readonly ONE = new Fp(1n);
|
||||
|
||||
static fromBytesLE(bytes: Uint8Array): Fp {
|
||||
if (bytes.length !== BYTE_LENGTH) {
|
||||
throw new Error(`Goldilocks element expects 8 bytes, got ${bytes.length}`);
|
||||
}
|
||||
let acc = 0n;
|
||||
for (let i = 0; i < BYTE_LENGTH; i++) {
|
||||
const byte = bytes[i];
|
||||
if (byte === undefined) throw new Error("Unexpected undefined byte when reading Goldilocks element");
|
||||
acc |= BigInt(byte) << BigInt(8 * i);
|
||||
}
|
||||
return new Fp(acc);
|
||||
}
|
||||
|
||||
toBytesLE(): Uint8Array {
|
||||
let v = this.value;
|
||||
const out = new Uint8Array(BYTE_LENGTH);
|
||||
for (let i = 0; i < BYTE_LENGTH; i++) {
|
||||
out[i] = Number(v & 0xffn);
|
||||
v >>= 8n;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
toBigInt(): bigint {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
toNumber(): number {
|
||||
return Number(this.value);
|
||||
}
|
||||
|
||||
add(...others: Fp[]): Fp {
|
||||
let acc = this.value;
|
||||
for (const other of others) acc += other.value;
|
||||
return new Fp(acc);
|
||||
}
|
||||
|
||||
sub(other: Fp): Fp {
|
||||
return new Fp(this.value - other.value);
|
||||
}
|
||||
|
||||
neg(): Fp {
|
||||
return new Fp(this.value === 0n ? 0n : GOLDILOCKS_MODULUS - this.value);
|
||||
}
|
||||
|
||||
mul(...others: Fp[]): Fp {
|
||||
let acc = this.value;
|
||||
for (const other of others) acc = mod(acc * other.value);
|
||||
return new Fp(acc);
|
||||
}
|
||||
|
||||
square(): Fp {
|
||||
return new Fp(mod(this.value * this.value));
|
||||
}
|
||||
|
||||
double(): Fp {
|
||||
return new Fp(this.value << 1n);
|
||||
}
|
||||
|
||||
inverse(): Fp {
|
||||
if (this.isZero()) {
|
||||
throw new Error("Cannot invert zero in Goldilocks field");
|
||||
}
|
||||
return this.pow(GOLDILOCKS_MODULUS - 2n);
|
||||
}
|
||||
|
||||
pow(exponent: bigint): Fp {
|
||||
let result = 1n;
|
||||
let base = this.value;
|
||||
let exp = exponent;
|
||||
while (exp > 0n) {
|
||||
if (exp & 1n) result = mod(result * base);
|
||||
base = mod(base * base);
|
||||
exp >>= 1n;
|
||||
}
|
||||
return new Fp(result);
|
||||
}
|
||||
|
||||
isZero(): boolean {
|
||||
return this.value === 0n;
|
||||
}
|
||||
|
||||
isOne(): boolean {
|
||||
return this.value === 1n;
|
||||
}
|
||||
|
||||
equals(other: Fp): boolean {
|
||||
return this.value === other.value;
|
||||
}
|
||||
|
||||
clone(): Fp {
|
||||
return new Fp(this.value);
|
||||
}
|
||||
|
||||
static random(): Fp {
|
||||
while (true) {
|
||||
const buf = randomBytes(BYTE_LENGTH);
|
||||
let acc = 0n;
|
||||
for (let i = 0; i < BYTE_LENGTH; i++) {
|
||||
const byte = buf[i];
|
||||
if (byte === undefined) throw new Error("Unexpected undefined byte when sampling Goldilocks element");
|
||||
acc |= BigInt(byte) << BigInt(8 * i);
|
||||
}
|
||||
if (acc < GOLDILOCKS_MODULUS) {
|
||||
return new Fp(acc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static fromUint32(value: number): Fp {
|
||||
return new Fp(BigInt(value >>> 0));
|
||||
}
|
||||
|
||||
static fromUint64(value: bigint | number): Fp {
|
||||
return new Fp(value);
|
||||
}
|
||||
}
|
||||
|
||||
export function addMany(elements: readonly Fp[]): Fp {
|
||||
let acc = 0n;
|
||||
for (const el of elements) acc += el.value;
|
||||
return new Fp(acc);
|
||||
}
|
||||
|
||||
export function arrayToBytesLE(elements: readonly Fp[]): Uint8Array {
|
||||
const out = new Uint8Array(elements.length * BYTE_LENGTH);
|
||||
elements.forEach((elem, idx) => {
|
||||
out.set(elem.toBytesLE(), idx * BYTE_LENGTH);
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
export function arrayFromBytesLE(bytes: Uint8Array): Fp[] {
|
||||
if (bytes.length % BYTE_LENGTH !== 0) {
|
||||
throw new Error("Goldilocks array bytes length must be multiple of 8");
|
||||
}
|
||||
const out: Fp[] = [];
|
||||
for (let i = 0; i < bytes.length; i += BYTE_LENGTH) {
|
||||
out.push(Fp.fromBytesLE(bytes.subarray(i, i + BYTE_LENGTH)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function powers(base: Fp, count: number): Fp[] {
|
||||
if (count <= 0) return [];
|
||||
const result = new Array<Fp>(count);
|
||||
result[0] = Fp.ONE;
|
||||
for (let i = 1; i < count; i++) {
|
||||
const prev = result[i - 1];
|
||||
if (!prev) throw new Error("unexpected undefined in goldilocks powers");
|
||||
result[i] = prev.mul(base);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export const GOLDILOCKS_BYTE_LENGTH = BYTE_LENGTH;
|
||||
@@ -0,0 +1,320 @@
|
||||
import { Fp } from "./goldilocks";
|
||||
import { Fp5 } from "./goldilocks-fp5";
|
||||
|
||||
const WIDTH = 12;
|
||||
const RATE = 8;
|
||||
const ROUNDS_F = 8;
|
||||
const ROUNDS_F_HALF = 4;
|
||||
const ROUNDS_P = 22;
|
||||
|
||||
const EXTERNAL_CONSTANTS: Fp[][] = [
|
||||
[
|
||||
new Fp(15492826721047263190n),
|
||||
new Fp(11728330187201910315n),
|
||||
new Fp(8836021247773420868n),
|
||||
new Fp(16777404051263952451n),
|
||||
new Fp(5510875212538051896n),
|
||||
new Fp(6173089941271892285n),
|
||||
new Fp(2927757366422211339n),
|
||||
new Fp(10340958981325008808n),
|
||||
new Fp(8541987352684552425n),
|
||||
new Fp(9739599543776434497n),
|
||||
new Fp(15073950188101532019n),
|
||||
new Fp(12084856431752384512n),
|
||||
],
|
||||
[
|
||||
new Fp(4584713381960671270n),
|
||||
new Fp(8807052963476652830n),
|
||||
new Fp(54136601502601741n),
|
||||
new Fp(4872702333905478703n),
|
||||
new Fp(5551030319979516287n),
|
||||
new Fp(12889366755535460989n),
|
||||
new Fp(16329242193178844328n),
|
||||
new Fp(412018088475211848n),
|
||||
new Fp(10505784623379650541n),
|
||||
new Fp(9758812378619434837n),
|
||||
new Fp(7421979329386275117n),
|
||||
new Fp(375240370024755551n),
|
||||
],
|
||||
[
|
||||
new Fp(3331431125640721931n),
|
||||
new Fp(15684937309956309981n),
|
||||
new Fp(578521833432107983n),
|
||||
new Fp(14379242000670861838n),
|
||||
new Fp(17922409828154900976n),
|
||||
new Fp(8153494278429192257n),
|
||||
new Fp(15904673920630731971n),
|
||||
new Fp(11217863998460634216n),
|
||||
new Fp(3301540195510742136n),
|
||||
new Fp(9937973023749922003n),
|
||||
new Fp(3059102938155026419n),
|
||||
new Fp(1895288289490976132n),
|
||||
],
|
||||
[
|
||||
new Fp(5580912693628927540n),
|
||||
new Fp(10064804080494788323n),
|
||||
new Fp(9582481583369602410n),
|
||||
new Fp(10186259561546797986n),
|
||||
new Fp(247426333829703916n),
|
||||
new Fp(13193193905461376067n),
|
||||
new Fp(6386232593701758044n),
|
||||
new Fp(17954717245501896472n),
|
||||
new Fp(1531720443376282699n),
|
||||
new Fp(2455761864255501970n),
|
||||
new Fp(11234429217864304495n),
|
||||
new Fp(4746959618548874102n),
|
||||
],
|
||||
[
|
||||
new Fp(13571697342473846203n),
|
||||
new Fp(17477857865056504753n),
|
||||
new Fp(15963032953523553760n),
|
||||
new Fp(16033593225279635898n),
|
||||
new Fp(14252634232868282405n),
|
||||
new Fp(8219748254835277737n),
|
||||
new Fp(7459165569491914711n),
|
||||
new Fp(15855939513193752003n),
|
||||
new Fp(16788866461340278896n),
|
||||
new Fp(7102224659693946577n),
|
||||
new Fp(3024718005636976471n),
|
||||
new Fp(13695468978618890430n),
|
||||
],
|
||||
[
|
||||
new Fp(8214202050877825436n),
|
||||
new Fp(2670727992739346204n),
|
||||
new Fp(16259532062589659211n),
|
||||
new Fp(11869922396257088411n),
|
||||
new Fp(3179482916972760137n),
|
||||
new Fp(13525476046633427808n),
|
||||
new Fp(3217337278042947412n),
|
||||
new Fp(14494689598654046340n),
|
||||
new Fp(15837379330312175383n),
|
||||
new Fp(8029037639801151344n),
|
||||
new Fp(2153456285263517937n),
|
||||
new Fp(8301106462311849241n),
|
||||
],
|
||||
[
|
||||
new Fp(13294194396455217955n),
|
||||
new Fp(17394768489610594315n),
|
||||
new Fp(12847609130464867455n),
|
||||
new Fp(14015739446356528640n),
|
||||
new Fp(5879251655839607853n),
|
||||
new Fp(9747000124977436185n),
|
||||
new Fp(8950393546890284269n),
|
||||
new Fp(10765765936405694368n),
|
||||
new Fp(14695323910334139959n),
|
||||
new Fp(16366254691123000864n),
|
||||
new Fp(15292774414889043182n),
|
||||
new Fp(10910394433429313384n),
|
||||
],
|
||||
[
|
||||
new Fp(17253424460214596184n),
|
||||
new Fp(3442854447664030446n),
|
||||
new Fp(3005570425335613727n),
|
||||
new Fp(10859158614900201063n),
|
||||
new Fp(9763230642109343539n),
|
||||
new Fp(6647722546511515039n),
|
||||
new Fp(909012944955815706n),
|
||||
new Fp(18101204076790399111n),
|
||||
new Fp(11588128829349125809n),
|
||||
new Fp(15863878496612806566n),
|
||||
new Fp(5201119062417750399n),
|
||||
new Fp(176665553780565743n),
|
||||
],
|
||||
];
|
||||
|
||||
const INTERNAL_CONSTANTS: Fp[] = [
|
||||
new Fp(11921381764981422944n),
|
||||
new Fp(10318423381711320787n),
|
||||
new Fp(8291411502347000766n),
|
||||
new Fp(229948027109387563n),
|
||||
new Fp(9152521390190983261n),
|
||||
new Fp(7129306032690285515n),
|
||||
new Fp(15395989607365232011n),
|
||||
new Fp(8641397269074305925n),
|
||||
new Fp(17256848792241043600n),
|
||||
new Fp(6046475228902245682n),
|
||||
new Fp(12041608676381094092n),
|
||||
new Fp(12785542378683951657n),
|
||||
new Fp(14546032085337914034n),
|
||||
new Fp(3304199118235116851n),
|
||||
new Fp(16499627707072547655n),
|
||||
new Fp(10386478025625759321n),
|
||||
new Fp(13475579315436919170n),
|
||||
new Fp(16042710511297532028n),
|
||||
new Fp(1411266850385657080n),
|
||||
new Fp(9024840976168649958n),
|
||||
new Fp(14047056970978379368n),
|
||||
new Fp(838728605080212101n),
|
||||
];
|
||||
|
||||
const MATRIX_DIAG: Fp[] = [
|
||||
new Fp(0xc3b6c08e23ba9300n),
|
||||
new Fp(0xd84b5de94a324fb6n),
|
||||
new Fp(0x0d0c371c5b35b84fn),
|
||||
new Fp(0x7964f570e7188037n),
|
||||
new Fp(0x5daf18bbd996604bn),
|
||||
new Fp(0x6743bc47b9595257n),
|
||||
new Fp(0x5528b9362c59bb70n),
|
||||
new Fp(0xac45e25b7127b68bn),
|
||||
new Fp(0xa2077d7dfbb606b5n),
|
||||
new Fp(0xf3faac6faee378aen),
|
||||
new Fp(0x0c6388b51545e883n),
|
||||
new Fp(0xd27dbb6944917b60n),
|
||||
];
|
||||
|
||||
export function hashToFp5(values: Fp[]): Fp5 {
|
||||
const result = hashNToMNoPad(values, 5);
|
||||
const [c0, c1, c2, c3, c4] = result as [Fp, Fp, Fp, Fp, Fp];
|
||||
return new Fp5([c0, c1, c2, c3, c4]);
|
||||
}
|
||||
|
||||
export function hashTwoToOne(a: Fp[], b: Fp[]): Fp[] {
|
||||
return hashNToMNoPad([...a, ...b], 4);
|
||||
}
|
||||
|
||||
export function hashNToMNoPad(input: Fp[], outputCount: number): Fp[] {
|
||||
const state: Fp[] = Array.from({ length: WIDTH }, () => Fp.ZERO);
|
||||
for (let offset = 0; offset < input.length; offset += RATE) {
|
||||
for (let j = 0; j < RATE && offset + j < input.length; j++) {
|
||||
const current = state[j]!;
|
||||
const value = input[offset + j];
|
||||
if (value === undefined) throw new Error("poseidon input missing element");
|
||||
state[j] = current.add(value);
|
||||
}
|
||||
permute(state);
|
||||
}
|
||||
|
||||
const outputs: Fp[] = [];
|
||||
while (outputs.length < outputCount) {
|
||||
for (let i = 0; i < RATE && outputs.length < outputCount; i++) {
|
||||
outputs.push(state[i]!);
|
||||
}
|
||||
if (outputs.length < outputCount) {
|
||||
permute(state);
|
||||
}
|
||||
}
|
||||
return outputs;
|
||||
}
|
||||
|
||||
function permute(state: Fp[]): void {
|
||||
externalLinearLayer(state);
|
||||
fullRounds(state, 0);
|
||||
partialRounds(state);
|
||||
fullRounds(state, ROUNDS_F_HALF);
|
||||
}
|
||||
|
||||
function fullRounds(state: Fp[], startRound: number): void {
|
||||
for (let r = startRound; r < startRound + ROUNDS_F_HALF; r++) {
|
||||
addRoundConstants(state, r);
|
||||
sbox(state);
|
||||
externalLinearLayer(state);
|
||||
}
|
||||
}
|
||||
|
||||
function partialRounds(state: Fp[]): void {
|
||||
for (let r = 0; r < ROUNDS_P; r++) {
|
||||
addInternalConstant(state, r);
|
||||
sboxP(state, 0);
|
||||
internalLinearLayer(state);
|
||||
}
|
||||
}
|
||||
|
||||
function addRoundConstants(state: Fp[], round: number): void {
|
||||
const constants = EXTERNAL_CONSTANTS[round];
|
||||
if (!constants) {
|
||||
throw new Error(`poseidon round constant missing for round ${round}`);
|
||||
}
|
||||
for (let i = 0; i < WIDTH; i++) {
|
||||
state[i] = state[i]!.add(constants[i]!);
|
||||
}
|
||||
}
|
||||
|
||||
function addInternalConstant(state: Fp[], round: number): void {
|
||||
const constant = INTERNAL_CONSTANTS[round];
|
||||
if (!constant) {
|
||||
throw new Error(`poseidon internal constant missing for round ${round}`);
|
||||
}
|
||||
state[0] = state[0]!.add(constant);
|
||||
}
|
||||
|
||||
function sbox(state: Fp[]): void {
|
||||
for (let i = 0; i < WIDTH; i++) {
|
||||
sboxP(state, i);
|
||||
}
|
||||
}
|
||||
|
||||
function sboxP(state: Fp[], index: number): void {
|
||||
const x = state[index];
|
||||
if (!x) throw new Error(`poseidon state missing at index ${index}`);
|
||||
const x2 = x.square();
|
||||
const x3 = x2.mul(x);
|
||||
const x6 = x3.square();
|
||||
state[index] = x6.mul(x);
|
||||
}
|
||||
|
||||
function externalLinearLayer(state: Fp[]): void {
|
||||
for (let block = 0; block < 3; block++) {
|
||||
const base = block * 4;
|
||||
const s0 = state[base]!;
|
||||
const s1 = state[base + 1]!;
|
||||
const s2 = state[base + 2]!;
|
||||
const s3 = state[base + 3]!;
|
||||
|
||||
const t0 = s0.add(s1);
|
||||
const t1 = s2.add(s3);
|
||||
const t2 = t0.add(t1);
|
||||
const t3 = t2.add(s1);
|
||||
const t4 = t2.add(s3);
|
||||
const t5 = s0.double();
|
||||
const t6 = s2.double();
|
||||
|
||||
state[base] = t3.add(t0);
|
||||
state[base + 1] = t6.add(t3);
|
||||
state[base + 2] = t1.add(t4);
|
||||
state[base + 3] = t5.add(t4);
|
||||
}
|
||||
|
||||
const sums: Fp[] = [Fp.ZERO, Fp.ZERO, Fp.ZERO, Fp.ZERO];
|
||||
for (let k = 0; k < 4; k++) {
|
||||
for (let j = 0; j < WIDTH; j += 4) {
|
||||
const currentSum = sums[k];
|
||||
if (currentSum === undefined) throw new Error("poseidon sums missing value");
|
||||
sums[k] = currentSum.add(state[j + k]!);
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < WIDTH; i++) {
|
||||
state[i] = state[i]!.add(sums[i % 4]!);
|
||||
}
|
||||
}
|
||||
|
||||
function internalLinearLayer(state: Fp[]): void {
|
||||
let sum = state[0]!;
|
||||
for (let i = 1; i < WIDTH; i++) {
|
||||
sum = sum.add(state[i]!);
|
||||
}
|
||||
for (let i = 0; i < WIDTH; i++) {
|
||||
state[i] = state[i]!.mul(MATRIX_DIAG[i]!).add(sum);
|
||||
}
|
||||
}
|
||||
|
||||
export function hashToQuinticExtension(preimage: Fp[]): Fp5 {
|
||||
return hashToFp5(preimage);
|
||||
}
|
||||
|
||||
export function hashFp5Pair(a: Fp5, b: Fp5): Fp5 {
|
||||
const inputs: Fp[] = [...a.toTuple(), ...b.toTuple()];
|
||||
return hashToQuinticExtension(inputs);
|
||||
}
|
||||
|
||||
export function mergeFp5WithHash(fp5Values: Fp5[]): Fp5 {
|
||||
if (fp5Values.length === 0) return Fp5.ZERO;
|
||||
const first = fp5Values[0];
|
||||
if (!first) throw new Error("mergeFp5WithHash received empty array");
|
||||
let acc = first;
|
||||
for (let i = 1; i < fp5Values.length; i++) {
|
||||
const next = fp5Values[i];
|
||||
if (!next) throw new Error("mergeFp5WithHash encountered undefined value");
|
||||
acc = hashFp5Pair(acc, next);
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { randomBytes } from "crypto";
|
||||
import { Fp } from "./goldilocks";
|
||||
import { Fp5 } from "./goldilocks-fp5";
|
||||
|
||||
const ORDER = BigInt("1067993516717146951041484916571792702745057740581727230159139685185762082554198619328292418486241");
|
||||
const BYTE_LENGTH = 40;
|
||||
const FOUR_BIT_LIMBS = 80;
|
||||
const BIT_LENGTH = 319;
|
||||
|
||||
function modOrder(value: bigint): bigint {
|
||||
let v = value % ORDER;
|
||||
if (v < 0n) v += ORDER;
|
||||
return v;
|
||||
}
|
||||
|
||||
export class Scalar {
|
||||
readonly value: bigint;
|
||||
|
||||
constructor(value: bigint | number) {
|
||||
this.value = modOrder(typeof value === "number" ? BigInt(value) : value);
|
||||
}
|
||||
|
||||
static readonly ZERO = new Scalar(0n);
|
||||
static readonly ONE = new Scalar(1n);
|
||||
|
||||
static fromBytesLE(bytes: Uint8Array): Scalar {
|
||||
if (bytes.length !== BYTE_LENGTH) {
|
||||
throw new Error(`Scalar expects ${BYTE_LENGTH} bytes, got ${bytes.length}`);
|
||||
}
|
||||
let acc = 0n;
|
||||
for (let i = 0; i < BYTE_LENGTH; i++) {
|
||||
const byte = bytes[i];
|
||||
if (byte === undefined) throw new Error("Unexpected undefined byte when reading scalar");
|
||||
acc |= BigInt(byte) << BigInt(8 * i);
|
||||
}
|
||||
return new Scalar(acc);
|
||||
}
|
||||
|
||||
toBytesLE(): Uint8Array {
|
||||
let v = this.value;
|
||||
const out = new Uint8Array(BYTE_LENGTH);
|
||||
for (let i = 0; i < BYTE_LENGTH; i++) {
|
||||
out[i] = Number(v & 0xffn);
|
||||
v >>= 8n;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
toBigInt(): bigint {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
add(other: Scalar): Scalar {
|
||||
return new Scalar(this.value + other.value);
|
||||
}
|
||||
|
||||
sub(other: Scalar): Scalar {
|
||||
return new Scalar(this.value - other.value);
|
||||
}
|
||||
|
||||
neg(): Scalar {
|
||||
return new Scalar(this.value === 0n ? 0n : ORDER - this.value);
|
||||
}
|
||||
|
||||
mul(other: Scalar): Scalar {
|
||||
return new Scalar(this.value * other.value);
|
||||
}
|
||||
|
||||
square(): Scalar {
|
||||
return this.mul(this);
|
||||
}
|
||||
|
||||
pow(exponent: bigint): Scalar {
|
||||
let result = 1n;
|
||||
let base = this.value;
|
||||
let exp = exponent;
|
||||
while (exp > 0n) {
|
||||
if (exp & 1n) result = modOrder(result * base);
|
||||
base = modOrder(base * base);
|
||||
exp >>= 1n;
|
||||
}
|
||||
return new Scalar(result);
|
||||
}
|
||||
|
||||
isZero(): boolean {
|
||||
return this.value === 0n;
|
||||
}
|
||||
|
||||
equals(other: Scalar): boolean {
|
||||
return this.value === other.value;
|
||||
}
|
||||
|
||||
clone(): Scalar {
|
||||
return new Scalar(this.value);
|
||||
}
|
||||
|
||||
splitTo4BitLimbs(): Uint8Array {
|
||||
const limbs = new Uint8Array(FOUR_BIT_LIMBS);
|
||||
let tmp = this.value;
|
||||
for (let i = 0; i < FOUR_BIT_LIMBS; i++) {
|
||||
limbs[i] = Number(tmp & 0xfn);
|
||||
tmp >>= 4n;
|
||||
}
|
||||
return limbs;
|
||||
}
|
||||
|
||||
recodeSigned(window: number): Int32Array {
|
||||
const length = Math.ceil(BIT_LENGTH / window);
|
||||
const digits = new Int32Array(length);
|
||||
const twoPowW = 1n << BigInt(window);
|
||||
const twoPowWMinus1 = 1n << BigInt(window - 1);
|
||||
let k = this.value;
|
||||
let i = 0;
|
||||
while (k > 0n && i < length) {
|
||||
if (k & 1n) {
|
||||
let remainder = Number(k % twoPowW);
|
||||
if (remainder >= Number(twoPowWMinus1)) {
|
||||
remainder -= Number(twoPowW);
|
||||
}
|
||||
digits[i] = remainder;
|
||||
k -= BigInt(remainder);
|
||||
}
|
||||
k >>= 1n;
|
||||
i++;
|
||||
}
|
||||
// remaining digits already zero
|
||||
return digits;
|
||||
}
|
||||
|
||||
static random(): Scalar {
|
||||
while (true) {
|
||||
const buf = randomBytes(BYTE_LENGTH);
|
||||
let acc = 0n;
|
||||
for (let i = 0; i < BYTE_LENGTH; i++) {
|
||||
const byte = buf[i];
|
||||
if (byte === undefined) throw new Error("Unexpected undefined byte when sampling scalar");
|
||||
acc |= BigInt(byte) << BigInt(8 * i);
|
||||
}
|
||||
if (acc < ORDER) {
|
||||
return new Scalar(acc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static fromFp5(element: Fp5): Scalar {
|
||||
const coeffs = element.toTuple();
|
||||
const entries = [coeffs[0], coeffs[1], coeffs[2], coeffs[3], coeffs[4]];
|
||||
let acc = 0n;
|
||||
for (let i = entries.length - 1; i >= 0; i--) {
|
||||
const limb = entries[i];
|
||||
if (!limb) throw new Error("Fp5 tuple missing limb");
|
||||
acc <<= 64n;
|
||||
acc |= limb.toBigInt();
|
||||
}
|
||||
return new Scalar(acc);
|
||||
}
|
||||
}
|
||||
|
||||
export const SCALAR_ORDER = ORDER;
|
||||
@@ -0,0 +1,64 @@
|
||||
import { randomBytes } from "crypto";
|
||||
import { Fp } from "./goldilocks";
|
||||
import { Fp5 } from "./goldilocks-fp5";
|
||||
import { hashToQuinticExtension } from "./poseidon2";
|
||||
import { Scalar } from "./scalar";
|
||||
import { ECPoint } from "./curve";
|
||||
|
||||
export interface SchnorrSignature {
|
||||
s: Scalar;
|
||||
e: Scalar;
|
||||
}
|
||||
|
||||
export class LighterPrivateKey {
|
||||
readonly scalar: Scalar;
|
||||
|
||||
constructor(scalar: Scalar) {
|
||||
this.scalar = scalar;
|
||||
}
|
||||
|
||||
static fromBytes(bytes: Uint8Array): LighterPrivateKey {
|
||||
if (bytes.length !== 40) {
|
||||
throw new Error("Lighter private key must be 40 bytes");
|
||||
}
|
||||
return new LighterPrivateKey(Scalar.fromBytesLE(bytes));
|
||||
}
|
||||
|
||||
static fromHex(hex: string): LighterPrivateKey {
|
||||
const normalized = hex.startsWith("0x") ? hex.slice(2) : hex;
|
||||
if (normalized.length !== 80) {
|
||||
throw new Error("Lighter private key hex must encode 40 bytes");
|
||||
}
|
||||
const bytes = Buffer.from(normalized, "hex");
|
||||
return LighterPrivateKey.fromBytes(bytes);
|
||||
}
|
||||
|
||||
toBytes(): Uint8Array {
|
||||
return this.scalar.toBytesLE();
|
||||
}
|
||||
|
||||
publicKey(): Fp5 {
|
||||
const point = ECPoint.generator().mul(this.scalar);
|
||||
return point.encode();
|
||||
}
|
||||
|
||||
signHashedMessage(hashed: Fp5): SchnorrSignature {
|
||||
const k = Scalar.random();
|
||||
const rPoint = ECPoint.generator().mul(k);
|
||||
const rEncoded = rPoint.encode();
|
||||
const preimage: Fp[] = [...rEncoded.toTuple(), ...hashed.toTuple()];
|
||||
const hash = hashToQuinticExtension(preimage);
|
||||
const e = Scalar.fromFp5(hash);
|
||||
const s = k.sub(e.mul(this.scalar));
|
||||
return { s, e };
|
||||
}
|
||||
}
|
||||
|
||||
export function signatureToBytes(sig: SchnorrSignature): Uint8Array {
|
||||
const sBytes = sig.s.toBytesLE();
|
||||
const eBytes = sig.e.toBytesLE();
|
||||
const out = new Uint8Array(80);
|
||||
out.set(sBytes, 0);
|
||||
out.set(eBytes, 40);
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
function normalizeDecimalInput(value: number | string | bigint): { sign: 1 | -1; digits: string; fractionLength: number } {
|
||||
if (typeof value === "bigint") {
|
||||
const sign = value < 0n ? -1 : 1;
|
||||
const digits = (sign === -1 ? -value : value).toString();
|
||||
return { sign, digits, fractionLength: 0 };
|
||||
}
|
||||
if (typeof value === "number") {
|
||||
if (!Number.isFinite(value)) {
|
||||
throw new Error(`Invalid decimal input: ${value}`);
|
||||
}
|
||||
value = value.toString();
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed.length) throw new Error("Decimal input cannot be empty");
|
||||
const sign: 1 | -1 = trimmed[0] === "-" ? -1 : 1;
|
||||
const unsigned = sign === -1 ? trimmed.slice(1) : trimmed;
|
||||
if (!/^\d*(?:\.\d*)?$/.test(unsigned)) {
|
||||
throw new Error(`Invalid decimal format: ${value}`);
|
||||
}
|
||||
if (unsigned === "" || unsigned === ".") {
|
||||
return { sign: 1, digits: "0", fractionLength: 0 };
|
||||
}
|
||||
const parts = unsigned.split(".");
|
||||
const integerPartRaw = parts[0] ?? "";
|
||||
const fractionRaw = parts[1] ?? "";
|
||||
const integerPart = integerPartRaw.replace(/^0+(?=\d)/, "");
|
||||
const fractionPart = fractionRaw.replace(/0+$/, "");
|
||||
if (!integerPart && !fractionPart) {
|
||||
return { sign: 1, digits: "0", fractionLength: 0 };
|
||||
}
|
||||
const digits = `${integerPart || "0"}${fractionPart}`;
|
||||
return { sign, digits, fractionLength: fractionPart.length };
|
||||
}
|
||||
|
||||
export function decimalToScaled(value: number | string | bigint, decimals: number): bigint {
|
||||
if (decimals < 0) throw new Error("Decimals must be non-negative");
|
||||
const { sign, digits, fractionLength } = normalizeDecimalInput(value);
|
||||
if (fractionLength > decimals) {
|
||||
const trimLength = fractionLength - decimals;
|
||||
const truncated = digits.slice(0, digits.length - trimLength) || "0";
|
||||
const result = BigInt(truncated);
|
||||
return sign === -1 ? -result : result;
|
||||
}
|
||||
const padded = digits.padEnd(digits.length + (decimals - fractionLength), "0");
|
||||
const result = BigInt(padded);
|
||||
return sign === -1 ? -result : result;
|
||||
}
|
||||
|
||||
export function scaledToDecimalString(value: bigint | number | string, decimals: number): string {
|
||||
if (typeof value === "number") {
|
||||
if (!Number.isFinite(value)) throw new Error(`Invalid scaled number: ${value}`);
|
||||
value = BigInt(Math.trunc(value));
|
||||
} else if (typeof value === "string") {
|
||||
if (!/^[-]?\d+$/.test(value.trim())) {
|
||||
throw new Error(`Invalid scaled string: ${value}`);
|
||||
}
|
||||
value = BigInt(value.trim());
|
||||
}
|
||||
const negative = value < 0n;
|
||||
let abs = negative ? -value : value;
|
||||
let digits = abs.toString();
|
||||
if (decimals === 0) {
|
||||
return negative ? `-${digits}` : digits;
|
||||
}
|
||||
if (digits.length <= decimals) {
|
||||
digits = digits.padStart(decimals + 1, "0");
|
||||
}
|
||||
const splitIndex = digits.length - decimals;
|
||||
const integerPart = digits.slice(0, splitIndex) || "0";
|
||||
const fractionPart = digits.slice(splitIndex);
|
||||
const result = `${integerPart}.${fractionPart}`.replace(/\.0+$/, "").replace(/\.$/, "");
|
||||
return negative ? `-${result}` : result;
|
||||
}
|
||||
|
||||
export function clampToInt64(value: bigint): bigint {
|
||||
const max = (1n << 63n) - 1n;
|
||||
const min = -(1n << 63n);
|
||||
if (value > max || value < min) {
|
||||
throw new Error("Value exceeds int64 bounds");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function toInt64(value: bigint): number {
|
||||
const bounded = clampToInt64(value);
|
||||
return Number(bounded);
|
||||
}
|
||||
|
||||
export function safeNumberToUint32(value: number | bigint): number {
|
||||
const val = typeof value === "bigint" ? Number(value) : value;
|
||||
if (!Number.isFinite(val) || val < 0 || val > 0xffffffff) {
|
||||
throw new Error(`Value ${value} is out of uint32 range`);
|
||||
}
|
||||
return Math.trunc(val);
|
||||
}
|
||||
|
||||
export function toSafeNumber(value: bigint | number): number {
|
||||
const numeric = typeof value === "bigint" ? Number(value) : value;
|
||||
if (!Number.isSafeInteger(numeric)) {
|
||||
throw new Error(`Value ${value.toString()} exceeds safe integer range`);
|
||||
}
|
||||
return numeric;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Fp, GOLDILOCKS_BYTE_LENGTH } from "./crypto/goldilocks";
|
||||
|
||||
const CHUNK_SIZE = GOLDILOCKS_BYTE_LENGTH;
|
||||
|
||||
export function arrayFromCanonicalLittleEndianBytes(bytes: Uint8Array): Fp[] {
|
||||
if (!bytes.length) return [];
|
||||
const remainder = bytes.length % CHUNK_SIZE;
|
||||
const paddedLength = remainder === 0 ? bytes.length : bytes.length + (CHUNK_SIZE - remainder);
|
||||
const padded = new Uint8Array(paddedLength);
|
||||
padded.set(bytes, 0);
|
||||
const result: Fp[] = [];
|
||||
for (let offset = 0; offset < padded.length; offset += CHUNK_SIZE) {
|
||||
const chunk = padded.subarray(offset, offset + CHUNK_SIZE);
|
||||
result.push(Fp.fromBytesLE(chunk));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,683 @@
|
||||
import { setInterval, clearInterval, setTimeout, clearTimeout } from "timers";
|
||||
import WebSocket from "ws";
|
||||
import type {
|
||||
AccountListener,
|
||||
DepthListener,
|
||||
KlineListener,
|
||||
OrderListener,
|
||||
TickerListener,
|
||||
} from "../adapter";
|
||||
import type { AsterAccountSnapshot, AsterDepth, AsterKline, AsterOrder, AsterTicker, CreateOrderParams } from "../types";
|
||||
import { extractMessage } from "../../utils/errors";
|
||||
import type { OrderSide, OrderType } from "../types";
|
||||
import { LighterHttpClient } from "./http-client";
|
||||
import { HttpNonceManager } from "./nonce-manager";
|
||||
import { LighterSigner, type CreateOrderSignParams } from "./signer";
|
||||
import { bytesToHex } from "./bytes";
|
||||
import type {
|
||||
LighterAccountDetails,
|
||||
LighterKline,
|
||||
LighterMarketStats,
|
||||
LighterOrder,
|
||||
LighterOrderBookLevel,
|
||||
LighterOrderBookSnapshot,
|
||||
LighterPosition,
|
||||
} from "./types";
|
||||
import { DEFAULT_AUTH_TOKEN_BUFFER_MS, DEFAULT_LIGHTER_ENVIRONMENT, LIGHTER_HOSTS, LIGHTER_ORDER_TYPE, LIGHTER_TIME_IN_FORCE, DEFAULT_ORDER_EXPIRY_PLACEHOLDER, IMMEDIATE_OR_CANCEL_EXPIRY_PLACEHOLDER } from "./constants";
|
||||
import { decimalToScaled, scaledToDecimalString } from "./decimal";
|
||||
import { lighterOrderToAster, toAccountSnapshot, toDepth, toKlines, toOrders, toTicker } from "./mappers";
|
||||
|
||||
interface SimpleEvent<T> {
|
||||
add(handler: (value: T) => void): void;
|
||||
remove(handler: (value: T) => void): void;
|
||||
emit(value: T): void;
|
||||
listenerCount(): number;
|
||||
}
|
||||
|
||||
function createEvent<T>(): SimpleEvent<T> {
|
||||
const listeners = new Set<(value: T) => void>();
|
||||
return {
|
||||
add(handler) {
|
||||
listeners.add(handler);
|
||||
},
|
||||
remove(handler) {
|
||||
listeners.delete(handler);
|
||||
},
|
||||
emit(value) {
|
||||
for (const handler of Array.from(listeners)) {
|
||||
try {
|
||||
handler(value);
|
||||
} catch (error) {
|
||||
console.error("[LighterGateway] listener error", error);
|
||||
}
|
||||
}
|
||||
},
|
||||
listenerCount() {
|
||||
return listeners.size;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface Pollers {
|
||||
ticker?: ReturnType<typeof setInterval>;
|
||||
klines: Map<string, ReturnType<typeof setInterval>>;
|
||||
}
|
||||
|
||||
const KLINE_DEFAULT_COUNT = 120;
|
||||
const DEFAULT_TICKER_POLL_MS = 3000;
|
||||
const DEFAULT_KLINE_POLL_MS = 15000;
|
||||
|
||||
const RESOLUTION_MS: Record<string, number> = {
|
||||
"1m": 60_000,
|
||||
"5m": 300_000,
|
||||
"15m": 900_000,
|
||||
"1h": 3_600_000,
|
||||
"4h": 14_400_000,
|
||||
"1d": 86_400_000,
|
||||
};
|
||||
|
||||
export interface LighterGatewayOptions {
|
||||
symbol: string; // display symbol used by strategy logging
|
||||
marketSymbol?: string; // actual Lighter order book symbol (e.g., BTC)
|
||||
accountIndex: number;
|
||||
apiKeys: Record<number, string>;
|
||||
baseUrl?: string;
|
||||
environment?: keyof typeof LIGHTER_HOSTS;
|
||||
marketId?: number;
|
||||
priceDecimals?: number;
|
||||
sizeDecimals?: number;
|
||||
chainId?: number;
|
||||
apiKeyIndices?: number[];
|
||||
tickerPollMs?: number;
|
||||
klinePollMs?: number;
|
||||
logger?: (context: string, error: unknown) => void;
|
||||
l1Address?: string;
|
||||
}
|
||||
|
||||
export class LighterGateway {
|
||||
private readonly displaySymbol: string;
|
||||
private readonly marketSymbol: string;
|
||||
private readonly http: LighterHttpClient;
|
||||
private readonly signer: LighterSigner;
|
||||
private readonly nonceManager: HttpNonceManager;
|
||||
private readonly logger: (context: string, error: unknown) => void;
|
||||
private readonly apiKeyIndices: number[];
|
||||
private readonly environment: keyof typeof LIGHTER_HOSTS;
|
||||
private readonly pollers: Pollers = { ticker: undefined, klines: new Map() };
|
||||
private readonly klineCache = new Map<string, AsterKline[]>();
|
||||
private readonly accountEvent = createEvent<AsterAccountSnapshot>();
|
||||
private readonly ordersEvent = createEvent<AsterOrder[]>();
|
||||
private readonly depthEvent = createEvent<AsterDepth>();
|
||||
private readonly tickerEvent = createEvent<AsterTicker>();
|
||||
private readonly klinesEvent = createEvent<AsterKline[]>();
|
||||
private readonly auth = { token: null as string | null, expiresAt: 0 };
|
||||
private readonly l1Address: string | null;
|
||||
|
||||
private marketId: number | null = null;
|
||||
private priceDecimals: number | null = null;
|
||||
private sizeDecimals: number | null = null;
|
||||
|
||||
private ws: WebSocket | null = null;
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private readonly wsUrl: string;
|
||||
private connectPromise: Promise<void> | null = null;
|
||||
|
||||
private accountDetails: LighterAccountDetails | null = null;
|
||||
private positions: LighterPosition[] = [];
|
||||
private orders: LighterOrder[] = [];
|
||||
private orderBook: LighterOrderBookSnapshot | null = null;
|
||||
private ticker: LighterMarketStats | null = null;
|
||||
private initialized = false;
|
||||
|
||||
private readonly tickerPollMs: number;
|
||||
private readonly klinePollMs: number;
|
||||
|
||||
constructor(options: LighterGatewayOptions) {
|
||||
this.displaySymbol = options.symbol;
|
||||
this.marketSymbol = (options.marketSymbol ?? options.symbol).toUpperCase();
|
||||
this.environment = options.environment ?? DEFAULT_LIGHTER_ENVIRONMENT;
|
||||
const host = options.baseUrl ?? LIGHTER_HOSTS[this.environment]?.rest;
|
||||
if (!host) {
|
||||
throw new Error(`Unknown Lighter environment ${this.environment}`);
|
||||
}
|
||||
const wsHost = LIGHTER_HOSTS[this.environment]?.ws;
|
||||
if (!wsHost) {
|
||||
throw new Error(`WebSocket endpoint not configured for env ${this.environment}`);
|
||||
}
|
||||
this.wsUrl = wsHost;
|
||||
this.http = new LighterHttpClient({ baseUrl: host });
|
||||
this.signer = new LighterSigner({
|
||||
accountIndex: options.accountIndex,
|
||||
chainId: options.chainId ?? (this.environment === "mainnet" ? 304 : 300),
|
||||
apiKeys: options.apiKeys,
|
||||
});
|
||||
this.apiKeyIndices = options.apiKeyIndices ?? Object.keys(options.apiKeys).map(Number);
|
||||
this.nonceManager = new HttpNonceManager({
|
||||
accountIndex: options.accountIndex,
|
||||
apiKeyIndices: this.apiKeyIndices,
|
||||
http: this.http,
|
||||
});
|
||||
this.logger = options.logger ?? ((context, error) => console.error(`[LighterGateway] ${context}`, error));
|
||||
this.marketId = options.marketId != null ? Number(options.marketId) : null;
|
||||
this.priceDecimals = options.priceDecimals ?? null;
|
||||
this.sizeDecimals = options.sizeDecimals ?? null;
|
||||
this.tickerPollMs = options.tickerPollMs ?? DEFAULT_TICKER_POLL_MS;
|
||||
this.klinePollMs = options.klinePollMs ?? DEFAULT_KLINE_POLL_MS;
|
||||
this.l1Address = options.l1Address ?? null;
|
||||
}
|
||||
|
||||
async ensureInitialized(): Promise<void> {
|
||||
if (this.initialized) return;
|
||||
if (!this.connectPromise) {
|
||||
this.connectPromise = this.initialize().catch((error) => {
|
||||
this.connectPromise = null;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
await this.connectPromise;
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
onAccount(handler: AccountListener): void {
|
||||
this.accountEvent.add(handler);
|
||||
}
|
||||
|
||||
onOrders(handler: OrderListener): void {
|
||||
this.ordersEvent.add(handler);
|
||||
}
|
||||
|
||||
onDepth(handler: DepthListener): void {
|
||||
this.depthEvent.add(handler);
|
||||
}
|
||||
|
||||
onTicker(handler: TickerListener): void {
|
||||
this.tickerEvent.add(handler);
|
||||
}
|
||||
|
||||
onKlines(handler: KlineListener): void {
|
||||
this.klinesEvent.add(handler);
|
||||
}
|
||||
|
||||
async createOrder(params: CreateOrderParams): Promise<AsterOrder> {
|
||||
await this.ensureInitialized();
|
||||
const conversion = this.mapCreateOrderParams(params);
|
||||
const { baseAmountScaledString, priceScaledString, triggerPriceScaledString, ...signParams } = conversion;
|
||||
const { apiKeyIndex, nonce } = this.nonceManager.next();
|
||||
try {
|
||||
const signed = this.signer.signCreateOrder({
|
||||
...signParams,
|
||||
apiKeyIndex,
|
||||
nonce,
|
||||
});
|
||||
const auth = await this.ensureAuthToken();
|
||||
await this.http.sendTransaction(signed.txType, signed.txInfo, { authToken: auth });
|
||||
return lighterOrderToAster(this.displaySymbol, {
|
||||
order_index: Number(signParams.clientOrderIndex % 1_000_000_000n),
|
||||
client_order_index: Number(signParams.clientOrderIndex),
|
||||
market_index: signParams.marketIndex,
|
||||
initial_base_amount: baseAmountScaledString,
|
||||
remaining_base_amount: baseAmountScaledString,
|
||||
price: priceScaledString,
|
||||
trigger_price: triggerPriceScaledString,
|
||||
is_ask: signParams.isAsk === 1,
|
||||
side: signParams.isAsk === 1 ? "sell" : "buy",
|
||||
type: params.type?.toLowerCase(),
|
||||
reduce_only: signParams.reduceOnly === 1,
|
||||
status: "NEW",
|
||||
created_at: Date.now(),
|
||||
} as LighterOrder);
|
||||
} catch (error) {
|
||||
this.nonceManager.acknowledgeFailure(apiKeyIndex);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async cancelOrder(params: { marketIndex?: number; orderId: number | string; apiKeyIndex?: number }): Promise<void> {
|
||||
await this.ensureInitialized();
|
||||
const marketIndex = params.marketIndex ?? this.marketId;
|
||||
if (marketIndex == null) throw new Error("Market index unknown");
|
||||
const indexValue = BigInt(typeof params.orderId === "string" ? Number(params.orderId) : params.orderId);
|
||||
const { apiKeyIndex, nonce } = this.nonceManager.next();
|
||||
try {
|
||||
const signed = this.signer.signCancelOrder({
|
||||
marketIndex,
|
||||
orderIndex: indexValue,
|
||||
nonce,
|
||||
apiKeyIndex,
|
||||
});
|
||||
const auth = await this.ensureAuthToken();
|
||||
await this.http.sendTransaction(signed.txType, signed.txInfo, { authToken: auth });
|
||||
} catch (error) {
|
||||
this.nonceManager.acknowledgeFailure(apiKeyIndex);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async cancelAllOrders(params?: { timeInForce?: number; scheduleMs?: number; apiKeyIndex?: number }): Promise<void> {
|
||||
await this.ensureInitialized();
|
||||
const timeInForce = params?.timeInForce ?? 0;
|
||||
const time = params?.scheduleMs != null ? BigInt(params.scheduleMs) : 0n;
|
||||
const { apiKeyIndex, nonce } = this.nonceManager.next();
|
||||
try {
|
||||
const signed = this.signer.signCancelAll({
|
||||
timeInForce,
|
||||
scheduledTime: time,
|
||||
nonce,
|
||||
apiKeyIndex,
|
||||
});
|
||||
const auth = await this.ensureAuthToken();
|
||||
await this.http.sendTransaction(signed.txType, signed.txInfo, { authToken: auth });
|
||||
} catch (error) {
|
||||
this.nonceManager.acknowledgeFailure(apiKeyIndex);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async initialize(): Promise<void> {
|
||||
await this.loadMetadata();
|
||||
await this.nonceManager.init(true);
|
||||
await this.refreshAccountSnapshot();
|
||||
await this.openWebSocket();
|
||||
// Emit an initial empty orders snapshot so strategies depending on an order
|
||||
// snapshot at startup can proceed even if the websocket does not publish
|
||||
// orders until there is activity.
|
||||
this.emitOrders();
|
||||
this.startPolling();
|
||||
}
|
||||
|
||||
private async loadMetadata(): Promise<void> {
|
||||
if (this.marketId != null && this.priceDecimals != null && this.sizeDecimals != null) return;
|
||||
const books = await this.http.getOrderBooks();
|
||||
const desiredSymbol = this.marketSymbol;
|
||||
let target = books.find((book) => (book.symbol ? String(book.symbol).toUpperCase() : "") === desiredSymbol);
|
||||
if (!target && this.marketId != null) {
|
||||
target = books.find((book) => Number(book.market_id) === Number(this.marketId));
|
||||
}
|
||||
if (!target) {
|
||||
if (this.marketId != null && this.priceDecimals != null && this.sizeDecimals != null) {
|
||||
return;
|
||||
}
|
||||
throw new Error(`Symbol ${desiredSymbol} not listed on Lighter order books`);
|
||||
}
|
||||
this.marketId = Number(target.market_id);
|
||||
if (this.priceDecimals == null) {
|
||||
this.priceDecimals = target.supported_price_decimals;
|
||||
}
|
||||
if (this.sizeDecimals == null) {
|
||||
this.sizeDecimals = target.supported_size_decimals;
|
||||
}
|
||||
}
|
||||
|
||||
private async refreshAccountSnapshot(): Promise<void> {
|
||||
try {
|
||||
const auth = await this.ensureAuthToken();
|
||||
let details: LighterAccountDetails | null = null;
|
||||
if (this.l1Address) {
|
||||
details = await this.http.getAccountDetails(Number(this.signer.accountIndex), auth, {
|
||||
by: "l1_address",
|
||||
value: this.l1Address,
|
||||
});
|
||||
}
|
||||
if (!details) {
|
||||
details = await this.http.getAccountDetails(Number(this.signer.accountIndex), auth, {
|
||||
by: "index",
|
||||
value: Number(this.signer.accountIndex),
|
||||
});
|
||||
}
|
||||
if (details) {
|
||||
this.accountDetails = details;
|
||||
this.emitAccount();
|
||||
} else {
|
||||
// Fallback: emit an empty account snapshot so strategies can proceed
|
||||
this.accountDetails = {
|
||||
account_index: Number(this.signer.accountIndex),
|
||||
status: 1,
|
||||
collateral: "0",
|
||||
available_balance: "0",
|
||||
} as LighterAccountDetails;
|
||||
this.positions = [];
|
||||
this.emitAccount();
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger("refreshAccount", error);
|
||||
}
|
||||
}
|
||||
|
||||
private async openWebSocket(): Promise<void> {
|
||||
if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
|
||||
return;
|
||||
}
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const ws = new WebSocket(this.wsUrl);
|
||||
this.ws = ws;
|
||||
const cleanup = () => {
|
||||
ws.removeAllListeners();
|
||||
};
|
||||
ws.on("open", async () => {
|
||||
try {
|
||||
await this.subscribeChannels();
|
||||
resolve();
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
ws.on("message", (data) => this.handleMessage(data));
|
||||
ws.on("close", (code, reason) => {
|
||||
cleanup();
|
||||
this.scheduleReconnect();
|
||||
});
|
||||
ws.on("error", (error) => {
|
||||
cleanup();
|
||||
this.logger("ws:error", error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private async subscribeChannels(): Promise<void> {
|
||||
const ws = this.ws;
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
||||
const marketId = this.marketId;
|
||||
if (marketId == null) throw new Error("Market ID unknown");
|
||||
ws.send(JSON.stringify({ type: "subscribe", channel: `order_book/${marketId}` }));
|
||||
ws.send(JSON.stringify({ type: "subscribe", channel: `account_all/${Number(this.signer.accountIndex)}` }));
|
||||
const auth = await this.ensureAuthToken();
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "subscribe",
|
||||
channel: `account_all_orders/${Number(this.signer.accountIndex)}`,
|
||||
auth,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private async ensureAuthToken(): Promise<string> {
|
||||
const now = Date.now();
|
||||
if (this.auth.token && now < this.auth.expiresAt - DEFAULT_AUTH_TOKEN_BUFFER_MS) {
|
||||
return this.auth.token;
|
||||
}
|
||||
const deadline = now + 10 * 60 * 1000; // 10 minutes horizon
|
||||
const token = this.signer.createAuthToken(deadline);
|
||||
this.auth.token = token;
|
||||
this.auth.expiresAt = deadline;
|
||||
return token;
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
if (this.reconnectTimer) return;
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = null;
|
||||
this.openWebSocket().catch((error) => this.logger("reconnect", error));
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
private handleMessage(data: WebSocket.RawData): void {
|
||||
try {
|
||||
const text = typeof data === "string" ? data : data.toString("utf8");
|
||||
const message = JSON.parse(text);
|
||||
const type = message?.type;
|
||||
switch (type) {
|
||||
case "connected":
|
||||
break;
|
||||
case "subscribed/order_book":
|
||||
this.handleOrderBookSnapshot(message);
|
||||
break;
|
||||
case "update/order_book":
|
||||
this.handleOrderBookUpdate(message);
|
||||
break;
|
||||
case "subscribed/account_all":
|
||||
case "update/account_all":
|
||||
this.handleAccountAll(message);
|
||||
break;
|
||||
case "subscribed/account_all_orders":
|
||||
case "update/account_all_orders":
|
||||
this.handleAccountOrders(message);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger("ws:message", error);
|
||||
}
|
||||
}
|
||||
|
||||
private handleOrderBookSnapshot(message: any): void {
|
||||
if (!message?.order_book) return;
|
||||
const snapshot: LighterOrderBookSnapshot = {
|
||||
market_id: this.marketId ?? 0,
|
||||
offset: message.order_book.offset ?? Date.now(),
|
||||
bids: message.order_book.bids ?? [],
|
||||
asks: message.order_book.asks ?? [],
|
||||
};
|
||||
this.orderBook = snapshot;
|
||||
this.emitDepth();
|
||||
}
|
||||
|
||||
private handleOrderBookUpdate(message: any): void {
|
||||
if (!this.orderBook) return;
|
||||
const update = message?.order_book;
|
||||
if (!update) return;
|
||||
if (Array.isArray(update.asks)) {
|
||||
this.orderBook.asks = mergeLevels(this.orderBook.asks ?? [], update.asks);
|
||||
}
|
||||
if (Array.isArray(update.bids)) {
|
||||
this.orderBook.bids = mergeLevels(this.orderBook.bids ?? [], update.bids);
|
||||
}
|
||||
this.orderBook.offset = update.offset ?? this.orderBook.offset;
|
||||
this.emitDepth();
|
||||
}
|
||||
|
||||
private handleAccountAll(message: any): void {
|
||||
if (!message) return;
|
||||
const positionsObject = message.positions ?? {};
|
||||
const positions: LighterPosition[] = Object.values(positionsObject) as LighterPosition[];
|
||||
this.positions = positions;
|
||||
this.emitAccount();
|
||||
}
|
||||
|
||||
private handleAccountOrders(message: any): void {
|
||||
if (!message) return;
|
||||
const ordersObject = message.orders ?? {};
|
||||
const buckets = Object.values(ordersObject) as unknown[];
|
||||
const allOrders: LighterOrder[] = buckets.flatMap((entry) => Array.isArray(entry) ? (entry as LighterOrder[]) : []);
|
||||
this.orders = allOrders;
|
||||
const mapped = toOrders(this.displaySymbol, allOrders);
|
||||
this.ordersEvent.emit(mapped);
|
||||
}
|
||||
|
||||
private emitDepth(): void {
|
||||
if (!this.orderBook || this.marketId == null) return;
|
||||
const depth = toDepth(this.displaySymbol, this.orderBook);
|
||||
this.depthEvent.emit(depth);
|
||||
}
|
||||
|
||||
private emitAccount(): void {
|
||||
if (!this.accountDetails) return;
|
||||
const snapshot = toAccountSnapshot(this.displaySymbol, this.accountDetails, this.positions);
|
||||
this.accountEvent.emit(snapshot);
|
||||
}
|
||||
|
||||
private emitOrders(): void {
|
||||
const mapped = toOrders(this.displaySymbol, this.orders ?? []);
|
||||
this.ordersEvent.emit(mapped);
|
||||
}
|
||||
|
||||
private startPolling(): void {
|
||||
if (!this.pollers.ticker) {
|
||||
this.pollers.ticker = setInterval(() => {
|
||||
this.refreshTicker().catch((error) => this.logger("ticker", error));
|
||||
}, this.tickerPollMs);
|
||||
void this.refreshTicker();
|
||||
}
|
||||
}
|
||||
|
||||
private async refreshTicker(): Promise<void> {
|
||||
try {
|
||||
const stats = await this.http.getExchangeStats();
|
||||
const marketId = this.marketId;
|
||||
if (marketId == null) return;
|
||||
const match = stats.find(
|
||||
(entry) => Number(entry.market_id) === marketId || (entry.symbol ? entry.symbol.toUpperCase() : "") === this.marketSymbol
|
||||
);
|
||||
if (!match) return;
|
||||
const ticker = toTicker(this.displaySymbol, match);
|
||||
this.tickerEvent.emit(ticker);
|
||||
} catch (error) {
|
||||
this.logger("refreshTicker", error);
|
||||
}
|
||||
}
|
||||
|
||||
watchKlines(interval: string, handler: KlineListener): void {
|
||||
this.klinesEvent.add(handler);
|
||||
const cached = this.klineCache.get(interval);
|
||||
if (cached) {
|
||||
handler(cloneKlines(cached));
|
||||
}
|
||||
const existing = this.pollers.klines.get(interval);
|
||||
if (!existing) {
|
||||
const poll = () => {
|
||||
void this.refreshKlines(interval).catch((error) => this.logger("klines", error));
|
||||
};
|
||||
const timer = setInterval(poll, this.klinePollMs);
|
||||
this.pollers.klines.set(interval, timer);
|
||||
poll();
|
||||
}
|
||||
}
|
||||
|
||||
private async refreshKlines(interval: string): Promise<void> {
|
||||
await this.ensureInitialized();
|
||||
const marketId = this.marketId;
|
||||
if (marketId == null) return;
|
||||
const resolutionMs = RESOLUTION_MS[interval];
|
||||
if (!resolutionMs) return;
|
||||
const end = Date.now();
|
||||
const count = Math.max(KLINE_DEFAULT_COUNT, 200);
|
||||
const start = end - resolutionMs * count;
|
||||
const startTs = Math.max(0, Math.floor(start));
|
||||
const endTs = Math.max(startTs + resolutionMs, Math.floor(end));
|
||||
const raw = await this.http.getCandlesticks({
|
||||
marketId,
|
||||
resolution: interval,
|
||||
countBack: count,
|
||||
endTimestamp: endTs,
|
||||
startTimestamp: startTs,
|
||||
setTimestampToEnd: true,
|
||||
});
|
||||
const mapped = toKlines(this.displaySymbol, interval, raw as LighterKline[]);
|
||||
this.klineCache.set(interval, mapped);
|
||||
this.klinesEvent.emit(cloneKlines(mapped));
|
||||
}
|
||||
|
||||
private mapCreateOrderParams(params: CreateOrderParams): Omit<CreateOrderSignParams, "nonce"> & {
|
||||
baseAmountScaledString: string;
|
||||
priceScaledString: string;
|
||||
triggerPriceScaledString: string;
|
||||
clientOrderIndex: bigint;
|
||||
} {
|
||||
if (this.marketId == null || this.priceDecimals == null || this.sizeDecimals == null) {
|
||||
throw new Error("Lighter market metadata not initialized");
|
||||
}
|
||||
if (params.quantity == null || !Number.isFinite(params.quantity)) {
|
||||
throw new Error("Lighter orders require quantity");
|
||||
}
|
||||
const side = params.side;
|
||||
const isAsk = side === "SELL" ? 1 : 0;
|
||||
const baseAmount = decimalToScaled(params.quantity, this.sizeDecimals);
|
||||
const baseAmountScaledString = scaledToDecimalString(baseAmount, this.sizeDecimals);
|
||||
const clientOrderIndex = BigInt(Date.now() % Number.MAX_SAFE_INTEGER);
|
||||
let priceScaled = params.price != null ? decimalToScaled(params.price, this.priceDecimals) : null;
|
||||
if (params.type === "MARKET" && priceScaled == null) {
|
||||
priceScaled = decimalToScaled(this.estimateMarketPrice(side), this.priceDecimals);
|
||||
}
|
||||
if (priceScaled == null) {
|
||||
throw new Error("Lighter order requires price");
|
||||
}
|
||||
const reduceOnly = params.reduceOnly === "true" || params.closePosition === "true" ? 1 : 0;
|
||||
const resultType = mapOrderType(params.type ?? "LIMIT");
|
||||
const resultTimeInForce = mapTimeInForce(params.timeInForce, params.type ?? "LIMIT");
|
||||
let triggerPriceScaled = 0n;
|
||||
if (params.stopPrice != null) {
|
||||
triggerPriceScaled = decimalToScaled(params.stopPrice, this.priceDecimals);
|
||||
}
|
||||
const orderExpiry = resultTimeInForce === LIGHTER_TIME_IN_FORCE.IMMEDIATE_OR_CANCEL
|
||||
? BigInt(IMMEDIATE_OR_CANCEL_EXPIRY_PLACEHOLDER)
|
||||
: BigInt(DEFAULT_ORDER_EXPIRY_PLACEHOLDER);
|
||||
|
||||
return {
|
||||
marketIndex: this.marketId,
|
||||
clientOrderIndex,
|
||||
baseAmount,
|
||||
baseAmountScaledString,
|
||||
price: Number(priceScaled),
|
||||
priceScaledString: scaledToDecimalString(priceScaled, this.priceDecimals),
|
||||
isAsk,
|
||||
orderType: resultType,
|
||||
timeInForce: resultTimeInForce,
|
||||
reduceOnly,
|
||||
triggerPrice: Number(triggerPriceScaled),
|
||||
triggerPriceScaledString: scaledToDecimalString(triggerPriceScaled, this.priceDecimals),
|
||||
orderExpiry,
|
||||
expiredAt: BigInt(Date.now() + 10 * 60 * 1000),
|
||||
};
|
||||
}
|
||||
|
||||
private estimateMarketPrice(side: OrderSide): number {
|
||||
if (this.orderBook) {
|
||||
const levels = side === "SELL" ? this.orderBook.bids : this.orderBook.asks;
|
||||
if (levels && levels.length) {
|
||||
const sorted = [...levels].sort((a, b) => {
|
||||
const aPrice = Number(a.price);
|
||||
const bPrice = Number(b.price);
|
||||
return side === "SELL" ? bPrice - aPrice : aPrice - bPrice;
|
||||
});
|
||||
const level = sorted[0];
|
||||
if (level) return Number(level.price);
|
||||
}
|
||||
}
|
||||
if (this.ticker) {
|
||||
return Number(this.ticker.last_trade_price);
|
||||
}
|
||||
throw new Error("Unable to determine market price for order");
|
||||
}
|
||||
}
|
||||
|
||||
function mergeLevels(existing: LighterOrderBookLevel[], updates: LighterOrderBookLevel[]): LighterOrderBookLevel[] {
|
||||
const map = new Map<string, string>();
|
||||
for (const level of existing) {
|
||||
map.set(level.price, level.size);
|
||||
}
|
||||
for (const update of updates) {
|
||||
if (Number(update.size) <= 0) {
|
||||
map.delete(update.price);
|
||||
} else {
|
||||
map.set(update.price, update.size);
|
||||
}
|
||||
}
|
||||
return Array.from(map.entries()).map(([price, size]) => ({ price, size } as LighterOrderBookLevel));
|
||||
}
|
||||
|
||||
function cloneKlines(klines: AsterKline[]): AsterKline[] {
|
||||
return klines.map((kline) => ({ ...kline }));
|
||||
}
|
||||
|
||||
function mapOrderType(type: OrderType): number {
|
||||
switch (type) {
|
||||
case "MARKET":
|
||||
return LIGHTER_ORDER_TYPE.MARKET;
|
||||
case "STOP_MARKET":
|
||||
return LIGHTER_ORDER_TYPE.STOP_LOSS;
|
||||
default:
|
||||
return LIGHTER_ORDER_TYPE.LIMIT;
|
||||
}
|
||||
}
|
||||
|
||||
function mapTimeInForce(timeInForce: string | undefined, type: OrderType): number {
|
||||
const value = (timeInForce ?? (type === "MARKET" ? "IOC" : "GTC")).toUpperCase();
|
||||
switch (value) {
|
||||
case "IOC":
|
||||
return LIGHTER_TIME_IN_FORCE.IMMEDIATE_OR_CANCEL;
|
||||
case "GTX":
|
||||
return LIGHTER_TIME_IN_FORCE.POST_ONLY;
|
||||
default:
|
||||
return LIGHTER_TIME_IN_FORCE.GOOD_TILL_TIME;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
import type {
|
||||
LighterAccountDetails,
|
||||
LighterKline,
|
||||
LighterMarketStats,
|
||||
LighterOrderBookMetadata,
|
||||
} from "./types";
|
||||
import { DEFAULT_LIGHTER_ENVIRONMENT, LIGHTER_HOSTS } from "./constants";
|
||||
|
||||
interface ApiResponseBase {
|
||||
code: number;
|
||||
message?: string | null;
|
||||
}
|
||||
|
||||
interface OrderBooksResponse extends ApiResponseBase {
|
||||
order_books?: LighterOrderBookMetadata[];
|
||||
}
|
||||
|
||||
interface ExchangeStatsResponse extends ApiResponseBase {
|
||||
order_book_stats?: Array<{
|
||||
market_id: number;
|
||||
index_price?: string;
|
||||
mark_price?: string;
|
||||
last_trade_price: string;
|
||||
open_interest?: string;
|
||||
daily_base_token_volume?: number;
|
||||
daily_quote_token_volume?: number;
|
||||
daily_price_low?: number;
|
||||
daily_price_high?: number;
|
||||
daily_price_change?: number;
|
||||
symbol: string;
|
||||
funding_rate?: string;
|
||||
funding_timestamp?: number;
|
||||
current_funding_rate?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface NextNonceResponse extends ApiResponseBase {
|
||||
nonce: number;
|
||||
}
|
||||
|
||||
interface SendTxResponse extends ApiResponseBase {
|
||||
tx_hash: string;
|
||||
predicted_execution_time_ms?: number;
|
||||
}
|
||||
|
||||
interface CandlesticksResponse extends ApiResponseBase {
|
||||
resolution: string;
|
||||
candlesticks: Array<{
|
||||
start_timestamp?: number;
|
||||
end_timestamp?: number;
|
||||
timestamp?: number;
|
||||
open: number | string;
|
||||
high: number | string;
|
||||
low: number | string;
|
||||
close: number | string;
|
||||
base_token_volume: number | string;
|
||||
quote_token_volume: number | string;
|
||||
trades?: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface AccountResponse extends ApiResponseBase {
|
||||
account?: LighterAccountDetails;
|
||||
}
|
||||
|
||||
export interface LighterHttpClientOptions {
|
||||
baseUrl?: string;
|
||||
environment?: keyof typeof LIGHTER_HOSTS;
|
||||
priceProtection?: boolean;
|
||||
fetcher?: typeof fetch;
|
||||
}
|
||||
|
||||
export class LighterHttpClient {
|
||||
readonly baseUrl: string;
|
||||
private readonly priceProtection: boolean;
|
||||
private readonly fetcher: typeof fetch;
|
||||
|
||||
constructor(options: LighterHttpClientOptions = {}) {
|
||||
const env = options.environment ?? DEFAULT_LIGHTER_ENVIRONMENT;
|
||||
const host = options.baseUrl ?? LIGHTER_HOSTS[env]?.rest;
|
||||
if (!host) {
|
||||
throw new Error(`Unknown Lighter environment: ${env}`);
|
||||
}
|
||||
this.baseUrl = host.replace(/\/$/, "");
|
||||
this.priceProtection = options.priceProtection ?? true;
|
||||
this.fetcher = options.fetcher ?? globalThis.fetch.bind(globalThis);
|
||||
if (!this.fetcher) {
|
||||
throw new Error("Global fetch is not available; provide a custom fetch implementation");
|
||||
}
|
||||
}
|
||||
|
||||
async getOrderBooks(): Promise<LighterOrderBookMetadata[]> {
|
||||
const response = await this.get<OrderBooksResponse>("/api/v1/orderBooks");
|
||||
return response.order_books ?? [];
|
||||
}
|
||||
|
||||
async getExchangeStats(): Promise<LighterMarketStats[]> {
|
||||
const response = await this.get<ExchangeStatsResponse>("/api/v1/exchangeStats");
|
||||
const stats = response.order_book_stats ?? [];
|
||||
return stats.map((entry) => ({
|
||||
market_id: entry.market_id,
|
||||
symbol: entry.symbol,
|
||||
index_price: entry.index_price ?? entry.mark_price ?? entry.last_trade_price,
|
||||
mark_price: entry.mark_price ?? entry.last_trade_price,
|
||||
last_trade_price: entry.last_trade_price,
|
||||
open_interest: entry.open_interest ?? "0",
|
||||
daily_base_token_volume: entry.daily_base_token_volume,
|
||||
daily_quote_token_volume: entry.daily_quote_token_volume,
|
||||
daily_price_low: entry.daily_price_low,
|
||||
daily_price_high: entry.daily_price_high,
|
||||
daily_price_change: entry.daily_price_change,
|
||||
current_funding_rate: entry.current_funding_rate,
|
||||
funding_rate: entry.funding_rate,
|
||||
funding_timestamp: entry.funding_timestamp,
|
||||
}));
|
||||
}
|
||||
|
||||
async getAccountDetails(
|
||||
accountIndex: number,
|
||||
authToken?: string,
|
||||
options: { by?: "index" | "l1_address"; value?: string | number } = {}
|
||||
): Promise<LighterAccountDetails | null> {
|
||||
const query: Record<string, unknown> = {};
|
||||
if (authToken) {
|
||||
query.auth = authToken;
|
||||
}
|
||||
const by = options.by ?? "index";
|
||||
query.by = by;
|
||||
if (options.value !== undefined) {
|
||||
query.value = options.value;
|
||||
} else if (by === "index") {
|
||||
query.value = accountIndex;
|
||||
}
|
||||
const response = await this.get<AccountResponse>("/api/v1/account", {
|
||||
query,
|
||||
headers: authToken ? { Authorization: authToken } : undefined,
|
||||
tolerateNotFound: true,
|
||||
});
|
||||
return response.account ?? null;
|
||||
}
|
||||
|
||||
async getCandlesticks(params: {
|
||||
marketId: number;
|
||||
resolution: string;
|
||||
countBack: number;
|
||||
startTimestamp: number;
|
||||
endTimestamp: number;
|
||||
setTimestampToEnd?: boolean;
|
||||
}): Promise<LighterKline[]> {
|
||||
const response = await this.get<CandlesticksResponse>("/api/v1/candlesticks", {
|
||||
query: {
|
||||
market_id: params.marketId,
|
||||
resolution: params.resolution,
|
||||
count_back: params.countBack,
|
||||
start_timestamp: params.startTimestamp,
|
||||
end_timestamp: params.endTimestamp,
|
||||
set_timestamp_to_end: params.setTimestampToEnd ?? true,
|
||||
},
|
||||
});
|
||||
|
||||
return (response.candlesticks ?? []).map((entry) => ({
|
||||
start_timestamp: entry.start_timestamp ?? entry.timestamp ?? 0,
|
||||
end_timestamp:
|
||||
entry.end_timestamp ??
|
||||
(entry.start_timestamp ?? entry.timestamp ?? 0) + 1,
|
||||
open: String(entry.open ?? 0),
|
||||
high: String(entry.high ?? 0),
|
||||
low: String(entry.low ?? 0),
|
||||
close: String(entry.close ?? 0),
|
||||
base_token_volume: String(entry.base_token_volume ?? 0),
|
||||
quote_token_volume: String(entry.quote_token_volume ?? 0),
|
||||
trades: entry.trades,
|
||||
}));
|
||||
}
|
||||
|
||||
async getNextNonce(accountIndex: number, apiKeyIndex: number): Promise<bigint> {
|
||||
const response = await this.get<NextNonceResponse>("/api/v1/nextNonce", {
|
||||
query: {
|
||||
account_index: accountIndex,
|
||||
api_key_index: apiKeyIndex,
|
||||
},
|
||||
});
|
||||
if (typeof response.nonce !== "number") {
|
||||
throw new Error("Lighter nextNonce response missing nonce");
|
||||
}
|
||||
return BigInt(response.nonce);
|
||||
}
|
||||
|
||||
async sendTransaction(
|
||||
txType: number,
|
||||
txInfo: string,
|
||||
options: { priceProtection?: boolean; authToken?: string } = {}
|
||||
): Promise<SendTxResponse> {
|
||||
const form = new FormData();
|
||||
form.set("tx_type", String(txType));
|
||||
form.set("tx_info", txInfo);
|
||||
const priceProtection = options.priceProtection ?? this.priceProtection;
|
||||
if (priceProtection != null) form.set("price_protection", String(priceProtection));
|
||||
return this.postForm<SendTxResponse>("/api/v1/sendTx", form, options.authToken);
|
||||
}
|
||||
|
||||
private async get<T extends ApiResponseBase>(
|
||||
path: string,
|
||||
options: {
|
||||
query?: Record<string, unknown>;
|
||||
headers?: Record<string, string | undefined>;
|
||||
tolerateNotFound?: boolean;
|
||||
} = {}
|
||||
): Promise<T> {
|
||||
const url = new URL(path, `${this.baseUrl}`);
|
||||
if (options.query) {
|
||||
for (const [key, value] of Object.entries(options.query)) {
|
||||
if (value === undefined || value === null) continue;
|
||||
url.searchParams.set(key, String(value));
|
||||
}
|
||||
}
|
||||
const requestUrl = url.toString();
|
||||
const response = await this.fetcher(requestUrl, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Accept": "application/json",
|
||||
...this.cleanHeaders(options.headers),
|
||||
},
|
||||
});
|
||||
if (options.tolerateNotFound && response.status === 404) {
|
||||
return { code: 404 } as T;
|
||||
}
|
||||
return this.parseResponse<T>(response, requestUrl);
|
||||
}
|
||||
|
||||
private async post<T extends ApiResponseBase>(path: string, body: unknown, authToken?: string): Promise<T> {
|
||||
const requestUrl = new URL(path, `${this.baseUrl}`).toString();
|
||||
const response = await this.fetcher(requestUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
...(authToken ? { Authorization: authToken } : {}),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return this.parseResponse<T>(response, requestUrl);
|
||||
}
|
||||
|
||||
private async postForm<T extends ApiResponseBase>(path: string, form: FormData, authToken?: string): Promise<T> {
|
||||
const requestUrl = new URL(path, `${this.baseUrl}`).toString();
|
||||
const response = await this.fetcher(requestUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
...(authToken ? { Authorization: authToken } : {}),
|
||||
},
|
||||
body: form as any,
|
||||
});
|
||||
return this.parseResponse<T>(response, requestUrl);
|
||||
}
|
||||
|
||||
private cleanHeaders(headers?: Record<string, string | undefined>): Record<string, string> | undefined {
|
||||
if (!headers) return undefined;
|
||||
const result: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
if (value) result[key] = value;
|
||||
}
|
||||
return Object.keys(result).length ? result : undefined;
|
||||
}
|
||||
|
||||
private async parseResponse<T extends ApiResponseBase>(response: Response, requestUrl: string): Promise<T> {
|
||||
const text = await response.text();
|
||||
if (!response.ok) {
|
||||
const snippet = text ? truncateBody(text) : response.statusText;
|
||||
throw new Error(`Lighter HTTP ${response.status} ${response.statusText} (${requestUrl}): ${snippet}`);
|
||||
}
|
||||
if (!text) {
|
||||
throw new Error(`Empty Lighter response body (${requestUrl})`);
|
||||
}
|
||||
let parsed: T;
|
||||
try {
|
||||
parsed = JSON.parse(text) as T;
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to parse Lighter response (${requestUrl}): ${String(error)}. Body: ${truncateBody(text)}`);
|
||||
}
|
||||
if (typeof parsed.code === "number" && parsed.code !== 200) {
|
||||
throw new Error(parsed.message ?? `Lighter API returned code ${parsed.code} (${requestUrl})`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
|
||||
function truncateBody(body: string, limit = 200): string {
|
||||
return body.length > limit ? `${body.slice(0, limit)}…` : body;
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import type {
|
||||
AsterAccountAsset,
|
||||
AsterAccountPosition,
|
||||
AsterAccountSnapshot,
|
||||
AsterDepth,
|
||||
AsterDepthLevel,
|
||||
AsterKline,
|
||||
AsterOrder,
|
||||
AsterTicker,
|
||||
OrderSide,
|
||||
OrderType,
|
||||
} from "../types";
|
||||
import type {
|
||||
LighterAccountDetails,
|
||||
LighterKline,
|
||||
LighterMarketStats,
|
||||
LighterOrder,
|
||||
LighterOrderBookLevel,
|
||||
LighterOrderBookSnapshot,
|
||||
LighterPosition,
|
||||
} from "./types";
|
||||
|
||||
export function toDepth(symbol: string, snapshot: LighterOrderBookSnapshot): AsterDepth {
|
||||
const toLevels = (levels: LighterOrderBookLevel[]): AsterDepthLevel[] =>
|
||||
levels.map((level) => [level.price, level.size]);
|
||||
return {
|
||||
symbol,
|
||||
lastUpdateId: snapshot.offset ?? Date.now(),
|
||||
bids: toLevels(snapshot.bids ?? []),
|
||||
asks: toLevels(snapshot.asks ?? []),
|
||||
eventTime: Date.now(),
|
||||
eventType: "lighterDepth",
|
||||
};
|
||||
}
|
||||
|
||||
export function toTicker(symbol: string, stats: LighterMarketStats): AsterTicker {
|
||||
return {
|
||||
symbol,
|
||||
eventType: "lighterTicker",
|
||||
eventTime: Date.now(),
|
||||
lastPrice: stats.last_trade_price,
|
||||
openPrice: stats.daily_price_low != null ? String(stats.daily_price_low) : stats.last_trade_price,
|
||||
highPrice: stats.daily_price_high != null ? String(stats.daily_price_high) : stats.last_trade_price,
|
||||
lowPrice: stats.daily_price_low != null ? String(stats.daily_price_low) : stats.last_trade_price,
|
||||
volume: stats.daily_base_token_volume != null ? String(stats.daily_base_token_volume) : "0",
|
||||
quoteVolume: stats.daily_quote_token_volume != null ? String(stats.daily_quote_token_volume) : "0",
|
||||
priceChange: stats.daily_price_change != null ? String(stats.daily_price_change) : undefined,
|
||||
markPrice: undefined,
|
||||
weightedAvgPrice: undefined,
|
||||
} as AsterTicker;
|
||||
}
|
||||
|
||||
export function toKlines(symbol: string, interval: string, klines: LighterKline[]): AsterKline[] {
|
||||
return klines.map((entry) => ({
|
||||
symbol,
|
||||
eventType: "lighterKline",
|
||||
eventTime: Date.now(),
|
||||
interval,
|
||||
openTime: entry.start_timestamp,
|
||||
closeTime: entry.end_timestamp,
|
||||
open: entry.open,
|
||||
high: entry.high,
|
||||
low: entry.low,
|
||||
close: entry.close,
|
||||
volume: entry.base_token_volume,
|
||||
quoteAssetVolume: entry.quote_token_volume,
|
||||
numberOfTrades: entry.trades ?? 0,
|
||||
isClosed: true,
|
||||
}));
|
||||
}
|
||||
|
||||
export function toOrders(symbol: string, orders: LighterOrder[]): AsterOrder[] {
|
||||
return orders.map((order) => lighterOrderToAster(symbol, order));
|
||||
}
|
||||
|
||||
export function lighterOrderToAster(symbol: string, order: LighterOrder): AsterOrder {
|
||||
const side: OrderSide = order.is_ask || order.side?.toLowerCase() === "sell" || order.side?.toLowerCase() === "ask"
|
||||
? "SELL"
|
||||
: "BUY";
|
||||
return {
|
||||
orderId: order.order_index,
|
||||
clientOrderId: String(order.client_order_index ?? order.order_index ?? ""),
|
||||
symbol,
|
||||
side,
|
||||
type: mapOrderType(order.type),
|
||||
status: order.status ?? order.trigger_status ?? "UNKNOWN",
|
||||
price: order.price ?? "0",
|
||||
origQty: order.initial_base_amount ?? "0",
|
||||
executedQty: computeExecutedQty(order),
|
||||
stopPrice: order.trigger_price ?? "0",
|
||||
time: order.created_at ?? Date.now(),
|
||||
updateTime: order.updated_at ?? Date.now(),
|
||||
reduceOnly: Boolean(order.reduce_only),
|
||||
closePosition: Boolean(order.reduce_only ?? order.owner_account_index === undefined ? false : order.is_ask),
|
||||
workingType: "MARK_PRICE",
|
||||
activationPrice: order.trigger_price,
|
||||
};
|
||||
}
|
||||
|
||||
function computeExecutedQty(order: LighterOrder): string {
|
||||
if (order.filled_base_amount) return order.filled_base_amount;
|
||||
if (order.initial_base_amount && order.remaining_base_amount) {
|
||||
try {
|
||||
const initial = Number(order.initial_base_amount);
|
||||
const remaining = Number(order.remaining_base_amount);
|
||||
if (Number.isFinite(initial) && Number.isFinite(remaining)) {
|
||||
return (initial - remaining).toString();
|
||||
}
|
||||
} catch (_) {
|
||||
// fall through
|
||||
}
|
||||
}
|
||||
return "0";
|
||||
}
|
||||
|
||||
function mapOrderType(value?: string): OrderType {
|
||||
if (!value) return "LIMIT";
|
||||
const normalized = value.toLowerCase();
|
||||
switch (normalized) {
|
||||
case "limit":
|
||||
return "LIMIT";
|
||||
case "market":
|
||||
return "MARKET";
|
||||
case "stop_loss":
|
||||
case "stop_loss_market":
|
||||
return "STOP_MARKET";
|
||||
case "stop_loss_limit":
|
||||
return "LIMIT";
|
||||
case "take_profit":
|
||||
case "take_profit_market":
|
||||
return "STOP_MARKET";
|
||||
case "take_profit_limit":
|
||||
return "LIMIT";
|
||||
default:
|
||||
return "LIMIT";
|
||||
}
|
||||
}
|
||||
|
||||
export function toAccountSnapshot(
|
||||
symbol: string,
|
||||
details: LighterAccountDetails,
|
||||
positions: LighterPosition[] = [],
|
||||
assets: AsterAccountAsset[] = []
|
||||
): AsterAccountSnapshot {
|
||||
const transformedPositions = positions.map((position) => lighterPositionToAster(symbol, position));
|
||||
const aggregateUnrealized = transformedPositions.reduce((acc, pos) => acc + Number(pos.unrealizedProfit ?? 0), 0);
|
||||
const assetList = assets.length ? assets : defaultAsset(details);
|
||||
return {
|
||||
canTrade: details.status !== 0,
|
||||
canDeposit: true,
|
||||
canWithdraw: true,
|
||||
updateTime: Date.now(),
|
||||
totalWalletBalance: details.collateral ?? "0",
|
||||
totalUnrealizedProfit: aggregateUnrealized.toFixed(8),
|
||||
positions: transformedPositions,
|
||||
assets: assetList,
|
||||
};
|
||||
}
|
||||
|
||||
function defaultAsset(details: LighterAccountDetails): AsterAccountAsset[] {
|
||||
return [
|
||||
{
|
||||
asset: "USDC",
|
||||
walletBalance: details.collateral ?? "0",
|
||||
availableBalance: details.available_balance ?? details.collateral ?? "0",
|
||||
updateTime: Date.now(),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function lighterPositionToAster(symbol: string, position: LighterPosition): AsterAccountPosition {
|
||||
const sign = position.sign ?? 0;
|
||||
const positionSide = sign > 0 ? "LONG" : sign < 0 ? "SHORT" : "BOTH";
|
||||
return {
|
||||
symbol: position.symbol ?? symbol,
|
||||
positionAmt: position.position ?? "0",
|
||||
entryPrice: position.avg_entry_price ?? "0",
|
||||
unrealizedProfit: position.unrealized_pnl ?? "0",
|
||||
positionSide,
|
||||
updateTime: Date.now(),
|
||||
liquidationPrice: position.liquidation_price,
|
||||
maintMargin: undefined,
|
||||
initialMargin: position.allocated_margin,
|
||||
marginType: position.margin_mode === 1 ? "ISOLATED" : "CROSS",
|
||||
markPrice: undefined,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { LighterHttpClient } from "./http-client";
|
||||
import type { LighterNonceManager } from "./types";
|
||||
|
||||
interface NonceSlot {
|
||||
apiKeyIndex: number;
|
||||
next: bigint;
|
||||
lastIssued: bigint | null;
|
||||
}
|
||||
|
||||
export interface NonceManagerOptions {
|
||||
accountIndex: number;
|
||||
apiKeyIndices: number[];
|
||||
http: LighterHttpClient;
|
||||
}
|
||||
|
||||
export class HttpNonceManager implements LighterNonceManager {
|
||||
private readonly accountIndex: number;
|
||||
private readonly apiKeyIndices: number[];
|
||||
private readonly http: LighterHttpClient;
|
||||
private readonly slots = new Map<number, NonceSlot>();
|
||||
private pointer = 0;
|
||||
private initPromise: Promise<void> | null = null;
|
||||
|
||||
constructor(options: NonceManagerOptions) {
|
||||
if (!options.apiKeyIndices.length) {
|
||||
throw new Error("Nonce manager requires at least one API key index");
|
||||
}
|
||||
this.accountIndex = options.accountIndex;
|
||||
this.apiKeyIndices = Array.from(new Set(options.apiKeyIndices)).sort((a, b) => a - b);
|
||||
this.http = options.http;
|
||||
}
|
||||
|
||||
async init(force = false): Promise<void> {
|
||||
if (!this.initPromise || force) {
|
||||
this.initPromise = this.refreshAll(force).catch((error) => {
|
||||
this.initPromise = null;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
await this.initPromise;
|
||||
}
|
||||
|
||||
next(): { apiKeyIndex: number; nonce: bigint } {
|
||||
if (!this.slots.size) {
|
||||
throw new Error("Nonce manager not initialized");
|
||||
}
|
||||
const slot = this.pickSlot();
|
||||
const nonce = slot.next;
|
||||
slot.lastIssued = nonce;
|
||||
slot.next = nonce + 1n;
|
||||
return { apiKeyIndex: slot.apiKeyIndex, nonce };
|
||||
}
|
||||
|
||||
acknowledgeFailure(apiKeyIndex: number): void {
|
||||
const slot = this.slots.get(apiKeyIndex);
|
||||
if (!slot || slot.lastIssued === null) return;
|
||||
slot.next = slot.lastIssued;
|
||||
slot.lastIssued = null;
|
||||
}
|
||||
|
||||
async refresh(apiKeyIndex: number): Promise<void> {
|
||||
const nonce = await this.http.getNextNonce(this.accountIndex, apiKeyIndex);
|
||||
this.slots.set(apiKeyIndex, { apiKeyIndex, next: nonce, lastIssued: null });
|
||||
}
|
||||
|
||||
private async refreshAll(force: boolean): Promise<void> {
|
||||
await Promise.all(
|
||||
this.apiKeyIndices.map(async (index) => {
|
||||
if (!force && this.slots.has(index)) return;
|
||||
await this.refresh(index);
|
||||
})
|
||||
);
|
||||
this.pointer = 0;
|
||||
}
|
||||
|
||||
private pickSlot(): NonceSlot {
|
||||
const total = this.apiKeyIndices.length;
|
||||
if (total === 0) {
|
||||
throw new Error("Nonce manager not initialized");
|
||||
}
|
||||
const index = this.apiKeyIndices[this.pointer % total]!;
|
||||
this.pointer = (this.pointer + 1) % total;
|
||||
const slot = this.slots.get(index);
|
||||
if (!slot) {
|
||||
throw new Error(`Nonce slot for API key index ${index} is not initialized`);
|
||||
}
|
||||
return slot;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
import { LighterPrivateKey, signatureToBytes } from "./crypto/schnorr";
|
||||
import { hashToQuinticExtension } from "./crypto/poseidon2";
|
||||
import { Fp } from "./crypto/goldilocks";
|
||||
import { Fp5 } from "./crypto/goldilocks-fp5";
|
||||
import { arrayFromCanonicalLittleEndianBytes } from "./field-array";
|
||||
import { bytesToHex } from "./bytes";
|
||||
import { DEFAULT_TRANSACTION_EXPIRY_BUFFER_MS, LIGHTER_TX_TYPE } from "./constants";
|
||||
import { safeNumberToUint32, toSafeNumber } from "./decimal";
|
||||
|
||||
const BASE64_ENCODE = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64");
|
||||
const AUTH_MAX_WINDOW_MS = 7 * 60 * 60 * 1000; // 7 hours
|
||||
|
||||
function fpFromUint32(value: number): Fp {
|
||||
const uint32 = safeNumberToUint32(value);
|
||||
return Fp.fromUint32(uint32);
|
||||
}
|
||||
|
||||
function fpFromInt64(value: bigint | number): Fp {
|
||||
const bigintValue = typeof value === "number" ? BigInt(Math.trunc(value)) : value;
|
||||
return new Fp(bigintValue);
|
||||
}
|
||||
|
||||
interface KeySlot {
|
||||
index: number;
|
||||
key: LighterPrivateKey;
|
||||
}
|
||||
|
||||
export interface LighterSignerConfig {
|
||||
accountIndex: number | bigint;
|
||||
chainId: number;
|
||||
apiKeys: Record<number, string>;
|
||||
}
|
||||
|
||||
interface BaseSignOptions {
|
||||
apiKeyIndex?: number;
|
||||
nonce: bigint;
|
||||
expiredAt?: bigint;
|
||||
}
|
||||
|
||||
export interface CreateOrderSignParams extends BaseSignOptions {
|
||||
marketIndex: number;
|
||||
clientOrderIndex: bigint;
|
||||
baseAmount: bigint;
|
||||
price: number;
|
||||
isAsk: number;
|
||||
orderType: number;
|
||||
timeInForce: number;
|
||||
reduceOnly: number;
|
||||
triggerPrice: number;
|
||||
orderExpiry: bigint;
|
||||
}
|
||||
|
||||
export interface CancelOrderSignParams extends BaseSignOptions {
|
||||
marketIndex: number;
|
||||
orderIndex: bigint;
|
||||
}
|
||||
|
||||
export interface CancelAllSignParams extends BaseSignOptions {
|
||||
timeInForce: number;
|
||||
scheduledTime: bigint;
|
||||
}
|
||||
|
||||
export interface SignedTxPayload {
|
||||
txType: number;
|
||||
txInfo: string;
|
||||
txHash: string;
|
||||
signature: string;
|
||||
}
|
||||
|
||||
export class LighterSigner {
|
||||
readonly accountIndex: bigint;
|
||||
readonly chainId: number;
|
||||
private readonly keys = new Map<number, LighterPrivateKey>();
|
||||
private readonly defaultKeyIndex: number;
|
||||
|
||||
constructor(config: LighterSignerConfig) {
|
||||
if (!config || typeof config !== "object") {
|
||||
throw new Error("LighterSigner requires configuration");
|
||||
}
|
||||
this.chainId = config.chainId >>> 0;
|
||||
this.accountIndex = typeof config.accountIndex === "number"
|
||||
? BigInt(Math.trunc(config.accountIndex))
|
||||
: config.accountIndex;
|
||||
const entries = Object.entries(config.apiKeys ?? {}).map(([idx, hex]) => ({
|
||||
index: Number(idx),
|
||||
key: LighterPrivateKey.fromHex(hex),
|
||||
}));
|
||||
if (!entries.length) {
|
||||
throw new Error("At least one Lighter API private key must be provided");
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (!Number.isInteger(entry.index) || entry.index < 0 || entry.index > 255) {
|
||||
throw new Error(`Invalid API key index: ${entry.index}`);
|
||||
}
|
||||
this.keys.set(entry.index, entry.key);
|
||||
}
|
||||
this.defaultKeyIndex = entries[0]!.index;
|
||||
}
|
||||
|
||||
private resolveKey(apiKeyIndex?: number): KeySlot {
|
||||
const index = apiKeyIndex ?? this.defaultKeyIndex;
|
||||
const key = this.keys.get(index);
|
||||
if (!key) {
|
||||
throw new Error(`Missing private key for API key index ${index}`);
|
||||
}
|
||||
return { index, key };
|
||||
}
|
||||
|
||||
signCreateOrder(params: CreateOrderSignParams): SignedTxPayload {
|
||||
const slot = this.resolveKey(params.apiKeyIndex);
|
||||
const expiredAt = params.expiredAt ?? BigInt(Date.now() + DEFAULT_TRANSACTION_EXPIRY_BUFFER_MS);
|
||||
const hash = hashCreateOrder({
|
||||
chainId: this.chainId,
|
||||
accountIndex: this.accountIndex,
|
||||
apiKeyIndex: slot.index,
|
||||
nonce: params.nonce,
|
||||
expiredAt,
|
||||
marketIndex: params.marketIndex,
|
||||
clientOrderIndex: params.clientOrderIndex,
|
||||
baseAmount: params.baseAmount,
|
||||
price: params.price,
|
||||
isAsk: params.isAsk,
|
||||
orderType: params.orderType,
|
||||
timeInForce: params.timeInForce,
|
||||
reduceOnly: params.reduceOnly,
|
||||
triggerPrice: params.triggerPrice,
|
||||
orderExpiry: params.orderExpiry,
|
||||
});
|
||||
|
||||
const signature = slot.key.signHashedMessage(hash);
|
||||
const signatureBytes = signatureToBytes(signature);
|
||||
const txInfo = JSON.stringify({
|
||||
AccountIndex: toSafeNumber(this.accountIndex),
|
||||
ApiKeyIndex: slot.index,
|
||||
OrderInfo: {
|
||||
MarketIndex: params.marketIndex,
|
||||
ClientOrderIndex: toSafeNumber(params.clientOrderIndex),
|
||||
BaseAmount: toSafeNumber(params.baseAmount),
|
||||
Price: safeNumberToUint32(params.price),
|
||||
IsAsk: params.isAsk,
|
||||
Type: params.orderType,
|
||||
TimeInForce: params.timeInForce,
|
||||
ReduceOnly: params.reduceOnly,
|
||||
TriggerPrice: safeNumberToUint32(params.triggerPrice),
|
||||
OrderExpiry: toSafeNumber(params.orderExpiry),
|
||||
},
|
||||
ExpiredAt: toSafeNumber(expiredAt),
|
||||
Nonce: toSafeNumber(params.nonce),
|
||||
Sig: BASE64_ENCODE(signatureBytes),
|
||||
});
|
||||
|
||||
return {
|
||||
txType: LIGHTER_TX_TYPE.CREATE_ORDER,
|
||||
txInfo,
|
||||
txHash: bytesToHex(hash.toBytes()),
|
||||
signature: BASE64_ENCODE(signatureBytes),
|
||||
};
|
||||
}
|
||||
|
||||
signCancelOrder(params: CancelOrderSignParams): SignedTxPayload {
|
||||
const slot = this.resolveKey(params.apiKeyIndex);
|
||||
const expiredAt = params.expiredAt ?? BigInt(Date.now() + DEFAULT_TRANSACTION_EXPIRY_BUFFER_MS);
|
||||
const hash = hashCancelOrder({
|
||||
chainId: this.chainId,
|
||||
accountIndex: this.accountIndex,
|
||||
apiKeyIndex: slot.index,
|
||||
nonce: params.nonce,
|
||||
expiredAt,
|
||||
marketIndex: params.marketIndex,
|
||||
orderIndex: params.orderIndex,
|
||||
});
|
||||
const signature = slot.key.signHashedMessage(hash);
|
||||
const signatureBytes = signatureToBytes(signature);
|
||||
const txInfo = JSON.stringify({
|
||||
AccountIndex: toSafeNumber(this.accountIndex),
|
||||
ApiKeyIndex: slot.index,
|
||||
MarketIndex: params.marketIndex,
|
||||
Index: toSafeNumber(params.orderIndex),
|
||||
ExpiredAt: toSafeNumber(expiredAt),
|
||||
Nonce: toSafeNumber(params.nonce),
|
||||
Sig: BASE64_ENCODE(signatureBytes),
|
||||
});
|
||||
return {
|
||||
txType: LIGHTER_TX_TYPE.CANCEL_ORDER,
|
||||
txInfo,
|
||||
txHash: bytesToHex(hash.toBytes()),
|
||||
signature: BASE64_ENCODE(signatureBytes),
|
||||
};
|
||||
}
|
||||
|
||||
signCancelAll(params: CancelAllSignParams): SignedTxPayload {
|
||||
const slot = this.resolveKey(params.apiKeyIndex);
|
||||
const expiredAt = params.expiredAt ?? BigInt(Date.now() + DEFAULT_TRANSACTION_EXPIRY_BUFFER_MS);
|
||||
const hash = hashCancelAll({
|
||||
chainId: this.chainId,
|
||||
accountIndex: this.accountIndex,
|
||||
apiKeyIndex: slot.index,
|
||||
nonce: params.nonce,
|
||||
expiredAt,
|
||||
timeInForce: params.timeInForce,
|
||||
time: params.scheduledTime,
|
||||
});
|
||||
const signature = slot.key.signHashedMessage(hash);
|
||||
const signatureBytes = signatureToBytes(signature);
|
||||
const txInfo = JSON.stringify({
|
||||
AccountIndex: toSafeNumber(this.accountIndex),
|
||||
ApiKeyIndex: slot.index,
|
||||
TimeInForce: params.timeInForce,
|
||||
Time: toSafeNumber(params.scheduledTime),
|
||||
ExpiredAt: toSafeNumber(expiredAt),
|
||||
Nonce: toSafeNumber(params.nonce),
|
||||
Sig: BASE64_ENCODE(signatureBytes),
|
||||
});
|
||||
return {
|
||||
txType: LIGHTER_TX_TYPE.CANCEL_ALL_ORDERS,
|
||||
txInfo,
|
||||
txHash: bytesToHex(hash.toBytes()),
|
||||
signature: BASE64_ENCODE(signatureBytes),
|
||||
};
|
||||
}
|
||||
|
||||
createAuthToken(deadlineMs: number, apiKeyIndex?: number): string {
|
||||
if (!Number.isFinite(deadlineMs) || deadlineMs <= Date.now()) {
|
||||
throw new Error("Auth token deadline must be in the future");
|
||||
}
|
||||
if (deadlineMs - Date.now() > AUTH_MAX_WINDOW_MS) {
|
||||
throw new Error("Auth token deadline must be within 7 hours");
|
||||
}
|
||||
const slot = this.resolveKey(apiKeyIndex);
|
||||
const deadlineSeconds = Math.floor(deadlineMs / 1000);
|
||||
const message = `${deadlineSeconds}:${toSafeNumber(this.accountIndex)}:${slot.index}`;
|
||||
const msgBytes = Buffer.from(message, "utf8");
|
||||
const preimage = arrayFromCanonicalLittleEndianBytes(msgBytes);
|
||||
const hashed = hashToQuinticExtension(preimage);
|
||||
const signature = slot.key.signHashedMessage(hashed);
|
||||
const signatureHex = bytesToHex(signatureToBytes(signature));
|
||||
return `${message}:${signatureHex}`;
|
||||
}
|
||||
}
|
||||
|
||||
interface CreateOrderHashInput {
|
||||
chainId: number;
|
||||
accountIndex: bigint;
|
||||
apiKeyIndex: number;
|
||||
nonce: bigint;
|
||||
expiredAt: bigint;
|
||||
marketIndex: number;
|
||||
clientOrderIndex: bigint;
|
||||
baseAmount: bigint;
|
||||
price: number;
|
||||
isAsk: number;
|
||||
orderType: number;
|
||||
timeInForce: number;
|
||||
reduceOnly: number;
|
||||
triggerPrice: number;
|
||||
orderExpiry: bigint;
|
||||
}
|
||||
|
||||
function hashCreateOrder(input: CreateOrderHashInput): Fp5 {
|
||||
const elements = [
|
||||
Fp.fromUint32(input.chainId >>> 0),
|
||||
Fp.fromUint32(LIGHTER_TX_TYPE.CREATE_ORDER),
|
||||
fpFromInt64(input.nonce),
|
||||
fpFromInt64(input.expiredAt),
|
||||
fpFromInt64(input.accountIndex),
|
||||
fpFromUint32(input.apiKeyIndex),
|
||||
fpFromUint32(input.marketIndex),
|
||||
fpFromInt64(input.clientOrderIndex),
|
||||
fpFromInt64(input.baseAmount),
|
||||
fpFromUint32(input.price),
|
||||
fpFromUint32(input.isAsk),
|
||||
fpFromUint32(input.orderType),
|
||||
fpFromUint32(input.timeInForce),
|
||||
fpFromUint32(input.reduceOnly),
|
||||
fpFromUint32(input.triggerPrice),
|
||||
fpFromInt64(input.orderExpiry),
|
||||
];
|
||||
return hashToQuinticExtension(elements);
|
||||
}
|
||||
|
||||
interface CancelOrderHashInput {
|
||||
chainId: number;
|
||||
accountIndex: bigint;
|
||||
apiKeyIndex: number;
|
||||
nonce: bigint;
|
||||
expiredAt: bigint;
|
||||
marketIndex: number;
|
||||
orderIndex: bigint;
|
||||
}
|
||||
|
||||
function hashCancelOrder(input: CancelOrderHashInput): Fp5 {
|
||||
const elements = [
|
||||
Fp.fromUint32(input.chainId >>> 0),
|
||||
Fp.fromUint32(LIGHTER_TX_TYPE.CANCEL_ORDER),
|
||||
fpFromInt64(input.nonce),
|
||||
fpFromInt64(input.expiredAt),
|
||||
fpFromInt64(input.accountIndex),
|
||||
fpFromUint32(input.apiKeyIndex),
|
||||
fpFromUint32(input.marketIndex),
|
||||
fpFromInt64(input.orderIndex),
|
||||
];
|
||||
return hashToQuinticExtension(elements);
|
||||
}
|
||||
|
||||
interface CancelAllHashInput {
|
||||
chainId: number;
|
||||
accountIndex: bigint;
|
||||
apiKeyIndex: number;
|
||||
nonce: bigint;
|
||||
expiredAt: bigint;
|
||||
timeInForce: number;
|
||||
time: bigint;
|
||||
}
|
||||
|
||||
function hashCancelAll(input: CancelAllHashInput): Fp5 {
|
||||
const elements = [
|
||||
Fp.fromUint32(input.chainId >>> 0),
|
||||
Fp.fromUint32(LIGHTER_TX_TYPE.CANCEL_ALL_ORDERS),
|
||||
fpFromInt64(input.nonce),
|
||||
fpFromInt64(input.expiredAt),
|
||||
fpFromInt64(input.accountIndex),
|
||||
fpFromUint32(input.apiKeyIndex),
|
||||
fpFromUint32(input.timeInForce),
|
||||
fpFromInt64(input.time),
|
||||
];
|
||||
return hashToQuinticExtension(elements);
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
export type LighterSide = "buy" | "sell" | "ask" | "bid" | string;
|
||||
export type LighterOrderType =
|
||||
| "limit"
|
||||
| "market"
|
||||
| "stop_loss"
|
||||
| "stop_loss_limit"
|
||||
| "take_profit"
|
||||
| "take_profit_limit"
|
||||
| string;
|
||||
|
||||
export interface LighterOrder {
|
||||
order_index: number;
|
||||
client_order_index: number;
|
||||
order_id?: string;
|
||||
client_order_id?: string;
|
||||
market_index: number;
|
||||
owner_account_index?: number;
|
||||
initial_base_amount: string;
|
||||
remaining_base_amount: string;
|
||||
filled_base_amount?: string;
|
||||
filled_quote_amount?: string;
|
||||
price: string;
|
||||
nonce?: number;
|
||||
is_ask?: boolean;
|
||||
side?: LighterSide;
|
||||
type?: LighterOrderType;
|
||||
time_in_force?: string;
|
||||
trigger_price?: string;
|
||||
reduce_only?: boolean;
|
||||
status?: string;
|
||||
trigger_status?: string;
|
||||
trigger_time?: number;
|
||||
updated_at?: number;
|
||||
created_at?: number;
|
||||
}
|
||||
|
||||
export interface LighterPosition {
|
||||
market_id: number;
|
||||
symbol: string;
|
||||
sign: number;
|
||||
position: string;
|
||||
avg_entry_price: string;
|
||||
position_value: string;
|
||||
unrealized_pnl: string;
|
||||
realized_pnl: string;
|
||||
liquidation_price?: string;
|
||||
initial_margin_fraction?: string;
|
||||
margin_mode?: number;
|
||||
allocated_margin?: string;
|
||||
}
|
||||
|
||||
export interface LighterAccountDetails {
|
||||
collateral: string;
|
||||
available_balance?: string;
|
||||
total_order_count?: number;
|
||||
positions?: LighterPosition[];
|
||||
status?: number;
|
||||
account_index: number;
|
||||
l1_address?: string;
|
||||
name?: string;
|
||||
description?: string;
|
||||
pending_order_count?: number;
|
||||
}
|
||||
|
||||
export interface LighterAuthToken {
|
||||
token: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export interface LighterOrderBookLevel {
|
||||
price: string;
|
||||
size: string;
|
||||
}
|
||||
|
||||
export interface LighterOrderBookSnapshot {
|
||||
market_id: number;
|
||||
symbol?: string;
|
||||
offset?: number;
|
||||
bids: LighterOrderBookLevel[];
|
||||
asks: LighterOrderBookLevel[];
|
||||
}
|
||||
|
||||
export interface LighterMarketStats {
|
||||
market_id: number;
|
||||
index_price: string;
|
||||
mark_price: string;
|
||||
open_interest: string;
|
||||
last_trade_price: string;
|
||||
symbol?: string;
|
||||
current_funding_rate?: string;
|
||||
funding_rate?: string;
|
||||
funding_timestamp?: number;
|
||||
daily_base_token_volume?: number;
|
||||
daily_quote_token_volume?: number;
|
||||
daily_price_low?: number;
|
||||
daily_price_high?: number;
|
||||
daily_price_change?: number;
|
||||
}
|
||||
|
||||
export interface LighterKline {
|
||||
start_timestamp: number;
|
||||
end_timestamp: number;
|
||||
open: string;
|
||||
high: string;
|
||||
low: string;
|
||||
close: string;
|
||||
base_token_volume: string;
|
||||
quote_token_volume: string;
|
||||
trades?: number;
|
||||
}
|
||||
|
||||
export interface LighterOrderBookMetadata {
|
||||
symbol: string;
|
||||
market_id: number;
|
||||
maker_fee: string;
|
||||
taker_fee: string;
|
||||
min_base_amount: string;
|
||||
min_quote_amount: string;
|
||||
supported_size_decimals: number;
|
||||
supported_price_decimals: number;
|
||||
supported_quote_decimals: number;
|
||||
status: "inactive" | "frozen" | "active" | string;
|
||||
}
|
||||
|
||||
export interface LighterAccountMarketUpdate {
|
||||
account: number;
|
||||
orders?: LighterOrder[];
|
||||
position?: LighterPosition;
|
||||
trades?: Array<Record<string, unknown>>;
|
||||
funding_history?: Array<Record<string, unknown>>;
|
||||
channel: string;
|
||||
}
|
||||
|
||||
export interface LighterClientOptions {
|
||||
baseUrl: string;
|
||||
accountIndex: number;
|
||||
apiKeyIndex: number;
|
||||
apiPrivateKey: string;
|
||||
maxApiKeyIndex?: number;
|
||||
orderMarketId?: number;
|
||||
symbol: string;
|
||||
signerLibraryPath?: string;
|
||||
signerOverrides?: Partial<LighterSignerBinding>;
|
||||
priceDecimals?: number;
|
||||
sizeDecimals?: number;
|
||||
authExpiryBufferMs?: number;
|
||||
}
|
||||
|
||||
export interface LighterSignerBinding {
|
||||
createClient(
|
||||
url: string,
|
||||
apiPrivateKey: string,
|
||||
chainId: number,
|
||||
apiKeyIndex: number,
|
||||
accountIndex: number
|
||||
): string | null;
|
||||
switchApiKey(apiKeyIndex: number): string | null;
|
||||
createAuthToken(deadlineSeconds: number): StrOrErr;
|
||||
signCreateOrder(params: {
|
||||
marketIndex: number;
|
||||
clientOrderIndex: number;
|
||||
baseAmount: bigint;
|
||||
price: bigint;
|
||||
isAsk: number;
|
||||
orderType: number;
|
||||
timeInForce: number;
|
||||
reduceOnly: number;
|
||||
triggerPrice: bigint;
|
||||
orderExpiry: bigint;
|
||||
nonce: bigint;
|
||||
}): StrOrErr;
|
||||
signCancelOrder(params: {
|
||||
marketIndex: number;
|
||||
orderIndex: bigint;
|
||||
nonce: bigint;
|
||||
}): StrOrErr;
|
||||
signCancelAllOrders(params: {
|
||||
timeInForce: number;
|
||||
time: bigint;
|
||||
nonce: bigint;
|
||||
}): StrOrErr;
|
||||
}
|
||||
|
||||
export interface StrOrErr {
|
||||
value: string | null;
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
export interface LighterNonceManager {
|
||||
init(force?: boolean): Promise<void>;
|
||||
next(): { apiKeyIndex: number; nonce: bigint };
|
||||
acknowledgeFailure(apiKeyIndex: number): void;
|
||||
refresh(apiKeyIndex: number): Promise<void>;
|
||||
}
|
||||
@@ -606,7 +606,7 @@ export class TrendEngine {
|
||||
await this.tryPlaceStopLoss(stopSide, roundDownToTick(stopPrice, this.config.priceTick), price);
|
||||
}
|
||||
|
||||
if (!currentTrailing) {
|
||||
if (!currentTrailing && this.exchange.supportsTrailingStops()) {
|
||||
await this.tryPlaceTrailingStop(
|
||||
stopSide,
|
||||
roundDownToTick(activationPrice, this.config.priceTick),
|
||||
@@ -824,6 +824,9 @@ export class TrendEngine {
|
||||
activationPrice: number,
|
||||
quantity: number
|
||||
): Promise<void> {
|
||||
if (!this.exchange.supportsTrailingStops()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await placeTrailingStopOrder(
|
||||
this.exchange,
|
||||
|
||||
@@ -48,6 +48,30 @@ export function MakerApp({ onExit }: MakerAppProps) {
|
||||
symbol: makerConfig.symbol,
|
||||
aster: { apiKey, apiSecret },
|
||||
});
|
||||
} else if (exchangeId === "lighter") {
|
||||
const accountIndexRaw = process.env.LIGHTER_ACCOUNT_INDEX;
|
||||
const apiPrivateKey = process.env.LIGHTER_API_PRIVATE_KEY;
|
||||
if (!accountIndexRaw || !apiPrivateKey) {
|
||||
setError(new Error("缺少 LIGHTER_ACCOUNT_INDEX 或 LIGHTER_API_PRIVATE_KEY 环境变量"));
|
||||
return;
|
||||
}
|
||||
adapter = createExchangeAdapter({
|
||||
exchange: exchangeId,
|
||||
symbol: makerConfig.symbol,
|
||||
lighter: {
|
||||
displaySymbol: makerConfig.symbol,
|
||||
accountIndex: parseInt(accountIndexRaw, 10),
|
||||
apiPrivateKey,
|
||||
apiKeyIndex: process.env.LIGHTER_API_KEY_INDEX ? Number(process.env.LIGHTER_API_KEY_INDEX) : 0,
|
||||
environment: process.env.LIGHTER_ENV,
|
||||
baseUrl: process.env.LIGHTER_BASE_URL,
|
||||
marketId: process.env.LIGHTER_MARKET_ID ? Number(process.env.LIGHTER_MARKET_ID) : undefined,
|
||||
marketSymbol: process.env.LIGHTER_SYMBOL,
|
||||
priceDecimals: process.env.LIGHTER_PRICE_DECIMALS ? Number(process.env.LIGHTER_PRICE_DECIMALS) : undefined,
|
||||
sizeDecimals: process.env.LIGHTER_SIZE_DECIMALS ? Number(process.env.LIGHTER_SIZE_DECIMALS) : undefined,
|
||||
l1Address: process.env.LIGHTER_L1_ADDRESS,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
adapter = createExchangeAdapter({
|
||||
exchange: exchangeId,
|
||||
|
||||
@@ -16,6 +16,8 @@ afterEach(() => {
|
||||
describe("exchange factory", () => {
|
||||
it("defaults to aster when no env is provided", () => {
|
||||
delete process.env.EXCHANGE;
|
||||
process.env.ASTER_API_KEY = "key";
|
||||
process.env.ASTER_API_SECRET = "secret";
|
||||
const adapter = createExchangeAdapter({ symbol: "BTCUSDT" });
|
||||
expect(adapter).toBeInstanceOf(AsterExchangeAdapter);
|
||||
expect(adapter.id).toBe("aster");
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { LighterSigner } from "../../src/exchanges/lighter/signer";
|
||||
import { LIGHTER_ORDER_TYPE, LIGHTER_TIME_IN_FORCE } from "../../src/exchanges/lighter/constants";
|
||||
|
||||
describe("LighterSigner", () => {
|
||||
it("produces deterministic create order signature", () => {
|
||||
const signer = new LighterSigner({
|
||||
accountIndex: 65,
|
||||
chainId: 300,
|
||||
apiKeys: {
|
||||
3: "0xed636277f3753b6c0275f7a28c2678a7f3a95655e09deaebec15179b50c5da7f903152e50f594f7b",
|
||||
},
|
||||
});
|
||||
|
||||
const signed = signer.signCreateOrder({
|
||||
marketIndex: 0,
|
||||
clientOrderIndex: 123n,
|
||||
baseAmount: 1000n,
|
||||
price: 170000,
|
||||
isAsk: 1,
|
||||
orderType: LIGHTER_ORDER_TYPE.MARKET,
|
||||
timeInForce: LIGHTER_TIME_IN_FORCE.IMMEDIATE_OR_CANCEL,
|
||||
reduceOnly: 0,
|
||||
triggerPrice: 0,
|
||||
orderExpiry: 0n,
|
||||
expiredAt: 1700000000000n,
|
||||
apiKeyIndex: 3,
|
||||
nonce: 42n,
|
||||
});
|
||||
|
||||
const payload = JSON.parse(signed.txInfo);
|
||||
expect(payload.AccountIndex).toBe(65);
|
||||
expect(payload.ApiKeyIndex).toBe(3);
|
||||
expect(payload.OrderInfo).toMatchObject({
|
||||
MarketIndex: 0,
|
||||
ClientOrderIndex: 123,
|
||||
BaseAmount: 1000,
|
||||
Price: 170000,
|
||||
IsAsk: 1,
|
||||
Type: LIGHTER_ORDER_TYPE.MARKET,
|
||||
TimeInForce: LIGHTER_TIME_IN_FORCE.IMMEDIATE_OR_CANCEL,
|
||||
ReduceOnly: 0,
|
||||
TriggerPrice: 0,
|
||||
OrderExpiry: 0,
|
||||
});
|
||||
expect(typeof payload.Sig).toBe("string");
|
||||
expect(payload.Sig.length).toBeGreaterThan(0);
|
||||
expect(signed.txHash).toBe("3ef41bc5fdb2e2146b5f5df046fb1ad801dc2aa5c47703665bfd3eb67a21e67048957f7187b12035");
|
||||
expect(typeof signed.signature).toBe("string");
|
||||
expect(signed.signature.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user