diff --git a/CHANGELOG.md b/CHANGELOG.md index ea625d54..f62d137a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,67 +1,81 @@ # Changelog +## 1.3.0 +IMPROVEMENT +[\#170](https://github.com/bnb-chain/go-sdk/pull/170) types: set the types to the origin package alias and remove trade client + +## 1.2.9 +IMPROVEMENT +[\#168](https://github.com/bnb-chain/go-sdk/pull/168) type: add more oracle claim type + +## 1.2.8 +FEATURE +[\#164](https://github.com/bnb-chain/go-sdk/pull/164) feat: impl bep159 txs cli and queries + +## 1.2.7 +* [\#160](https://github.com/bnb-chain/go-sdk/pull/160) [RPC] Support minimal 0.1 BNB staking ## 1.2.6 CHAIN UPGRADE -* [\#144](https://github.com/binance-chain/go-sdk/pull/144) [RPC] [API] Support for the transfer of token ownership, and change the minimum token symbol length +* [\#144](https://github.com/bnb-chain/go-sdk/pull/144) [RPC] [API] Support for the transfer of token ownership, and change the minimum token symbol length ## 1.2.5 IMPROVEMENT -* [\#142](https://github.com/binance-chain/go-sdk/pull/142) [RPC] [API] add contract info for a token if there is any +* [\#142](https://github.com/bnb-chain/go-sdk/pull/142) [RPC] [API] add contract info for a token if there is any ## 1.2.4 CHAIN UPGRADE -* [\#132](https://github.com/binance-chain/go-sdk/pull/132) [RPC] [API] enable side chain governance transaction -* [\#133](https://github.com/binance-chain/go-sdk/pull/133) [RPC] [API] enable side chain unbind transaction, and modify the structure of claimMsg -* [\#136](https://github.com/binance-chain/go-sdk/pull/136) [TX] [TOOL] add utils to parse Claim payload to human readable interface +* [\#132](https://github.com/bnb-chain/go-sdk/pull/132) [RPC] [API] enable side chain governance transaction +* [\#133](https://github.com/bnb-chain/go-sdk/pull/133) [RPC] [API] enable side chain unbind transaction, and modify the structure of claimMsg +* [\#136](https://github.com/bnb-chain/go-sdk/pull/136) [TX] [TOOL] add utils to parse Claim payload to human readable interface ## 1.2.3 CHAIN UPGRADE -* [\#110](https://github.com/binance-chain/go-sdk/pull/110) [RPC] [API] Add pending_match flag -* [\#130](https://github.com/binance-chain/go-sdk/pull/130) [RPC] [API] Support Mini Token +* [\#110](https://github.com/bnb-chain/go-sdk/pull/110) [RPC] [API] Add pending_match flag +* [\#130](https://github.com/bnb-chain/go-sdk/pull/130) [RPC] [API] Support Mini Token ## 1.2.2 -* [\#106](https://github.com/binance-chain/go-sdk/pull/106) [RPC] fix nil point error in getBalance rpc call -* [\#103](https://github.com/binance-chain/go-sdk/pull/103) [RPC] change the default timeout of RPC client as 5 seconds -* [\#102](https://github.com/binance-chain/go-sdk/pull/102) [FIX] Some typos only (managr/manger) +* [\#106](https://github.com/bnb-chain/go-sdk/pull/106) [RPC] fix nil point error in getBalance rpc call +* [\#103](https://github.com/bnb-chain/go-sdk/pull/103) [RPC] change the default timeout of RPC client as 5 seconds +* [\#102](https://github.com/bnb-chain/go-sdk/pull/102) [FIX] Some typos only (managr/manger) ## 1.2.1 -* [\#99](https://github.com/binance-chain/go-sdk/pull/99) [BUILD] upgrade version of btcd to avoid retag issue +* [\#99](https://github.com/bnb-chain/go-sdk/pull/99) [BUILD] upgrade version of btcd to avoid retag issue ## v1.2.0 -* [\#93](https://github.com/binance-chain/go-sdk/pull/93) [BREAKING] uprade to binance chain release 0.6.3 +* [\#93](https://github.com/bnb-chain/go-sdk/pull/93) [BREAKING] uprade to binance chain release 0.6.3 ## v1.1.3 -* [\#81](https://github.com/binance-chain/go-sdk/pull/81) [TX] support swap on a single chain +* [\#81](https://github.com/bnb-chain/go-sdk/pull/81) [TX] support swap on a single chain ## v1.1.2 -* [\#88](https://github.com/binance-chain/go-sdk/pull/88) [RPC] wrap error for abci query when abci code is not 0 +* [\#88](https://github.com/bnb-chain/go-sdk/pull/88) [RPC] wrap error for abci query when abci code is not 0 ## v1.1.1 IMPROVEMENT -* [\#87](https://github.com/binance-chain/go-sdk/pull/87) [RPC] distinguish not found error for get timelock rpc -* [\#84](https://github.com/binance-chain/go-sdk/pull/84) [RPC] change interface of get timelock +* [\#87](https://github.com/bnb-chain/go-sdk/pull/87) [RPC] distinguish not found error for get timelock rpc +* [\#84](https://github.com/bnb-chain/go-sdk/pull/84) [RPC] change interface of get timelock ## v1.1.0 IMPROVEMENT -* [\#82](https://github.com/binance-chain/go-sdk/pull/82) [RPC] refactor reconnection +* [\#82](https://github.com/bnb-chain/go-sdk/pull/82) [RPC] refactor reconnection ## v1.0.9 FEATURES -* [\#71](https://github.com/binance-chain/go-sdk/pull/71) [RPC] add timelock query support -* [\#73](https://github.com/binance-chain/go-sdk/pull/73) [RPC] add limit param to get depth api for RPC +* [\#71](https://github.com/bnb-chain/go-sdk/pull/71) [RPC] add timelock query support +* [\#73](https://github.com/bnb-chain/go-sdk/pull/73) [RPC] add limit param to get depth api for RPC ## v1.0.8 IMPROVEMENTS -* [\#53](https://github.com/binance-chain/go-sdk/pull/53) [SOURCE] change the default source into 0 -* [\#56](https://github.com/binance-chain/go-sdk/pull/56) [RPC] add reconnect strategy when timeout to receive response -* [\#61](https://github.com/binance-chain/go-sdk/pull/61) [KEY] support bip44 to derive many address from same seed phase +* [\#53](https://github.com/bnb-chain/go-sdk/pull/53) [SOURCE] change the default source into 0 +* [\#56](https://github.com/bnb-chain/go-sdk/pull/56) [RPC] add reconnect strategy when timeout to receive response +* [\#61](https://github.com/bnb-chain/go-sdk/pull/61) [KEY] support bip44 to derive many address from same seed phase FEATURES -* [\#66](https://github.com/binance-chain/go-sdk/pull/66) [API] support set account flag transaction -* [\#70](https://github.com/binance-chain/go-sdk/pull/70) [API] support atomic swap transactions +* [\#66](https://github.com/bnb-chain/go-sdk/pull/66) [API] support set account flag transaction +* [\#70](https://github.com/bnb-chain/go-sdk/pull/70) [API] support atomic swap transactions BREAKING -* [\#57](https://github.com/binance-chain/go-sdk/pull/57) [API] add query option to getTokens api +* [\#57](https://github.com/bnb-chain/go-sdk/pull/57) [API] add query option to getTokens api diff --git a/client/basic/basic.go b/client/basic/basic.go index 35db139f..4b77fbda 100644 --- a/client/basic/basic.go +++ b/client/basic/basic.go @@ -9,8 +9,8 @@ import ( "gopkg.in/resty.v1" - "github.com/binance-chain/go-sdk/types" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/types" + "github.com/bnb-chain/go-sdk/types/tx" "github.com/gorilla/websocket" ) @@ -34,7 +34,7 @@ type client struct { } func NewClient(baseUrl string, apiKey string) BasicClient { - return &client{baseUrl: baseUrl, apiUrl: fmt.Sprintf("%s://%s", types.DefaultApiSchema, baseUrl+types.DefaultAPIVersionPrefix),apiKey:apiKey} + return &client{baseUrl: baseUrl, apiUrl: fmt.Sprintf("%s://%s", types.DefaultApiSchema, baseUrl+types.DefaultAPIVersionPrefix), apiKey: apiKey} } func (c *client) Get(path string, qp map[string]string) ([]byte, int, error) { diff --git a/client/client.go b/client/client.go index 61ecd2a8..b4caa08d 100644 --- a/client/client.go +++ b/client/client.go @@ -3,18 +3,16 @@ package client import ( "gopkg.in/resty.v1" - "github.com/binance-chain/go-sdk/client/basic" - "github.com/binance-chain/go-sdk/client/query" - "github.com/binance-chain/go-sdk/client/transaction" - "github.com/binance-chain/go-sdk/client/websocket" - "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/keys" + "github.com/bnb-chain/go-sdk/client/basic" + "github.com/bnb-chain/go-sdk/client/query" + "github.com/bnb-chain/go-sdk/client/transaction" + "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/keys" ) // dexClient wrapper type dexClient struct { query.QueryClient - websocket.WSClient transaction.TransactionClient basic.BasicClient } @@ -23,7 +21,6 @@ type dexClient struct { type DexClient interface { basic.BasicClient query.QueryClient - websocket.WSClient transaction.TransactionClient } @@ -32,27 +29,25 @@ func init() { } func NewDexClientWithApiKey(baseUrl string, network types.ChainNetwork, keyManager keys.KeyManager, apiKey string) (DexClient, error) { - types.Network = network + types.SetNetwork(network) c := basic.NewClient(baseUrl+"/internal", apiKey) - w := websocket.NewClient(c) q := query.NewClient(c) n, err := q.GetNodeInfo() if err != nil { return nil, err } t := transaction.NewClient(n.NodeInfo.Network, keyManager, q, c) - return &dexClient{BasicClient: c, QueryClient: q, TransactionClient: t, WSClient: w}, nil + return &dexClient{BasicClient: c, QueryClient: q, TransactionClient: t}, nil } func NewDexClient(baseUrl string, network types.ChainNetwork, keyManager keys.KeyManager) (DexClient, error) { - types.Network = network + types.SetNetwork(network) c := basic.NewClient(baseUrl, "") - w := websocket.NewClient(c) q := query.NewClient(c) n, err := q.GetNodeInfo() if err != nil { return nil, err } t := transaction.NewClient(n.NodeInfo.Network, keyManager, q, c) - return &dexClient{BasicClient: c, QueryClient: q, TransactionClient: t, WSClient: w}, nil + return &dexClient{BasicClient: c, QueryClient: q, TransactionClient: t}, nil } diff --git a/client/query/get_account.go b/client/query/get_account.go index 31156a6d..9a1c18d3 100644 --- a/client/query/get_account.go +++ b/client/query/get_account.go @@ -4,7 +4,7 @@ import ( "encoding/json" "net/http" - "github.com/binance-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/common/types" ) // GetAccount returns list of trading pairs diff --git a/client/query/get_closed_orders.go b/client/query/get_closed_orders.go deleted file mode 100644 index d81074a4..00000000 --- a/client/query/get_closed_orders.go +++ /dev/null @@ -1,31 +0,0 @@ -package query - -import ( - "encoding/json" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -// GetClosedOrders returns array of open orders -func (c *client) GetClosedOrders(query *types.ClosedOrdersQuery) (*types.CloseOrders, error) { - err := query.Check() - if err != nil { - return nil, err - } - qp, err := common.QueryParamToMap(*query) - if err != nil { - return nil, err - } - resp, _, err := c.baseClient.Get("/orders/closed", qp) - if err != nil { - return nil, err - } - - var orders types.CloseOrders - if err := json.Unmarshal(resp, &orders); err != nil { - return nil, err - } - - return &orders, nil -} diff --git a/client/query/get_depth.go b/client/query/get_depth.go deleted file mode 100644 index 6dc94523..00000000 --- a/client/query/get_depth.go +++ /dev/null @@ -1,31 +0,0 @@ -package query - -import ( - "encoding/json" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -// GetDepth returns market depth records -func (c *client) GetDepth(query *types.DepthQuery) (*types.MarketDepth, error) { - err := query.Check() - if err != nil { - return nil, err - } - qp, err := common.QueryParamToMap(*query) - if err != nil { - return nil, err - } - resp, _, err := c.baseClient.Get("/depth", qp) - if err != nil { - return nil, err - } - - var MarketDepth types.MarketDepth - if err := json.Unmarshal(resp, &MarketDepth); err != nil { - return nil, err - } - - return &MarketDepth, nil -} diff --git a/client/query/get_kline.go b/client/query/get_kline.go deleted file mode 100644 index 2ae1de1b..00000000 --- a/client/query/get_kline.go +++ /dev/null @@ -1,60 +0,0 @@ -package query - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -// GetKlines returns transaction details -func (c *client) GetKlines(query *types.KlineQuery) ([]types.Kline, error) { - err := query.Check() - if err != nil { - return nil, err - } - qp, err := common.QueryParamToMap(*query) - if err != nil { - return nil, err - } - - resp, _, err := c.baseClient.Get("/klines", qp) - if err != nil { - return nil, err - } - - iklines := [][]interface{}{} - if err := json.Unmarshal(resp, &iklines); err != nil { - return nil, err - } - klines := make([]types.Kline, len(iklines)) - // Todo - for index, ikline := range iklines { - kl := types.Kline{} - imap := make(map[string]interface{}, 9) - if len(ikline) >= 9 { - imap["openTime"] = ikline[0] - imap["open"] = ikline[1] - imap["high"] = ikline[2] - imap["low"] = ikline[3] - imap["close"] = ikline[4] - imap["volume"] = ikline[5] - imap["closeTime"] = ikline[6] - imap["quoteAssetVolume"] = ikline[7] - imap["NumberOfTrades"] = ikline[8] - } else { - return nil, fmt.Errorf("Receive kline scheme is unexpected ") - } - bz, err := json.Marshal(imap) - if err != nil { - return nil, err - } - err = json.Unmarshal(bz, &kl) - if err != nil { - return nil, err - } - klines[index] = kl - } - return klines, nil -} diff --git a/client/query/get_markets.go b/client/query/get_markets.go deleted file mode 100644 index ec464138..00000000 --- a/client/query/get_markets.go +++ /dev/null @@ -1,30 +0,0 @@ -package query - -import ( - "encoding/json" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -// GetMarkets returns list of trading pairs -func (c *client) GetMarkets(query *types.MarketsQuery) ([]types.TradingPair, error) { - err := query.Check() - if err != nil { - return nil, err - } - qp, err := common.QueryParamToMap(*query) - if err != nil { - return nil, err - } - resp, _, err := c.baseClient.Get("/markets", qp) - if err != nil { - return nil, err - } - var listOfPairs []types.TradingPair - if err := json.Unmarshal(resp, &listOfPairs); err != nil { - return nil, err - } - - return listOfPairs, nil -} diff --git a/client/query/get_mini_closed_orders.go b/client/query/get_mini_closed_orders.go deleted file mode 100644 index 270780da..00000000 --- a/client/query/get_mini_closed_orders.go +++ /dev/null @@ -1,31 +0,0 @@ -package query - -import ( - "encoding/json" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -// GetMiniClosedOrders returns array of mini closed orders -func (c *client) GetMiniClosedOrders(query *types.ClosedOrdersQuery) (*types.CloseOrders, error) { - err := query.Check() - if err != nil { - return nil, err - } - qp, err := common.QueryParamToMap(*query) - if err != nil { - return nil, err - } - resp, _, err := c.baseClient.Get("/mini/orders/closed", qp) - if err != nil { - return nil, err - } - - var orders types.CloseOrders - if err := json.Unmarshal(resp, &orders); err != nil { - return nil, err - } - - return &orders, nil -} diff --git a/client/query/get_mini_kline.go b/client/query/get_mini_kline.go deleted file mode 100644 index b1f44e72..00000000 --- a/client/query/get_mini_kline.go +++ /dev/null @@ -1,60 +0,0 @@ -package query - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -// GetMiniKlines returns mini token klines -func (c *client) GetMiniKlines(query *types.KlineQuery) ([]types.Kline, error) { - err := query.Check() - if err != nil { - return nil, err - } - qp, err := common.QueryParamToMap(*query) - if err != nil { - return nil, err - } - - resp, _, err := c.baseClient.Get("/mini/klines", qp) - if err != nil { - return nil, err - } - - iklines := [][]interface{}{} - if err := json.Unmarshal(resp, &iklines); err != nil { - return nil, err - } - klines := make([]types.Kline, len(iklines)) - // Todo - for index, ikline := range iklines { - kl := types.Kline{} - imap := make(map[string]interface{}, 9) - if len(ikline) >= 9 { - imap["openTime"] = ikline[0] - imap["open"] = ikline[1] - imap["high"] = ikline[2] - imap["low"] = ikline[3] - imap["close"] = ikline[4] - imap["volume"] = ikline[5] - imap["closeTime"] = ikline[6] - imap["quoteAssetVolume"] = ikline[7] - imap["NumberOfTrades"] = ikline[8] - } else { - return nil, fmt.Errorf("Receive kline scheme is unexpected ") - } - bz, err := json.Marshal(imap) - if err != nil { - return nil, err - } - err = json.Unmarshal(bz, &kl) - if err != nil { - return nil, err - } - klines[index] = kl - } - return klines, nil -} diff --git a/client/query/get_mini_markets.go b/client/query/get_mini_markets.go deleted file mode 100644 index 4881f33f..00000000 --- a/client/query/get_mini_markets.go +++ /dev/null @@ -1,30 +0,0 @@ -package query - -import ( - "encoding/json" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -// GetMiniMarkets returns list of trading pairs -func (c *client) GetMiniMarkets(query *types.MarketsQuery) ([]types.TradingPair, error) { - err := query.Check() - if err != nil { - return nil, err - } - qp, err := common.QueryParamToMap(*query) - if err != nil { - return nil, err - } - resp, _, err := c.baseClient.Get("/mini/markets", qp) - if err != nil { - return nil, err - } - var listOfPairs []types.TradingPair - if err := json.Unmarshal(resp, &listOfPairs); err != nil { - return nil, err - } - - return listOfPairs, nil -} diff --git a/client/query/get_mini_order.go b/client/query/get_mini_order.go deleted file mode 100644 index bc66aa49..00000000 --- a/client/query/get_mini_order.go +++ /dev/null @@ -1,26 +0,0 @@ -package query - -import ( - "encoding/json" - "github.com/binance-chain/go-sdk/common/types" -) - -// GetMiniOrder returns transaction details -func (c *client) GetMiniOrder(orderID string) (*types.Order, error) { - if orderID == "" { - return nil, types.OrderIdMissingError - } - - qp := map[string]string{} - resp, _, err := c.baseClient.Get("/mini/orders/"+orderID, qp) - if err != nil { - return nil, err - } - - var order types.Order - if err := json.Unmarshal(resp, &order); err != nil { - return nil, err - } - - return &order, nil -} diff --git a/client/query/get_mini_orders_open.go b/client/query/get_mini_orders_open.go deleted file mode 100644 index d33a02bb..00000000 --- a/client/query/get_mini_orders_open.go +++ /dev/null @@ -1,32 +0,0 @@ -package query - -import ( - "encoding/json" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -// GetMiniOpenOrders returns array of mini open orders -func (c *client) GetMiniOpenOrders(query *types.OpenOrdersQuery) (*types.OpenOrders, error) { - err := query.Check() - if err != nil { - return nil, err - } - qp, err := common.QueryParamToMap(*query) - if err != nil { - return nil, err - } - - resp, _, err := c.baseClient.Get("/mini/orders/open", qp) - if err != nil { - return nil, err - } - - var openOrders types.OpenOrders - if err := json.Unmarshal(resp, &openOrders); err != nil { - return nil, err - } - - return &openOrders, nil -} diff --git a/client/query/get_mini_ticker24h.go b/client/query/get_mini_ticker24h.go deleted file mode 100644 index e2031288..00000000 --- a/client/query/get_mini_ticker24h.go +++ /dev/null @@ -1,28 +0,0 @@ -package query - -import ( - "encoding/json" - "github.com/binance-chain/go-sdk/common/types" - - "github.com/binance-chain/go-sdk/common" -) - -// GetMiniTicker24h returns mini token ticker 24h -func (c *client) GetMiniTicker24h(query *types.Ticker24hQuery) ([]types.Ticker24h, error) { - qp, err := common.QueryParamToMap(query) - if err != nil { - return nil, err - } - - resp, _, err := c.baseClient.Get("/mini/ticker/24hr", qp) - if err != nil { - return nil, err - } - - tickers := []types.Ticker24h{} - if err := json.Unmarshal(resp, &tickers); err != nil { - return nil, err - } - - return tickers, nil -} diff --git a/client/query/get_mini_tokens.go b/client/query/get_mini_tokens.go index 5fd1f330..37979b0e 100644 --- a/client/query/get_mini_tokens.go +++ b/client/query/get_mini_tokens.go @@ -3,8 +3,8 @@ package query import ( "encoding/json" - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/common" + "github.com/bnb-chain/go-sdk/common/types" ) // GetMiniTokens returns list of mini tokens diff --git a/client/query/get_mini_trades.go b/client/query/get_mini_trades.go deleted file mode 100644 index 6432a074..00000000 --- a/client/query/get_mini_trades.go +++ /dev/null @@ -1,32 +0,0 @@ -package query - -import ( - "encoding/json" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -// GetMiniTrades returns trade details -func (c *client) GetMiniTrades(query *types.TradesQuery) (*types.Trades, error) { - err := query.Check() - if err != nil { - return nil, err - } - qp, err := common.QueryParamToMap(*query) - if err != nil { - return nil, err - } - - resp, _, err := c.baseClient.Get("/mini/trades", qp) - if err != nil { - return nil, err - } - - var trades types.Trades - if err := json.Unmarshal(resp, &trades); err != nil { - return nil, err - } - - return &trades, nil -} diff --git a/client/query/get_node_info.go b/client/query/get_node_info.go index 371bc6a0..585be2ce 100644 --- a/client/query/get_node_info.go +++ b/client/query/get_node_info.go @@ -2,7 +2,8 @@ package query import ( "encoding/json" - "github.com/binance-chain/go-sdk/common/types" + + "github.com/bnb-chain/go-sdk/common/types" ) func (c *client) GetNodeInfo() (*types.ResultStatus, error) { diff --git a/client/query/get_order.go b/client/query/get_order.go deleted file mode 100644 index 2b38e4ae..00000000 --- a/client/query/get_order.go +++ /dev/null @@ -1,26 +0,0 @@ -package query - -import ( - "encoding/json" - "github.com/binance-chain/go-sdk/common/types" -) - -// GetOrder returns transaction details -func (c *client) GetOrder(orderID string) (*types.Order, error) { - if orderID == "" { - return nil, types.OrderIdMissingError - } - - qp := map[string]string{} - resp, _, err := c.baseClient.Get("/orders/"+orderID, qp) - if err != nil { - return nil, err - } - - var order types.Order - if err := json.Unmarshal(resp, &order); err != nil { - return nil, err - } - - return &order, nil -} diff --git a/client/query/get_orders_open.go b/client/query/get_orders_open.go deleted file mode 100644 index c88c9d47..00000000 --- a/client/query/get_orders_open.go +++ /dev/null @@ -1,32 +0,0 @@ -package query - -import ( - "encoding/json" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -// GetOpenOrders returns array of open orders -func (c *client) GetOpenOrders(query *types.OpenOrdersQuery) (*types.OpenOrders, error) { - err := query.Check() - if err != nil { - return nil, err - } - qp, err := common.QueryParamToMap(*query) - if err != nil { - return nil, err - } - - resp, _, err := c.baseClient.Get("/orders/open", qp) - if err != nil { - return nil, err - } - - var openOrders types.OpenOrders - if err := json.Unmarshal(resp, &openOrders); err != nil { - return nil, err - } - - return &openOrders, nil -} diff --git a/client/query/get_ticker24h.go b/client/query/get_ticker24h.go deleted file mode 100644 index d1a8b475..00000000 --- a/client/query/get_ticker24h.go +++ /dev/null @@ -1,28 +0,0 @@ -package query - -import ( - "encoding/json" - "github.com/binance-chain/go-sdk/common/types" - - "github.com/binance-chain/go-sdk/common" -) - -// GetTicker24h returns ticker 24h -func (c *client) GetTicker24h(query *types.Ticker24hQuery) ([]types.Ticker24h, error) { - qp, err := common.QueryParamToMap(query) - if err != nil { - return nil, err - } - - resp, _, err := c.baseClient.Get("/ticker/24hr", qp) - if err != nil { - return nil, err - } - - tickers := []types.Ticker24h{} - if err := json.Unmarshal(resp, &tickers); err != nil { - return nil, err - } - - return tickers, nil -} diff --git a/client/query/get_time.go b/client/query/get_time.go index 03b9e314..d2aed673 100644 --- a/client/query/get_time.go +++ b/client/query/get_time.go @@ -3,7 +3,7 @@ package query import ( "encoding/json" - "github.com/binance-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/common/types" ) // GetTime returns market depth records diff --git a/client/query/get_tokens.go b/client/query/get_tokens.go index 4ae6e708..154fce6a 100644 --- a/client/query/get_tokens.go +++ b/client/query/get_tokens.go @@ -3,8 +3,8 @@ package query import ( "encoding/json" - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/common" + "github.com/bnb-chain/go-sdk/common/types" ) // GetTokens returns list of tokens diff --git a/client/query/get_trades.go b/client/query/get_trades.go deleted file mode 100644 index 1ddd5ccb..00000000 --- a/client/query/get_trades.go +++ /dev/null @@ -1,32 +0,0 @@ -package query - -import ( - "encoding/json" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -// GetTrades returns transaction details -func (c *client) GetTrades(query *types.TradesQuery) (*types.Trades, error) { - err := query.Check() - if err != nil { - return nil, err - } - qp, err := common.QueryParamToMap(*query) - if err != nil { - return nil, err - } - - resp, _, err := c.baseClient.Get("/trades", qp) - if err != nil { - return nil, err - } - - var trades types.Trades - if err := json.Unmarshal(resp, &trades); err != nil { - return nil, err - } - - return &trades, nil -} diff --git a/client/query/query.go b/client/query/query.go index 4580e4ff..5195df60 100644 --- a/client/query/query.go +++ b/client/query/query.go @@ -1,31 +1,16 @@ package query import ( - "github.com/binance-chain/go-sdk/client/basic" - "github.com/binance-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/client/basic" + "github.com/bnb-chain/go-sdk/common/types" ) type QueryClient interface { - GetClosedOrders(query *types.ClosedOrdersQuery) (*types.CloseOrders, error) - GetDepth(query *types.DepthQuery) (*types.MarketDepth, error) - GetKlines(query *types.KlineQuery) ([]types.Kline, error) - GetMarkets(query *types.MarketsQuery) ([]types.TradingPair, error) - GetOrder(orderID string) (*types.Order, error) - GetOpenOrders(query *types.OpenOrdersQuery) (*types.OpenOrders, error) - GetTicker24h(query *types.Ticker24hQuery) ([]types.Ticker24h, error) - GetTrades(query *types.TradesQuery) (*types.Trades, error) GetAccount(string) (*types.BalanceAccount, error) GetTime() (*types.Time, error) GetTokens(query *types.TokensQuery) ([]types.Token, error) GetNodeInfo() (*types.ResultStatus, error) GetMiniTokens(query *types.TokensQuery) ([]types.MiniToken, error) - GetMiniMarkets(query *types.MarketsQuery) ([]types.TradingPair, error) - GetMiniOpenOrders(query *types.OpenOrdersQuery) (*types.OpenOrders, error) - GetMiniClosedOrders(query *types.ClosedOrdersQuery) (*types.CloseOrders, error) - GetMiniOrder(orderID string) (*types.Order, error) - GetMiniKlines(query *types.KlineQuery) ([]types.Kline, error) - GetMiniTicker24h(query *types.Ticker24hQuery) ([]types.Ticker24h, error) - GetMiniTrades(query *types.TradesQuery) (*types.Trades, error) } type client struct { diff --git a/client/rpc/basic_client.go b/client/rpc/basic_client.go index c9dfed29..ed026826 100644 --- a/client/rpc/basic_client.go +++ b/client/rpc/basic_client.go @@ -8,12 +8,12 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/rpc/client" ctypes "github.com/tendermint/tendermint/rpc/core/types" - "github.com/tendermint/tendermint/rpc/lib/client" + rpcclient "github.com/tendermint/tendermint/rpc/lib/client" "github.com/tendermint/tendermint/types" - ntypes "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/keys" - "github.com/binance-chain/go-sdk/types/tx" + ntypes "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/keys" + "github.com/bnb-chain/go-sdk/types/tx" ) var DefaultTimeout = 5 * time.Second @@ -59,7 +59,7 @@ type EventsClient interface { } func NewRPCClient(nodeURI string, network ntypes.ChainNetwork) *HTTP { - ntypes.Network = network + ntypes.SetNetwork(network) return NewHTTP(nodeURI, "/websocket") } diff --git a/client/rpc/dex_client.go b/client/rpc/dex_client.go index 770e9b51..fb3a3554 100644 --- a/client/rpc/dex_client.go +++ b/client/rpc/dex_client.go @@ -7,13 +7,14 @@ import ( "fmt" "time" - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" - sdk "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/keys" - gtypes "github.com/binance-chain/go-sdk/types" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/common" + "github.com/bnb-chain/go-sdk/common/types" + sdk "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/keys" + gtypes "github.com/bnb-chain/go-sdk/types" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" + cTypes "github.com/cosmos/cosmos-sdk/types" core_types "github.com/tendermint/tendermint/rpc/core/types" ) @@ -48,9 +49,6 @@ type DexClient interface { GetBalances(addr types.AccAddress) ([]types.TokenBalance, error) GetBalance(addr types.AccAddress, symbol string) (*types.TokenBalance, error) GetFee() ([]types.FeeParam, error) - GetOpenOrders(addr types.AccAddress, pair string) ([]types.OpenOrder, error) - GetTradingPairs(offset int, limit int) ([]types.TradingPair, error) - GetDepth(tradePair string, level int) (*types.OrderBook, error) GetProposals(status types.ProposalStatus, numLatest int64) ([]types.Proposal, error) GetSideChainProposals(status types.ProposalStatus, numLatest int64, sideChainId string) ([]types.Proposal, error) GetSideChainProposal(proposalId int64, sideChainId string) (types.Proposal, error) @@ -64,11 +62,12 @@ type DexClient interface { ListAllMiniTokens(offset int, limit int) ([]types.MiniToken, error) GetMiniTokenInfo(symbol string) (*types.MiniToken, error) - GetMiniTradingPairs(offset int, limit int) ([]types.TradingPair, error) SetKeyManager(k keys.KeyManager) SendToken(transfers []msg.Transfer, syncType SyncType, options ...tx.Option) (*core_types.ResultBroadcastTx, error) + // CreateOrder deprecated CreateOrder(baseAssetSymbol, quoteAssetSymbol string, op int8, price, quantity int64, syncType SyncType, options ...tx.Option) (*core_types.ResultBroadcastTx, error) + // CancelOrder deprecated CancelOrder(baseAssetSymbol, quoteAssetSymbol, refId string, syncType SyncType, options ...tx.Option) (*core_types.ResultBroadcastTx, error) HTLT(recipient types.AccAddress, recipientOtherChain, senderOtherChain string, randomNumberHash []byte, timestamp int64, amount types.Coins, expectedIncome string, heightSpan int64, crossChain bool, syncType SyncType, options ...tx.Option) (*core_types.ResultBroadcastTx, error) @@ -273,73 +272,6 @@ func (c *HTTP) GetFee() ([]types.FeeParam, error) { return fees, err } -func (c *HTTP) GetOpenOrders(addr types.AccAddress, pair string) ([]types.OpenOrder, error) { - if err := ValidatePair(pair); err != nil { - return nil, err - } - rawOrders, err := c.ABCIQuery(fmt.Sprintf("dex/openorders/%s/%s", pair, addr), nil) - if err != nil { - return nil, err - } - if !rawOrders.Response.IsOK() { - return nil, fmt.Errorf(rawOrders.Response.Log) - } - bz := rawOrders.Response.GetValue() - openOrders := make([]types.OpenOrder, 0) - if bz == nil { - return openOrders, nil - } - if err := c.cdc.UnmarshalBinaryLengthPrefixed(bz, &openOrders); err != nil { - return nil, err - } else { - return openOrders, nil - } -} - -func (c *HTTP) GetTradingPairs(offset int, limit int) ([]types.TradingPair, error) { - if err := ValidateLimit(limit); err != nil { - return nil, err - } - if err := ValidateOffset(offset); err != nil { - return nil, err - } - rawTradePairs, err := c.ABCIQuery(fmt.Sprintf("dex/pairs/%d/%d", offset, limit), nil) - if err != nil { - return nil, err - } - if !rawTradePairs.Response.IsOK() { - return nil, fmt.Errorf(rawTradePairs.Response.Log) - } - pairs := make([]types.TradingPair, 0) - if rawTradePairs.Response.GetValue() == nil { - return pairs, nil - } - err = c.cdc.UnmarshalBinaryLengthPrefixed(rawTradePairs.Response.GetValue(), &pairs) - return pairs, err -} - -func (c *HTTP) GetDepth(tradePair string, level int) (*types.OrderBook, error) { - if err := ValidatePair(tradePair); err != nil { - return nil, err - } - if err := ValidateDepthLevel(level); err != nil { - return nil, err - } - rawDepth, err := c.ABCIQuery(fmt.Sprintf("dex/orderbook/%s/%d", tradePair, level), nil) - if err != nil { - return nil, err - } - if !rawDepth.Response.IsOK() { - return nil, fmt.Errorf(rawDepth.Response.Log) - } - var ob types.OrderBook - err = c.cdc.UnmarshalBinaryLengthPrefixed(rawDepth.Response.GetValue(), &ob) - if err != nil { - return nil, err - } - return &ob, nil -} - func (c *HTTP) GetTimelocks(addr types.AccAddress) ([]types.TimeLockRecord, error) { params := types.QueryTimeLocksParams{ @@ -515,7 +447,7 @@ func (c *HTTP) GetSwapByID(swapID types.SwapBytes) (types.AtomicSwap, error) { return types.AtomicSwap{}, err } - resp, err := c.ABCIQuery(fmt.Sprintf("custom/%s/%s", msg.AtomicSwapRoute, "swapid"), bz) + resp, err := c.ABCIQuery(fmt.Sprintf("custom/%s/%s", "atomicSwap", "swapid"), bz) if err != nil { return types.AtomicSwap{}, err } @@ -550,7 +482,7 @@ func (c *HTTP) GetSwapByCreator(creatorAddr string, offset int64, limit int64) ( return nil, err } - resp, err := c.ABCIQuery(fmt.Sprintf("custom/%s/%s", msg.AtomicSwapRoute, "swapcreator"), bz) + resp, err := c.ABCIQuery(fmt.Sprintf("custom/%s/%s", "atomicSwap", "swapcreator"), bz) if err != nil { return nil, err } @@ -584,7 +516,7 @@ func (c *HTTP) GetSwapByRecipient(recipientAddr string, offset int64, limit int6 return nil, err } - resp, err := c.ABCIQuery(fmt.Sprintf("custom/%s/%s", msg.AtomicSwapRoute, "swaprecipient"), bz) + resp, err := c.ABCIQuery(fmt.Sprintf("custom/%s/%s", "atomicSwap", "swaprecipient"), bz) if err != nil { return nil, err } @@ -641,28 +573,6 @@ func (c *HTTP) GetMiniTokenInfo(symbol string) (*types.MiniToken, error) { return token, err } -func (c *HTTP) GetMiniTradingPairs(offset int, limit int) ([]types.TradingPair, error) { - if err := ValidateLimit(limit); err != nil { - return nil, err - } - if err := ValidateOffset(offset); err != nil { - return nil, err - } - rawTradePairs, err := c.ABCIQuery(fmt.Sprintf("dex-mini/pairs/%d/%d", offset, limit), nil) - if err != nil { - return nil, err - } - if !rawTradePairs.Response.IsOK() { - return nil, fmt.Errorf(rawTradePairs.Response.Log) - } - pairs := make([]types.TradingPair, 0) - if rawTradePairs.Response.GetValue() == nil { - return pairs, nil - } - err = c.cdc.UnmarshalBinaryLengthPrefixed(rawTradePairs.Response.GetValue(), &pairs) - return pairs, err -} - func (c *HTTP) SendToken(transfers []msg.Transfer, syncType SyncType, options ...tx.Option) (*core_types.ResultBroadcastTx, error) { if c.key == nil { return nil, KeyMissingError @@ -678,6 +588,7 @@ func (c *HTTP) SendToken(transfers []msg.Transfer, syncType SyncType, options .. } +// CreateOrder deprecated func (c *HTTP) CreateOrder(baseAssetSymbol, quoteAssetSymbol string, op int8, price, quantity int64, syncType SyncType, options ...tx.Option) (*core_types.ResultBroadcastTx, error) { if c.key == nil { return nil, KeyMissingError @@ -726,8 +637,8 @@ func (c *HTTP) DepositHTLT(recipient types.AccAddress, swapID []byte, amount typ fromAddr := c.key.GetAddr() depositHTLTMsg := msg.NewDepositHTLTMsg( fromAddr, - swapID, amount, + swapID, ) return c.Broadcast(depositHTLTMsg, syncType, options...) } @@ -868,6 +779,7 @@ func (c *HTTP) Vote(proposalID int64, option msg.VoteOption, syncType SyncType, return c.Broadcast(msg, syncType, options...) } +// CancelOrder deprecated func (c *HTTP) CancelOrder(baseAssetSymbol, quoteAssetSymbol, refId string, syncType SyncType, options ...tx.Option) (*core_types.ResultBroadcastTx, error) { if c.key == nil { return nil, KeyMissingError @@ -961,7 +873,7 @@ func (c *HTTP) Claim(chainId sdk.IbcChainID, sequence uint64, payload []byte, sy fromAddr := c.key.GetAddr() - claimMsg := msg.NewClaimMsg(chainId, sequence, payload, fromAddr) + claimMsg := msg.NewClaimMsg(cTypes.ChainID(chainId), sequence, payload, fromAddr) return c.Broadcast(claimMsg, syncType, options...) } @@ -987,7 +899,7 @@ func (c *HTTP) GetOracleRelayers() (relayers []msg.OracleRelayer, err error) { } func (c *HTTP) GetProphecy(chainId sdk.IbcChainID, sequence int64) (*msg.Prophecy, error) { - key := []byte(msg.GetClaimId(chainId, msg.OracleChannelId, sequence)) + key := []byte(msg.GetClaimId(cTypes.ChainID(chainId), msg.OracleChannelId, uint64(sequence))) bz, err := c.QueryStore(key, OracleStoreName) if err != nil { return nil, err @@ -1065,7 +977,7 @@ func (c *HTTP) sign(m msg.Msg, options ...tx.Option) ([]byte, error) { // special logic for createOrder, to save account query if orderMsg, ok := m.(msg.CreateOrderMsg); ok { - orderMsg.ID = msg.GenerateOrderID(signMsg.Sequence+1, c.key.GetAddr()) + orderMsg.Id = msg.GenerateOrderID(signMsg.Sequence+1, c.key.GetAddr()) signMsg.Msgs[0] = orderMsg } diff --git a/client/rpc/mock/abci.go b/client/rpc/mock/abci.go index 30ad1738..c7f41368 100644 --- a/client/rpc/mock/abci.go +++ b/client/rpc/mock/abci.go @@ -1,7 +1,7 @@ package mock import ( - "github.com/binance-chain/go-sdk/client/rpc" + "github.com/bnb-chain/go-sdk/client/rpc" abci "github.com/tendermint/tendermint/abci/types" cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/proxy" diff --git a/client/rpc/mock/client.go b/client/rpc/mock/client.go index e94a3239..54ab64e0 100644 --- a/client/rpc/mock/client.go +++ b/client/rpc/mock/client.go @@ -1,9 +1,10 @@ package mock import ( - "github.com/binance-chain/go-sdk/client/rpc" "reflect" + "github.com/bnb-chain/go-sdk/client/rpc" + cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/rpc/client" diff --git a/client/rpc/ops_client.go b/client/rpc/ops_client.go index 7c204461..ee2ee580 100644 --- a/client/rpc/ops_client.go +++ b/client/rpc/ops_client.go @@ -1,6 +1,6 @@ package rpc -import "github.com/binance-chain/go-sdk/common/types" +import "github.com/bnb-chain/go-sdk/common/types" type OpsClient interface { IsActive() bool diff --git a/client/rpc/staking_client.go b/client/rpc/staking_client.go index e54f31f7..d55b2c42 100644 --- a/client/rpc/staking_client.go +++ b/client/rpc/staking_client.go @@ -9,10 +9,11 @@ import ( "strings" "time" - "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" "github.com/tendermint/go-amino" + "github.com/tendermint/tendermint/crypto" coretypes "github.com/tendermint/tendermint/rpc/core/types" ) @@ -28,8 +29,8 @@ var ( ) type StakingClient interface { - CreateValidatorOpen(delegation types.Coin, description msg.Description, commission types.CommissionMsg, sideConsAddr []byte, sideFeeAddr []byte, syncType SyncType, options ...tx.Option) (*coretypes.ResultBroadcastTx, error) - EditValidator(description msg.Description, commissionRate *types.Dec, sideFeeAddr []byte, syncType SyncType, options ...tx.Option) (*coretypes.ResultBroadcastTx, error) + CreateValidatorOpen(delegation types.Coin, description msg.Description, commission types.CommissionMsg, pubkey string, syncType SyncType, options ...tx.Option) (*coretypes.ResultBroadcastTx, error) + EditValidator(description msg.Description, commissionRate *types.Dec, pubkey string, syncType SyncType, options ...tx.Option) (*coretypes.ResultBroadcastTx, error) Delegate(valAddr types.ValAddress, delegation types.Coin, syncType SyncType, options ...tx.Option) (*coretypes.ResultBroadcastTx, error) Redelegate(valSrcAddr types.ValAddress, valDstAddr types.ValAddress, amount types.Coin, syncType SyncType, options ...tx.Option) (*coretypes.ResultBroadcastTx, error) Undelegate(valAddr types.ValAddress, amount types.Coin, syncType SyncType, options ...tx.Option) (*coretypes.ResultBroadcastTx, error) @@ -49,7 +50,7 @@ type StakingClient interface { GetAllValidatorsCount(jailInvolved bool) (int, error) CreateSideChainValidator(delegation types.Coin, description msg.Description, commission types.CommissionMsg, sideChainId string, sideConsAddr []byte, sideFeeAddr []byte, syncType SyncType, options ...tx.Option) (*coretypes.ResultBroadcastTx, error) - EditSideChainValidator(sideChainId string, description msg.Description, commissionRate *types.Dec, sideFeeAddr []byte, syncType SyncType, options ...tx.Option) (*coretypes.ResultBroadcastTx, error) + EditSideChainValidator(sideChainId string, description msg.Description, commissionRate *types.Dec, sideFeeAddr []byte, sideConsAddr []byte, syncType SyncType, options ...tx.Option) (*coretypes.ResultBroadcastTx, error) SideChainDelegate(sideChainId string, valAddr types.ValAddress, delegation types.Coin, syncType SyncType, options ...tx.Option) (*coretypes.ResultBroadcastTx, error) SideChainRedelegate(sideChainId string, valSrcAddr types.ValAddress, valDstAddr types.ValAddress, amount types.Coin, syncType SyncType, options ...tx.Option) (*coretypes.ResultBroadcastTx, error) SideChainUnbond(sideChainId string, valAddr types.ValAddress, amount types.Coin, syncType SyncType, options ...tx.Option) (*coretypes.ResultBroadcastTx, error) @@ -72,7 +73,7 @@ type StakingClient interface { type bechValidator struct { FeeAddr types.AccAddress `json:"fee_addr"` // the bech32 address for fee collection OperatorAddr types.ValAddress `json:"operator_address"` // the bech32 address of the validator's operator - ConsPubKey string `json:"consensus_pubkey,omitempty"` // the bech32 consensus public key of the validator + ConsPubKey crypto.PubKey `json:"consensus_pubkey,omitempty"` // the bech32 consensus public key of the validator Jailed bool `json:"jailed"` // has the validator been jailed from bonded status? Status types.BondStatus `json:"status"` // validator status (bonded/unbonding/unbonded) @@ -221,7 +222,7 @@ func (c *HTTP) SideChainUnjail(sideChainId string, valAddr types.ValAddress, syn return c.Broadcast(m, syncType, options...) } -//Query a validator +// Query a validator func (c *HTTP) QuerySideChainValidator(sideChainId string, valAddr types.ValAddress) (*types.Validator, error) { storePrefix, err := c.getSideChainStorePrefixKey(sideChainId) @@ -322,7 +323,7 @@ func (c *HTTP) QuerySideChainTopValidators(sideChainId string, top int) ([]types return validators, nil } -//Query a delegation based on address and validator address +// Query a delegation based on address and validator address func (c *HTTP) QuerySideChainDelegation(sideChainId string, delAddr types.AccAddress, valAddr types.ValAddress) (*types.DelegationResponse, error) { params := types.QueryBondsParams{ BaseParams: types.NewBaseParams(sideChainId), @@ -350,7 +351,7 @@ func (c *HTTP) QuerySideChainDelegation(sideChainId string, delAddr types.AccAdd return &delResponse, nil } -//Query all delegations made from one delegator +// Query all delegations made from one delegator func (c *HTTP) QuerySideChainDelegations(sideChainId string, delAddr types.AccAddress) ([]types.DelegationResponse, error) { params := types.QueryDelegatorParams{ BaseParams: types.NewBaseParams(sideChainId), @@ -379,7 +380,7 @@ func (c *HTTP) QuerySideChainDelegations(sideChainId string, delAddr types.AccAd return delegationResponses, nil } -//Query a redelegation record based on delegator and a source and destination validator address +// Query a redelegation record based on delegator and a source and destination validator address func (c *HTTP) QuerySideChainRedelegation(sideChainId string, delAddr types.AccAddress, valSrcAddr types.ValAddress, valDstAddr types.ValAddress) (*types.Redelegation, error) { storePrefix, err := c.getSideChainStorePrefixKey(sideChainId) @@ -406,7 +407,7 @@ func (c *HTTP) QuerySideChainRedelegation(sideChainId string, delAddr types.AccA return &result, nil } -//Query all redelegations records for one delegator +// Query all redelegations records for one delegator func (c *HTTP) QuerySideChainRedelegations(sideChainId string, delAddr types.AccAddress) ([]types.Redelegation, error) { storePrefix, err := c.getSideChainStorePrefixKey(sideChainId) if err != nil { @@ -437,7 +438,7 @@ func (c *HTTP) QuerySideChainRedelegations(sideChainId string, delAddr types.Acc return redels, nil } -//Query an unbonding-delegation record based on delegator and validator address +// Query an unbonding-delegation record based on delegator and validator address func (c *HTTP) QuerySideChainUnbondingDelegation(sideChainId string, valAddr types.ValAddress, delAddr types.AccAddress) (*types.UnbondingDelegation, error) { storePrefix, err := c.getSideChainStorePrefixKey(sideChainId) if err != nil { @@ -464,7 +465,7 @@ func (c *HTTP) QuerySideChainUnbondingDelegation(sideChainId string, valAddr typ return &ubd, nil } -//Query all unbonding-delegations records for one delegator +// Query all unbonding-delegations records for one delegator func (c *HTTP) QuerySideChainUnbondingDelegations(sideChainId string, delAddr types.AccAddress) ([]types.UnbondingDelegation, error) { storePrefix, err := c.getSideChainStorePrefixKey(sideChainId) if err != nil { @@ -895,7 +896,7 @@ func (c *HTTP) QueryRedelegation(delAddr types.AccAddress, valSrcAddr types.ValA return &red, err } -//Query all redelegations records for one delegator +// Query all redelegations records for one delegator func (c *HTTP) QueryRedelegations(delAddr types.AccAddress) ([]types.Redelegation, error) { params := types.QueryDelegatorParams{ DelegatorAddr: delAddr, @@ -913,7 +914,7 @@ func (c *HTTP) QueryRedelegations(delAddr types.AccAddress) ([]types.Redelegatio return reds, err } -//Query an unbonding-delegation record based on delegator and validator address +// Query an unbonding-delegation record based on delegator and validator address func (c *HTTP) QueryUnbondingDelegation(valAddr types.ValAddress, delAddr types.AccAddress) (*types.UnbondingDelegation, error) { params := types.QueryBondsParams{ DelegatorAddr: delAddr, @@ -932,7 +933,7 @@ func (c *HTTP) QueryUnbondingDelegation(valAddr types.ValAddress, delAddr types. return &ub, err } -//Query all unbonding-delegations records for one delegator +// Query all unbonding-delegations records for one delegator func (c *HTTP) QueryUnbondingDelegations(delAddr types.AccAddress) ([]types.UnbondingDelegation, error) { params := types.QueryDelegatorParams{ DelegatorAddr: delAddr, diff --git a/client/rpc/types.go b/client/rpc/types.go index 4a54ad7c..9f31f81b 100644 --- a/client/rpc/types.go +++ b/client/rpc/types.go @@ -1,7 +1,7 @@ package rpc import ( - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/types/tx" "github.com/tendermint/tendermint/abci/types" cmn "github.com/tendermint/tendermint/libs/common" abci "github.com/tendermint/tendermint/types" diff --git a/client/rpc/ws_client.go b/client/rpc/ws_client.go index d070287d..44b5ecdd 100644 --- a/client/rpc/ws_client.go +++ b/client/rpc/ws_client.go @@ -20,11 +20,11 @@ import ( "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/rpc/client" ctypes "github.com/tendermint/tendermint/rpc/core/types" - "github.com/tendermint/tendermint/rpc/lib/types" + rpctypes "github.com/tendermint/tendermint/rpc/lib/types" "github.com/tendermint/tendermint/types" - "github.com/binance-chain/go-sdk/common/uuid" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/common/uuid" + "github.com/bnb-chain/go-sdk/types/tx" ) const ( diff --git a/client/transaction/burn_token.go b/client/transaction/burn_token.go index 566778d1..fb5174b0 100644 --- a/client/transaction/burn_token.go +++ b/client/transaction/burn_token.go @@ -3,8 +3,8 @@ package transaction import ( "fmt" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type BurnTokenResult struct { diff --git a/client/transaction/cancel_order.go b/client/transaction/cancel_order.go index 830916bb..0ce71da5 100644 --- a/client/transaction/cancel_order.go +++ b/client/transaction/cancel_order.go @@ -3,15 +3,16 @@ package transaction import ( "fmt" - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/common" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type CancelOrderResult struct { tx.TxCommitResult } +// CancelOrder deprecated func (c *client) CancelOrder(baseAssetSymbol, quoteAssetSymbol, refId string, sync bool, options ...Option) (*CancelOrderResult, error) { if baseAssetSymbol == "" || quoteAssetSymbol == "" { return nil, fmt.Errorf("BaseAssetSymbol or QuoteAssetSymbol is missing. ") diff --git a/client/transaction/create_order.go b/client/transaction/create_order.go index 7b7153df..06666d02 100644 --- a/client/transaction/create_order.go +++ b/client/transaction/create_order.go @@ -4,9 +4,9 @@ import ( "encoding/json" "fmt" - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/common" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type CreateOrderResult struct { @@ -14,6 +14,7 @@ type CreateOrderResult struct { OrderId string } +// CreateOrder deprecated func (c *client) CreateOrder(baseAssetSymbol, quoteAssetSymbol string, op int8, price, quantity int64, sync bool, options ...Option) (*CreateOrderResult, error) { if baseAssetSymbol == "" || quoteAssetSymbol == "" { return nil, fmt.Errorf("BaseAssetSymbol or QuoteAssetSymbol is missing. ") diff --git a/client/transaction/deposit_proposal.go b/client/transaction/deposit_proposal.go index 348d0f7b..888bb1db 100644 --- a/client/transaction/deposit_proposal.go +++ b/client/transaction/deposit_proposal.go @@ -1,10 +1,10 @@ package transaction import ( - ctypes "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/types" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + ctypes "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/types" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type DepositProposalResult struct { diff --git a/client/transaction/freeze_token.go b/client/transaction/freeze_token.go index cae96da8..a93e25d9 100644 --- a/client/transaction/freeze_token.go +++ b/client/transaction/freeze_token.go @@ -3,8 +3,8 @@ package transaction import ( "fmt" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type FreezeTokenResult struct { diff --git a/client/transaction/htlc.go b/client/transaction/htlc.go index c9bc322c..f9cd5a66 100644 --- a/client/transaction/htlc.go +++ b/client/transaction/htlc.go @@ -1,9 +1,9 @@ package transaction import ( - "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type HTLTResult struct { @@ -41,8 +41,8 @@ func (c *client) DepositHTLT(swapID []byte, amount types.Coins, fromAddr := c.keyManager.GetAddr() depositHTLTMsg := msg.NewDepositHTLTMsg( fromAddr, - swapID, amount, + swapID, ) commit, err := c.broadcastMsg(depositHTLTMsg, sync, options...) if err != nil { diff --git a/client/transaction/issue_mini_token.go b/client/transaction/issue_mini_token.go index 769cdee6..73fe853c 100644 --- a/client/transaction/issue_mini_token.go +++ b/client/transaction/issue_mini_token.go @@ -4,8 +4,8 @@ import ( "encoding/json" "fmt" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type IssueMiniTokenResult struct { diff --git a/client/transaction/issue_tiny_token.go b/client/transaction/issue_tiny_token.go index be192075..81ebd0b7 100644 --- a/client/transaction/issue_tiny_token.go +++ b/client/transaction/issue_tiny_token.go @@ -4,8 +4,8 @@ import ( "encoding/json" "fmt" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type IssueTinyTokenResult struct { diff --git a/client/transaction/issue_token.go b/client/transaction/issue_token.go index 47c47ac9..72b8e0b6 100644 --- a/client/transaction/issue_token.go +++ b/client/transaction/issue_token.go @@ -4,8 +4,8 @@ import ( "encoding/json" "fmt" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type IssueTokenResult struct { diff --git a/client/transaction/list_mini_pair.go b/client/transaction/list_mini_pair.go index 4fc7c502..3aa31343 100644 --- a/client/transaction/list_mini_pair.go +++ b/client/transaction/list_mini_pair.go @@ -1,8 +1,8 @@ package transaction import ( - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type ListMiniPairResult struct { diff --git a/client/transaction/list_pair.go b/client/transaction/list_pair.go index 8bd36e8a..f73d4e0d 100644 --- a/client/transaction/list_pair.go +++ b/client/transaction/list_pair.go @@ -1,8 +1,8 @@ package transaction import ( - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type ListPairResult struct { diff --git a/client/transaction/mint_token.go b/client/transaction/mint_token.go index 3c19e23d..f0a47a18 100644 --- a/client/transaction/mint_token.go +++ b/client/transaction/mint_token.go @@ -3,8 +3,8 @@ package transaction import ( "fmt" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type MintTokenResult struct { diff --git a/client/transaction/send_token.go b/client/transaction/send_token.go index bcb39ef7..1051fa6a 100644 --- a/client/transaction/send_token.go +++ b/client/transaction/send_token.go @@ -1,9 +1,9 @@ package transaction import ( - "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type SendTokenResult struct { diff --git a/client/transaction/set_account_flags.go b/client/transaction/set_account_flags.go index 1321618f..c23286cf 100644 --- a/client/transaction/set_account_flags.go +++ b/client/transaction/set_account_flags.go @@ -2,9 +2,10 @@ package transaction import ( "fmt" - "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + + "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type SetAccountFlagsResult struct { diff --git a/client/transaction/set_uri.go b/client/transaction/set_uri.go index c0791d1a..9aa4fe23 100644 --- a/client/transaction/set_uri.go +++ b/client/transaction/set_uri.go @@ -1,8 +1,8 @@ package transaction import ( - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type SetUriResult struct { diff --git a/client/transaction/submit_proposal.go b/client/transaction/submit_proposal.go index 57b2f347..6eeda832 100644 --- a/client/transaction/submit_proposal.go +++ b/client/transaction/submit_proposal.go @@ -5,10 +5,10 @@ import ( "strconv" "time" - ctypes "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/types" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + ctypes "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/types" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type SubmitProposalResult struct { diff --git a/client/transaction/time_lock.go b/client/transaction/time_lock.go index 493acb46..511a4bc9 100644 --- a/client/transaction/time_lock.go +++ b/client/transaction/time_lock.go @@ -3,9 +3,9 @@ package transaction import ( "strconv" - "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type TimeLockResult struct { @@ -44,18 +44,18 @@ func (c *client) TimeUnLock(id int64, sync bool, options ...Option) (*TimeUnLock if err != nil { return nil, err } - commit, err := c.broadcastMsg(unlockMsg, sync, options...) - if err != nil { - return nil, err + commit, err2 := c.broadcastMsg(unlockMsg, sync, options...) + if err2 != nil { + return nil, err2 } var lockId int64 if commit.Ok && sync { - lockId, err = strconv.ParseInt(string(commit.Data), 10, 64) - if err != nil { - return nil, err + lockId, err2 = strconv.ParseInt(string(commit.Data), 10, 64) + if err2 != nil { + return nil, err2 } } - return &TimeUnLockResult{*commit, lockId}, err + return &TimeUnLockResult{*commit, lockId}, nil } type TimeReLockResult struct { @@ -71,16 +71,16 @@ func (c *client) TimeReLock(id int64, description string, amount types.Coins, lo if err != nil { return nil, err } - commit, err := c.broadcastMsg(relockMsg, sync, options...) - if err != nil { - return nil, err + commit, err2 := c.broadcastMsg(relockMsg, sync, options...) + if err2 != nil { + return nil, err2 } var lockId int64 if commit.Ok && sync { - lockId, err = strconv.ParseInt(string(commit.Data), 10, 64) - if err != nil { - return nil, err + lockId, err2 = strconv.ParseInt(string(commit.Data), 10, 64) + if err2 != nil { + return nil, err2 } } - return &TimeReLockResult{*commit, lockId}, err + return &TimeReLockResult{*commit, lockId}, nil } diff --git a/client/transaction/transaction.go b/client/transaction/transaction.go index 64dcf14d..bcc89af2 100644 --- a/client/transaction/transaction.go +++ b/client/transaction/transaction.go @@ -5,12 +5,12 @@ import ( "fmt" "time" - "github.com/binance-chain/go-sdk/client/basic" - "github.com/binance-chain/go-sdk/client/query" - "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/keys" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/client/basic" + "github.com/bnb-chain/go-sdk/client/query" + "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/keys" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type Option = tx.Option @@ -22,7 +22,9 @@ var ( ) type TransactionClient interface { + // CreateOrder deprecated CreateOrder(baseAssetSymbol, quoteAssetSymbol string, op int8, price, quantity int64, sync bool, options ...Option) (*CreateOrderResult, error) + // CancelOrder deprecated CancelOrder(baseAssetSymbol, quoteAssetSymbol, refId string, sync bool, options ...Option) (*CancelOrderResult, error) BurnToken(symbol string, amount int64, sync bool, options ...Option) (*BurnTokenResult, error) ListPair(proposalId int64, baseAssetSymbol string, quoteAssetSymbol string, initPrice int64, sync bool, options ...Option) (*ListPairResult, error) @@ -97,7 +99,7 @@ func (c *client) broadcastMsg(m msg.Msg, sync bool, options ...Option) (*tx.TxCo // special logic for createOrder, to save account query if orderMsg, ok := m.(msg.CreateOrderMsg); ok { - orderMsg.ID = msg.GenerateOrderID(signMsg.Sequence+1, c.keyManager.GetAddr()) + orderMsg.Id = msg.GenerateOrderID(signMsg.Sequence+1, c.keyManager.GetAddr()) signMsg.Msgs[0] = orderMsg } diff --git a/client/transaction/transfer_token_ownership.go b/client/transaction/transfer_token_ownership.go index e0ce16a6..bc0c1813 100644 --- a/client/transaction/transfer_token_ownership.go +++ b/client/transaction/transfer_token_ownership.go @@ -1,9 +1,9 @@ package transaction import ( - "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type TransferTokenOwnershipResult struct { diff --git a/client/transaction/unfreeze_token.go b/client/transaction/unfreeze_token.go index 4e193aa4..80eec84f 100644 --- a/client/transaction/unfreeze_token.go +++ b/client/transaction/unfreeze_token.go @@ -3,8 +3,8 @@ package transaction import ( "fmt" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type UnfreezeTokenResult struct { diff --git a/client/transaction/vote_proposal.go b/client/transaction/vote_proposal.go index 26fa40c0..c089437c 100644 --- a/client/transaction/vote_proposal.go +++ b/client/transaction/vote_proposal.go @@ -1,8 +1,8 @@ package transaction import ( - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" ) type VoteProposalResult struct { diff --git a/client/websocket/accounts.go b/client/websocket/accounts.go deleted file mode 100644 index 424b35f1..00000000 --- a/client/websocket/accounts.go +++ /dev/null @@ -1,43 +0,0 @@ -package websocket - -import ( - "encoding/json" - - "github.com/binance-chain/go-sdk/common/types" -) - -// -type AccountEvent struct { - EventType string `json:"e"` // "e": "outboundAccountInfo" - EventTime int64 `json:"E"` // "E": 1499405658658, - Balances []EventAssetBalance `json:"B"` -} - -// EventAssetBalance record structure as send to the user -type EventAssetBalance struct { - Asset string `json:"a"` // "a": "LTC", // Asset - Free types.Fixed8 `json:"f"` // "f": "17366.18538083", // Free amount - Frozen types.Fixed8 `json:"r"` // "r": "0.00000000" // Frozen amount - Locked types.Fixed8 `json:"l"` // "l": "0.00000000" // Locked amount -} - -func (c *client) SubscribeAccountEvent(userAddr string, quit chan struct{}, onReceive func(event *AccountEvent), onError func(err error), onClose func()) error { - msgs, err := c.baseClient.WsGet(userAddr, func(bz []byte) (interface{}, error) { - var event AccountEvent - err := json.Unmarshal(bz, &event) - // Todo: the ws will return order data also. Ignore error now - if err != nil { - return nil, nil - } - return &event, err - }, quit) - if err != nil { - return err - } - go c.SubscribeEvent(quit, msgs, func(event interface{}) { - if accountEvent, ok := event.(*AccountEvent); ok { - onReceive(accountEvent) - } - }, onError, onClose) - return nil -} diff --git a/client/websocket/blockheight.go b/client/websocket/blockheight.go deleted file mode 100644 index aa7360b9..00000000 --- a/client/websocket/blockheight.go +++ /dev/null @@ -1,24 +0,0 @@ -package websocket - -import "encoding/json" - -type BlockHeightEvent struct { - BlockHeight int64 `json:"h"` // "h": 1499405658658, -} - -func (c *client) SubscribeBlockHeightEvent(quit chan struct{}, onReceive func(event *BlockHeightEvent), onError func(err error), onClose func()) error { - msgs, err := c.baseClient.WsGet("$all@blockheight", func(bz []byte) (interface{}, error) { - var event BlockHeightEvent - err := json.Unmarshal(bz, &event) - return &event, err - }, quit) - if err != nil { - return err - } - go c.SubscribeEvent(quit, msgs, func(event interface{}) { - if blockHeightEvent, ok := event.(*BlockHeightEvent); ok { - onReceive(blockHeightEvent) - } - }, onError, onClose) - return nil -} diff --git a/client/websocket/kline.go b/client/websocket/kline.go deleted file mode 100644 index 3890c4df..00000000 --- a/client/websocket/kline.go +++ /dev/null @@ -1,72 +0,0 @@ -package websocket - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -type KlineInterval string - -const ( - OneMinuteInterval KlineInterval = "1m" - - FiveMinutesInterval KlineInterval = "5m" - FifteenMinuteInterval KlineInterval = "15m" - ThirtMinutesInterval KlineInterval = "30m" - OneHourInterval KlineInterval = "1h" - TwoHoursInterval KlineInterval = "2h" - FourHoursInterval KlineInterval = "4h" - SixHoursInterval KlineInterval = "6h" - EightHoursInterval KlineInterval = "8h" - TwelveHoursInterval KlineInterval = "12h" - OneDayInterval KlineInterval = "1d" - ThreeDaysInterval KlineInterval = "3d" - OneWeekInterval KlineInterval = "1w" - OneMonthInterval KlineInterval = "1M" -) - -type KlineEvent struct { - EventType string `json:"e"` // "e": "executionReport" - EventTime int64 `json:"E"` // "E": 1499405658658, - Symbol string `json:"s"` // "s": "ETH_BTC", - Kline KlineRecordEvent `json:"k"` -} - -// KlineRecordEvent record structure as received from the kafka messages stream -type KlineRecordEvent struct { - Timestamp int64 `json:"-"` - Symbol string `json:"s"` //"BNBBTC", // Symbol - OpenTime int64 `json:"t"` //123400000, // Kline start time - CloseTime int64 `json:"T"` //123460000, // Kline close time - Interval string `json:"i"` //"1m", // Interval - FirstTradeID string `json:"f"` //100, // First trade ID - LastTradeID string `json:"L"` //200, // Last trade ID - OpenPrice types.Fixed8 `json:"o"` //"0.0010", // Open price - ClosePrice types.Fixed8 `json:"c"` //"0.0020", // Close price - HighPrice types.Fixed8 `json:"h"` //"0.0025", // High price - LowPrice types.Fixed8 `json:"l"` //"0.0015", // Low price - Volume types.Double `json:"v"` //"1000", // Base asset volume - QuoteAssetVolume types.Double `json:"q"` //"1.0000", // Quote asset volume - NumberOfTrades int64 `json:"n"` //100, // Number of trades - Closed bool `json:"x"` //Is this kline closed? -} - -func (c *client) SubscribeKlineEvent(baseAssetSymbol, quoteAssetSymbol string, interval KlineInterval, quit chan struct{}, onReceive func(event *KlineEvent), onError func(err error), onClose func()) error { - msgs, err := c.baseClient.WsGet(fmt.Sprintf("%s@%s_%s", common.CombineSymbol(baseAssetSymbol, quoteAssetSymbol), "kline", interval), func(bz []byte) (interface{}, error) { - var event KlineEvent - err := json.Unmarshal(bz, &event) - return &event, err - }, quit) - if err != nil { - return err - } - go c.SubscribeEvent(quit, msgs, func(event interface{}) { - if klineEvent, ok := event.(*KlineEvent); ok { - onReceive(klineEvent) - } - }, onError, onClose) - return nil -} diff --git a/client/websocket/market.go b/client/websocket/market.go deleted file mode 100644 index 0a364c02..00000000 --- a/client/websocket/market.go +++ /dev/null @@ -1,58 +0,0 @@ -package websocket - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -type MarketDeltaEvent struct { - EventType string `json:"e"` // "e": "depthUpdate", - EventTime int64 `json:"E"` // "E": 123456789, - Symbol string `json:"s"` // "s": "ETH_BTC", - Bids [][]types.Fixed8 `json:"b"` // "b": [ [ "0.0024", "10" ] ] - Asks [][]types.Fixed8 `json:"a"` // "a": [ [ "0.0024", "10" ] ] -} - -func (c *client) SubscribeMarketDiffEvent(baseAssetSymbol, quoteAssetSymbol string, quit chan struct{}, onReceive func(event *MarketDeltaEvent), onError func(err error), onClose func()) error { - msgs, err := c.baseClient.WsGet(fmt.Sprintf("%s@%s", common.CombineSymbol(baseAssetSymbol, quoteAssetSymbol), "marketDiff"), func(bz []byte) (interface{}, error) { - var event MarketDeltaEvent - err := json.Unmarshal(bz, &event) - return &event, err - }, quit) - if err != nil { - return err - } - go c.SubscribeEvent(quit, msgs, func(event interface{}) { - if marketDeltaEvent, ok := event.(*MarketDeltaEvent); ok { - onReceive(marketDeltaEvent) - } - }, onError, onClose) - return nil -} - -type MarketDepthEvent struct { - LastUpdateID int64 `json:"lastUpdateId"` // "lastUpdateId": 160, - Symbol string `json:"symbol"` // "symbol": "BNB_BTC" - Bids [][]types.Fixed8 `json:"bids"` // "bids": [ [ "0.0024", "10" ] ] - Asks [][]types.Fixed8 `json:"asks"` // "asks": [ [ "0.0024", "10" ] ] -} - -func (c *client) SubscribeMarketDepthEvent(baseAssetSymbol, quoteAssetSymbol string, quit chan struct{}, onReceive func(event *MarketDepthEvent), onError func(err error), onClose func()) error { - msgs, err := c.baseClient.WsGet(fmt.Sprintf("%s@%s", common.CombineSymbol(baseAssetSymbol, quoteAssetSymbol), "marketDepth"), func(bz []byte) (interface{}, error) { - var event MarketDepthEvent - err := json.Unmarshal(bz, &event) - return &event, err - }, quit) - if err != nil { - return err - } - go c.SubscribeEvent(quit, msgs, func(event interface{}) { - if marketDepthEvent, ok := event.(*MarketDepthEvent); ok { - onReceive(marketDepthEvent) - } - }, onError, onClose) - return nil -} diff --git a/client/websocket/orders.go b/client/websocket/orders.go deleted file mode 100644 index e4e679fa..00000000 --- a/client/websocket/orders.go +++ /dev/null @@ -1,49 +0,0 @@ -package websocket - -import ( - "encoding/json" - - "github.com/binance-chain/go-sdk/common/types" -) - -type OrderEvent struct { - EventType string `json:"e"` // "e": "executionReport" - EventTime int64 `json:"E"` // "E": 1499405658658, - Symbol string `json:"s"` // "s": "ETH_BTC", - Side int8 `json:"S"` //"S": "BUY", - OrderType int8 `json:"o"` //"o": "LIMIT", always to `LIMIT`, `will be published` - TimeInForce int8 `json:"f"` //"f": "GTC", - OrderQty types.Fixed8 `json:"q"` //"q": "1.00000000", `will be published` - OrderPrice types.Fixed8 `json:"p"` //"p": "0.10264410", `will be published` - CurrentExecutionType string `json:"x"` //"x": "NEW", always `NEW` for now `will be published` - CurrentOrderStatus string `json:"X"` //"X": "Ack", "Canceled", "Expired", "IocNoFill", "PartialFill", "FullyFill", "FailedBlocking", "FailedMatching", "Unknown" - OrderID string `json:"i"` //"i": "917E1846D6B3C40B97465CCF52818471E2C1027C-466", - LastExecutedQty types.Fixed8 `json:"l"` // "l": "0.00000000", - LastExecutedPrice types.Fixed8 `json:"L"` // "L": "0.00000000", - CommulativeFilledQty types.Fixed8 `json:"z"` // "z": "0.00000000", - CommissionAmount string `json:"n"` // "n": "0", - TransactionTime int64 `json:"T"` //"T": 1499405658657, `this will be the BLockheight` - TradeID string `json:"t"` //"t": -1, `will be published` - OrderCreationTime int64 `json:"O"` //"O": 1499405658657, `will be published` -} - -func (c *client) SubscribeOrderEvent(userAddr string, quit chan struct{}, onReceive func(event []*OrderEvent), onError func(err error), onClose func()) error { - msgs, err := c.baseClient.WsGet(userAddr, func(bz []byte) (interface{}, error) { - events := make([]*OrderEvent, 0) - err := json.Unmarshal(bz, &events) - // Todo: the ws will return account data also. Ignore error now - if err != nil { - return nil, nil - } - return events, err - }, quit) - if err != nil { - return err - } - go c.SubscribeEvent(quit, msgs, func(event interface{}) { - if orderEvent, ok := event.([]*OrderEvent); ok { - onReceive(orderEvent) - } - }, onError, onClose) - return nil -} diff --git a/client/websocket/ticker.go b/client/websocket/ticker.go deleted file mode 100644 index 495c2bf8..00000000 --- a/client/websocket/ticker.go +++ /dev/null @@ -1,115 +0,0 @@ -package websocket - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -type TickerEvent struct { - EventType string `json:"e"` // "e": "24hrTicker", - EventTime int64 `json:"E"` // "E": 123456789, - Symbol string `json:"s"` // "s": "BNBBTC", // Symbol - PriceChange types.Fixed8 `json:"p"` // "p": "0.0015", // Price change - PriceChangePercent types.Fixed8 `json:"P"` // "P": "250.00", // Price change percent - WeightedAvgPrice types.Fixed8 `json:"w"` // "w": "0.0018", // Weighted average price - PrevClosePrice types.Fixed8 `json:"x"` // "x": "0.0009", // Previous day's close price - LastPrice types.Fixed8 `json:"c"` // "c": "0.0025", // Current day's close price - LastQuantity types.Fixed8 `json:"Q"` // "Q": "10", // Close trade's quantity - BidPrice types.Fixed8 `json:"b"` // "b": "0.0024", // Best bid price - BidQuantity types.Fixed8 `json:"B"` // "B": "10", // Best bid quantity - AskPrice types.Fixed8 `json:"a"` // "a": "0.0026", // Best ask price - AskQuantity types.Fixed8 `json:"A"` // "A": "100", // Best ask quantity - OpenPrice types.Fixed8 `json:"o"` // "o": "0.0010", // Open price - HighPrice types.Fixed8 `json:"h"` // "h": "0.0025", // High price - LowPrice types.Fixed8 `json:"l"` // "l": "0.0010", // Low price - Volume types.Double `json:"v"` // "v": "10000", // Total traded base asset volume - QuoteVolume types.Double `json:"q"` // "q": "18", // Total traded quote asset volume - OpenTime int64 `json:"O"` // "O": 0, // Statistics open time - CloseTime int64 `json:"C"` // "C": 86400000, // Statistics close time - FirstID string `json:"F"` // "F": 0, // First trade ID - LastID string `json:"L"` // "L": 18150, // Last trade Id - Count int64 `json:"n"` // "n": 18151 // Total number of trades -} - -func (c *client) SubscribeTickerEvent(baseAssetSymbol, quoteAssetSymbol string, quit chan struct{}, onReceive func(event *TickerEvent), onError func(err error), onClose func()) error { - msgs, err := c.baseClient.WsGet(fmt.Sprintf("%s@%s", common.CombineSymbol(baseAssetSymbol, quoteAssetSymbol), "ticker"), func(bz []byte) (interface{}, error) { - event := TickerEvent{} - err := json.Unmarshal(bz, &event) - return &event, err - }, quit) - if err != nil { - return err - } - go c.SubscribeEvent(quit, msgs, func(event interface{}) { - if tickerEvent, ok := event.(*TickerEvent); ok { - onReceive(tickerEvent) - } - }, onError, onClose) - return nil -} - -func (c *client) SubscribeAllTickerEvent(quit chan struct{}, onReceiveHandler func(event []*TickerEvent), onError func(err error), onClose func()) error { - msgs, err := c.baseClient.WsGet(fmt.Sprintf("%s@%s", "$all", "allTickers"), func(bz []byte) (interface{}, error) { - events := make([]*TickerEvent, 0) - err := json.Unmarshal(bz, &events) - return events, err - }, quit) - if err != nil { - return err - } - go c.SubscribeEvent(quit, msgs, func(event interface{}) { - if tickersEvent, ok := event.([]*TickerEvent); ok { - onReceiveHandler(tickersEvent) - } - }, onError, onClose) - return nil -} - -type MiniTickerEvent struct { - EventType string `json:"e"` // "e": "24hrMiniTicker", - EventTime int64 `json:"E"` // "E": 123456789, - Symbol string `json:"s"` // "s": "BNBBTC", // Symbol - LastPrice types.Fixed8 `json:"c"` // "c": "0.0025", // Current day's close price - OpenPrice types.Fixed8 `json:"o"` // "o": "0.0010", // Open price - HighPrice types.Fixed8 `json:"h"` // "h": "0.0025", // High price - LowPrice types.Fixed8 `json:"l"` // "l": "0.0010", // Low price - Volume types.Double `json:"v"` // "v": "10000", // Total traded base asset volume - QuoteVolume types.Double `json:"q"` // "q": "18", // Total traded quote asset volume -} - -func (c *client) SubscribeMiniTickerEvent(baseAssetSymbol, quoteAssetSymbol string, quit chan struct{}, onReceive func(event *MiniTickerEvent), onError func(err error), onClose func()) error { - msgs, err := c.baseClient.WsGet(fmt.Sprintf("%s@%s", common.CombineSymbol(baseAssetSymbol, quoteAssetSymbol), "miniTicker"), func(bz []byte) (interface{}, error) { - var event MiniTickerEvent - err := json.Unmarshal(bz, &event) - return &event, err - }, quit) - if err != nil { - return err - } - go c.SubscribeEvent(quit, msgs, func(event interface{}) { - if miniTickerEvent, ok := event.(*MiniTickerEvent); ok { - onReceive(miniTickerEvent) - } - }, onError, onClose) - return nil -} - -func (c *client) SubscribeAllMiniTickersEvent(quit chan struct{}, onReceive func(events []*MiniTickerEvent), onError func(err error), onClose func()) error { - msgs, err := c.baseClient.WsGet(fmt.Sprintf("%s@%s", "$all", "allMiniTickers"), func(bz []byte) (interface{}, error) { - events := make([]*MiniTickerEvent, 0) - err := json.Unmarshal(bz, &events) - return events, err - }, quit) - if err != nil { - return err - } - go c.SubscribeEvent(quit, msgs, func(event interface{}) { - if miniTickers, ok := event.([]*MiniTickerEvent); ok { - onReceive(miniTickers) - } - }, onError, onClose) - return nil -} diff --git a/client/websocket/trades.go b/client/websocket/trades.go deleted file mode 100644 index 41f28cab..00000000 --- a/client/websocket/trades.go +++ /dev/null @@ -1,40 +0,0 @@ -package websocket - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/types" -) - -type TradeEvent struct { - EventType string `json:"e"` // "e": "trade", - EventTime int64 `json:"E"` // "E": 123456789, - Symbol string `json:"s"` // "s": "ETH_BTC", - TradeID string `json:"t"` // "t": 4293153, - Price types.Fixed8 `json:"p"` // "p": "0.001", - Qty types.Fixed8 `json:"q"` // "q": "88", - BuyerOrderID string `json:"b"` // "f": "50", - SellerOrderID string `json:"a"` // "q": "100", - TradeTime int64 `json:"T"` // "p": 123456785 - SellerAddress string `json:"sa"` // "sa": 0x4092678e4e78230f46a1534c0fbc8fa39780892b - BuyerAddress string `json:"ba"` // "ba": 0x4092778e4e78230f46a1534c0fbc8fa39780892c -} - -func (c *client) SubscribeTradeEvent(baseAssetSymbol, quoteAssetSymbol string, quit chan struct{}, onReceive func(events []*TradeEvent), onError func(err error), onClose func()) error { - msgs, err := c.baseClient.WsGet(fmt.Sprintf("%s@%s", common.CombineSymbol(baseAssetSymbol, quoteAssetSymbol), "trades"), func(bz []byte) (interface{}, error) { - events := make([]*TradeEvent, 0) - err := json.Unmarshal(bz, &events) - return events, err - }, quit) - if err != nil { - return err - } - go c.SubscribeEvent(quit, msgs, func(event interface{}) { - if tradeEvents, ok := event.([]*TradeEvent); ok { - onReceive(tradeEvents) - } - }, onError, onClose) - return nil -} diff --git a/client/websocket/websocket.go b/client/websocket/websocket.go deleted file mode 100644 index a039fc70..00000000 --- a/client/websocket/websocket.go +++ /dev/null @@ -1,53 +0,0 @@ -package websocket - -import ( - "github.com/binance-chain/go-sdk/client/basic" -) - -type WSClient interface { - SubscribeAccountEvent(userAddr string, quit chan struct{}, onReceive func(event *AccountEvent), onError func(err error), onClose func()) error - SubscribeBlockHeightEvent(quit chan struct{}, onReceive func(event *BlockHeightEvent), onError func(err error), onClose func()) error - SubscribeKlineEvent(baseAssetSymbol, quoteAssetSymbol string, interval KlineInterval, quit chan struct{}, onReceive func(event *KlineEvent), onError func(err error), onClose func()) error - SubscribeMarketDiffEvent(baseAssetSymbol, quoteAssetSymbol string, quit chan struct{}, onReceive func(event *MarketDeltaEvent), onError func(err error), onClose func()) error - SubscribeMarketDepthEvent(baseAssetSymbol, quoteAssetSymbol string, quit chan struct{}, onReceive func(event *MarketDepthEvent), onError func(err error), onClose func()) error - SubscribeOrderEvent(userAddr string, quit chan struct{}, onReceive func(event []*OrderEvent), onError func(err error), onClose func()) error - SubscribeTickerEvent(baseAssetSymbol, quoteAssetSymbol string, quit chan struct{}, onReceive func(event *TickerEvent), onError func(err error), onClose func()) error - SubscribeAllTickerEvent(quit chan struct{}, onReceive func(event []*TickerEvent), onError func(err error), onClose func()) error - SubscribeMiniTickerEvent(baseAssetSymbol, quoteAssetSymbol string, quit chan struct{}, onReceive func(event *MiniTickerEvent), onError func(err error), onClose func()) error - SubscribeAllMiniTickersEvent(quit chan struct{}, onReceive func(events []*MiniTickerEvent), onError func(err error), onClose func()) error - SubscribeTradeEvent(baseAssetSymbol, quoteAssetSymbol string, quit chan struct{}, onReceive func(events []*TradeEvent), onError func(err error), onClose func()) error -} - -type client struct { - baseClient basic.BasicClient -} - -func NewClient(c basic.BasicClient) WSClient { - return &client{baseClient: c} -} - -func (c *client) SubscribeEvent(quit chan struct{}, msgs <-chan interface{}, onReceive func(event interface{}), onError func(err error), onClose func()) { - for { - select { - case <-quit: - return - case m, ok := <-msgs: - if !ok { - if onClose != nil { - onClose() - } - return - } else { - switch o := m.(type) { - case error: - if onError != nil { - onError(o) - } - return - default: - onReceive(o) - } - } - } - } -} diff --git a/common/bech32/bech32.go b/common/bech32/bech32.go deleted file mode 100644 index a4db86d5..00000000 --- a/common/bech32/bech32.go +++ /dev/null @@ -1,29 +0,0 @@ -package bech32 - -import ( - "github.com/btcsuite/btcutil/bech32" - "github.com/pkg/errors" -) - -//ConvertAndEncode converts from a base64 encoded byte string to base32 encoded byte string and then to bech32 -func ConvertAndEncode(hrp string, data []byte) (string, error) { - converted, err := bech32.ConvertBits(data, 8, 5, true) - if err != nil { - return "", errors.Wrap(err, "encoding bech32 failed") - } - return bech32.Encode(hrp, converted) - -} - -//DecodeAndConvert decodes a bech32 encoded string and converts to base64 encoded bytes -func DecodeAndConvert(bech string) (string, []byte, error) { - hrp, data, err := bech32.Decode(bech) - if err != nil { - return "", nil, errors.Wrap(err, "decoding bech32 failed") - } - converted, err := bech32.ConvertBits(data, 5, 8, false) - if err != nil { - return "", nil, errors.Wrap(err, "decoding bech32 failed") - } - return hrp, converted, nil -} diff --git a/common/common.go b/common/common.go index a30e8b0f..81d4954e 100644 --- a/common/common.go +++ b/common/common.go @@ -42,7 +42,3 @@ func GenerateRandomBytes(n int) ([]byte, error) { return b, nil } - -func IsAlphaNum(s string) bool { - return isAlphaNumFunc(s) -} diff --git a/common/ledger/ledger.go b/common/ledger/ledger.go index e99ef302..8cc2e29e 100644 --- a/common/ledger/ledger.go +++ b/common/ledger/ledger.go @@ -1,9 +1,10 @@ +//go:build cgo && ledger // +build cgo,ledger package ledger import ( - ledger "github.com/binance-chain/ledger-cosmos-go" + ledger "github.com/zondax/ledger-cosmos-go" ) // If ledger support (build tag) has been enabled, which implies a CGO dependency, diff --git a/common/ledger/ledger_secp256k1.go b/common/ledger/ledger_secp256k1.go index 4076dc6f..89e07735 100644 --- a/common/ledger/ledger_secp256k1.go +++ b/common/ledger/ledger_secp256k1.go @@ -1,12 +1,12 @@ package ledger import ( - "github.com/binance-chain/go-sdk/common/types" - ledgergo "github.com/binance-chain/ledger-cosmos-go" "github.com/btcsuite/btcd/btcec" + stypes "github.com/cosmos/cosmos-sdk/types" tmbtcec "github.com/tendermint/btcd/btcec" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/secp256k1" + ledgergo "github.com/zondax/ledger-cosmos-go" ) var ( @@ -67,7 +67,7 @@ func (pkl PrivKeyLedgerSecp256k1) Bytes() []byte { } func (pkl PrivKeyLedgerSecp256k1) ShowSignAddr() error { - return pkl.ledger.ShowAddressSECP256K1(pkl.path, types.Network.Bech32Prefixes()) + return pkl.ledger.ShowAddressSECP256K1(pkl.path, stypes.GetConfig().GetBech32AccountAddrPrefix()) } func (pkl PrivKeyLedgerSecp256k1) Sign(msg []byte) ([]byte, error) { diff --git a/common/rlp/decode.go b/common/rlp/decode.go deleted file mode 100644 index 5f3f5eed..00000000 --- a/common/rlp/decode.go +++ /dev/null @@ -1,989 +0,0 @@ -// Copyright 2014 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package rlp - -import ( - "bufio" - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "math/big" - "reflect" - "strings" - "sync" -) - -//lint:ignore ST1012 EOL is not an error. - -// EOL is returned when the end of the current list -// has been reached during streaming. -var EOL = errors.New("rlp: end of list") - -var ( - ErrExpectedString = errors.New("rlp: expected String or Byte") - ErrExpectedList = errors.New("rlp: expected List") - ErrCanonInt = errors.New("rlp: non-canonical integer format") - ErrCanonSize = errors.New("rlp: non-canonical size information") - ErrElemTooLarge = errors.New("rlp: element is larger than containing list") - ErrValueTooLarge = errors.New("rlp: value size exceeds available input length") - ErrMoreThanOneValue = errors.New("rlp: input contains more than one value") - - // internal errors - errNotInList = errors.New("rlp: call of ListEnd outside of any list") - errNotAtEOL = errors.New("rlp: call of ListEnd not positioned at EOL") - errUintOverflow = errors.New("rlp: uint overflow") - errNoPointer = errors.New("rlp: interface given to Decode must be a pointer") - errDecodeIntoNil = errors.New("rlp: pointer given to Decode must not be nil") - - streamPool = sync.Pool{ - New: func() interface{} { return new(Stream) }, - } -) - -// Decoder is implemented by types that require custom RLP decoding rules or need to decode -// into private fields. -// -// The DecodeRLP method should read one value from the given Stream. It is not forbidden to -// read less or more, but it might be confusing. -type Decoder interface { - DecodeRLP(*Stream) error -} - -// Decode parses RLP-encoded data from r and stores the result in the value pointed to by -// val. Please see package-level documentation for the decoding rules. Val must be a -// non-nil pointer. -// -// If r does not implement ByteReader, Decode will do its own buffering. -// -// Note that Decode does not set an input limit for all readers and may be vulnerable to -// panics cause by huge value sizes. If you need an input limit, use -// -// NewStream(r, limit).Decode(val) -func Decode(r io.Reader, val interface{}) error { - stream := streamPool.Get().(*Stream) - defer streamPool.Put(stream) - - stream.Reset(r, 0) - return stream.Decode(val) -} - -// DecodeBytes parses RLP data from b into val. Please see package-level documentation for -// the decoding rules. The input must contain exactly one value and no trailing data. -func DecodeBytes(b []byte, val interface{}) error { - r := bytes.NewReader(b) - - stream := streamPool.Get().(*Stream) - defer streamPool.Put(stream) - - stream.Reset(r, uint64(len(b))) - if err := stream.Decode(val); err != nil { - return err - } - if r.Len() > 0 { - return ErrMoreThanOneValue - } - return nil -} - -type decodeError struct { - msg string - typ reflect.Type - ctx []string -} - -func (err *decodeError) Error() string { - ctx := "" - if len(err.ctx) > 0 { - ctx = ", decoding into " - for i := len(err.ctx) - 1; i >= 0; i-- { - ctx += err.ctx[i] - } - } - return fmt.Sprintf("rlp: %s for %v%s", err.msg, err.typ, ctx) -} - -func wrapStreamError(err error, typ reflect.Type) error { - switch err { - case ErrCanonInt: - return &decodeError{msg: "non-canonical integer (leading zero bytes)", typ: typ} - case ErrCanonSize: - return &decodeError{msg: "non-canonical size information", typ: typ} - case ErrExpectedList: - return &decodeError{msg: "expected input list", typ: typ} - case ErrExpectedString: - return &decodeError{msg: "expected input string or byte", typ: typ} - case errUintOverflow: - return &decodeError{msg: "input string too long", typ: typ} - case errNotAtEOL: - return &decodeError{msg: "input list has too many elements", typ: typ} - } - return err -} - -func addErrorContext(err error, ctx string) error { - if decErr, ok := err.(*decodeError); ok { - decErr.ctx = append(decErr.ctx, ctx) - } - return err -} - -var ( - decoderInterface = reflect.TypeOf(new(Decoder)).Elem() - bigInt = reflect.TypeOf(big.Int{}) -) - -func makeDecoder(typ reflect.Type, tags tags) (dec decoder, err error) { - kind := typ.Kind() - switch { - case typ == rawValueType: - return decodeRawValue, nil - case typ.AssignableTo(reflect.PtrTo(bigInt)): - return decodeBigInt, nil - case typ.AssignableTo(bigInt): - return decodeBigIntNoPtr, nil - case kind == reflect.Ptr: - return makePtrDecoder(typ, tags) - case reflect.PtrTo(typ).Implements(decoderInterface): - return decodeDecoder, nil - case isUint(kind): - return decodeUint, nil - case kind == reflect.Bool: - return decodeBool, nil - case kind == reflect.String: - return decodeString, nil - case kind == reflect.Slice || kind == reflect.Array: - return makeListDecoder(typ, tags) - case kind == reflect.Struct: - return makeStructDecoder(typ) - case kind == reflect.Interface: - return decodeInterface, nil - default: - return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ) - } -} - -func decodeRawValue(s *Stream, val reflect.Value) error { - r, err := s.Raw() - if err != nil { - return err - } - val.SetBytes(r) - return nil -} - -func decodeUint(s *Stream, val reflect.Value) error { - typ := val.Type() - num, err := s.uint(typ.Bits()) - if err != nil { - return wrapStreamError(err, val.Type()) - } - val.SetUint(num) - return nil -} - -func decodeBool(s *Stream, val reflect.Value) error { - b, err := s.Bool() - if err != nil { - return wrapStreamError(err, val.Type()) - } - val.SetBool(b) - return nil -} - -func decodeString(s *Stream, val reflect.Value) error { - b, err := s.Bytes() - if err != nil { - return wrapStreamError(err, val.Type()) - } - val.SetString(string(b)) - return nil -} - -func decodeBigIntNoPtr(s *Stream, val reflect.Value) error { - return decodeBigInt(s, val.Addr()) -} - -func decodeBigInt(s *Stream, val reflect.Value) error { - b, err := s.Bytes() - if err != nil { - return wrapStreamError(err, val.Type()) - } - i := val.Interface().(*big.Int) - if i == nil { - i = new(big.Int) - val.Set(reflect.ValueOf(i)) - } - // Reject leading zero bytes - if len(b) > 0 && b[0] == 0 { - return wrapStreamError(ErrCanonInt, val.Type()) - } - i.SetBytes(b) - return nil -} - -func makeListDecoder(typ reflect.Type, tag tags) (decoder, error) { - etype := typ.Elem() - if etype.Kind() == reflect.Uint8 && !reflect.PtrTo(etype).Implements(decoderInterface) { - if typ.Kind() == reflect.Array { - return decodeByteArray, nil - } - return decodeByteSlice, nil - } - etypeinfo := cachedTypeInfo1(etype, tags{}) - if etypeinfo.decoderErr != nil { - return nil, etypeinfo.decoderErr - } - var dec decoder - switch { - case typ.Kind() == reflect.Array: - dec = func(s *Stream, val reflect.Value) error { - return decodeListArray(s, val, etypeinfo.decoder) - } - case tag.tail: - // A slice with "tail" tag can occur as the last field - // of a struct and is supposed to swallow all remaining - // list elements. The struct decoder already called s.List, - // proceed directly to decoding the elements. - dec = func(s *Stream, val reflect.Value) error { - return decodeSliceElems(s, val, etypeinfo.decoder) - } - default: - dec = func(s *Stream, val reflect.Value) error { - return decodeListSlice(s, val, etypeinfo.decoder) - } - } - return dec, nil -} - -func decodeListSlice(s *Stream, val reflect.Value, elemdec decoder) error { - size, err := s.List() - if err != nil { - return wrapStreamError(err, val.Type()) - } - if size == 0 { - val.Set(reflect.MakeSlice(val.Type(), 0, 0)) - return s.ListEnd() - } - if err := decodeSliceElems(s, val, elemdec); err != nil { - return err - } - return s.ListEnd() -} - -func decodeSliceElems(s *Stream, val reflect.Value, elemdec decoder) error { - i := 0 - for ; ; i++ { - // grow slice if necessary - if i >= val.Cap() { - newcap := val.Cap() + val.Cap()/2 - if newcap < 4 { - newcap = 4 - } - newv := reflect.MakeSlice(val.Type(), val.Len(), newcap) - reflect.Copy(newv, val) - val.Set(newv) - } - if i >= val.Len() { - val.SetLen(i + 1) - } - // decode into element - if err := elemdec(s, val.Index(i)); err == EOL { - break - } else if err != nil { - return addErrorContext(err, fmt.Sprint("[", i, "]")) - } - } - if i < val.Len() { - val.SetLen(i) - } - return nil -} - -func decodeListArray(s *Stream, val reflect.Value, elemdec decoder) error { - if _, err := s.List(); err != nil { - return wrapStreamError(err, val.Type()) - } - vlen := val.Len() - i := 0 - for ; i < vlen; i++ { - if err := elemdec(s, val.Index(i)); err == EOL { - break - } else if err != nil { - return addErrorContext(err, fmt.Sprint("[", i, "]")) - } - } - if i < vlen { - return &decodeError{msg: "input list has too few elements", typ: val.Type()} - } - return wrapStreamError(s.ListEnd(), val.Type()) -} - -func decodeByteSlice(s *Stream, val reflect.Value) error { - b, err := s.Bytes() - if err != nil { - return wrapStreamError(err, val.Type()) - } - val.SetBytes(b) - return nil -} - -func decodeByteArray(s *Stream, val reflect.Value) error { - kind, size, err := s.Kind() - if err != nil { - return err - } - vlen := val.Len() - switch kind { - case Byte: - if vlen == 0 { - return &decodeError{msg: "input string too long", typ: val.Type()} - } - if vlen > 1 { - return &decodeError{msg: "input string too short", typ: val.Type()} - } - bv, _ := s.Uint() - val.Index(0).SetUint(bv) - case String: - if uint64(vlen) < size { - return &decodeError{msg: "input string too long", typ: val.Type()} - } - if uint64(vlen) > size { - return &decodeError{msg: "input string too short", typ: val.Type()} - } - slice := val.Slice(0, vlen).Interface().([]byte) - if err := s.readFull(slice); err != nil { - return err - } - // Reject cases where single byte encoding should have been used. - if size == 1 && slice[0] < 128 { - return wrapStreamError(ErrCanonSize, val.Type()) - } - case List: - return wrapStreamError(ErrExpectedString, val.Type()) - } - return nil -} - -func makeStructDecoder(typ reflect.Type) (decoder, error) { - fields, err := structFields(typ) - if err != nil { - return nil, err - } - for _, f := range fields { - if f.info.decoderErr != nil { - return nil, structFieldError{typ, f.index, f.info.decoderErr} - } - } - dec := func(s *Stream, val reflect.Value) (err error) { - if _, err := s.List(); err != nil { - return wrapStreamError(err, typ) - } - for _, f := range fields { - err := f.info.decoder(s, val.Field(f.index)) - if err == EOL { - return &decodeError{msg: "too few elements", typ: typ} - } else if err != nil { - return addErrorContext(err, "."+typ.Field(f.index).Name) - } - } - return wrapStreamError(s.ListEnd(), typ) - } - return dec, nil -} - -// makePtrDecoder creates a decoder that decodes into the pointer's element type. -func makePtrDecoder(typ reflect.Type, tag tags) (decoder, error) { - etype := typ.Elem() - etypeinfo := cachedTypeInfo1(etype, tags{}) - switch { - case etypeinfo.decoderErr != nil: - return nil, etypeinfo.decoderErr - case !tag.nilOK: - return makeSimplePtrDecoder(etype, etypeinfo), nil - default: - return makeNilPtrDecoder(etype, etypeinfo, tag.nilKind), nil - } -} - -func makeSimplePtrDecoder(etype reflect.Type, etypeinfo *typeinfo) decoder { - return func(s *Stream, val reflect.Value) (err error) { - newval := val - if val.IsNil() { - newval = reflect.New(etype) - } - if err = etypeinfo.decoder(s, newval.Elem()); err == nil { - val.Set(newval) - } - return err - } -} - -// makeNilPtrDecoder creates a decoder that decodes empty values as nil. Non-empty -// values are decoded into a value of the element type, just like makePtrDecoder does. -// -// This decoder is used for pointer-typed struct fields with struct tag "nil". -func makeNilPtrDecoder(etype reflect.Type, etypeinfo *typeinfo, nilKind Kind) decoder { - typ := reflect.PtrTo(etype) - nilPtr := reflect.Zero(typ) - return func(s *Stream, val reflect.Value) (err error) { - kind, size, err := s.Kind() - if err != nil { - val.Set(nilPtr) - return wrapStreamError(err, typ) - } - // Handle empty values as a nil pointer. - if kind != Byte && size == 0 { - if kind != nilKind { - return &decodeError{ - msg: fmt.Sprintf("wrong kind of empty value (got %v, want %v)", kind, nilKind), - typ: typ, - } - } - // rearm s.Kind. This is important because the input - // position must advance to the next value even though - // we don't read anything. - s.kind = -1 - val.Set(nilPtr) - return nil - } - newval := val - if val.IsNil() { - newval = reflect.New(etype) - } - if err = etypeinfo.decoder(s, newval.Elem()); err == nil { - val.Set(newval) - } - return err - } -} - -var ifsliceType = reflect.TypeOf([]interface{}{}) - -func decodeInterface(s *Stream, val reflect.Value) error { - if val.Type().NumMethod() != 0 { - return fmt.Errorf("rlp: type %v is not RLP-serializable", val.Type()) - } - kind, _, err := s.Kind() - if err != nil { - return err - } - if kind == List { - slice := reflect.New(ifsliceType).Elem() - if err := decodeListSlice(s, slice, decodeInterface); err != nil { - return err - } - val.Set(slice) - } else { - b, err := s.Bytes() - if err != nil { - return err - } - val.Set(reflect.ValueOf(b)) - } - return nil -} - -func decodeDecoder(s *Stream, val reflect.Value) error { - return val.Addr().Interface().(Decoder).DecodeRLP(s) -} - -// Kind represents the kind of value contained in an RLP stream. -type Kind int - -const ( - Byte Kind = iota - String - List -) - -func (k Kind) String() string { - switch k { - case Byte: - return "Byte" - case String: - return "String" - case List: - return "List" - default: - return fmt.Sprintf("Unknown(%d)", k) - } -} - -// ByteReader must be implemented by any input reader for a Stream. It -// is implemented by e.g. bufio.Reader and bytes.Reader. -type ByteReader interface { - io.Reader - io.ByteReader -} - -// Stream can be used for piecemeal decoding of an input stream. This -// is useful if the input is very large or if the decoding rules for a -// type depend on the input structure. Stream does not keep an -// internal buffer. After decoding a value, the input reader will be -// positioned just before the type information for the next value. -// -// When decoding a list and the input position reaches the declared -// length of the list, all operations will return error EOL. -// The end of the list must be acknowledged using ListEnd to continue -// reading the enclosing list. -// -// Stream is not safe for concurrent use. -type Stream struct { - r ByteReader - - // number of bytes remaining to be read from r. - remaining uint64 - limited bool - - // auxiliary buffer for integer decoding - uintbuf []byte - - kind Kind // kind of value ahead - size uint64 // size of value ahead - byteval byte // value of single byte in type tag - kinderr error // error from last readKind - stack []listpos -} - -type listpos struct{ pos, size uint64 } - -// NewStream creates a new decoding stream reading from r. -// -// If r implements the ByteReader interface, Stream will -// not introduce any buffering. -// -// For non-toplevel values, Stream returns ErrElemTooLarge -// for values that do not fit into the enclosing list. -// -// Stream supports an optional input limit. If a limit is set, the -// size of any toplevel value will be checked against the remaining -// input length. Stream operations that encounter a value exceeding -// the remaining input length will return ErrValueTooLarge. The limit -// can be set by passing a non-zero value for inputLimit. -// -// If r is a bytes.Reader or strings.Reader, the input limit is set to -// the length of r's underlying data unless an explicit limit is -// provided. -func NewStream(r io.Reader, inputLimit uint64) *Stream { - s := new(Stream) - s.Reset(r, inputLimit) - return s -} - -// NewListStream creates a new stream that pretends to be positioned -// at an encoded list of the given length. -func NewListStream(r io.Reader, len uint64) *Stream { - s := new(Stream) - s.Reset(r, len) - s.kind = List - s.size = len - return s -} - -// Bytes reads an RLP string and returns its contents as a byte slice. -// If the input does not contain an RLP string, the returned -// error will be ErrExpectedString. -func (s *Stream) Bytes() ([]byte, error) { - kind, size, err := s.Kind() - if err != nil { - return nil, err - } - switch kind { - case Byte: - s.kind = -1 // rearm Kind - return []byte{s.byteval}, nil - case String: - b := make([]byte, size) - if err = s.readFull(b); err != nil { - return nil, err - } - if size == 1 && b[0] < 128 { - return nil, ErrCanonSize - } - return b, nil - default: - return nil, ErrExpectedString - } -} - -// Raw reads a raw encoded value including RLP type information. -func (s *Stream) Raw() ([]byte, error) { - kind, size, err := s.Kind() - if err != nil { - return nil, err - } - if kind == Byte { - s.kind = -1 // rearm Kind - return []byte{s.byteval}, nil - } - // the original header has already been read and is no longer - // available. read content and put a new header in front of it. - start := headsize(size) - buf := make([]byte, uint64(start)+size) - if err := s.readFull(buf[start:]); err != nil { - return nil, err - } - if kind == String { - puthead(buf, 0x80, 0xB7, size) - } else { - puthead(buf, 0xC0, 0xF7, size) - } - return buf, nil -} - -// Uint reads an RLP string of up to 8 bytes and returns its contents -// as an unsigned integer. If the input does not contain an RLP string, the -// returned error will be ErrExpectedString. -func (s *Stream) Uint() (uint64, error) { - return s.uint(64) -} - -func (s *Stream) uint(maxbits int) (uint64, error) { - kind, size, err := s.Kind() - if err != nil { - return 0, err - } - switch kind { - case Byte: - if s.byteval == 0 { - return 0, ErrCanonInt - } - s.kind = -1 // rearm Kind - return uint64(s.byteval), nil - case String: - if size > uint64(maxbits/8) { - return 0, errUintOverflow - } - v, err := s.readUint(byte(size)) - switch { - case err == ErrCanonSize: - // Adjust error because we're not reading a size right now. - return 0, ErrCanonInt - case err != nil: - return 0, err - case size > 0 && v < 128: - return 0, ErrCanonSize - default: - return v, nil - } - default: - return 0, ErrExpectedString - } -} - -// Bool reads an RLP string of up to 1 byte and returns its contents -// as a boolean. If the input does not contain an RLP string, the -// returned error will be ErrExpectedString. -func (s *Stream) Bool() (bool, error) { - num, err := s.uint(8) - if err != nil { - return false, err - } - switch num { - case 0: - return false, nil - case 1: - return true, nil - default: - return false, fmt.Errorf("rlp: invalid boolean value: %d", num) - } -} - -// List starts decoding an RLP list. If the input does not contain a -// list, the returned error will be ErrExpectedList. When the list's -// end has been reached, any Stream operation will return EOL. -func (s *Stream) List() (size uint64, err error) { - kind, size, err := s.Kind() - if err != nil { - return 0, err - } - if kind != List { - return 0, ErrExpectedList - } - s.stack = append(s.stack, listpos{0, size}) - s.kind = -1 - s.size = 0 - return size, nil -} - -// ListEnd returns to the enclosing list. -// The input reader must be positioned at the end of a list. -func (s *Stream) ListEnd() error { - if len(s.stack) == 0 { - return errNotInList - } - tos := s.stack[len(s.stack)-1] - if tos.pos != tos.size { - return errNotAtEOL - } - s.stack = s.stack[:len(s.stack)-1] // pop - if len(s.stack) > 0 { - s.stack[len(s.stack)-1].pos += tos.size - } - s.kind = -1 - s.size = 0 - return nil -} - -// Decode decodes a value and stores the result in the value pointed -// to by val. Please see the documentation for the Decode function -// to learn about the decoding rules. -func (s *Stream) Decode(val interface{}) error { - if val == nil { - return errDecodeIntoNil - } - rval := reflect.ValueOf(val) - rtyp := rval.Type() - if rtyp.Kind() != reflect.Ptr { - return errNoPointer - } - if rval.IsNil() { - return errDecodeIntoNil - } - decoder, err := cachedDecoder(rtyp.Elem()) - if err != nil { - return err - } - - err = decoder(s, rval.Elem()) - if decErr, ok := err.(*decodeError); ok && len(decErr.ctx) > 0 { - // add decode target type to error so context has more meaning - decErr.ctx = append(decErr.ctx, fmt.Sprint("(", rtyp.Elem(), ")")) - } - return err -} - -// Reset discards any information about the current decoding context -// and starts reading from r. This method is meant to facilitate reuse -// of a preallocated Stream across many decoding operations. -// -// If r does not also implement ByteReader, Stream will do its own -// buffering. -func (s *Stream) Reset(r io.Reader, inputLimit uint64) { - if inputLimit > 0 { - s.remaining = inputLimit - s.limited = true - } else { - // Attempt to automatically discover - // the limit when reading from a byte slice. - switch br := r.(type) { - case *bytes.Reader: - s.remaining = uint64(br.Len()) - s.limited = true - case *strings.Reader: - s.remaining = uint64(br.Len()) - s.limited = true - default: - s.limited = false - } - } - // Wrap r with a buffer if it doesn't have one. - bufr, ok := r.(ByteReader) - if !ok { - bufr = bufio.NewReader(r) - } - s.r = bufr - // Reset the decoding context. - s.stack = s.stack[:0] - s.size = 0 - s.kind = -1 - s.kinderr = nil - if s.uintbuf == nil { - s.uintbuf = make([]byte, 8) - } - s.byteval = 0 -} - -// Kind returns the kind and size of the next value in the -// input stream. -// -// The returned size is the number of bytes that make up the value. -// For kind == Byte, the size is zero because the value is -// contained in the type tag. -// -// The first call to Kind will read size information from the input -// reader and leave it positioned at the start of the actual bytes of -// the value. Subsequent calls to Kind (until the value is decoded) -// will not advance the input reader and return cached information. -func (s *Stream) Kind() (kind Kind, size uint64, err error) { - var tos *listpos - if len(s.stack) > 0 { - tos = &s.stack[len(s.stack)-1] - } - if s.kind < 0 { - s.kinderr = nil - // Don't read further if we're at the end of the - // innermost list. - if tos != nil && tos.pos == tos.size { - return 0, 0, EOL - } - s.kind, s.size, s.kinderr = s.readKind() - if s.kinderr == nil { - if tos == nil { - // At toplevel, check that the value is smaller - // than the remaining input length. - if s.limited && s.size > s.remaining { - s.kinderr = ErrValueTooLarge - } - } else { - // Inside a list, check that the value doesn't overflow the list. - if s.size > tos.size-tos.pos { - s.kinderr = ErrElemTooLarge - } - } - } - } - // Note: this might return a sticky error generated - // by an earlier call to readKind. - return s.kind, s.size, s.kinderr -} - -func (s *Stream) readKind() (kind Kind, size uint64, err error) { - b, err := s.readByte() - if err != nil { - if len(s.stack) == 0 { - // At toplevel, Adjust the error to actual EOF. io.EOF is - // used by callers to determine when to stop decoding. - switch err { - case io.ErrUnexpectedEOF: - err = io.EOF - case ErrValueTooLarge: - err = io.EOF - } - } - return 0, 0, err - } - s.byteval = 0 - switch { - case b < 0x80: - // For a single byte whose value is in the [0x00, 0x7F] range, that byte - // is its own RLP encoding. - s.byteval = b - return Byte, 0, nil - case b < 0xB8: - // Otherwise, if a string is 0-55 bytes long, - // the RLP encoding consists of a single byte with value 0x80 plus the - // length of the string followed by the string. The range of the first - // byte is thus [0x80, 0xB7]. - return String, uint64(b - 0x80), nil - case b < 0xC0: - // If a string is more than 55 bytes long, the - // RLP encoding consists of a single byte with value 0xB7 plus the length - // of the length of the string in binary form, followed by the length of - // the string, followed by the string. For example, a length-1024 string - // would be encoded as 0xB90400 followed by the string. The range of - // the first byte is thus [0xB8, 0xBF]. - size, err = s.readUint(b - 0xB7) - if err == nil && size < 56 { - err = ErrCanonSize - } - return String, size, err - case b < 0xF8: - // If the total payload of a list - // (i.e. the combined length of all its items) is 0-55 bytes long, the - // RLP encoding consists of a single byte with value 0xC0 plus the length - // of the list followed by the concatenation of the RLP encodings of the - // items. The range of the first byte is thus [0xC0, 0xF7]. - return List, uint64(b - 0xC0), nil - default: - // If the total payload of a list is more than 55 bytes long, - // the RLP encoding consists of a single byte with value 0xF7 - // plus the length of the length of the payload in binary - // form, followed by the length of the payload, followed by - // the concatenation of the RLP encodings of the items. The - // range of the first byte is thus [0xF8, 0xFF]. - size, err = s.readUint(b - 0xF7) - if err == nil && size < 56 { - err = ErrCanonSize - } - return List, size, err - } -} - -func (s *Stream) readUint(size byte) (uint64, error) { - switch size { - case 0: - s.kind = -1 // rearm Kind - return 0, nil - case 1: - b, err := s.readByte() - return uint64(b), err - default: - start := int(8 - size) - for i := 0; i < start; i++ { - s.uintbuf[i] = 0 - } - if err := s.readFull(s.uintbuf[start:]); err != nil { - return 0, err - } - if s.uintbuf[start] == 0 { - // Note: readUint is also used to decode integer - // values. The error needs to be adjusted to become - // ErrCanonInt in this case. - return 0, ErrCanonSize - } - return binary.BigEndian.Uint64(s.uintbuf), nil - } -} - -func (s *Stream) readFull(buf []byte) (err error) { - if err := s.willRead(uint64(len(buf))); err != nil { - return err - } - var nn, n int - for n < len(buf) && err == nil { - nn, err = s.r.Read(buf[n:]) - n += nn - } - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return err -} - -func (s *Stream) readByte() (byte, error) { - if err := s.willRead(1); err != nil { - return 0, err - } - b, err := s.r.ReadByte() - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return b, err -} - -func (s *Stream) willRead(n uint64) error { - s.kind = -1 // rearm Kind - - if len(s.stack) > 0 { - // check list overflow - tos := s.stack[len(s.stack)-1] - if n > tos.size-tos.pos { - return ErrElemTooLarge - } - s.stack[len(s.stack)-1].pos += n - } - if s.limited { - if n > s.remaining { - return ErrValueTooLarge - } - s.remaining -= n - } - return nil -} diff --git a/common/rlp/decode_tail_test.go b/common/rlp/decode_tail_test.go deleted file mode 100644 index 884c1148..00000000 --- a/common/rlp/decode_tail_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2015 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package rlp - -import ( - "bytes" - "fmt" -) - -type structWithTail struct { - A, B uint - C []uint `rlp:"tail"` -} - -func ExampleDecode_structTagTail() { - // In this example, the "tail" struct tag is used to decode lists of - // differing length into a struct. - var val structWithTail - - err := Decode(bytes.NewReader([]byte{0xC4, 0x01, 0x02, 0x03, 0x04}), &val) - fmt.Printf("with 4 elements: err=%v val=%v\n", err, val) - - err = Decode(bytes.NewReader([]byte{0xC6, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), &val) - fmt.Printf("with 6 elements: err=%v val=%v\n", err, val) - - // Note that at least two list elements must be present to - // fill fields A and B: - err = Decode(bytes.NewReader([]byte{0xC1, 0x01}), &val) - fmt.Printf("with 1 element: err=%q\n", err) - - // Output: - // with 4 elements: err= val={1 2 [3 4]} - // with 6 elements: err= val={1 2 [3 4 5 6]} - // with 1 element: err="rlp: too few elements for rlp.structWithTail" -} diff --git a/common/rlp/decode_test.go b/common/rlp/decode_test.go deleted file mode 100644 index 167e9974..00000000 --- a/common/rlp/decode_test.go +++ /dev/null @@ -1,929 +0,0 @@ -// Copyright 2014 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package rlp - -import ( - "bytes" - "encoding/hex" - "errors" - "fmt" - "io" - "math/big" - "reflect" - "strings" - "testing" -) - -func TestStreamKind(t *testing.T) { - tests := []struct { - input string - wantKind Kind - wantLen uint64 - }{ - {"00", Byte, 0}, - {"01", Byte, 0}, - {"7F", Byte, 0}, - {"80", String, 0}, - {"B7", String, 55}, - {"B90400", String, 1024}, - {"BFFFFFFFFFFFFFFFFF", String, ^uint64(0)}, - {"C0", List, 0}, - {"C8", List, 8}, - {"F7", List, 55}, - {"F90400", List, 1024}, - {"FFFFFFFFFFFFFFFFFF", List, ^uint64(0)}, - } - - for i, test := range tests { - // using plainReader to inhibit input limit errors. - s := NewStream(newPlainReader(unhex(test.input)), 0) - kind, len, err := s.Kind() - if err != nil { - t.Errorf("test %d: Kind returned error: %v", i, err) - continue - } - if kind != test.wantKind { - t.Errorf("test %d: kind mismatch: got %d, want %d", i, kind, test.wantKind) - } - if len != test.wantLen { - t.Errorf("test %d: len mismatch: got %d, want %d", i, len, test.wantLen) - } - } -} - -func TestNewListStream(t *testing.T) { - ls := NewListStream(bytes.NewReader(unhex("0101010101")), 3) - if k, size, err := ls.Kind(); k != List || size != 3 || err != nil { - t.Errorf("Kind() returned (%v, %d, %v), expected (List, 3, nil)", k, size, err) - } - if size, err := ls.List(); size != 3 || err != nil { - t.Errorf("List() returned (%d, %v), expected (3, nil)", size, err) - } - for i := 0; i < 3; i++ { - if val, err := ls.Uint(); val != 1 || err != nil { - t.Errorf("Uint() returned (%d, %v), expected (1, nil)", val, err) - } - } - if err := ls.ListEnd(); err != nil { - t.Errorf("ListEnd() returned %v, expected (3, nil)", err) - } -} - -func TestStreamErrors(t *testing.T) { - withoutInputLimit := func(b []byte) *Stream { - return NewStream(newPlainReader(b), 0) - } - withCustomInputLimit := func(limit uint64) func([]byte) *Stream { - return func(b []byte) *Stream { - return NewStream(bytes.NewReader(b), limit) - } - } - - type calls []string - tests := []struct { - string - calls - newStream func([]byte) *Stream // uses bytes.Reader if nil - error error - }{ - {"C0", calls{"Bytes"}, nil, ErrExpectedString}, - {"C0", calls{"Uint"}, nil, ErrExpectedString}, - {"89000000000000000001", calls{"Uint"}, nil, errUintOverflow}, - {"00", calls{"List"}, nil, ErrExpectedList}, - {"80", calls{"List"}, nil, ErrExpectedList}, - {"C0", calls{"List", "Uint"}, nil, EOL}, - {"C8C9010101010101010101", calls{"List", "Kind"}, nil, ErrElemTooLarge}, - {"C3C2010201", calls{"List", "List", "Uint", "Uint", "ListEnd", "Uint"}, nil, EOL}, - {"00", calls{"ListEnd"}, nil, errNotInList}, - {"C401020304", calls{"List", "Uint", "ListEnd"}, nil, errNotAtEOL}, - - // Non-canonical integers (e.g. leading zero bytes). - {"00", calls{"Uint"}, nil, ErrCanonInt}, - {"820002", calls{"Uint"}, nil, ErrCanonInt}, - {"8133", calls{"Uint"}, nil, ErrCanonSize}, - {"817F", calls{"Uint"}, nil, ErrCanonSize}, - {"8180", calls{"Uint"}, nil, nil}, - - // Non-valid boolean - {"02", calls{"Bool"}, nil, errors.New("rlp: invalid boolean value: 2")}, - - // Size tags must use the smallest possible encoding. - // Leading zero bytes in the size tag are also rejected. - {"8100", calls{"Uint"}, nil, ErrCanonSize}, - {"8100", calls{"Bytes"}, nil, ErrCanonSize}, - {"8101", calls{"Bytes"}, nil, ErrCanonSize}, - {"817F", calls{"Bytes"}, nil, ErrCanonSize}, - {"8180", calls{"Bytes"}, nil, nil}, - {"B800", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, - {"B90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, - {"B90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, - {"BA0002FFFF", calls{"Bytes"}, withoutInputLimit, ErrCanonSize}, - {"F800", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, - {"F90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, - {"F90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, - {"FA0002FFFF", calls{"List"}, withoutInputLimit, ErrCanonSize}, - - // Expected EOF - {"", calls{"Kind"}, nil, io.EOF}, - {"", calls{"Uint"}, nil, io.EOF}, - {"", calls{"List"}, nil, io.EOF}, - {"8180", calls{"Uint", "Uint"}, nil, io.EOF}, - {"C0", calls{"List", "ListEnd", "List"}, nil, io.EOF}, - - {"", calls{"List"}, withoutInputLimit, io.EOF}, - {"8180", calls{"Uint", "Uint"}, withoutInputLimit, io.EOF}, - {"C0", calls{"List", "ListEnd", "List"}, withoutInputLimit, io.EOF}, - - // Input limit errors. - {"81", calls{"Bytes"}, nil, ErrValueTooLarge}, - {"81", calls{"Uint"}, nil, ErrValueTooLarge}, - {"81", calls{"Raw"}, nil, ErrValueTooLarge}, - {"BFFFFFFFFFFFFFFFFFFF", calls{"Bytes"}, nil, ErrValueTooLarge}, - {"C801", calls{"List"}, nil, ErrValueTooLarge}, - - // Test for list element size check overflow. - {"CD04040404FFFFFFFFFFFFFFFFFF0303", calls{"List", "Uint", "Uint", "Uint", "Uint", "List"}, nil, ErrElemTooLarge}, - - // Test for input limit overflow. Since we are counting the limit - // down toward zero in Stream.remaining, reading too far can overflow - // remaining to a large value, effectively disabling the limit. - {"C40102030401", calls{"Raw", "Uint"}, withCustomInputLimit(5), io.EOF}, - {"C4010203048180", calls{"Raw", "Uint"}, withCustomInputLimit(6), ErrValueTooLarge}, - - // Check that the same calls are fine without a limit. - {"C40102030401", calls{"Raw", "Uint"}, withoutInputLimit, nil}, - {"C4010203048180", calls{"Raw", "Uint"}, withoutInputLimit, nil}, - - // Unexpected EOF. This only happens when there is - // no input limit, so the reader needs to be 'dumbed down'. - {"81", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF}, - {"81", calls{"Uint"}, withoutInputLimit, io.ErrUnexpectedEOF}, - {"BFFFFFFFFFFFFFFF", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF}, - {"C801", calls{"List", "Uint", "Uint"}, withoutInputLimit, io.ErrUnexpectedEOF}, - - // This test verifies that the input position is advanced - // correctly when calling Bytes for empty strings. Kind can be called - // any number of times in between and doesn't advance. - {"C3808080", calls{ - "List", // enter the list - "Bytes", // past first element - - "Kind", "Kind", "Kind", // this shouldn't advance - - "Bytes", // past second element - - "Kind", "Kind", // can't hurt to try - - "Bytes", // past final element - "Bytes", // this one should fail - }, nil, EOL}, - } - -testfor: - for i, test := range tests { - if test.newStream == nil { - test.newStream = func(b []byte) *Stream { return NewStream(bytes.NewReader(b), 0) } - } - s := test.newStream(unhex(test.string)) - rs := reflect.ValueOf(s) - for j, call := range test.calls { - fval := rs.MethodByName(call) - ret := fval.Call(nil) - err := "" - if lastret := ret[len(ret)-1].Interface(); lastret != nil { - err = lastret.(error).Error() - } - if j == len(test.calls)-1 { - want := "" - if test.error != nil { - want = test.error.Error() - } - if err != want { - t.Log(test) - t.Errorf("test %d: last call (%s) error mismatch\ngot: %s\nwant: %s", - i, call, err, test.error) - } - } else if err != "" { - t.Log(test) - t.Errorf("test %d: call %d (%s) unexpected error: %q", i, j, call, err) - continue testfor - } - } - } -} - -func TestStreamList(t *testing.T) { - s := NewStream(bytes.NewReader(unhex("C80102030405060708")), 0) - - len, err := s.List() - if err != nil { - t.Fatalf("List error: %v", err) - } - if len != 8 { - t.Fatalf("List returned invalid length, got %d, want 8", len) - } - - for i := uint64(1); i <= 8; i++ { - v, err := s.Uint() - if err != nil { - t.Fatalf("Uint error: %v", err) - } - if i != v { - t.Errorf("Uint returned wrong value, got %d, want %d", v, i) - } - } - - if _, err := s.Uint(); err != EOL { - t.Errorf("Uint error mismatch, got %v, want %v", err, EOL) - } - if err = s.ListEnd(); err != nil { - t.Fatalf("ListEnd error: %v", err) - } -} - -func TestStreamRaw(t *testing.T) { - tests := []struct { - input string - output string - }{ - { - "C58401010101", - "8401010101", - }, - { - "F842B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", - "B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", - }, - } - for i, tt := range tests { - s := NewStream(bytes.NewReader(unhex(tt.input)), 0) - s.List() - - want := unhex(tt.output) - raw, err := s.Raw() - if err != nil { - t.Fatal(err) - } - if !bytes.Equal(want, raw) { - t.Errorf("test %d: raw mismatch: got %x, want %x", i, raw, want) - } - } -} - -func TestDecodeErrors(t *testing.T) { - r := bytes.NewReader(nil) - - if err := Decode(r, nil); err != errDecodeIntoNil { - t.Errorf("Decode(r, nil) error mismatch, got %q, want %q", err, errDecodeIntoNil) - } - - var nilptr *struct{} - if err := Decode(r, nilptr); err != errDecodeIntoNil { - t.Errorf("Decode(r, nilptr) error mismatch, got %q, want %q", err, errDecodeIntoNil) - } - - if err := Decode(r, struct{}{}); err != errNoPointer { - t.Errorf("Decode(r, struct{}{}) error mismatch, got %q, want %q", err, errNoPointer) - } - - expectErr := "rlp: type chan bool is not RLP-serializable" - if err := Decode(r, new(chan bool)); err == nil || err.Error() != expectErr { - t.Errorf("Decode(r, new(chan bool)) error mismatch, got %q, want %q", err, expectErr) - } - - if err := Decode(r, new(uint)); err != io.EOF { - t.Errorf("Decode(r, new(int)) error mismatch, got %q, want %q", err, io.EOF) - } -} - -type decodeTest struct { - input string - ptr interface{} - value interface{} - error string -} - -type simplestruct struct { - A uint - B string -} - -type recstruct struct { - I uint - Child *recstruct `rlp:"nil"` -} - -type invalidNilTag struct { - X []byte `rlp:"nil"` -} - -type invalidTail1 struct { - A uint `rlp:"tail"` - B string -} - -type invalidTail2 struct { - A uint - B string `rlp:"tail"` -} - -type tailRaw struct { - A uint - Tail []RawValue `rlp:"tail"` -} - -type tailUint struct { - A uint - Tail []uint `rlp:"tail"` -} - -type tailPrivateFields struct { - A uint - Tail []uint `rlp:"tail"` - x, y bool //lint:ignore U1000 unused fields required for testing purposes. -} - -type nilListUint struct { - X *uint `rlp:"nilList"` -} - -type nilStringSlice struct { - X *[]uint `rlp:"nilString"` -} - -type intField struct { - X int -} - -var ( - veryBigInt = big.NewInt(0).Add( - big.NewInt(0).Lsh(big.NewInt(0xFFFFFFFFFFFFFF), 16), - big.NewInt(0xFFFF), - ) -) - -type hasIgnoredField struct { - A uint - B uint `rlp:"-"` - C uint -} - -var decodeTests = []decodeTest{ - // booleans - {input: "01", ptr: new(bool), value: true}, - {input: "80", ptr: new(bool), value: false}, - {input: "02", ptr: new(bool), error: "rlp: invalid boolean value: 2"}, - - // integers - {input: "05", ptr: new(uint32), value: uint32(5)}, - {input: "80", ptr: new(uint32), value: uint32(0)}, - {input: "820505", ptr: new(uint32), value: uint32(0x0505)}, - {input: "83050505", ptr: new(uint32), value: uint32(0x050505)}, - {input: "8405050505", ptr: new(uint32), value: uint32(0x05050505)}, - {input: "850505050505", ptr: new(uint32), error: "rlp: input string too long for uint32"}, - {input: "C0", ptr: new(uint32), error: "rlp: expected input string or byte for uint32"}, - {input: "00", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"}, - {input: "8105", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"}, - {input: "820004", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"}, - {input: "B8020004", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"}, - - // slices - {input: "C0", ptr: new([]uint), value: []uint{}}, - {input: "C80102030405060708", ptr: new([]uint), value: []uint{1, 2, 3, 4, 5, 6, 7, 8}}, - {input: "F8020004", ptr: new([]uint), error: "rlp: non-canonical size information for []uint"}, - - // arrays - {input: "C50102030405", ptr: new([5]uint), value: [5]uint{1, 2, 3, 4, 5}}, - {input: "C0", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"}, - {input: "C102", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"}, - {input: "C6010203040506", ptr: new([5]uint), error: "rlp: input list has too many elements for [5]uint"}, - {input: "F8020004", ptr: new([5]uint), error: "rlp: non-canonical size information for [5]uint"}, - - // zero sized arrays - {input: "C0", ptr: new([0]uint), value: [0]uint{}}, - {input: "C101", ptr: new([0]uint), error: "rlp: input list has too many elements for [0]uint"}, - - // byte slices - {input: "01", ptr: new([]byte), value: []byte{1}}, - {input: "80", ptr: new([]byte), value: []byte{}}, - {input: "8D6162636465666768696A6B6C6D", ptr: new([]byte), value: []byte("abcdefghijklm")}, - {input: "C0", ptr: new([]byte), error: "rlp: expected input string or byte for []uint8"}, - {input: "8105", ptr: new([]byte), error: "rlp: non-canonical size information for []uint8"}, - - // byte arrays - {input: "02", ptr: new([1]byte), value: [1]byte{2}}, - {input: "8180", ptr: new([1]byte), value: [1]byte{128}}, - {input: "850102030405", ptr: new([5]byte), value: [5]byte{1, 2, 3, 4, 5}}, - - // byte array errors - {input: "02", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"}, - {input: "80", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"}, - {input: "820000", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"}, - {input: "C0", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"}, - {input: "C3010203", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"}, - {input: "86010203040506", ptr: new([5]byte), error: "rlp: input string too long for [5]uint8"}, - {input: "8105", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"}, - {input: "817F", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"}, - - // zero sized byte arrays - {input: "80", ptr: new([0]byte), value: [0]byte{}}, - {input: "01", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"}, - {input: "8101", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"}, - - // strings - {input: "00", ptr: new(string), value: "\000"}, - {input: "8D6162636465666768696A6B6C6D", ptr: new(string), value: "abcdefghijklm"}, - {input: "C0", ptr: new(string), error: "rlp: expected input string or byte for string"}, - - // big ints - {input: "01", ptr: new(*big.Int), value: big.NewInt(1)}, - {input: "89FFFFFFFFFFFFFFFFFF", ptr: new(*big.Int), value: veryBigInt}, - {input: "10", ptr: new(big.Int), value: *big.NewInt(16)}, // non-pointer also works - {input: "C0", ptr: new(*big.Int), error: "rlp: expected input string or byte for *big.Int"}, - {input: "820001", ptr: new(big.Int), error: "rlp: non-canonical integer (leading zero bytes) for *big.Int"}, - {input: "8105", ptr: new(big.Int), error: "rlp: non-canonical size information for *big.Int"}, - - // structs - { - input: "C50583343434", - ptr: new(simplestruct), - value: simplestruct{5, "444"}, - }, - { - input: "C601C402C203C0", - ptr: new(recstruct), - value: recstruct{1, &recstruct{2, &recstruct{3, nil}}}, - }, - - // struct errors - { - input: "C0", - ptr: new(simplestruct), - error: "rlp: too few elements for rlp.simplestruct", - }, - { - input: "C105", - ptr: new(simplestruct), - error: "rlp: too few elements for rlp.simplestruct", - }, - { - input: "C7C50583343434C0", - ptr: new([]*simplestruct), - error: "rlp: too few elements for rlp.simplestruct, decoding into ([]*rlp.simplestruct)[1]", - }, - { - input: "83222222", - ptr: new(simplestruct), - error: "rlp: expected input list for rlp.simplestruct", - }, - { - input: "C3010101", - ptr: new(simplestruct), - error: "rlp: input list has too many elements for rlp.simplestruct", - }, - { - input: "C501C3C00000", - ptr: new(recstruct), - error: "rlp: expected input string or byte for uint, decoding into (rlp.recstruct).Child.I", - }, - { - input: "C103", - ptr: new(intField), - error: "rlp: type int is not RLP-serializable (struct field rlp.intField.X)", - }, - { - input: "C50102C20102", - ptr: new(tailUint), - error: "rlp: expected input string or byte for uint, decoding into (rlp.tailUint).Tail[1]", - }, - { - input: "C0", - ptr: new(invalidNilTag), - error: `rlp: invalid struct tag "nil" for rlp.invalidNilTag.X (field is not a pointer)`, - }, - - // struct tag "tail" - { - input: "C3010203", - ptr: new(tailRaw), - value: tailRaw{A: 1, Tail: []RawValue{unhex("02"), unhex("03")}}, - }, - { - input: "C20102", - ptr: new(tailRaw), - value: tailRaw{A: 1, Tail: []RawValue{unhex("02")}}, - }, - { - input: "C101", - ptr: new(tailRaw), - value: tailRaw{A: 1, Tail: []RawValue{}}, - }, - { - input: "C3010203", - ptr: new(tailPrivateFields), - value: tailPrivateFields{A: 1, Tail: []uint{2, 3}}, - }, - { - input: "C0", - ptr: new(invalidTail1), - error: `rlp: invalid struct tag "tail" for rlp.invalidTail1.A (must be on last field)`, - }, - { - input: "C0", - ptr: new(invalidTail2), - error: `rlp: invalid struct tag "tail" for rlp.invalidTail2.B (field type is not slice)`, - }, - - // struct tag "-" - { - input: "C20102", - ptr: new(hasIgnoredField), - value: hasIgnoredField{A: 1, C: 2}, - }, - - // struct tag "nilList" - { - input: "C180", - ptr: new(nilListUint), - error: "rlp: wrong kind of empty value (got String, want List) for *uint, decoding into (rlp.nilListUint).X", - }, - { - input: "C1C0", - ptr: new(nilListUint), - value: nilListUint{}, - }, - { - input: "C103", - ptr: new(nilListUint), - value: func() interface{} { - v := uint(3) - return nilListUint{X: &v} - }(), - }, - - // struct tag "nilString" - { - input: "C1C0", - ptr: new(nilStringSlice), - error: "rlp: wrong kind of empty value (got List, want String) for *[]uint, decoding into (rlp.nilStringSlice).X", - }, - { - input: "C180", - ptr: new(nilStringSlice), - value: nilStringSlice{}, - }, - { - input: "C2C103", - ptr: new(nilStringSlice), - value: nilStringSlice{X: &[]uint{3}}, - }, - - // RawValue - {input: "01", ptr: new(RawValue), value: RawValue(unhex("01"))}, - {input: "82FFFF", ptr: new(RawValue), value: RawValue(unhex("82FFFF"))}, - {input: "C20102", ptr: new([]RawValue), value: []RawValue{unhex("01"), unhex("02")}}, - - // pointers - {input: "00", ptr: new(*[]byte), value: &[]byte{0}}, - {input: "80", ptr: new(*uint), value: uintp(0)}, - {input: "C0", ptr: new(*uint), error: "rlp: expected input string or byte for uint"}, - {input: "07", ptr: new(*uint), value: uintp(7)}, - {input: "817F", ptr: new(*uint), error: "rlp: non-canonical size information for uint"}, - {input: "8180", ptr: new(*uint), value: uintp(0x80)}, - {input: "C109", ptr: new(*[]uint), value: &[]uint{9}}, - {input: "C58403030303", ptr: new(*[][]byte), value: &[][]byte{{3, 3, 3, 3}}}, - - // check that input position is advanced also for empty values. - {input: "C3808005", ptr: new([]*uint), value: []*uint{uintp(0), uintp(0), uintp(5)}}, - - // interface{} - {input: "00", ptr: new(interface{}), value: []byte{0}}, - {input: "01", ptr: new(interface{}), value: []byte{1}}, - {input: "80", ptr: new(interface{}), value: []byte{}}, - {input: "850505050505", ptr: new(interface{}), value: []byte{5, 5, 5, 5, 5}}, - {input: "C0", ptr: new(interface{}), value: []interface{}{}}, - {input: "C50183040404", ptr: new(interface{}), value: []interface{}{[]byte{1}, []byte{4, 4, 4}}}, - { - input: "C3010203", - ptr: new([]io.Reader), - error: "rlp: type io.Reader is not RLP-serializable", - }, - - // fuzzer crashes - { - input: "c330f9c030f93030ce3030303030303030bd303030303030", - ptr: new(interface{}), - error: "rlp: element is larger than containing list", - }, -} - -func uintp(i uint) *uint { return &i } - -func runTests(t *testing.T, decode func([]byte, interface{}) error) { - for i, test := range decodeTests { - input, err := hex.DecodeString(test.input) - if err != nil { - t.Errorf("test %d: invalid hex input %q", i, test.input) - continue - } - err = decode(input, test.ptr) - if err != nil && test.error == "" { - t.Errorf("test %d: unexpected Decode error: %v\ndecoding into %T\ninput %q", - i, err, test.ptr, test.input) - continue - } - if test.error != "" && fmt.Sprint(err) != test.error { - t.Errorf("test %d: Decode error mismatch\ngot %v\nwant %v\ndecoding into %T\ninput %q", - i, err, test.error, test.ptr, test.input) - continue - } - deref := reflect.ValueOf(test.ptr).Elem().Interface() - if err == nil && !reflect.DeepEqual(deref, test.value) { - t.Errorf("test %d: value mismatch\ngot %#v\nwant %#v\ndecoding into %T\ninput %q", - i, deref, test.value, test.ptr, test.input) - } - } -} - -func TestDecodeWithByteReader(t *testing.T) { - runTests(t, func(input []byte, into interface{}) error { - return Decode(bytes.NewReader(input), into) - }) -} - -// plainReader reads from a byte slice but does not -// implement ReadByte. It is also not recognized by the -// size validation. This is useful to test how the decoder -// behaves on a non-buffered input stream. -type plainReader []byte - -func newPlainReader(b []byte) io.Reader { - return (*plainReader)(&b) -} - -func (r *plainReader) Read(buf []byte) (n int, err error) { - if len(*r) == 0 { - return 0, io.EOF - } - n = copy(buf, *r) - *r = (*r)[n:] - return n, nil -} - -func TestDecodeWithNonByteReader(t *testing.T) { - runTests(t, func(input []byte, into interface{}) error { - return Decode(newPlainReader(input), into) - }) -} - -func TestDecodeStreamReset(t *testing.T) { - s := NewStream(nil, 0) - runTests(t, func(input []byte, into interface{}) error { - s.Reset(bytes.NewReader(input), 0) - return s.Decode(into) - }) -} - -type testDecoder struct{ called bool } - -func (t *testDecoder) DecodeRLP(s *Stream) error { - if _, err := s.Uint(); err != nil { - return err - } - t.called = true - return nil -} - -func TestDecodeDecoder(t *testing.T) { - var s struct { - T1 testDecoder - T2 *testDecoder - T3 **testDecoder - } - if err := Decode(bytes.NewReader(unhex("C3010203")), &s); err != nil { - t.Fatalf("Decode error: %v", err) - } - - if !s.T1.called { - t.Errorf("DecodeRLP was not called for (non-pointer) testDecoder") - } - - if s.T2 == nil { - t.Errorf("*testDecoder has not been allocated") - } else if !s.T2.called { - t.Errorf("DecodeRLP was not called for *testDecoder") - } - - if s.T3 == nil || *s.T3 == nil { - t.Errorf("**testDecoder has not been allocated") - } else if !(*s.T3).called { - t.Errorf("DecodeRLP was not called for **testDecoder") - } -} - -func TestDecodeDecoderNilPointer(t *testing.T) { - var s struct { - T1 *testDecoder `rlp:"nil"` - T2 *testDecoder - } - if err := Decode(bytes.NewReader(unhex("C2C002")), &s); err != nil { - t.Fatalf("Decode error: %v", err) - } - if s.T1 != nil { - t.Errorf("decoder T1 allocated for empty input (called: %v)", s.T1.called) - } - if s.T2 == nil || !s.T2.called { - t.Errorf("decoder T2 not allocated/called") - } -} - -type byteDecoder byte - -func (bd *byteDecoder) DecodeRLP(s *Stream) error { - _, err := s.Uint() - *bd = 255 - return err -} - -func (bd byteDecoder) called() bool { - return bd == 255 -} - -// This test verifies that the byte slice/byte array logic -// does not kick in for element types implementing Decoder. -func TestDecoderInByteSlice(t *testing.T) { - var slice []byteDecoder - if err := Decode(bytes.NewReader(unhex("C101")), &slice); err != nil { - t.Errorf("unexpected Decode error %v", err) - } else if !slice[0].called() { - t.Errorf("DecodeRLP not called for slice element") - } - - var array [1]byteDecoder - if err := Decode(bytes.NewReader(unhex("C101")), &array); err != nil { - t.Errorf("unexpected Decode error %v", err) - } else if !array[0].called() { - t.Errorf("DecodeRLP not called for array element") - } -} - -type unencodableDecoder func() - -func (f *unencodableDecoder) DecodeRLP(s *Stream) error { - if _, err := s.List(); err != nil { - return err - } - if err := s.ListEnd(); err != nil { - return err - } - *f = func() {} - return nil -} - -func TestDecoderFunc(t *testing.T) { - var x func() - if err := DecodeBytes([]byte{0xC0}, (*unencodableDecoder)(&x)); err != nil { - t.Fatal(err) - } - x() -} - -func ExampleDecode() { - input, _ := hex.DecodeString("C90A1486666F6F626172") - - type example struct { - A, B uint - String string - } - - var s example - err := Decode(bytes.NewReader(input), &s) - if err != nil { - fmt.Printf("Error: %v\n", err) - } else { - fmt.Printf("Decoded value: %#v\n", s) - } - // Output: - // Decoded value: rlp.example{A:0xa, B:0x14, String:"foobar"} -} - -func ExampleDecode_structTagNil() { - // In this example, we'll use the "nil" struct tag to change - // how a pointer-typed field is decoded. The input contains an RLP - // list of one element, an empty string. - input := []byte{0xC1, 0x80} - - // This type uses the normal rules. - // The empty input string is decoded as a pointer to an empty Go string. - var normalRules struct { - String *string - } - Decode(bytes.NewReader(input), &normalRules) - fmt.Printf("normal: String = %q\n", *normalRules.String) - - // This type uses the struct tag. - // The empty input string is decoded as a nil pointer. - var withEmptyOK struct { - String *string `rlp:"nil"` - } - Decode(bytes.NewReader(input), &withEmptyOK) - fmt.Printf("with nil tag: String = %v\n", withEmptyOK.String) - - // Output: - // normal: String = "" - // with nil tag: String = -} - -func ExampleStream() { - input, _ := hex.DecodeString("C90A1486666F6F626172") - s := NewStream(bytes.NewReader(input), 0) - - // Check what kind of value lies ahead - kind, size, _ := s.Kind() - fmt.Printf("Kind: %v size:%d\n", kind, size) - - // Enter the list - if _, err := s.List(); err != nil { - fmt.Printf("List error: %v\n", err) - return - } - - // Decode elements - fmt.Println(s.Uint()) - fmt.Println(s.Uint()) - fmt.Println(s.Bytes()) - - // Acknowledge end of list - if err := s.ListEnd(); err != nil { - fmt.Printf("ListEnd error: %v\n", err) - } - // Output: - // Kind: List size:9 - // 10 - // 20 - // [102 111 111 98 97 114] -} - -func BenchmarkDecode(b *testing.B) { - enc := encodeTestSlice(90000) - b.SetBytes(int64(len(enc))) - b.ReportAllocs() - b.ResetTimer() - - for i := 0; i < b.N; i++ { - var s []uint - r := bytes.NewReader(enc) - if err := Decode(r, &s); err != nil { - b.Fatalf("Decode error: %v", err) - } - } -} - -func BenchmarkDecodeIntSliceReuse(b *testing.B) { - enc := encodeTestSlice(100000) - b.SetBytes(int64(len(enc))) - b.ReportAllocs() - b.ResetTimer() - - var s []uint - for i := 0; i < b.N; i++ { - r := bytes.NewReader(enc) - if err := Decode(r, &s); err != nil { - b.Fatalf("Decode error: %v", err) - } - } -} - -func encodeTestSlice(n uint) []byte { - s := make([]uint, n) - for i := uint(0); i < n; i++ { - s[i] = i - } - b, err := EncodeToBytes(s) - if err != nil { - panic(fmt.Sprintf("encode error: %v", err)) - } - return b -} - -func unhex(str string) []byte { - b, err := hex.DecodeString(strings.Replace(str, " ", "", -1)) - if err != nil { - panic(fmt.Sprintf("invalid hex string: %q", str)) - } - return b -} diff --git a/common/rlp/doc.go b/common/rlp/doc.go deleted file mode 100644 index 7e6ee852..00000000 --- a/common/rlp/doc.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2014 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -/* -Package rlp implements the RLP serialization format. - -The purpose of RLP (Recursive Linear Prefix) is to encode arbitrarily nested arrays of -binary data, and RLP is the main encoding method used to serialize objects in Ethereum. -The only purpose of RLP is to encode structure; encoding specific atomic data types (eg. -strings, ints, floats) is left up to higher-order protocols. In Ethereum integers must be -represented in big endian binary form with no leading zeroes (thus making the integer -value zero equivalent to the empty string). - -RLP values are distinguished by a type tag. The type tag precedes the value in the input -stream and defines the size and kind of the bytes that follow. - - -Encoding Rules - -Package rlp uses reflection and encodes RLP based on the Go type of the value. - -If the type implements the Encoder interface, Encode calls EncodeRLP. It does not -call EncodeRLP on nil pointer values. - -To encode a pointer, the value being pointed to is encoded. A nil pointer to a struct -type, slice or array always encodes as an empty RLP list unless the slice or array has -elememt type byte. A nil pointer to any other value encodes as the empty string. - -Struct values are encoded as an RLP list of all their encoded public fields. Recursive -struct types are supported. - -To encode slices and arrays, the elements are encoded as an RLP list of the value's -elements. Note that arrays and slices with element type uint8 or byte are always encoded -as an RLP string. - -A Go string is encoded as an RLP string. - -An unsigned integer value is encoded as an RLP string. Zero always encodes as an empty RLP -string. big.Int values are treated as integers. Signed integers (int, int8, int16, ...) -are not supported and will return an error when encoding. - -Boolean values are encoded as the unsigned integers zero (false) and one (true). - -An interface value encodes as the value contained in the interface. - -Floating point numbers, maps, channels and functions are not supported. - - -Decoding Rules - -Decoding uses the following type-dependent rules: - -If the type implements the Decoder interface, DecodeRLP is called. - -To decode into a pointer, the value will be decoded as the element type of the pointer. If -the pointer is nil, a new value of the pointer's element type is allocated. If the pointer -is non-nil, the existing value will be reused. Note that package rlp never leaves a -pointer-type struct field as nil unless one of the "nil" struct tags is present. - -To decode into a struct, decoding expects the input to be an RLP list. The decoded -elements of the list are assigned to each public field in the order given by the struct's -definition. The input list must contain an element for each decoded field. Decoding -returns an error if there are too few or too many elements for the struct. - -To decode into a slice, the input must be a list and the resulting slice will contain the -input elements in order. For byte slices, the input must be an RLP string. Array types -decode similarly, with the additional restriction that the number of input elements (or -bytes) must match the array's defined length. - -To decode into a Go string, the input must be an RLP string. The input bytes are taken -as-is and will not necessarily be valid UTF-8. - -To decode into an unsigned integer type, the input must also be an RLP string. The bytes -are interpreted as a big endian representation of the integer. If the RLP string is larger -than the bit size of the type, decoding will return an error. Decode also supports -*big.Int. There is no size limit for big integers. - -To decode into a boolean, the input must contain an unsigned integer of value zero (false) -or one (true). - -To decode into an interface value, one of these types is stored in the value: - - []interface{}, for RLP lists - []byte, for RLP strings - -Non-empty interface types are not supported when decoding. -Signed integers, floating point numbers, maps, channels and functions cannot be decoded into. - - -Struct Tags - -Package rlp honours certain struct tags: "-", "tail", "nil", "nilList" and "nilString". - -The "-" tag ignores fields. - -The "tail" tag, which may only be used on the last exported struct field, allows slurping -up any excess list elements into a slice. See examples for more details. - -The "nil" tag applies to pointer-typed fields and changes the decoding rules for the field -such that input values of size zero decode as a nil pointer. This tag can be useful when -decoding recursive types. - - type StructWithOptionalFoo struct { - Foo *[20]byte `rlp:"nil"` - } - -RLP supports two kinds of empty values: empty lists and empty strings. When using the -"nil" tag, the kind of empty value allowed for a type is chosen automatically. A struct -field whose Go type is a pointer to an unsigned integer, string, boolean or byte -array/slice expects an empty RLP string. Any other pointer field type encodes/decodes as -an empty RLP list. - -The choice of null value can be made explicit with the "nilList" and "nilString" struct -tags. Using these tags encodes/decodes a Go nil pointer value as the kind of empty -RLP value defined by the tag. -*/ -package rlp diff --git a/common/rlp/encode.go b/common/rlp/encode.go deleted file mode 100644 index 9c9e8d70..00000000 --- a/common/rlp/encode.go +++ /dev/null @@ -1,612 +0,0 @@ -// Copyright 2014 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package rlp - -import ( - "fmt" - "io" - "math/big" - "reflect" - "sync" -) - -var ( - // Common encoded values. - // These are useful when implementing EncodeRLP. - EmptyString = []byte{0x80} - EmptyList = []byte{0xC0} -) - -// Encoder is implemented by types that require custom -// encoding rules or want to encode private fields. -type Encoder interface { - // EncodeRLP should write the RLP encoding of its receiver to w. - // If the implementation is a pointer method, it may also be - // called for nil pointers. - // - // Implementations should generate valid RLP. The data written is - // not verified at the moment, but a future version might. It is - // recommended to write only a single value but writing multiple - // values or no value at all is also permitted. - EncodeRLP(io.Writer) error -} - -// Encode writes the RLP encoding of val to w. Note that Encode may -// perform many small writes in some cases. Consider making w -// buffered. -// -// Please see package-level documentation of encoding rules. -func Encode(w io.Writer, val interface{}) error { - if outer, ok := w.(*encbuf); ok { - // Encode was called by some type's EncodeRLP. - // Avoid copying by writing to the outer encbuf directly. - return outer.encode(val) - } - eb := encbufPool.Get().(*encbuf) - defer encbufPool.Put(eb) - eb.reset() - if err := eb.encode(val); err != nil { - return err - } - return eb.toWriter(w) -} - -// EncodeToBytes returns the RLP encoding of val. -// Please see package-level documentation for the encoding rules. -func EncodeToBytes(val interface{}) ([]byte, error) { - eb := encbufPool.Get().(*encbuf) - defer encbufPool.Put(eb) - eb.reset() - if err := eb.encode(val); err != nil { - return nil, err - } - return eb.toBytes(), nil -} - -// EncodeToReader returns a reader from which the RLP encoding of val -// can be read. The returned size is the total size of the encoded -// data. -// -// Please see the documentation of Encode for the encoding rules. -func EncodeToReader(val interface{}) (size int, r io.Reader, err error) { - eb := encbufPool.Get().(*encbuf) - eb.reset() - if err := eb.encode(val); err != nil { - return 0, nil, err - } - return eb.size(), &encReader{buf: eb}, nil -} - -type encbuf struct { - str []byte // string data, contains everything except list headers - lheads []*listhead // all list headers - lhsize int // sum of sizes of all encoded list headers - sizebuf []byte // 9-byte auxiliary buffer for uint encoding -} - -type listhead struct { - offset int // index of this header in string data - size int // total size of encoded data (including list headers) -} - -// encode writes head to the given buffer, which must be at least -// 9 bytes long. It returns the encoded bytes. -func (head *listhead) encode(buf []byte) []byte { - return buf[:puthead(buf, 0xC0, 0xF7, uint64(head.size))] -} - -// headsize returns the size of a list or string header -// for a value of the given size. -func headsize(size uint64) int { - if size < 56 { - return 1 - } - return 1 + intsize(size) -} - -// puthead writes a list or string header to buf. -// buf must be at least 9 bytes long. -func puthead(buf []byte, smalltag, largetag byte, size uint64) int { - if size < 56 { - buf[0] = smalltag + byte(size) - return 1 - } - sizesize := putint(buf[1:], size) - buf[0] = largetag + byte(sizesize) - return sizesize + 1 -} - -// encbufs are pooled. -var encbufPool = sync.Pool{ - New: func() interface{} { return &encbuf{sizebuf: make([]byte, 9)} }, -} - -func (w *encbuf) reset() { - w.lhsize = 0 - if w.str != nil { - w.str = w.str[:0] - } - if w.lheads != nil { - w.lheads = w.lheads[:0] - } -} - -// encbuf implements io.Writer so it can be passed it into EncodeRLP. -func (w *encbuf) Write(b []byte) (int, error) { - w.str = append(w.str, b...) - return len(b), nil -} - -func (w *encbuf) encode(val interface{}) error { - rval := reflect.ValueOf(val) - writer, err := cachedWriter(rval.Type()) - if err != nil { - return err - } - return writer(rval, w) -} - -func (w *encbuf) encodeStringHeader(size int) { - if size < 56 { - w.str = append(w.str, 0x80+byte(size)) - } else { - // TODO: encode to w.str directly - sizesize := putint(w.sizebuf[1:], uint64(size)) - w.sizebuf[0] = 0xB7 + byte(sizesize) - w.str = append(w.str, w.sizebuf[:sizesize+1]...) - } -} - -func (w *encbuf) encodeString(b []byte) { - if len(b) == 1 && b[0] <= 0x7F { - // fits single byte, no string header - w.str = append(w.str, b[0]) - } else { - w.encodeStringHeader(len(b)) - w.str = append(w.str, b...) - } -} - -func (w *encbuf) list() *listhead { - lh := &listhead{offset: len(w.str), size: w.lhsize} - w.lheads = append(w.lheads, lh) - return lh -} - -func (w *encbuf) listEnd(lh *listhead) { - lh.size = w.size() - lh.offset - lh.size - if lh.size < 56 { - w.lhsize++ // length encoded into kind tag - } else { - w.lhsize += 1 + intsize(uint64(lh.size)) - } -} - -func (w *encbuf) size() int { - return len(w.str) + w.lhsize -} - -func (w *encbuf) toBytes() []byte { - out := make([]byte, w.size()) - strpos := 0 - pos := 0 - for _, head := range w.lheads { - // write string data before header - n := copy(out[pos:], w.str[strpos:head.offset]) - pos += n - strpos += n - // write the header - enc := head.encode(out[pos:]) - pos += len(enc) - } - // copy string data after the last list header - copy(out[pos:], w.str[strpos:]) - return out -} - -func (w *encbuf) toWriter(out io.Writer) (err error) { - strpos := 0 - for _, head := range w.lheads { - // write string data before header - if head.offset-strpos > 0 { - n, err := out.Write(w.str[strpos:head.offset]) - strpos += n - if err != nil { - return err - } - } - // write the header - enc := head.encode(w.sizebuf) - if _, err = out.Write(enc); err != nil { - return err - } - } - if strpos < len(w.str) { - // write string data after the last list header - _, err = out.Write(w.str[strpos:]) - } - return err -} - -// encReader is the io.Reader returned by EncodeToReader. -// It releases its encbuf at EOF. -type encReader struct { - buf *encbuf // the buffer we're reading from. this is nil when we're at EOF. - lhpos int // index of list header that we're reading - strpos int // current position in string buffer - piece []byte // next piece to be read -} - -func (r *encReader) Read(b []byte) (n int, err error) { - for { - if r.piece = r.next(); r.piece == nil { - // Put the encode buffer back into the pool at EOF when it - // is first encountered. Subsequent calls still return EOF - // as the error but the buffer is no longer valid. - if r.buf != nil { - encbufPool.Put(r.buf) - r.buf = nil - } - return n, io.EOF - } - nn := copy(b[n:], r.piece) - n += nn - if nn < len(r.piece) { - // piece didn't fit, see you next time. - r.piece = r.piece[nn:] - return n, nil - } - r.piece = nil - } -} - -// next returns the next piece of data to be read. -// it returns nil at EOF. -func (r *encReader) next() []byte { - switch { - case r.buf == nil: - return nil - - case r.piece != nil: - // There is still data available for reading. - return r.piece - - case r.lhpos < len(r.buf.lheads): - // We're before the last list header. - head := r.buf.lheads[r.lhpos] - sizebefore := head.offset - r.strpos - if sizebefore > 0 { - // String data before header. - p := r.buf.str[r.strpos:head.offset] - r.strpos += sizebefore - return p - } - r.lhpos++ - return head.encode(r.buf.sizebuf) - - case r.strpos < len(r.buf.str): - // String data at the end, after all list headers. - p := r.buf.str[r.strpos:] - r.strpos = len(r.buf.str) - return p - - default: - return nil - } -} - -var ( - encoderInterface = reflect.TypeOf(new(Encoder)).Elem() - big0 = big.NewInt(0) -) - -// makeWriter creates a writer function for the given type. -func makeWriter(typ reflect.Type, ts tags) (writer, error) { - kind := typ.Kind() - switch { - case typ == rawValueType: - return writeRawValue, nil - case typ.AssignableTo(reflect.PtrTo(bigInt)): - return writeBigIntPtr, nil - case typ.AssignableTo(bigInt): - return writeBigIntNoPtr, nil - case kind == reflect.Ptr: - return makePtrWriter(typ, ts) - case reflect.PtrTo(typ).Implements(encoderInterface): - return makeEncoderWriter(typ), nil - case isUint(kind): - return writeUint, nil - case kind == reflect.Bool: - return writeBool, nil - case kind == reflect.String: - return writeString, nil - case kind == reflect.Slice && isByte(typ.Elem()): - return writeBytes, nil - case kind == reflect.Array && isByte(typ.Elem()): - return writeByteArray, nil - case kind == reflect.Slice || kind == reflect.Array: - return makeSliceWriter(typ, ts) - case kind == reflect.Struct: - return makeStructWriter(typ) - case kind == reflect.Interface: - return writeInterface, nil - default: - return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ) - } -} - -func isByte(typ reflect.Type) bool { - return typ.Kind() == reflect.Uint8 && !typ.Implements(encoderInterface) -} - -func writeRawValue(val reflect.Value, w *encbuf) error { - w.str = append(w.str, val.Bytes()...) - return nil -} - -func writeUint(val reflect.Value, w *encbuf) error { - i := val.Uint() - if i == 0 { - w.str = append(w.str, 0x80) - } else if i < 128 { - // fits single byte - w.str = append(w.str, byte(i)) - } else { - // TODO: encode int to w.str directly - s := putint(w.sizebuf[1:], i) - w.sizebuf[0] = 0x80 + byte(s) - w.str = append(w.str, w.sizebuf[:s+1]...) - } - return nil -} - -func writeBool(val reflect.Value, w *encbuf) error { - if val.Bool() { - w.str = append(w.str, 0x01) - } else { - w.str = append(w.str, 0x80) - } - return nil -} - -func writeBigIntPtr(val reflect.Value, w *encbuf) error { - ptr := val.Interface().(*big.Int) - if ptr == nil { - w.str = append(w.str, 0x80) - return nil - } - return writeBigInt(ptr, w) -} - -func writeBigIntNoPtr(val reflect.Value, w *encbuf) error { - i := val.Interface().(big.Int) - return writeBigInt(&i, w) -} - -func writeBigInt(i *big.Int, w *encbuf) error { - if cmp := i.Cmp(big0); cmp == -1 { - return fmt.Errorf("rlp: cannot encode negative *big.Int") - } else if cmp == 0 { - w.str = append(w.str, 0x80) - } else { - w.encodeString(i.Bytes()) - } - return nil -} - -func writeBytes(val reflect.Value, w *encbuf) error { - w.encodeString(val.Bytes()) - return nil -} - -func writeByteArray(val reflect.Value, w *encbuf) error { - if !val.CanAddr() { - // Slice requires the value to be addressable. - // Make it addressable by copying. - copy := reflect.New(val.Type()).Elem() - copy.Set(val) - val = copy - } - size := val.Len() - slice := val.Slice(0, size).Bytes() - w.encodeString(slice) - return nil -} - -func writeString(val reflect.Value, w *encbuf) error { - s := val.String() - if len(s) == 1 && s[0] <= 0x7f { - // fits single byte, no string header - w.str = append(w.str, s[0]) - } else { - w.encodeStringHeader(len(s)) - w.str = append(w.str, s...) - } - return nil -} - -func writeInterface(val reflect.Value, w *encbuf) error { - if val.IsNil() { - // Write empty list. This is consistent with the previous RLP - // encoder that we had and should therefore avoid any - // problems. - w.str = append(w.str, 0xC0) - return nil - } - eval := val.Elem() - writer, err := cachedWriter(eval.Type()) - if err != nil { - return err - } - return writer(eval, w) -} - -func makeSliceWriter(typ reflect.Type, ts tags) (writer, error) { - etypeinfo := cachedTypeInfo1(typ.Elem(), tags{}) - if etypeinfo.writerErr != nil { - return nil, etypeinfo.writerErr - } - writer := func(val reflect.Value, w *encbuf) error { - if !ts.tail { - defer w.listEnd(w.list()) - } - vlen := val.Len() - for i := 0; i < vlen; i++ { - if err := etypeinfo.writer(val.Index(i), w); err != nil { - return err - } - } - return nil - } - return writer, nil -} - -func makeStructWriter(typ reflect.Type) (writer, error) { - fields, err := structFields(typ) - if err != nil { - return nil, err - } - for _, f := range fields { - if f.info.writerErr != nil { - return nil, structFieldError{typ, f.index, f.info.writerErr} - } - } - writer := func(val reflect.Value, w *encbuf) error { - lh := w.list() - for _, f := range fields { - if err := f.info.writer(val.Field(f.index), w); err != nil { - return err - } - } - w.listEnd(lh) - return nil - } - return writer, nil -} - -func makePtrWriter(typ reflect.Type, ts tags) (writer, error) { - etypeinfo := cachedTypeInfo1(typ.Elem(), tags{}) - if etypeinfo.writerErr != nil { - return nil, etypeinfo.writerErr - } - // Determine how to encode nil pointers. - var nilKind Kind - if ts.nilOK { - nilKind = ts.nilKind // use struct tag if provided - } else { - nilKind = defaultNilKind(typ.Elem()) - } - - writer := func(val reflect.Value, w *encbuf) error { - if val.IsNil() { - if nilKind == String { - w.str = append(w.str, 0x80) - } else { - w.listEnd(w.list()) - } - return nil - } - return etypeinfo.writer(val.Elem(), w) - } - return writer, nil -} - -func makeEncoderWriter(typ reflect.Type) writer { - if typ.Implements(encoderInterface) { - return func(val reflect.Value, w *encbuf) error { - return val.Interface().(Encoder).EncodeRLP(w) - } - } - w := func(val reflect.Value, w *encbuf) error { - if !val.CanAddr() { - // package json simply doesn't call MarshalJSON for this case, but encodes the - // value as if it didn't implement the interface. We don't want to handle it that - // way. - return fmt.Errorf("rlp: unadressable value of type %v, EncodeRLP is pointer method", val.Type()) - } - return val.Addr().Interface().(Encoder).EncodeRLP(w) - } - return w -} - -// putint writes i to the beginning of b in big endian byte -// order, using the least number of bytes needed to represent i. -func putint(b []byte, i uint64) (size int) { - switch { - case i < (1 << 8): - b[0] = byte(i) - return 1 - case i < (1 << 16): - b[0] = byte(i >> 8) - b[1] = byte(i) - return 2 - case i < (1 << 24): - b[0] = byte(i >> 16) - b[1] = byte(i >> 8) - b[2] = byte(i) - return 3 - case i < (1 << 32): - b[0] = byte(i >> 24) - b[1] = byte(i >> 16) - b[2] = byte(i >> 8) - b[3] = byte(i) - return 4 - case i < (1 << 40): - b[0] = byte(i >> 32) - b[1] = byte(i >> 24) - b[2] = byte(i >> 16) - b[3] = byte(i >> 8) - b[4] = byte(i) - return 5 - case i < (1 << 48): - b[0] = byte(i >> 40) - b[1] = byte(i >> 32) - b[2] = byte(i >> 24) - b[3] = byte(i >> 16) - b[4] = byte(i >> 8) - b[5] = byte(i) - return 6 - case i < (1 << 56): - b[0] = byte(i >> 48) - b[1] = byte(i >> 40) - b[2] = byte(i >> 32) - b[3] = byte(i >> 24) - b[4] = byte(i >> 16) - b[5] = byte(i >> 8) - b[6] = byte(i) - return 7 - default: - b[0] = byte(i >> 56) - b[1] = byte(i >> 48) - b[2] = byte(i >> 40) - b[3] = byte(i >> 32) - b[4] = byte(i >> 24) - b[5] = byte(i >> 16) - b[6] = byte(i >> 8) - b[7] = byte(i) - return 8 - } -} - -// intsize computes the minimum number of bytes required to store i. -func intsize(i uint64) (size int) { - for size = 1; ; size++ { - if i >>= 8; i == 0 { - return size - } - } -} diff --git a/common/rlp/encode_test.go b/common/rlp/encode_test.go deleted file mode 100644 index b4b9e512..00000000 --- a/common/rlp/encode_test.go +++ /dev/null @@ -1,403 +0,0 @@ -// Copyright 2014 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package rlp - -import ( - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "math/big" - "sync" - "testing" -) - -type testEncoder struct { - err error -} - -func (e *testEncoder) EncodeRLP(w io.Writer) error { - if e == nil { - panic("EncodeRLP called on nil value") - } - if e.err != nil { - return e.err - } else { - w.Write([]byte{0, 1, 0, 1, 0, 1, 0, 1, 0, 1}) - } - return nil -} - -type testEncoderValueMethod struct{} - -func (e testEncoderValueMethod) EncodeRLP(w io.Writer) error { - w.Write([]byte{0xFA, 0xFE, 0xF0}) - return nil -} - -type byteEncoder byte - -func (e byteEncoder) EncodeRLP(w io.Writer) error { - w.Write(EmptyList) - return nil -} - -type undecodableEncoder func() - -func (f undecodableEncoder) EncodeRLP(w io.Writer) error { - w.Write([]byte{0xF5, 0xF5, 0xF5}) - return nil -} - -type encodableReader struct { - A, B uint -} - -func (e *encodableReader) Read(b []byte) (int, error) { - panic("called") -} - -type namedByteType byte - -var ( - _ = Encoder(&testEncoder{}) - _ = Encoder(byteEncoder(0)) - - reader io.Reader = &encodableReader{1, 2} -) - -type encTest struct { - val interface{} - output, error string -} - -var encTests = []encTest{ - // booleans - {val: true, output: "01"}, - {val: false, output: "80"}, - - // integers - {val: uint32(0), output: "80"}, - {val: uint32(127), output: "7F"}, - {val: uint32(128), output: "8180"}, - {val: uint32(256), output: "820100"}, - {val: uint32(1024), output: "820400"}, - {val: uint32(0xFFFFFF), output: "83FFFFFF"}, - {val: uint32(0xFFFFFFFF), output: "84FFFFFFFF"}, - {val: uint64(0xFFFFFFFF), output: "84FFFFFFFF"}, - {val: uint64(0xFFFFFFFFFF), output: "85FFFFFFFFFF"}, - {val: uint64(0xFFFFFFFFFFFF), output: "86FFFFFFFFFFFF"}, - {val: uint64(0xFFFFFFFFFFFFFF), output: "87FFFFFFFFFFFFFF"}, - {val: uint64(0xFFFFFFFFFFFFFFFF), output: "88FFFFFFFFFFFFFFFF"}, - - // big integers (should match uint for small values) - {val: big.NewInt(0), output: "80"}, - {val: big.NewInt(1), output: "01"}, - {val: big.NewInt(127), output: "7F"}, - {val: big.NewInt(128), output: "8180"}, - {val: big.NewInt(256), output: "820100"}, - {val: big.NewInt(1024), output: "820400"}, - {val: big.NewInt(0xFFFFFF), output: "83FFFFFF"}, - {val: big.NewInt(0xFFFFFFFF), output: "84FFFFFFFF"}, - {val: big.NewInt(0xFFFFFFFFFF), output: "85FFFFFFFFFF"}, - {val: big.NewInt(0xFFFFFFFFFFFF), output: "86FFFFFFFFFFFF"}, - {val: big.NewInt(0xFFFFFFFFFFFFFF), output: "87FFFFFFFFFFFFFF"}, - { - val: big.NewInt(0).SetBytes(unhex("102030405060708090A0B0C0D0E0F2")), - output: "8F102030405060708090A0B0C0D0E0F2", - }, - { - val: big.NewInt(0).SetBytes(unhex("0100020003000400050006000700080009000A000B000C000D000E01")), - output: "9C0100020003000400050006000700080009000A000B000C000D000E01", - }, - { - val: big.NewInt(0).SetBytes(unhex("010000000000000000000000000000000000000000000000000000000000000000")), - output: "A1010000000000000000000000000000000000000000000000000000000000000000", - }, - - // non-pointer big.Int - {val: *big.NewInt(0), output: "80"}, - {val: *big.NewInt(0xFFFFFF), output: "83FFFFFF"}, - - // negative ints are not supported - {val: big.NewInt(-1), error: "rlp: cannot encode negative *big.Int"}, - - // byte slices, strings - {val: []byte{}, output: "80"}, - {val: []byte{0x7E}, output: "7E"}, - {val: []byte{0x7F}, output: "7F"}, - {val: []byte{0x80}, output: "8180"}, - {val: []byte{1, 2, 3}, output: "83010203"}, - - {val: []namedByteType{1, 2, 3}, output: "83010203"}, - {val: [...]namedByteType{1, 2, 3}, output: "83010203"}, - - {val: "", output: "80"}, - {val: "\x7E", output: "7E"}, - {val: "\x7F", output: "7F"}, - {val: "\x80", output: "8180"}, - {val: "dog", output: "83646F67"}, - { - val: "Lorem ipsum dolor sit amet, consectetur adipisicing eli", - output: "B74C6F72656D20697073756D20646F6C6F722073697420616D65742C20636F6E7365637465747572206164697069736963696E6720656C69", - }, - { - val: "Lorem ipsum dolor sit amet, consectetur adipisicing elit", - output: "B8384C6F72656D20697073756D20646F6C6F722073697420616D65742C20636F6E7365637465747572206164697069736963696E6720656C6974", - }, - { - val: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur mauris magna, suscipit sed vehicula non, iaculis faucibus tortor. Proin suscipit ultricies malesuada. Duis tortor elit, dictum quis tristique eu, ultrices at risus. Morbi a est imperdiet mi ullamcorper aliquet suscipit nec lorem. Aenean quis leo mollis, vulputate elit varius, consequat enim. Nulla ultrices turpis justo, et posuere urna consectetur nec. Proin non convallis metus. Donec tempor ipsum in mauris congue sollicitudin. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse convallis sem vel massa faucibus, eget lacinia lacus tempor. Nulla quis ultricies purus. Proin auctor rhoncus nibh condimentum mollis. Aliquam consequat enim at metus luctus, a eleifend purus egestas. Curabitur at nibh metus. Nam bibendum, neque at auctor tristique, lorem libero aliquet arcu, non interdum tellus lectus sit amet eros. Cras rhoncus, metus ac ornare cursus, dolor justo ultrices metus, at ullamcorper volutpat", - output: "B904004C6F72656D20697073756D20646F6C6F722073697420616D65742C20636F6E73656374657475722061646970697363696E6720656C69742E20437572616269747572206D6175726973206D61676E612C20737573636970697420736564207665686963756C61206E6F6E2C20696163756C697320666175636962757320746F72746F722E2050726F696E20737573636970697420756C74726963696573206D616C6573756164612E204475697320746F72746F7220656C69742C2064696374756D2071756973207472697374697175652065752C20756C7472696365732061742072697375732E204D6F72626920612065737420696D70657264696574206D6920756C6C616D636F7270657220616C6971756574207375736369706974206E6563206C6F72656D2E2041656E65616E2071756973206C656F206D6F6C6C69732C2076756C70757461746520656C6974207661726975732C20636F6E73657175617420656E696D2E204E756C6C6120756C74726963657320747572706973206A7573746F2C20657420706F73756572652075726E6120636F6E7365637465747572206E65632E2050726F696E206E6F6E20636F6E76616C6C6973206D657475732E20446F6E65632074656D706F7220697073756D20696E206D617572697320636F6E67756520736F6C6C696369747564696E2E20566573746962756C756D20616E746520697073756D207072696D697320696E206661756369627573206F726369206C756374757320657420756C74726963657320706F737565726520637562696C69612043757261653B2053757370656E646973736520636F6E76616C6C69732073656D2076656C206D617373612066617563696275732C2065676574206C6163696E6961206C616375732074656D706F722E204E756C6C61207175697320756C747269636965732070757275732E2050726F696E20617563746F722072686F6E637573206E69626820636F6E64696D656E74756D206D6F6C6C69732E20416C697175616D20636F6E73657175617420656E696D206174206D65747573206C75637475732C206120656C656966656E6420707572757320656765737461732E20437572616269747572206174206E696268206D657475732E204E616D20626962656E64756D2C206E6571756520617420617563746F72207472697374697175652C206C6F72656D206C696265726F20616C697175657420617263752C206E6F6E20696E74657264756D2074656C6C7573206C65637475732073697420616D65742065726F732E20437261732072686F6E6375732C206D65747573206163206F726E617265206375727375732C20646F6C6F72206A7573746F20756C747269636573206D657475732C20617420756C6C616D636F7270657220766F6C7574706174", - }, - - // slices - {val: []uint{}, output: "C0"}, - {val: []uint{1, 2, 3}, output: "C3010203"}, - { - // [ [], [[]], [ [], [[]] ] ] - val: []interface{}{[]interface{}{}, [][]interface{}{{}}, []interface{}{[]interface{}{}, [][]interface{}{{}}}}, - output: "C7C0C1C0C3C0C1C0", - }, - { - val: []string{"aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk", "lll", "mmm", "nnn", "ooo"}, - output: "F83C836161618362626283636363836464648365656583666666836767678368686883696969836A6A6A836B6B6B836C6C6C836D6D6D836E6E6E836F6F6F", - }, - { - val: []interface{}{uint(1), uint(0xFFFFFF), []interface{}{[]uint{4, 5, 5}}, "abc"}, - output: "CE0183FFFFFFC4C304050583616263", - }, - { - val: [][]string{ - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - {"asdf", "qwer", "zxcv"}, - }, - output: "F90200CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376", - }, - - // RawValue - {val: RawValue(unhex("01")), output: "01"}, - {val: RawValue(unhex("82FFFF")), output: "82FFFF"}, - {val: []RawValue{unhex("01"), unhex("02")}, output: "C20102"}, - - // structs - {val: simplestruct{}, output: "C28080"}, - {val: simplestruct{A: 3, B: "foo"}, output: "C50383666F6F"}, - {val: &recstruct{5, nil}, output: "C205C0"}, - {val: &recstruct{5, &recstruct{4, &recstruct{3, nil}}}, output: "C605C404C203C0"}, - {val: &tailRaw{A: 1, Tail: []RawValue{unhex("02"), unhex("03")}}, output: "C3010203"}, - {val: &tailRaw{A: 1, Tail: []RawValue{unhex("02")}}, output: "C20102"}, - {val: &tailRaw{A: 1, Tail: []RawValue{}}, output: "C101"}, - {val: &tailRaw{A: 1, Tail: nil}, output: "C101"}, - {val: &hasIgnoredField{A: 1, B: 2, C: 3}, output: "C20103"}, - {val: &intField{X: 3}, error: "rlp: type int is not RLP-serializable (struct field rlp.intField.X)"}, - - // nil - {val: (*uint)(nil), output: "80"}, - {val: (*string)(nil), output: "80"}, - {val: (*[]byte)(nil), output: "80"}, - {val: (*[10]byte)(nil), output: "80"}, - {val: (*big.Int)(nil), output: "80"}, - {val: (*[]string)(nil), output: "C0"}, - {val: (*[10]string)(nil), output: "C0"}, - {val: (*[]interface{})(nil), output: "C0"}, - {val: (*[]struct{ uint })(nil), output: "C0"}, - {val: (*interface{})(nil), output: "C0"}, - - // nil struct fields - { - val: struct { - X *[]byte - }{}, - output: "C180", - }, - { - val: struct { - X *[2]byte - }{}, - output: "C180", - }, - { - val: struct { - X *uint64 - }{}, - output: "C180", - }, - { - val: struct { - X *uint64 `rlp:"nilList"` - }{}, - output: "C1C0", - }, - { - val: struct { - X *[]uint64 - }{}, - output: "C1C0", - }, - { - val: struct { - X *[]uint64 `rlp:"nilString"` - }{}, - output: "C180", - }, - - // interfaces - {val: []io.Reader{reader}, output: "C3C20102"}, // the contained value is a struct - - // Encoder - {val: (*testEncoder)(nil), output: "C0"}, - {val: &testEncoder{}, output: "00010001000100010001"}, - {val: &testEncoder{errors.New("test error")}, error: "test error"}, - {val: struct{ E testEncoderValueMethod }{}, output: "C3FAFEF0"}, - {val: struct{ E *testEncoderValueMethod }{}, output: "C1C0"}, - - // Verify that the Encoder interface works for unsupported types like func(). - {val: undecodableEncoder(func() {}), output: "F5F5F5"}, - - // Verify that pointer method testEncoder.EncodeRLP is called for - // addressable non-pointer values. - {val: &struct{ TE testEncoder }{testEncoder{}}, output: "CA00010001000100010001"}, - {val: &struct{ TE testEncoder }{testEncoder{errors.New("test error")}}, error: "test error"}, - - // Verify the error for non-addressable non-pointer Encoder. - {val: testEncoder{}, error: "rlp: unadressable value of type rlp.testEncoder, EncodeRLP is pointer method"}, - - // Verify Encoder takes precedence over []byte. - {val: []byteEncoder{0, 1, 2, 3, 4}, output: "C5C0C0C0C0C0"}, -} - -func runEncTests(t *testing.T, f func(val interface{}) ([]byte, error)) { - for i, test := range encTests { - output, err := f(test.val) - if err != nil && test.error == "" { - t.Errorf("test %d: unexpected error: %v\nvalue %#v\ntype %T", - i, err, test.val, test.val) - continue - } - if test.error != "" && fmt.Sprint(err) != test.error { - t.Errorf("test %d: error mismatch\ngot %v\nwant %v\nvalue %#v\ntype %T", - i, err, test.error, test.val, test.val) - continue - } - if err == nil && !bytes.Equal(output, unhex(test.output)) { - t.Errorf("test %d: output mismatch:\ngot %X\nwant %s\nvalue %#v\ntype %T", - i, output, test.output, test.val, test.val) - } - } -} - -func TestEncode(t *testing.T) { - runEncTests(t, func(val interface{}) ([]byte, error) { - b := new(bytes.Buffer) - err := Encode(b, val) - return b.Bytes(), err - }) -} - -func TestEncodeToBytes(t *testing.T) { - runEncTests(t, EncodeToBytes) -} - -func TestEncodeToReader(t *testing.T) { - runEncTests(t, func(val interface{}) ([]byte, error) { - _, r, err := EncodeToReader(val) - if err != nil { - return nil, err - } - return ioutil.ReadAll(r) - }) -} - -func TestEncodeToReaderPiecewise(t *testing.T) { - runEncTests(t, func(val interface{}) ([]byte, error) { - size, r, err := EncodeToReader(val) - if err != nil { - return nil, err - } - - // read output piecewise - output := make([]byte, size) - for start, end := 0, 0; start < size; start = end { - if remaining := size - start; remaining < 3 { - end += remaining - } else { - end = start + 3 - } - n, err := r.Read(output[start:end]) - end = start + n - if err == io.EOF { - break - } else if err != nil { - return nil, err - } - } - return output, nil - }) -} - -// This is a regression test verifying that encReader -// returns its encbuf to the pool only once. -func TestEncodeToReaderReturnToPool(t *testing.T) { - buf := make([]byte, 50) - wg := new(sync.WaitGroup) - for i := 0; i < 5; i++ { - wg.Add(1) - go func() { - for i := 0; i < 1000; i++ { - _, r, _ := EncodeToReader("foo") - ioutil.ReadAll(r) - r.Read(buf) - r.Read(buf) - r.Read(buf) - r.Read(buf) - } - wg.Done() - }() - } - wg.Wait() -} diff --git a/common/rlp/encoder_example_test.go b/common/rlp/encoder_example_test.go deleted file mode 100644 index 42c1c5c8..00000000 --- a/common/rlp/encoder_example_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2014 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package rlp - -import ( - "fmt" - "io" -) - -type MyCoolType struct { - Name string - a, b uint -} - -// EncodeRLP writes x as RLP list [a, b] that omits the Name field. -func (x *MyCoolType) EncodeRLP(w io.Writer) (err error) { - return Encode(w, []uint{x.a, x.b}) -} - -func ExampleEncoder() { - var t *MyCoolType // t is nil pointer to MyCoolType - bytes, _ := EncodeToBytes(t) - fmt.Printf("%v → %X\n", t, bytes) - - t = &MyCoolType{Name: "foobar", a: 5, b: 6} - bytes, _ = EncodeToBytes(t) - fmt.Printf("%v → %X\n", t, bytes) - - // Output: - // → C0 - // &{foobar 5 6} → C20506 -} diff --git a/common/rlp/raw.go b/common/rlp/raw.go deleted file mode 100644 index 2b3f328f..00000000 --- a/common/rlp/raw.go +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2015 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package rlp - -import ( - "io" - "reflect" -) - -// RawValue represents an encoded RLP value and can be used to delay -// RLP decoding or to precompute an encoding. Note that the decoder does -// not verify whether the content of RawValues is valid RLP. -type RawValue []byte - -var rawValueType = reflect.TypeOf(RawValue{}) - -// ListSize returns the encoded size of an RLP list with the given -// content size. -func ListSize(contentSize uint64) uint64 { - return uint64(headsize(contentSize)) + contentSize -} - -// Split returns the content of first RLP value and any -// bytes after the value as subslices of b. -func Split(b []byte) (k Kind, content, rest []byte, err error) { - k, ts, cs, err := readKind(b) - if err != nil { - return 0, nil, b, err - } - return k, b[ts : ts+cs], b[ts+cs:], nil -} - -// SplitString splits b into the content of an RLP string -// and any remaining bytes after the string. -func SplitString(b []byte) (content, rest []byte, err error) { - k, content, rest, err := Split(b) - if err != nil { - return nil, b, err - } - if k == List { - return nil, b, ErrExpectedString - } - return content, rest, nil -} - -// SplitList splits b into the content of a list and any remaining -// bytes after the list. -func SplitList(b []byte) (content, rest []byte, err error) { - k, content, rest, err := Split(b) - if err != nil { - return nil, b, err - } - if k != List { - return nil, b, ErrExpectedList - } - return content, rest, nil -} - -// CountValues counts the number of encoded values in b. -func CountValues(b []byte) (int, error) { - i := 0 - for ; len(b) > 0; i++ { - _, tagsize, size, err := readKind(b) - if err != nil { - return 0, err - } - b = b[tagsize+size:] - } - return i, nil -} - -func readKind(buf []byte) (k Kind, tagsize, contentsize uint64, err error) { - if len(buf) == 0 { - return 0, 0, 0, io.ErrUnexpectedEOF - } - b := buf[0] - switch { - case b < 0x80: - k = Byte - tagsize = 0 - contentsize = 1 - case b < 0xB8: - k = String - tagsize = 1 - contentsize = uint64(b - 0x80) - // Reject strings that should've been single bytes. - if contentsize == 1 && len(buf) > 1 && buf[1] < 128 { - return 0, 0, 0, ErrCanonSize - } - case b < 0xC0: - k = String - tagsize = uint64(b-0xB7) + 1 - contentsize, err = readSize(buf[1:], b-0xB7) - case b < 0xF8: - k = List - tagsize = 1 - contentsize = uint64(b - 0xC0) - default: - k = List - tagsize = uint64(b-0xF7) + 1 - contentsize, err = readSize(buf[1:], b-0xF7) - } - if err != nil { - return 0, 0, 0, err - } - // Reject values larger than the input slice. - if contentsize > uint64(len(buf))-tagsize { - return 0, 0, 0, ErrValueTooLarge - } - return k, tagsize, contentsize, err -} - -func readSize(b []byte, slen byte) (uint64, error) { - if int(slen) > len(b) { - return 0, io.ErrUnexpectedEOF - } - var s uint64 - switch slen { - case 1: - s = uint64(b[0]) - case 2: - s = uint64(b[0])<<8 | uint64(b[1]) - case 3: - s = uint64(b[0])<<16 | uint64(b[1])<<8 | uint64(b[2]) - case 4: - s = uint64(b[0])<<24 | uint64(b[1])<<16 | uint64(b[2])<<8 | uint64(b[3]) - case 5: - s = uint64(b[0])<<32 | uint64(b[1])<<24 | uint64(b[2])<<16 | uint64(b[3])<<8 | uint64(b[4]) - case 6: - s = uint64(b[0])<<40 | uint64(b[1])<<32 | uint64(b[2])<<24 | uint64(b[3])<<16 | uint64(b[4])<<8 | uint64(b[5]) - case 7: - s = uint64(b[0])<<48 | uint64(b[1])<<40 | uint64(b[2])<<32 | uint64(b[3])<<24 | uint64(b[4])<<16 | uint64(b[5])<<8 | uint64(b[6]) - case 8: - s = uint64(b[0])<<56 | uint64(b[1])<<48 | uint64(b[2])<<40 | uint64(b[3])<<32 | uint64(b[4])<<24 | uint64(b[5])<<16 | uint64(b[6])<<8 | uint64(b[7]) - } - // Reject sizes < 56 (shouldn't have separate size) and sizes with - // leading zero bytes. - if s < 56 || b[0] == 0 { - return 0, ErrCanonSize - } - return s, nil -} diff --git a/common/rlp/raw_test.go b/common/rlp/raw_test.go deleted file mode 100644 index 2aad0421..00000000 --- a/common/rlp/raw_test.go +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2015 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package rlp - -import ( - "bytes" - "io" - "reflect" - "testing" -) - -func TestCountValues(t *testing.T) { - tests := []struct { - input string // note: spaces in input are stripped by unhex - count int - err error - }{ - // simple cases - {"", 0, nil}, - {"00", 1, nil}, - {"80", 1, nil}, - {"C0", 1, nil}, - {"01 02 03", 3, nil}, - {"01 C406070809 02", 3, nil}, - {"820101 820202 8403030303 04", 4, nil}, - - // size errors - {"8142", 0, ErrCanonSize}, - {"01 01 8142", 0, ErrCanonSize}, - {"02 84020202", 0, ErrValueTooLarge}, - - { - input: "A12000BF49F440A1CD0527E4D06E2765654C0F56452257516D793A9B8D604DCFDF2AB853F851808D10000000000000000000000000A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - count: 2, - }, - } - for i, test := range tests { - count, err := CountValues(unhex(test.input)) - if count != test.count { - t.Errorf("test %d: count mismatch, got %d want %d\ninput: %s", i, count, test.count, test.input) - } - if !reflect.DeepEqual(err, test.err) { - t.Errorf("test %d: err mismatch, got %q want %q\ninput: %s", i, err, test.err, test.input) - } - } -} - -func TestSplitTypes(t *testing.T) { - if _, _, err := SplitString(unhex("C100")); err != ErrExpectedString { - t.Errorf("SplitString returned %q, want %q", err, ErrExpectedString) - } - if _, _, err := SplitList(unhex("01")); err != ErrExpectedList { - t.Errorf("SplitString returned %q, want %q", err, ErrExpectedList) - } - if _, _, err := SplitList(unhex("81FF")); err != ErrExpectedList { - t.Errorf("SplitString returned %q, want %q", err, ErrExpectedList) - } -} - -func TestSplit(t *testing.T) { - tests := []struct { - input string - kind Kind - val, rest string - err error - }{ - {input: "01FFFF", kind: Byte, val: "01", rest: "FFFF"}, - {input: "80FFFF", kind: String, val: "", rest: "FFFF"}, - {input: "C3010203", kind: List, val: "010203"}, - - // errors - {input: "", err: io.ErrUnexpectedEOF}, - - {input: "8141", err: ErrCanonSize, rest: "8141"}, - {input: "B800", err: ErrCanonSize, rest: "B800"}, - {input: "B802FFFF", err: ErrCanonSize, rest: "B802FFFF"}, - {input: "B90000", err: ErrCanonSize, rest: "B90000"}, - {input: "B90055", err: ErrCanonSize, rest: "B90055"}, - {input: "BA0002FFFF", err: ErrCanonSize, rest: "BA0002FFFF"}, - {input: "F800", err: ErrCanonSize, rest: "F800"}, - {input: "F90000", err: ErrCanonSize, rest: "F90000"}, - {input: "F90055", err: ErrCanonSize, rest: "F90055"}, - {input: "FA0002FFFF", err: ErrCanonSize, rest: "FA0002FFFF"}, - - {input: "81", err: ErrValueTooLarge, rest: "81"}, - {input: "8501010101", err: ErrValueTooLarge, rest: "8501010101"}, - {input: "C60607080902", err: ErrValueTooLarge, rest: "C60607080902"}, - - // size check overflow - {input: "BFFFFFFFFFFFFFFFFF", err: ErrValueTooLarge, rest: "BFFFFFFFFFFFFFFFFF"}, - {input: "FFFFFFFFFFFFFFFFFF", err: ErrValueTooLarge, rest: "FFFFFFFFFFFFFFFFFF"}, - - { - input: "B838FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", - err: ErrValueTooLarge, - rest: "B838FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", - }, - { - input: "F838FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", - err: ErrValueTooLarge, - rest: "F838FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", - }, - - // a few bigger values, just for kicks - { - input: "F839FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", - kind: List, - val: "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", - rest: "", - }, - { - input: "F90211A060EF29F20CC1007AE6E9530AEE16F4B31F8F1769A2D1264EC995C6D1241868D6A07C62AB8AC9838F5F5877B20BB37B387BC2106E97A3D52172CBEDB5EE17C36008A00EAB6B7324AADC0F6047C6AFC8229F09F7CF451B51D67C8DFB08D49BA8C3C626A04453343B2F3A6E42FCF87948F88AF7C8FC16D0C2735CBA7F026836239AB2C15FA024635C7291C882CE4C0763760C1A362DFC3FFCD802A55722236DE058D74202ACA0A220C808DE10F55E40AB25255201CFF009EA181D3906638E944EE2BF34049984A08D325AB26796F1CCB470F69C0F842501DC35D368A0C2575B2D243CFD1E8AB0FDA0B5298FF60DA5069463D610513C9F04F24051348391A143AFFAB7197DFACDEA72A02D2A7058A4463F8FB69378369E11EF33AE3252E2DB86CB545B36D3C26DDECE5AA0888F97BCA8E0BD83DC5B3B91CFF5FAF2F66F9501010682D67EF4A3B4E66115FBA0E8175A60C93BE9ED02921958F0EA55DA0FB5E4802AF5846147BAD92BC2D8AF26A08B3376FF433F3A4250FA64B7F804004CAC5807877D91C4427BD1CD05CF912ED8A09B32EF0F03BD13C37FF950C0CCCEFCCDD6669F2E7F2AA5CB859928E84E29763EA09BBA5E46610C8C8B1F8E921E5691BF8C7E40D75825D5EA3217AA9C3A8A355F39A0EEB95BC78251CCCEC54A97F19755C4A59A293544EEE6119AFA50531211E53C4FA00B6E86FE150BF4A9E0FEEE9C90F5465E617A861BB5E357F942881EE762212E2580", - kind: List, - val: "A060EF29F20CC1007AE6E9530AEE16F4B31F8F1769A2D1264EC995C6D1241868D6A07C62AB8AC9838F5F5877B20BB37B387BC2106E97A3D52172CBEDB5EE17C36008A00EAB6B7324AADC0F6047C6AFC8229F09F7CF451B51D67C8DFB08D49BA8C3C626A04453343B2F3A6E42FCF87948F88AF7C8FC16D0C2735CBA7F026836239AB2C15FA024635C7291C882CE4C0763760C1A362DFC3FFCD802A55722236DE058D74202ACA0A220C808DE10F55E40AB25255201CFF009EA181D3906638E944EE2BF34049984A08D325AB26796F1CCB470F69C0F842501DC35D368A0C2575B2D243CFD1E8AB0FDA0B5298FF60DA5069463D610513C9F04F24051348391A143AFFAB7197DFACDEA72A02D2A7058A4463F8FB69378369E11EF33AE3252E2DB86CB545B36D3C26DDECE5AA0888F97BCA8E0BD83DC5B3B91CFF5FAF2F66F9501010682D67EF4A3B4E66115FBA0E8175A60C93BE9ED02921958F0EA55DA0FB5E4802AF5846147BAD92BC2D8AF26A08B3376FF433F3A4250FA64B7F804004CAC5807877D91C4427BD1CD05CF912ED8A09B32EF0F03BD13C37FF950C0CCCEFCCDD6669F2E7F2AA5CB859928E84E29763EA09BBA5E46610C8C8B1F8E921E5691BF8C7E40D75825D5EA3217AA9C3A8A355F39A0EEB95BC78251CCCEC54A97F19755C4A59A293544EEE6119AFA50531211E53C4FA00B6E86FE150BF4A9E0FEEE9C90F5465E617A861BB5E357F942881EE762212E2580", - rest: "", - }, - { - input: "F877A12000BF49F440A1CD0527E4D06E2765654C0F56452257516D793A9B8D604DCFDF2AB853F851808D10000000000000000000000000A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - kind: List, - val: "A12000BF49F440A1CD0527E4D06E2765654C0F56452257516D793A9B8D604DCFDF2AB853F851808D10000000000000000000000000A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - rest: "", - }, - } - - for i, test := range tests { - kind, val, rest, err := Split(unhex(test.input)) - if kind != test.kind { - t.Errorf("test %d: kind mismatch: got %v, want %v", i, kind, test.kind) - } - if !bytes.Equal(val, unhex(test.val)) { - t.Errorf("test %d: val mismatch: got %x, want %s", i, val, test.val) - } - if !bytes.Equal(rest, unhex(test.rest)) { - t.Errorf("test %d: rest mismatch: got %x, want %s", i, rest, test.rest) - } - if err != test.err { - t.Errorf("test %d: error mismatch: got %q, want %q", i, err, test.err) - } - } -} - -func TestReadSize(t *testing.T) { - tests := []struct { - input string - slen byte - size uint64 - err error - }{ - {input: "", slen: 1, err: io.ErrUnexpectedEOF}, - {input: "FF", slen: 2, err: io.ErrUnexpectedEOF}, - {input: "00", slen: 1, err: ErrCanonSize}, - {input: "36", slen: 1, err: ErrCanonSize}, - {input: "37", slen: 1, err: ErrCanonSize}, - {input: "38", slen: 1, size: 0x38}, - {input: "FF", slen: 1, size: 0xFF}, - {input: "FFFF", slen: 2, size: 0xFFFF}, - {input: "FFFFFF", slen: 3, size: 0xFFFFFF}, - {input: "FFFFFFFF", slen: 4, size: 0xFFFFFFFF}, - {input: "FFFFFFFFFF", slen: 5, size: 0xFFFFFFFFFF}, - {input: "FFFFFFFFFFFF", slen: 6, size: 0xFFFFFFFFFFFF}, - {input: "FFFFFFFFFFFFFF", slen: 7, size: 0xFFFFFFFFFFFFFF}, - {input: "FFFFFFFFFFFFFFFF", slen: 8, size: 0xFFFFFFFFFFFFFFFF}, - {input: "0102", slen: 2, size: 0x0102}, - {input: "010203", slen: 3, size: 0x010203}, - {input: "01020304", slen: 4, size: 0x01020304}, - {input: "0102030405", slen: 5, size: 0x0102030405}, - {input: "010203040506", slen: 6, size: 0x010203040506}, - {input: "01020304050607", slen: 7, size: 0x01020304050607}, - {input: "0102030405060708", slen: 8, size: 0x0102030405060708}, - } - - for _, test := range tests { - size, err := readSize(unhex(test.input), test.slen) - if err != test.err { - t.Errorf("readSize(%s, %d): error mismatch: got %q, want %q", test.input, test.slen, err, test.err) - continue - } - if size != test.size { - t.Errorf("readSize(%s, %d): size mismatch: got %#x, want %#x", test.input, test.slen, size, test.size) - } - } -} diff --git a/common/rlp/typecache.go b/common/rlp/typecache.go deleted file mode 100644 index e9a1e3f9..00000000 --- a/common/rlp/typecache.go +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright 2014 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package rlp - -import ( - "fmt" - "reflect" - "strings" - "sync" -) - -var ( - typeCacheMutex sync.RWMutex - typeCache = make(map[typekey]*typeinfo) -) - -type typeinfo struct { - decoder decoder - decoderErr error // error from makeDecoder - writer writer - writerErr error // error from makeWriter -} - -// tags represents struct tags. -type tags struct { - // rlp:"nil" controls whether empty input results in a nil pointer. - nilOK bool - - // This controls whether nil pointers are encoded/decoded as empty strings - // or empty lists. - nilKind Kind - - // rlp:"tail" controls whether this field swallows additional list - // elements. It can only be set for the last field, which must be - // of slice type. - tail bool - - // rlp:"-" ignores fields. - ignored bool -} - -// typekey is the key of a type in typeCache. It includes the struct tags because -// they might generate a different decoder. -type typekey struct { - reflect.Type - tags -} - -type decoder func(*Stream, reflect.Value) error - -type writer func(reflect.Value, *encbuf) error - -func cachedDecoder(typ reflect.Type) (decoder, error) { - info := cachedTypeInfo(typ, tags{}) - return info.decoder, info.decoderErr -} - -func cachedWriter(typ reflect.Type) (writer, error) { - info := cachedTypeInfo(typ, tags{}) - return info.writer, info.writerErr -} - -func cachedTypeInfo(typ reflect.Type, tags tags) *typeinfo { - typeCacheMutex.RLock() - info := typeCache[typekey{typ, tags}] - typeCacheMutex.RUnlock() - if info != nil { - return info - } - // not in the cache, need to generate info for this type. - typeCacheMutex.Lock() - defer typeCacheMutex.Unlock() - return cachedTypeInfo1(typ, tags) -} - -func cachedTypeInfo1(typ reflect.Type, tags tags) *typeinfo { - key := typekey{typ, tags} - info := typeCache[key] - if info != nil { - // another goroutine got the write lock first - return info - } - // put a dummy value into the cache before generating. - // if the generator tries to lookup itself, it will get - // the dummy value and won't call itself recursively. - info = new(typeinfo) - typeCache[key] = info - info.generate(typ, tags) - return info -} - -type field struct { - index int - info *typeinfo -} - -func structFields(typ reflect.Type) (fields []field, err error) { - lastPublic := lastPublicField(typ) - for i := 0; i < typ.NumField(); i++ { - if f := typ.Field(i); f.PkgPath == "" { // exported - tags, err := parseStructTag(typ, i, lastPublic) - if err != nil { - return nil, err - } - if tags.ignored { - continue - } - info := cachedTypeInfo1(f.Type, tags) - fields = append(fields, field{i, info}) - } - } - return fields, nil -} - -type structFieldError struct { - typ reflect.Type - field int - err error -} - -func (e structFieldError) Error() string { - return fmt.Sprintf("%v (struct field %v.%s)", e.err, e.typ, e.typ.Field(e.field).Name) -} - -type structTagError struct { - typ reflect.Type - field, tag, err string -} - -func (e structTagError) Error() string { - return fmt.Sprintf("rlp: invalid struct tag %q for %v.%s (%s)", e.tag, e.typ, e.field, e.err) -} - -func parseStructTag(typ reflect.Type, fi, lastPublic int) (tags, error) { - f := typ.Field(fi) - var ts tags - for _, t := range strings.Split(f.Tag.Get("rlp"), ",") { - switch t = strings.TrimSpace(t); t { - case "": - case "-": - ts.ignored = true - case "nil", "nilString", "nilList": - ts.nilOK = true - if f.Type.Kind() != reflect.Ptr { - return ts, structTagError{typ, f.Name, t, "field is not a pointer"} - } - switch t { - case "nil": - ts.nilKind = defaultNilKind(f.Type.Elem()) - case "nilString": - ts.nilKind = String - case "nilList": - ts.nilKind = List - } - case "tail": - ts.tail = true - if fi != lastPublic { - return ts, structTagError{typ, f.Name, t, "must be on last field"} - } - if f.Type.Kind() != reflect.Slice { - return ts, structTagError{typ, f.Name, t, "field type is not slice"} - } - default: - return ts, fmt.Errorf("rlp: unknown struct tag %q on %v.%s", t, typ, f.Name) - } - } - return ts, nil -} - -func lastPublicField(typ reflect.Type) int { - last := 0 - for i := 0; i < typ.NumField(); i++ { - if typ.Field(i).PkgPath == "" { - last = i - } - } - return last -} - -func (i *typeinfo) generate(typ reflect.Type, tags tags) { - i.decoder, i.decoderErr = makeDecoder(typ, tags) - i.writer, i.writerErr = makeWriter(typ, tags) -} - -// defaultNilKind determines whether a nil pointer to typ encodes/decodes -// as an empty string or empty list. -func defaultNilKind(typ reflect.Type) Kind { - k := typ.Kind() - if isUint(k) || k == reflect.String || k == reflect.Bool || isByteArray(typ) { - return String - } - return List -} - -func isUint(k reflect.Kind) bool { - return k >= reflect.Uint && k <= reflect.Uintptr -} - -func isByteArray(typ reflect.Type) bool { - return (typ.Kind() == reflect.Slice || typ.Kind() == reflect.Array) && isByte(typ.Elem()) -} diff --git a/common/types/account.go b/common/types/account.go index c88896ea..f89a5706 100644 --- a/common/types/account.go +++ b/common/types/account.go @@ -1,179 +1,18 @@ package types import ( - "github.com/pkg/errors" - "github.com/tendermint/tendermint/crypto" + nodeTypes "github.com/bnb-chain/node/common/types" + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" ) -// AppAccount definition -type AppAccount struct { - BaseAccount `json:"base"` - Name string `json:"name"` - FrozenCoins Coins `json:"frozen"` - LockedCoins Coins `json:"locked"` - Flags uint64 `json:"flags"` -} - -type Account interface { - GetAddress() AccAddress - SetAddress(address AccAddress) error // errors if already set. - - GetPubKey() crypto.PubKey // can return nil. - SetPubKey(crypto.PubKey) error - - GetAccountNumber() int64 - SetAccountNumber(int64) error - - GetSequence() int64 - SetSequence(int64) error - - GetCoins() Coins - SetCoins(Coins) error - Clone() Account - - GetFlags() uint64 - SetFlags(flags uint64) -} - -type NamedAccount interface { - Account - GetName() string - SetName(string) - - GetFrozenCoins() Coins - SetFrozenCoins(Coins) - - //TODO: this should merge into Coin - GetLockedCoins() Coins - SetLockedCoins(Coins) -} - -func (acc AppAccount) GetName() string { return acc.Name } -func (acc *AppAccount) SetName(name string) { acc.Name = name } -func (acc AppAccount) GetFrozenCoins() Coins { return acc.FrozenCoins } -func (acc *AppAccount) SetFrozenCoins(frozen Coins) { acc.FrozenCoins = frozen } -func (acc AppAccount) GetLockedCoins() Coins { return acc.LockedCoins } -func (acc *AppAccount) SetLockedCoins(frozen Coins) { acc.LockedCoins = frozen } -func (acc *AppAccount) GetFlags() uint64 { return acc.Flags } -func (acc *AppAccount) SetFlags(flags uint64) { acc.Flags = flags } - -func (acc *AppAccount) Clone() Account { - baseAcc := acc.BaseAccount.Clone() - clonedAcc := &AppAccount{ - BaseAccount: baseAcc, - Name: acc.Name, - } - if acc.FrozenCoins == nil { - clonedAcc.FrozenCoins = nil - } else { - coins := Coins{} - for _, coin := range acc.FrozenCoins { - coins = append(coins, Coin{Denom: coin.Denom, Amount: coin.Amount}) - } - clonedAcc.FrozenCoins = coins - } - if acc.LockedCoins == nil { - clonedAcc.LockedCoins = nil - } else { - coins := Coins{} - for _, coin := range acc.LockedCoins { - coins = append(coins, Coin{Denom: coin.Denom, Amount: coin.Amount}) - } - clonedAcc.LockedCoins = coins - } - return clonedAcc -} - -type BaseAccount struct { - Address AccAddress `json:"address"` - Coins Coins `json:"coins"` - PubKey crypto.PubKey `json:"public_key"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` -} - -// Implements sdk.Account. -func (acc BaseAccount) GetAddress() AccAddress { - return acc.Address -} - -// Implements sdk.Account. -func (acc *BaseAccount) SetAddress(addr AccAddress) error { - if len(acc.Address) != 0 { - return errors.New("cannot override BaseAccount address") - } - acc.Address = addr - return nil -} +type ( + AppAccount = nodeTypes.AppAccount + BaseAccount = auth.BaseAccount -// Implements sdk.Account. -func (acc BaseAccount) GetPubKey() crypto.PubKey { - return acc.PubKey -} - -// Implements sdk.Account. -func (acc *BaseAccount) SetPubKey(pubKey crypto.PubKey) error { - acc.PubKey = pubKey - return nil -} - -// Implements sdk.Account. -func (acc *BaseAccount) GetCoins() Coins { - return acc.Coins -} - -// Implements sdk.Account. -func (acc *BaseAccount) SetCoins(coins Coins) error { - acc.Coins = coins - return nil -} - -// Implements Account -func (acc *BaseAccount) GetAccountNumber() int64 { - return acc.AccountNumber -} - -// Implements Account -func (acc *BaseAccount) SetAccountNumber(accNumber int64) error { - acc.AccountNumber = accNumber - return nil -} - -// Implements sdk.Account. -func (acc *BaseAccount) GetSequence() int64 { - return acc.Sequence -} - -// Implements sdk.Account. -func (acc *BaseAccount) SetSequence(seq int64) error { - acc.Sequence = seq - return nil -} - -// Implements sdk.Account. -func (acc *BaseAccount) Clone() BaseAccount { - // given the fact PubKey and Address doesn't change, - // it should be fine if not deep copy them. if both of - // the two interfaces can provide a Clone() method would be terrific. - clonedAcc := BaseAccount{ - PubKey: acc.PubKey, - Address: acc.Address, - AccountNumber: acc.AccountNumber, - Sequence: acc.Sequence, - } - - if acc.Coins == nil { - clonedAcc.Coins = nil - } else { - coins := make(Coins, 0, len(acc.Coins)) - for _, coin := range acc.Coins { - coins = append(coins, Coin{Denom: coin.Denom, Amount: coin.Amount}) - } - clonedAcc.Coins = coins - } - - return clonedAcc -} + Account = types.Account + NamedAccount = nodeTypes.NamedAccount +) // Balance Account definition type BalanceAccount struct { diff --git a/common/types/address.go b/common/types/address.go index 33d39592..c449ecff 100644 --- a/common/types/address.go +++ b/common/types/address.go @@ -1,20 +1,10 @@ package types import ( - "encoding/hex" - "encoding/json" - "errors" - "fmt" - cryptoAmino "github.com/tendermint/tendermint/crypto/encoding/amino" - - "github.com/tendermint/tendermint/crypto" - - "github.com/binance-chain/go-sdk/common/bech32" + "github.com/cosmos/cosmos-sdk/types" ) -// AccAddress a wrapper around bytes meant to represent an account address. -// When marshaled to a string or JSON, it uses Bech32. -type AccAddress []byte +type AccAddress = types.AccAddress type ChainNetwork uint8 @@ -26,14 +16,19 @@ const ( ) const ( - AddrLen = 20 - - bech32PrefixConsPub = "bcap" - bech32PrefixConsAddr = "bca" + AddrLen = types.AddrLen ) var Network = ProdNetwork +func SetNetwork(network ChainNetwork) { + Network = network + if network != ProdNetwork { + sdkConfig := types.GetConfig() + sdkConfig.SetBech32PrefixForAccount("tbnb", "bnbp") + } +} + func (this ChainNetwork) Bech32Prefixes() string { switch this { case TestNetwork: @@ -49,118 +44,18 @@ func (this ChainNetwork) Bech32Prefixes() string { } } -func (this ChainNetwork) Bech32ValidatorAddrPrefix() string { - return "bva" -} - -// Marshal needed for protobuf compatibility -func (bz AccAddress) Marshal() ([]byte, error) { - return bz, nil -} - -// Unmarshal needed for protobuf compatibility -func (bz *AccAddress) Unmarshal(data []byte) error { - *bz = data - return nil -} - -// MarshalJSON to Marshals to JSON using Bech32 -func (bz AccAddress) MarshalJSON() ([]byte, error) { - return json.Marshal(bz.String()) -} - -// UnmarshalJSON to Unmarshal from JSON assuming Bech32 encoding -func (bz *AccAddress) UnmarshalJSON(data []byte) error { - var s string - err := json.Unmarshal(data, &s) - if err != nil { - return nil - } - - bz2, err := AccAddressFromBech32(s) - if err != nil { - return err - } - *bz = bz2 - return nil -} - -// AccAddressFromHex to create an AccAddress from a hex string -func AccAddressFromHex(address string) (addr AccAddress, err error) { - if len(address) == 0 { - return addr, errors.New("decoding bech32 address failed: must provide an address") - } - bz, err := hex.DecodeString(address) - if err != nil { - return nil, err - } - return AccAddress(bz), nil -} - -// AccAddressFromBech32 to create an AccAddress from a bech32 string -func AccAddressFromBech32(address string) (addr AccAddress, err error) { - bz, err := GetFromBech32(address, Network.Bech32Prefixes()) - if err != nil { - return nil, err - } - return AccAddress(bz), nil -} - -// GetFromBech32 to decode a bytestring from a bech32-encoded string -func GetFromBech32(bech32str, prefix string) ([]byte, error) { - if len(bech32str) == 0 { - return nil, errors.New("decoding bech32 address failed: must provide an address") - } - hrp, bz, err := bech32.DecodeAndConvert(bech32str) - if err != nil { - return nil, err - } - - if hrp != prefix { - return nil, fmt.Errorf("invalid bech32 prefix. Expected %s, Got %s", prefix, hrp) - } - - return bz, nil -} - -func (bz AccAddress) Bytes() []byte { - return bz -} - -// String representation -func (bz AccAddress) String() string { - bech32Addr, err := bech32.ConvertAndEncode(Network.Bech32Prefixes(), bz.Bytes()) - if err != nil { - panic(err) - } - return bech32Addr -} - -func MustBech32ifyConsPub(pub crypto.PubKey) string { - enc, err := Bech32ifyConsPub(pub) - if err != nil { - panic(err) - } - - return enc -} - -// Bech32ifyConsPub returns a Bech32 encoded string containing the -// Bech32PrefixConsPub prefixfor a given consensus node's PubKey. -func Bech32ifyConsPub(pub crypto.PubKey) (string, error) { - return bech32.ConvertAndEncode(bech32PrefixConsPub, pub.Bytes()) +func init() { + sdkConfig := types.GetConfig() + sdkConfig.SetBech32PrefixForAccount("bnb", "bnbp") + sdkConfig.SetBech32PrefixForValidator("bva", "bvap") + sdkConfig.SetBech32PrefixForConsensusNode("bca", "bcap") } -func GetConsPubKeyBech32(pubkey string) (pk crypto.PubKey, err error) { - bz, err := GetFromBech32(pubkey, bech32PrefixConsPub) - if err != nil { - return nil, err - } - - pk, err = cryptoAmino.PubKeyFromBytes(bz) - if err != nil { - return nil, err - } - - return pk, nil -} +var ( + AccAddressFromHex = types.AccAddressFromHex + AccAddressFromBech32 = types.AccAddressFromBech32 + GetFromBech32 = types.GetFromBech32 + MustBech32ifyConsPub = types.MustBech32ifyConsPub + Bech32ifyConsPub = types.Bech32ifyConsPub + GetConsPubKeyBech32 = types.GetConsPubKeyBech32 +) diff --git a/common/types/coins.go b/common/types/coins.go index 3a525f97..649df48a 100644 --- a/common/types/coins.go +++ b/common/types/coins.go @@ -1,195 +1,10 @@ package types import ( - "fmt" - "sort" - "strings" + "github.com/cosmos/cosmos-sdk/types" ) -// Coin def -type Coin struct { - Denom string `json:"denom"` - Amount int64 `json:"amount"` -} - -func (coin Coin) IsZero() bool { - return coin.Amount == 0 -} - -func (coin Coin) IsPositive() bool { - return coin.Amount > 0 -} - -func (coin Coin) IsNotNegative() bool { - return coin.Amount >= 0 -} - -func (coin Coin) SameDenomAs(other Coin) bool { - return (coin.Denom == other.Denom) -} - -func (coin Coin) Plus(coinB Coin) Coin { - if !coin.SameDenomAs(coinB) { - return coin - } - return Coin{coin.Denom, coin.Amount + coinB.Amount} -} - -func (coin Coin) String() string { - return fmt.Sprintf("%v%v", coin.Amount, coin.Denom) -} - -func (coin Coin) IsEqual(other Coin) bool { - return coin.Denom == other.Denom && coin.Amount == other.Amount -} - -// Coins def -type Coins []Coin - -func (coins Coins) String() string { - if len(coins) == 0 { - return "" - } - - out := "" - for _, coin := range coins { - out += fmt.Sprintf("%v,", coin.String()) - } - return out[:len(out)-1] -} - -func (coins Coins) IsValid() bool { - switch len(coins) { - case 0: - return true - case 1: - return !coins[0].IsZero() - default: - lowDenom := coins[0].Denom - for _, coin := range coins[1:] { - if coin.Denom <= lowDenom { - return false - } - if coin.IsZero() { - return false - } - lowDenom = coin.Denom - } - return true - } -} - -func (coins Coins) IsPositive() bool { - if len(coins) == 0 { - return false - } - for _, coin := range coins { - if !coin.IsPositive() { - return false - } - } - return true -} - -func (coins Coins) Plus(coinsB Coins) Coins { - sum := ([]Coin)(nil) - indexA, indexB := 0, 0 - lenA, lenB := len(coins), len(coinsB) - for { - if indexA == lenA { - if indexB == lenB { - return sum - } - return append(sum, coinsB[indexB:]...) - } else if indexB == lenB { - return append(sum, coins[indexA:]...) - } - coinA, coinB := coins[indexA], coinsB[indexB] - switch strings.Compare(coinA.Denom, coinB.Denom) { - case -1: - sum = append(sum, coinA) - indexA++ - case 0: - if coinA.Amount+coinB.Amount == 0 { - // ignore 0 sum coin type - } else { - sum = append(sum, coinA.Plus(coinB)) - } - indexA++ - indexB++ - case 1: - sum = append(sum, coinB) - indexB++ - } - } -} - -// IsEqual returns true if the two sets of Coins have the same value -func (coins Coins) IsEqual(coinsB Coins) bool { - if len(coins) != len(coinsB) { - return false - } - for i := 0; i < len(coins); i++ { - if coins[i].Denom != coinsB[i].Denom || !(coins[i].Amount == coinsB[i].Amount) { - return false - } - } - return true -} - -func (coins Coins) IsZero() bool { - for _, coin := range coins { - if !coin.IsZero() { - return false - } - } - return true -} - -func (coins Coins) IsNotNegative() bool { - if len(coins) == 0 { - return true - } - for _, coin := range coins { - if !coin.IsNotNegative() { - return false - } - } - return true -} - -func (coins Coins) AmountOf(denom string) int64 { - switch len(coins) { - case 0: - return 0 - case 1: - coin := coins[0] - if coin.Denom == denom { - return coin.Amount - } - return 0 - default: - midIdx := len(coins) / 2 // 2:1, 3:1, 4:2 - coin := coins[midIdx] - if denom < coin.Denom { - return coins[:midIdx].AmountOf(denom) - } else if denom == coin.Denom { - return coin.Amount - } else { - return coins[midIdx+1:].AmountOf(denom) - } - } -} - -// Sort interface - -//nolint -func (coins Coins) Len() int { return len(coins) } -func (coins Coins) Less(i, j int) bool { return coins[i].Denom < coins[j].Denom } -func (coins Coins) Swap(i, j int) { coins[i], coins[j] = coins[j], coins[i] } - -// Sort is a helper function to sort the set of coins inplace -func (coins Coins) Sort() Coins { - sort.Sort(coins) - return coins -} +type ( + Coin = types.Coin + Coins = types.Coins +) diff --git a/common/types/dec.go b/common/types/dec.go index 50f039e6..0096cea6 100644 --- a/common/types/dec.go +++ b/common/types/dec.go @@ -1,154 +1,15 @@ package types import ( - "encoding/json" - "fmt" - "math/big" - "strconv" + "github.com/cosmos/cosmos-sdk/types" ) -// number of decimal places -const ( - Precision = 8 - - // bytes required to represent the above precision - // ceil(log2(9999999999)) - DecimalPrecisionBits = 34 -) +type Dec = types.Dec var ( - precisionReuse = new(big.Int).Exp(big.NewInt(10), big.NewInt(Precision), nil).Int64() - precisionMultipliers []int64 - zeroInt = big.NewInt(0) - oneInt = big.NewInt(1) - tenInt = big.NewInt(10) + NewDecFromStr = types.NewDecFromStr + ZeroDec = types.ZeroDec + OneDec = types.OneDec + NewDecWithPrec = types.NewDecWithPrec + NewDec = types.NewDec ) - -// Set precision multipliers -func init() { - precisionMultipliers = make([]int64, Precision+1) - for i := 0; i <= Precision; i++ { - precisionMultipliers[i] = calcPrecisionMultiplier(int64(i)) - } -} - -func precisionInt() int64 { - return precisionReuse -} - -type Dec struct { - int64 `json:"int"` -} - -func (d Dec) String() string { - return strconv.FormatInt(d.int64, 10) -} - -func (d Dec) MarshalText() ([]byte, error) { - return []byte(strconv.FormatInt(d.int64, 10)), nil -} - -func (d *Dec) UnmarshalText(text []byte) error { - v, err := strconv.ParseInt(string(text), 10, 64) - d.int64 = v - return err -} - -// requires a valid JSON string - strings quotes and calls UnmarshalText -func (d *Dec) UnmarshalAmino(v int64) (err error) { - d.int64 = v - return nil -} -func (d Dec) MarshalAmino() (int64, error) { - return d.int64, nil -} - -// MarshalJSON marshals the decimal -func (d Dec) MarshalJSON() ([]byte, error) { - return json.Marshal(d.String()) -} - -// UnmarshalJSON defines custom decoding scheme -func (d *Dec) UnmarshalJSON(bz []byte) error { - var text string - err := json.Unmarshal(bz, &text) - if err != nil { - return err - } - // TODO: Reuse dec allocation - newDec, err := NewDecFromStr(text) - if err != nil { - return err - } - d.int64 = newDec.int64 - return nil -} - -func NewDecFromStr(str string) (d Dec, err error) { - value, parseErr := strconv.ParseInt(str, 10, 64) - if parseErr != nil { - return d, fmt.Errorf("bad string to integer conversion, input string: %v, error: %v", str, parseErr) - } - return Dec{value}, nil -} - -//nolint -func (d Dec) IsNil() bool { return false } // is decimal nil -func (d Dec) IsZero() bool { return d.int64 == 0 } // is equal to zero -func (d Dec) Equal(d2 Dec) bool { return d.int64 == d2.int64 } // equal decimals -func (d Dec) GT(d2 Dec) bool { return d.int64 > d2.int64 } // greater than -func (d Dec) GTE(d2 Dec) bool { return d.int64 >= d2.int64 } // greater than or equal -func (d Dec) LT(d2 Dec) bool { return d.int64 < d2.int64 } // less than -func (d Dec) LTE(d2 Dec) bool { return d.int64 <= d2.int64 } // less than or equal -func (d Dec) Neg() Dec { return Dec{-d.int64} } // reverse the decimal sign -func (d Dec) Abs() Dec { - if d.int64 < 0 { - return d.Neg() - } - return d -} - -// subtraction -func (d Dec) Sub(d2 Dec) Dec { - c := d.int64 - d2.int64 - if (c < d.int64) != (d2.int64 > 0) { - panic("Int overflow") - } - return Dec{c} -} - -// nolint - common values -func ZeroDec() Dec { return Dec{0} } -func OneDec() Dec { return Dec{precisionInt()} } -func NewDecWithPrec(i, prec int64) Dec { - if i == 0 { - return Dec{0} - } - c := i * precisionMultiplier(prec) - if c/i != precisionMultiplier(prec) { - panic("Int overflow") - } - return Dec{c} -} - -func NewDec(i int64) Dec { - return NewDecWithPrec(i, Precision) -} - -// get the precision multiplier, do not mutate result -func precisionMultiplier(prec int64) int64 { - if prec > Precision { - panic(fmt.Sprintf("too much precision, maximum %v, provided %v", Precision, prec)) - } - return precisionMultipliers[prec] -} - -// calculate the precision multiplier -func calcPrecisionMultiplier(prec int64) int64 { - if prec > Precision { - panic(fmt.Sprintf("too much precision, maximum %v, provided %v", Precision, prec)) - } - zerosToAdd := Precision - prec - multiplier := new(big.Int).Exp(tenInt, big.NewInt(zerosToAdd), nil).Int64() - return multiplier -} diff --git a/common/types/delegation.go b/common/types/delegation.go index 293678cf..14a19d03 100644 --- a/common/types/delegation.go +++ b/common/types/delegation.go @@ -1,90 +1,19 @@ package types import ( - "fmt" - "time" - - "github.com/tendermint/go-amino" + "github.com/cosmos/cosmos-sdk/x/stake/querier" + stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" ) -// Delegation represents the bond with tokens held by an account. It is -// owned by one delegator, and is associated with the voting power of one -// pubKey. -type Delegation struct { - DelegatorAddr AccAddress `json:"delegator_addr"` - ValidatorAddr ValAddress `json:"validator_addr"` - Shares Dec `json:"shares"` -} - -type DelegationValue struct { - Shares Dec - Height int64 -} - -type Redelegation struct { - DelegatorAddr AccAddress `json:"delegator_addr"` // delegator - ValidatorSrcAddr ValAddress `json:"validator_src_addr"` // validator redelegation source operator addr - ValidatorDstAddr ValAddress `json:"validator_dst_addr"` // validator redelegation destination operator addr - CreationHeight int64 `json:"creation_height"` // height which the redelegation took place - MinTime time.Time `json:"min_time"` // unix time for redelegation completion - InitialBalance Coin `json:"initial_balance"` // initial balance when redelegation started - Balance Coin `json:"balance"` // current balance - SharesSrc Dec `json:"shares_src"` // amount of source shares redelegating - SharesDst Dec `json:"shares_dst"` // amount of destination shares redelegating -} - -type redValue struct { - CreationHeight int64 - MinTime time.Time - InitialBalance Coin - Balance Coin - SharesSrc Dec - SharesDst Dec -} - -// unmarshal a redelegation from a store key and value -func UnmarshalRED(cdc *amino.Codec, key, value []byte) (red Redelegation, err error) { - var storeValue redValue - err = cdc.UnmarshalBinaryLengthPrefixed(value, &storeValue) - if err != nil { - return - } +type ( + Delegation = stakeTypes.Delegation + Redelegation = stakeTypes.Redelegation + DelegationResponse = stakeTypes.DelegationResponse - addrs := key[1:] // remove prefix bytes - if len(addrs) != 3*AddrLen { - err = fmt.Errorf("unexpected address length for this (address, srcValidator, dstValidator) tuple") - return - } - delAddr := AccAddress(addrs[:AddrLen]) - valSrcAddr := ValAddress(addrs[AddrLen : 2*AddrLen]) - valDstAddr := ValAddress(addrs[2*AddrLen:]) - - return Redelegation{ - DelegatorAddr: delAddr, - ValidatorSrcAddr: valSrcAddr, - ValidatorDstAddr: valDstAddr, - CreationHeight: storeValue.CreationHeight, - MinTime: storeValue.MinTime, - InitialBalance: storeValue.InitialBalance, - Balance: storeValue.Balance, - SharesSrc: storeValue.SharesSrc, - SharesDst: storeValue.SharesDst, - }, nil -} - -type DelegationResponse struct { - Delegation - Balance Coin `json:"balance"` -} - -type QueryDelegatorParams struct { - BaseParams - DelegatorAddr AccAddress -} + QueryDelegatorParams = querier.QueryDelegatorParams + QueryRedelegationParams = querier.QueryRedelegationParams +) -type QueryRedelegationParams struct { - BaseParams - DelegatorAddr AccAddress - ValSrcAddr ValAddress - ValDstAddr ValAddress -} +var ( + UnmarshalRED = stakeTypes.UnmarshalRED +) diff --git a/common/types/depth.go b/common/types/depth.go deleted file mode 100644 index 8f61c6a5..00000000 --- a/common/types/depth.go +++ /dev/null @@ -1,8 +0,0 @@ -package types - -type MarketDepth struct { - Bids [][]string `json:"bids"` // "bids": [ [ "0.0024", "10" ] ] - Asks [][]string `json:"asks"` // "asks": [ [ "0.0024", "10" ] ] - Height int64 `json:"height"` - PendingMatch bool `json:"pending_match"` -} diff --git a/common/types/fees.go b/common/types/fees.go index e81f791c..0de66185 100644 --- a/common/types/fees.go +++ b/common/types/fees.go @@ -1,99 +1,22 @@ package types -import "fmt" +import ( + "github.com/cosmos/cosmos-sdk/types" + paramHubTypes "github.com/cosmos/cosmos-sdk/x/paramHub/types" +) const ( - OperateFeeType = "operate" - TransferFeeType = "transfer" - DexFeeType = "dex" - - FeeForProposer = FeeDistributeType(0x01) - FeeForAll = FeeDistributeType(0x02) - FeeFree = FeeDistributeType(0x03) + FeeForProposer = types.FeeForProposer + FeeForAll = types.FeeForAll + FeeFree = types.FeeFree ) -type FeeDistributeType int8 - -type FeeParam interface { - GetParamType() string - Check() error -} - -// dexFee -type DexFeeParam struct { - DexFeeFields []DexFeeField `json:"dex_fee_fields"` -} - -type DexFeeField struct { - FeeName string `json:"fee_name"` - FeeValue int64 `json:"fee_value"` -} - -func (p *DexFeeParam) GetParamType() string { - return DexFeeType -} - -func (p *DexFeeParam) isNil() bool { - for _, d := range p.DexFeeFields { - if d.FeeValue < 0 { - return true - } - } - return false -} - -func (p *DexFeeParam) Check() error { - if p.isNil() { - return fmt.Errorf("Dex fee param is less than 0 ") - } - return nil -} +type ( + FeeDistributeType = types.FeeDistributeType -// fixedFee -type FixedFeeParams struct { - MsgType string `json:"msg_type"` - Fee int64 `json:"fee"` - FeeFor FeeDistributeType `json:"fee_for"` -} - -func (p *FixedFeeParams) GetParamType() string { - return OperateFeeType -} - -func (p *FixedFeeParams) Check() error { - if p.FeeFor != FeeForProposer && p.FeeFor != FeeForAll && p.FeeFor != FeeFree { - return fmt.Errorf("fee_for %d is invalid", p.FeeFor) - } - - if p.Fee < 0 { - return fmt.Errorf("fee(%d) should not be negative", p.Fee) - } - return nil -} - -type TransferFeeParam struct { - FixedFeeParams `json:"fixed_fee_params"` - MultiTransferFee int64 `json:"multi_transfer_fee"` - LowerLimitAsMulti int64 `json:"lower_limit_as_multi"` -} - -func (p *TransferFeeParam) GetParamType() string { - return TransferFeeType -} - -func (p *TransferFeeParam) Check() error { - err := p.FixedFeeParams.Check() - if err != nil { - return err - } - if p.Fee <= 0 || p.MultiTransferFee <= 0 { - return fmt.Errorf("both fee(%d) and multi_transfer_fee(%d) should be positive", p.Fee, p.MultiTransferFee) - } - if p.MultiTransferFee > p.Fee { - return fmt.Errorf("multi_transfer_fee(%d) should not be bigger than fee(%d)", p.MultiTransferFee, p.Fee) - } - if p.LowerLimitAsMulti <= 1 { - return fmt.Errorf("lower_limit_as_multi should > 1") - } - return nil -} + FeeParam = paramHubTypes.FeeParam + DexFeeParam = paramHubTypes.DexFeeParam + DexFeeField = paramHubTypes.DexFeeField + FixedFeeParams = paramHubTypes.FixedFeeParams + TransferFeeParam = paramHubTypes.TransferFeeParam +) diff --git a/common/types/fixed8.go b/common/types/fixed8.go index b7dca15b..4b214704 100644 --- a/common/types/fixed8.go +++ b/common/types/fixed8.go @@ -1,131 +1,18 @@ package types import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "math" - "strconv" - "strings" -) - -const ( - precision = 8 + "github.com/bnb-chain/node/common/utils" ) var ( - // Fixed8Decimals represents 10^precision (100000000), a value of 1 in Fixed8 format - Fixed8Decimals = int(math.Pow10(precision)) - // Fixed8One represetns one unit - Fixed8One = NewFixed8(1) - Fixed8Zero = NewFixed8(0) + Fixed8Decimals = utils.Fixed8Decimals + Fixed8One = utils.Fixed8One + Fixed8Zero = utils.NewFixed8(0) ) -var errInvalidString = errors.New("Fixed8 must satisfy following regex \\d+(\\.\\d{1,8})?") - -// Fixed8 represents a fixed-point number with precision 10^-8 -type Fixed8 int64 - -// String implements the Stringer interface -func (f Fixed8) String() string { - buf := new(bytes.Buffer) - val := int64(f) - if val < 0 { - buf.WriteRune('-') - val = -val - } - str := strconv.FormatInt(val/int64(Fixed8Decimals), 10) - buf.WriteString(str) - val %= int64(Fixed8Decimals) - buf.WriteRune('.') - str = strconv.FormatInt(val, 10) - for i := len(str); i < 8; i++ { - buf.WriteRune('0') - } - buf.WriteString(str) - return buf.String() -} - -// ToInt64 returns the original value representing the Fixed8 -func (f Fixed8) ToInt64() int64 { - return int64(f) -} - -// Value returns the original value representing the Fixed8 divided by 10^8 -func (f Fixed8) Value() int64 { - return int64(f) / int64(Fixed8Decimals) -} - -// NewFixed8 returns a new Fixed8 with the supplied int multiplied by 10^8 -func NewFixed8(val int64) Fixed8 { - return Fixed8(int64(Fixed8Decimals) * val) -} - -// Fixed8DecodeString parses s which must be a fixed point number -// with precision up to 10^-8 -func Fixed8DecodeString(s string) (Fixed8, error) { - parts := strings.SplitN(s, ".", 2) - ip, err := strconv.Atoi(parts[0]) - if err != nil { - return 0, errInvalidString - } else if len(parts) == 1 { - return NewFixed8(int64(ip)), nil - } - - fp, err := strconv.Atoi(parts[1]) - if err != nil || fp >= Fixed8Decimals { - return 0, errInvalidString - } - for i := len(parts[1]); i < precision; i++ { - fp *= 10 - } - return Fixed8(ip*Fixed8Decimals + fp), nil -} +type Fixed8 = utils.Fixed8 -// UnmarshalJSON implements the json unmarshaller interface -func (f *Fixed8) UnmarshalJSON(data []byte) error { - var s string - if err := json.Unmarshal(data, &s); err == nil { - p, err := Fixed8DecodeString(s) - if err != nil { - return err - } - *f = p - return nil - } - - var fl float64 - if err := json.Unmarshal(data, &fl); err != nil { - return err - } - - *f = Fixed8(float64(Fixed8Decimals) * fl) - return nil -} - -// MarshalJSON implements the json marshaller interface -func (f *Fixed8) MarshalJSON() ([]byte, error) { - var s = f.String() - return json.Marshal(s) -} - -type Double float64 - -func (n *Double) UnmarshalJSON(data []byte) error { - var s string - if err := json.Unmarshal(data, &s); err == nil { - if p, err := strconv.ParseFloat(s, 64); err == nil { - *n = Double(p) - } else { - return err - } - } else { - return err - } - return nil -} - -func (n *Double) MarshalJSON() ([]byte, error) { - return json.Marshal(fmt.Sprintf("%.8f", float64(*n))) -} +var ( + NewFixed8 = utils.NewFixed8 + Fixed8DecodeString = utils.Fixed8DecodeString +) diff --git a/common/types/int.go b/common/types/int.go index 995ea1d2..4233ba18 100644 --- a/common/types/int.go +++ b/common/types/int.go @@ -1,91 +1,12 @@ package types import ( - "encoding/json" - "math/big" + "github.com/cosmos/cosmos-sdk/types" ) -type Int struct { - i *big.Int -} +type Int = types.Int -func NewInt(n int64) Int { - return Int{big.NewInt(n)} -} - -func NewIntFromBigInt(i *big.Int) Int { - if i.BitLen() > 255 { - panic("NewIntFromBigInt() out of bound") - } - return Int{i} -} - -func (i Int) GT(i2 Int) bool { - return gt(i.i, i2.i) -} - -func gt(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) == 1 } - -// MarshalAmino defines custom encoding scheme -func (i Int) MarshalAmino() (string, error) { - if i.i == nil { // Necessary since default Uint initialization has i.i as nil - i.i = new(big.Int) - } - return marshalAmino(i.i) -} - -// UnmarshalAmino defines custom decoding scheme -func (i *Int) UnmarshalAmino(text string) error { - if i.i == nil { // Necessary since default Int initialization has i.i as nil - i.i = new(big.Int) - } - return unmarshalAmino(i.i, text) -} - -// MarshalJSON defines custom encoding scheme -func (i Int) MarshalJSON() ([]byte, error) { - if i.i == nil { // Necessary since default Uint initialization has i.i as nil - i.i = new(big.Int) - } - return marshalJSON(i.i) -} - -// UnmarshalJSON defines custom decoding scheme -func (i *Int) UnmarshalJSON(bz []byte) error { - if i.i == nil { // Necessary since default Int initialization has i.i as nil - i.i = new(big.Int) - } - return unmarshalJSON(i.i, bz) -} - -// MarshalAmino for custom encoding scheme -func marshalAmino(i *big.Int) (string, error) { - bz, err := i.MarshalText() - return string(bz), err -} - -// UnmarshalAmino for custom decoding scheme -func unmarshalAmino(i *big.Int, text string) (err error) { - return i.UnmarshalText([]byte(text)) -} - -// MarshalJSON for custom encoding scheme -// Must be encoded as a string for JSON precision -func marshalJSON(i *big.Int) ([]byte, error) { - text, err := i.MarshalText() - if err != nil { - return nil, err - } - return json.Marshal(string(text)) -} - -// UnmarshalJSON for custom decoding scheme -// Must be encoded as a string for JSON precision -func unmarshalJSON(i *big.Int, bz []byte) error { - var text string - err := json.Unmarshal(bz, &text) - if err != nil { - return err - } - return i.UnmarshalText([]byte(text)) -} +var ( + NewInt = types.NewInt + NewIntFromBigInt = types.NewIntFromBigInt +) diff --git a/common/types/kline.go b/common/types/kline.go deleted file mode 100644 index 5e460694..00000000 --- a/common/types/kline.go +++ /dev/null @@ -1,13 +0,0 @@ -package types - -type Kline struct { - Close float64 `json:"close,string"` - CloseTime int64 `json:"closeTime"` - High float64 `json:"high,string"` - Low float64 `json:"low,string"` - NumberOfTrades int32 `json:"numberOfTrades"` - Open float64 `json:"open,string"` - OpenTime int64 `json:"openTime"` - QuoteAssetVolume float64 `json:"quoteAssetVolume,string"` - Volume float64 `json:"volume,string"` -} diff --git a/common/types/nodeinfo.go b/common/types/nodeinfo.go index 9ad675ee..7a58555d 100644 --- a/common/types/nodeinfo.go +++ b/common/types/nodeinfo.go @@ -6,7 +6,6 @@ import ( "github.com/tendermint/tendermint/libs/common" ) -// Account definition type ResultStatus struct { NodeInfo NodeInfo `json:"node_info"` SyncInfo SyncInfo `json:"sync_info"` diff --git a/common/types/oracle.go b/common/types/oracle.go index 988e50cb..b351d4f0 100644 --- a/common/types/oracle.go +++ b/common/types/oracle.go @@ -2,10 +2,13 @@ package types import ( "encoding/binary" + + ctypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/sidechain" ) -type IbcChannelID uint8 -type IbcChainID uint16 +type IbcChannelID = ctypes.ChannelID +type IbcChainID = ctypes.ChainID const ( prefixLength = 1 @@ -14,10 +17,10 @@ const ( ) var ( - SideChainStorePrefixByIdKey = []byte{0x01} // prefix for each key to a side chain store prefix, by side chain id + SideChainStorePrefixByIdKey = sidechain.SideChainStorePrefixByIdKey - PrefixForSendSequenceKey = []byte{0xf0} - PrefixForReceiveSequenceKey = []byte{0xf1} + PrefixForSendSequenceKey = sidechain.PrefixForSendSequenceKey + PrefixForReceiveSequenceKey = sidechain.PrefixForReceiveSequenceKey ) func GetReceiveSequenceKey(destIbcChainID IbcChainID, channelID IbcChannelID) []byte { diff --git a/common/types/proposal.go b/common/types/proposal.go index c344dd4e..1c640a89 100644 --- a/common/types/proposal.go +++ b/common/types/proposal.go @@ -1,320 +1,53 @@ package types import ( - "encoding/json" - "fmt" - "time" - - "github.com/pkg/errors" + "github.com/cosmos/cosmos-sdk/x/gov" ) -// Type that represents Proposal Type as a byte -type ProposalKind byte +type ProposalKind = gov.ProposalKind -//nolint +// nolint const ( - ProposalTypeNil ProposalKind = 0x00 - ProposalTypeText ProposalKind = 0x01 - ProposalTypeParameterChange ProposalKind = 0x02 - ProposalTypeSoftwareUpgrade ProposalKind = 0x03 - ProposalTypeListTradingPair ProposalKind = 0x04 - // ProposalTypeFeeChange belongs to ProposalTypeParameterChange. We use this to make it easily to distinguish。 - ProposalTypeFeeChange ProposalKind = 0x05 - ProposalTypeCreateValidator ProposalKind = 0x06 - ProposalTypeRemoveValidator ProposalKind = 0x07 - ProposalTypeDelistTradingPair ProposalKind = 0x08 - ProposalTypeManageChanPermission ProposalKind = 0x09 - - ProposalTypeSCParamsChange ProposalKind = 0x81 - // cross side chain param change - ProposalTypeCSCParamsChange ProposalKind = 0x82 + ProposalTypeNil = gov.ProposalTypeNil + ProposalTypeText = gov.ProposalTypeText + ProposalTypeParameterChange = gov.ProposalTypeParameterChange + ProposalTypeSoftwareUpgrade = gov.ProposalTypeSoftwareUpgrade + ProposalTypeListTradingPair = gov.ProposalTypeListTradingPair + ProposalTypeFeeChange = gov.ProposalTypeFeeChange + ProposalTypeCreateValidator = gov.ProposalTypeCreateValidator + ProposalTypeRemoveValidator = gov.ProposalTypeRemoveValidator + ProposalTypeDelistTradingPair = gov.ProposalTypeDelistTradingPair + ProposalTypeManageChanPermission = gov.ProposalTypeManageChanPermission + + ProposalTypeSCParamsChange = gov.ProposalTypeSCParamsChange + ProposalTypeCSCParamsChange = gov.ProposalTypeCSCParamsChange ) -// Marshal needed for protobuf compatibility -func (pt ProposalKind) Marshal() ([]byte, error) { - return []byte{byte(pt)}, nil -} - -// Unmarshal needed for protobuf compatibility -func (pt *ProposalKind) Unmarshal(data []byte) error { - *pt = ProposalKind(data[0]) - return nil -} - -// Marshals to JSON using string -func (pt ProposalKind) MarshalJSON() ([]byte, error) { - return json.Marshal(pt.String()) -} - -// Unmarshals from JSON assuming Bech32 encoding -func (pt *ProposalKind) UnmarshalJSON(data []byte) error { - var s string - err := json.Unmarshal(data, &s) - if err != nil { - return nil - } - - bz2, err := ProposalTypeFromString(s) - if err != nil { - return err - } - *pt = bz2 - return nil -} - -// String to proposalType byte. Returns ff if invalid. -func ProposalTypeFromString(str string) (ProposalKind, error) { - switch str { - case "Text": - return ProposalTypeText, nil - case "ParameterChange": - return ProposalTypeParameterChange, nil - case "SoftwareUpgrade": - return ProposalTypeSoftwareUpgrade, nil - case "ListTradingPair": - return ProposalTypeListTradingPair, nil - case "FeeChange": - return ProposalTypeFeeChange, nil - case "CreateValidator": - return ProposalTypeCreateValidator, nil - case "RemoveValidator": - return ProposalTypeRemoveValidator, nil - case "DelistTradingPair": - return ProposalTypeDelistTradingPair, nil - case "SCParamsChange": - return ProposalTypeSCParamsChange, nil - case "CSCParamsChange": - return ProposalTypeCSCParamsChange, nil - case "ManageChanPermission": - return ProposalTypeManageChanPermission, nil - default: - return ProposalKind(0xff), errors.Errorf("'%s' is not a valid proposal type", str) - } -} - -// Turns VoteOption byte to String -func (pt ProposalKind) String() string { - switch pt { - case ProposalTypeText: - return "Text" - case ProposalTypeParameterChange: - return "ParameterChange" - case ProposalTypeSoftwareUpgrade: - return "SoftwareUpgrade" - case ProposalTypeListTradingPair: - return "ListTradingPair" - case ProposalTypeFeeChange: - return "FeeChange" - case ProposalTypeCreateValidator: - return "CreateValidator" - case ProposalTypeRemoveValidator: - return "RemoveValidator" - case ProposalTypeDelistTradingPair: - return "DelistTradingPair" - case ProposalTypeSCParamsChange: - return "SCParamsChange" - case ProposalTypeCSCParamsChange: - return "CSCParamsChange" - case ProposalTypeManageChanPermission: - return "ManageChanPermission" - default: - return "" - } -} - -type ProposalStatus byte - -//nolint -const ( - StatusNil ProposalStatus = 0x00 - StatusDepositPeriod ProposalStatus = 0x01 - StatusVotingPeriod ProposalStatus = 0x02 - StatusPassed ProposalStatus = 0x03 - StatusRejected ProposalStatus = 0x04 - StatusExecuted ProposalStatus = 0x05 +var ( + ProposalTypeFromString = gov.ProposalTypeFromString ) -// ProposalStatusToString turns a string into a ProposalStatus -func ProposalStatusFromString(str string) (ProposalStatus, error) { - switch str { - case "DepositPeriod": - return StatusDepositPeriod, nil - case "VotingPeriod": - return StatusVotingPeriod, nil - case "Passed": - return StatusPassed, nil - case "Rejected": - return StatusRejected, nil - case "Executed": - return StatusExecuted, nil - case "": - return StatusNil, nil - default: - return ProposalStatus(0xff), errors.Errorf("'%s' is not a valid proposal status", str) - } -} - -// Marshal needed for protobuf compatibility -func (status ProposalStatus) Marshal() ([]byte, error) { - return []byte{byte(status)}, nil -} - -// Unmarshal needed for protobuf compatibility -func (status *ProposalStatus) Unmarshal(data []byte) error { - *status = ProposalStatus(data[0]) - return nil -} - -// Marshals to JSON using string -func (status ProposalStatus) MarshalJSON() ([]byte, error) { - return json.Marshal(status.String()) -} - -// Unmarshals from JSON assuming Bech32 encoding -func (status *ProposalStatus) UnmarshalJSON(data []byte) error { - var s string - err := json.Unmarshal(data, &s) - if err != nil { - return nil - } - - bz2, err := ProposalStatusFromString(s) - if err != nil { - return err - } - *status = bz2 - return nil -} - -// Turns VoteStatus byte to String -func (status ProposalStatus) String() string { - switch status { - case StatusDepositPeriod: - return "DepositPeriod" - case StatusVotingPeriod: - return "VotingPeriod" - case StatusPassed: - return "Passed" - case StatusRejected: - return "Rejected" - case StatusExecuted: - return "Executed" - default: - return "" - } -} - -// For Printf / Sprintf, returns bech32 when using %s -// nolint: errcheck -func (status ProposalStatus) Format(s fmt.State, verb rune) { - switch verb { - case 's': - s.Write([]byte(status.String())) - default: - // TODO: Do this conversion more directly - s.Write([]byte(fmt.Sprintf("%v", byte(status)))) - } -} - -// Tally Results -type TallyResult struct { - Yes Dec `json:"yes"` - Abstain Dec `json:"abstain"` - No Dec `json:"no"` - NoWithVeto Dec `json:"no_with_veto"` - Total Dec `json:"total"` -} - -type Proposal interface { - GetProposalID() int64 - SetProposalID(int64) - - GetTitle() string - SetTitle(string) - - GetDescription() string - SetDescription(string) - - GetProposalType() ProposalKind - SetProposalType(ProposalKind) - - GetStatus() ProposalStatus - SetStatus(ProposalStatus) - - GetTallyResult() TallyResult - SetTallyResult(TallyResult) - - GetSubmitTime() time.Time - SetSubmitTime(time.Time) - - GetTotalDeposit() Coins - SetTotalDeposit(Coins) - - GetVotingStartTime() time.Time - SetVotingStartTime(time.Time) - - GetVotingPeriod() time.Duration - SetVotingPeriod(time.Duration) -} - -// Text Proposals -type TextProposal struct { - ProposalID int64 `json:"proposal_id"` // ID of the proposal - Title string `json:"title"` // Title of the proposal - Description string `json:"description"` // Description of the proposal - ProposalType ProposalKind `json:"proposal_type"` // Type of proposal. Initial set {PlainTextProposal, SoftwareUpgradeProposal} - VotingPeriod time.Duration `json:"voting_period"` // Length of the voting period - - Status ProposalStatus `json:"proposal_status"` // Status of the Proposal {Pending, Active, Passed, Rejected} - TallyResult TallyResult `json:"tally_result"` // Result of Tallys - - SubmitTime time.Time `json:"submit_time"` // Height of the block where TxGovSubmitProposal was included - TotalDeposit Coins `json:"total_deposit"` // Current deposit on this proposal. Initial value is set at InitialDeposit - - VotingStartTime time.Time `json:"voting_start_time"` // Height of the block where MinDeposit was reached. -1 if MinDeposit is not reached -} - -// Implements Proposal Interface -var _ Proposal = (*TextProposal)(nil) +type ProposalStatus = gov.ProposalStatus // nolint -func (tp TextProposal) GetProposalID() int64 { return tp.ProposalID } -func (tp *TextProposal) SetProposalID(proposalID int64) { tp.ProposalID = proposalID } -func (tp TextProposal) GetTitle() string { return tp.Title } -func (tp *TextProposal) SetTitle(title string) { tp.Title = title } -func (tp TextProposal) GetDescription() string { return tp.Description } -func (tp *TextProposal) SetDescription(description string) { tp.Description = description } -func (tp TextProposal) GetProposalType() ProposalKind { return tp.ProposalType } -func (tp *TextProposal) SetProposalType(proposalType ProposalKind) { tp.ProposalType = proposalType } -func (tp TextProposal) GetStatus() ProposalStatus { return tp.Status } -func (tp *TextProposal) SetStatus(status ProposalStatus) { tp.Status = status } -func (tp TextProposal) GetTallyResult() TallyResult { return tp.TallyResult } -func (tp *TextProposal) SetTallyResult(tallyResult TallyResult) { tp.TallyResult = tallyResult } -func (tp TextProposal) GetSubmitTime() time.Time { return tp.SubmitTime } -func (tp *TextProposal) SetSubmitTime(submitTime time.Time) { tp.SubmitTime = submitTime } -func (tp TextProposal) GetTotalDeposit() Coins { return tp.TotalDeposit } -func (tp *TextProposal) SetTotalDeposit(totalDeposit Coins) { tp.TotalDeposit = totalDeposit } -func (tp TextProposal) GetVotingStartTime() time.Time { return tp.VotingStartTime } -func (tp *TextProposal) SetVotingStartTime(votingStartTime time.Time) { - tp.VotingStartTime = votingStartTime -} -func (tp TextProposal) GetVotingPeriod() time.Duration { return tp.VotingPeriod } -func (tp *TextProposal) SetVotingPeriod(votingPeriod time.Duration) { - tp.VotingPeriod = votingPeriod -} - -type BaseParams struct { - SideChainId string -} +const ( + StatusNil = gov.StatusNil + StatusDepositPeriod = gov.StatusDepositPeriod + StatusVotingPeriod = gov.StatusVotingPeriod + StatusPassed = gov.StatusPassed + StatusRejected = gov.StatusRejected + StatusExecuted = gov.StatusExecuted +) -type QueryProposalsParams struct { - BaseParams - ProposalStatus ProposalStatus - NumLatestProposals int64 -} +var ( + ProposalStatusFromString = gov.ProposalStatusFromString +) -// Params for query 'custom/gov/proposal' -type QueryProposalParams struct { - BaseParams - ProposalID int64 -} +type ( + TallyResult = gov.TallyResult + Proposal = gov.Proposal + TextProposal = gov.TextProposal + BaseParams = gov.BaseParams + QueryProposalsParams = gov.QueryProposalsParams + QueryProposalParams = gov.QueryProposalParams +) diff --git a/common/types/query.go b/common/types/query.go index 909ceb2f..21e1e438 100644 --- a/common/types/query.go +++ b/common/types/query.go @@ -2,8 +2,6 @@ package types import ( "errors" - - "github.com/binance-chain/go-sdk/common" ) const ( @@ -13,322 +11,11 @@ const ( var ( // Param error - AddressMissingError = errors.New("Address is required ") - SymbolMissingError = errors.New("Symbol is required ") - OffsetOutOfRangeError = errors.New("offset out of range ") - LimitOutOfRangeError = errors.New("limit out of range ") - TradeSideMisMatchError = errors.New("Trade side is invalid ") - StartTimeOutOfRangeError = errors.New("start time out of range ") - EndTimeOutOfRangeError = errors.New("end time out of range ") - IntervalMissingError = errors.New("interval is required ") - EndTimeLessThanStartTimeError = errors.New("end time should great than start time") - OrderIdMissingError = errors.New("order id is required ") + AddressMissingError = errors.New("Address is required ") + OffsetOutOfRangeError = errors.New("offset out of range ") + LimitOutOfRangeError = errors.New("limit out of range ") ) -// ClosedOrdersQuery definition -type ClosedOrdersQuery struct { - SenderAddress string `json:"address"` // required - Symbol string `json:"symbol,omitempty"` //option - Offset *uint32 `json:"offset,omitempty,string"` //option - Limit *uint32 `json:"limit,omitempty,string"` //option - Start *int64 `json:"start,omitempty,string"` //option - End *int64 `json:"end,omitempty,string"` //option - Side string `json:"side,omitempty"` //option - Total int `json:"total,string"` //0 for not required and 1 for required; default not required, return total=-1 in response -} - -func NewClosedOrdersQuery(senderAddress string, withTotal bool) *ClosedOrdersQuery { - totalQuery := 0 - if withTotal { - totalQuery = 1 - } - return &ClosedOrdersQuery{SenderAddress: senderAddress, Total: totalQuery} -} - -func (param *ClosedOrdersQuery) Check() error { - if param.SenderAddress == "" { - return AddressMissingError - } - if param.Side != SideBuy && param.Side != SideSell && param.Side != "" { - return TradeSideMisMatchError - } - if param.Limit != nil && *param.Limit <= 0 { - return LimitOutOfRangeError - } - if param.Start != nil && *param.Start <= 0 { - return StartTimeOutOfRangeError - } - if param.End != nil && *param.End <= 0 { - return EndTimeOutOfRangeError - } - if param.Start != nil && param.End != nil && *param.Start > *param.End { - return EndTimeLessThanStartTimeError - } - return nil -} - -func (param *ClosedOrdersQuery) WithSymbol(baseAssetSymbol, quoteAssetSymbol string) *ClosedOrdersQuery { - param.Symbol = common.CombineSymbol(baseAssetSymbol, quoteAssetSymbol) - return param -} - -func (param *ClosedOrdersQuery) WithOffset(offset uint32) *ClosedOrdersQuery { - param.Offset = &offset - return param -} - -func (param *ClosedOrdersQuery) WithLimit(limit uint32) *ClosedOrdersQuery { - param.Limit = &limit - return param -} - -func (param *ClosedOrdersQuery) WithStart(start int64) *ClosedOrdersQuery { - param.Start = &start - return param -} - -func (param *ClosedOrdersQuery) WithEnd(end int64) *ClosedOrdersQuery { - param.End = &end - return param -} - -func (param *ClosedOrdersQuery) WithSide(side string) *ClosedOrdersQuery { - param.Side = side - return param -} - -// TradesQuery definition -type TradesQuery struct { - SenderAddress *string `json:"address,omitempty"` // option - Symbol string `json:"symbol,omitempty"` //option - Offset *uint32 `json:"offset,omitempty,string"` //option - Limit *uint32 `json:"limit,omitempty,string"` //option - Start *int64 `json:"start,omitempty,string"` //option - End *int64 `json:"end,omitempty,string"` //option - Side *string `json:"side,omitempty"` //option - Total int `json:"total,string"` //0 for not required and 1 for required; default not required, return total=-1 in response -} - -func NewTradesQuery(withTotal bool) *TradesQuery { - totalQuery := 0 - if withTotal { - totalQuery = 1 - } - return &TradesQuery{Total: totalQuery} -} - -func (param *TradesQuery) Check() error { - if param.Side != nil && *param.Side != SideBuy && *param.Side != SideSell && *param.Side != "" { - return TradeSideMisMatchError - } - if param.Limit != nil && *param.Limit <= 0 { - return LimitOutOfRangeError - } - if param.Start != nil && *param.Start <= 0 { - return StartTimeOutOfRangeError - } - if param.End != nil && *param.End <= 0 { - return EndTimeOutOfRangeError - } - if param.Start != nil && param.End != nil && *param.Start > *param.End { - return EndTimeLessThanStartTimeError - } - return nil -} - -func (param *TradesQuery) WithSymbol(baseAssetSymbol, quoteAssetSymbol string) *TradesQuery { - param.Symbol = common.CombineSymbol(baseAssetSymbol, quoteAssetSymbol) - return param -} - -func (param *TradesQuery) WithOffset(offset uint32) *TradesQuery { - param.Offset = &offset - return param -} - -func (param *TradesQuery) WithLimit(limit uint32) *TradesQuery { - param.Limit = &limit - return param -} - -func (param *TradesQuery) WithStart(start int64) *TradesQuery { - param.Start = &start - return param -} - -func (param *TradesQuery) WithEnd(end int64) *TradesQuery { - param.End = &end - return param -} - -func (param *TradesQuery) WithSide(side string) *TradesQuery { - param.Side = &side - return param -} - -func (param *TradesQuery) WithAddress(addr string) *TradesQuery { - param.SenderAddress = &addr - return param -} - -// Ticker24hQuery definition -type Ticker24hQuery struct { - Symbol string `json:"symbol,omitempty"` -} - -func NewTicker24hQuery() *Ticker24hQuery { - return &Ticker24hQuery{} -} - -func (param *Ticker24hQuery) WithSymbol(baseAssetSymbol, quoteAssetSymbol string) *Ticker24hQuery { - param.Symbol = common.CombineSymbol(baseAssetSymbol, quoteAssetSymbol) - return param -} - -// OpenOrdersQuery definition -type OpenOrdersQuery struct { - SenderAddress string `json:"address"` // required - Symbol string `json:"symbol,omitempty"` - Offset *uint32 `json:"offset,omitempty,string"` - Limit *uint32 `json:"limit,omitempty,string"` - Total int `json:"total,string"` //0 for not required and 1 for required; default not required, return total=-1 in response -} - -func NewOpenOrdersQuery(senderAddress string, withTotal bool) *OpenOrdersQuery { - totalQuery := 0 - if withTotal { - totalQuery = 1 - } - return &OpenOrdersQuery{SenderAddress: senderAddress, Total: totalQuery} -} - -func (param *OpenOrdersQuery) WithSymbol(symbol string) *OpenOrdersQuery { - param.Symbol = symbol - return param -} - -func (param *OpenOrdersQuery) WithOffset(offset uint32) *OpenOrdersQuery { - param.Offset = &offset - return param -} - -func (param *OpenOrdersQuery) WithLimit(limit uint32) *OpenOrdersQuery { - param.Limit = &limit - return param -} - -func (param *OpenOrdersQuery) Check() error { - if param.SenderAddress == "" { - return AddressMissingError - } - if param.Limit != nil && *param.Limit <= 0 { - return LimitOutOfRangeError - } - return nil -} - -// DepthQuery -type DepthQuery struct { - Symbol string `json:"symbol"` - Limit *uint32 `json:"limit,omitempty,string"` -} - -func NewDepthQuery(baseAssetSymbol, quoteAssetSymbol string) *DepthQuery { - return &DepthQuery{Symbol: common.CombineSymbol(baseAssetSymbol, quoteAssetSymbol)} -} - -func (param *DepthQuery) WithLimit(limit uint32) *DepthQuery { - param.Limit = &limit - return param -} - -func (param *DepthQuery) Check() error { - if param.Symbol == "" { - return SymbolMissingError - } - if param.Limit != nil && *param.Limit <= 0 { - return LimitOutOfRangeError - } - return nil -} - -// KlineQuery definition -type KlineQuery struct { - Symbol string `json:"symbol"` // required - Interval string `json:"interval"` // required, interval (5m, 1h, 1d, 1w, etc.) - Limit *uint32 `json:"limit,omitempty,string"` - StartTime *int64 `json:"start_time,omitempty,string"` - EndTime *int64 `json:"end_time,omitempty,string"` -} - -func NewKlineQuery(baseAssetSymbol, quoteAssetSymbol, interval string) *KlineQuery { - return &KlineQuery{Symbol: common.CombineSymbol(baseAssetSymbol, quoteAssetSymbol), Interval: interval} -} - -func (param *KlineQuery) WithStartTime(start int64) *KlineQuery { - param.StartTime = &start - return param -} - -func (param *KlineQuery) WithEndTime(end int64) *KlineQuery { - param.EndTime = &end - return param -} - -func (param *KlineQuery) WithLimit(limit uint32) *KlineQuery { - param.Limit = &limit - return param -} - -func (param *KlineQuery) Check() error { - if param.Symbol == "" { - return SymbolMissingError - } - if param.Interval == "" { - return IntervalMissingError - } - if param.Limit != nil && *param.Limit <= 0 { - return LimitOutOfRangeError - } - if param.StartTime != nil && *param.StartTime <= 0 { - return StartTimeOutOfRangeError - } - if param.EndTime != nil && *param.EndTime <= 0 { - return EndTimeOutOfRangeError - } - if param.StartTime != nil && param.EndTime != nil && *param.StartTime > *param.EndTime { - return EndTimeLessThanStartTimeError - } - return nil -} - -// MarketsQuery definition -type MarketsQuery struct { - Offset *uint32 `json:"offset,omitempty,string"` //Option - Limit *uint32 `json:"limit,omitempty,string"` //Option -} - -func NewMarketsQuery() *MarketsQuery { - return &MarketsQuery{} -} - -func (param *MarketsQuery) WithOffset(offset uint32) *MarketsQuery { - param.Offset = &offset - return param -} - -func (param *MarketsQuery) WithLimit(limit uint32) *MarketsQuery { - param.Limit = &limit - return param -} - -func (param *MarketsQuery) Check() error { - if param.Limit != nil && *param.Limit <= 0 { - return LimitOutOfRangeError - } - return nil -} - // TokensQuery definition type TokensQuery struct { Offset *uint32 `json:"offset,omitempty,string"` //Option diff --git a/common/types/scripts.go b/common/types/scripts.go index 69aa8478..9472ecd3 100644 --- a/common/types/scripts.go +++ b/common/types/scripts.go @@ -1,7 +1,9 @@ package types -type FlagOption uint64 +import "github.com/bnb-chain/node/plugins/account/scripts" + +type FlagOption = uint64 const ( - TransferMemoCheckerFlag FlagOption = 0x0000000000000001 + TransferMemoCheckerFlag = scripts.TransferMemoCheckerFlag ) diff --git a/common/types/stake.go b/common/types/stake.go index bb8ac074..c0e506ae 100644 --- a/common/types/stake.go +++ b/common/types/stake.go @@ -1,356 +1,42 @@ package types import ( - "bytes" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "time" - - "github.com/binance-chain/go-sdk/common/bech32" - "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/stake" + stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" ) -type ValAddress []byte - -type BondStatus byte - // nolint const ( - Unbonded BondStatus = 0x00 - Unbonding BondStatus = 0x01 - Bonded BondStatus = 0x02 + Unbonded = types.Unbonded + Unbonding = types.Unbonding + Bonded = types.Bonded ) type ( - // Commission defines a commission parameters for a given validator. - Commission struct { - Rate Dec `json:"rate"` // the commission rate charged to delegators - MaxRate Dec `json:"max_rate"` // maximum commission rate which validator can ever charge - MaxChangeRate Dec `json:"max_change_rate"` // maximum daily increase of the validator commission - UpdateTime time.Time `json:"update_time"` // the last time the commission rate was changed - } - - // CommissionMsg defines a commission message to be used for creating a - // validator. - CommissionMsg struct { - Rate Dec `json:"rate"` // the commission rate charged to delegators - MaxRate Dec `json:"max_rate"` // maximum commission rate which validator can ever charge - MaxChangeRate Dec `json:"max_change_rate"` // maximum daily increase of the validator commission - } + Commission = stakeTypes.Commission + CommissionMsg = stakeTypes.CommissionMsg + Description = stakeTypes.Description + Validator = stakeTypes.Validator + UnbondingDelegation = stakeTypes.UnbondingDelegation + Pool = stakeTypes.Pool + + ValAddress = types.ValAddress + BondStatus = types.BondStatus + ConsAddress = types.ConsAddress + + QueryTopValidatorsParams = stake.QueryTopValidatorsParams + QueryBondsParams = stake.QueryBondsParams + QueryValidatorParams = stake.QueryValidatorParams ) -func NewCommission(rate, maxRate, maxChangeRate Dec) Commission { - return Commission{ - Rate: rate, - MaxRate: maxRate, - MaxChangeRate: maxChangeRate, - UpdateTime: time.Unix(0, 0).UTC(), - } -} - -// Validate performs basic sanity validation checks of initial commission -// parameters. If validation fails, an error is returned. -func (c Commission) Validate() error { - switch { - case c.MaxRate.LT(ZeroDec()): - // max rate cannot be negative - return fmt.Errorf("Commission maxrate %v is negative", c.MaxRate) - - case c.MaxRate.GT(OneDec()): - // max rate cannot be greater than 100% - return fmt.Errorf("Commission maxrate %v can't be greater than 100%", c.MaxRate) - - case c.Rate.LT(ZeroDec()): - // rate cannot be negative - return fmt.Errorf("Commission rate %v can't be negative ", c.Rate) - - case c.Rate.GT(c.MaxRate): - // rate cannot be greater than the max rate - return fmt.Errorf("Commission rate %v can't be greater than maxrate %v", c.Rate, c.MaxRate) - - case c.MaxChangeRate.LT(ZeroDec()): - // change rate cannot be negative - return fmt.Errorf("Commission change rate %v can't be negative", c.MaxChangeRate) - - case c.MaxChangeRate.GT(c.MaxRate): - // change rate cannot be greater than the max rate - return fmt.Errorf("Commission change rate %v can't be greater than MaxRat %v", c.MaxChangeRate, c.MaxRate) - } - - return nil -} - -// ValidateNewRate performs basic sanity validation checks of a new commission -// rate. If validation fails, an SDK error is returned. -func (c Commission) ValidateNewRate(newRate Dec, blockTime time.Time) error { - switch { - case blockTime.Sub(c.UpdateTime).Hours() < 24: - // new rate cannot be changed more than once within 24 hours - return fmt.Errorf("new rate %v cannot be changed more than once within 24 hours", blockTime.Sub(c.UpdateTime).Hours()) - - case newRate.LT(ZeroDec()): - // new rate cannot be negative - return fmt.Errorf("new rate %v cannot be negative", newRate) - - case newRate.GT(c.MaxRate): - // new rate cannot be greater than the max rate - return fmt.Errorf("new rate %v cannot be greater than the max rate %v", newRate, c.MaxRate) - - case newRate.Sub(c.Rate).Abs().GT(c.MaxChangeRate): - // new rate % points change cannot be greater than the max change rate - return fmt.Errorf("new rate %v points change cannot be greater than the max change rate %v", newRate.Sub(c.Rate).Abs(), c.MaxChangeRate) - } - - return nil -} - -func (c Commission) String() string { - return fmt.Sprintf("rate: %s, maxRate: %s, maxChangeRate: %s, updateTime: %s", - c.Rate, c.MaxRate, c.MaxChangeRate, c.UpdateTime, - ) -} - -// Description - description fields for a validator -type Description struct { - Moniker string `json:"moniker"` // name - Identity string `json:"identity"` // optional identity signature (ex. UPort or Keybase) - Website string `json:"website"` // optional website link - Details string `json:"details"` // optional details -} - -// Validator defines the total amount of bond shares and their exchange rate to -// coins. Accumulation of interest is modelled as an in increase in the -// exchange rate, and slashing as a decrease. When coins are delegated to this -// validator, the validator is credited with a Delegation whose number of -// bond shares is based on the amount of coins delegated divided by the current -// exchange rate. Voting power can be calculated as total bonds multiplied by -// exchange rate. -type Validator struct { - FeeAddr AccAddress `json:"fee_addr"` // address for fee collection - OperatorAddr ValAddress `json:"operator_address"` // address of the validator's operator; bech encoded in JSON - ConsPubKey string `json:"consensus_pubkey"` // the consensus public key of the validator; bech encoded in JSON - Jailed bool `json:"jailed"` // has the validator been jailed from bonded status? - - Status BondStatus `json:"status"` // validator status (bonded/unbonding/unbonded) - Tokens Dec `json:"tokens"` // delegated tokens (incl. self-delegation) - DelegatorShares Dec `json:"delegator_shares"` // total shares issued to a validator's delegators - - Description Description `json:"description"` // description terms for the validator - BondHeight int64 `json:"bond_height"` // earliest height as a bonded validator - BondIntraTxCounter int16 `json:"bond_intra_tx_counter"` // block-local tx index of validator change - - UnbondingHeight int64 `json:"unbonding_height"` // if unbonding, height at which this validator has begun unbonding - UnbondingMinTime time.Time `json:"unbonding_time"` // if unbonding, min time for the validator to complete unbonding - - Commission Commission `json:"commission"` // commission parameters - - DistributionAddr AccAddress `json:"distribution_addr"` // the address receives rewards from the side address, and distribute rewards to delegators. It's auto generated - SideChainId string `json:"side_chain_id"` // side chain id to distinguish different side chains - SideConsAddr []byte `json:"side_cons_addr"` // consensus address of the side chain validator, this replaces the `ConsPubKey` - SideFeeAddr []byte `json:"side_fee_addr"` // fee address on the side chain - - StakeSnapshots []Dec `json:"stake_snapshots"` // staked tokens snapshot over a period of time, e.g. 30 days - AccumulatedStake Dec `json:"accumulated_stake"` // accumulated stake, sum of StakeSnapshots -} - -type UnbondingDelegation struct { - DelegatorAddr AccAddress `json:"delegator_addr"` // delegator - ValidatorAddr ValAddress `json:"validator_addr"` // validator unbonding from operator addr - CreationHeight int64 `json:"creation_height"` // height which the unbonding took place - MinTime time.Time `json:"min_time"` // unix time for unbonding completion - InitialBalance Coin `json:"initial_balance"` // atoms initially scheduled to receive at completion - Balance Coin `json:"balance"` // atoms to receive at completion -} - -func (va ValAddress) String() string { - bech32PrefixValAddr := Network.Bech32ValidatorAddrPrefix() - bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixValAddr, va.Bytes()) - if err != nil { - panic(err) - } - - return bech32Addr -} - -func (va ValAddress) Bytes() []byte { - return va -} - -// MarshalJSON marshals to JSON using Bech32. -func (va ValAddress) MarshalJSON() ([]byte, error) { - return json.Marshal(va.String()) -} - -// UnmarshalJSON unmarshals from JSON assuming Bech32 encoding. -func (va *ValAddress) UnmarshalJSON(data []byte) error { - var s string - - err := json.Unmarshal(data, &s) - if err != nil { - return nil - } +var ( + NewCommission = stakeTypes.NewCommission - va2, err := ValAddressFromBech32(s) - if err != nil { - return err - } + ValAddressFromBech32 = types.ValAddressFromBech32 + ConsAddressFromHex = types.ConsAddressFromHex + ConsAddressFromBech32 = types.ConsAddressFromBech32 + GetConsAddress = types.GetConsAddress - *va = va2 - return nil -} - -func ValAddressFromBech32(address string) (addr ValAddress, err error) { - bech32PrefixValAddr := Network.Bech32ValidatorAddrPrefix() - bz, err := GetFromBech32(address, bech32PrefixValAddr) - if err != nil { - return nil, err - } - - return ValAddress(bz), nil -} - -// consensus node -// ---------------------------------------------------------------------------- - -// ConsAddress defines a wrapper around bytes meant to present a consensus node. -// When marshaled to a string or JSON, it uses Bech32. -type ConsAddress []byte - -// ConsAddressFromHex creates a ConsAddress from a hex string. -func ConsAddressFromHex(address string) (addr ConsAddress, err error) { - if len(address) == 0 { - return addr, errors.New("decoding Bech32 address failed: must provide an address") - } - - bz, err := hex.DecodeString(address) - if err != nil { - return nil, err - } - - return ConsAddress(bz), nil -} - -// ConsAddressFromBech32 creates a ConsAddress from a Bech32 string. -func ConsAddressFromBech32(address string) (addr ConsAddress, err error) { - bz, err := GetFromBech32(address, bech32PrefixConsAddr) - if err != nil { - return nil, err - } - - return ConsAddress(bz), nil -} - -// get ConsAddress from pubkey -func GetConsAddress(pubkey crypto.PubKey) ConsAddress { - return ConsAddress(pubkey.Address()) -} - -// Returns boolean for whether two ConsAddress are Equal -func (ca ConsAddress) Equals(ca2 ConsAddress) bool { - if ca.Empty() && ca2.Empty() { - return true - } - - return bytes.Compare(ca.Bytes(), ca2.Bytes()) == 0 -} - -// Returns boolean for whether an ConsAddress is empty -func (ca ConsAddress) Empty() bool { - if ca == nil { - return true - } - - ca2 := ConsAddress{} - return bytes.Compare(ca.Bytes(), ca2.Bytes()) == 0 -} - -// Marshal returns the raw address bytes. It is needed for protobuf -// compatibility. -func (ca ConsAddress) Marshal() ([]byte, error) { - return ca, nil -} - -// Unmarshal sets the address to the given data. It is needed for protobuf -// compatibility. -func (ca *ConsAddress) Unmarshal(data []byte) error { - *ca = data - return nil -} - -// MarshalJSON marshals to JSON using Bech32. -func (ca ConsAddress) MarshalJSON() ([]byte, error) { - return json.Marshal(ca.String()) -} - -// UnmarshalJSON unmarshals from JSON assuming Bech32 encoding. -func (ca *ConsAddress) UnmarshalJSON(data []byte) error { - var s string - - err := json.Unmarshal(data, &s) - if err != nil { - return nil - } - - ca2, err := ConsAddressFromBech32(s) - if err != nil { - return err - } - - *ca = ca2 - return nil -} - -// Bytes returns the raw address bytes. -func (ca ConsAddress) Bytes() []byte { - return ca -} - -// String implements the Stringer interface. -func (ca ConsAddress) String() string { - bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixConsAddr, ca.Bytes()) - if err != nil { - panic(err) - } - - return bech32Addr -} - -// Format implements the fmt.Formatter interface. -// nolint: errcheck -func (ca ConsAddress) Format(s fmt.State, verb rune) { - switch verb { - case 's': - s.Write([]byte(fmt.Sprintf("%s", ca.String()))) - case 'p': - s.Write([]byte(fmt.Sprintf("%p", ca))) - default: - s.Write([]byte(fmt.Sprintf("%X", []byte(ca)))) - } -} - -func NewBaseParams(sideChainId string) BaseParams { - return BaseParams{SideChainId: sideChainId} -} - -type QueryTopValidatorsParams struct { - BaseParams - Top int -} - -type QueryBondsParams struct { - BaseParams - DelegatorAddr AccAddress - ValidatorAddr ValAddress -} - -type QueryValidatorParams struct { - BaseParams - ValidatorAddr ValAddress -} - -type Pool struct { - LooseTokens Dec `json:"loose_tokens"` // tokens which are not bonded in a validator - BondedTokens Dec `json:"bonded_tokens"` // reserve of bonded tokens -} + NewBaseParams = stake.NewBaseParams +) diff --git a/common/types/swap.go b/common/types/swap.go index ccbe7539..fa1fea99 100644 --- a/common/types/swap.go +++ b/common/types/swap.go @@ -1,128 +1,25 @@ package types import ( - "encoding/hex" - "encoding/json" - "fmt" + "github.com/bnb-chain/node/plugins/tokens/swap" ) -type SwapStatus byte - const ( - NULL SwapStatus = 0x00 - Open SwapStatus = 0x01 - Completed SwapStatus = 0x02 - Expired SwapStatus = 0x03 + NULL = swap.NULL + Open = swap.Open + Completed = swap.Completed + Expired = swap.Expired ) -func NewSwapStatusFromString(str string) SwapStatus { - switch str { - case "Open", "open": - return Open - case "Completed", "completed": - return Completed - case "Expired", "expired": - return Expired - default: - return NULL - } -} - -func (status SwapStatus) String() string { - switch status { - case Open: - return "Open" - case Completed: - return "Completed" - case Expired: - return "Expired" - default: - return "NULL" - } -} - -func (status SwapStatus) MarshalJSON() ([]byte, error) { - return json.Marshal(status.String()) -} - -func (status *SwapStatus) UnmarshalJSON(data []byte) error { - var s string - err := json.Unmarshal(data, &s) - if err != nil { - return err - } - *status = NewSwapStatusFromString(s) - return nil -} - -type SwapBytes []byte - -func (bz SwapBytes) Marshal() ([]byte, error) { - return bz, nil -} - -func (bz *SwapBytes) Unmarshal(data []byte) error { - *bz = data - return nil -} - -func (bz SwapBytes) MarshalJSON() ([]byte, error) { - s := hex.EncodeToString(bz) - jbz := make([]byte, len(s)+2) - jbz[0] = '"' - copy(jbz[1:], []byte(s)) - jbz[len(jbz)-1] = '"' - return jbz, nil -} - -func (bz *SwapBytes) UnmarshalJSON(data []byte) error { - if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' { - return fmt.Errorf("Invalid hex string: %s", data) - } - bz2, err := hex.DecodeString(string(data[1 : len(data)-1])) - if err != nil { - return err - } - *bz = bz2 - return nil -} - -type AtomicSwap struct { - From AccAddress `json:"from"` - To AccAddress `json:"to"` - OutAmount Coins `json:"out_amount"` - InAmount Coins `json:"in_amount"` - - ExpectedIncome string `json:"expected_income"` - RecipientOtherChain string `json:"recipient_other_chain"` - - RandomNumberHash SwapBytes `json:"random_number_hash"` - RandomNumber SwapBytes `json:"random_number"` - Timestamp int64 `json:"timestamp"` - - CrossChain bool `json:"cross_chain"` - - ExpireHeight int64 `json:"expire_height"` - Index int64 `json:"index"` - ClosedTime int64 `json:"closed_time"` - Status SwapStatus `json:"status"` -} - -// Params for query 'custom/atomicswap/swapid' -type QuerySwapByID struct { - SwapID SwapBytes -} - -// Params for query 'custom/atomicswap/swapcreator' -type QuerySwapByCreatorParams struct { - Creator AccAddress - Limit int64 - Offset int64 -} +var ( + NewSwapStatusFromString = swap.NewSwapStatusFromString +) -// Params for query 'custom/atomicswap/swaprecipient' -type QuerySwapByRecipientParams struct { - Recipient AccAddress - Limit int64 - Offset int64 -} +type ( + SwapStatus = swap.SwapStatus + SwapBytes = swap.SwapBytes + AtomicSwap = swap.AtomicSwap + QuerySwapByID swap.QuerySwapByID + QuerySwapByCreatorParams = swap.QuerySwapByCreatorParams + QuerySwapByRecipientParams swap.QuerySwapByRecipientParams +) diff --git a/common/types/ticker.go b/common/types/ticker.go deleted file mode 100644 index 71977488..00000000 --- a/common/types/ticker.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -type Ticker24h struct { - Symbol string `json:"symbol"` - AskPrice string `json:"askPrice"` // In decimal form, e.g. 1.00000000 - AskQuantity string `json:"askQuantity"` // In decimal form, e.g. 1.00000000 - BidPrice string `json:"bidPrice"` // In decimal form, e.g. 1.00000000 - BidQuantity string `json:"bidQuantity"` // In decimal form, e.g. 1.00000000 - CloseTime int64 `json:"closeTime"` - Count int64 `json:"count"` - FirstID string `json:"firstId"` - HighPrice string `json:"highPrice"` // In decimal form, e.g. 1.00000000 - LastID string `json:"lastId"` - LastPrice string `json:"lastPrice"` // In decimal form, e.g. 1.00000000 - LastQuantity string `json:"lastQuantity"` // In decimal form, e.g. 1.00000000 - LowPrice string `json:"lowPrice"` // In decimal form, e.g. 1.00000000 - OpenPrice string `json:"openPrice"` // In decimal form, e.g. 1.00000000 - OpenTime int64 `json:"openTime"` - PrevClosePrice string `json:"prevClosePrice"` // In decimal form, e.g. 1.00000000 - PriceChange string `json:"priceChange"` // In decimal form, e.g. 1.00000000 - PriceChangePercent string `json:"priceChangePercent"` - QuoteVolume string `json:"quoteVolume"` // In decimal form, e.g. 1.00000000 - Volume string `json:"volume"` // In decimal form, e.g. 1.00000000 - WeightedAvgPrice string `json:"weightedAvgPrice"` // In decimal form, e.g. 1.00000000 -} diff --git a/common/types/timelock.go b/common/types/timelock.go index 8f63b8ac..41c6c6c7 100644 --- a/common/types/timelock.go +++ b/common/types/timelock.go @@ -1,21 +1,11 @@ package types -import "time" - -type TimeLockRecord struct { - Id int64 `json:"id"` - Description string `json:"description"` - Amount Coins `json:"amount"` - LockTime time.Time `json:"lock_time"` -} - -// Params for query 'custom/timelock/timelocks' -type QueryTimeLocksParams struct { - Account AccAddress -} - -// Params for query 'custom/timelock/timelock' -type QueryTimeLockParams struct { - Account AccAddress - Id int64 -} +import ( + "github.com/bnb-chain/node/plugins/tokens/timelock" +) + +type ( + TimeLockRecord = timelock.TimeLockRecord + QueryTimeLocksParams = timelock.QueryTimeLocksParams + QueryTimeLockParams = timelock.QueryTimeLockParams +) diff --git a/common/types/tokens.go b/common/types/tokens.go index ecd4cec2..eb9e3ec3 100644 --- a/common/types/tokens.go +++ b/common/types/tokens.go @@ -1,34 +1,12 @@ package types -// Token definition -type Token struct { - Name string `json:"name"` - Symbol string `json:"symbol"` - OrigSymbol string `json:"original_symbol"` - TotalSupply Fixed8 `json:"total_supply"` - Owner AccAddress `json:"owner"` - Mintable bool `json:"mintable"` - ContractAddress string `json:"contract_address,omitempty"` - ContractDecimals int8 `json:"contract_decimals,omitempty"` -} +import ( + nodeTypes "github.com/bnb-chain/node/common/types" + "github.com/bnb-chain/node/plugins/tokens/client/rest" +) -type TokenBalance struct { - Symbol string `json:"symbol"` - Free Fixed8 `json:"free"` - Locked Fixed8 `json:"locked"` - Frozen Fixed8 `json:"frozen"` -} - -// MiniToken definition -type MiniToken struct { - Name string `json:"name"` - Symbol string `json:"symbol"` - OrigSymbol string `json:"original_symbol"` - TotalSupply Fixed8 `json:"total_supply"` - Owner AccAddress `json:"owner"` - Mintable bool `json:"mintable"` - TokenType int8 `json:"token_type"` - TokenURI string `json:"token_uri"` - ContractAddress string `json:"contract_address,omitempty"` - ContractDecimals int8 `json:"contract_decimals,omitempty"` -} +type ( + Token = nodeTypes.Token + MiniToken = nodeTypes.MiniToken + TokenBalance = rest.TokenBalance +) diff --git a/common/types/trade.go b/common/types/trade.go deleted file mode 100644 index 50df85fd..00000000 --- a/common/types/trade.go +++ /dev/null @@ -1,144 +0,0 @@ -package types - -// OrderSide enum -var OrderSide = struct { - BUY string - SELL string -}{ - "BUY", - "SELL", -} - -// TimeInForce enum -var TimeInForce = struct { - GTC string - IOC string -}{"GTC", "IOC"} - -// OrderStatus enum -var OrderStatus = struct { - ACK string - PARTIALLY_FILLED string - IOC_NO_FILL string - FULLY_FILLED string - CANCELED string - EXPIRED string - UNKNOWN string -}{ - "ACK", - "PARTIALLY_FILLED", - "IOC_NO_FILL", - "FULLY_FILLED", - "CANCELED", - "EXPIRED", - "UNKNOWN", -} - -// OrderType enum -var OrderType = struct { - LIMIT string - MARKET string - STOP_LOSS string - STOP_LOSS_LIMIT string - TAKE_PROFIT string - TAKE_PROFIT_LIMIT string - LIMIT_MAKER string -}{ - "LIMIT", - "MARKET", - "STOP_LOSS", - "STOP_LOSS_LIMIT", - "TAKE_PROFIT", - "TAKE_PROFIT_LIMIT", - "LIMIT_MAKER", -} - -type CloseOrders struct { - Order []Order `json:"order"` - Total int `json:"total"` -} - -type OpenOrders struct { - Order []Order `json:"order"` - Total int `json:"total"` -} - -type OpenOrder struct { - Id string `json:"id"` - Symbol string `json:"symbol"` - Price Fixed8 `json:"price"` - Quantity Fixed8 `json:"quantity"` - CumQty Fixed8 `json:"cumQty"` - CreatedHeight int64 `json:"createdHeight"` - CreatedTimestamp int64 `json:"createdTimestamp"` - LastUpdatedHeight int64 `json:"lastUpdatedHeight"` - LastUpdatedTimestamp int64 `json:"lastUpdatedTimestamp"` -} - -type TradingPair struct { - BaseAssetSymbol string `json:"base_asset_symbol"` - QuoteAssetSymbol string `json:"quote_asset_symbol"` - ListPrice Fixed8 `json:"list_price"` - TickSize Fixed8 `json:"tick_size"` - LotSize Fixed8 `json:"lot_size"` -} - -type OrderBook struct { - Height int64 - Levels []OrderBookLevel - PendingMatch bool -} - -// OrderBookLevel represents a single order book level. -type OrderBookLevel struct { - BuyQty Fixed8 `json:"buyQty"` - BuyPrice Fixed8 `json:"buyPrice"` - SellQty Fixed8 `json:"sellQty"` - SellPrice Fixed8 `json:"sellPrice"` -} - -type Trades struct { - Trade []Trade `json:"trade"` - Total int `json:"total"` -} - -// Trade def -type Trade struct { - BaseAsset string `json:"baseAsset"` - BlockHeight int64 `json:"blockHeight"` - BuyFee string `json:"buyFee"` - BuySingleFee string `json:"buySingleFee"` - BuyerId string `json:"buyerId"` - BuyerOrderID string `json:"buyerOrderId"` - Price string `json:"price"` - Quantity string `json:"quantity"` - QuoteAsset string `json:"quoteAsset"` - SellFee string `json:"sellFee"` - sellSingleFee string `json:"sellSingleFee"` - SellerId string `json:"sellerId"` - SellerOrderID string `json:"sellerOrderId"` - Symbol string `json:"symbol"` - Time int64 `json:"time"` - TradeID string `json:"tradeId"` - TickType string `json:"tickType"` -} - -type Order struct { - ID string `json:"orderId"` - Owner string `json:"owner"` - Symbol string `json:"symbol"` - Price string `json:"price"` - Quantity string `json:"quantity"` - CumulateQuantity string `json:"cumulateQuantity"` - Fee string `json:"fee"` - Side int `json:"side"` // BUY or SELL - Status string `json:"status"` - TimeInForce int `json:"timeInForce"` - Type int `json:"type"` - TradeId string `json:"tradeId"` - LastExecutedPrice string `json:"last_executed_price"` - LastExecutedQuantity string `json:"lastExecutedQuantity"` - TransactionHash string `json:"transactionHash"` - OrderCreateTime string `json:"orderCreateTime"` - TransactionTime string `json:"transactionTime"` -} diff --git a/e2e/e2e_rpc_side_staking_test.go b/e2e/e2e_rpc_side_staking_test.go index 9614d8ad..920ab7b4 100644 --- a/e2e/e2e_rpc_side_staking_test.go +++ b/e2e/e2e_rpc_side_staking_test.go @@ -5,12 +5,12 @@ import ( "sync" "testing" - "github.com/binance-chain/go-sdk/client/rpc" - ctypes "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/keys" - "github.com/binance-chain/go-sdk/types" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/client/rpc" + ctypes "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/keys" + "github.com/bnb-chain/go-sdk/types" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" "github.com/stretchr/testify/assert" ) @@ -19,18 +19,18 @@ var ( sOnceClient = sync.Once{} sTestClientInstance *rpc.HTTP - jackAddress = "bnb1lrzg56jhtkqu7fmca3394vdx00r7apx4gwvj6w" - jackMnemonic = "orphan thing pelican flee spray sense sketch dutch opinion vessel fringe surround hurt theory hospital provide foil love stock vast shrug detail harbor pattern" + jackAddress = "bnb1lrzg56jhtkqu7fmca3394vdx00r7apx4gwvj6w" + jackMnemonic = "orphan thing pelican flee spray sense sketch dutch opinion vessel fringe surround hurt theory hospital provide foil love stock vast shrug detail harbor pattern" - roseAddress = "bnb1rxnydtfjccaz2tck7wrentntdylrnnqzmvqvwn" - roseMnemonic = "earth hamster near become enlist degree foil crucial weapon poverty mad purity chest lucky equal jazz pony either knee cloud drive badge jacket caught" + roseAddress = "bnb1rxnydtfjccaz2tck7wrentntdylrnnqzmvqvwn" + roseMnemonic = "earth hamster near become enlist degree foil crucial weapon poverty mad purity chest lucky equal jazz pony either knee cloud drive badge jacket caught" - markAddress = "bnb1sh4cfzvcut9nywffs6gs5zkyt4pzeej6k84klt" - markMnemonic = "depend water drink monitor earn praise permit autumn board cable impact wink wolf sting middle misery bridge stamp close very robust slam annual verify" + markAddress = "bnb1sh4cfzvcut9nywffs6gs5zkyt4pzeej6k84klt" + markMnemonic = "depend water drink monitor earn praise permit autumn board cable impact wink wolf sting middle misery bridge stamp close very robust slam annual verify" - chainId = "test-chain-qUlw6e" - valAddress = "bva1lrzg56jhtkqu7fmca3394vdx00r7apx4gjdzy2" - valAddress2 = "bva1rxnydtfjccaz2tck7wrentntdylrnnqzmspush" + chainId = "test-chain-qUlw6e" + valAddress = "bva1lrzg56jhtkqu7fmca3394vdx00r7apx4gjdzy2" + valAddress2 = "bva1rxnydtfjccaz2tck7wrentntdylrnnqzmspush" ) func rpcClient() *rpc.HTTP { @@ -42,7 +42,7 @@ func rpcClient() *rpc.HTTP { func getRpcClientWithKeyManager() *rpc.HTTP { c := rpcClient() - ctypes.Network = ctypes.ProdNetwork + ctypes.SetNetwork(ctypes.ProdNetwork) keyManager, _ := keys.NewMnemonicKeyManager(jackMnemonic) c.SetKeyManager(keyManager) return c @@ -101,8 +101,8 @@ func TestEditSideChainValidator(t *testing.T) { rate, _ := ctypes.NewDecFromStr("2") sideFeeAddr := FromHex("0xd1B22dCC24C55f4d728E7aaA5c9b5a22e1512C08") - - res, err := c.EditSideChainValidator(types.RialtoNet, des, &rate, sideFeeAddr, rpc.Sync, tx.WithChainID(chainId)) + consAddr := FromHex("0xd1B22dCC24C55f4d728E7aaA5c9b5a22e1512C08") + res, err := c.EditSideChainValidator(types.RialtoNet, des, &rate, sideFeeAddr, consAddr, rpc.Sync, tx.WithChainID(chainId)) assert.NotNil(t, res) assert.Nil(t, err) @@ -167,8 +167,8 @@ func TestQuerySideChainValidator(t *testing.T) { res, err := c.QuerySideChainValidator(types.RialtoNet, valAddr) if res == nil { - assert.Equal(t, rpc.EmptyResultError, err) - }else{ + assert.Equal(t, rpc.EmptyResultError, err) + } else { assert.NotNil(t, res.OperatorAddr) } } @@ -189,7 +189,7 @@ func TestQuerySideChainDelegation(t *testing.T) { if res == nil { assert.Equal(t, rpc.EmptyResultError, err) - }else{ + } else { assert.NotNil(t, res.ValidatorAddr) } } @@ -214,7 +214,7 @@ func TestQuerySideChainRelegation(t *testing.T) { if res == nil { assert.Equal(t, rpc.EmptyResultError, err) - }else{ + } else { assert.NotNil(t, res.DelegatorAddr) } } @@ -237,7 +237,7 @@ func TestQuerySideChainUnbondingDelegation(t *testing.T) { if res == nil { assert.Equal(t, rpc.EmptyResultError, err) - }else{ + } else { assert.NotNil(t, res.DelegatorAddr) } } diff --git a/e2e/e2e_rpc_test.go b/e2e/e2e_rpc_test.go index 579efdb6..cf3ac6c2 100644 --- a/e2e/e2e_rpc_test.go +++ b/e2e/e2e_rpc_test.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "encoding/json" "fmt" + "github.com/tendermint/tendermint/types" "math/rand" "os/exec" "strconv" @@ -12,24 +13,23 @@ import ( "testing" "time" + "github.com/bnb-chain/go-sdk/client/rpc" + "github.com/bnb-chain/go-sdk/client/transaction" + ctypes "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/keys" + stypes "github.com/bnb-chain/go-sdk/types" + "github.com/bnb-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/tx" "github.com/stretchr/testify/assert" "github.com/tendermint/tendermint/libs/common" tmquery "github.com/tendermint/tendermint/libs/pubsub/query" - "github.com/tendermint/tendermint/types" - - "github.com/binance-chain/go-sdk/client/rpc" - "github.com/binance-chain/go-sdk/client/transaction" - ctypes "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/keys" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" ) var ( nodeAddr = "tcp://data-seed-pre-0-s3.binance.org:80" badAddr = "tcp://127.0.0.1:80" - testTxHash = "F45BAB1BA5B79609F7307A64AD1F84ECFAF73D1F2C2D010D17F41303BC1B00CA" - testTxHeight = int64(47905085) + testTxHash = "6165507B990A1CCAD1758512382C6B76F952CC945ABB84D9BF18160C11DE902A" + testTxHeight = int64(34762951) testAddress = "tbnb1e803p76n4rtyeclef7pg3295nurwfuwsw8l36m" testDelAddr = "tbnb12hlquylu78cjylk5zshxpdj6hf3t0tahwjt3ex" testTradePair = "PPC-00A_BNB" @@ -104,7 +104,7 @@ func TestRPCGetTimelock(t *testing.T) { func TestRPCGetProposal(t *testing.T) { c := defaultClient() - proposal, err := c.GetProposal(int64(1)) + proposal, err := c.GetProposal(int64(100)) assert.NoError(t, err) bz, err := json.Marshal(proposal) fmt.Println(string(bz)) @@ -313,17 +313,6 @@ func TestBadNodeAddr(t *testing.T) { assert.Error(t, err, "context deadline exceeded") } -func TestSetTimeOut(t *testing.T) { - c := rpc.NewRPCClient(badAddr, ctypes.TestNetwork) - c.SetTimeOut(1 * time.Second) - before := time.Now() - _, err := c.Validators(nil) - duration := time.Now().Sub(before).Seconds() - assert.True(t, duration > 1) - assert.True(t, duration < 2) - assert.Error(t, err, "context deadline exceeded") -} - func TestSubscribeEvent(t *testing.T) { c := defaultClient() query := "tm.event = 'CompleteProposal'" @@ -364,9 +353,9 @@ func TestSubscribeEventTwice(t *testing.T) { func TestReceiveWithRequestId(t *testing.T) { c := defaultClient() - c.SetTimeOut(1 * time.Second) + c.SetTimeOut(2 * time.Second) w := sync.WaitGroup{} - w.Add(2000) + w.Add(100) testCases := []func(t *testing.T){ TestRPCStatus, TestRPCABCIInfo, @@ -385,7 +374,7 @@ func TestReceiveWithRequestId(t *testing.T) { //TestTxSearch, TestValidators, } - for i := 0; i < 2000; i++ { + for i := 0; i < 100; i++ { testFuncIndex := rand.Intn(len(testCases)) go func() { testCases[testFuncIndex](t) @@ -412,7 +401,7 @@ func TestGetTokenInfo(t *testing.T) { } func TestGetAccount(t *testing.T) { - ctypes.Network = ctypes.TestNetwork + ctypes.SetNetwork(ctypes.TestNetwork) c := defaultClient() acc, err := ctypes.AccAddressFromBech32(testAddress) assert.NoError(t, err) @@ -424,7 +413,7 @@ func TestGetAccount(t *testing.T) { } func TestNoneExistGetAccount(t *testing.T) { - ctypes.Network = ctypes.TestNetwork + ctypes.SetNetwork(ctypes.TestNetwork) c := defaultClient() acc, err := keys.NewKeyManager() account, err := c.GetAccount(acc.GetAddr()) @@ -433,19 +422,19 @@ func TestNoneExistGetAccount(t *testing.T) { } func TestGetBalances(t *testing.T) { - ctypes.Network = ctypes.TestNetwork + ctypes.SetNetwork(ctypes.TestNetwork) c := defaultClient() acc, err := ctypes.AccAddressFromBech32(testAddress) assert.NoError(t, err) balances, err := c.GetBalances(acc) - assert.Equal(t, 0, len(balances)) + assert.Equal(t, 1, len(balances)) assert.NoError(t, err) bz, err := json.Marshal(balances) fmt.Println(string(bz)) } func TestNoneExistGetBalances(t *testing.T) { - ctypes.Network = ctypes.TestNetwork + ctypes.SetNetwork(ctypes.TestNetwork) c := defaultClient() acc, _ := keys.NewKeyManager() balances, err := c.GetBalances(acc.GetAddr()) @@ -455,7 +444,7 @@ func TestNoneExistGetBalances(t *testing.T) { } func TestGetBalance(t *testing.T) { - ctypes.Network = ctypes.TestNetwork + ctypes.SetNetwork(ctypes.TestNetwork) c := defaultClient() acc, err := ctypes.AccAddressFromBech32(testAddress) assert.NoError(t, err) @@ -466,7 +455,7 @@ func TestGetBalance(t *testing.T) { } func TestNoneExistGetBalance(t *testing.T) { - ctypes.Network = ctypes.TestNetwork + ctypes.SetNetwork(ctypes.TestNetwork) c := defaultClient() acc, _ := keys.NewKeyManager() balance, err := c.GetBalance(acc.GetAddr(), "BNB") @@ -486,37 +475,9 @@ func TestGetFees(t *testing.T) { fmt.Println(string(bz)) } -func TestGetOpenOrder(t *testing.T) { - ctypes.Network = ctypes.TestNetwork - acc, err := ctypes.AccAddressFromBech32(testAddress) - assert.NoError(t, err) - c := defaultClient() - openorders, err := c.GetOpenOrders(acc, testTradePair) - assert.NoError(t, err) - bz, err := json.Marshal(openorders) - assert.NoError(t, err) - fmt.Println(string(bz)) -} - -func TestGetTradePair(t *testing.T) { - c := defaultClient() - trades, err := c.GetTradingPairs(0, 10) - assert.NoError(t, err) - bz, err := json.Marshal(trades) - fmt.Println(string(bz)) -} - -func TestGetDepth(t *testing.T) { - c := defaultClient() - depth, err := c.GetDepth(testTradePair, 2) - assert.NoError(t, err) - bz, err := json.Marshal(depth) - fmt.Println(string(bz)) -} - func TestSendToken(t *testing.T) { c := defaultClient() - ctypes.Network = ctypes.TestNetwork + ctypes.SetNetwork(ctypes.TestNetwork) keyManager, err := keys.NewMnemonicKeyManager(mnemonic) assert.NoError(t, err) c.SetKeyManager(keyManager) @@ -530,8 +491,8 @@ func TestSendToken(t *testing.T) { func TestQuerySideChainParam(t *testing.T) { c := defaultClient() - ctypes.Network = ctypes.TestNetwork - params, err := c.GetSideChainParams("bsc") + ctypes.SetNetwork(ctypes.TestNetwork) + params, err := c.GetSideChainParams("chapel") assert.NoError(t, err) bz, _ := json.Marshal(params) fmt.Println(string(bz)) @@ -539,7 +500,7 @@ func TestQuerySideChainParam(t *testing.T) { func TestSubmitSideProposal(t *testing.T) { c := defaultClient() - ctypes.Network = ctypes.TestNetwork + ctypes.SetNetwork(ctypes.TestNetwork) keyManager, err := keys.NewMnemonicKeyManager(mnemonic) assert.NoError(t, err) @@ -550,7 +511,7 @@ func TestSubmitSideProposal(t *testing.T) { err = tx.Cdc.UnmarshalJSON([]byte(scParams), &iScPrams) assert.NoError(t, err) - res, err := c.SideChainSubmitSCParamsProposal("title", msg.SCChangeParams{SCParams: iScPrams, Description: "des"}, ctypes.Coins{{msg.NativeToken, 5e11}}, 5*time.Second, "rialto", rpc.Sync) + res, err := c.SideChainSubmitSCParamsProposal("title", msg.SCChangeParams{SCParams: iScPrams, Description: "des"}, ctypes.Coins{{stypes.NativeSymbol, 5e11}}, 5*time.Second, "rialto", rpc.Sync) assert.NoError(t, err) assert.True(t, res.Code == 0) proposalIdStr := string(res.Data) @@ -563,7 +524,7 @@ func TestSubmitSideProposal(t *testing.T) { func TestSubmitCSCProposal(t *testing.T) { c := defaultClient() - ctypes.Network = ctypes.TestNetwork + ctypes.SetNetwork(ctypes.TestNetwork) keyManager, err := keys.NewMnemonicKeyManager(mnemonic) assert.NoError(t, err) @@ -575,47 +536,22 @@ func TestSubmitCSCProposal(t *testing.T) { Target: hex.EncodeToString(common.RandBytes(20)), } - res, err := c.SideChainSubmitCSCParamsProposal("title", cscPrams, ctypes.Coins{{msg.NativeToken, 5e8}}, 5*time.Second, "rialto", rpc.Sync) + res, err := c.SideChainSubmitCSCParamsProposal("title", cscPrams, ctypes.Coins{{stypes.NativeSymbol, 5e8}}, 5*time.Second, "chapel", rpc.Sync) assert.NoError(t, err) assert.True(t, res.Code == 0) proposalIdStr := string(res.Data) id, err := strconv.ParseInt(proposalIdStr, 10, 64) assert.NoError(t, err) - res, err = c.SideChainDeposit(int64(id), ctypes.Coins{{"BNB", 1e8}}, "rialto", rpc.Sync) + res, err = c.SideChainDeposit(int64(id), ctypes.Coins{{"BNB", 1e8}}, "chapel", rpc.Sync) assert.NoError(t, err) assert.True(t, res.Code == 0) } -func TestCreateOrder(t *testing.T) { - c := defaultClient() - ctypes.Network = ctypes.TestNetwork - keyManager, err := keys.NewMnemonicKeyManager(mnemonic) - assert.NoError(t, err) - c.SetKeyManager(keyManager) - createOrderResult, err := c.CreateOrder(testTradeSymbol, "BNB", msg.OrderSide.BUY, 100000000, 100000000, rpc.Commit, transaction.WithSource(100), transaction.WithMemo("test memo")) - - assert.NoError(t, err) - bz, err := json.Marshal(createOrderResult) - fmt.Println(string(bz)) - fmt.Println(createOrderResult.Hash.String()) - - type commitData struct { - OrderId string `json:"order_id"` - } - var cdata commitData - err = json.Unmarshal([]byte(createOrderResult.Data), &cdata) - assert.NoError(t, err) - cancleOrderResult, err := c.CancelOrder(testTradeSymbol, "BNB", cdata.OrderId, rpc.Commit) - assert.NoError(t, err) - bz, _ = json.Marshal(cancleOrderResult) - fmt.Println(string(bz)) -} - func TestTransferTokenOwnership(t *testing.T) { c := defaultClient() - ctypes.Network = ctypes.TestNetwork + ctypes.SetNetwork(ctypes.TestNetwork) keyManager, err := keys.NewMnemonicKeyManager(mnemonic) assert.NoError(t, err) c.SetKeyManager(keyManager) @@ -639,7 +575,7 @@ func TestBroadcastTxCommit(t *testing.T) { func TestGetStakeValidators(t *testing.T) { c := defaultClient() - ctypes.Network = ctypes.TestNetwork + ctypes.SetNetwork(ctypes.TestNetwork) vals, err := c.GetStakeValidators() assert.NoError(t, err) bz, err := json.Marshal(vals) @@ -648,7 +584,7 @@ func TestGetStakeValidators(t *testing.T) { func TestGetDelegatorUnbondingDelegations(t *testing.T) { c := defaultClient() - ctypes.Network = ctypes.TestNetwork + ctypes.SetNetwork(ctypes.TestNetwork) acc, err := ctypes.AccAddressFromBech32(testDelAddr) assert.NoError(t, err) vals, err := c.GetDelegatorUnbondingDelegations(acc) @@ -674,10 +610,10 @@ func TestNoRequestLeakInBadNetwork(t *testing.T) { func TestNoRequestLeakInGoodNetwork(t *testing.T) { c := defaultClient() - c.SetTimeOut(1 * time.Second) + c.SetTimeOut(2 * time.Second) w := sync.WaitGroup{} - w.Add(3000) - for i := 0; i < 3000; i++ { + w.Add(100) + for i := 0; i < 100; i++ { go func() { _, err := c.Block(nil) assert.NoError(t, err) @@ -709,11 +645,3 @@ func TestGetMiniTokenInfo(t *testing.T) { fmt.Println(string(bz)) } } - -func TestGetMiniTradePair(t *testing.T) { - c := defaultClient() - trades, err := c.GetMiniTradingPairs(0, 10) - assert.NoError(t, err) - bz, err := json.Marshal(trades) - fmt.Println(string(bz)) -} diff --git a/e2e/e2e_trans_test.go b/e2e/e2e_trans_test.go index 534b3c47..b38d9e52 100644 --- a/e2e/e2e_trans_test.go +++ b/e2e/e2e_trans_test.go @@ -2,35 +2,32 @@ package e2e import ( "fmt" - "github.com/binance-chain/go-sdk/client/rpc" - "github.com/tendermint/tendermint/crypto" + "github.com/bnb-chain/go-sdk/types" "strings" "testing" time2 "time" + "github.com/bnb-chain/go-sdk/client/rpc" + "github.com/tendermint/tendermint/crypto" + "github.com/stretchr/testify/assert" "github.com/tendermint/tendermint/types/time" - sdk "github.com/binance-chain/go-sdk/client" - "github.com/binance-chain/go-sdk/client/transaction" - "github.com/binance-chain/go-sdk/common" - ctypes "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/keys" - "github.com/binance-chain/go-sdk/types/msg" - txtype "github.com/binance-chain/go-sdk/types/tx" + sdk "github.com/bnb-chain/go-sdk/client" + ctypes "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/keys" + "github.com/bnb-chain/go-sdk/types/msg" + txtype "github.com/bnb-chain/go-sdk/types/tx" ) // After bnbchain integration_test.sh has runned func TestTransProcess(t *testing.T) { //----- Recover account --------- mnemonic := "test mnemonic" - baeUrl := "test base url" + baeUrl := "testnet-dex.binance.org" keyManager, err := keys.NewMnemonicKeyManager(mnemonic) assert.NoError(t, err) - validatorMnemonics := []string{ - "test mnemonic", - } testAccount1 := keyManager.GetAddr() testKeyManager2, _ := keys.NewKeyManager() testAccount2 := testKeyManager2.GetAddr() @@ -39,14 +36,15 @@ func TestTransProcess(t *testing.T) { //----- Init sdk ------------- client, err := sdk.NewDexClient(baeUrl, ctypes.TestNetwork, keyManager) + assert.NoError(t, err) - nativeSymbol := msg.NativeToken + nativeSymbol := types.NativeSymbol //---- set Account flags addFlags, err := client.AddAccountFlags([]ctypes.FlagOption{ctypes.TransferMemoCheckerFlag}, true) assert.NoError(t, err) fmt.Printf("Set account flags: %v \n", addFlags) - accn,_:=client.GetAccount(client.GetKeyManager().GetAddr().String()) + accn, _ := client.GetAccount(client.GetKeyManager().GetAddr().String()) fmt.Println(accn) setFlags, err := client.SetAccountFlags(0, true) assert.NoError(t, err) @@ -58,41 +56,11 @@ func TestTransProcess(t *testing.T) { assert.NotNil(t, account) assert.True(t, len(account.Balances) > 0) - //----- Get Markets ------------ - markets, err := client.GetMarkets(ctypes.NewMarketsQuery().WithLimit(1)) - assert.NoError(t, err) - assert.Equal(t, 1, len(markets)) - tradeSymbol := markets[0].QuoteAssetSymbol - if tradeSymbol == "BNB" { - tradeSymbol = markets[0].BaseAssetSymbol - } - - //----- Get Depth ---------- - depth, err := client.GetDepth(ctypes.NewDepthQuery(tradeSymbol, nativeSymbol)) - assert.NoError(t, err) - assert.True(t, depth.Height > 0) - - //----- Get Kline - kline, err := client.GetKlines(ctypes.NewKlineQuery(tradeSymbol, nativeSymbol, "1h").WithLimit(1)) - assert.NoError(t, err) - assert.Equal(t, 1, len(kline)) - - //----- Get Ticker 24h ----------- - ticker24h, err := client.GetTicker24h(ctypes.NewTicker24hQuery().WithSymbol(tradeSymbol, nativeSymbol)) - assert.NoError(t, err) - assert.True(t, len(ticker24h) > 0) - //----- Get Tokens ----------- tokens, err := client.GetTokens(ctypes.NewTokensQuery().WithLimit(101)) assert.NoError(t, err) fmt.Printf("GetTokens: %v \n", tokens) - //----- Get Trades ----------- - fmt.Println(testAccount1.String()) - trades, err := client.GetTrades(ctypes.NewTradesQuery(true).WithSymbol(tradeSymbol, nativeSymbol)) - assert.NoError(t, err) - fmt.Printf("GetTrades: %v \n", trades) - //----- Get Time ----------- time, err := client.GetTime() assert.NoError(t, err) @@ -101,65 +69,18 @@ func TestTransProcess(t *testing.T) { //----- time lock ----------- lockResult, err := client.TimeLock("test lock", ctypes.Coins{{"BNB", 100000000}}, int64(time2.Now().Add(65*time2.Second).Unix()), true) assert.NoError(t, err) - fmt.Printf("timelock %d", lockResult.LockId) + fmt.Printf("timelock %d \n", lockResult.LockId) //----- time relock --------- - relockResult, err := client.TimeReLock(lockResult.LockId, "test lock", ctypes.Coins{{"BNB", 200000000}}, int64(time2.Now().Add(65*time2.Second).Unix()), true) + relockResult, err := client.TimeReLock(lockResult.LockId, "test lock", ctypes.Coins{{"BNB", 200000000}}, int64(time2.Now().Add(70*time2.Second).Unix()), true) assert.NoError(t, err) - fmt.Printf("timelock %d", relockResult.LockId) + fmt.Printf("timelock %d \n", relockResult.LockId) //------ time unlock -------- - time2.Sleep(70 * time2.Second) + time2.Sleep(75 * time2.Second) unlockResult, err := client.TimeUnLock(relockResult.LockId, true) assert.NoError(t, err) - fmt.Printf("timelock %d", unlockResult.LockId) - - //----- Create order ----------- - createOrderResult, err := client.CreateOrder(tradeSymbol, nativeSymbol, msg.OrderSide.BUY, 100000000, 100000000, true, transaction.WithSource(100), transaction.WithMemo("test memo")) - assert.NoError(t, err) - assert.True(t, true, createOrderResult.Ok) - - //---- Create order by sequence -- - acc, err := client.GetAccount(client.GetKeyManager().GetAddr().String()) - assert.NoError(t, err) - - _, err = client.CreateOrder(tradeSymbol, nativeSymbol, msg.OrderSide.BUY, 100000000, 100000000, true, transaction.WithAcNumAndSequence(acc.Number, acc.Sequence)) - assert.NoError(t, err) - _, err = client.CreateOrder(tradeSymbol, nativeSymbol, msg.OrderSide.BUY, 100000000, 100000000, true, transaction.WithAcNumAndSequence(acc.Number, acc.Sequence+1)) - assert.NoError(t, err) - _, err = client.CreateOrder(tradeSymbol, nativeSymbol, msg.OrderSide.BUY, 100000000, 100000000, true, transaction.WithAcNumAndSequence(acc.Number, acc.Sequence+2)) - assert.NoError(t, err) - - //---- Get Open Order --------- - openOrders, err := client.GetOpenOrders(ctypes.NewOpenOrdersQuery(testAccount1.String(), true)) - assert.NoError(t, err) - assert.True(t, len(openOrders.Order) > 0) - orderId := openOrders.Order[0].ID - fmt.Printf("GetOpenOrders: %v \n", openOrders) - - //---- Get Order ------------ - order, err := client.GetOrder(orderId) - assert.NoError(t, err) - assert.Equal(t, common.CombineSymbol(tradeSymbol, nativeSymbol), order.Symbol) - - //---- Cancel Order --------- - time2.Sleep(2 * time2.Second) - cancelOrderResult, err := client.CancelOrder(tradeSymbol, nativeSymbol, orderId, true) - assert.NoError(t, err) - assert.True(t, cancelOrderResult.Ok) - fmt.Printf("cancelOrderResult: %v \n", cancelOrderResult) - - //---- Get Close Order--------- - closedOrders, err := client.GetClosedOrders(ctypes.NewClosedOrdersQuery(testAccount1.String(), true).WithSymbol(tradeSymbol, nativeSymbol)) - assert.NoError(t, err) - assert.True(t, len(closedOrders.Order) > 0) - fmt.Printf("GetClosedOrders: %v \n", closedOrders) - - //---- Get tx --------- - tx, err := client.GetTx(openOrders.Order[0].TransactionHash) - assert.NoError(t, err) - assert.NotNil(t, tx) - fmt.Printf("GetTx: %v\n", tx) + fmt.Printf("timelock %d \n", unlockResult.LockId) //---- Send tx ----------- send, err := client.SendToken([]msg.Transfer{{testAccount2, []ctypes.Coin{{nativeSymbol, 100000000}}}, {testAccount3, []ctypes.Coin{{nativeSymbol, 100000000}}}}, true) @@ -194,7 +115,7 @@ func TestTransProcess(t *testing.T) { fmt.Printf("Issue token: %v\n", issue) //--- check issue success --- - time2.Sleep(2 * time2.Second) + time2.Sleep(4 * time2.Second) issueresult, err := client.GetTx(issue.Hash) assert.NoError(t, err) assert.True(t, issueresult.Code == txtype.CodeOk) @@ -205,99 +126,45 @@ func TestTransProcess(t *testing.T) { fmt.Printf("Mint token: %v\n", mint) //---- Submit Proposal ------ - time2.Sleep(2 * time2.Second) + time2.Sleep(4 * time2.Second) listTradingProposal, err := client.SubmitListPairProposal("New trading pair", msg.ListTradingPairParams{issue.Symbol, nativeSymbol, 1000000000, "my trade", time2.Now().Add(1 * time2.Hour)}, 200000000000, 20*time2.Second, true) assert.NoError(t, err) fmt.Printf("Submit list trading pair: %v\n", listTradingProposal) //--- check submit proposal success --- - time2.Sleep(2 * time2.Second) + time2.Sleep(4 * time2.Second) submitPorposalStatus, err := client.GetTx(listTradingProposal.Hash) assert.NoError(t, err) assert.True(t, submitPorposalStatus.Code == txtype.CodeOk) - //---- Vote Proposal ------- - for _, m := range validatorMnemonics { - time2.Sleep(1 * time2.Second) - k, err := keys.NewMnemonicKeyManager(m) - assert.NoError(t, err) - client, err := sdk.NewDexClient(baeUrl, ctypes.TestNetwork, k) - assert.NoError(t, err) - vote, err := client.VoteProposal(listTradingProposal.ProposalId, msg.OptionYes, true) - assert.NoError(t, err) - fmt.Printf("Vote: %v\n", vote) - } - - //--- List trade pair ------ - time2.Sleep(20 * time2.Second) - l, err := client.ListPair(listTradingProposal.ProposalId, issue.Symbol, nativeSymbol, 1000000000, true) - assert.NoError(t, err) - fmt.Printf("List trading pair: %v\n", l) - //---- issue mini token --------- + time2.Sleep(4 * time2.Second) miniIssue, err := client.IssueMiniToken("Mini-Client-Token", "msdk", 10000000000, true, true, "http://test.sdk") assert.NoError(t, err) fmt.Printf("Issue mini token: %v\n", miniIssue) //---- issue tiny token --------- + time2.Sleep(4 * time2.Second) tinyIssue, err := client.IssueMiniToken("Tiny-Client-Token", "tsdk", 10000000000, true, true, "http://test.sdk") assert.NoError(t, err) fmt.Printf("Issue tiny token: %v\n", tinyIssue) //---- set mini token uri --------- + time2.Sleep(4 * time2.Second) setUri, err := client.SetURI(miniIssue.Symbol, "http://test-uri.sdk", true) assert.NoError(t, err) fmt.Printf("Set mini token uri: %v\n", setUri) - //---- list mini trading pair --------- - listMini, err := client.ListMiniPair(miniIssue.Symbol, nativeSymbol, 1000000000, true) - assert.NoError(t, err) - fmt.Printf("List mini pair: %v\n", listMini) - //----- Get Mini Tokens ----------- + time2.Sleep(4 * time2.Second) miniTokens, err := client.GetMiniTokens(ctypes.NewTokensQuery().WithLimit(101)) assert.NoError(t, err) fmt.Printf("Get Mini Tokens: %v \n", miniTokens) - - //----- Get Mini Markets ------------ - miniMarkets, err := client.GetMiniMarkets(ctypes.NewMarketsQuery().WithLimit(101)) - assert.NoError(t, err) - fmt.Printf("Get Mini Markets: %v \n", miniMarkets) - miniTradeSymbol := miniMarkets[0].QuoteAssetSymbol - if miniTradeSymbol == "BNB" { - miniTradeSymbol = miniMarkets[0].BaseAssetSymbol - } - - //----- Get Mini Kline - miniKline, err := client.GetMiniKlines(ctypes.NewKlineQuery(miniTradeSymbol, nativeSymbol, "1h").WithLimit(1)) - assert.NoError(t, err) - fmt.Printf("GetMiniKlines: %v \n", miniKline) - - //----- Get Mini Ticker 24h ----------- - miniTicker24h, err := client.GetMiniTicker24h(ctypes.NewTicker24hQuery().WithSymbol(miniTradeSymbol, nativeSymbol)) - assert.NoError(t, err) - fmt.Printf("GetMiniTicker24h: %v \n", miniTicker24h) - - //----- Get Mini Trades ----------- - fmt.Println(testAccount1.String()) - miniTrades, err := client.GetMiniTrades(ctypes.NewTradesQuery(true).WithSymbol(miniTradeSymbol, nativeSymbol)) - assert.NoError(t, err) - fmt.Printf("GetMiniTrades: %v \n", miniTrades) - - //---- Get Mini Open Order --------- - miniOpenOrders, err := client.GetMiniOpenOrders(ctypes.NewOpenOrdersQuery(testAccount1.String(), true)) - assert.NoError(t, err) - fmt.Printf("GetMiniOpenOrders: %v \n", miniOpenOrders) - - //---- Get Mini Close Order--------- - miniClosedOrders, err := client.GetMiniClosedOrders(ctypes.NewClosedOrdersQuery(testAccount1.String(), true).WithSymbol(miniTradeSymbol, nativeSymbol)) - assert.NoError(t, err) - fmt.Printf("GetMiniClosedOrders: %v \n", miniClosedOrders) } func TestAtomicSwap(t *testing.T) { - mnemonic1 := "owner square swap resemble lift spawn hazard gift series jeans frozen client leave smooth soap quit appear bonus eagle omit again fetch rug trip" - mnemonic2 := "web auto pluck icon taxi cruise replace square trust grunt together hurdle sight island weasel share yard pelican demand reason diesel leaf choose biology" + mnemonic1 := "test mnemonic1" + mnemonic2 := "test mnemonic2" baeUrl := "testnet-dex.binance.org" keyManager, err := keys.NewMnemonicKeyManager(mnemonic1) assert.NoError(t, err) @@ -319,11 +186,11 @@ func TestAtomicSwap(t *testing.T) { heightSpan := int64(1000) _, err = client.HTLT(testAccount2, recipientOtherChain, senderOtherChain, randomNumberHash, timestamp, amount, expetedIncome, heightSpan, true, true) assert.NoError(t, err) - time2.Sleep(2 * time2.Second) + time2.Sleep(4 * time2.Second) swapID := msg.CalculateSwapID(randomNumberHash, testAccount1, senderOtherChain) _, err = client.ClaimHTLT(swapID, randomNumber, true) assert.NoError(t, err) - time2.Sleep(2 * time2.Second) + time2.Sleep(4 * time2.Second) randomNumber = crypto.CRandBytes(32) timestamp = int64(time.Now().Unix()) @@ -331,11 +198,11 @@ func TestAtomicSwap(t *testing.T) { heightSpan = int64(360) _, err = client.HTLT(testAccount2, recipientOtherChain, senderOtherChain, randomNumberHash, timestamp, amount, expetedIncome, heightSpan, true, true) assert.NoError(t, err) - time2.Sleep(2 * time2.Second) + time2.Sleep(4 * time2.Second) swapID1 := msg.CalculateSwapID(randomNumberHash, testAccount1, senderOtherChain) _, err = client.RefundHTLT(swapID1, true) assert.Error(t, err) - time2.Sleep(2 * time2.Second) + time2.Sleep(4 * time2.Second) assert.True(t, strings.Contains(err.Error(), "is still not reached")) randomNumber = crypto.CRandBytes(32) @@ -346,17 +213,17 @@ func TestAtomicSwap(t *testing.T) { heightSpan = int64(1000) _, err = client.HTLT(testAccount2, "", "", randomNumberHash, timestamp, amount, expetedIncome, heightSpan, false, true) assert.NoError(t, err) - time2.Sleep(2 * time2.Second) + time2.Sleep(4 * time2.Second) swapID2 := msg.CalculateSwapID(randomNumberHash, testAccount1, "") depositAmount := ctypes.Coins{ctypes.Coin{"BTC-271", 1000}} client1, err := sdk.NewDexClient(baeUrl, ctypes.TestNetwork, testKeyManager2) assert.NoError(t, err) _, err = client1.DepositHTLT(swapID2, depositAmount, true) assert.NoError(t, err) - time2.Sleep(2 * time2.Second) + time2.Sleep(4 * time2.Second) _, err = client.ClaimHTLT(swapID2, randomNumber, true) assert.NoError(t, err) - time2.Sleep(2 * time2.Second) + time2.Sleep(4 * time2.Second) c := rpc.NewRPCClient("tcp://seed-pre-s3.binance.org:80", ctypes.TestNetwork) swap, err := c.GetSwapByID(swapID) diff --git a/e2e/e2e_ws_test.go b/e2e/e2e_ws_test.go deleted file mode 100644 index 874cb009..00000000 --- a/e2e/e2e_ws_test.go +++ /dev/null @@ -1,249 +0,0 @@ -package e2e - -import ( - "encoding/json" - "fmt" - "testing" - "time" - - "github.com/stretchr/testify/assert" - - sdk "github.com/binance-chain/go-sdk/client" - "github.com/binance-chain/go-sdk/client/websocket" - ctypes "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/keys" - "github.com/binance-chain/go-sdk/types" -) - -func NewClient(t *testing.T) sdk.DexClient { - mnemonic := "test mnemonic" - keyManager, err := keys.NewMnemonicKeyManager(mnemonic) - assert.NoError(t, err) - - client, err := sdk.NewDexClient("testnet-dex.binance.org", ctypes.TestNetwork, keyManager) - assert.NoError(t, err) - return client -} - -func TestSubscribeAllTickerEvent(t *testing.T) { - client := NewClient(t) - - quit := make(chan struct{}) - err := client.SubscribeAllTickerEvent(quit, func(events []*websocket.TickerEvent) { - bz, _ := json.Marshal(events) - fmt.Println(string(bz)) - }, func(err error) { - assert.NoError(t, err) - }, nil) - assert.NoError(t, err) - time.Sleep(10 * time.Second) - close(quit) - time.Sleep(1 * time.Second) -} - -func TestSubscribeTickerEvent(t *testing.T) { - client := NewClient(t) - - markets, err := client.GetMarkets(ctypes.NewMarketsQuery().WithLimit(1)) - assert.NoError(t, err) - assert.Equal(t, 1, len(markets)) - tradeSymbol := markets[0].BaseAssetSymbol - if markets[0].QuoteAssetSymbol != types.NativeSymbol { - tradeSymbol = markets[0].QuoteAssetSymbol - } - quit := make(chan struct{}) - err = client.SubscribeTickerEvent(tradeSymbol, types.NativeSymbol, quit, func(event *websocket.TickerEvent) { - bz, _ := json.Marshal(event) - fmt.Println(string(bz)) - }, func(err error) { - assert.NoError(t, err) - }, nil) - assert.NoError(t, err) - time.Sleep(10 * time.Second) - close(quit) - time.Sleep(1 * time.Second) -} - -func TestSubscribeAllMiniTickersEvent(t *testing.T) { - client := NewClient(t) - - quit := make(chan struct{}) - err := client.SubscribeAllMiniTickersEvent(quit, func(events []*websocket.MiniTickerEvent) { - bz, _ := json.Marshal(events) - fmt.Println(string(bz)) - }, func(err error) { - assert.NoError(t, err) - }, nil) - assert.NoError(t, err) - time.Sleep(10 * time.Second) - close(quit) - time.Sleep(1 * time.Second) -} - -func TestSubscribeMiniTickersEvent(t *testing.T) { - client := NewClient(t) - - markets, err := client.GetMarkets(ctypes.NewMarketsQuery().WithLimit(1)) - assert.NoError(t, err) - assert.Equal(t, 1, len(markets)) - tradeSymbol := markets[0].BaseAssetSymbol - if markets[0].QuoteAssetSymbol != types.NativeSymbol { - tradeSymbol = markets[0].QuoteAssetSymbol - } - quit := make(chan struct{}) - err = client.SubscribeMiniTickerEvent(tradeSymbol, types.NativeSymbol, quit, func(event *websocket.MiniTickerEvent) { - bz, err := json.Marshal(event) - assert.NoError(t, err) - fmt.Println(string(bz)) - }, func(err error) { - assert.NoError(t, err) - }, nil) - assert.NoError(t, err) - time.Sleep(10 * time.Second) - close(quit) - time.Sleep(1 * time.Second) -} - -func TestSubscribeTradeEvent(t *testing.T) { - client := NewClient(t) - - markets, err := client.GetMarkets(ctypes.NewMarketsQuery().WithLimit(1)) - assert.NoError(t, err) - assert.Equal(t, 1, len(markets)) - tradeSymbol := markets[0].BaseAssetSymbol - if markets[0].QuoteAssetSymbol != types.NativeSymbol { - tradeSymbol = markets[0].QuoteAssetSymbol - } - quit := make(chan struct{}) - err = client.SubscribeTradeEvent(tradeSymbol, types.NativeSymbol, quit, func(events []*websocket.TradeEvent) { - bz, err := json.Marshal(events) - assert.NoError(t, err) - fmt.Println(string(bz)) - }, func(err error) { - assert.NoError(t, err) - }, nil) - assert.NoError(t, err) - time.Sleep(10 * time.Second) - close(quit) - time.Sleep(1 * time.Second) -} - -func TestSubscribeOrderEvent(t *testing.T) { - client := NewClient(t) - - quit := make(chan struct{}) - err := client.SubscribeOrderEvent(client.GetKeyManager().GetAddr().String(), quit, func(event []*websocket.OrderEvent) { - bz, _ := json.Marshal(event) - fmt.Println(string(bz)) - }, func(err error) { - assert.NoError(t, err) - }, nil) - assert.NoError(t, err) - time.Sleep(10 * time.Second) - close(quit) - time.Sleep(1 * time.Second) -} - -func TestSubscribeAccountEvent(t *testing.T) { - client := NewClient(t) - - quit := make(chan struct{}) - err := client.SubscribeAccountEvent(client.GetKeyManager().GetAddr().String(), quit, func(event *websocket.AccountEvent) { - bz, _ := json.Marshal(event) - fmt.Println(string(bz)) - }, func(err error) { - assert.NoError(t, err) - }, nil) - assert.NoError(t, err) - time.Sleep(10 * time.Second) - close(quit) - time.Sleep(1 * time.Second) -} - -func TestSubscribeBlockHeightEvent(t *testing.T) { - client := NewClient(t) - - quit := make(chan struct{}) - err := client.SubscribeBlockHeightEvent(quit, func(event *websocket.BlockHeightEvent) { - bz, _ := json.Marshal(event) - fmt.Println(string(bz)) - }, func(err error) { - assert.NoError(t, err) - }, nil) - assert.NoError(t, err) - time.Sleep(10 * time.Second) - close(quit) - time.Sleep(1 * time.Second) -} - -func TestSubscribeKlineEvent(t *testing.T) { - client := NewClient(t) - - markets, err := client.GetMarkets(ctypes.NewMarketsQuery().WithLimit(1)) - assert.NoError(t, err) - assert.Equal(t, 1, len(markets)) - tradeSymbol := markets[0].BaseAssetSymbol - if markets[0].QuoteAssetSymbol != types.NativeSymbol { - tradeSymbol = markets[0].QuoteAssetSymbol - } - quit := make(chan struct{}) - err = client.SubscribeKlineEvent(tradeSymbol, types.NativeSymbol, websocket.OneMinuteInterval, quit, func(event *websocket.KlineEvent) { - bz, err := json.Marshal(event) - assert.NoError(t, err) - fmt.Println(string(bz)) - }, func(err error) { - assert.NoError(t, err) - }, nil) - assert.NoError(t, err) - time.Sleep(10 * time.Second) - close(quit) - time.Sleep(1 * time.Second) -} - -func TestSubscribeMarketDiffEvent(t *testing.T) { - client := NewClient(t) - - markets, err := client.GetMarkets(ctypes.NewMarketsQuery().WithLimit(1)) - assert.NoError(t, err) - assert.Equal(t, 1, len(markets)) - tradeSymbol := markets[0].BaseAssetSymbol - if markets[0].QuoteAssetSymbol != types.NativeSymbol { - tradeSymbol = markets[0].QuoteAssetSymbol - } - quit := make(chan struct{}) - err = client.SubscribeMarketDiffEvent(tradeSymbol, types.NativeSymbol, quit, func(event *websocket.MarketDeltaEvent) { - bz, err := json.Marshal(event) - assert.NoError(t, err) - fmt.Println(string(bz)) - }, func(err error) { - assert.NoError(t, err) - }, nil) - assert.NoError(t, err) - time.Sleep(10 * time.Second) - close(quit) - time.Sleep(1 * time.Second) -} - -func TestSubscribeMarketDepthEvent(t *testing.T) { - client := NewClient(t) - - markets, err := client.GetMarkets(ctypes.NewMarketsQuery().WithLimit(1)) - assert.NoError(t, err) - assert.Equal(t, 1, len(markets)) - tradeSymbol := markets[0].BaseAssetSymbol - if markets[0].QuoteAssetSymbol != types.NativeSymbol { - tradeSymbol = markets[0].BaseAssetSymbol - } - quit := make(chan struct{}) - err = client.SubscribeMarketDepthEvent(tradeSymbol, types.NativeSymbol, quit, func(event *websocket.MarketDepthEvent) { - bz, err := json.Marshal(event) - assert.NoError(t, err) - fmt.Println(string(bz)) - }, func(err error) { - assert.NoError(t, err) - }, nil) - assert.NoError(t, err) - time.Sleep(10 * time.Second) - close(quit) - time.Sleep(1 * time.Second) -} diff --git a/example/ledger-keys/main.go b/example/ledger-keys/main.go index 4619d298..711186b0 100644 --- a/example/ledger-keys/main.go +++ b/example/ledger-keys/main.go @@ -4,16 +4,16 @@ import ( "fmt" "strconv" - "github.com/binance-chain/go-sdk/client" - "github.com/binance-chain/go-sdk/common/ledger" - "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/keys" - "github.com/binance-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/client" + "github.com/bnb-chain/go-sdk/common/ledger" + "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/keys" + "github.com/bnb-chain/go-sdk/types/msg" ) // To run this example, please make sure your key address have more than 1:BNB on testnet func main() { - types.Network = types.TestNetwork + types.SetNetwork(types.TestNetwork) //Check whether there are variable ledger devices ledgerDevice, err := ledger.DiscoverLedger() diff --git a/go.mod b/go.mod index ba870928..5bd66ab8 100644 --- a/go.mod +++ b/go.mod @@ -1,57 +1,81 @@ -module github.com/binance-chain/go-sdk +module github.com/bnb-chain/go-sdk go 1.17 require ( - github.com/binance-chain/ledger-cosmos-go v0.9.9-binance.1 + github.com/bnb-chain/node v0.10.6 github.com/btcsuite/btcd v0.20.1-beta github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d + github.com/cosmos/cosmos-sdk v0.25.0 github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d github.com/gorilla/websocket v1.4.1-0.20190629185528-ae1634f6a989 - github.com/pkg/errors v0.8.1 - github.com/stretchr/testify v1.4.0 - github.com/tendermint/btcd v0.0.0-20180816174608-e5840949ff4f - github.com/tendermint/go-amino v0.14.1 + github.com/pkg/errors v0.9.1 + github.com/stretchr/testify v1.5.1 + github.com/tendermint/btcd v0.1.1 + github.com/tendermint/go-amino v0.15.0 github.com/tendermint/tendermint v0.32.3 - golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 - gopkg.in/resty.v1 v1.10.3 + github.com/zondax/ledger-cosmos-go v0.9.9 + golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 + gopkg.in/resty.v1 v1.12.0 ) require ( - github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 // indirect + github.com/bartekn/go-bip39 v0.0.0-20171116152956-a05967ea095d // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/bgentry/speakeasy v0.1.0 // indirect + github.com/cosmos/ledger-go v0.9.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/etcd-io/bbolt v1.3.3 // indirect - github.com/go-kit/kit v0.8.0 // indirect - github.com/go-logfmt/logfmt v0.3.0 // indirect - github.com/gogo/protobuf v1.2.1 // indirect + github.com/fsnotify/fsnotify v1.4.7 // indirect + github.com/go-kit/kit v0.9.0 // indirect + github.com/go-logfmt/logfmt v0.4.0 // indirect + github.com/gogo/protobuf v1.3.1 // indirect github.com/golang/protobuf v1.3.2 // indirect github.com/golang/snappy v0.0.1 // indirect + github.com/google/btree v1.0.0 // indirect + github.com/gorilla/mux v1.7.3 // indirect + github.com/hashicorp/golang-lru v0.5.3 // indirect + github.com/hashicorp/hcl v1.0.0 // indirect + github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/jmhodges/levigo v1.0.0 // indirect github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515 // indirect - github.com/kr/pretty v0.1.0 // indirect - github.com/libp2p/go-buffer-pool v0.0.1 // indirect + github.com/libp2p/go-buffer-pool v0.0.2 // indirect + github.com/magiconair/properties v1.8.1 // indirect + github.com/mattn/go-isatty v0.0.10 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect + github.com/mitchellh/go-homedir v1.1.0 // indirect + github.com/mitchellh/mapstructure v1.1.2 // indirect + github.com/pelletier/go-toml v1.4.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v0.9.2 // indirect - github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 // indirect - github.com/prometheus/common v0.0.0-20181126121408-4724e9255275 // indirect - github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a // indirect - github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a // indirect + github.com/prometheus/client_golang v1.1.0 // indirect + github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90 // indirect + github.com/prometheus/common v0.6.0 // indirect + github.com/prometheus/procfs v0.0.3 // indirect + github.com/rcrowley/go-metrics v0.0.0-20190826022208-cac0b30c2563 // indirect github.com/rs/cors v1.6.0 // indirect + github.com/spf13/afero v1.2.2 // indirect + github.com/spf13/cast v1.3.0 // indirect + github.com/spf13/cobra v0.0.5 // indirect + github.com/spf13/jwalterweatherman v1.1.0 // indirect + github.com/spf13/pflag v1.0.3 // indirect + github.com/spf13/viper v1.4.0 // indirect github.com/syndtr/goleveldb v1.0.1-0.20190923125748-758128399b1d // indirect - github.com/tendermint/tm-db v0.1.1 // indirect + github.com/tendermint/iavl v0.12.4 // indirect github.com/zondax/hid v0.9.0 // indirect - github.com/zondax/ledger-go v0.9.0 // indirect - golang.org/x/net v0.0.0-20190628185345-da137c7871d7 // indirect - golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7 // indirect - golang.org/x/text v0.3.2 // indirect - google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2 // indirect - google.golang.org/grpc v1.22.0 // indirect - gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect - gopkg.in/yaml.v2 v2.2.2 // indirect + golang.org/x/net v0.3.0 // indirect + golang.org/x/sys v0.3.0 // indirect + golang.org/x/text v0.5.0 // indirect + google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb // indirect + google.golang.org/grpc v1.23.0 // indirect + gopkg.in/yaml.v2 v2.2.4 // indirect ) replace ( - github.com/tendermint/go-amino => github.com/binance-chain/bnc-go-amino v0.14.1-binance.1 - github.com/zondax/ledger-go => github.com/binance-chain/ledger-go v0.9.1 + github.com/cosmos/cosmos-sdk => github.com/bnb-chain/bnc-cosmos-sdk v0.25.4-0.20221221115251-f9e69ff1b273 + github.com/tendermint/go-amino => github.com/bnb-chain/bnc-go-amino v0.14.1-binance.2 + github.com/tendermint/iavl => github.com/bnb-chain/bnc-tendermint-iavl v0.12.0-binance.4 + github.com/tendermint/tendermint => github.com/bnb-chain/bnc-tendermint v0.32.3-binance.3.0.20221109023026-379ddbab19d1 + github.com/zondax/ledger-cosmos-go => github.com/bnb-chain/ledger-cosmos-go v0.9.9-binance.3 + github.com/zondax/ledger-go => github.com/bnb-chain/ledger-go v0.9.1 + golang.org/x/crypto => github.com/tendermint/crypto v0.0.0-20190823183015-45b1026d81ae ) diff --git a/go.sum b/go.sum index 9ada1c88..506c7e50 100644 --- a/go.sum +++ b/go.sum @@ -1,16 +1,40 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/DataDog/zstd v1.3.5 h1:DtpNbljikUepEPD16hD4LvIcmhnhdLTiW/5pHgbmp14= +github.com/DataDog/zstd v1.3.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= +github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/Shopify/sarama v1.21.0 h1:0GKs+e8mn1RRUzfg9oUXv3v7ZieQLmOZF/bfnmmGhM8= +github.com/Shopify/sarama v1.21.0/go.mod h1:yuqtN/pe8cXRWG5zPaO7hCfNJp5MwmkoJEoLjkm5tCQ= +github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= github.com/VividCortex/gohistogram v1.0.0 h1:6+hBz+qvs0JOrrNhhmR7lFxo5sINxBCGXrdtl/UvroE= github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= -github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 h1:xJ4a3vCFaGF/jqvzLMYoU8P317H5OQ+Via4RmuPwCS0= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/bartekn/go-bip39 v0.0.0-20171116152956-a05967ea095d h1:1aAija9gr0Hyv4KfQcRcwlmFIrhkDmIj2dz5bkg/s/8= +github.com/bartekn/go-bip39 v0.0.0-20171116152956-a05967ea095d/go.mod h1:icNx/6QdFblhsEjZehARqbNumymUT/ydwlLojFdv7Sk= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= -github.com/binance-chain/bnc-go-amino v0.14.1-binance.1 h1:RU33Toj/38sztKjcJTdziUIL0MBoMF7Xt1gQ3bT2zK0= -github.com/binance-chain/bnc-go-amino v0.14.1-binance.1/go.mod h1:yaElUUxWtv/TC/ldGtlKAvS1vKwokxgJ1d97I+6is80= -github.com/binance-chain/ledger-cosmos-go v0.9.9-binance.1 h1:8mAtw1Tp/BhhTrsXmXM60H1fihcvcKLfo2ZSxShaXKw= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= +github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/binance-chain/ledger-cosmos-go v0.9.9-binance.1/go.mod h1:FI6WAujuiBpoSavYreux2zTKyrUkngXDlRJczxsDK5M= -github.com/binance-chain/ledger-go v0.9.1 h1:OjKbhUSq19jmMVqdnmkczjSD7qH4UtW4KY2IhsKnvfM= -github.com/binance-chain/ledger-go v0.9.1/go.mod h1:Nd1Y0OY+m7C50kNEL4+LIH8Lj9DA9CbCLrv54t6fF1g= +github.com/bnb-chain/bnc-cosmos-sdk v0.25.4-0.20221221115251-f9e69ff1b273 h1:kfUgCOr+C81J6mHJeR0JgFcHTH8/jiMuYCdYPMfIfWU= +github.com/bnb-chain/bnc-cosmos-sdk v0.25.4-0.20221221115251-f9e69ff1b273/go.mod h1:PwnW2N20xpAqZ8PW+BajCUTX/CHDkB90A3Hl7jT1CUU= +github.com/bnb-chain/bnc-go-amino v0.14.1-binance.2 h1:iAlp9gqG0f2LGAauf3ZiijWlT6NI+W2r9y70HH9LI3k= +github.com/bnb-chain/bnc-go-amino v0.14.1-binance.2/go.mod h1:LiCO7jev+3HwLGAiN9gpD0z+jTz95RqgSavbse55XOY= +github.com/bnb-chain/bnc-tendermint v0.32.3-binance.3.0.20221109023026-379ddbab19d1 h1:+Bv9DlvDYUMBXipfqyuvUJeuwkAzFFdQhxmalWj0+Lk= +github.com/bnb-chain/bnc-tendermint v0.32.3-binance.3.0.20221109023026-379ddbab19d1/go.mod h1:EJSMv0Dh5v91CiHn+2pOnl1a3sdRVjpdekJ20AyYmlQ= +github.com/bnb-chain/bnc-tendermint-iavl v0.12.0-binance.4 h1:w8pAAx1N0lmVf0Lxs1prYuDikXwirOb9T7y2yw8zOBw= +github.com/bnb-chain/bnc-tendermint-iavl v0.12.0-binance.4/go.mod h1:Zmh8GRdNJB8DULIOBar3JCZp6tSpcvM1NGKfE9U2EzA= +github.com/bnb-chain/ledger-cosmos-go v0.9.9-binance.3 h1:a+QLVLaP32v9gfRDKHH2AcRkzYLTWbC8UxYTJkXRSec= +github.com/bnb-chain/ledger-cosmos-go v0.9.9-binance.3/go.mod h1:TULULYTvPuWBxFIZFy6KjJaxJzbHeUderYNB1YhD6N0= +github.com/bnb-chain/ledger-go v0.9.1/go.mod h1:EeUZBE/ZbIVOrb4PaSyx1Qz8WvNVG5QJfbw3LSqKv4Q= +github.com/bnb-chain/node v0.10.6 h1:a31ehuh5At5AWAMpY9MtshbO7jnfDewvtqrn481FCPA= +github.com/bnb-chain/node v0.10.6/go.mod h1:kqwX0JL7zII95oBLj5muozaHfQ66wX7gNR8PeYdkMug= github.com/btcsuite/btcd v0.0.0-20190115013929-ed77733ec07d/go.mod h1:d3C0AkH6BRcvO8T0UEPu53cnw4IbV63x1bEjildYhO0= github.com/btcsuite/btcd v0.20.1-beta h1:Ik4hyJqN8Jfyv3S4AGBOmyouMsYE3EdYODkMbQjwPGw= github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= @@ -23,52 +47,103 @@ github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVa github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= +github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= +github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= +github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d h1:49RLWk1j44Xu4fjHb6JFYmeUnDORVwHNkDxaQ0ctCVU= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= +github.com/cosmos/ledger-go v0.9.2 h1:Nnao/dLwaVTk1Q5U9THldpUMMXU94BOTWPddSmVB6pI= +github.com/cosmos/ledger-go v0.9.2/go.mod h1:oZJ2hHAZROdlHiwTg4t7kP+GKIIkBT+o6c9QWFanOyI= +github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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/deathowl/go-metrics-prometheus v0.0.0-20200518174047-74482eab5bfb h1:vhS5LxjRvIc6ptzKtTjzYV2rEsuAvTtez27UJkKIrjc= +github.com/deathowl/go-metrics-prometheus v0.0.0-20200518174047-74482eab5bfb/go.mod h1:kZ9Xvhj+PTMJ415unU/sutrnWDVqG0PDS/Sl4Rt3xkE= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= +github.com/eapache/go-resiliency v1.1.0 h1:1NtRmCAqadE2FN4ZcN6g90TP3uk8cg9rn9eNK2197aU= +github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= +github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 h1:YEetp8/yCZMuEPMUDHG0CW/brkkEp8mzqk2+ODEitlw= +github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= +github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc= +github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= github.com/etcd-io/bbolt v1.3.3 h1:gSJmxrs37LgTqR/oyJBWok6k6SvXEUerFTbltIhXkBM= github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw= -github.com/fortytw2/leaktest v1.2.0 h1:cj6GCiwJDH7l3tMHLjZDo0QqPtrXJiWSI9JgpeQKw+Q= github.com/fortytw2/leaktest v1.2.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= +github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= +github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/go-kit/kit v0.6.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.8.0 h1:Wz+5lgoB0kkuqLEc6NVmwRknTKP6dTGbSqvhZtBI/j0= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-logfmt/logfmt v0.3.0 h1:8HUsc87TaSWLKwrnumgC8/YconD2fJQsRJAsWaPg2ic= +github.com/go-kit/kit v0.9.0 h1:wDJmvq38kDhkVxi50ni9ykkdUr1PKgqKOoi01fa0Mdk= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0 h1:MP4Eh7ZCb31lleYCFuwm0oe4/YGak+5l1vA2NOE80nA= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/gogo/protobuf v1.2.1 h1:/s5zKNz0uPFCZ5hddgPdo2TK2TVrUNMn0OOX8/aZMTE= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= +github.com/gogo/protobuf v1.3.1 h1:DqDEcV5aeaTmdFBePNpYsp3FlcVH/2ISVVM9Qf8PSls= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw= +github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/websocket v1.2.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.1-0.20190629185528-ae1634f6a989 h1:giknQ4mEuDFmmHSrGcbargOuLHQGtywqo4mheITex54= github.com/gorilla/websocket v1.4.1-0.20190629185528-ae1634f6a989/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/hashicorp/golang-lru v0.5.3 h1:YPkqC67at8FYaadspW/6uE0COsBxS2656RLEr8Bppgk= +github.com/hashicorp/golang-lru v0.5.3/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/jmhodges/levigo v0.0.0-20161115193449-c42d9e0ca023/go.mod h1:Q6Qx+uH3RAqyK4rFQroq9RL7mdkABMcfhEI+nNuzMJQ= github.com/jmhodges/levigo v1.0.0 h1:q5EC36kV79HWeTBWsod3mG11EgStG3qArTKcvlksN1U= github.com/jmhodges/levigo v1.0.0/go.mod h1:Q6Qx+uH3RAqyK4rFQroq9RL7mdkABMcfhEI+nNuzMJQ= +github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515 h1:T+h1c/A9Gawja4Y9mFVWj2vyii2bbUNDw3kt9VxK2EY= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= @@ -76,108 +151,215 @@ github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORN github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/libp2p/go-buffer-pool v0.0.1 h1:9Rrn/H46cXjaA2HQ5Y8lyhOS1NhTkZ4yuEs2r3Eechg= -github.com/libp2p/go-buffer-pool v0.0.1/go.mod h1:xtyIz9PMobb13WaxR6Zo1Pd1zXJKYg0a8KiIvDp3TzQ= -github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY= +github.com/libp2p/go-buffer-pool v0.0.2 h1:QNK2iAFa8gjAe1SPz6mHSMuCcjs+X1wlHzeOSqcmlfs= +github.com/libp2p/go-buffer-pool v0.0.2/go.mod h1:MvaB6xw5vOrDl8rYZGLFdKAuk/hRoRZd1Vi32+RXyFM= +github.com/linkedin/goavro v0.0.0-20180427201934-fa8f6a30176c h1:5VZFnez+6M7nwhbIT8L4DtViRFR8GpYpZj97EVAphuk= +github.com/linkedin/goavro v0.0.0-20180427201934-fa8f6a30176c/go.mod h1:dGGt/b0JBWmQoI1Zfa2H/QIsh/viOpE0nHAvUgqJUf8= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4= +github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/mattn/go-isatty v0.0.10 h1:qxFzApOv4WsAL965uUPIsXzAKCZxN2p9UqdhFS4ZW10= +github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/natefinch/lumberjack v2.0.0+incompatible h1:4QJd3OLAMgj7ph+yZTuX13Ld4UpgHp07nNdFX7mqFfM= +github.com/natefinch/lumberjack v2.0.0+incompatible/go.mod h1:Wi9p2TTF5DG5oU+6YfsmYQpsTIOm0B1VNzQg9Mw6nPk= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU= +github.com/onsi/ginkgo v1.10.3 h1:OoxbjfXVZyod1fmWYhI7SEyaD8B00ynP3T+D5GiyHOY= +github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pelletier/go-toml v1.4.0 h1:u3Z1r+oOXJIkxqw34zVhyPgjBsm6X2wn21NWs/HfSeg= +github.com/pelletier/go-toml v1.4.0/go.mod h1:PN7xzY2wHTK0K9p34ErDQMlFxa51Fk0OUruD3k1mMwo= +github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I= +github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 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/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v0.9.2 h1:awm861/B8OKDd2I/6o1dy3ra4BamzKhYOiGItCeZ740= -github.com/prometheus/client_golang v0.9.2/go.mod h1:OsXs2jCmiKlQ1lTBmv21f2mNfw4xf/QclQDMrYNZzcM= -github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910 h1:idejC8f05m9MGOsuEi1ATq9shN03HrxNkD/luQvxCv8= +github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.1.0 h1:BQ53HtBmfOitExawJ6LokA4x8ov/z0SYYb0+HxJfRI8= +github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90 h1:S/YWwWx/RA8rT8tKFRuGUZhuA90OyIBpPCXkcbwU8DE= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/common v0.0.0-20181020173914-7e9e6cabbd39/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= -github.com/prometheus/common v0.0.0-20181126121408-4724e9255275 h1:PnBWHBf+6L0jOqq0gIVUe6Yk0/QMZ640k6NvkxcBf+8= -github.com/prometheus/common v0.0.0-20181126121408-4724e9255275/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.6.0 h1:kRhiuYSXR3+uv2IbVbZhUxK5zVD/2pp3Gd2PpvPkpEo= +github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a h1:9a8MnZMP0X2nLJdBg+pBmGgkJlSaKC2KaQmTCk1XDtE= -github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.3 h1:CTwfnzjQ+8dS6MhHHu4YswVAD99sL2wjPqP+VkURmKE= +github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= +github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= +github.com/rakyll/statik v0.1.5/go.mod h1:OEi9wJV/fMUAGx1eNjq75DKDsJVuEv1U0oYdX6GX8Zs= github.com/rcrowley/go-metrics v0.0.0-20180503174638-e2704e165165/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= -github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a h1:9ZKAASQSHhDYGoxY8uLVpewe1GDZ2vu2Tr/vTdVAkFQ= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/rcrowley/go-metrics v0.0.0-20190826022208-cac0b30c2563 h1:dY6ETXrvDG7Sa4vE8ZQG4yqWg6UnOcbqTAahkV813vQ= +github.com/rcrowley/go-metrics v0.0.0-20190826022208-cac0b30c2563/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rs/cors v1.6.0 h1:G9tHG9lebljV9mfp9SNPDL36nCDxmo3zTlAf1YgvzmI= github.com/rs/cors v1.6.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa/go.mod h1:oJyF+mSPHbB5mVY2iO9KV3pTt/QbIkGaO8gQ2WrDbP4= +github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= +github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= +github.com/spf13/afero v1.2.2 h1:5jhuqJyZCZf2JRofRvN/nIFgIWNzPa3/Vz8mYylgbWc= +github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= +github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cobra v0.0.1/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/cobra v0.0.5 h1:f0B+LkLX6DtmRH1isoNA9VTtNUK9K8xYd28JNNfOv/s= +github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= +github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= +github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= +github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/viper v1.0.0/go.mod h1:A8kyI5cUJhb8N+3pkfONlcEcZbueH6nhAm0Fq7SrnBM= +github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= +github.com/spf13/viper v1.4.0 h1:yXHLWeravcrgGyFSyCgdYpXQ9dR9c/WED3pg1RhxqEU= +github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/syndtr/goleveldb v0.0.0-20181105012736-f9080354173f/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= github.com/syndtr/goleveldb v1.0.1-0.20190318030020-c3a204f8e965/go.mod h1:9OrXJhf154huy1nPWmuSrkgjPUtUNhA+Zmy+6AESzuA= github.com/syndtr/goleveldb v1.0.1-0.20190923125748-758128399b1d h1:gZZadD8H+fF+n9CmNhYL1Y0dJB+kLOmKd7FbPJLeGHs= github.com/syndtr/goleveldb v1.0.1-0.20190923125748-758128399b1d/go.mod h1:9OrXJhf154huy1nPWmuSrkgjPUtUNhA+Zmy+6AESzuA= -github.com/tendermint/btcd v0.0.0-20180816174608-e5840949ff4f h1:R0wLxgASGMoRQTF/dCSk4N+M3j9DLyPDzDff2WtCg/I= -github.com/tendermint/btcd v0.0.0-20180816174608-e5840949ff4f/go.mod h1:DC6/m53jtQzr/NFmMNEu0rxf18/ktVoVtMrnDD5pN+U= -github.com/tendermint/tendermint v0.32.3 h1:GEnWpGQ795h5oTFNbfBLsY0LW/CW2j6p6HtiYNfxsgg= -github.com/tendermint/tendermint v0.32.3/go.mod h1:ZK2c29jl1QRYznIRyRWRDsmm1yvtPzBRT00x4t1JToY= -github.com/tendermint/tm-db v0.1.1 h1:G3Xezy3sOk9+ekhjZ/kjArYIs1SmwV+1OUgNkj7RgV0= -github.com/tendermint/tm-db v0.1.1/go.mod h1:0cPKWu2Mou3IlxecH+MEUSYc1Ch537alLe6CpFrKzgw= +github.com/tendermint/btcd v0.1.1 h1:0VcxPfflS2zZ3RiOAHkBiFUcPvbtRj5O7zHmcJWHV7s= +github.com/tendermint/btcd v0.1.1/go.mod h1:DC6/m53jtQzr/NFmMNEu0rxf18/ktVoVtMrnDD5pN+U= +github.com/tendermint/crypto v0.0.0-20190823183015-45b1026d81ae h1:AOXNM7c2Vvo45SjAgeWF8Wy+NS7/NCqzRNpUc+HPAec= +github.com/tendermint/crypto v0.0.0-20190823183015-45b1026d81ae/go.mod h1:z4YtwM70uOnk8h0pjJYlj3zdYwi9l03By6iAIF5j/Pk= +github.com/tidwall/gjson v1.14.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= +github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= +github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/zondax/hid v0.9.0 h1:eiT3P6vNxAEVxXMw66eZUAAnU2zD33JBkfG/EnfAKl8= github.com/zondax/hid v0.9.0/go.mod h1:l5wttcP0jwtdLjqjMMWFVEE7d1zO0jvSPA9OPZxWpEM= +go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.3.3 h1:MUGmc65QhB3pIlaQ5bB4LwqSj6GIonVJXpZiaKNyaKk= go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= -golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 h1:HuIa8hRrWRSrqYzx1qI49NNxhdi2PrY7gxVSq1JjLDc= -golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/ratelimit v0.1.0/go.mod h1:2X8KaoNd1J0lZV+PxJk/5+DGbO/tpwLR1m++a7FnB/Y= +go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181011144130-49bb7cea24b1/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190628185345-da137c7871d7 h1:rTIdg5QFRR7XCaK4LCjBiPbx8j4DQRpdYMnGn/bJUEU= -golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190909003024-a7b16738d86b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.3.0 h1:VWL6FNY2bEEmsGVKabSlHu5Irp34xmMRoqb/9lF9lxk= +golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7 h1:LepdCS8Gf/MVejFIt8lsiexZATdoGVyp5bcyS+rYoUI= -golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ= +golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.5.0 h1:OLmvp0KP+FVG99Ct/qFiL/Fhk4zp4QQnZ7b2U+5piUM= +golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2 h1:67iHsV9djwGdZpdZNbLuQj6FOzCaZe3w+vhLjn5AcFA= google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/grpc v1.22.0 h1:J0UbZOIrCAl+fpTOf8YLs4dJo8L/owV4LYVtAXQoPkw= -google.golang.org/grpc v1.22.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb h1:i1Ppqkc3WQXikh8bXiwHqAN5Rv3/qDCcRk0/Otx73BY= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.23.0 h1:AzbTB6ux+okLTzP8Ru1Xs41C303zdcfEht7MQnYJt5A= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/resty.v1 v1.10.3 h1:w8FjChB7PWrvE5z6JX/gfFzVwTDj38qiAQJKgdWDGvA= -gopkg.in/resty.v1 v1.10.3/go.mod h1:nrgQYbPhkRfn2BfT32NNTLfq3K9NuHRB0MsAcA9weWY= +gopkg.in/linkedin/goavro.v1 v1.0.5/go.mod h1:Aw5GdAbizjOEl0kAMHV9iHmA8reZzW/OKuJAl4Hb9F0= +gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= +gopkg.in/resty.v1 v1.12.0 h1:CuXP0Pjfw9rOuY6EP+UvtNvt5DSqHpIxILZKT/quCZI= +gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/keys/keys.go b/keys/keys.go index 17904609..48072963 100644 --- a/keys/keys.go +++ b/keys/keys.go @@ -14,12 +14,12 @@ import ( "github.com/tendermint/tendermint/crypto/secp256k1" - "github.com/binance-chain/go-sdk/common" - "github.com/binance-chain/go-sdk/common/ledger" - "github.com/binance-chain/go-sdk/common/types" - ctypes "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/common/uuid" - "github.com/binance-chain/go-sdk/types/tx" + "github.com/bnb-chain/go-sdk/common" + "github.com/bnb-chain/go-sdk/common/ledger" + "github.com/bnb-chain/go-sdk/common/types" + ctypes "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/common/uuid" + "github.com/bnb-chain/go-sdk/types/tx" "github.com/tendermint/tendermint/crypto" ) @@ -28,7 +28,7 @@ const ( ) type KeyManager interface { - Sign(tx.StdSignMsg) ([]byte, error) + Sign(msg tx.StdSignMsg) ([]byte, error) GetPrivKey() crypto.PrivKey GetAddr() ctypes.AccAddress diff --git a/keys/keys_test.go b/keys/keys_test.go index 13ccd9e1..0af2ab8c 100644 --- a/keys/keys_test.go +++ b/keys/keys_test.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/hex" "encoding/json" + "github.com/bnb-chain/go-sdk/types/tx" "io/ioutil" "os" "testing" @@ -11,9 +12,8 @@ import ( "github.com/stretchr/testify/assert" - ctypes "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/types/msg" - "github.com/binance-chain/go-sdk/types/tx" + ctypes "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/types/msg" ) func TestRecoveryFromKeyWordsNoError(t *testing.T) { diff --git a/types/msg/msg-HTLT.go b/types/msg/msg-HTLT.go deleted file mode 100644 index 072d78e9..00000000 --- a/types/msg/msg-HTLT.go +++ /dev/null @@ -1,251 +0,0 @@ -package msg - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common/types" - "github.com/tendermint/tendermint/crypto" -) - -const ( - AtomicSwapRoute = "atomicSwap" - HTLT = "HTLT" - DepositHTLT = "depositHTLT" - ClaimHTLT = "claimHTLT" - RefundHTLT = "refundHTLT" - - Int64Size = 8 - RandomNumberHashLength = 32 - RandomNumberLength = 32 - MaxOtherChainAddrLength = 64 - SwapIDLength = 32 - MaxExpectedIncomeLength = 64 - MinimumHeightSpan = 360 - MaximumHeightSpan = 518400 -) - -var ( - // bnb prefix address: bnb1wxeplyw7x8aahy93w96yhwm7xcq3ke4f8ge93u - // tbnb prefix address: tbnb1wxeplyw7x8aahy93w96yhwm7xcq3ke4ffasp3d - AtomicSwapCoinsAccAddr = types.AccAddress(crypto.AddressHash([]byte("BinanceChainAtomicSwapCoins"))) -) - -type HTLTMsg struct { - From types.AccAddress `json:"from"` - To types.AccAddress `json:"to"` - RecipientOtherChain string `json:"recipient_other_chain"` - SenderOtherChain string `json:"sender_other_chain"` - RandomNumberHash types.SwapBytes `json:"random_number_hash"` - Timestamp int64 `json:"timestamp"` - Amount types.Coins `json:"amount"` - ExpectedIncome string `json:"expected_income"` - HeightSpan int64 `json:"height_span"` - CrossChain bool `json:"cross_chain"` -} - -func NewHTLTMsg(from, to types.AccAddress, recipientOtherChain, senderOtherChain string, randomNumberHash types.SwapBytes, timestamp int64, - amount types.Coins, expectedIncome string, heightSpan int64, crossChain bool) HTLTMsg { - return HTLTMsg{ - From: from, - To: to, - RecipientOtherChain: recipientOtherChain, - SenderOtherChain: senderOtherChain, - RandomNumberHash: randomNumberHash, - Timestamp: timestamp, - Amount: amount, - ExpectedIncome: expectedIncome, - HeightSpan: heightSpan, - CrossChain: crossChain, - } -} - -func (msg HTLTMsg) Route() string { return AtomicSwapRoute } -func (msg HTLTMsg) Type() string { return HTLT } -func (msg HTLTMsg) String() string { - return fmt.Sprintf("HTLT{%v#%v#%v#%v#%v#%v#%v#%v#%v#%v}", msg.From, msg.To, msg.RecipientOtherChain, msg.SenderOtherChain, msg.RandomNumberHash, - msg.Timestamp, msg.Amount, msg.ExpectedIncome, msg.HeightSpan, msg.CrossChain) -} -func (msg HTLTMsg) GetInvolvedAddresses() []types.AccAddress { - return append(msg.GetSigners(), AtomicSwapCoinsAccAddr) -} -func (msg HTLTMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.From} -} - -func (msg HTLTMsg) ValidateBasic() error { - if len(msg.From) != types.AddrLen { - return fmt.Errorf("the expected address length is %d, actual length is %d", types.AddrLen, len(msg.From)) - } - if len(msg.To) != types.AddrLen { - return fmt.Errorf("the expected address length is %d, actual length is %d", types.AddrLen, len(msg.To)) - } - if !msg.CrossChain && len(msg.RecipientOtherChain) != 0 { - return fmt.Errorf("must leave recipient address on other chain to empty for single chain swap") - } - if !msg.CrossChain && len(msg.SenderOtherChain) != 0 { - return fmt.Errorf("must leave sender address on other chain to empty for single chain swap") - } - if msg.CrossChain && len(msg.RecipientOtherChain) == 0 { - return fmt.Errorf("missing recipient address on other chain for cross chain swap") - } - if len(msg.RecipientOtherChain) > MaxOtherChainAddrLength { - return fmt.Errorf("the length of recipient address on other chain should be less than %d", MaxOtherChainAddrLength) - } - if len(msg.SenderOtherChain) > MaxOtherChainAddrLength { - return fmt.Errorf("the length of sender address on other chain should be less than %d", MaxOtherChainAddrLength) - } - if len(msg.ExpectedIncome) > MaxExpectedIncomeLength { - return fmt.Errorf("the length of expected income should be less than %d", MaxExpectedIncomeLength) - } - if len(msg.RandomNumberHash) != RandomNumberHashLength { - return fmt.Errorf("the length of random number hash should be %d", RandomNumberHashLength) - } - if !msg.Amount.IsPositive() { - return fmt.Errorf("the swapped out coin must be positive") - } - if msg.HeightSpan < MinimumHeightSpan || msg.HeightSpan > MaximumHeightSpan { - return fmt.Errorf("the height span should be no less than 360 and no greater than 518400") - } - return nil -} - -func (msg HTLTMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -type DepositHTLTMsg struct { - From types.AccAddress `json:"from"` - Amount types.Coins `json:"amount"` - SwapID types.SwapBytes `json:"swap_id"` -} - -func NewDepositHTLTMsg(from types.AccAddress, swapID []byte, amount types.Coins) DepositHTLTMsg { - return DepositHTLTMsg{ - From: from, - SwapID: swapID, - Amount: amount, - } -} - -func (msg DepositHTLTMsg) Route() string { return AtomicSwapRoute } -func (msg DepositHTLTMsg) Type() string { return DepositHTLT } -func (msg DepositHTLTMsg) String() string { - return fmt.Sprintf("depositHTLT{%v#%v#%v}", msg.From, msg.Amount, msg.SwapID) -} -func (msg DepositHTLTMsg) GetInvolvedAddresses() []types.AccAddress { - return append(msg.GetSigners(), AtomicSwapCoinsAccAddr) -} -func (msg DepositHTLTMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.From} -} - -func (msg DepositHTLTMsg) ValidateBasic() error { - if len(msg.From) != types.AddrLen { - return fmt.Errorf("the expected address length is %d, actual length is %d", types.AddrLen, len(msg.From)) - } - if len(msg.SwapID) != SwapIDLength { - return fmt.Errorf("the length of swapID should be %d", SwapIDLength) - } - if !msg.Amount.IsPositive() { - return fmt.Errorf("the swapped out coin must be positive") - } - return nil -} - -func (msg DepositHTLTMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -type ClaimHTLTMsg struct { - From types.AccAddress `json:"from"` - SwapID types.SwapBytes `json:"swap_id"` - RandomNumber types.SwapBytes `json:"random_number"` -} - -func NewClaimHTLTMsg(from types.AccAddress, swapID, randomNumber []byte) ClaimHTLTMsg { - return ClaimHTLTMsg{ - From: from, - SwapID: swapID, - RandomNumber: randomNumber, - } -} - -func (msg ClaimHTLTMsg) Route() string { return AtomicSwapRoute } -func (msg ClaimHTLTMsg) Type() string { return ClaimHTLT } -func (msg ClaimHTLTMsg) String() string { - return fmt.Sprintf("claimHTLT{%v#%v#%v}", msg.From, msg.SwapID, msg.RandomNumber) -} -func (msg ClaimHTLTMsg) GetInvolvedAddresses() []types.AccAddress { - return append(msg.GetSigners(), AtomicSwapCoinsAccAddr) -} -func (msg ClaimHTLTMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} } - -func (msg ClaimHTLTMsg) ValidateBasic() error { - if len(msg.From) != types.AddrLen { - return fmt.Errorf("the expected address length is %d, actual length is %d", types.AddrLen, len(msg.From)) - } - if len(msg.SwapID) != SwapIDLength { - return fmt.Errorf("the length of swapID should be %d", SwapIDLength) - } - if len(msg.RandomNumber) != RandomNumberLength { - return fmt.Errorf("the length of random number should be %d", RandomNumberLength) - } - return nil -} - -func (msg ClaimHTLTMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -type RefundHTLTMsg struct { - From types.AccAddress `json:"from"` - SwapID types.SwapBytes `json:"swap_id"` -} - -func NewRefundHTLTMsg(from types.AccAddress, swapID []byte) RefundHTLTMsg { - return RefundHTLTMsg{ - From: from, - SwapID: swapID, - } -} - -func (msg RefundHTLTMsg) Route() string { return AtomicSwapRoute } -func (msg RefundHTLTMsg) Type() string { return RefundHTLT } -func (msg RefundHTLTMsg) String() string { - return fmt.Sprintf("refundHTLT{%v#%v}", msg.From, msg.SwapID) -} -func (msg RefundHTLTMsg) GetInvolvedAddresses() []types.AccAddress { - return append(msg.GetSigners(), AtomicSwapCoinsAccAddr) -} -func (msg RefundHTLTMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} } - -func (msg RefundHTLTMsg) ValidateBasic() error { - if len(msg.From) != types.AddrLen { - return fmt.Errorf("the expected address length is %d, actual length is %d", types.AddrLen, len(msg.From)) - } - if len(msg.SwapID) != SwapIDLength { - return fmt.Errorf("the length of swapID should be %d", SwapIDLength) - } - return nil -} - -func (msg RefundHTLTMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} diff --git a/types/msg/msg-bridge.go b/types/msg/msg-bridge.go deleted file mode 100644 index 75cf01f4..00000000 --- a/types/msg/msg-bridge.go +++ /dev/null @@ -1,227 +0,0 @@ -package msg - -import ( - "encoding/json" - "fmt" - "math/big" - - sdk "github.com/binance-chain/go-sdk/common/types" -) - -const ( - RouteBridge = "bridge" - - BindMsgType = "crossBind" - UnbindMsgType = "crossUnbind" - TransferOutMsgType = "crossTransferOut" -) - -const ( - MaxSymbolLength = 32 -) - -// SmartChainAddress defines a standard smart chain address -type SmartChainAddress [20]byte - -// NewSmartChainAddress is a constructor function for SmartChainAddress -func NewSmartChainAddress(addr string) SmartChainAddress { - // we don't want to return error here, ethereum also do the same thing here - hexBytes, _ := HexDecode(addr) - var address SmartChainAddress - address.SetBytes(hexBytes) - return address -} - -func (addr *SmartChainAddress) SetBytes(b []byte) { - if len(b) > len(addr) { - b = b[len(b)-20:] - } - copy(addr[20-len(b):], b) -} - -func (addr SmartChainAddress) IsEmpty() bool { - addrValue := big.NewInt(0) - addrValue.SetBytes(addr[:]) - - return addrValue.Cmp(big.NewInt(0)) == 0 -} - -// Route should return the name of the module -func (addr SmartChainAddress) String() string { - return HexAddress(addr[:]) -} - -// MarshalJSON marshals the ethereum address to JSON -func (addr SmartChainAddress) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf("\"%v\"", addr.String())), nil -} - -// UnmarshalJSON unmarshals an smart chain address -func (addr *SmartChainAddress) UnmarshalJSON(input []byte) error { - hexBytes, err := HexDecode(string(input[1 : len(input)-1])) - if err != nil { - return err - } - addr.SetBytes(hexBytes) - return nil -} - -type BindStatus int8 - -type BindMsg struct { - From sdk.AccAddress `json:"from"` - Symbol string `json:"symbol"` - Amount int64 `json:"amount"` - ContractAddress SmartChainAddress `json:"contract_address"` - ContractDecimals int8 `json:"contract_decimals"` - ExpireTime int64 `json:"expire_time"` -} - -func NewBindMsg(from sdk.AccAddress, symbol string, amount int64, contractAddress SmartChainAddress, contractDecimals int8, expireTime int64) BindMsg { - return BindMsg{ - From: from, - Amount: amount, - Symbol: symbol, - ContractAddress: contractAddress, - ContractDecimals: contractDecimals, - ExpireTime: expireTime, - } -} - -func (msg BindMsg) Route() string { return RouteBridge } -func (msg BindMsg) Type() string { return BindMsgType } -func (msg BindMsg) String() string { - return fmt.Sprintf("Bind{%v#%s#%d$%s#%d#%d}", msg.From, msg.Symbol, msg.Amount, msg.ContractAddress.String(), msg.ContractDecimals, msg.ExpireTime) -} -func (msg BindMsg) GetInvolvedAddresses() []sdk.AccAddress { return msg.GetSigners() } -func (msg BindMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.From} } - -func (msg BindMsg) ValidateBasic() error { - if len(msg.From) != sdk.AddrLen { - return fmt.Errorf("address length should be %d", sdk.AddrLen) - } - - if len(msg.Symbol) == 0 { - return fmt.Errorf("symbol should not be empty") - } - - if msg.Amount <= 0 { - return fmt.Errorf("amount should be larger than 0") - } - - if msg.ContractAddress.IsEmpty() { - return fmt.Errorf("contract address should not be empty") - } - - if msg.ContractDecimals < 0 { - return fmt.Errorf("decimal should be no less than 0") - } - - if msg.ExpireTime <= 0 { - return fmt.Errorf("expire time should be larger than 0") - } - - return nil -} - -func (msg BindMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) // XXX: ensure some canonical form - if err != nil { - panic(err) - } - return b -} - -type TransferOutMsg struct { - From sdk.AccAddress `json:"from"` - To SmartChainAddress `json:"to"` - Amount sdk.Coin `json:"amount"` - ExpireTime int64 `json:"expire_time"` -} - -func NewTransferOutMsg(from sdk.AccAddress, to SmartChainAddress, amount sdk.Coin, expireTime int64) TransferOutMsg { - return TransferOutMsg{ - From: from, - To: to, - Amount: amount, - ExpireTime: expireTime, - } -} - -func (msg TransferOutMsg) Route() string { return RouteBridge } -func (msg TransferOutMsg) Type() string { return TransferOutMsgType } -func (msg TransferOutMsg) String() string { - return fmt.Sprintf("TransferOut{%v#%s#%s#%d}", msg.From, msg.To.String(), msg.Amount.String(), msg.ExpireTime) -} -func (msg TransferOutMsg) GetInvolvedAddresses() []sdk.AccAddress { return msg.GetSigners() } -func (msg TransferOutMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.From} } -func (msg TransferOutMsg) ValidateBasic() error { - if len(msg.From) != sdk.AddrLen { - return fmt.Errorf("address length should be %d", sdk.AddrLen) - } - - if msg.To.IsEmpty() { - return fmt.Errorf("to address should not be empty") - } - - if !msg.Amount.IsPositive() { - return fmt.Errorf("amount should be positive") - } - - if msg.ExpireTime <= 0 { - return fmt.Errorf("expire time should be larger than 0") - } - - return nil -} -func (msg TransferOutMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) // XXX: ensure some canonical form - if err != nil { - panic(err) - } - return b -} - -type UnbindMsg struct { - From sdk.AccAddress `json:"from"` - Symbol string `json:"symbol"` -} - -func NewUnbindMsg(from sdk.AccAddress, symbol string) UnbindMsg { - return UnbindMsg{ - From: from, - Symbol: symbol, - } -} - -func (msg UnbindMsg) Route() string { return RouteBridge } -func (msg UnbindMsg) Type() string { return UnbindMsgType } -func (msg UnbindMsg) String() string { - return fmt.Sprintf("Unbind{%v#%s}", msg.From, msg.Symbol) -} -func (msg UnbindMsg) GetInvolvedAddresses() []sdk.AccAddress { return msg.GetSigners() } -func (msg UnbindMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.From} } - -func (msg UnbindMsg) ValidateBasic() error { - if len(msg.From) != sdk.AddrLen { - return fmt.Errorf("address length should be %d", sdk.AddrLen) - } - - if len(msg.Symbol) == 0 { - return fmt.Errorf("symbol should not be empty") - } - - if len(msg.Symbol) > MaxSymbolLength { - return fmt.Errorf("symbol length should not be larger than %d", MaxSymbolLength) - } - - return nil -} - -func (msg UnbindMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) // XXX: ensure some canonical form - if err != nil { - panic(err) - } - return b -} diff --git a/types/msg/msg-burn.go b/types/msg/msg-burn.go deleted file mode 100644 index 0c42dcc1..00000000 --- a/types/msg/msg-burn.go +++ /dev/null @@ -1,68 +0,0 @@ -package msg - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common/types" -) - -// TokenBurnMsg def -type TokenBurnMsg struct { - From types.AccAddress `json:"from"` - Symbol string `json:"symbol"` - Amount int64 `json:"amount"` -} - -// NewMsg for instance creation -func NewTokenBurnMsg(from types.AccAddress, symbol string, amount int64) TokenBurnMsg { - return TokenBurnMsg{From: from, Symbol: symbol, Amount: amount} -} - -// Route is part of Msg interface -func (msg TokenBurnMsg) Route() string { - return "tokensBurn" -} - -// Type is part of Msg interface -func (msg TokenBurnMsg) Type() string { - return "tokensBurn" -} - -// String is part of Msg interface -func (msg TokenBurnMsg) String() string { - return fmt.Sprintf("BurnMsg{%v#%v%v}", msg.From, msg.Amount, msg.Symbol) -} - -// GetInvolvedAddresses is part of Msg interface -func (msg TokenBurnMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -func (msg TokenBurnMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -// GetSigners is part of Msg interface -func (msg TokenBurnMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.From} -} - -// ValidateBasic does a simple validation check that -// doesn't require access to any other information. -func (msg TokenBurnMsg) ValidateBasic() error { - err := ValidateSymbol(msg.Symbol) - if err != nil { - return fmt.Errorf("ErrInvalidCoins %s", msg.Symbol) - } - - if msg.Amount <= 0 { - return fmt.Errorf("ErrInsufficientFunds, amount should be more than 0") - } - - return nil -} diff --git a/types/msg/msg-dexList.go b/types/msg/msg-dexList.go deleted file mode 100644 index 485d4097..00000000 --- a/types/msg/msg-dexList.go +++ /dev/null @@ -1,73 +0,0 @@ -package msg - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common/types" -) - -// DexListMsg def -type DexListMsg struct { - From types.AccAddress `json:"from"` - ProposalId int64 `json:"proposal_id"` - BaseAssetSymbol string `json:"base_asset_symbol"` - QuoteAssetSymbol string `json:"quote_asset_symbol"` - InitPrice int64 `json:"init_price"` -} - -// NewDexListMsg for instance creation -func NewDexListMsg(from types.AccAddress, proposalId int64, baseAssetSymbol string, quoteAssetSymbol string, initPrice int64) DexListMsg { - return DexListMsg{ - From: from, - ProposalId: proposalId, - BaseAssetSymbol: baseAssetSymbol, - QuoteAssetSymbol: quoteAssetSymbol, - InitPrice: initPrice, - } -} - -// Route part of Msg interface -func (msg DexListMsg) Route() string { return "dexList" } - -// Type part of Msg interface -func (msg DexListMsg) Type() string { return "dexList" } - -// String part of Msg interface -func (msg DexListMsg) String() string { return fmt.Sprintf("MsgList{%#v}", msg) } - -// GetSigners part of Msg interface -func (msg DexListMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} } - -// GetSignBytes part of Msg interface -func (msg DexListMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -// GetInvolvedAddresses part of Msg interface -func (msg DexListMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -// ValidateBasic part of Msg interface -func (msg DexListMsg) ValidateBasic() error { - err := ValidateSymbol(msg.BaseAssetSymbol) - if err != nil { - return fmt.Errorf("Invalid base asset token %v", msg.BaseAssetSymbol) - } - - err = ValidateSymbol(msg.QuoteAssetSymbol) - if err != nil { - return fmt.Errorf("Invalid quote asset token %v", msg.QuoteAssetSymbol) - } - - if msg.InitPrice <= 0 { - return fmt.Errorf("Price should be positive") - } - - return nil -} diff --git a/types/msg/msg-dexListMini.go b/types/msg/msg-dexListMini.go deleted file mode 100644 index 4dc5f765..00000000 --- a/types/msg/msg-dexListMini.go +++ /dev/null @@ -1,66 +0,0 @@ -package msg - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common/types" -) - -// ListMiniMsg def -type ListMiniMsg struct { - From types.AccAddress `json:"from"` - BaseAssetSymbol string `json:"base_asset_symbol"` - QuoteAssetSymbol string `json:"quote_asset_symbol"` - InitPrice int64 `json:"init_price"` -} - -// NewListMiniMsg for instance creation -func NewListMiniMsg(from types.AccAddress, baseAssetSymbol string, quoteAssetSymbol string, initPrice int64) ListMiniMsg { - return ListMiniMsg{ - From: from, - BaseAssetSymbol: baseAssetSymbol, - QuoteAssetSymbol: quoteAssetSymbol, - InitPrice: initPrice, - } -} - -// Route part of Msg interface -func (msg ListMiniMsg) Route() string { return "dexListMini" } - -// Type part of Msg interface -func (msg ListMiniMsg) Type() string { return "dexListMini" } - -// String part of Msg interface -func (msg ListMiniMsg) String() string { return fmt.Sprintf("MsgListMini{%#v}", msg) } - -// GetSigners part of Msg interface -func (msg ListMiniMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} } - -// GetSignBytes part of Msg interface -func (msg ListMiniMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -// GetInvolvedAddresses part of Msg interface -func (msg ListMiniMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -// ValidateBasic part of Msg interface -func (msg ListMiniMsg) ValidateBasic() error { - err := ValidateMiniTokenSymbol(msg.BaseAssetSymbol) - if err != nil { - return fmt.Errorf("Invalid base asset token %v", msg.BaseAssetSymbol) - } - - if msg.InitPrice <= 0 { - return fmt.Errorf("Price should be positive") - } - - return nil -} diff --git a/types/msg/msg-freeze.go b/types/msg/msg-freeze.go deleted file mode 100644 index cbc0c189..00000000 --- a/types/msg/msg-freeze.go +++ /dev/null @@ -1,114 +0,0 @@ -package msg - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common/types" -) - -// TokenFreezeMsg def -type TokenFreezeMsg struct { - From types.AccAddress `json:"from"` - Symbol string `json:"symbol"` - Amount int64 `json:"amount"` -} - -// NewFreezeMsg for instance creation -func NewFreezeMsg(from types.AccAddress, symbol string, amount int64) TokenFreezeMsg { - return TokenFreezeMsg{From: from, Symbol: symbol, Amount: amount} -} - -// Route is part of Msg interface -func (msg TokenFreezeMsg) Route() string { return "tokensFreeze" } - -// Type is part of Msg interface -func (msg TokenFreezeMsg) Type() string { return "tokensFreeze" } - -// String is part of Msg interface -func (msg TokenFreezeMsg) String() string { - return fmt.Sprintf("Freeze{%v#%v}", msg.From, msg.Symbol) -} - -// GetInvolvedAddresses is part of Msg interface -func (msg TokenFreezeMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -func (msg TokenFreezeMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.From} -} - -func (msg TokenFreezeMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -func (msg TokenFreezeMsg) ValidateBasic() error { - err := ValidateSymbol(msg.Symbol) - if err != nil { - return fmt.Errorf("ErrInvalidCoins %s", msg.Symbol) - } - - if msg.Amount <= 0 { - return fmt.Errorf("ErrInsufficientFunds, amount should be more than 0") - } - - return nil -} - -// TokenUnfreezeMsg def -type TokenUnfreezeMsg struct { - From types.AccAddress `json:"from"` - Symbol string `json:"symbol"` - Amount int64 `json:"amount"` -} - -// NewUnfreezeMsg for instance creation -func NewUnfreezeMsg(from types.AccAddress, symbol string, amount int64) TokenUnfreezeMsg { - return TokenUnfreezeMsg{From: from, Symbol: symbol, Amount: amount} -} - -// Route is part of Msg interface -func (msg TokenUnfreezeMsg) Route() string { return "tokensFreeze" } - -// Type is part of Msg interface -func (msg TokenUnfreezeMsg) Type() string { return "tokensFreeze" } - -// String is part of Msg interface -func (msg TokenUnfreezeMsg) String() string { - return fmt.Sprintf("Unfreeze{%v#%v%v}", msg.From, msg.Amount, msg.Symbol) -} - -// GetInvolvedAddresses is part of Msg interface -func (msg TokenUnfreezeMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -func (msg TokenUnfreezeMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.From} -} - -func (msg TokenUnfreezeMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -func (msg TokenUnfreezeMsg) ValidateBasic() error { - err := ValidateSymbol(msg.Symbol) - if err != nil { - return fmt.Errorf("ErrInvalidCoins %s", msg.Symbol) - } - - if msg.Amount <= 0 { - return fmt.Errorf("ErrInsufficientFunds, amount should be more than 0") - } - - return nil -} diff --git a/types/msg/msg-gov.go b/types/msg/msg-gov.go deleted file mode 100644 index d158ddad..00000000 --- a/types/msg/msg-gov.go +++ /dev/null @@ -1,456 +0,0 @@ -package msg - -import ( - "encoding/json" - "fmt" - "time" - - "github.com/binance-chain/go-sdk/common/types" - "github.com/pkg/errors" - "github.com/tendermint/go-amino" -) - -// name to idetify transaction types -const ( - MsgRoute = "gov" - - MaxTitleLength = 128 - MaxDescriptionLength int = 2048 - MaxVotingPeriod = 2 * 7 * 24 * 60 * 60 * time.Second // 2 weeks -) - -type VoteOption byte - -//nolint -const ( - OptionEmpty VoteOption = 0x00 - OptionYes VoteOption = 0x01 - OptionAbstain VoteOption = 0x02 - OptionNo VoteOption = 0x03 - OptionNoWithVeto VoteOption = 0x04 -) - -// String to proposalType byte. Returns ff if invalid. -func VoteOptionFromString(str string) (VoteOption, error) { - switch str { - case "Yes": - return OptionYes, nil - case "Abstain": - return OptionAbstain, nil - case "No": - return OptionNo, nil - case "NoWithVeto": - return OptionNoWithVeto, nil - default: - return VoteOption(0xff), errors.Errorf("'%s' is not a valid vote option", str) - } -} - -// Marshal needed for protobuf compatibility -func (vo VoteOption) Marshal() ([]byte, error) { - return []byte{byte(vo)}, nil -} - -// Unmarshal needed for protobuf compatibility -func (vo *VoteOption) Unmarshal(data []byte) error { - *vo = VoteOption(data[0]) - return nil -} - -// Marshals to JSON using string -func (vo VoteOption) MarshalJSON() ([]byte, error) { - return json.Marshal(vo.String()) -} - -// Unmarshals from JSON assuming Bech32 encoding -func (vo *VoteOption) UnmarshalJSON(data []byte) error { - var s string - err := json.Unmarshal(data, &s) - if err != nil { - return nil - } - - bz2, err := VoteOptionFromString(s) - if err != nil { - return err - } - *vo = bz2 - return nil -} - -// Turns VoteOption byte to String -func (vo VoteOption) String() string { - switch vo { - case OptionYes: - return "Yes" - case OptionAbstain: - return "Abstain" - case OptionNo: - return "No" - case OptionNoWithVeto: - return "NoWithVeto" - default: - return "" - } -} - -// For Printf / Sprintf, returns bech32 when using %s -// nolint: errcheck -func (vo VoteOption) Format(s fmt.State, verb rune) { - switch verb { - case 's': - s.Write([]byte(fmt.Sprintf("%s", vo.String()))) - default: - s.Write([]byte(fmt.Sprintf("%v", byte(vo)))) - } -} - -//----------------------------------------------------------- -// ProposalKind - -// Type that represents Proposal Type as a byte -type ProposalKind byte - -//nolint -const ( - ProposalTypeNil ProposalKind = 0x00 - ProposalTypeText ProposalKind = 0x01 - ProposalTypeParameterChange ProposalKind = 0x02 - ProposalTypeSoftwareUpgrade ProposalKind = 0x03 - ProposalTypeListTradingPair ProposalKind = 0x04 - // ProposalTypeFeeChange belongs to ProposalTypeParameterChange. We use this to make it easily to distinguish。 - ProposalTypeFeeChange ProposalKind = 0x05 -) - -// String to proposalType byte. Returns ff if invalid. -func ProposalTypeFromString(str string) (ProposalKind, error) { - switch str { - case "Text": - return ProposalTypeText, nil - case "ParameterChange": - return ProposalTypeParameterChange, nil - case "SoftwareUpgrade": - return ProposalTypeSoftwareUpgrade, nil - case "ListTradingPair": - return ProposalTypeListTradingPair, nil - case "FeeChange": - return ProposalTypeFeeChange, nil - case "SCParamsChange": - return ProposalTypeSCParamsChange, nil - case "CSCParamsChange": - return ProposalTypeCSCParamsChange, nil - default: - return ProposalKind(0xff), errors.Errorf("'%s' is not a valid proposal type", str) - } -} - -// is defined ProposalType? -func validProposalType(pt ProposalKind) bool { - if pt == ProposalTypeText || - pt == ProposalTypeParameterChange || - pt == ProposalTypeSoftwareUpgrade || - pt == ProposalTypeListTradingPair || - pt == ProposalTypeFeeChange { - return true - } - return false -} - -// Marshal needed for protobuf compatibility -func (pt ProposalKind) Marshal() ([]byte, error) { - return []byte{byte(pt)}, nil -} - -// Unmarshal needed for protobuf compatibility -func (pt *ProposalKind) Unmarshal(data []byte) error { - *pt = ProposalKind(data[0]) - return nil -} - -// Marshals to JSON using string -func (pt ProposalKind) MarshalJSON() ([]byte, error) { - return json.Marshal(pt.String()) -} - -// Unmarshals from JSON assuming Bech32 encoding -func (pt *ProposalKind) UnmarshalJSON(data []byte) error { - var s string - err := json.Unmarshal(data, &s) - if err != nil { - return nil - } - - bz2, err := ProposalTypeFromString(s) - if err != nil { - return err - } - *pt = bz2 - return nil -} - -// Turns VoteOption byte to String -func (pt ProposalKind) String() string { - switch pt { - case ProposalTypeText: - return "Text" - case ProposalTypeParameterChange: - return "ParameterChange" - case ProposalTypeSoftwareUpgrade: - return "SoftwareUpgrade" - case ProposalTypeListTradingPair: - return "ListTradingPair" - case ProposalTypeFeeChange: - return "FeeChange" - case ProposalTypeSCParamsChange: - return "SCParamsChange" - case ProposalTypeCSCParamsChange: - return "CSCParamsChange" - default: - return "" - } -} - -// For Printf / Sprintf, returns bech32 when using %s -// nolint: errcheck -func (pt ProposalKind) Format(s fmt.State, verb rune) { - switch verb { - case 's': - s.Write([]byte(pt.String())) - default: - // TODO: Do this conversion more directly - s.Write([]byte(fmt.Sprintf("%v", byte(pt)))) - } -} - -//----------------------------------------------------------- -type ListTradingPairParams struct { - BaseAssetSymbol string `json:"base_asset_symbol"` // base asset symbol - QuoteAssetSymbol string `json:"quote_asset_symbol"` // quote asset symbol - InitPrice int64 `json:"init_price"` // init price - Description string `json:"description"` // description - ExpireTime time.Time `json:"expire_time"` // expire time -} - -//----------------------------------------------------------- -// SubmitProposalMsg -type SubmitProposalMsg struct { - Title string `json:"title"` // Title of the proposal - Description string `json:"description"` // Description of the proposal - ProposalType ProposalKind `json:"proposal_type"` // Type of proposal. Initial set {PlainTextProposal, SoftwareUpgradeProposal} - Proposer types.AccAddress `json:"proposer"` // Address of the proposer - InitialDeposit types.Coins `json:"initial_deposit"` // Initial deposit paid by sender. Must be strictly positive. - VotingPeriod time.Duration `json:"voting_period"` // Length of the voting period (s) -} - -func NewMsgSubmitProposal(title string, description string, proposalType ProposalKind, proposer types.AccAddress, initialDeposit types.Coins, votingPeriod time.Duration) SubmitProposalMsg { - return SubmitProposalMsg{ - Title: title, - Description: description, - ProposalType: proposalType, - Proposer: proposer, - InitialDeposit: initialDeposit, - VotingPeriod: votingPeriod, - } -} - -//nolint -func (msg SubmitProposalMsg) Route() string { return MsgRoute } -func (msg SubmitProposalMsg) Type() string { return "submit_proposal" } - -// Implements Msg. -func (msg SubmitProposalMsg) ValidateBasic() error { - if len(msg.Title) == 0 { - return fmt.Errorf("title can't be empty") - } - if len(msg.Title) > MaxTitleLength { - return fmt.Errorf("Proposal title is longer than max length of %d", MaxTitleLength) - } - if len(msg.Description) == 0 { - return fmt.Errorf("description can't be empty") - } - - if len(msg.Description) > MaxDescriptionLength { - return fmt.Errorf("Proposal description is longer than max length of %d", MaxDescriptionLength) - } - - if !validProposalType(msg.ProposalType) { - return fmt.Errorf("invalid proposal type %v ", msg.ProposalType) - } - if len(msg.Proposer) == 0 { - return fmt.Errorf("proposer can't be empty") - } - if !msg.InitialDeposit.IsValid() { - return fmt.Errorf("initial deposit %v is invalid. ", msg.InitialDeposit) - } - if !msg.InitialDeposit.IsNotNegative() { - return fmt.Errorf("initial deposit %v is negative. ", msg.InitialDeposit) - } - if msg.VotingPeriod <= 0 || msg.VotingPeriod > MaxVotingPeriod { - return fmt.Errorf("voting period should between 0 and %d weeks", MaxVotingPeriod/(7*24*60*60*time.Second)) - } - return nil -} - -func (msg SubmitProposalMsg) String() string { - return fmt.Sprintf("SubmitProposalMsg{%s, %s, %s, %v}", msg.Title, msg.Description, msg.ProposalType, msg.InitialDeposit) -} - -// Implements Msg. -func (msg SubmitProposalMsg) Get(key interface{}) (value interface{}) { - return nil -} - -// Implements Msg. -func (msg SubmitProposalMsg) GetSignBytes() []byte { - b, err := amino.NewCodec().MarshalJSON(msg) - if err != nil { - panic(err) - } - return MustSortJSON(b) -} - -// Implements Msg. -func (msg SubmitProposalMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.Proposer} -} - -func (msg SubmitProposalMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -//----------------------------------------------------------- -// DepositMsg -type DepositMsg struct { - ProposalID int64 `json:"proposal_id"` // ID of the proposal - Depositer types.AccAddress `json:"depositer"` // Address of the depositer - Amount types.Coins `json:"amount"` // Coins to add to the proposal's deposit -} - -func NewDepositMsg(depositer types.AccAddress, proposalID int64, amount types.Coins) DepositMsg { - return DepositMsg{ - ProposalID: proposalID, - Depositer: depositer, - Amount: amount, - } -} - -// Implements Msg. -// nolint -func (msg DepositMsg) Route() string { return MsgRoute } -func (msg DepositMsg) Type() string { return "deposit" } - -// Implements Msg. -func (msg DepositMsg) ValidateBasic() error { - if len(msg.Depositer) == 0 { - return fmt.Errorf("depositer can't be empty ") - } - if !msg.Amount.IsValid() { - return fmt.Errorf("amount is invalid ") - } - if !msg.Amount.IsNotNegative() { - return fmt.Errorf("amount can't be negative ") - } - if msg.ProposalID < 0 { - return fmt.Errorf("proposalId can't be negative ") - } - return nil -} - -func (msg DepositMsg) String() string { - return fmt.Sprintf("DepositMsg{%s=>%v: %v}", msg.Depositer, msg.ProposalID, msg.Amount) -} - -// Implements Msg. -func (msg DepositMsg) Get(key interface{}) (value interface{}) { - return nil -} - -// Implements Msg. -func (msg DepositMsg) GetSignBytes() []byte { - b, err := MsgCdc.MarshalJSON(msg) - if err != nil { - panic(err) - } - return MustSortJSON(b) -} - -// Implements Msg. -func (msg DepositMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.Depositer} -} - -func (msg DepositMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -//----------------------------------------------------------- -// VoteMsg -type VoteMsg struct { - ProposalID int64 `json:"proposal_id"` // ID of the proposal - Voter types.AccAddress `json:"voter"` // address of the voter - Option VoteOption `json:"option"` // option from OptionSet chosen by the voter -} - -func NewMsgVote(voter types.AccAddress, proposalID int64, option VoteOption) VoteMsg { - return VoteMsg{ - ProposalID: proposalID, - Voter: voter, - Option: option, - } -} - -// Implements Msg. -// nolint -func (msg VoteMsg) Route() string { return MsgRoute } -func (msg VoteMsg) Type() string { return "vote" } - -// Implements Msg. -func (msg VoteMsg) ValidateBasic() error { - if len(msg.Voter.Bytes()) == 0 { - return fmt.Errorf("vaoter can't be empty ") - } - if msg.ProposalID < 0 { - return fmt.Errorf("proposalId can't be less than 0") - } - if !validVoteOption(msg.Option) { - return fmt.Errorf("invalid msg option %v", msg.Option) - } - return nil -} - -func (msg VoteMsg) String() string { - return fmt.Sprintf("VoteMsg{%v - %s}", msg.ProposalID, msg.Option) -} - -// Implements Msg. -func (msg VoteMsg) Get(key interface{}) (value interface{}) { - return nil -} - -// Implements Msg. -func (msg VoteMsg) GetSignBytes() []byte { - b, err := amino.NewCodec().MarshalJSON(msg) - if err != nil { - panic(err) - } - return MustSortJSON(b) -} - -// Implements Msg. -func (msg VoteMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.Voter} -} - -func (msg VoteMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -func validVoteOption(option VoteOption) bool { - if option == OptionYes || - option == OptionAbstain || - option == OptionNo || - option == OptionNoWithVeto { - return true - } - return false -} diff --git a/types/msg/msg-issue.go b/types/msg/msg-issue.go deleted file mode 100644 index 5bc487e1..00000000 --- a/types/msg/msg-issue.go +++ /dev/null @@ -1,104 +0,0 @@ -package msg - -import ( - "encoding/json" - "errors" - "fmt" - "math" - "strings" - - "github.com/binance-chain/go-sdk/common/types" - - "github.com/binance-chain/go-sdk/common" -) - -const maxTokenNameLength = 32 - -// TokenIssueMsg def -type TokenIssueMsg struct { - From types.AccAddress `json:"from"` - Name string `json:"name"` - Symbol string `json:"symbol"` - TotalSupply int64 `json:"total_supply"` - Mintable bool `json:"mintable"` -} - -// NewTokenIssueMsg for instance creation -func NewTokenIssueMsg(from types.AccAddress, name, symbol string, supply int64, mintable bool) TokenIssueMsg { - return TokenIssueMsg{ - From: from, - Name: name, - Symbol: symbol, - TotalSupply: supply, - Mintable: mintable, - } -} - -// ValidateBasic does a simple validation check that -// doesn't require access to any other information. -func (msg TokenIssueMsg) ValidateBasic() error { - if msg.From == nil { - return fmt.Errorf("sender address cannot be empty") - } - - if err := validateIssueMsgTokenSymbol(msg.Symbol); err != nil { - return fmt.Errorf("Invalid symbol %v", msg.Symbol) - } - - if len(msg.Name) == 0 || len(msg.Name) > maxTokenNameLength { - return fmt.Errorf("Token name should have 1~%d characters", maxTokenNameLength) - } - - if msg.TotalSupply < 0 || msg.TotalSupply > MaxTotalSupply { - return fmt.Errorf("Total supply should be <= " + string(MaxTotalSupply/int64(math.Pow10(int(Decimals))))) - } - - return nil -} - -// Route part of Msg interface -func (msg TokenIssueMsg) Route() string { return "tokenIssue" } - -// Type part of Msg interface -func (msg TokenIssueMsg) Type() string { return "tokenIssue" } - -// String part of Msg interface -func (msg TokenIssueMsg) String() string { return fmt.Sprintf("IssueMsg{%#v}", msg) } - -// GetSigners part of Msg interface -func (msg TokenIssueMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} } - -// GetSignBytes part of Msg interface -func (msg TokenIssueMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -// GetInvolvedAddresses part of Msg interface -func (msg TokenIssueMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -func validateIssueMsgTokenSymbol(symbol string) error { - if len(symbol) == 0 { - return errors.New("token symbol cannot be empty") - } - - if strings.HasSuffix(symbol, DotBSuffix) { - symbol = strings.TrimSuffix(symbol, DotBSuffix) - } - - // check len without .B suffix - if symbolLen := len(symbol); symbolLen > TokenSymbolMaxLen || symbolLen < TokenSymbolMinLen { - return errors.New("length of token symbol is limited to 2~8") - } - - if !common.IsAlphaNum(symbol) { - return errors.New("token symbol should be alphanumeric") - } - - return nil -} diff --git a/types/msg/msg-issueMini.go b/types/msg/msg-issueMini.go deleted file mode 100644 index 235c7472..00000000 --- a/types/msg/msg-issueMini.go +++ /dev/null @@ -1,113 +0,0 @@ -package msg - -import ( - "encoding/json" - "errors" - "fmt" - "github.com/binance-chain/go-sdk/common/types" - - "github.com/binance-chain/go-sdk/common" -) - -const ( - MiniRoute = "miniTokensIssue" - IssueMiniMsgType = "miniIssueMsg" -) - -// MiniTokenIssueMsg def -type MiniTokenIssueMsg struct { - From types.AccAddress `json:"from"` - Name string `json:"name"` - Symbol string `json:"symbol"` - TotalSupply int64 `json:"total_supply"` - Mintable bool `json:"mintable"` - TokenURI string `json:"token_uri"` -} - -// NewMiniTokenIssueMsg for instance creation -func NewMiniTokenIssueMsg(from types.AccAddress, name, symbol string, supply int64, mintable bool, tokenURI string) MiniTokenIssueMsg { - return MiniTokenIssueMsg{ - From: from, - Name: name, - Symbol: symbol, - TotalSupply: supply, - Mintable: mintable, - TokenURI: tokenURI, - } -} - -// ValidateBasic does a simple validation check that -// doesn't require access to any other information. -func (msg MiniTokenIssueMsg) ValidateBasic() error { - - if msg.From == nil { - return errors.New("sender address cannot be empty") - } - - if err := validateIssueMsgMiniTokenSymbol(msg.Symbol); err != nil { - return fmt.Errorf("Invalid symbol %v", msg.Symbol) - } - - if len(msg.Name) == 0 || len(msg.Name) > MaxMiniTokenNameLength { - return fmt.Errorf("token name should have 1 ~ %v characters", MaxMiniTokenNameLength) - } - - if len(msg.TokenURI) > MaxTokenURILength { - return fmt.Errorf("token seturi should not exceed %v characters", MaxTokenURILength) - } - - //if msg.MaxTotalSupply < MiniTokenMinTotalSupply || msg.MaxTotalSupply > MiniTokenMaxTotalSupplyUpperBound { - // return fmt.Errorf("max total supply should be between %d ~ %d", MiniTokenMinTotalSupply, MiniTokenMaxTotalSupplyUpperBound) - //} - // - //if msg.TotalSupply < MiniTokenMinTotalSupply || msg.TotalSupply > msg.MaxTotalSupply { - // return fmt.Errorf("total supply should be between %d ~ %d", MiniTokenMinTotalSupply, msg.MaxTotalSupply) - //} - - return nil -} - -// Route part of Msg interface -func (msg MiniTokenIssueMsg) Route() string { return MiniRoute } - -// Type part of Msg interface -func (msg MiniTokenIssueMsg) Type() string { - return IssueMiniMsgType -} - -// String part of Msg interface -func (msg MiniTokenIssueMsg) String() string { return fmt.Sprintf("IssueMiniMsg{%#v}", msg) } - -// GetSigners part of Msg interface -func (msg MiniTokenIssueMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} } - -// GetSignBytes part of Msg interface -func (msg MiniTokenIssueMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -// GetInvolvedAddresses part of Msg interface -func (msg MiniTokenIssueMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -func validateIssueMsgMiniTokenSymbol(symbol string) error { - if len(symbol) == 0 { - return errors.New("token symbol cannot be empty") - } - - // check len without suffix - if symbolLen := len(symbol); symbolLen > MiniTokenSymbolMaxLen || symbolLen < MiniTokenSymbolMinLen { - return errors.New("length of token symbol is limited to 2~8") - } - - if !common.IsAlphaNum(symbol) { - return errors.New("token symbol should be alphanumeric") - } - - return nil -} diff --git a/types/msg/msg-issueTiny.go b/types/msg/msg-issueTiny.go deleted file mode 100644 index c5db7ee0..00000000 --- a/types/msg/msg-issueTiny.go +++ /dev/null @@ -1,93 +0,0 @@ -package msg - -import ( - "encoding/json" - "errors" - "fmt" - "github.com/binance-chain/go-sdk/common/types" -) - -const ( - IssueTinyMsgType = "tinyIssueMsg" -) - -// TinyTokenIssueMsg def -type TinyTokenIssueMsg struct { - From types.AccAddress `json:"from"` - Name string `json:"name"` - Symbol string `json:"symbol"` - TotalSupply int64 `json:"total_supply"` - Mintable bool `json:"mintable"` - TokenURI string `json:"token_uri"` -} - -// NewTinyTokenIssueMsg for instance creation -func NewTinyTokenIssueMsg(from types.AccAddress, name, symbol string, supply int64, mintable bool, tokenURI string) TinyTokenIssueMsg { - return TinyTokenIssueMsg{ - From: from, - Name: name, - Symbol: symbol, - TotalSupply: supply, - Mintable: mintable, - TokenURI: tokenURI, - } -} - -// ValidateBasic does a simple validation check that -// doesn't require access to any other information. -func (msg TinyTokenIssueMsg) ValidateBasic() error { - - if msg.From == nil { - return errors.New("sender address cannot be empty") - } - - if err := validateIssueMsgMiniTokenSymbol(msg.Symbol); err != nil { - return fmt.Errorf("Invalid symbol %v", msg.Symbol) - } - - if len(msg.Name) == 0 || len(msg.Name) > MaxMiniTokenNameLength { - return fmt.Errorf("token name should have 1 ~ %v characters", MaxMiniTokenNameLength) - } - - if len(msg.TokenURI) > MaxTokenURILength { - return fmt.Errorf("token seturi should not exceed %v characters", MaxTokenURILength) - } - - //if msg.MaxTotalSupply < MiniTokenMinTotalSupply || msg.MaxTotalSupply > MiniTokenMaxTotalSupplyUpperBound { - // return fmt.Errorf("max total supply should be between %d ~ %d", MiniTokenMinTotalSupply, MiniTokenMaxTotalSupplyUpperBound) - //} - // - //if msg.TotalSupply < MiniTokenMinTotalSupply || msg.TotalSupply > msg.MaxTotalSupply { - // return fmt.Errorf("total supply should be between %d ~ %d", MiniTokenMinTotalSupply, msg.MaxTotalSupply) - //} - - return nil -} - -// Route part of Msg interface -func (msg TinyTokenIssueMsg) Route() string { return MiniRoute } - -// Type part of Msg interface -func (msg TinyTokenIssueMsg) Type() string { - return IssueTinyMsgType -} - -// String part of Msg interface -func (msg TinyTokenIssueMsg) String() string { return fmt.Sprintf("IssueTinyMsg{%#v}", msg) } - -// GetSigners part of Msg interface -func (msg TinyTokenIssueMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} } - -// GetSignBytes part of Msg interface -func (msg TinyTokenIssueMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -// GetInvolvedAddresses part of Msg interface -func (msg TinyTokenIssueMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} diff --git a/types/msg/msg-mint.go b/types/msg/msg-mint.go deleted file mode 100644 index a3f54367..00000000 --- a/types/msg/msg-mint.go +++ /dev/null @@ -1,49 +0,0 @@ -package msg - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common/types" -) - -type MintMsg struct { - From types.AccAddress `json:"from"` - Symbol string `json:"symbol"` - Amount int64 `json:"amount"` -} - -func NewMintMsg(from types.AccAddress, symbol string, amount int64) MintMsg { - return MintMsg{ - From: from, - Symbol: symbol, - Amount: amount, - } -} - -func (msg MintMsg) ValidateBasic() error { - if msg.From == nil { - return fmt.Errorf("sender address cannot be empty") - } - if msg.Amount <= 0 { - return fmt.Errorf("Amount cant be less than 0 ") - } - - return nil -} - -// Implements MintMsg. -func (msg MintMsg) Route() string { return "tokensIssue" } -func (msg MintMsg) Type() string { return "mintMsg" } -func (msg MintMsg) String() string { return fmt.Sprintf("MintMsg{%#v}", msg) } -func (msg MintMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} } -func (msg MintMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) // XXX: ensure some canonical form - if err != nil { - panic(err) - } - return b -} -func (msg MintMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} diff --git a/types/msg/msg-oracle.go b/types/msg/msg-oracle.go deleted file mode 100644 index 34a8be11..00000000 --- a/types/msg/msg-oracle.go +++ /dev/null @@ -1,343 +0,0 @@ -package msg - -import ( - "encoding/json" - "fmt" - "math/big" - - "github.com/binance-chain/go-sdk/common/rlp" - sdk "github.com/binance-chain/go-sdk/common/types" -) - -const ( - RouteOracle = "oracle" - - ClaimMsgType = "oracleClaim" - - OracleChannelId sdk.IbcChannelID = 0x00 -) - -const ( - CrossChainFeeLength = 32 - PackageTypeLength = 1 - PackageHeaderLength = CrossChainFeeLength + PackageTypeLength -) - -func GetClaimId(chainId sdk.IbcChainID, channelId sdk.IbcChannelID, sequence int64) string { - return fmt.Sprintf("%d:%d:%d", chainId, channelId, sequence) -} - -// Claim contains an arbitrary claim with arbitrary content made by a given validator -type Claim struct { - ID string `json:"id"` - ValidatorAddress sdk.ValAddress `json:"validator_address"` - Content string `json:"content"` -} - -// NewClaim returns a new Claim -func NewClaim(id string, validatorAddress sdk.ValAddress, content string) Claim { - return Claim{ - ID: id, - ValidatorAddress: validatorAddress, - Content: content, - } -} - -type ClaimMsg struct { - ChainId sdk.IbcChainID `json:"chain_id"` - Sequence uint64 `json:"sequence"` - Payload []byte `json:"payload"` - ValidatorAddress sdk.AccAddress `json:"validator_address"` -} - -type Packages []Package - -type Package struct { - ChannelId sdk.IbcChannelID - Sequence uint64 - Payload []byte -} - -func NewClaimMsg(ChainId sdk.IbcChainID, sequence uint64, payload []byte, validatorAddr sdk.AccAddress) ClaimMsg { - return ClaimMsg{ - ChainId: ChainId, - Sequence: sequence, - Payload: payload, - ValidatorAddress: validatorAddr, - } -} - -// nolint -func (msg ClaimMsg) Route() string { return RouteOracle } -func (msg ClaimMsg) Type() string { return ClaimMsgType } -func (msg ClaimMsg) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.ValidatorAddress} -} - -func (msg ClaimMsg) String() string { - return fmt.Sprintf("Claim{%v#%v#%v%v%x}", - msg.ChainId, msg.Sequence, msg.ValidatorAddress.String(), msg.Payload) -} - -// GetSignBytes - Get the bytes for the message signer to sign on -func (msg ClaimMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -func (msg ClaimMsg) GetInvolvedAddresses() []sdk.AccAddress { - return msg.GetSigners() -} - -// ValidateBasic is used to quickly disqualify obviously invalid messages quickly -func (msg ClaimMsg) ValidateBasic() error { - if len(msg.Payload) < PackageHeaderLength { - return fmt.Errorf("length of payload is less than %d", PackageHeaderLength) - } - if len(msg.ValidatorAddress) != sdk.AddrLen { - return fmt.Errorf("address length should be %d", sdk.AddrLen) - } - return nil -} - -type CrossChainPackageType uint8 - -const ( - SynCrossChainPackageType CrossChainPackageType = 0x00 - AckCrossChainPackageType CrossChainPackageType = 0x01 - FailAckCrossChainPackageType CrossChainPackageType = 0x02 -) - -func noneExistPackageProto() interface{} { - panic("should not exist such package") -} - -// package type -var protoMetrics = map[sdk.IbcChannelID]map[CrossChainPackageType]func() interface{}{ - sdk.IbcChannelID(1): { - SynCrossChainPackageType: func() interface{} { - return new(ApproveBindSynPackage) - }, - AckCrossChainPackageType: noneExistPackageProto, - FailAckCrossChainPackageType: func() interface{} { - return new(BindSynPackage) - }, - }, - sdk.IbcChannelID(2): { - SynCrossChainPackageType: noneExistPackageProto, - AckCrossChainPackageType: func() interface{} { - return new(TransferOutRefundPackage) - }, - FailAckCrossChainPackageType: func() interface{} { - return new(TransferOutSynPackage) - }, - }, - sdk.IbcChannelID(3): { - SynCrossChainPackageType: func() interface{} { - return new(TransferInSynPackage) - }, - AckCrossChainPackageType: noneExistPackageProto, - FailAckCrossChainPackageType: noneExistPackageProto, - }, - sdk.IbcChannelID(4): { - SynCrossChainPackageType: func() interface{} { - return new(MirrorSynPackage) - }, - AckCrossChainPackageType: noneExistPackageProto, - FailAckCrossChainPackageType: noneExistPackageProto, - }, - sdk.IbcChannelID(5): { - SynCrossChainPackageType: func() interface{} { - return new(MirrorSyncSynPackage) - }, - AckCrossChainPackageType: noneExistPackageProto, - FailAckCrossChainPackageType: noneExistPackageProto, - }, - sdk.IbcChannelID(8): { - SynCrossChainPackageType: noneExistPackageProto, - AckCrossChainPackageType: func() interface{} { - return new(CommonAckPackage) - }, - FailAckCrossChainPackageType: func() interface{} { - return new(IbcValidatorSetPackage) - }, - }, - sdk.IbcChannelID(9): { - SynCrossChainPackageType: noneExistPackageProto, - AckCrossChainPackageType: func() interface{} { - return new(CommonAckPackage) - }, - FailAckCrossChainPackageType: func() interface{} { - return new(CrossParamChange) - }, - }, - sdk.IbcChannelID(11): { - SynCrossChainPackageType: func() interface{} { - return new(SideDowntimeSlashPackage) - }, - AckCrossChainPackageType: noneExistPackageProto, - FailAckCrossChainPackageType: noneExistPackageProto, - }, - sdk.IbcChannelID(16): { - SynCrossChainPackageType: func() interface{} { - return new(CrossStakeSynPackageFromBSC) - }, - AckCrossChainPackageType: func() interface{} { - return new(CrossStakeRefundPackage) - }, - FailAckCrossChainPackageType: noneExistPackageProto, - }, -} - -type ApproveBindSynPackage struct { - Status uint32 - Bep2TokenSymbol [32]byte -} - -type BindSynPackage struct { - PackageType uint8 - Bep2TokenSymbol [32]byte - ContractAddr SmartChainAddress - TotalSupply *big.Int - PeggyAmount *big.Int - Decimals uint8 - ExpireTime uint64 -} - -type TransferOutRefundPackage struct { - Bep2TokenSymbol [32]byte - RefundAmount *big.Int - RefundAddr sdk.AccAddress - RefundReason uint32 -} - -type TransferOutSynPackage struct { - Bep2TokenSymbol [32]byte - ContractAddress SmartChainAddress - Amount *big.Int - Recipient SmartChainAddress - RefundAddress sdk.AccAddress - ExpireTime uint64 -} - -type TransferInSynPackage struct { - Bep2TokenSymbol [32]byte - ContractAddress SmartChainAddress - Amounts []*big.Int - ReceiverAddresses []sdk.AccAddress - RefundAddresses []SmartChainAddress - ExpireTime uint64 -} - -type MirrorSynPackage struct { - MirrorSender SmartChainAddress - ContractAddr SmartChainAddress - BEP20Name [32]byte - BEP20Symbol [32]byte - BEP20TotalSupply *big.Int - BEP20Decimals uint8 - MirrorFee *big.Int - ExpireTime uint64 -} - -type MirrorSyncSynPackage struct { - SyncSender SmartChainAddress - ContractAddr SmartChainAddress - BEP2Symbol [32]byte - BEP20TotalSupply *big.Int - SyncFee *big.Int - ExpireTime uint64 -} - -type CommonAckPackage struct { - Code uint32 -} - -type IbcValidatorSetPackage struct { - Type uint8 - ValidatorSet []IbcValidator -} - -type IbcValidator struct { - ConsAddr []byte - FeeAddr []byte - DistAddr []byte - Power uint64 -} - -type CrossParamChange struct { - Key string - Value []byte - Target []byte -} - -type SideDowntimeSlashPackage struct { - SideConsAddr []byte `json:"side_cons_addr"` - SideHeight uint64 `json:"side_height"` - SideChainId uint16 `json:"side_chain_id"` - SideTimestamp uint64 `json:"side_timestamp"` -} - -type CrossStakeSynPackageFromBSC struct { - EventType uint8 - ParamsBytes []byte -} - -type CrossStakeRefundPackage struct { - EventType uint8 - Recipient SmartChainAddress - Amount *big.Int - ErrorCode uint32 -} - -type CrossChainPackage struct { - PackageType CrossChainPackageType - RelayFee big.Int - Content interface{} -} - -func ParseClaimPayload(payload []byte) ([]CrossChainPackage, error) { - packages := Packages{} - err := rlp.DecodeBytes(payload, &packages) - if err != nil { - return nil, err - } - decodedPackage := make([]CrossChainPackage, 0, len(packages)) - for _, pack := range packages { - ptype, relayerFee, err := DecodePackageHeader(pack.Payload) - if err != nil { - return nil, err - } - if _, exist := protoMetrics[pack.ChannelId]; !exist { - return nil, fmt.Errorf("channnel id do not exist") - } - proto, exist := protoMetrics[pack.ChannelId][ptype] - if !exist || proto == nil { - return nil, fmt.Errorf("package type do not exist") - } - content := proto() - err = rlp.DecodeBytes(pack.Payload[PackageHeaderLength:], content) - if err != nil { - return nil, err - } - decodedPackage = append(decodedPackage, CrossChainPackage{ - PackageType: ptype, - RelayFee: relayerFee, - Content: content, - }) - } - return decodedPackage, nil -} - -func DecodePackageHeader(packageHeader []byte) (packageType CrossChainPackageType, relayFee big.Int, err error) { - if len(packageHeader) < PackageHeaderLength { - err = fmt.Errorf("length of packageHeader is less than %d", PackageHeaderLength) - return - } - packageType = CrossChainPackageType(packageHeader[0]) - relayFee.SetBytes(packageHeader[PackageTypeLength : CrossChainFeeLength+PackageTypeLength]) - return -} diff --git a/types/msg/msg-order.go b/types/msg/msg-order.go deleted file mode 100644 index 0a01d7c5..00000000 --- a/types/msg/msg-order.go +++ /dev/null @@ -1,292 +0,0 @@ -package msg - -import ( - "encoding/json" - "errors" - "fmt" - "strings" - - "github.com/binance-chain/go-sdk/common/types" -) - -// Order routes -const ( - RouteNewOrder = "orderNew" - RouteCancelOrder = "orderCancel" -) - -// OrderSide /TimeInForce /OrderType are const, following FIX protocol convention -// Used as Enum -var OrderSide = struct { - BUY int8 - SELL int8 -}{1, 2} - -var sideNames = map[string]int8{ - "BUY": 1, - "SELL": 2, -} - -// IToSide conversion -func IToSide(side int8) string { - switch side { - case OrderSide.BUY: - return "BUY" - case OrderSide.SELL: - return "SELL" - default: - return "UNKNOWN" - } -} - -// GenerateOrderID generates an order ID -func GenerateOrderID(sequence int64, from types.AccAddress) string { - id := fmt.Sprintf("%X-%d", from.Bytes(), sequence) - return id -} - -// IsValidSide validates that a side is valid and supported by the matching engine -func IsValidSide(side int8) bool { - switch side { - case OrderSide.BUY, OrderSide.SELL: - return true - default: - return false - } -} - -// SideStringToSideCode converts a string like "BUY" to its internal side code -func SideStringToSideCode(side string) (int8, error) { - upperSide := strings.ToUpper(side) - if val, ok := sideNames[upperSide]; ok { - return val, nil - } - return -1, errors.New("side `" + upperSide + "` not found or supported") -} - -const ( - _ int8 = iota - orderMarket int8 = iota - orderLimit int8 = iota -) - -// OrderType is an enum of order type options supported by the matching engine -var OrderType = struct { - LIMIT int8 - MARKET int8 -}{orderLimit, orderMarket} - -// IToOrderType conversion -func IToOrderType(tpe int8) string { - switch tpe { - case OrderType.LIMIT: - return "LIMIT" - case OrderType.MARKET: - return "MARKET" - default: - return "UNKNOWN" - } -} - -// IsValidOrderType validates that an order type is valid and supported by the matching engine -func IsValidOrderType(ot int8) bool { - switch ot { - case OrderType.LIMIT: // only allow LIMIT for now. - return true - default: - return false - } -} - -const ( - _ int8 = iota - tifGTC int8 = iota - _ int8 = iota - tifIOC int8 = iota -) - -// TimeInForce is an enum of TIF (Time in Force) options supported by the matching engine -var TimeInForce = struct { - GTC int8 - IOC int8 -}{tifGTC, tifIOC} - -var timeInForceNames = map[string]int8{ - "GTC": tifGTC, - "IOC": tifIOC, -} - -// IsValidTimeInForce validates that a tif code is correct -func IsValidTimeInForce(tif int8) bool { - switch tif { - case TimeInForce.GTC, TimeInForce.IOC: - return true - default: - return false - } -} - -// IToTimeInForce conversion -func IToTimeInForce(tif int8) string { - switch tif { - case TimeInForce.GTC: - return "GTC" - case TimeInForce.IOC: - return "IOC" - default: - return "UNKNOWN" - } -} - -// TifStringToTifCode converts a string like "GTC" to its internal tif code -func TifStringToTifCode(tif string) (int8, error) { - upperTif := strings.ToUpper(tif) - if val, ok := timeInForceNames[upperTif]; ok { - return val, nil - } - return -1, errors.New("tif `" + upperTif + "` not found or supported") -} - -// CreateOrderMsg def -type CreateOrderMsg struct { - Sender types.AccAddress `json:"sender"` - ID string `json:"id"` - Symbol string `json:"symbol"` - OrderType int8 `json:"ordertype"` - Side int8 `json:"side"` - Price int64 `json:"price"` - Quantity int64 `json:"quantity"` - TimeInForce int8 `json:"timeinforce"` -} - -// NewCreateOrderMsg constructs a new CreateOrderMsg -func NewCreateOrderMsg(sender types.AccAddress, id string, side int8, symbol string, price int64, qty int64) CreateOrderMsg { - return CreateOrderMsg{ - Sender: sender, - ID: id, - Symbol: symbol, - OrderType: OrderType.LIMIT, // default - Side: side, - Price: price, - Quantity: qty, - TimeInForce: TimeInForce.GTC, // default - } -} - -// Route is part of Msg interface -func (msg CreateOrderMsg) Route() string { return RouteNewOrder } - -// Type is part of Msg interface -func (msg CreateOrderMsg) Type() string { return RouteNewOrder } - -// GetSigners is part of Msg interface -func (msg CreateOrderMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.Sender} } - -// String is part of Msg interface -func (msg CreateOrderMsg) String() string { - return fmt.Sprintf("CreateOrderMsg{Sender: %v, Id: %v, Symbol: %v, OrderSide: %v, Price: %v, Qty: %v}", msg.Sender, msg.ID, msg.Symbol, msg.Side, msg.Price, msg.Quantity) -} - -// GetSignBytes - Get the bytes for the message signer to sign on -func (msg CreateOrderMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -// GetInvolvedAddresses as part of the Msg interface -func (msg CreateOrderMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -// ValidateBasic is used to quickly disqualify obviously invalid messages quickly -func (msg CreateOrderMsg) ValidateBasic() error { - if len(msg.Sender) == 0 { - return fmt.Errorf("ErrUnknownAddress %s", msg.Sender.String()) - } - - // `-` is required in the compound order id:
- - if len(msg.ID) == 0 || !strings.Contains(msg.ID, "-") { - return fmt.Errorf("Invalid order ID:%s", msg.ID) - } - - if msg.Quantity <= 0 { - return fmt.Errorf("Invalid order Quantity, Zero/Negative Number:%d", msg.Quantity) - } - - if msg.Price <= 0 { - return fmt.Errorf("Invalid order Price, Zero/Negative Number:%d", msg.Price) - } - - if !IsValidOrderType(msg.OrderType) { - return fmt.Errorf("Invalid order type:%d", msg.OrderType) - } - - if !IsValidSide(msg.Side) { - return fmt.Errorf("Invalid side:%d", msg.Side) - } - - if !IsValidTimeInForce(msg.TimeInForce) { - return fmt.Errorf("Invalid TimeInForce:%d", msg.TimeInForce) - } - - return nil -} - -// CancelOrderMsg represents a message to cancel an open order -type CancelOrderMsg struct { - Sender types.AccAddress `json:"sender"` - Symbol string `json:"symbol"` - RefID string `json:"refid"` -} - -// NewCancelOrderMsg constructs a new CancelOrderMsg -func NewCancelOrderMsg(sender types.AccAddress, symbol, refID string) CancelOrderMsg { - return CancelOrderMsg{ - Sender: sender, - Symbol: symbol, - RefID: refID, - } -} - -// Route is part of Msg interface -func (msg CancelOrderMsg) Route() string { return RouteCancelOrder } - -// Type is part of Msg interface -func (msg CancelOrderMsg) Type() string { return RouteCancelOrder } - -// GetSigners is part of Msg interface -func (msg CancelOrderMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.Sender} } - -// String is part of Msg interface -func (msg CancelOrderMsg) String() string { - return fmt.Sprintf("CancelOrderMsg{Sender: %v}", msg.Sender) -} - -// GetSignBytes - Get the bytes for the message signer to sign on -func (msg CancelOrderMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -// GetInvolvedAddresses as part of Msg interface -func (msg CancelOrderMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -// ValidateBasic is used to quickly disqualify obviously invalid messages quickly -func (msg CancelOrderMsg) ValidateBasic() error { - if len(msg.Sender) == 0 { - return fmt.Errorf("ErrUnknownAddress %s", msg.Sender.String()) - } - if len(msg.RefID) == 0 || !strings.Contains(msg.RefID, "-") { - return fmt.Errorf("Invalid order RefID:%s", msg.RefID) - } - - return nil -} diff --git a/types/msg/msg-send.go b/types/msg/msg-send.go deleted file mode 100644 index fb864e9a..00000000 --- a/types/msg/msg-send.go +++ /dev/null @@ -1,181 +0,0 @@ -package msg - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common/types" -) - -// SendMsg - high level transaction of the coin module -type SendMsg struct { - Inputs []Input `json:"inputs"` - Outputs []Output `json:"outputs"` -} - -// NewMsgSend - construct arbitrary multi-in, multi-out send msg. -func NewMsgSend(in []Input, out []Output) SendMsg { - return SendMsg{Inputs: in, Outputs: out} -} - -func (msg SendMsg) Route() string { return "bank" } // TODO: "bank/send" -func (msg SendMsg) Type() string { return "send" } - -// Implements Msg. -func (msg SendMsg) ValidateBasic() error { - if len(msg.Inputs) == 0 { - return fmt.Errorf("Len of inputs is less than 1 ") - } - if len(msg.Outputs) == 0 { - return fmt.Errorf("Len of outputs is less than 1 ") - } - // make sure all inputs and outputs are individually valid - var totalIn, totalOut types.Coins - for _, in := range msg.Inputs { - if err := in.ValidateBasic(); err != nil { - return err - } - totalIn = totalIn.Plus(in.Coins) - } - for _, out := range msg.Outputs { - if err := out.ValidateBasic(); err != nil { - return err - } - totalOut = totalOut.Plus(out.Coins) - } - // make sure inputs and outputs match - if !totalIn.IsEqual(totalOut) { - return fmt.Errorf("inputs %v and outputs %v don't match", totalIn, totalOut) - } - return nil -} - -// Implements Msg. -func (msg SendMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -// Implements Msg. -func (msg SendMsg) GetSigners() []types.AccAddress { - addrs := make([]types.AccAddress, len(msg.Inputs)) - for i, in := range msg.Inputs { - addrs[i] = in.Address - } - return addrs -} - -func (msg SendMsg) GetInvolvedAddresses() []types.AccAddress { - numOfInputs := len(msg.Inputs) - numOfOutputs := len(msg.Outputs) - addrs := make([]types.AccAddress, numOfInputs+numOfOutputs, numOfInputs+numOfOutputs) - for i, in := range msg.Inputs { - addrs[i] = in.Address - } - for i, out := range msg.Outputs { - addrs[i+numOfInputs] = out.Address - } - return addrs -} - -//---------------------------------------- -// Input - -// Transaction Input -type Input struct { - Address types.AccAddress `json:"address"` - Coins types.Coins `json:"coins"` -} - -// Return bytes to sign for Input -func (in Input) GetSignBytes() []byte { - bin, err := MsgCdc.MarshalJSON(in) - if err != nil { - panic(err) - } - return MustSortJSON(bin) -} - -// ValidateBasic - validate transaction input -func (in Input) ValidateBasic() error { - if len(in.Address) == 0 { - return fmt.Errorf("Len of input address is less than 1 ") - } - if !in.Coins.IsValid() { - return fmt.Errorf("Inputs coins %v is invalid ", in.Coins) - } - if !in.Coins.IsPositive() { - return fmt.Errorf("Inputs coins %v is negative ", in.Coins) - } - return nil -} - -// NewInput - create a transaction input, used with SendMsg -func NewInput(addr types.AccAddress, coins types.Coins) Input { - input := Input{ - Address: addr, - Coins: coins, - } - return input -} - -//---------------------------------------- -// Output - -// Transaction Output -type Output struct { - Address types.AccAddress `json:"address"` - Coins types.Coins `json:"coins"` -} - -// Return bytes to sign for Output -func (out Output) GetSignBytes() []byte { - bin, err := MsgCdc.MarshalJSON(out) - if err != nil { - panic(err) - } - return MustSortJSON(bin) -} - -// ValidateBasic - validate transaction output -func (out Output) ValidateBasic() error { - if len(out.Address) == 0 { - return fmt.Errorf("Len output %d should is less than 1 ", 0) - } - if !out.Coins.IsValid() { - return fmt.Errorf("Coins is invalid ") - } - if !out.Coins.IsPositive() { - return fmt.Errorf(" Coins is negative ") - } - return nil -} - -// NewOutput - create a transaction output, used with SendMsg -func NewOutput(addr types.AccAddress, coins types.Coins) Output { - output := Output{ - Address: addr, - Coins: coins, - } - return output -} - -type Transfer struct { - ToAddr types.AccAddress - Coins types.Coins -} - -func CreateSendMsg(from types.AccAddress, fromCoins types.Coins, transfers []Transfer) SendMsg { - input := NewInput(from, fromCoins) - - output := make([]Output, 0, len(transfers)) - for _, t := range transfers { - t.Coins = t.Coins.Sort() - output = append(output, NewOutput(t.ToAddr, t.Coins)) - } - msg := NewMsgSend([]Input{input}, output) - return msg -} diff --git a/types/msg/msg-setUri.go b/types/msg/msg-setUri.go deleted file mode 100644 index b2558e11..00000000 --- a/types/msg/msg-setUri.go +++ /dev/null @@ -1,68 +0,0 @@ -package msg - -import ( - "encoding/json" - "fmt" - "github.com/binance-chain/go-sdk/common/types" -) - -// SetURIMsg def -type SetURIMsg struct { - From types.AccAddress `json:"from"` - Symbol string `json:"symbol"` - TokenURI string `json:"token_uri"` -} - -// NewSetUriMsg for instance creation -func NewSetUriMsg(from types.AccAddress, symbol string, tokenURI string) SetURIMsg { - return SetURIMsg{ - From: from, - Symbol: symbol, - TokenURI: tokenURI, - } -} - -// ValidateBasic does a simple validation check that -// doesn't require access to any other information. -func (msg SetURIMsg) ValidateBasic() error { - if msg.From == nil { - return fmt.Errorf("sender address cannot be empty") - } - - if len(msg.TokenURI) > MaxTokenURILength { - return fmt.Errorf("token seturi should not exceed %v characters", MaxTokenURILength) - } - - err := ValidateMiniTokenSymbol(msg.Symbol) - if err != nil { - return fmt.Errorf("Invalid symbol %v", msg.Symbol) - } - - return nil -} - -// Route part of Msg interface -func (msg SetURIMsg) Route() string { return "miniTokensSetURI" } - -// Type part of Msg interface -func (msg SetURIMsg) Type() string { return "miniTokensSetURI" } - -// String part of Msg interface -func (msg SetURIMsg) String() string { return fmt.Sprintf("MsgSetURI{%#v}", msg) } - -// GetSigners part of Msg interface -func (msg SetURIMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} } - -// GetSignBytes part of Msg interface -func (msg SetURIMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -// GetInvolvedAddresses part of Msg interface -func (msg SetURIMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} diff --git a/types/msg/msg-setaccount.go b/types/msg/msg-setaccount.go deleted file mode 100644 index ea040bf9..00000000 --- a/types/msg/msg-setaccount.go +++ /dev/null @@ -1,48 +0,0 @@ -package msg - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common/types" -) - -const ( - AccountFlagsRoute = "accountFlags" - SetAccountFlagsMsgType = "setAccountFlags" -) - -type SetAccountFlagsMsg struct { - From types.AccAddress `json:"from"` - Flags uint64 `json:"flags"` -} - -func NewSetAccountFlagsMsg(from types.AccAddress, flags uint64) SetAccountFlagsMsg { - return SetAccountFlagsMsg{ - From: from, - Flags: flags, - } -} - -func (msg SetAccountFlagsMsg) Route() string { return AccountFlagsRoute } -func (msg SetAccountFlagsMsg) Type() string { return SetAccountFlagsMsgType } -func (msg SetAccountFlagsMsg) String() string { - return fmt.Sprintf("setAccountFlags{%v#%v}", msg.From, msg.Flags) -} -func (msg SetAccountFlagsMsg) GetInvolvedAddresses() []types.AccAddress { return msg.GetSigners() } -func (msg SetAccountFlagsMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} } - -func (msg SetAccountFlagsMsg) ValidateBasic() error { - if len(msg.From) != types.AddrLen { - return fmt.Errorf("Expected address length is %d, actual length is %d", types.AddrLen, len(msg.From)) - } - return nil -} - -func (msg SetAccountFlagsMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} diff --git a/types/msg/msg-side-gov.go b/types/msg/msg-side-gov.go deleted file mode 100644 index 55b041bf..00000000 --- a/types/msg/msg-side-gov.go +++ /dev/null @@ -1,442 +0,0 @@ -package msg - -import ( - "encoding/hex" - "fmt" - "math" - "time" - - "github.com/tendermint/go-amino" - - "github.com/binance-chain/go-sdk/common/types" -) - -const ( - MsgTypeSideSubmitProposal = "side_submit_proposal" - MsgTypeSideDeposit = "side_deposit" - MsgTypeSideVote = "side_vote" - - // side chain params change - ProposalTypeSCParamsChange ProposalKind = 0x81 - // cross side chain param change - ProposalTypeCSCParamsChange ProposalKind = 0x82 - - MaxSideChainIdLength = 20 -) - -//----------------------------------------------------------- -// SideChainSubmitProposalMsg -type SideChainSubmitProposalMsg struct { - Title string `json:"title"` // Title of the proposal - Description string `json:"description"` // Description of the proposal - ProposalType ProposalKind `json:"proposal_type"` // Type of proposal. Initial set {PlainTextProposal, SoftwareUpgradeProposal} - Proposer types.AccAddress `json:"proposer"` // Address of the proposer - InitialDeposit types.Coins `json:"initial_deposit"` // Initial deposit paid by sender. Must be strictly positive. - VotingPeriod time.Duration `json:"voting_period"` // Length of the voting period (s) - SideChainId string `json:"side_chain_id"` -} - -func NewSideChainSubmitProposalMsg(title string, description string, proposalType ProposalKind, proposer types.AccAddress, initialDeposit types.Coins, votingPeriod time.Duration, sideChainId string) SideChainSubmitProposalMsg { - return SideChainSubmitProposalMsg{ - Title: title, - Description: description, - ProposalType: proposalType, - Proposer: proposer, - InitialDeposit: initialDeposit, - VotingPeriod: votingPeriod, - SideChainId: sideChainId, - } -} - -//nolint -func (msg SideChainSubmitProposalMsg) Route() string { return MsgRoute } -func (msg SideChainSubmitProposalMsg) Type() string { return MsgTypeSideSubmitProposal } - -// Implements Msg. -func (msg SideChainSubmitProposalMsg) ValidateBasic() error { - if len(msg.Title) == 0 { - return fmt.Errorf("title can't be empty") - } - if len(msg.Title) > MaxTitleLength { - return fmt.Errorf("Proposal title is longer than max length of %d", MaxTitleLength) - } - if len(msg.Description) == 0 { - return fmt.Errorf("description can't be empty") - } - - if len(msg.Description) > MaxDescriptionLength { - return fmt.Errorf("Proposal description is longer than max length of %d", MaxDescriptionLength) - } - if !validSideProposalType(msg.ProposalType) { - return fmt.Errorf("invalid proposal type %v ", msg.ProposalType) - } - if len(msg.Proposer) == 0 { - return fmt.Errorf("proposer can't be empty") - } - if !msg.InitialDeposit.IsValid() { - return fmt.Errorf("initial deposit %v is invalid. ", msg.InitialDeposit) - } - if !msg.InitialDeposit.IsNotNegative() { - return fmt.Errorf("initial deposit %v is negative. ", msg.InitialDeposit) - } - if msg.VotingPeriod <= 0 || msg.VotingPeriod > MaxVotingPeriod { - return fmt.Errorf("voting period should between 0 and %d weeks", MaxVotingPeriod/(7*24*60*60*time.Second)) - } - return nil - return nil -} - -func (msg SideChainSubmitProposalMsg) String() string { - return fmt.Sprintf("SideChainSubmitProposalMsg{%s, %s, %s, %v, %s, %s}", msg.Title, - msg.Description, msg.ProposalType, msg.InitialDeposit, msg.VotingPeriod, msg.SideChainId) -} - -// Implements Msg. -func (msg SideChainSubmitProposalMsg) GetSignBytes() []byte { - b, err := amino.NewCodec().MarshalJSON(msg) - if err != nil { - panic(err) - } - return MustSortJSON(b) -} - -// Implements Msg. Identical to MsgSubmitProposal, keep here for code readability. -func (msg SideChainSubmitProposalMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.Proposer} -} - -// Implements Msg. Identical to MsgSubmitProposal, keep here for code readability. -func (msg SideChainSubmitProposalMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -//----------------------------------------------------------- -// SideChainDepositMsg -type SideChainDepositMsg struct { - ProposalID int64 `json:"proposal_id"` // ID of the proposal - Depositer types.AccAddress `json:"depositer"` // Address of the depositer - Amount types.Coins `json:"amount"` // Coins to add to the proposal's deposit - SideChainId string `json:"side_chain_id"` -} - -func NewSideChainDepositMsg(depositer types.AccAddress, proposalID int64, amount types.Coins, sideChainId string) SideChainDepositMsg { - return SideChainDepositMsg{ - ProposalID: proposalID, - Depositer: depositer, - Amount: amount, - SideChainId: sideChainId, - } -} - -// nolint -func (msg SideChainDepositMsg) Route() string { return MsgRoute } -func (msg SideChainDepositMsg) Type() string { return MsgTypeSideDeposit } - -// Implements Msg. -func (msg SideChainDepositMsg) ValidateBasic() error { - if len(msg.SideChainId) == 0 || len(msg.SideChainId) > MaxSideChainIdLength { - return fmt.Errorf("invalid side chain id %s", msg.SideChainId) - } - if len(msg.Depositer) == 0 { - return fmt.Errorf("depositer can't be empty ") - } - if !msg.Amount.IsValid() { - return fmt.Errorf("amount is invalid ") - } - if !msg.Amount.IsNotNegative() { - return fmt.Errorf("amount can't be negative ") - } - if msg.ProposalID < 0 { - return fmt.Errorf("proposalId can't be negative ") - } - return nil -} - -func (msg SideChainDepositMsg) String() string { - return fmt.Sprintf("SideChainDepositMsg{%s=>%v: %v, %s}", msg.Depositer, msg.ProposalID, msg.Amount, msg.SideChainId) -} - -// Implements Msg. -func (msg SideChainDepositMsg) GetSignBytes() []byte { - b, err := amino.NewCodec().MarshalJSON(msg) - if err != nil { - panic(err) - } - return MustSortJSON(b) -} - -// Implements Msg. Identical to MsgDeposit, keep here for code readability. -func (msg SideChainDepositMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.Depositer} -} - -// Implements Msg. Identical to MsgDeposit, keep here for code readability. -func (msg SideChainDepositMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -//----------------------------------------------------------- -// SideChainVoteMsg - -type SideChainVoteMsg struct { - ProposalID int64 `json:"proposal_id"` // ID of the proposal - Voter types.AccAddress `json:"voter"` // address of the voter - Option VoteOption `json:"option"` // option from OptionSet chosen by the voter - SideChainId string `json:"side_chain_id"` -} - -func NewSideChainVoteMsg(voter types.AccAddress, proposalID int64, option VoteOption, sideChainId string) SideChainVoteMsg { - return SideChainVoteMsg{ - ProposalID: proposalID, - Voter: voter, - Option: option, - SideChainId: sideChainId, - } -} - -func (msg SideChainVoteMsg) Route() string { return MsgRoute } -func (msg SideChainVoteMsg) Type() string { return MsgTypeSideVote } - -// Implements Msg. -func (msg SideChainVoteMsg) ValidateBasic() error { - if len(msg.SideChainId) == 0 || len(msg.SideChainId) > MaxSideChainIdLength { - return fmt.Errorf("invalid side chain id %s", msg.SideChainId) - } - if len(msg.Voter.Bytes()) == 0 { - return fmt.Errorf("vaoter can't be empty ") - } - if msg.ProposalID < 0 { - return fmt.Errorf("proposalId can't be less than 0") - } - if !validVoteOption(msg.Option) { - return fmt.Errorf("invalid msg option %v", msg.Option) - } - return nil -} - -func (msg SideChainVoteMsg) String() string { - return fmt.Sprintf("SideChainVoteMsg{%v - %s, %s}", msg.ProposalID, msg.Option, msg.SideChainId) -} - -// Implements Msg. -func (msg SideChainVoteMsg) GetSignBytes() []byte { - b, err := amino.NewCodec().MarshalJSON(msg) - if err != nil { - panic(err) - } - return MustSortJSON(b) -} - -// Implements Msg. Identical to MsgVote, keep here for code readability. -func (msg SideChainVoteMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.Voter} -} - -// Implements Msg. Identical to MsgVote, keep here for code readability. -func (msg SideChainVoteMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -func validSideProposalType(pt ProposalKind) bool { - if pt == ProposalTypeSCParamsChange || - pt == ProposalTypeCSCParamsChange { - return true - } - return false -} - -// --------- Definition side chain prams change ------------------- // -type SCParam interface { - UpdateCheck() error - // native means weather the parameter stored in native store context or side chain store context - //GetParamAttribute() (string, bool) - GetParamAttribute() (string, bool) -} - -type SCChangeParams struct { - SCParams []SCParam `json:"sc_params"` - Description string `json:"description"` -} - -func (s *SCChangeParams) Check() error { - // use literal string to avoid import cycle - supportParams := []string{"slash", "ibc", "oracle", "staking"} - - if len(s.SCParams) != len(supportParams) { - return fmt.Errorf("the sc_params length mismatch, suppose %d", len(supportParams)) - } - - paramSet := make(map[string]bool) - for _, s := range supportParams { - paramSet[s] = true - } - - for _, sc := range s.SCParams { - if sc == nil { - return fmt.Errorf("sc_params contains empty element") - } - err := sc.UpdateCheck() - if err != nil { - return err - } - paramType, _ := sc.GetParamAttribute() - if exist := paramSet[paramType]; exist { - delete(paramSet, paramType) - } else { - return fmt.Errorf("unsupported param type %s", paramType) - } - } - return nil -} - -type IbcParams struct { - RelayerFee int64 `json:"relayer_fee"` -} - -func (p *IbcParams) UpdateCheck() error { - if p.RelayerFee <= 0 { - return fmt.Errorf("the syn_package_fee should be greater than 0") - } - return nil -} - -func (p *IbcParams) GetParamAttribute() (string, bool) { - return "ibc", false -} - -type OracleParams struct { - ConsensusNeeded types.Dec `json:"ConsensusNeeded"` // Minimum deposit for a proposal to enter voting period. -} - -func (p *OracleParams) UpdateCheck() error { - if p.ConsensusNeeded.IsNil() || p.ConsensusNeeded.GT(types.OneDec()) || p.ConsensusNeeded.LT(types.NewDecWithPrec(5, 1)) { - return fmt.Errorf("the value should be in range 0.5 to 1") - } - return nil -} - -func (p *OracleParams) GetParamAttribute() (string, bool) { - return "oracle", true -} - -type SlashParams struct { - MaxEvidenceAge time.Duration `json:"max_evidence_age"` - SignedBlocksWindow int64 `json:"signed_blocks_window"` - MinSignedPerWindow types.Dec `json:"min_signed_per_window"` - DoubleSignUnbondDuration time.Duration `json:"double_sign_unbond_duration"` - DowntimeUnbondDuration time.Duration `json:"downtime_unbond_duration"` - TooLowDelUnbondDuration time.Duration `json:"too_low_del_unbond_duration"` - SlashFractionDoubleSign types.Dec `json:"slash_fraction_double_sign"` - SlashFractionDowntime types.Dec `json:"slash_fraction_downtime"` - DoubleSignSlashAmount int64 `json:"double_sign_slash_amount"` - DowntimeSlashAmount int64 `json:"downtime_slash_amount"` - SubmitterReward int64 `json:"submitter_reward"` - DowntimeSlashFee int64 `json:"downtime_slash_fee"` -} - -func (p *SlashParams) GetParamAttribute() (string, bool) { - return "slash", false -} - -func (p *SlashParams) UpdateCheck() error { - // no check for SignedBlocksWindow, MinSignedPerWindow, SlashFractionDoubleSign, SlashFractionDowntime - if p.MaxEvidenceAge < 1*time.Minute || p.MaxEvidenceAge > 100*24*time.Hour { - return fmt.Errorf("the max_evidence_age should be in range 1 minutes to 100 day") - } - if p.DoubleSignUnbondDuration < 1*time.Hour { - return fmt.Errorf("the double_sign_unbond_duration should be greate than 1 hour") - } - if p.DowntimeUnbondDuration < 60*time.Second || p.DowntimeUnbondDuration > 100*24*time.Hour { - return fmt.Errorf("the downtime_unbond_duration should be in range 1 minutes to 100 day") - } - if p.TooLowDelUnbondDuration < 60*time.Second || p.TooLowDelUnbondDuration > 100*24*time.Hour { - return fmt.Errorf("the too_low_del_unbond_duration should be in range 1 minutes to 100 day") - } - if p.DoubleSignSlashAmount < 1e8 { - return fmt.Errorf("the double_sign_slash_amount should be larger than 1e8") - } - if p.DowntimeSlashAmount < 1e8 || p.DowntimeSlashAmount > 10000e8 { - return fmt.Errorf("the downtime_slash_amount should be in range 1e8 to 10000e8") - } - if p.SubmitterReward < 1e7 || p.SubmitterReward > 1000e8 { - return fmt.Errorf("the submitter_reward should be in range 1e7 to 1000e8") - } - if p.DowntimeSlashFee < 1e8 || p.DowntimeSlashFee > 1000e8 { - return fmt.Errorf("the downtime_slash_fee should be in range 1e8 to 1000e8") - } - return nil -} - -// Params defines the high level settings for staking -type StakeParams struct { - UnbondingTime time.Duration `json:"unbonding_time"` - - MaxValidators uint16 `json:"max_validators"` // maximum number of validators - BondDenom string `json:"bond_denom"` // bondable coin denomination - MinSelfDelegation int64 `json:"min_self_delegation"` // the minimal self-delegation amount - MinDelegationChange int64 `json:"min_delegation_change"` // the minimal delegation amount changed -} - -func (p *StakeParams) GetParamAttribute() (string, bool) { - return "staking", false -} - -func (p *StakeParams) UpdateCheck() error { - if p.BondDenom != NativeToken { - return fmt.Errorf("only native token is availabe as bond_denom so far") - } - // the valid range is 1 minute to 100 day. - if p.UnbondingTime > 100*24*time.Hour || p.UnbondingTime < time.Minute { - return fmt.Errorf("the UnbondingTime should be in range 1 minute to 100 days") - } - if p.MaxValidators < 1 || p.MaxValidators > 500 { - return fmt.Errorf("the max validator should be in range 1 to 500") - } - // BondDenom do not check here, it should be native token and do not support update so far. - // Leave the check in node repo. - - if p.MinSelfDelegation > 10000000e8 || p.MinSelfDelegation < 1e8 { - return fmt.Errorf("the min_self_delegation should be in range 1e8 to 10000000e8]") - } - if p.MinDelegationChange < 1e5 { - return fmt.Errorf("the min_delegation_change should be no less than 1e5") - } - return nil -} - -// --------- Definition cross side chain prams change ------------------- // - -type CSCParamChange struct { - Key string `json:"key"` // the name of the parameter - Value string `json:"value"` - Target string `json:"target"` - - // Since byte slice is not friendly to show in proposal description, omit it. - ValueBytes []byte `json:"-"` // the value of the parameter - TargetBytes []byte `json:"-"` // the address of the target contract -} - -func (c *CSCParamChange) Check() error { - targetBytes, err := hex.DecodeString(c.Target) - if err != nil { - return fmt.Errorf("target is not hex encoded, err %v", err) - } - c.TargetBytes = targetBytes - - valueBytes, err := hex.DecodeString(c.Value) - if err != nil { - return fmt.Errorf("value is not hex encoded, err %v", err) - } - c.ValueBytes = valueBytes - keyBytes := []byte(c.Key) - if len(keyBytes) <= 0 || len(keyBytes) > math.MaxUint8 { - return fmt.Errorf("the length of key exceed the limitation") - } - if len(c.ValueBytes) <= 0 || len(c.ValueBytes) > math.MaxUint8 { - return fmt.Errorf("the length of value exceed the limitation") - } - if len(c.TargetBytes) != types.AddrLen { - return fmt.Errorf("the length of target address is not %d", types.AddrLen) - } - return nil -} diff --git a/types/msg/msg-sidechain-slash.go b/types/msg/msg-sidechain-slash.go deleted file mode 100644 index 125692b6..00000000 --- a/types/msg/msg-sidechain-slash.go +++ /dev/null @@ -1,50 +0,0 @@ -package msg - -import ( - "fmt" - - "github.com/binance-chain/go-sdk/common/types" -) - -const ( - TypeMsgSideChainUnjail = "side_chain_unjail" - - SideChainSlashMsgRoute = "slashing" -) - -type MsgSideChainUnjail struct { - ValidatorAddr types.ValAddress `json:"address"` - SideChainId string `json:"side_chain_id"` -} - -func NewMsgSideChainUnjail(validatorAddr types.ValAddress, sideChainId string) MsgSideChainUnjail { - return MsgSideChainUnjail{ - ValidatorAddr: validatorAddr, - SideChainId: sideChainId, - } -} - -func (msg MsgSideChainUnjail) Route() string { return SideChainSlashMsgRoute } -func (msg MsgSideChainUnjail) Type() string { return TypeMsgSideChainUnjail } -func (msg MsgSideChainUnjail) GetSigners() []types.AccAddress { - return []types.AccAddress{types.AccAddress(msg.ValidatorAddr)} -} - -func (msg MsgSideChainUnjail) GetSignBytes() []byte { - b := MsgCdc.MustMarshalJSON(msg) - return MustSortJSON(b) -} - -func (msg MsgSideChainUnjail) ValidateBasic() error { - if msg.ValidatorAddr == nil { - return fmt.Errorf("validator does not exist for that address") - } - if len(msg.SideChainId) == 0 || len(msg.SideChainId) > MaxSideChainIdLength { - return fmt.Errorf(fmt.Sprintf("side chain id must be included and max length is %d bytes", MaxSideChainIdLength)) - } - return nil -} - -func (msg MsgSideChainUnjail) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} diff --git a/types/msg/msg-sidechain-stake.go b/types/msg/msg-sidechain-stake.go deleted file mode 100644 index 34355708..00000000 --- a/types/msg/msg-sidechain-stake.go +++ /dev/null @@ -1,393 +0,0 @@ -package msg - -import ( - "bytes" - "fmt" - - "github.com/binance-chain/go-sdk/common/types" -) - -const ( - TypeCreateSideChainValidator = "side_create_validator" - TypeEditSideChainValidator = "side_edit_validator" - TypeSideChainDelegate = "side_delegate" - TypeSideChainRedelegate = "side_redelegate" - TypeSideChainUndelegate = "side_undelegate" - - SideChainStakeMsgRoute = "stake" - SideChainAddrLen = 20 - - MinDelegationAmount = 1e7 -) - -type CreateSideChainValidatorMsg struct { - Description Description `json:"description"` - Commission types.CommissionMsg `json:"commission"` - DelegatorAddr types.AccAddress `json:"delegator_address"` - ValidatorAddr types.ValAddress `json:"validator_address"` - Delegation types.Coin `json:"delegation"` - SideChainId string `json:"side_chain_id"` - SideConsAddr []byte `json:"side_cons_addr"` - SideFeeAddr []byte `json:"side_fee_addr"` -} - -func NewCreateSideChainValidatorMsg(valAddr types.ValAddress, delegation types.Coin, - description Description, commission types.CommissionMsg, sideChainId string, sideConsAddr []byte, sideFeeAddr []byte) CreateSideChainValidatorMsg { - return NewMsgCreateSideChainValidatorOnBehalfOf(types.AccAddress(valAddr), valAddr, delegation, description, commission, sideChainId, sideConsAddr, sideFeeAddr) -} - -func NewMsgCreateSideChainValidatorOnBehalfOf(delegatorAddr types.AccAddress, valAddr types.ValAddress, delegation types.Coin, - description Description, commission types.CommissionMsg, sideChainId string, sideConsAddr []byte, sideFeeAddr []byte) CreateSideChainValidatorMsg { - return CreateSideChainValidatorMsg{ - Description: description, - Commission: commission, - DelegatorAddr: delegatorAddr, - ValidatorAddr: valAddr, - Delegation: delegation, - SideChainId: sideChainId, - SideConsAddr: sideConsAddr, - SideFeeAddr: sideFeeAddr, - } -} - -func (msg CreateSideChainValidatorMsg) Route() string { return SideChainStakeMsgRoute } - -func (msg CreateSideChainValidatorMsg) Type() string { return TypeCreateSideChainValidator } - -func (msg CreateSideChainValidatorMsg) GetSigners() []types.AccAddress { - addrs := []types.AccAddress{msg.DelegatorAddr} - - if !bytes.Equal(msg.DelegatorAddr.Bytes(), msg.ValidatorAddr.Bytes()) { - addrs = append(addrs, types.AccAddress(msg.ValidatorAddr)) - } - return addrs -} - -func (msg CreateSideChainValidatorMsg) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) - return MustSortJSON(bz) -} - -func (msg CreateSideChainValidatorMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -func (msg CreateSideChainValidatorMsg) ValidateBasic() error { - //self-delegator address length is 20 - if len(msg.DelegatorAddr) != types.AddrLen { - return fmt.Errorf("Expected delegator address length is %d, actual length is %d ", types.AddrLen, len(msg.DelegatorAddr)) - } - - //validator operator address length is 20 - if len(msg.ValidatorAddr) != types.AddrLen { - return fmt.Errorf("Expected validator address length is %d, actual length is %d ", types.AddrLen, len(msg.ValidatorAddr)) - } - - //description check - if msg.Description == (Description{}) { - return fmt.Errorf("description must be included") - } - if _, err := msg.Description.EnsureLength(); err != nil { - return err - } - - //commission check - commission := types.NewCommission(msg.Commission.Rate, msg.Commission.MaxRate, msg.Commission.MaxChangeRate) - if err := commission.Validate(); err != nil { - return err - } - - //side chain id length 1-20 - if len(msg.SideChainId) == 0 || len(msg.SideChainId) > MaxSideChainIdLength { - return fmt.Errorf("side chain id must be included and max length is %d bytes", MaxSideChainIdLength) - } - - //sideConsAddr length should between 16 - 64 - if err := checkSideChainAddr("SideConsAddr", msg.SideConsAddr); err != nil { - return err - } - - //sideFeeAddr length should between 16 - 64 - if err := checkSideChainAddr("SideFeeAddr", msg.SideFeeAddr); err != nil { - return err - } - - return nil -} - -func checkSideChainAddr(addrName string, addr []byte) error { - if len(addr) != SideChainAddrLen { - return fmt.Errorf("Expected %s length is %d, got %d ", addrName, SideChainAddrLen, len(addr)) - } - - return nil -} - -//---------------------------------------------------------------------------- - -type EditSideChainValidatorMsg struct { - Description Description `json:"description"` - ValidatorAddr types.ValAddress `json:"address"` - - CommissionRate *types.Dec `json:"commission_rate"` - - SideChainId string `json:"side_chain_id"` - SideFeeAddr []byte `json:"side_fee_addr"` - SideConsAddr []byte `json:"side_cons_addr,omitempty"` -} - -func NewEditSideChainValidatorMsg(sideChainId string, validatorAddr types.ValAddress, description Description, commissionRate *types.Dec, sideFeeAddr, sideConsAddr []byte) EditSideChainValidatorMsg { - return EditSideChainValidatorMsg{ - Description: description, - ValidatorAddr: validatorAddr, - CommissionRate: commissionRate, - SideChainId: sideChainId, - SideFeeAddr: sideFeeAddr, - SideConsAddr: sideConsAddr, - } -} - -func (msg EditSideChainValidatorMsg) Route() string { return SideChainStakeMsgRoute } - -func (msg EditSideChainValidatorMsg) Type() string { return TypeEditSideChainValidator } - -func (msg EditSideChainValidatorMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{types.AccAddress(msg.ValidatorAddr)} -} - -func (msg EditSideChainValidatorMsg) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) - return MustSortJSON(bz) -} - -func (msg EditSideChainValidatorMsg) ValidateBasic() error { - //validator operator address length is 20 - if len(msg.ValidatorAddr) != types.AddrLen { - return fmt.Errorf("Expected validator address length is %d, actual length is %d ", types.AddrLen, len(msg.ValidatorAddr)) - } - - //description check - if msg.Description == (Description{}) { - return fmt.Errorf("description must be included. if you do not want to edit the description, assign each field to [do-not-modify]") - } - if _, err := msg.Description.EnsureLength(); err != nil { - return err - } - - //commission rate is between 0 and 1 - if msg.CommissionRate != nil { - if msg.CommissionRate.GT(types.OneDec()) || msg.CommissionRate.LT(types.ZeroDec()) { - return fmt.Errorf("commission rate must be between 0 and 1 (inclusive)") - } - } - - //side chain id length 1 - 20 - if len(msg.SideChainId) == 0 || len(msg.SideChainId) > MaxSideChainIdLength { - return fmt.Errorf("side chain id must be included and max length is %d bytes", MaxSideChainIdLength) - } - - if len(msg.SideFeeAddr) != 0 { - if err := checkSideChainAddr("SideFeeAddr", msg.SideFeeAddr); err != nil { - return err - } - } - - if len(msg.SideConsAddr) != 0 { - if err := checkSideChainAddr("SideConsAddr", msg.SideConsAddr); err != nil { - return err - } - } - - return nil -} - -func (msg EditSideChainValidatorMsg) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -//---------------------------------------------------------------------------- - -type SideChainDelegateMsg struct { - DelegatorAddr types.AccAddress `json:"delegator_addr"` - ValidatorAddr types.ValAddress `json:"validator_addr"` - Delegation types.Coin `json:"delegation"` - - SideChainId string `json:"side_chain_id"` -} - -func NewSideChainDelegateMsg(sideChainId string, delAddr types.AccAddress, valAddr types.ValAddress, delegation types.Coin) SideChainDelegateMsg { - return SideChainDelegateMsg{ - DelegatorAddr: delAddr, - ValidatorAddr: valAddr, - Delegation: delegation, - SideChainId: sideChainId, - } -} - -func (msg SideChainDelegateMsg) Route() string { return SideChainStakeMsgRoute } - -func (msg SideChainDelegateMsg) Type() string { return TypeSideChainDelegate } - -func (msg SideChainDelegateMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.DelegatorAddr} -} - -func (msg SideChainDelegateMsg) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) - return MustSortJSON(bz) -} - -func (msg SideChainDelegateMsg) ValidateBasic() error { - //delegator address is 20 - if len(msg.DelegatorAddr) != types.AddrLen { - return fmt.Errorf("Expected delegator address length is %d, actual length is %d ", types.AddrLen, len(msg.DelegatorAddr)) - } - - //validator operator address length is 20 - if len(msg.ValidatorAddr) != types.AddrLen { - return fmt.Errorf("Expected validator address length is %d, actual length is %d ", types.AddrLen, len(msg.ValidatorAddr)) - } - - //delegation amount should be greater than or equal to 1e8 - if msg.Delegation.Amount < MinDelegationAmount { - return fmt.Errorf("delegation must not be less than %d ", msg.Delegation.Amount) - } - - //side chain id length 1 - 20 - if len(msg.SideChainId) == 0 || len(msg.SideChainId) > MaxSideChainIdLength { - return fmt.Errorf("side chain id must be included and max length is %d bytes", MaxSideChainIdLength) - } - return nil -} - -func (msg SideChainDelegateMsg) GetInvolvedAddresses() []types.AccAddress { - return []types.AccAddress{msg.DelegatorAddr, types.AccAddress(msg.ValidatorAddr)} -} - -//---------------------------------------------------------------------------- - -type SideChainRedelegateMsg struct { - DelegatorAddr types.AccAddress `json:"delegator_addr"` - ValidatorSrcAddr types.ValAddress `json:"validator_src_addr"` - ValidatorDstAddr types.ValAddress `json:"validator_dst_addr"` - Amount types.Coin `json:"amount"` - SideChainId string `json:"side_chain_id"` -} - -func NewSideChainRedelegateMsg(sideChainId string, delegatorAddr types.AccAddress, valSrcAddr types.ValAddress, valDstAddr types.ValAddress, amount types.Coin) SideChainRedelegateMsg { - return SideChainRedelegateMsg{ - DelegatorAddr: delegatorAddr, - ValidatorSrcAddr: valSrcAddr, - ValidatorDstAddr: valDstAddr, - Amount: amount, - SideChainId: sideChainId, - } -} - -func (msg SideChainRedelegateMsg) Route() string { return SideChainStakeMsgRoute } - -func (msg SideChainRedelegateMsg) Type() string { return TypeSideChainRedelegate } - -func (msg SideChainRedelegateMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.DelegatorAddr} -} - -func (msg SideChainRedelegateMsg) GetSignBytes() []byte { - b := MsgCdc.MustMarshalJSON(msg) - return MustSortJSON(b) -} - -func (msg SideChainRedelegateMsg) GetInvolvedAddresses() []types.AccAddress { - return []types.AccAddress{msg.DelegatorAddr, types.AccAddress(msg.ValidatorSrcAddr), types.AccAddress(msg.DelegatorAddr)} -} - -func (msg SideChainRedelegateMsg) ValidateBasic() error { - //delegator address length is 20 - if len(msg.DelegatorAddr) != types.AddrLen { - return fmt.Errorf("Expected delegator address length is %d, actual length is %d ", types.AddrLen, len(msg.DelegatorAddr)) - } - - //source validator address length is 20 - if len(msg.ValidatorSrcAddr) != types.AddrLen { - return fmt.Errorf("Expected ValidatorSrcAddr length is %d, actual length is %d ", types.AddrLen, len(msg.ValidatorSrcAddr)) - } - - //destination validator address length is 20 - if len(msg.ValidatorDstAddr) != types.AddrLen { - return fmt.Errorf("Expected ValidatorDstAddr length is %d, actual length is %d ", types.AddrLen, len(msg.ValidatorDstAddr)) - } - - //source address and destination address are not the same one - if bytes.Equal(msg.ValidatorSrcAddr, msg.ValidatorDstAddr) { - return fmt.Errorf("cannot redelegate to the same validator") - } - - //redelegation amount is greater than or equal to 1e8 - if msg.Amount.Amount < MinDelegationAmount { - return fmt.Errorf("redelegation amount must not be less than %f ", MinDelegationAmount) - } - - //side chain id length 1 - 20 - if len(msg.SideChainId) == 0 || len(msg.SideChainId) > MaxSideChainIdLength { - return fmt.Errorf("side chain id must be included and max length is %d bytes", MaxSideChainIdLength) - } - return nil -} - -//---------------------------------------------------------------------------- - -type SideChainUndelegateMsg struct { - DelegatorAddr types.AccAddress `json:"delegator_addr"` - ValidatorAddr types.ValAddress `json:"validator_addr"` - Amount types.Coin `json:"amount"` - SideChainId string `json:"side_chain_id"` -} - -func NewSideChainUndelegateMsg(sideChainId string, delegatorAddr types.AccAddress, valAddr types.ValAddress, amount types.Coin) SideChainUndelegateMsg { - return SideChainUndelegateMsg{ - DelegatorAddr: delegatorAddr, - ValidatorAddr: valAddr, - Amount: amount, - SideChainId: sideChainId, - } -} - -func (msg SideChainUndelegateMsg) Route() string { return SideChainStakeMsgRoute } - -func (msg SideChainUndelegateMsg) Type() string { return TypeSideChainUndelegate } - -func (msg SideChainUndelegateMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.DelegatorAddr} -} - -func (msg SideChainUndelegateMsg) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) - return MustSortJSON(bz) -} - -func (msg SideChainUndelegateMsg) ValidateBasic() error { - //delegator address length is 20 - if len(msg.DelegatorAddr) != types.AddrLen { - return fmt.Errorf("Expected delegator address length is %d, actual length is %d ", types.AddrLen, len(msg.DelegatorAddr)) - } - - //validator operator address length is 20 - if len(msg.ValidatorAddr) != types.AddrLen { - return fmt.Errorf("Expected validator address length is %d, actual length is %d ", types.AddrLen, len(msg.ValidatorAddr)) - } - - //undelegate amount must be positive - if msg.Amount.Amount <= 0 { - return fmt.Errorf("undelegation amount must be positive") - } - - //side chain id length 1 - 20 - if len(msg.SideChainId) == 0 || len(msg.SideChainId) > MaxSideChainIdLength { - return fmt.Errorf("side chain id must be included and max length is %d bytes", MaxSideChainIdLength) - } - return nil -} - -func (msg SideChainUndelegateMsg) GetInvolvedAddresses() []types.AccAddress { - return []types.AccAddress{msg.DelegatorAddr, types.AccAddress(msg.ValidatorAddr)} -} diff --git a/types/msg/msg-timelock.go b/types/msg/msg-timelock.go deleted file mode 100644 index 94d1c0e4..00000000 --- a/types/msg/msg-timelock.go +++ /dev/null @@ -1,180 +0,0 @@ -package msg - -import ( - "encoding/json" - "fmt" - "time" - - "github.com/binance-chain/go-sdk/common/types" - "github.com/tendermint/tendermint/crypto" -) - -const ( - MaxTimeLockDescriptionLength = 128 - MinLockTime = 60 * time.Second - - InitialRecordId = 1 -) - -var ( - TimeLockCoinsAccAddr = types.AccAddress(crypto.AddressHash([]byte("BinanceChainTimeLockCoins"))) -) - -type TimeLockMsg struct { - From types.AccAddress `json:"from"` - Description string `json:"description"` - Amount types.Coins `json:"amount"` - LockTime int64 `json:"lock_time"` -} - -func NewTimeLockMsg(from types.AccAddress, description string, amount types.Coins, lockTime int64) TimeLockMsg { - return TimeLockMsg{ - From: from, - Description: description, - Amount: amount, - LockTime: lockTime, - } -} - -func (msg TimeLockMsg) Route() string { return MsgRoute } -func (msg TimeLockMsg) Type() string { return "timeLock" } -func (msg TimeLockMsg) String() string { - return fmt.Sprintf("TimeLock{%s#%v#%v#%v}", msg.From, msg.Description, msg.Amount, msg.LockTime) -} -func (msg TimeLockMsg) GetInvolvedAddresses() []types.AccAddress { - return []types.AccAddress{msg.From, TimeLockCoinsAccAddr} -} -func (msg TimeLockMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} } - -func (msg TimeLockMsg) ValidateBasic() error { - if len(msg.Description) == 0 || len(msg.Description) > MaxTimeLockDescriptionLength { - return fmt.Errorf("length of description(%d) should be larger than 0 and be less than or equal to %d", - len(msg.Description), MaxTimeLockDescriptionLength) - } - - if msg.LockTime <= 0 { - return fmt.Errorf("lock time(%d) should be larger than 0", msg.LockTime) - } - - if !msg.Amount.IsValid() { - return fmt.Errorf("amount %v is invalid", msg.Amount) - } - - if !msg.Amount.IsPositive() { - return fmt.Errorf("amount %v can't be negative", msg.Amount) - } - - return nil -} - -func (msg TimeLockMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -type TimeRelockMsg struct { - From types.AccAddress `json:"from"` - Id int64 `json:"time_lock_id"` - Description string `json:"description"` - Amount types.Coins `json:"amount"` - LockTime int64 `json:"lock_time"` -} - -func NewTimeRelockMsg(from types.AccAddress, id int64, description string, amount types.Coins, lockTime int64) TimeRelockMsg { - return TimeRelockMsg{ - From: from, - Id: id, - Description: description, - Amount: amount, - LockTime: lockTime, - } -} - -func (msg TimeRelockMsg) Route() string { return MsgRoute } -func (msg TimeRelockMsg) Type() string { return "timeRelock" } -func (msg TimeRelockMsg) String() string { - return fmt.Sprintf("TimeRelock{%v#%s#%v#%v#%v}", msg.Id, msg.From, msg.Description, msg.Amount, msg.LockTime) -} -func (msg TimeRelockMsg) GetInvolvedAddresses() []types.AccAddress { - return []types.AccAddress{msg.From, TimeLockCoinsAccAddr} -} -func (msg TimeRelockMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} } - -func (msg TimeRelockMsg) ValidateBasic() error { - if msg.Id < InitialRecordId { - return fmt.Errorf("time lock id should not be less than %d", InitialRecordId) - } - - if len(msg.Description) > MaxTimeLockDescriptionLength { - return fmt.Errorf("length of description(%d) should be less than or equal to %d", - len(msg.Description), MaxTimeLockDescriptionLength) - } - - if msg.LockTime < 0 { - return fmt.Errorf("lock time(%d) should not be less than 0", msg.LockTime) - } - - if !msg.Amount.IsValid() { - return fmt.Errorf("amount %v is invalid", msg.Amount) - } - - if !msg.Amount.IsNotNegative() { - return fmt.Errorf("amount %v can't be negative", msg.Amount) - } - - if len(msg.Description) == 0 && - msg.Amount.IsZero() && - msg.LockTime == 0 { - return fmt.Errorf("nothing to update for time lock") - } - - return nil -} - -func (msg TimeRelockMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -type TimeUnlockMsg struct { - From types.AccAddress `json:"from"` - Id int64 `json:"time_lock_id"` -} - -func NewTimeUnlockMsg(from types.AccAddress, id int64) TimeUnlockMsg { - return TimeUnlockMsg{ - From: from, - Id: id, - } -} - -func (msg TimeUnlockMsg) Route() string { return MsgRoute } -func (msg TimeUnlockMsg) Type() string { return "timeUnlock" } -func (msg TimeUnlockMsg) String() string { - return fmt.Sprintf("TimeUnlock{%s#%v}", msg.From, msg.Id) -} -func (msg TimeUnlockMsg) GetInvolvedAddresses() []types.AccAddress { - return []types.AccAddress{msg.From, TimeLockCoinsAccAddr} -} -func (msg TimeUnlockMsg) GetSigners() []types.AccAddress { return []types.AccAddress{msg.From} } - -func (msg TimeUnlockMsg) ValidateBasic() error { - if msg.Id < InitialRecordId { - return fmt.Errorf("time lock id should not be less than %d", InitialRecordId) - } - return nil -} - -func (msg TimeUnlockMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} diff --git a/types/msg/msg-transferOwnership.go b/types/msg/msg-transferOwnership.go deleted file mode 100644 index c96cb77d..00000000 --- a/types/msg/msg-transferOwnership.go +++ /dev/null @@ -1,59 +0,0 @@ -package msg - -import ( - "encoding/json" - "fmt" - - "github.com/binance-chain/go-sdk/common/types" -) - -// TransferOwnershipMsg def -type TransferOwnershipMsg struct { - From types.AccAddress `json:"from"` - Symbol string `json:"symbol"` - NewOwner types.AccAddress `json:"new_owner"` -} - -func NewTransferOwnershipMsg(from types.AccAddress, symbol string, newOwner types.AccAddress) TransferOwnershipMsg { - return TransferOwnershipMsg{ - From: from, - Symbol: symbol, - NewOwner: newOwner, - } -} - -func (msg TransferOwnershipMsg) Route() string { return "tokensOwnershipTransfer" } -func (msg TransferOwnershipMsg) Type() string { return "transferOwnership" } -func (msg TransferOwnershipMsg) String() string { return fmt.Sprintf("TransferOwnershipMsg{%#v}", msg) } - -func (msg TransferOwnershipMsg) ValidateBasic() error { - if len(msg.From) != types.AddrLen { - return fmt.Errorf("Invalid from address, expected address length is %d, actual length is %d ", types.AddrLen, len(msg.From)) - } - if len(msg.NewOwner) != types.AddrLen { - return fmt.Errorf("Invalid newOwner, expected address length is %d, actual length is %d ", types.AddrLen, len(msg.NewOwner)) - } - if !IsValidMiniTokenSymbol(msg.Symbol) { - err := ValidateSymbol(msg.Symbol) - if err != nil { - return err - } - } - return nil -} - -func (msg TransferOwnershipMsg) GetSignBytes() []byte { - b, err := json.Marshal(msg) - if err != nil { - panic(err) - } - return b -} - -func (msg TransferOwnershipMsg) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.From} -} - -func (msg TransferOwnershipMsg) GetInvolvedAddresses() []types.AccAddress { - return append(msg.GetSigners(), msg.NewOwner) -} diff --git a/types/msg/msg-unjail.go b/types/msg/msg-unjail.go deleted file mode 100644 index 769463d4..00000000 --- a/types/msg/msg-unjail.go +++ /dev/null @@ -1,52 +0,0 @@ -package msg - -import ( - "fmt" - sdk "github.com/binance-chain/go-sdk/common/types" -) - -// name to identify transaction types -const ( - TypeMsgUnjail = "unjail" - SlashMsgRoute = "slashing" -) - -// MsgUnjail - struct for unjailing jailed validator -type MsgUnjail struct { - ValidatorAddr sdk.ValAddress `json:"address"` // address of the validator operator -} - -func NewMsgUnjail(validatorAddr sdk.ValAddress) MsgUnjail { - return MsgUnjail{ - ValidatorAddr: validatorAddr, - } -} - -//nolint -func (msg MsgUnjail) Route() string { return SlashMsgRoute } -func (msg MsgUnjail) Type() string { return TypeMsgUnjail } -func (msg MsgUnjail) GetSigners() []sdk.AccAddress { - res := []sdk.AccAddress{sdk.AccAddress(msg.ValidatorAddr)} - fmt.Printf("MsgUnjail.GetSigners: %+v\n", res) - return res -} - -// get the bytes for the message signer to sign on -func (msg MsgUnjail) GetSignBytes() []byte { - b := MsgCdc.MustMarshalJSON(msg) - res := MustSortJSON(b) - fmt.Printf("MsgUnjail.GetSignBytes: %X\n", res) - return res -} - -// quick validity check -func (msg MsgUnjail) ValidateBasic() error { - if len(msg.ValidatorAddr) != sdk.AddrLen { - return fmt.Errorf("validator does not exist for that address") - } - return nil -} - -func (msg MsgUnjail) GetInvolvedAddresses() []sdk.AccAddress { - return msg.GetSigners() -} diff --git a/types/msg/msg-validator.go b/types/msg/msg-validator.go deleted file mode 100644 index 1bc05d14..00000000 --- a/types/msg/msg-validator.go +++ /dev/null @@ -1,324 +0,0 @@ -package msg - -import ( - "bytes" - "fmt" - - "github.com/binance-chain/go-sdk/common/types" -) - -// Description - description fields for a validator -type Description struct { - Moniker string `json:"moniker"` // name - Identity string `json:"identity"` // optional identity signature (ex. UPort or Keybase) - Website string `json:"website"` // optional website link - Details string `json:"details"` // optional details -} - -// EnsureLength ensures the length of a validator's description. -func (d Description) EnsureLength() (Description, error) { - if len(d.Moniker) > 70 { - return d, fmt.Errorf("len moniker %d can be more than %d ", len(d.Moniker), 70) - } - if len(d.Identity) > 3000 { - return d, fmt.Errorf("len Identity %d can be more than %d ", len(d.Identity), 3000) - } - if len(d.Website) > 140 { - return d, fmt.Errorf("len Website %d can be more than %d ", len(d.Website), 140) - } - if len(d.Details) > 280 { - return d, fmt.Errorf("len Details %d can be more than %d ", len(d.Details), 280) - } - - return d, nil -} - -type MsgCreateValidatorOpen struct { - Description Description `json:"description"` - Commission types.CommissionMsg `json:"commission"` - DelegatorAddr types.AccAddress `json:"delegator_address"` - ValidatorAddr types.ValAddress `json:"validator_address"` - PubKey string `json:"pubkey"` - Delegation types.Coin `json:"delegation"` -} - -func (msg MsgCreateValidatorOpen) Route() string { return MsgRoute } -func (msg MsgCreateValidatorOpen) Type() string { return "create_validator_open" } - -// Return address(es) that must sign over msg.GetSignBytes() -func (msg MsgCreateValidatorOpen) GetSigners() []types.AccAddress { - // delegator is first signer so delegator pays fees - addrs := []types.AccAddress{msg.DelegatorAddr} - - if !bytes.Equal(msg.DelegatorAddr.Bytes(), msg.ValidatorAddr.Bytes()) { - // if validator addr is not same as delegator addr, validator must sign - // msg as well - addrs = append(addrs, types.AccAddress(msg.ValidatorAddr)) - } - return addrs -} - -// get the bytes for the message signer to sign on -func (msg MsgCreateValidatorOpen) GetSignBytes() []byte { - b := MsgCdc.MustMarshalJSON(msg) - return MustSortJSON(b) -} - -func (msg MsgCreateValidatorOpen) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -// quick validity check -func (msg MsgCreateValidatorOpen) ValidateBasic() error { - if len(msg.DelegatorAddr) != types.AddrLen { - return fmt.Errorf("Expected delegator address length is %d, actual length is %d", types.AddrLen, len(msg.DelegatorAddr)) - } - if len(msg.ValidatorAddr) != types.AddrLen { - return fmt.Errorf("Expected validator address length is %d, actual length is %d", types.AddrLen, len(msg.ValidatorAddr)) - } - if msg.Delegation.Amount < 1e8 { - return fmt.Errorf("self delegation must not be less than 1e8") - } - if msg.Description == (Description{}) { - return fmt.Errorf("description must be included") - } - if _, err := msg.Description.EnsureLength(); err != nil { - return err - } - commission := types.NewCommission(msg.Commission.Rate, msg.Commission.MaxRate, msg.Commission.MaxChangeRate) - if err := commission.Validate(); err != nil { - return err - } - - return nil -} - -type MsgRemoveValidator struct { - LauncherAddr types.AccAddress `json:"launcher_addr"` - ValAddr types.ValAddress `json:"val_addr"` - ValConsAddr types.ConsAddress `json:"val_cons_addr"` - ProposalId int64 `json:"proposal_id"` -} - -func NewMsgRemoveValidator(launcherAddr types.AccAddress, valAddr types.ValAddress, - valConsAddr types.ConsAddress, proposalId int64) MsgRemoveValidator { - return MsgRemoveValidator{ - LauncherAddr: launcherAddr, - ValAddr: valAddr, - ValConsAddr: valConsAddr, - ProposalId: proposalId, - } -} - -//nolint -func (msg MsgRemoveValidator) Route() string { return MsgRoute } -func (msg MsgRemoveValidator) Type() string { return "remove_validator" } -func (msg MsgRemoveValidator) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.LauncherAddr} -} - -// get the bytes for the message signer to sign on -func (msg MsgRemoveValidator) GetSignBytes() []byte { - b, err := MsgCdc.MarshalJSON(struct { - LauncherAddr types.AccAddress `json:"launcher_addr"` - ValAddr types.ValAddress `json:"val_addr"` - ValConsAddr types.ConsAddress `json:"val_cons_addr"` - ProposalId int64 `json:"proposal_id"` - }{ - LauncherAddr: msg.LauncherAddr, - ValAddr: msg.ValAddr, - ValConsAddr: msg.ValConsAddr, - ProposalId: msg.ProposalId, - }) - if err != nil { - panic(err) - } - return MustSortJSON(b) -} - -// quick validity check -func (msg MsgRemoveValidator) ValidateBasic() error { - if len(msg.LauncherAddr) != types.AddrLen { - return fmt.Errorf("Expected launcher address length is %d, actual length is %d", types.AddrLen, len(msg.LauncherAddr)) - } - if len(msg.ValAddr) != types.AddrLen { - return fmt.Errorf("Expected validator address length is %d, actual length is %d", types.AddrLen, len(msg.ValAddr)) - } - if len(msg.ValConsAddr) != types.AddrLen { - return fmt.Errorf("Expected validator consensus address length is %d, actual length is %d", types.AddrLen, len(msg.ValConsAddr)) - } - if msg.ProposalId <= 0 { - return fmt.Errorf("Proposal id is expected to be positive, actual value is %d", msg.ProposalId) - } - return nil -} - -func (msg MsgRemoveValidator) GetInvolvedAddresses() []types.AccAddress { - return []types.AccAddress{msg.LauncherAddr} -} - -// MsgEditValidator - struct for editing a validator -type MsgEditValidator struct { - Description Description `json:"description"` - ValidatorAddr types.ValAddress `json:"address"` - // We pass a reference to the new commission rate as it's not mandatory to - // update. If not updated, the deserialized rate will be zero with no way to - // distinguish if an update was intended. - CommissionRate *types.Dec `json:"commission_rate"` - PubKey string `json:"pubkey"` -} - -//nolint -func (msg MsgEditValidator) Route() string { return MsgRoute } -func (msg MsgEditValidator) Type() string { return "edit_validator" } -func (msg MsgEditValidator) GetSigners() []types.AccAddress { - return []types.AccAddress{types.AccAddress(msg.ValidatorAddr)} -} - -// get the bytes for the message signer to sign on -func (msg MsgEditValidator) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) - return MustSortJSON(bz) -} - -// quick validity check -func (msg MsgEditValidator) ValidateBasic() error { - if msg.ValidatorAddr == nil { - return fmt.Errorf("nil validator address") - } - - if msg.Description == (Description{}) { - return fmt.Errorf("transaction must include some information to modify") - } - - if msg.PubKey != "" { - if _, err := types.GetConsPubKeyBech32(msg.PubKey); err != nil { - return fmt.Errorf("invalid PubKey: %v", err) - } - } - - return nil -} - -func (msg MsgEditValidator) GetInvolvedAddresses() []types.AccAddress { - return msg.GetSigners() -} - -//______________________________________________________________________ - -// MsgDelegate - struct for bonding transactions -type MsgDelegate struct { - DelegatorAddr types.AccAddress `json:"delegator_addr"` - ValidatorAddr types.ValAddress `json:"validator_addr"` - Delegation types.Coin `json:"delegation"` -} - -//nolint -func (msg MsgDelegate) Route() string { return MsgRoute } -func (msg MsgDelegate) Type() string { return "delegate" } -func (msg MsgDelegate) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.DelegatorAddr} -} - -// get the bytes for the message signer to sign on -func (msg MsgDelegate) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) - return MustSortJSON(bz) -} - -// quick validity check -func (msg MsgDelegate) ValidateBasic() error { - if msg.DelegatorAddr == nil { - return fmt.Errorf("delegator address is nil") - } - if msg.ValidatorAddr == nil { - return fmt.Errorf("validator address is nil") - } - if msg.Delegation.Amount < 1e8 { - return fmt.Errorf("delegation amount should not be less than 1e8") - } - return nil -} - -func (msg MsgDelegate) GetInvolvedAddresses() []types.AccAddress { - return []types.AccAddress{msg.DelegatorAddr, types.AccAddress(msg.ValidatorAddr)} -} - -// MsgDelegate - struct for bonding transactions -type MsgRedelegate struct { - DelegatorAddr types.AccAddress `json:"delegator_addr"` - ValidatorSrcAddr types.ValAddress `json:"validator_src_addr"` - ValidatorDstAddr types.ValAddress `json:"validator_dst_addr"` - Amount types.Coin `json:"amount"` -} - -//nolint -func (msg MsgRedelegate) Route() string { return MsgRoute } -func (msg MsgRedelegate) Type() string { return "redelegate" } -func (msg MsgRedelegate) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.DelegatorAddr} -} - -// get the bytes for the message signer to sign on -func (msg MsgRedelegate) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) - return MustSortJSON(bz) -} - -func (msg MsgRedelegate) GetInvolvedAddresses() []types.AccAddress { - return []types.AccAddress{msg.DelegatorAddr, types.AccAddress(msg.ValidatorSrcAddr), types.AccAddress(msg.DelegatorAddr)} -} - -// ValidateBasic is used to quickly disqualify obviously invalid messages quickly -func (msg MsgRedelegate) ValidateBasic() error { - if len(msg.DelegatorAddr) != types.AddrLen { - return fmt.Errorf("Expected delegator address length is %d, actual length is %d", types.AddrLen, len(msg.DelegatorAddr)) - } - if len(msg.ValidatorSrcAddr) != types.AddrLen { - return fmt.Errorf("Expected validator source address length is %d, actual length is %d", types.AddrLen, len(msg.ValidatorSrcAddr)) - } - if len(msg.ValidatorDstAddr) != types.AddrLen { - return fmt.Errorf("Expected validator destination address length is %d, actual length is %d", types.AddrLen, len(msg.ValidatorDstAddr)) - } - if msg.Amount.Amount <= 0 { - return fmt.Errorf("Expected positive amount, actual amount is %v", msg.Amount.Amount) - } - return nil -} - -type MsgUndelegate struct { - DelegatorAddr types.AccAddress `json:"delegator_addr"` - ValidatorAddr types.ValAddress `json:"validator_addr"` - Amount types.Coin `json:"amount"` -} - -//nolint -func (msg MsgUndelegate) Route() string { return MsgRoute } -func (msg MsgUndelegate) Type() string { return "undelegate" } -func (msg MsgUndelegate) GetSigners() []types.AccAddress { - return []types.AccAddress{msg.DelegatorAddr} -} - -// get the bytes for the message signer to sign on -func (msg MsgUndelegate) GetSignBytes() []byte { - bz := MsgCdc.MustMarshalJSON(msg) - return MustSortJSON(bz) -} - -// quick validity check -func (msg MsgUndelegate) ValidateBasic() error { - if len(msg.DelegatorAddr) != types.AddrLen { - return fmt.Errorf("Expected delegator address length is %d, actual length is %d", types.AddrLen, len(msg.DelegatorAddr)) - } - if len(msg.ValidatorAddr) != types.AddrLen { - return fmt.Errorf("Expected validator address length is %d, actual length is %d", types.AddrLen, len(msg.ValidatorAddr)) - } - if msg.Amount.Amount <= 0 { - return fmt.Errorf("undelegation amount must be positive: %d", msg.Amount.Amount) - } - return nil -} - -func (msg MsgUndelegate) GetInvolvedAddresses() []types.AccAddress { - return []types.AccAddress{msg.DelegatorAddr, types.AccAddress(msg.ValidatorAddr)} -} diff --git a/types/msg/msg.go b/types/msg/msg.go index e04c4852..bc343506 100644 --- a/types/msg/msg.go +++ b/types/msg/msg.go @@ -1,299 +1,159 @@ package msg import ( - "encoding/json" - "fmt" - "regexp" - "strconv" - "strings" - - "github.com/binance-chain/go-sdk/common/types" - - "github.com/pkg/errors" - - "github.com/binance-chain/go-sdk/common" + "github.com/bnb-chain/node/plugins/account" + bTypes "github.com/bnb-chain/node/plugins/bridge/types" + "github.com/bnb-chain/node/plugins/dex/order" + dexTypes "github.com/bnb-chain/node/plugins/dex/types" + "github.com/bnb-chain/node/plugins/tokens/burn" + "github.com/bnb-chain/node/plugins/tokens/freeze" + "github.com/bnb-chain/node/plugins/tokens/issue" + "github.com/bnb-chain/node/plugins/tokens/ownership" + "github.com/bnb-chain/node/plugins/tokens/seturi" + "github.com/bnb-chain/node/plugins/tokens/swap" + "github.com/bnb-chain/node/plugins/tokens/timelock" + cTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/gov" + oracleTypes "github.com/cosmos/cosmos-sdk/x/oracle/types" + "github.com/cosmos/cosmos-sdk/x/slashing" + stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" ) -// constants -const ( - DotBSuffix = ".B" - NativeToken = "BNB" - NativeTokenDotBSuffixed = "BNB" + DotBSuffix - Decimals int8 = 8 - MaxTotalSupply int64 = 9000000000000000000 // 90 billions with 8 decimal digits - - TokenSymbolMaxLen = 8 - TokenSymbolMinLen = 2 - TokenSymbolTxHashSuffixLen = 3 - - MiniTokenSymbolMaxLen = 8 - MiniTokenSymbolMinLen = 2 - MiniTokenSymbolSuffixLen = 4 - MiniTokenSymbolMSuffix = "M" - MiniTokenSymbolTxHashSuffixLen = 3 - MaxMiniTokenNameLength = 32 - MaxTokenURILength = 2048 +// Msg definition +type ( + SmartChainAddress = cTypes.SmartChainAddress + + // bridge module + BindMsg = bTypes.BindMsg + TransferOutMsg = bTypes.TransferOutMsg + UnbindMsg = bTypes.UnbindMsg + + // token module + TokenBurnMsg = burn.BurnMsg + DexListMsg = dexTypes.ListMsg + ListMiniMsg = dexTypes.ListMiniMsg + TokenFreezeMsg = freeze.FreezeMsg + TokenUnfreezeMsg = freeze.UnfreezeMsg + TokenIssueMsg = issue.IssueMsg + MiniTokenIssueMsg = issue.IssueMiniMsg + TinyTokenIssueMsg = issue.IssueTinyMsg + MintMsg = issue.MintMsg + SendMsg = bank.MsgSend + SetURIMsg = seturi.SetURIMsg + TimeLockMsg = timelock.TimeLockMsg + TimeRelockMsg = timelock.TimeRelockMsg + TimeUnlockMsg = timelock.TimeUnlockMsg + TransferOwnershipMsg = ownership.TransferOwnershipMsg + + // gov module + SubmitProposalMsg = gov.MsgSubmitProposal + DepositMsg = gov.MsgDeposit + VoteMsg = gov.MsgVote + SideChainSubmitProposalMsg = gov.MsgSideChainSubmitProposal + SideChainDepositMsg = gov.MsgSideChainDeposit + SideChainVoteMsg = gov.MsgSideChainVote + + // atomic swap module + HTLTMsg = swap.HTLTMsg + DepositHTLTMsg = swap.DepositHTLTMsg + ClaimHTLTMsg = swap.ClaimHTLTMsg + RefundHTLTMsg = swap.RefundHTLTMsg + + // oracle claim module + Claim = oracleTypes.Claim + ClaimMsg = oracleTypes.ClaimMsg + + // trade module + CreateOrderMsg = order.NewOrderMsg + CancelOrderMsg = order.CancelOrderMsg + + // account module + SetAccountFlagsMsg = account.SetAccountFlagsMsg + + // slash module + MsgSideChainUnjail = slashing.MsgSideChainUnjail + MsgUnjail = slashing.MsgUnjail + + // stake module + CreateSideChainValidatorMsg = stakeTypes.MsgCreateSideChainValidator + EditSideChainValidatorMsg = stakeTypes.MsgEditSideChainValidator + SideChainDelegateMsg = stakeTypes.MsgSideChainDelegate + SideChainRedelegateMsg = stakeTypes.MsgSideChainRedelegate + SideChainUndelegateMsg = stakeTypes.MsgSideChainUndelegate + MsgCreateValidatorOpen = stakeTypes.MsgCreateValidatorOpen + MsgRemoveValidator = stakeTypes.MsgRemoveValidator + MsgEditValidator = stakeTypes.MsgEditValidator + MsgDelegate = stakeTypes.MsgDelegate + MsgRedelegate = stakeTypes.MsgRedelegate + MsgUndelegate = stakeTypes.MsgUndelegate ) -// Msg - Transactions messages must fulfill the Msg -type Msg interface { - // Return the message type. - // Must be alphanumeric or empty. - Route() string - - // Returns a human-readable string for the message, intended for utilization - // within tags - Type() string - - // ValidateBasic does a simple validation check that - // doesn't require access to any other information. - ValidateBasic() error - - // Get the canonical byte representation of the Msg. - GetSignBytes() []byte - - // Signers returns the addrs of signers that must sign. - // CONTRACT: All signatures must be present to be valid. - // CONTRACT: Returns addrs in some deterministic order. - GetSigners() []types.AccAddress - - // Get involved addresses of this msg so that we can publish account balance change - GetInvolvedAddresses() []types.AccAddress -} - -// ValidateSymbol utility -func ValidateSymbol(symbol string) error { - if len(symbol) == 0 { - return errors.New("suffixed token symbol cannot be empty") - } - - // suffix exception for native token (less drama in existing tests) - if symbol == NativeToken || - symbol == NativeTokenDotBSuffixed { - return nil - } - - parts, err := splitSuffixedTokenSymbol(symbol) - if err != nil { - return err - } - - symbolPart := parts[0] - - // since the native token was given a suffix exception above, do not allow it to have a suffix - if symbolPart == NativeToken || - symbolPart == NativeTokenDotBSuffixed { - return errors.New("native token symbol should not be suffixed with tx hash") - } - - if strings.HasSuffix(symbolPart, DotBSuffix) { - symbolPart = strings.TrimSuffix(symbolPart, DotBSuffix) - } - - // check len without .B suffix - if len(symbolPart) < TokenSymbolMinLen { - return fmt.Errorf("token symbol part is too short, got %d chars", len(symbolPart)) - } - if len(symbolPart) > TokenSymbolMaxLen { - return fmt.Errorf("token symbol part is too long, got %d chars", len(symbolPart)) - } - - if !common.IsAlphaNum(symbolPart) { - return errors.New("token symbol part should be alphanumeric") - } - - txHashPart := parts[1] - - if len(txHashPart) != TokenSymbolTxHashSuffixLen { - return fmt.Errorf("token symbol tx hash suffix must be %d chars in length, got %d", TokenSymbolTxHashSuffixLen, len(txHashPart)) - } - - // prohibit non-hexadecimal chars in the suffix part - isHex, err := regexp.MatchString(fmt.Sprintf("[0-9A-F]{%d}", TokenSymbolTxHashSuffixLen), txHashPart) - if err != nil { - return err - } - if !isHex { - return fmt.Errorf("token symbol tx hash suffix must be hex with a length of %d", TokenSymbolTxHashSuffixLen) - } - - return nil -} - -func splitSuffixedTokenSymbol(suffixed string) ([]string, error) { - // as above, the native token symbol is given an exception - it is not required to be suffixed - if suffixed == NativeToken || - suffixed == NativeTokenDotBSuffixed { - return []string{suffixed, ""}, nil - } - - split := strings.SplitN(suffixed, "-", 2) - - if len(split) != 2 { - return nil, errors.New("suffixed token symbol must contain a hyphen ('-')") - } - - if strings.Contains(split[1], "-") { - return nil, errors.New("suffixed token symbol must contain just one hyphen ('-')") - } - - return split, nil -} - -type StatusText int - -const ( - PendingStatusText StatusText = iota - SuccessStatusText - FailedStatusText +var ( + NewSmartChainAddress = cTypes.NewSmartChainAddress + + // bridge module + NewBindMsg = bTypes.NewBindMsg + NewTransferOutMsg = bTypes.NewTransferOutMsg + NewUnbindMsg = bTypes.NewUnbindMsg + + // token module + NewTokenBurnMsg = burn.NewMsg + NewDexListMsg = dexTypes.NewListMsg + NewListMiniMsg = dexTypes.NewListMiniMsg + NewFreezeMsg = freeze.NewFreezeMsg + NewUnfreezeMsg = freeze.NewUnfreezeMsg + NewTokenIssueMsg = issue.NewIssueMsg + NewMiniTokenIssueMsg = issue.NewIssueMiniMsg + NewTinyTokenIssueMsg = issue.NewIssueTinyMsg + NewMintMsg = issue.NewMintMsg + NewMsgSend = bank.NewMsgSend + NewSetUriMsg = seturi.NewSetUriMsg + NewTimeLockMsg = timelock.NewTimeLockMsg + NewTimeRelockMsg = timelock.NewTimeRelockMsg + NewTimeUnlockMsg = timelock.NewTimeUnlockMsg + NewTransferOwnershipMsg = ownership.NewTransferOwnershipMsg + + // gov module + NewDepositMsg = gov.NewMsgDeposit + NewMsgVote = gov.NewMsgVote + NewMsgSubmitProposal = gov.NewMsgSubmitProposal + NewSideChainSubmitProposalMsg = gov.NewMsgSideChainSubmitProposal + NewSideChainDepositMsg = gov.NewMsgSideChainDeposit + NewSideChainVoteMsg = gov.NewMsgSideChainVote + + // atomic swap module + NewHTLTMsg = swap.NewHTLTMsg + NewDepositHTLTMsg = swap.NewDepositHTLTMsg + NewClaimHTLTMsg = swap.NewClaimHTLTMsg + NewRefundHTLTMsg = swap.NewRefundHTLTMsg + + // oracle claim module + NewClaim = oracleTypes.NewClaim + NewClaimMsg = oracleTypes.NewClaimMsg + + // trade module + NewCreateOrderMsg = order.NewNewOrderMsg + NewCancelOrderMsg = order.NewCancelOrderMsg + + // account module + NewSetAccountFlagsMsg = account.NewSetAccountFlagsMsg + + // slash module + NewMsgSideChainUnjail = slashing.NewMsgSideChainUnjail + NewMsgUnjail = slashing.NewMsgUnjail + + // stake module + NewCreateSideChainValidatorMsg = stakeTypes.NewMsgCreateSideChainValidator + NewMsgCreateSideChainValidatorOnBehalfOf = stakeTypes.NewMsgCreateSideChainValidatorOnBehalfOf + NewEditSideChainValidatorMsg = stakeTypes.NewMsgEditSideChainValidator + NewSideChainDelegateMsg = stakeTypes.NewMsgSideChainDelegate + NewSideChainRedelegateMsg = stakeTypes.NewMsgSideChainRedelegate + NewSideChainUndelegateMsg = stakeTypes.NewMsgSideChainUndelegate + NewMsgCreateValidatorOpen = stakeTypes.NewMsgRemoveValidator + NewMsgRemoveValidator = stakeTypes.NewMsgRemoveValidator + NewMsgEditValidator = stakeTypes.NewMsgEditValidator + NewMsgDelegate = stakeTypes.NewMsgDelegate + NewMsgRedelegate = stakeTypes.NewMsgRedelegate + NewMsgUndelegate = stakeTypes.NewMsgUndelegate ) - -var StatusTextToString = [...]string{"pending", "success", "failed"} -var StringToStatusText = map[string]StatusText{ - "pending": PendingStatusText, - "success": SuccessStatusText, - "failed": FailedStatusText, -} - -func (text StatusText) String() string { - return StatusTextToString[text] -} - -func (text StatusText) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf("\"%v\"", text.String())), nil -} - -func (text *StatusText) UnmarshalJSON(b []byte) error { - var j string - err := json.Unmarshal(b, &j) - if err != nil { - return err - } - stringKey, err := strconv.Unquote(string(b)) - if err != nil { - return err - } - // Note that if the string cannot be found then it will be set to the zero value, 'pending' in this case. - *text = StringToStatusText[stringKey] - return nil -} - -type Status struct { - Text StatusText `json:"text"` - FinalClaim string `json:"final_claim"` -} - -type Prophecy struct { - ID string `json:"id"` - Status Status `json:"status"` - - //WARNING: Mappings are nondeterministic in Amino, - // an so iterating over them could result in consensus failure. New code should not iterate over the below 2 mappings. - - //This is a mapping from a claim to the list of validators that made that claim. - ClaimValidators map[string][]types.ValAddress `json:"claim_validators"` - //This is a mapping from a validator bech32 address to their claim - ValidatorClaims map[string]string `json:"validator_claims"` -} - -// DBProphecy is what the prophecy becomes when being saved to the database. -// Tendermint/Amino does not support maps so we must serialize those variables into bytes. -type DBProphecy struct { - ID string `json:"id"` - Status Status `json:"status"` - ValidatorClaims []byte `json:"validator_claims"` -} - -// SerializeForDB serializes a prophecy into a DBProphecy -func (prophecy Prophecy) SerializeForDB() (DBProphecy, error) { - validatorClaims, err := json.Marshal(prophecy.ValidatorClaims) - if err != nil { - return DBProphecy{}, err - } - - return DBProphecy{ - ID: prophecy.ID, - Status: prophecy.Status, - ValidatorClaims: validatorClaims, - }, nil -} - -// DeserializeFromDB deserializes a DBProphecy into a prophecy -func (dbProphecy DBProphecy) DeserializeFromDB() (Prophecy, error) { - var validatorClaims map[string]string - if err := json.Unmarshal(dbProphecy.ValidatorClaims, &validatorClaims); err != nil { - return Prophecy{}, err - } - - var claimValidators = map[string][]types.ValAddress{} - for addr, claim := range validatorClaims { - valAddr, err := types.ValAddressFromBech32(addr) - if err != nil { - panic(fmt.Errorf("unmarshal validator address err, address=%s", addr)) - } - claimValidators[claim] = append(claimValidators[claim], valAddr) - } - - return Prophecy{ - ID: dbProphecy.ID, - Status: dbProphecy.Status, - ClaimValidators: claimValidators, - ValidatorClaims: validatorClaims, - }, nil -} - -type OracleRelayer struct { - Address types.ValAddress `json:"address"` - Power int64 `json:"power"` -} - -//Validate and check if it's mini token -func IsValidMiniTokenSymbol(symbol string) bool { - return ValidateMiniTokenSymbol(symbol) == nil -} - -func ValidateMiniTokenSymbol(symbol string) error { - if len(symbol) == 0 { - return errors.New("suffixed token symbol cannot be empty") - } - - parts, err := splitSuffixedTokenSymbol(symbol) - if err != nil { - return err - } - - symbolPart := parts[0] - - // check len without suffix - if len(symbolPart) < MiniTokenSymbolMinLen { - return fmt.Errorf("mini-token symbol part is too short, got %d chars", len(symbolPart)) - } - if len(symbolPart) > MiniTokenSymbolMaxLen { - return fmt.Errorf("mini-token symbol part is too long, got %d chars", len(symbolPart)) - } - - if !common.IsAlphaNum(symbolPart) { - return errors.New("mini-token symbol part should be alphanumeric") - } - - suffixPart := parts[1] - - if len(suffixPart) != MiniTokenSymbolSuffixLen { - return fmt.Errorf("mini-token symbol suffix must be %d chars in length, got %d", MiniTokenSymbolSuffixLen, len(suffixPart)) - } - - if suffixPart[len(suffixPart)-1:] != MiniTokenSymbolMSuffix { - return fmt.Errorf("mini-token symbol suffix must end with M") - } - - // prohibit non-hexadecimal chars in the suffix part - isHex, err := regexp.MatchString(fmt.Sprintf("[0-9A-F]{%d}M", MiniTokenSymbolTxHashSuffixLen), suffixPart) - if err != nil { - return err - } - if !isHex { - return fmt.Errorf("mini-token symbol tx hash suffix must be hex with a length of %d", MiniTokenSymbolTxHashSuffixLen) - } - - return nil -} diff --git a/types/msg/types.go b/types/msg/types.go new file mode 100644 index 00000000..5c02cc80 --- /dev/null +++ b/types/msg/types.go @@ -0,0 +1,216 @@ +package msg + +import ( + "math/big" + + sdk "github.com/bnb-chain/go-sdk/common/types" + bridgeTypes "github.com/bnb-chain/node/plugins/bridge/types" + "github.com/bnb-chain/node/plugins/dex/order" + cTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/ibc" + oracleTypes "github.com/cosmos/cosmos-sdk/x/oracle/types" + paramHubTypes "github.com/cosmos/cosmos-sdk/x/paramHub/types" + sidechainTypes "github.com/cosmos/cosmos-sdk/x/sidechain/types" + slashingTypes "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/stake" + crossStake "github.com/cosmos/cosmos-sdk/x/stake/cross_stake" + stakeTypes "github.com/cosmos/cosmos-sdk/x/stake/types" +) + +type ( + Msg = cTypes.Msg +) + +// =================== gov module ==================== +const ( + OptionEmpty = gov.OptionEmpty + OptionYes = gov.OptionYes + OptionAbstain = gov.OptionAbstain + OptionNo = gov.OptionNo + OptionNoWithVeto = gov.OptionNoWithVeto + + ProposalTypeNil = gov.ProposalTypeNil + ProposalTypeText = gov.ProposalTypeText + ProposalTypeParameterChange = gov.ProposalTypeParameterChange + ProposalTypeSoftwareUpgrade = gov.ProposalTypeSoftwareUpgrade + ProposalTypeListTradingPair = gov.ProposalTypeListTradingPair + ProposalTypeFeeChange = gov.ProposalTypeFeeChange + + ProposalTypeSCParamsChange = gov.ProposalTypeSCParamsChange + ProposalTypeCSCParamsChange = gov.ProposalTypeCSCParamsChange +) + +type ( + VoteOption = gov.VoteOption + ProposalKind = gov.ProposalKind + + ListTradingPairParams = gov.ListTradingPairParams +) + +type ( + SCParam = paramHubTypes.SCParam + SCChangeParams = paramHubTypes.SCChangeParams + CSCParamChange = paramHubTypes.CSCParamChange + IbcParams = ibc.Params + OracleParams = oracleTypes.Params + SlashParams = slashingTypes.Params + StakeParams = stake.Params +) + +// =================== trade module ==================== +var ( + OrderSide = order.Side + GenerateOrderID = order.GenerateOrderID +) + +// =================== oracle module ==================== +const ( + OracleChannelId = oracleTypes.RelayPackagesChannelId + PackageHeaderLength = sidechainTypes.PackageHeaderLength + + SynCrossChainPackageType = cTypes.SynCrossChainPackageType + AckCrossChainPackageType = cTypes.AckCrossChainPackageType + FailAckCrossChainPackageType = cTypes.FailAckCrossChainPackageType +) + +var ( + GetClaimId = oracleTypes.GetClaimId + DecodePackageHeader = sidechainTypes.DecodePackageHeader +) + +type ( + Package = oracleTypes.Package + Packages = oracleTypes.Packages + + CrossChainPackageType = cTypes.CrossChainPackageType +) + +type ( + Status = oracleTypes.Status + Prophecy = oracleTypes.Prophecy + DBProphecy = oracleTypes.DBProphecy + OracleRelayer = stakeTypes.OracleRelayer +) + +type ( + ApproveBindSynPackage = bridgeTypes.ApproveBindSynPackage + BindSynPackage = bridgeTypes.BindSynPackage + TransferOutRefundPackage = bridgeTypes.TransferOutRefundPackage + TransferOutSynPackage = bridgeTypes.TransferOutSynPackage + TransferInSynPackage = bridgeTypes.TransferInSynPackage + MirrorSynPackage = bridgeTypes.MirrorSynPackage + MirrorSyncSynPackage = bridgeTypes.MirrorSyncSynPackage + CommonAckPackage = sidechainTypes.CommonAckPackage + IbcValidatorSetPackage = stakeTypes.IbcValidatorSetPackage + IbcValidator = stakeTypes.IbcValidator + CrossParamChange = paramHubTypes.CSCParamChange + SideDowntimeSlashPackage = slashingTypes.SideDowntimeSlashPackage + CrossStakeSynPackageFromBSC = crossStake.CrossStakeSynPackageFromBSC + CrossStakeRefundPackage = stakeTypes.CrossStakeRefundPackage +) + +type CrossChainPackage struct { + PackageType CrossChainPackageType + RelayFee big.Int + Content interface{} +} + +// package type +var protoMetrics = map[sdk.IbcChannelID]map[CrossChainPackageType]func() interface{}{ + sdk.IbcChannelID(1): { + SynCrossChainPackageType: func() interface{} { + return new(ApproveBindSynPackage) + }, + AckCrossChainPackageType: noneExistPackageProto, + FailAckCrossChainPackageType: func() interface{} { + return new(BindSynPackage) + }, + }, + sdk.IbcChannelID(2): { + SynCrossChainPackageType: noneExistPackageProto, + AckCrossChainPackageType: func() interface{} { + return new(TransferOutRefundPackage) + }, + FailAckCrossChainPackageType: func() interface{} { + return new(TransferOutSynPackage) + }, + }, + sdk.IbcChannelID(3): { + SynCrossChainPackageType: func() interface{} { + return new(TransferInSynPackage) + }, + AckCrossChainPackageType: noneExistPackageProto, + FailAckCrossChainPackageType: noneExistPackageProto, + }, + sdk.IbcChannelID(4): { + SynCrossChainPackageType: func() interface{} { + return new(MirrorSynPackage) + }, + AckCrossChainPackageType: noneExistPackageProto, + FailAckCrossChainPackageType: noneExistPackageProto, + }, + sdk.IbcChannelID(5): { + SynCrossChainPackageType: func() interface{} { + return new(MirrorSyncSynPackage) + }, + AckCrossChainPackageType: noneExistPackageProto, + FailAckCrossChainPackageType: noneExistPackageProto, + }, + sdk.IbcChannelID(8): { + SynCrossChainPackageType: noneExistPackageProto, + AckCrossChainPackageType: func() interface{} { + return new(CommonAckPackage) + }, + FailAckCrossChainPackageType: func() interface{} { + return new(IbcValidatorSetPackage) + }, + }, + sdk.IbcChannelID(9): { + SynCrossChainPackageType: noneExistPackageProto, + AckCrossChainPackageType: func() interface{} { + return new(CommonAckPackage) + }, + FailAckCrossChainPackageType: func() interface{} { + return new(CrossParamChange) + }, + }, + sdk.IbcChannelID(11): { + SynCrossChainPackageType: func() interface{} { + return new(SideDowntimeSlashPackage) + }, + AckCrossChainPackageType: noneExistPackageProto, + FailAckCrossChainPackageType: noneExistPackageProto, + }, + sdk.IbcChannelID(16): { + SynCrossChainPackageType: func() interface{} { + return new(CrossStakeSynPackageFromBSC) + }, + AckCrossChainPackageType: func() interface{} { + return new(CrossStakeRefundPackage) + }, + FailAckCrossChainPackageType: noneExistPackageProto, + }, +} + +// =================== bank module ==================== +type ( + Input = bank.Input + Output = bank.Output +) + +var ( + NewInput = bank.NewInput + NewOutput = bank.NewOutput +) + +type Transfer struct { + ToAddr cTypes.AccAddress + Coins cTypes.Coins +} + +// =================== staking module ==================== +type ( + Description = stakeTypes.Description +) diff --git a/types/msg/utils.go b/types/msg/utils.go index a957efd3..691974af 100644 --- a/types/msg/utils.go +++ b/types/msg/utils.go @@ -1,102 +1,70 @@ package msg import ( - "encoding/binary" - "encoding/hex" - "encoding/json" - "strings" + "fmt" + "github.com/cosmos/cosmos-sdk/bsc/rlp" - "golang.org/x/crypto/sha3" - - "github.com/pkg/errors" - "github.com/tendermint/tendermint/crypto/tmhash" + "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/node/plugins/tokens/swap" + cTypes "github.com/cosmos/cosmos-sdk/types" +) - "github.com/binance-chain/go-sdk/common/types" +var ( + SortJSON = cTypes.SortJSON + MustSortJSON = cTypes.MustSortJSON + CalculateRandomHash = swap.CalculateRandomHash + CalculateSwapID = swap.CalculateSwapID + HexAddress = cTypes.HexAddress + HexEncode = cTypes.HexEncode + HexDecode = cTypes.HexDecode + Has0xPrefix = cTypes.Has0xPrefix ) -// SortJSON takes any JSON and returns it sorted by keys. Also, all white-spaces -// are removed. -// This method can be used to canonicalize JSON to be returned by GetSignBytes, -// e.g. for the ledger integration. -// If the passed JSON isn't valid it will return an error. -func SortJSON(toSortJSON []byte) ([]byte, error) { - var c interface{} - err := json.Unmarshal(toSortJSON, &c) - if err != nil { - return nil, err - } - js, err := json.Marshal(c) - if err != nil { - return nil, err - } - return js, nil +func noneExistPackageProto() interface{} { + panic("should not exist such package") } -// MustSortJSON is like SortJSON but panic if an error occurs, e.g., if -// the passed JSON isn't valid. -func MustSortJSON(toSortJSON []byte) []byte { - js, err := SortJSON(toSortJSON) +func ParseClaimPayload(payload []byte) ([]CrossChainPackage, error) { + packages := Packages{} + err := rlp.DecodeBytes(payload, &packages) if err != nil { - panic(err) - } - return js -} - -func CalculateRandomHash(randomNumber []byte, timestamp int64) []byte { - data := make([]byte, RandomNumberLength+Int64Size) - copy(data[:RandomNumberLength], randomNumber) - binary.BigEndian.PutUint64(data[RandomNumberLength:], uint64(timestamp)) - return tmhash.Sum(data) -} - -func CalculateSwapID(randomNumberHash []byte, sender types.AccAddress, senderOtherChain string) []byte { - senderOtherChain = strings.ToLower(senderOtherChain) - data := randomNumberHash - data = append(data, []byte(sender)...) - data = append(data, []byte(senderOtherChain)...) - return tmhash.Sum(data) -} - -func HexAddress(a []byte) string { - if len(a) == 0 { - return "" + return nil, err } - unchecksummed := hex.EncodeToString(a[:]) - sha := sha3.NewLegacyKeccak256() - sha.Write([]byte(unchecksummed)) - hash := sha.Sum(nil) - - result := []byte(unchecksummed) - for i := 0; i < len(result); i++ { - hashByte := hash[i/2] - if i%2 == 0 { - hashByte = hashByte >> 4 - } else { - hashByte &= 0xf + decodedPackage := make([]CrossChainPackage, 0, len(packages)) + for _, pack := range packages { + ptype, relayerFee, err := DecodePackageHeader(pack.Payload) + if err != nil { + return nil, err } - if result[i] > '9' && hashByte > 7 { - result[i] -= 32 + if _, exist := protoMetrics[pack.ChannelId]; !exist { + return nil, fmt.Errorf("channnel id do not exist") } + proto, exist := protoMetrics[pack.ChannelId][ptype] + if !exist || proto == nil { + return nil, fmt.Errorf("package type do not exist") + } + content := proto() + err = rlp.DecodeBytes(pack.Payload[PackageHeaderLength:], content) + if err != nil { + return nil, err + } + decodedPackage = append(decodedPackage, CrossChainPackage{ + PackageType: ptype, + RelayFee: relayerFee, + Content: content, + }) } - return "0x" + string(result) + return decodedPackage, nil } -func HexEncode(b []byte) string { - enc := make([]byte, len(b)*2+2) - copy(enc, "0x") - hex.Encode(enc[2:], b) - return string(enc) -} +func CreateSendMsg(from types.AccAddress, fromCoins types.Coins, transfers []Transfer) SendMsg { + input := NewInput(from, fromCoins) -// Decode decodes a hex string with 0x prefix. -func HexDecode(input string) ([]byte, error) { - if !Has0xPrefix(input) { - return nil, errors.New("hex string must have 0x prefix") + output := make([]Output, 0, len(transfers)) + for _, t := range transfers { + t.Coins = t.Coins.Sort() + output = append(output, NewOutput(t.ToAddr, t.Coins)) } - return hex.DecodeString(input[2:]) -} - -// has0xPrefix validates str begins with '0x' or '0X'. -func Has0xPrefix(input string) bool { - return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X') + msg := NewMsgSend([]Input{input}, output) + return msg } diff --git a/types/tx/option.go b/types/tx/option.go index 1f5ea734..31e43e33 100644 --- a/types/tx/option.go +++ b/types/tx/option.go @@ -1,6 +1,6 @@ package tx -type Option func(*StdSignMsg) *StdSignMsg +type Option func(msg *StdSignMsg) *StdSignMsg func WithSource(source int64) Option { return func(txMsg *StdSignMsg) *StdSignMsg { diff --git a/types/tx/stdsign.go b/types/tx/stdsign.go deleted file mode 100644 index 5c56b264..00000000 --- a/types/tx/stdsign.go +++ /dev/null @@ -1,64 +0,0 @@ -package tx - -import ( - "encoding/json" - - "github.com/binance-chain/go-sdk/types/msg" - "github.com/tendermint/tendermint/crypto" -) - -// StdSignDoc def -type StdSignDoc struct { - ChainID string `json:"chain_id"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` - Memo string `json:"memo"` - Source int64 `json:"source"` - Msgs []json.RawMessage `json:"msgs"` - Data []byte `json:"data"` -} - -// StdSignMsg def -type StdSignMsg struct { - ChainID string `json:"chain_id"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` - Msgs []msg.Msg `json:"msgs"` - Memo string `json:"memo"` - Source int64 `json:"source"` - Data []byte `json:"data"` -} - -// StdSignature Signature -type StdSignature struct { - crypto.PubKey `json:"pub_key"` // optional - Signature []byte `json:"signature"` - AccountNumber int64 `json:"account_number"` - Sequence int64 `json:"sequence"` -} - -// Bytes gets message bytes -func (msg StdSignMsg) Bytes() []byte { - return StdSignBytes(msg.ChainID, msg.AccountNumber, msg.Sequence, msg.Msgs, msg.Memo, msg.Source, msg.Data) -} - -// StdSignBytes returns the bytes to sign for a transaction. -func StdSignBytes(chainID string, accnum int64, sequence int64, msgs []msg.Msg, memo string, source int64, data []byte) []byte { - var msgsBytes []json.RawMessage - for _, msg := range msgs { - msgsBytes = append(msgsBytes, json.RawMessage(msg.GetSignBytes())) - } - bz, err := Cdc.MarshalJSON(StdSignDoc{ - AccountNumber: accnum, - ChainID: chainID, - Memo: memo, - Msgs: msgsBytes, - Sequence: sequence, - Source: source, - Data: data, - }) - if err != nil { - panic(err) - } - return msg.MustSortJSON(bz) -} diff --git a/types/tx/stdtx.go b/types/tx/stdtx.go index 1bcd3c6a..92f53e1a 100644 --- a/types/tx/stdtx.go +++ b/types/tx/stdtx.go @@ -1,36 +1,22 @@ package tx import ( - "github.com/binance-chain/go-sdk/types/msg" + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + context "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder" ) const Source int64 = 0 -type Tx interface { - - // Gets the Msg. - GetMsgs() []msg.Msg -} - -// StdTx def -type StdTx struct { - Msgs []msg.Msg `json:"msg"` - Signatures []StdSignature `json:"signatures"` - Memo string `json:"memo"` - Source int64 `json:"source"` - Data []byte `json:"data"` -} - -// NewStdTx to instantiate an instance -func NewStdTx(msgs []msg.Msg, sigs []StdSignature, memo string, source int64, data []byte) StdTx { - return StdTx{ - Msgs: msgs, - Signatures: sigs, - Memo: memo, - Source: source, - Data: data, - } -} +type ( + Tx = types.Tx + StdTx = auth.StdTx + StdSignDoc = auth.StdSignDoc + StdSignature = auth.StdSignature + StdSignMsg = context.StdSignMsg +) -// GetMsgs def -func (tx StdTx) GetMsgs() []msg.Msg { return tx.Msgs } +var ( + StdSignBytes = auth.StdSignBytes + NewStdTx = auth.NewStdTx +) diff --git a/types/tx/wire.go b/types/tx/wire.go index 514c5da2..827e6e67 100644 --- a/types/tx/wire.go +++ b/types/tx/wire.go @@ -2,9 +2,9 @@ package tx import ( "github.com/tendermint/go-amino" - "github.com/tendermint/tendermint/crypto/encoding/amino" + cryptoAmino "github.com/tendermint/tendermint/crypto/encoding/amino" - "github.com/binance-chain/go-sdk/types/msg" + "github.com/bnb-chain/go-sdk/types/msg" ) // cdc global variable diff --git a/types/wire.go b/types/wire.go index 54ff5517..74a7dca9 100644 --- a/types/wire.go +++ b/types/wire.go @@ -1,8 +1,8 @@ package types import ( - ntypes "github.com/binance-chain/go-sdk/common/types" - "github.com/binance-chain/go-sdk/types/tx" + ntypes "github.com/bnb-chain/go-sdk/common/types" + "github.com/bnb-chain/go-sdk/types/tx" "github.com/tendermint/go-amino" types "github.com/tendermint/tendermint/rpc/core/types" )