Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da982a949d |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016-2019 LBRY Inc
|
||||
Copyright (c) 2016-2018 LBRY Inc
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ package bits
|
||||
import (
|
||||
"math/big"
|
||||
|
||||
"github.com/lbryio/lbry.go/extras/errors"
|
||||
"github.com/lbryio/errors.go"
|
||||
)
|
||||
|
||||
// Range has a start and end
|
||||
|
||||
+9
-24
@@ -113,17 +113,21 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var trace []string
|
||||
if TraceEnabled && errors.HasTrace(rsp.Error) {
|
||||
trace = getTraceFromError(rsp.Error)
|
||||
trace = strings.Split(errors.Trace(rsp.Error), "\n")
|
||||
for index, element := range trace {
|
||||
if strings.HasPrefix(element, "\t") {
|
||||
trace[index] = strings.Replace(element, "\t", " ", 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// http://choly.ca/post/go-json-marshalling/
|
||||
type apiResponse struct {
|
||||
jsonResponse, err := json.MarshalIndent(&struct {
|
||||
Success bool `json:"success"`
|
||||
Error *string `json:"error"`
|
||||
Data interface{} `json:"data"`
|
||||
Trace []string `json:"_trace,omitempty"`
|
||||
}
|
||||
jsonResponse, err := json.MarshalIndent(&apiResponse{
|
||||
}{
|
||||
Success: success,
|
||||
Error: errorString,
|
||||
Data: rsp.Data,
|
||||
@@ -131,29 +135,10 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}, "", " ")
|
||||
if err != nil {
|
||||
Log(r, &rsp, errors.Prefix("Error encoding JSON response: ", err))
|
||||
jsonResponse, err = json.MarshalIndent(&apiResponse{
|
||||
Success: false,
|
||||
Error: util.PtrToString(err.Error()),
|
||||
Data: nil,
|
||||
Trace: getTraceFromError(err),
|
||||
}, "", " ")
|
||||
if err != nil {
|
||||
Log(r, &rsp, errors.Prefix("Error encoding JSON response: ", err))
|
||||
}
|
||||
}
|
||||
|
||||
w.WriteHeader(rsp.Status)
|
||||
_, _ = w.Write(jsonResponse)
|
||||
}
|
||||
|
||||
func getTraceFromError(err error) []string {
|
||||
trace := strings.Split(errors.Trace(err), "\n")
|
||||
for index, element := range trace {
|
||||
if strings.HasPrefix(element, "\t") {
|
||||
trace[index] = strings.Replace(element, "\t", " ", 1)
|
||||
}
|
||||
}
|
||||
return trace
|
||||
w.Write(jsonResponse)
|
||||
}
|
||||
|
||||
// IgnoredFormFields are ignored by FormValues() when checking for extraneous fields
|
||||
|
||||
+23
-189
@@ -10,8 +10,9 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/structs"
|
||||
"github.com/lbryio/lbry.go/extras/errors"
|
||||
|
||||
"github.com/fatih/structs"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/shopspring/decimal"
|
||||
log "github.com/sirupsen/logrus"
|
||||
@@ -137,17 +138,11 @@ func (d *Client) SetRPCTimeout(timeout time.Duration) {
|
||||
//============================================
|
||||
// NEW SDK
|
||||
//============================================
|
||||
|
||||
func (d *Client) AccountList() (*AccountListResponse, error) {
|
||||
response := new(AccountListResponse)
|
||||
return response, d.call(response, "account_list", map[string]interface{}{})
|
||||
}
|
||||
|
||||
func (d *Client) AccountListForWallet(walletID string) (*AccountListResponse, error) {
|
||||
response := new(AccountListResponse)
|
||||
return response, d.call(response, "account_list", map[string]interface{}{"wallet_id": walletID})
|
||||
}
|
||||
|
||||
func (d *Client) SingleAccountList(accountID string) (*Account, error) {
|
||||
response := new(Account)
|
||||
return response, d.call(response, "account_list", map[string]interface{}{"account_id": accountID})
|
||||
@@ -195,16 +190,16 @@ func (d *Client) AccountFund(fromAccount string, toAccount string, amount string
|
||||
})
|
||||
}
|
||||
|
||||
func (d *Client) AccountCreate(accountName string, singleKey bool) (*Account, error) {
|
||||
response := new(Account)
|
||||
func (d *Client) AccountCreate(accountName string, singleKey bool) (*AccountCreateResponse, error) {
|
||||
response := new(AccountCreateResponse)
|
||||
return response, d.call(response, "account_create", map[string]interface{}{
|
||||
"account_name": accountName,
|
||||
"single_key": singleKey,
|
||||
})
|
||||
}
|
||||
|
||||
func (d *Client) AccountRemove(accountID string) (*Account, error) {
|
||||
response := new(Account)
|
||||
func (d *Client) AccountRemove(accountID string) (*AccountRemoveResponse, error) {
|
||||
response := new(AccountRemoveResponse)
|
||||
return response, d.call(response, "account_remove", map[string]interface{}{
|
||||
"account_id": accountID,
|
||||
})
|
||||
@@ -217,7 +212,7 @@ func (d *Client) AddressUnused(account *string) (*AddressUnusedResponse, error)
|
||||
})
|
||||
}
|
||||
|
||||
func (d *Client) ChannelList(account *string, page uint64, pageSize uint64, wid *string) (*ChannelListResponse, error) {
|
||||
func (d *Client) ChannelList(account *string, page uint64, pageSize uint64) (*ChannelListResponse, error) {
|
||||
if page == 0 {
|
||||
return nil, errors.Err("pages start from 1")
|
||||
}
|
||||
@@ -227,7 +222,6 @@ func (d *Client) ChannelList(account *string, page uint64, pageSize uint64, wid
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
"include_protobuf": true,
|
||||
"wallet_id": wid,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -265,7 +259,6 @@ type ChannelCreateOptions struct {
|
||||
WebsiteURL *string `json:"website_url,omitempty"`
|
||||
CoverURL *string `json:"cover_url,omitempty"`
|
||||
Featured []string `json:"featured,omitempty"`
|
||||
AccountID *string `json:"account_id,omitempty"`
|
||||
}
|
||||
|
||||
func (d *Client) ChannelCreate(name string, bid float64, options ChannelCreateOptions) (*TransactionSummary, error) {
|
||||
@@ -290,12 +283,11 @@ func (d *Client) ChannelCreate(name string, bid float64, options ChannelCreateOp
|
||||
|
||||
type ChannelUpdateOptions struct {
|
||||
ChannelCreateOptions `json:",flatten"`
|
||||
NewSigningKey *bool `json:"new_signing_key,omitempty"`
|
||||
ClearFeatured *bool `json:"clear_featured,omitempty"`
|
||||
ClearTags *bool `json:"clear_tags,omitempty"`
|
||||
ClearLanguages *bool `json:"clear_languages,omitempty"`
|
||||
ClearLocations *bool `json:"clear_locations,omitempty"`
|
||||
Bid *string `json:"bid,omitempty"`
|
||||
NewSigningKey *bool `json:"new_signing_key,omitempty"`
|
||||
ClearFeatured *bool `json:"clear_featured,omitempty"`
|
||||
ClearTags *bool `json:"clear_tags,omitempty"`
|
||||
ClearLanguages *bool `json:"clear_languages,omitempty"`
|
||||
ClearLocations *bool `json:"clear_locations,omitempty"`
|
||||
}
|
||||
|
||||
func (d *Client) ChannelUpdate(claimID string, options ChannelUpdateOptions) (*TransactionSummary, error) {
|
||||
@@ -331,7 +323,6 @@ type StreamCreateOptions struct {
|
||||
ChannelName *string `json:"channel_name,omitempty"`
|
||||
ChannelID *string `json:"channel_id,omitempty"`
|
||||
ChannelAccountID *string `json:"channel_account_id,omitempty"`
|
||||
AccountID *string `json:"account_id,omitempty"`
|
||||
}
|
||||
|
||||
func (d *Client) StreamCreate(name, filePath string, bid float64, options StreamCreateOptions) (*TransactionSummary, error) {
|
||||
@@ -415,30 +406,11 @@ func (d *Client) ChannelAbandon(txID string, nOut uint64, accountID *string, blo
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (d *Client) AddressList(account *string, address *string) (*AddressListResponse, error) {
|
||||
func (d *Client) AddressList(account *string) (*AddressListResponse, error) {
|
||||
response := new(AddressListResponse)
|
||||
|
||||
args := struct {
|
||||
AccountID *string `json:"account_id,omitempty"`
|
||||
Address *string `json:"address,omitempty"`
|
||||
}{
|
||||
AccountID: account,
|
||||
Address: address,
|
||||
}
|
||||
structs.DefaultTagName = "json"
|
||||
return response, d.call(response, "address_list", structs.Map(args))
|
||||
}
|
||||
|
||||
func (d *Client) StreamList(account *string) (*StreamListResponse, error) {
|
||||
response := new(StreamListResponse)
|
||||
err := d.call(response, "stream_list", map[string]interface{}{
|
||||
"account_id": account,
|
||||
"include_protobuf": true,
|
||||
return response, d.call(response, "address_list", map[string]interface{}{
|
||||
"account_id": account,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (d *Client) ClaimList(account *string, page uint64, pageSize uint64) (*ClaimListResponse, error) {
|
||||
@@ -463,13 +435,6 @@ func (d *Client) Status() (*StatusResponse, error) {
|
||||
return response, d.call(response, "status", map[string]interface{}{})
|
||||
}
|
||||
|
||||
func (d *Client) TransactionList(account *string) (*TransactionListResponse, error) {
|
||||
response := new(TransactionListResponse)
|
||||
return response, d.call(response, "transaction_list", map[string]interface{}{
|
||||
"account_id": account,
|
||||
})
|
||||
}
|
||||
|
||||
func (d *Client) UTXOList(account *string) (*UTXOListResponse, error) {
|
||||
response := new(UTXOListResponse)
|
||||
return response, d.call(response, "utxo_list", map[string]interface{}{
|
||||
@@ -477,13 +442,6 @@ func (d *Client) UTXOList(account *string) (*UTXOListResponse, error) {
|
||||
})
|
||||
}
|
||||
|
||||
func (d *Client) UTXORelease(account *string) (*UTXOReleaseResponse, error) {
|
||||
response := new(UTXOReleaseResponse)
|
||||
return response, d.call(response, "utxo_release", map[string]interface{}{
|
||||
"account_id": account,
|
||||
})
|
||||
}
|
||||
|
||||
func (d *Client) Get(uri string) (*GetResponse, error) {
|
||||
response := new(GetResponse)
|
||||
return response, d.call(response, "get", map[string]interface{}{
|
||||
@@ -515,17 +473,15 @@ func (d *Client) Resolve(urls string) (*ResolveResponse, error) {
|
||||
func (d *Client) ClaimSearch(claimName, claimID, txid *string, nout *uint) (*ClaimSearchResponse, error) {
|
||||
response := new(ClaimSearchResponse)
|
||||
args := struct {
|
||||
ClaimID *string `json:"claim_id,omitempty"`
|
||||
TXID *string `json:"txid,omitempty"`
|
||||
Nout *uint `json:"nout,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
IncludeProtobuf bool `json:"include_protobuf"`
|
||||
ClaimID *string `json:"claim_id,omitempty"`
|
||||
TXID *string `json:"txid,omitempty"`
|
||||
Nout *uint `json:"nout,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
}{
|
||||
ClaimID: claimID,
|
||||
TXID: txid,
|
||||
Nout: nout,
|
||||
Name: claimName,
|
||||
IncludeProtobuf: true,
|
||||
ClaimID: claimID,
|
||||
TXID: txid,
|
||||
Nout: nout,
|
||||
Name: claimName,
|
||||
}
|
||||
structs.DefaultTagName = "json"
|
||||
return response, d.call(response, "claim_search", structs.Map(args))
|
||||
@@ -539,125 +495,3 @@ func (d *Client) ChannelExport(channelClaimID string, channelName, accountID *st
|
||||
"account_id": accountID,
|
||||
})
|
||||
}
|
||||
|
||||
func (d *Client) ChannelImport(key string, walletID *string) (*ChannelImportResponse, error) {
|
||||
response := new(ChannelImportResponse)
|
||||
return response, d.call(response, "channel_import", map[string]interface{}{
|
||||
"channel_data": key,
|
||||
"wallet_id": walletID,
|
||||
})
|
||||
}
|
||||
|
||||
func (d *Client) SupportList(accountID *string, page uint64, pageSize uint64) (*SupportListResponse, error) {
|
||||
response := new(SupportListResponse)
|
||||
return response, d.call(response, "support_list", map[string]interface{}{
|
||||
"account_id": accountID,
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
})
|
||||
}
|
||||
|
||||
func (d *Client) SupportCreate(claimID string, amount string, tip *bool, accountID *string, fundingAccountIDs []string) (*TransactionSummary, error) {
|
||||
response := new(TransactionSummary)
|
||||
args := struct {
|
||||
ClaimID string `json:"claim_id"`
|
||||
Amount string `json:"amount"`
|
||||
Tip *bool `json:"tip,omitempty"`
|
||||
AccountID *string `json:"account_id,omitempty"`
|
||||
FundingAccountIDs []string `json:"funding_account_ids,omitempty"`
|
||||
Preview bool `json:"preview,omitempty"`
|
||||
Blocking bool `json:"blocking,omitempty"`
|
||||
}{
|
||||
ClaimID: claimID,
|
||||
AccountID: accountID,
|
||||
Blocking: true,
|
||||
Amount: amount,
|
||||
FundingAccountIDs: fundingAccountIDs,
|
||||
Preview: false,
|
||||
Tip: tip,
|
||||
}
|
||||
structs.DefaultTagName = "json"
|
||||
return response, d.call(response, "support_create", structs.Map(args))
|
||||
}
|
||||
|
||||
func (d *Client) SupportAbandon(claimID *string, txid *string, nout *uint, keep *string, accountID *string) (*TransactionSummary, error) {
|
||||
if claimID == nil && (txid == nil || nout == nil) {
|
||||
return nil, errors.Err("either claimID or txid+nout must be supplied")
|
||||
}
|
||||
response := new(TransactionSummary)
|
||||
args := struct {
|
||||
ClaimID *string `json:"claim_id,omitempty"`
|
||||
TxID *string `json:"claim_id,omitempty"`
|
||||
Nout *uint `json:"nout,omitempty"`
|
||||
AccountID *string `json:"account_id,omitempty"`
|
||||
Preview bool `json:"preview,omitempty"`
|
||||
Blocking bool `json:"blocking,omitempty"`
|
||||
}{
|
||||
ClaimID: claimID,
|
||||
AccountID: accountID,
|
||||
Nout: nout,
|
||||
TxID: txid,
|
||||
Blocking: true,
|
||||
Preview: false,
|
||||
}
|
||||
structs.DefaultTagName = "json"
|
||||
return response, d.call(response, "support_abandon", structs.Map(args))
|
||||
}
|
||||
|
||||
func (d *Client) AccountAdd(accountName string, seed *string, privateKey *string, publicKey *string, singleKey *bool, walletID *string) (*Account, error) {
|
||||
response := new(Account)
|
||||
|
||||
args := struct {
|
||||
AccountName string `json:"account_name"`
|
||||
Seed *string `json:"seed,omitempty"`
|
||||
PrivateKey *string `json:"private_key,omitempty"`
|
||||
PublicKey *string `json:"public_key,omitempty"`
|
||||
SingleKey *bool `json:"single_key,omitempty"`
|
||||
WalletID *string `json:"wallet_id,omitempty"`
|
||||
}{
|
||||
AccountName: accountName,
|
||||
Seed: seed,
|
||||
PrivateKey: privateKey,
|
||||
PublicKey: publicKey,
|
||||
SingleKey: singleKey,
|
||||
WalletID: walletID,
|
||||
}
|
||||
structs.DefaultTagName = "json"
|
||||
return response, d.call(response, "account_add", structs.Map(args))
|
||||
}
|
||||
|
||||
type WalletCreateOpts struct {
|
||||
ID string `json:"wallet_id"`
|
||||
SkipOnStartup bool `json:"skip_on_startup,omitempty"`
|
||||
CreateAccount bool `json:"create_account,omitempty"`
|
||||
SingleKey bool `json:"single_key,omitempty"`
|
||||
}
|
||||
|
||||
func (d *Client) WalletCreate(id string, opts *WalletCreateOpts) (*Wallet, error) {
|
||||
response := new(Wallet)
|
||||
if opts == nil {
|
||||
opts = &WalletCreateOpts{}
|
||||
}
|
||||
opts.ID = id
|
||||
structs.DefaultTagName = "json"
|
||||
return response, d.call(response, "wallet_create", structs.Map(opts))
|
||||
}
|
||||
|
||||
func (d *Client) WalletAdd(id string) (*Wallet, error) {
|
||||
response := new(Wallet)
|
||||
return response, d.call(response, "wallet_add", map[string]interface{}{"wallet_id": id})
|
||||
}
|
||||
|
||||
func (d *Client) WalletList(id string) (*WalletList, error) {
|
||||
response := new(WalletList)
|
||||
params := map[string]interface{}{}
|
||||
if id != "" {
|
||||
params["wallet_id"] = id
|
||||
}
|
||||
return response, d.call(response, "wallet_list", params)
|
||||
}
|
||||
|
||||
func (d *Client) WalletRemove(id string) (*Wallet, error) {
|
||||
response := new(Wallet)
|
||||
return response, d.call(response, "wallet_remove", map[string]interface{}{"wallet_id": id})
|
||||
}
|
||||
+43
-312
@@ -3,7 +3,6 @@ package jsonrpc
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -12,8 +11,6 @@ import (
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
|
||||
"github.com/lbryio/lbry.go/extras/errors"
|
||||
|
||||
"github.com/lbryio/lbry.go/extras/util"
|
||||
)
|
||||
|
||||
@@ -22,12 +19,6 @@ func prettyPrint(i interface{}) {
|
||||
fmt.Println(string(s))
|
||||
}
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
code := m.Run()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func TestClient_AccountFund(t *testing.T) {
|
||||
d := NewClient("")
|
||||
accounts, err := d.AccountList()
|
||||
@@ -41,7 +32,7 @@ func TestClient_AccountFund(t *testing.T) {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
balance, err := strconv.ParseFloat(balanceString.Available.String(), 64)
|
||||
balance, err := strconv.ParseFloat(string(*balanceString), 64)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
@@ -66,20 +57,17 @@ func TestClient_AccountList(t *testing.T) {
|
||||
|
||||
func TestClient_SingleAccountList(t *testing.T) {
|
||||
d := NewClient("")
|
||||
name := "test" + fmt.Sprintf("%d", rand.Int()) + "@lbry.com"
|
||||
createdAccount, err := d.AccountCreate(name, false)
|
||||
createdAccount, err := d.AccountCreate("test"+fmt.Sprintf("%d", time.Now().Unix())+"@lbry.com", false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
account, err := d.SingleAccountList(createdAccount.ID)
|
||||
prettyPrint(*createdAccount)
|
||||
prettyPrint(*account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
if account.Name != name {
|
||||
t.Fatalf("account name mismatch: %v != %v", account.Name, name)
|
||||
}
|
||||
prettyPrint(*account)
|
||||
}
|
||||
|
||||
func TestClient_AccountBalance(t *testing.T) {
|
||||
@@ -104,7 +92,7 @@ func TestClient_AddressUnused(t *testing.T) {
|
||||
|
||||
func TestClient_ChannelList(t *testing.T) {
|
||||
d := NewClient("")
|
||||
got, err := d.ChannelList(nil, 1, 50, nil)
|
||||
got, err := d.ChannelList(nil, 1, 50)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
@@ -112,35 +100,6 @@ func TestClient_ChannelList(t *testing.T) {
|
||||
prettyPrint(*got)
|
||||
}
|
||||
|
||||
var channelID string
|
||||
|
||||
func TestClient_ChannelCreate(t *testing.T) {
|
||||
d := NewClient("")
|
||||
got, err := d.ChannelCreate("@Test"+fmt.Sprintf("%d", time.Now().Unix()), 13.37, ChannelCreateOptions{
|
||||
ClaimCreateOptions: ClaimCreateOptions{
|
||||
Title: util.PtrToString("Mess with the channels"),
|
||||
Description: util.PtrToString("And you'll get what you deserve"),
|
||||
Tags: []string{"we", "got", "tags"},
|
||||
Languages: []string{"en-US"},
|
||||
Locations: []Location{{
|
||||
Country: util.PtrToString("CH"),
|
||||
State: util.PtrToString("Ticino"),
|
||||
City: util.PtrToString("Lugano"),
|
||||
}},
|
||||
ThumbnailURL: util.PtrToString("https://scrn.storni.info/2019-04-12_15-43-25-001592625.png"),
|
||||
},
|
||||
Email: util.PtrToString("niko@lbry.com"),
|
||||
WebsiteURL: util.PtrToString("https://lbry.com"),
|
||||
CoverURL: util.PtrToString("https://scrn.storni.info/2019-04-12_15-43-25-001592625.png"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
channelID = got.Outputs[0].ClaimID
|
||||
prettyPrint(*got)
|
||||
}
|
||||
|
||||
func TestClient_StreamCreate(t *testing.T) {
|
||||
_ = os.Setenv("BLOCKCHAIN_NAME", "lbrycrd_regtest")
|
||||
d := NewClient("")
|
||||
@@ -183,7 +142,7 @@ func TestClient_StreamCreate(t *testing.T) {
|
||||
Preview: nil,
|
||||
AllowDuplicateName: nil,
|
||||
ChannelName: nil,
|
||||
ChannelID: util.PtrToString(channelID),
|
||||
ChannelID: util.PtrToString("dd0b559b4f17a7af984f173efb5438534eb6ab27"),
|
||||
ChannelAccountID: nil,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -193,10 +152,35 @@ func TestClient_StreamCreate(t *testing.T) {
|
||||
prettyPrint(*got)
|
||||
}
|
||||
|
||||
func TestClient_ChannelCreate(t *testing.T) {
|
||||
d := NewClient("")
|
||||
got, err := d.ChannelCreate("@Test"+fmt.Sprintf("%d", time.Now().Unix()), 13.37, ChannelCreateOptions{
|
||||
ClaimCreateOptions: ClaimCreateOptions{
|
||||
Title: util.PtrToString("Mess with the channels"),
|
||||
Description: util.PtrToString("And you'll get what you deserve"),
|
||||
Tags: []string{"we", "got", "tags"},
|
||||
Languages: []string{"en-US"},
|
||||
Locations: []Location{{
|
||||
Country: util.PtrToString("CH"),
|
||||
State: util.PtrToString("Ticino"),
|
||||
City: util.PtrToString("Lugano"),
|
||||
}},
|
||||
ThumbnailURL: util.PtrToString("https://scrn.storni.info/2019-04-12_15-43-25-001592625.png"),
|
||||
},
|
||||
Email: util.PtrToString("niko@lbry.com"),
|
||||
WebsiteURL: util.PtrToString("https://lbry.com"),
|
||||
CoverURL: util.PtrToString("https://scrn.storni.info/2019-04-12_15-43-25-001592625.png"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
prettyPrint(*got)
|
||||
}
|
||||
|
||||
func TestClient_ChannelUpdate(t *testing.T) {
|
||||
d := NewClient("")
|
||||
got, err := d.ChannelUpdate(channelID, ChannelUpdateOptions{
|
||||
Bid: util.PtrToString("0.01"),
|
||||
got, err := d.ChannelUpdate("2a8b6d061c5ecb2515f1dd7e04729e9fafac660d", ChannelUpdateOptions{
|
||||
ClearLanguages: util.PtrToBool(true),
|
||||
ClearLocations: util.PtrToBool(true),
|
||||
ClearTags: util.PtrToBool(true),
|
||||
@@ -261,7 +245,7 @@ func TestClient_ChannelAbandon(t *testing.T) {
|
||||
|
||||
func TestClient_AddressList(t *testing.T) {
|
||||
d := NewClient("")
|
||||
got, err := d.AddressList(nil, nil)
|
||||
got, err := d.AddressList(nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
@@ -280,87 +264,9 @@ func TestClient_ClaimList(t *testing.T) {
|
||||
prettyPrint(*got)
|
||||
}
|
||||
|
||||
func TestClient_StreamList(t *testing.T) {
|
||||
_ = os.Setenv("BLOCKCHAIN_NAME", "lbrycrd_regtest")
|
||||
d := NewClient("")
|
||||
got, err := d.StreamList(nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
prettyPrint(*got)
|
||||
}
|
||||
|
||||
func TestClient_TransactionList(t *testing.T) {
|
||||
_ = os.Setenv("BLOCKCHAIN_NAME", "lbrycrd_regtest")
|
||||
d := NewClient("")
|
||||
got, err := d.TransactionList(nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
prettyPrint(*got)
|
||||
}
|
||||
|
||||
func TestClient_SupportTest(t *testing.T) {
|
||||
_ = os.Setenv("BLOCKCHAIN_NAME", "lbrycrd_regtest")
|
||||
d := NewClient("")
|
||||
got, err := d.ChannelCreate("@Test"+fmt.Sprintf("%d", time.Now().Unix()), 13.37, ChannelCreateOptions{
|
||||
ClaimCreateOptions: ClaimCreateOptions{
|
||||
Title: util.PtrToString("Mess with the channels"),
|
||||
Description: util.PtrToString("And you'll get what you deserve"),
|
||||
Tags: []string{"we", "got", "tags"},
|
||||
Languages: []string{"en-US"},
|
||||
Locations: []Location{{
|
||||
Country: util.PtrToString("CH"),
|
||||
State: util.PtrToString("Ticino"),
|
||||
City: util.PtrToString("Lugano"),
|
||||
}},
|
||||
ThumbnailURL: util.PtrToString("https://scrn.storni.info/2019-04-12_15-43-25-001592625.png"),
|
||||
},
|
||||
Email: util.PtrToString("niko@lbry.com"),
|
||||
WebsiteURL: util.PtrToString("https://lbry.com"),
|
||||
CoverURL: util.PtrToString("https://scrn.storni.info/2019-04-12_15-43-25-001592625.png"),
|
||||
})
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Second)
|
||||
got2, err := d.SupportCreate(got.Outputs[0].ClaimID, "1.0", util.PtrToBool(true), nil, nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
prettyPrint(*got2)
|
||||
|
||||
got3, err := d.SupportList(nil, 1, 10)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
found := false
|
||||
for _, support := range got3.Items {
|
||||
if support.ClaimID == got.Outputs[0].ClaimID {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error(errors.Err("support not found"))
|
||||
return
|
||||
}
|
||||
prettyPrint(*got3)
|
||||
got4, err := d.SupportAbandon(util.PtrToString(got.Outputs[0].ClaimID), nil, nil, nil, nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
prettyPrint(*got4)
|
||||
}
|
||||
|
||||
func TestClient_ClaimSearch(t *testing.T) {
|
||||
d := NewClient("")
|
||||
got, err := d.ClaimSearch(nil, util.PtrToString(channelID), nil, nil)
|
||||
got, err := d.ClaimSearch(nil, util.PtrToString("2a8b6d061c5ecb2515f1dd7e04729e9fafac660d"), nil, nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
@@ -454,7 +360,7 @@ func TestClient_AccountSet(t *testing.T) {
|
||||
|
||||
func TestClient_AccountCreate(t *testing.T) {
|
||||
d := NewClient("")
|
||||
name := "lbry#user#id:" + fmt.Sprintf("%d", rand.Int())
|
||||
name := "test" + fmt.Sprintf("%d", time.Now().Unix()) + "@lbry.com"
|
||||
account, err := d.AccountCreate(name, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -467,30 +373,9 @@ func TestClient_AccountCreate(t *testing.T) {
|
||||
prettyPrint(*account)
|
||||
}
|
||||
|
||||
func TestClient_AccountAdd(t *testing.T) {
|
||||
d := NewClient("")
|
||||
name := "test" + fmt.Sprintf("%d", time.Now().Unix()) + "@lbry.com"
|
||||
pubKey := "tpubDA9GDAntyJu4hD3wU7175p7CuV6DWbYXfyb2HedBA3yuBp9HZ4n3QE4Ex6RHCSiEuVp2nKAL1Lzf2ZLo9ApaFgNaJjG6Xo1wB3iEeVbrDZp"
|
||||
account, err := d.AccountAdd(name, nil, nil, &pubKey, util.PtrToBool(true), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
if account.Name != name {
|
||||
t.Errorf("account name mismatch, expected %q, got %q", name, account.Name)
|
||||
return
|
||||
}
|
||||
if account.PublicKey != pubKey {
|
||||
t.Errorf("public key mismatch, expected %q, got %q", name, account.Name)
|
||||
return
|
||||
}
|
||||
prettyPrint(*account)
|
||||
}
|
||||
|
||||
func TestClient_AccountRemove(t *testing.T) {
|
||||
d := NewClient("")
|
||||
name := "lbry#user#id:" + fmt.Sprintf("%d", rand.Int())
|
||||
createdAccount, err := d.AccountCreate(name, false)
|
||||
createdAccount, err := d.AccountCreate("test"+fmt.Sprintf("%d", time.Now().Unix())+"@lbry.com", false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
@@ -510,7 +395,9 @@ func TestClient_AccountRemove(t *testing.T) {
|
||||
prettyPrint(*removedAccount)
|
||||
return
|
||||
}
|
||||
t.Fatal(err)
|
||||
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
t.Error("account was not removed")
|
||||
prettyPrint(*account)
|
||||
@@ -518,7 +405,8 @@ func TestClient_AccountRemove(t *testing.T) {
|
||||
|
||||
func TestClient_ChannelExport(t *testing.T) {
|
||||
d := NewClient("")
|
||||
response, err := d.ChannelExport(channelID, nil, nil)
|
||||
channelClaimID := "f1ad0d72eae6b471cfd72b7956768c0c191b22d7"
|
||||
response, err := d.ChannelExport(channelClaimID, nil, nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
@@ -527,160 +415,3 @@ func TestClient_ChannelExport(t *testing.T) {
|
||||
}
|
||||
t.Log("Export:", *response)
|
||||
}
|
||||
|
||||
func TestClient_ChannelImport(t *testing.T) {
|
||||
d := NewClient("")
|
||||
|
||||
// A channel created just for automated testing purposes
|
||||
channelName := "@LbryAutomatedTestChannel"
|
||||
channelkey := "7943FWPBHZES4dUcMXSpDYwoM5a2tsyJT1R8V54QoUhekGcqmeH3hbzDXoLLQ8" +
|
||||
"oKkfb99PgGK5efrZeYqaxg4X5XRJMJ6gKC8hqKcnwhYkmKDXmoBDNgd2ccZ9jhP8z" +
|
||||
"HG3NJorAN9Hh4XMyBc5goBLZYYvC9MYvBmT3Fcteb5saqMvmQxFURv74NqXLQZC1t" +
|
||||
"p6iRZKfTj77Pd5gsBsCYAbVmCqzbm5m1hHkUmfFEZVGcQNTYCDwZn543xSMYvSPnJ" +
|
||||
"zt8tRYCJWaPdj713uENZZMo3gxuAMb1NwSnx8tbwETp7WPkpFLL6HZ9jKpB8BURHM" +
|
||||
"F1RFD1PRyqbC6YezPyPQ2oninKKHdBduvXZG5KF2G2Q3ixsuE2ntifBBo1f5PotRk" +
|
||||
"UanXKEafWxvXAayJjpsmZ4bFt7n6Xg4438WZXBiZKCPobLJAiHfe72n618kE6PCNU" +
|
||||
"77cyU5Rk8J3CuY6QzZPzwuiXz2GLfkUMCYd9jGT6g53XbE6SwCsmGnd9NJkBAaJf5" +
|
||||
"1FAYRURrhHnp79PAoHftEWtZEuU8MCPMdSRjzxYMRS4ScUzg5viDMTAkE8frsfCVZ" +
|
||||
"hxsFwGUyNNno8eiqrrYmpbJGEwwK3S4437JboAUEFPdMNn8zNQWZcLLVrK9KyQeKM" +
|
||||
"XpKkf4zJV6sZJ7gBMpzvPL18ULEgXTy7VsNBKmsfC1rM4WVG9ri1UixEcLDS79foC" +
|
||||
"Jb3FnSr1T4MRKESeN3W"
|
||||
response, err := d.ChannelImport(channelkey, nil)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
channels, err := d.ChannelList(nil, 1, 50, nil)
|
||||
seen := false
|
||||
for _, c := range channels.Items {
|
||||
if c.Name == channelName {
|
||||
seen = true
|
||||
}
|
||||
}
|
||||
if !seen {
|
||||
t.Error("couldn't find imported channel")
|
||||
}
|
||||
t.Log("Response:", *response)
|
||||
}
|
||||
|
||||
func TestClient_ChannelImportWithWalletID(t *testing.T) {
|
||||
d := NewClient("")
|
||||
|
||||
id := "lbry#wallet#id:" + fmt.Sprintf("%d", rand.Int())
|
||||
wallet, err := d.WalletCreate(id, nil)
|
||||
|
||||
// A channel created just for automated testing purposes
|
||||
channelName := "@LbryAutomatedTestChannel"
|
||||
channelkey := "7943FWPBHZES4dUcMXSpDYwoM5a2tsyJT1R8V54QoUhekGcqmeH3hbzDXoLLQ8" +
|
||||
"oKkfb99PgGK5efrZeYqaxg4X5XRJMJ6gKC8hqKcnwhYkmKDXmoBDNgd2ccZ9jhP8z" +
|
||||
"HG3NJorAN9Hh4XMyBc5goBLZYYvC9MYvBmT3Fcteb5saqMvmQxFURv74NqXLQZC1t" +
|
||||
"p6iRZKfTj77Pd5gsBsCYAbVmCqzbm5m1hHkUmfFEZVGcQNTYCDwZn543xSMYvSPnJ" +
|
||||
"zt8tRYCJWaPdj713uENZZMo3gxuAMb1NwSnx8tbwETp7WPkpFLL6HZ9jKpB8BURHM" +
|
||||
"F1RFD1PRyqbC6YezPyPQ2oninKKHdBduvXZG5KF2G2Q3ixsuE2ntifBBo1f5PotRk" +
|
||||
"UanXKEafWxvXAayJjpsmZ4bFt7n6Xg4438WZXBiZKCPobLJAiHfe72n618kE6PCNU" +
|
||||
"77cyU5Rk8J3CuY6QzZPzwuiXz2GLfkUMCYd9jGT6g53XbE6SwCsmGnd9NJkBAaJf5" +
|
||||
"1FAYRURrhHnp79PAoHftEWtZEuU8MCPMdSRjzxYMRS4ScUzg5viDMTAkE8frsfCVZ" +
|
||||
"hxsFwGUyNNno8eiqrrYmpbJGEwwK3S4437JboAUEFPdMNn8zNQWZcLLVrK9KyQeKM" +
|
||||
"XpKkf4zJV6sZJ7gBMpzvPL18ULEgXTy7VsNBKmsfC1rM4WVG9ri1UixEcLDS79foC" +
|
||||
"Jb3FnSr1T4MRKESeN3W"
|
||||
response, err := d.ChannelImport(channelkey, &wallet.ID)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
channels, err := d.ChannelList(nil, 1, 50, &wallet.ID)
|
||||
seen := false
|
||||
for _, c := range channels.Items {
|
||||
if c.Name == channelName {
|
||||
seen = true
|
||||
}
|
||||
}
|
||||
if !seen {
|
||||
t.Error("couldn't find imported channel")
|
||||
}
|
||||
t.Log("Response:", *response)
|
||||
}
|
||||
|
||||
func TestClient_WalletCreate(t *testing.T) {
|
||||
d := NewClient("")
|
||||
|
||||
id := "lbry#wallet#id:" + fmt.Sprintf("%d", rand.Int())
|
||||
wallet, err := d.WalletCreate(id, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if wallet.ID != id {
|
||||
prettyPrint(*wallet)
|
||||
t.Fatalf("wallet ID mismatch, expected %q, got %q", id, wallet.Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_WalletCreateWithOpts(t *testing.T) {
|
||||
d := NewClient("")
|
||||
|
||||
id := "lbry#wallet#id:" + fmt.Sprintf("%d", rand.Int())
|
||||
wallet, err := d.WalletCreate(id, &WalletCreateOpts{CreateAccount: true, SingleKey: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accounts, err := d.AccountListForWallet(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prettyPrint(wallet)
|
||||
prettyPrint(accounts)
|
||||
if accounts.LBCMainnet[0].Name == "" {
|
||||
t.Fatalf("account name is empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_WalletList(t *testing.T) {
|
||||
d := NewClient("")
|
||||
|
||||
id := "lbry#wallet#id:" + fmt.Sprintf("%d", rand.Int())
|
||||
wList, err := d.WalletList(id)
|
||||
if err == nil {
|
||||
t.Fatalf("wallet %v was unexpectedly found", id)
|
||||
}
|
||||
if err.Error() != fmt.Sprintf("Error in daemon: Couldn't find wallet: %v.", id) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err = d.WalletCreate(id, &WalletCreateOpts{CreateAccount: true, SingleKey: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
wList, err = d.WalletList(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(*wList) < 1 {
|
||||
t.Fatal("wallet list is empty")
|
||||
}
|
||||
if (*wList)[0].ID != id {
|
||||
t.Fatalf("wallet ID mismatch, expected %q, got %q", id, (*wList)[0].ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_WalletRemoveWalletAdd(t *testing.T) {
|
||||
d := NewClient("")
|
||||
|
||||
id := "lbry#wallet#id:" + fmt.Sprintf("%d", rand.Int())
|
||||
wallet, err := d.WalletCreate(id, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err = d.WalletRemove(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
addedWallet, err := d.WalletAdd(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if addedWallet.ID != wallet.ID {
|
||||
prettyPrint(*addedWallet)
|
||||
t.Fatalf("wallet ID mismatch, expected %q, got %q", wallet.ID, addedWallet.Name)
|
||||
}
|
||||
}
|
||||
@@ -204,21 +204,14 @@ type Account struct {
|
||||
MaximumUsesPerAddress uint64 `json:"maximum_uses_per_address"`
|
||||
} `json:"receiving"`
|
||||
} `json:"address_generator"`
|
||||
Certificates uint64 `json:"certificates"`
|
||||
Coins float64 `json:"coins"`
|
||||
Encrypted bool `json:"encrypted"`
|
||||
ID string `json:"id"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
Ledger *string `json:"ledger,omitempty"`
|
||||
ModifiedOn *float64 `json:"modified_on,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Preferences *struct {
|
||||
Theme string `json:"theme"`
|
||||
} `json:"preferences,omitempty"`
|
||||
PublicKey string `json:"public_key"`
|
||||
PrivateKey *string `json:"private_key,omitempty"`
|
||||
Seed *string `json:"seed,omitempty"`
|
||||
Satoshis uint64 `json:"satoshis"`
|
||||
Certificates uint64 `json:"certificates"`
|
||||
Coins float64 `json:"coins"`
|
||||
Encrypted bool `json:"encrypted"`
|
||||
ID string `json:"id"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
Name string `json:"name"`
|
||||
PublicKey string `json:"public_key"`
|
||||
Satoshis uint64 `json:"satoshis"`
|
||||
}
|
||||
|
||||
type AccountListResponse struct {
|
||||
@@ -227,13 +220,20 @@ type AccountListResponse struct {
|
||||
LBCRegtest []Account `json:"lbc_regtest"`
|
||||
}
|
||||
|
||||
type AccountBalanceResponse struct {
|
||||
Available decimal.Decimal `json:"available"`
|
||||
Reserved decimal.Decimal `json:"reserved"`
|
||||
ReservedSubtotals *decimal.Decimal `json:"reserved_subtotals"`
|
||||
Total decimal.Decimal `json:"total"`
|
||||
type AccountBalanceResponse string
|
||||
|
||||
type AccountCreateResponse struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
PublicKey string `json:"public_key"`
|
||||
PrivateKey string `json:"private_key"`
|
||||
Seed string `json:"seed"`
|
||||
Ledger string `json:"ledger"`
|
||||
ModifiedOn float64 `json:"modified_on"`
|
||||
}
|
||||
|
||||
type AccountRemoveResponse AccountCreateResponse
|
||||
|
||||
type Transaction struct {
|
||||
Address string `json:"address"`
|
||||
Amount string `json:"amount"`
|
||||
@@ -265,15 +265,8 @@ type AccountFundResponse TransactionSummary
|
||||
|
||||
type Address string
|
||||
type AddressUnusedResponse Address
|
||||
type AddressListResponse []struct {
|
||||
Account string `json:"account"`
|
||||
Address Address `json:"address"`
|
||||
Pubkey string `json:"pubkey"`
|
||||
UsedTimes uint64 `json:"used_times"`
|
||||
}
|
||||
|
||||
type AddressListResponse []Address
|
||||
type ChannelExportResponse string
|
||||
type ChannelImportResponse string
|
||||
|
||||
type ChannelListResponse struct {
|
||||
Items []Transaction `json:"items"`
|
||||
@@ -396,8 +389,6 @@ func (c *Claim) GetStreamSizeByMagic() (streamSize uint64, e error) {
|
||||
return streamSize, nil
|
||||
}
|
||||
|
||||
type StreamListResponse []Claim
|
||||
|
||||
type ClaimListResponse struct {
|
||||
Claims []Claim `json:"items"`
|
||||
Page uint64 `json:"page"`
|
||||
@@ -406,12 +397,6 @@ type ClaimListResponse struct {
|
||||
}
|
||||
type ClaimSearchResponse ClaimListResponse
|
||||
|
||||
type SupportListResponse struct {
|
||||
Items []Claim
|
||||
Page uint64 `json:"page"`
|
||||
PageSize uint64 `json:"page_size"`
|
||||
TotalPages uint64 `json:"total_pages"`
|
||||
}
|
||||
type StatusResponse struct {
|
||||
BlobManager struct {
|
||||
FinishedBlobs uint64 `json:"finished_blobs"`
|
||||
@@ -475,42 +460,6 @@ type UTXOListResponse []struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
type UTXOReleaseResponse *string
|
||||
|
||||
type transactionListBlob struct {
|
||||
Address string `json:"address"`
|
||||
Amount string `json:"amount"`
|
||||
BalanceDelta string `json:"balance_delta"`
|
||||
ClaimId string `json:"claim_id"`
|
||||
ClaimName string `json:"claim_name"`
|
||||
Nout int `json:"nout"`
|
||||
}
|
||||
|
||||
//TODO: this repeats all the fields from transactionListBlob which doesn't make sense
|
||||
// but if i extend the type with transactionListBlob it doesn't fill the fields. does our unmarshaller crap out on these?
|
||||
type supportBlob struct {
|
||||
Address string `json:"address"`
|
||||
Amount string `json:"amount"`
|
||||
BalanceDelta string `json:"balance_delta"`
|
||||
ClaimId string `json:"claim_id"`
|
||||
ClaimName string `json:"claim_name"`
|
||||
Nout int `json:"nout"`
|
||||
IsTip bool `json:"is_tip"`
|
||||
}
|
||||
|
||||
type TransactionListResponse []struct {
|
||||
AbandonInfo []transactionListBlob `json:"abandon_info"`
|
||||
ClaimInfo []transactionListBlob `json:"claim_info"`
|
||||
Confirmations int64 `json:"confirmations"`
|
||||
Date string `json:"date"`
|
||||
Fee string `json:"fee"`
|
||||
SupportInfo []supportBlob `json:"support_info"`
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
Txid string `json:"txid"`
|
||||
UpdateInfo []transactionListBlob `json:"update_info"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
type VersionResponse struct {
|
||||
Build string `json:"build"`
|
||||
Desktop string `json:"desktop"`
|
||||
@@ -542,10 +491,3 @@ type NumClaimsInChannelResponse map[string]struct {
|
||||
}
|
||||
|
||||
type ClaimShowResponse *Claim
|
||||
|
||||
type Wallet struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type WalletList []Wallet
|
||||
+12
-40
@@ -13,29 +13,11 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultServerAddress = "https://api.lbry.com"
|
||||
timeout = 5 * time.Second
|
||||
headerForwardedFor = "X-Forwarded-For"
|
||||
|
||||
userObjectPath = "user"
|
||||
userMeMethod = "me"
|
||||
)
|
||||
|
||||
// Client stores data about internal-apis call it is about to make.
|
||||
type Client struct {
|
||||
ServerAddress string
|
||||
AuthToken string
|
||||
Logger *log.Logger
|
||||
serverAddress string
|
||||
extraHeaders map[string]string
|
||||
}
|
||||
|
||||
// ClientOpts allow to provide extra parameters to NewClient:
|
||||
// - ServerAddress
|
||||
// - RemoteIP — to forward the IP of a frontend client making the request
|
||||
type ClientOpts struct {
|
||||
ServerAddress string
|
||||
RemoteIP string
|
||||
}
|
||||
|
||||
// APIResponse reflects internal-apis JSON response format.
|
||||
@@ -48,29 +30,24 @@ type APIResponse struct {
|
||||
// ResponseData is a map containing parsed json response.
|
||||
type ResponseData map[string]interface{}
|
||||
|
||||
const (
|
||||
defaultAPIHost = "https://api.lbry.com"
|
||||
timeout = 5 * time.Second
|
||||
userObjectPath = "user"
|
||||
)
|
||||
|
||||
// NewClient returns a client instance for internal-apis. It requires authToken to be provided
|
||||
// for authentication.
|
||||
func NewClient(authToken string, opts *ClientOpts) Client {
|
||||
c := Client{
|
||||
serverAddress: defaultServerAddress,
|
||||
extraHeaders: make(map[string]string),
|
||||
func NewClient(authToken string) Client {
|
||||
return Client{
|
||||
ServerAddress: defaultAPIHost,
|
||||
AuthToken: authToken,
|
||||
Logger: log.StandardLogger(),
|
||||
}
|
||||
if opts != nil {
|
||||
if opts.ServerAddress != "" {
|
||||
c.serverAddress = opts.ServerAddress
|
||||
}
|
||||
if opts.RemoteIP != "" {
|
||||
c.extraHeaders[headerForwardedFor] = opts.RemoteIP
|
||||
}
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func (c Client) getEndpointURL(object, method string) string {
|
||||
return fmt.Sprintf("%s/%s/%s", c.serverAddress, object, method)
|
||||
return fmt.Sprintf("%s/%s/%s", c.ServerAddress, object, method)
|
||||
}
|
||||
|
||||
func (c Client) prepareParams(params map[string]interface{}) (string, error) {
|
||||
@@ -92,14 +69,9 @@ func (c Client) doCall(url string, payload string) ([]byte, error) {
|
||||
if err != nil {
|
||||
return body, err
|
||||
}
|
||||
|
||||
req.Header.Add("Accept", "application/json")
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
for k, v := range c.extraHeaders {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: timeout}
|
||||
r, err := client.Do(req)
|
||||
if err != nil {
|
||||
@@ -135,5 +107,5 @@ func (c Client) Call(object, method string, params map[string]interface{}) (Resp
|
||||
|
||||
// UserMe returns user details for the user associated with the current auth_token
|
||||
func (c Client) UserMe() (ResponseData, error) {
|
||||
return c.Call(userObjectPath, userMeMethod, map[string]interface{}{})
|
||||
return c.Call(userObjectPath, "me", map[string]interface{}{})
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
package lbryinc
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -10,64 +10,56 @@ import (
|
||||
)
|
||||
|
||||
func TestUserMeWrongToken(t *testing.T) {
|
||||
c := NewClient("abc", nil)
|
||||
c := NewClient("abc")
|
||||
r, err := c.UserMe()
|
||||
require.NotNil(t, err)
|
||||
assert.Equal(t, "could not authenticate user", err.Error())
|
||||
assert.Nil(t, r)
|
||||
}
|
||||
|
||||
func launchDummyServer(lastReq **http.Request) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
*lastReq = &*r
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
response := []byte(`{
|
||||
"success": true,
|
||||
"error": null,
|
||||
"data": {
|
||||
"id": 751365,
|
||||
"language": "en",
|
||||
"given_name": null,
|
||||
"family_name": null,
|
||||
"created_at": "2019-01-17T12:13:06Z",
|
||||
"updated_at": "2019-05-02T13:57:59Z",
|
||||
"invited_by_id": null,
|
||||
"invited_at": null,
|
||||
"invites_remaining": 0,
|
||||
"invite_reward_claimed": false,
|
||||
"is_email_enabled": true,
|
||||
"manual_approval_user_id": 837139,
|
||||
"reward_status_change_trigger": "manual",
|
||||
"primary_email": "andrey@lbry.com",
|
||||
"has_verified_email": true,
|
||||
"is_identity_verified": false,
|
||||
"is_reward_approved": true,
|
||||
"groups": []
|
||||
}
|
||||
}`)
|
||||
w.Write(response)
|
||||
}))
|
||||
const dummyServerURL = "http://127.0.0.1:59999"
|
||||
|
||||
func launchDummyServer() {
|
||||
s := &http.Server{
|
||||
Addr: "127.0.0.1:59999",
|
||||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
response := []byte(`{
|
||||
"success": true,
|
||||
"error": null,
|
||||
"data": {
|
||||
"id": 751365,
|
||||
"language": "en",
|
||||
"given_name": null,
|
||||
"family_name": null,
|
||||
"created_at": "2019-01-17T12:13:06Z",
|
||||
"updated_at": "2019-05-02T13:57:59Z",
|
||||
"invited_by_id": null,
|
||||
"invited_at": null,
|
||||
"invites_remaining": 0,
|
||||
"invite_reward_claimed": false,
|
||||
"is_email_enabled": true,
|
||||
"manual_approval_user_id": 837139,
|
||||
"reward_status_change_trigger": "manual",
|
||||
"primary_email": "andrey@lbry.com",
|
||||
"has_verified_email": true,
|
||||
"is_identity_verified": false,
|
||||
"is_reward_approved": true,
|
||||
"groups": []
|
||||
}
|
||||
}`)
|
||||
w.Write(response)
|
||||
}),
|
||||
}
|
||||
log.Fatal(s.ListenAndServe())
|
||||
}
|
||||
|
||||
func TestUserMe(t *testing.T) {
|
||||
var req *http.Request
|
||||
ts := launchDummyServer(&req)
|
||||
defer ts.Close()
|
||||
|
||||
c := NewClient("realToken", &ClientOpts{ServerAddress: ts.URL})
|
||||
go launchDummyServer()
|
||||
c := NewClient("realToken")
|
||||
c.ServerAddress = dummyServerURL
|
||||
r, err := c.UserMe()
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, r["primary_email"], "andrey@lbry.com")
|
||||
}
|
||||
|
||||
func TestRemoteIP(t *testing.T) {
|
||||
var req *http.Request
|
||||
ts := launchDummyServer(&req)
|
||||
defer ts.Close()
|
||||
|
||||
c := NewClient("realToken", &ClientOpts{ServerAddress: ts.URL, RemoteIP: "8.8.8.8"})
|
||||
_, err := c.UserMe()
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, []string{"8.8.8.8"}, req.Header["X-Forwarded-For"])
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
package orderedmap
|
||||
|
||||
// mostly from https://github.com/iancoleman/orderedmap
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/lbryio/lbry.go/extras/errors"
|
||||
)
|
||||
|
||||
type keyIndex struct {
|
||||
Key string
|
||||
Index int
|
||||
}
|
||||
|
||||
type byIndex []keyIndex
|
||||
|
||||
func (a byIndex) Len() int { return len(a) }
|
||||
func (a byIndex) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
|
||||
func (a byIndex) Less(i, j int) bool { return a[i].Index < a[j].Index }
|
||||
|
||||
type Map struct {
|
||||
l sync.RWMutex
|
||||
keys []string
|
||||
values map[string]interface{}
|
||||
}
|
||||
|
||||
func New() *Map {
|
||||
o := Map{}
|
||||
o.l = sync.RWMutex{}
|
||||
o.keys = []string{}
|
||||
o.values = map[string]interface{}{}
|
||||
return &o
|
||||
}
|
||||
|
||||
func (o *Map) Get(key string) (interface{}, bool) {
|
||||
o.l.RLock()
|
||||
defer o.l.RUnlock()
|
||||
val, exists := o.values[key]
|
||||
return val, exists
|
||||
}
|
||||
|
||||
func (o *Map) Set(key string, value interface{}) {
|
||||
o.l.Lock()
|
||||
defer o.l.Unlock()
|
||||
_, exists := o.values[key]
|
||||
if !exists {
|
||||
o.keys = append(o.keys, key)
|
||||
}
|
||||
o.values[key] = value
|
||||
}
|
||||
|
||||
const outOfRange = "position value %d is outside of the range %d - %d"
|
||||
|
||||
//InsertAt This is a zero based position index: 0,1,2,3..n(from left) OR -1,-2,-3...-n(from right) where -1 is the last place.
|
||||
func (o *Map) InsertAt(key string, value interface{}, position int) error {
|
||||
o.l.Lock()
|
||||
defer o.l.Unlock()
|
||||
var index = position
|
||||
if position < 0 {
|
||||
// support indexing from the back: -1 = last in array.
|
||||
index += len(o.keys) + 1
|
||||
if index < 0 || index > len(o.keys) {
|
||||
return errors.Err(fmt.Sprintf(outOfRange, position, len(o.keys), len(o.keys)-1))
|
||||
}
|
||||
} else if index > len(o.keys) {
|
||||
return errors.Err(fmt.Sprintf(outOfRange, position, len(o.keys), len(o.keys)-1))
|
||||
}
|
||||
_, exists := o.values[key]
|
||||
if !exists {
|
||||
// left + key + right
|
||||
o.keys = append(o.keys[0:index], append([]string{key}, o.keys[index:]...)...)
|
||||
}
|
||||
o.values[key] = value
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *Map) Prepend(key string, value interface{}) {
|
||||
o.l.Lock()
|
||||
defer o.l.Unlock()
|
||||
_, exists := o.values[key]
|
||||
if !exists {
|
||||
o.keys = append([]string{key}, o.keys...)
|
||||
}
|
||||
o.values[key] = value
|
||||
}
|
||||
|
||||
func (o *Map) Delete(key string) {
|
||||
o.l.Lock()
|
||||
defer o.l.Unlock()
|
||||
// check key is in use
|
||||
_, ok := o.values[key]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// remove from keys
|
||||
for i, k := range o.keys {
|
||||
if k == key {
|
||||
o.keys = append(o.keys[:i], o.keys[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
// remove from values
|
||||
delete(o.values, key)
|
||||
}
|
||||
|
||||
func (o *Map) Keys() []string {
|
||||
o.l.RLock()
|
||||
defer o.l.RUnlock()
|
||||
return o.keys
|
||||
}
|
||||
|
||||
func (o *Map) UnmarshalJSON(b []byte) error {
|
||||
o.l.Lock()
|
||||
defer o.l.Unlock()
|
||||
m := map[string]interface{}{}
|
||||
if err := json.Unmarshal(b, &m); err != nil {
|
||||
return errors.Err(err)
|
||||
}
|
||||
s := string(b)
|
||||
mapToOrderedMap(o, s, m)
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapToOrderedMap(o *Map, s string, m map[string]interface{}) {
|
||||
// Get the order of the keys
|
||||
orderedKeys := []keyIndex{}
|
||||
for k := range m {
|
||||
kEscaped := strings.Replace(k, `"`, `\"`, -1)
|
||||
kQuoted := `"` + kEscaped + `"`
|
||||
// Find how much content exists before this key.
|
||||
// If all content from this key and after is replaced with a close
|
||||
// brace, it should still form a valid json string.
|
||||
sTrimmed := s
|
||||
for len(sTrimmed) > 0 {
|
||||
lastIndex := strings.LastIndex(sTrimmed, kQuoted)
|
||||
if lastIndex == -1 {
|
||||
break
|
||||
}
|
||||
sTrimmed = sTrimmed[0:lastIndex]
|
||||
sTrimmed = strings.TrimSpace(sTrimmed)
|
||||
if len(sTrimmed) > 0 && sTrimmed[len(sTrimmed)-1] == ',' {
|
||||
sTrimmed = sTrimmed[0 : len(sTrimmed)-1]
|
||||
}
|
||||
maybeValidJson := sTrimmed + "}"
|
||||
testMap := map[string]interface{}{}
|
||||
err := json.Unmarshal([]byte(maybeValidJson), &testMap)
|
||||
if err == nil {
|
||||
// record the position of this key in s
|
||||
ki := keyIndex{
|
||||
Key: k,
|
||||
Index: len(sTrimmed),
|
||||
}
|
||||
orderedKeys = append(orderedKeys, ki)
|
||||
// shorten the string to get the next key
|
||||
startOfValueIndex := lastIndex + len(kQuoted)
|
||||
valueStr := s[startOfValueIndex : len(s)-1]
|
||||
valueStr = strings.TrimSpace(valueStr)
|
||||
if len(valueStr) > 0 && valueStr[0] == ':' {
|
||||
valueStr = valueStr[1:]
|
||||
}
|
||||
valueStr = strings.TrimSpace(valueStr)
|
||||
if valueStr[0] == '{' {
|
||||
// if the value for this key is a map, convert it to an orderedmap.
|
||||
// find end of valueStr by removing everything after last }
|
||||
// until it forms valid json
|
||||
hasValidJson := false
|
||||
i := 1
|
||||
for i < len(valueStr) && !hasValidJson {
|
||||
if valueStr[i] != '}' {
|
||||
i = i + 1
|
||||
continue
|
||||
}
|
||||
subTestMap := map[string]interface{}{}
|
||||
testValue := valueStr[0 : i+1]
|
||||
err = json.Unmarshal([]byte(testValue), &subTestMap)
|
||||
if err == nil {
|
||||
hasValidJson = true
|
||||
valueStr = testValue
|
||||
break
|
||||
}
|
||||
i = i + 1
|
||||
}
|
||||
// convert to orderedmap
|
||||
if hasValidJson {
|
||||
mkTyped := m[k].(map[string]interface{})
|
||||
oo := &Map{}
|
||||
mapToOrderedMap(oo, valueStr, mkTyped)
|
||||
m[k] = oo
|
||||
}
|
||||
} else if valueStr[0] == '[' {
|
||||
// if the value for this key is a []interface, convert any map items to an orderedmap.
|
||||
// find end of valueStr by removing everything after last ]
|
||||
// until it forms valid json
|
||||
hasValidJson := false
|
||||
i := 1
|
||||
for i < len(valueStr) && !hasValidJson {
|
||||
if valueStr[i] != ']' {
|
||||
i = i + 1
|
||||
continue
|
||||
}
|
||||
subTestSlice := []interface{}{}
|
||||
testValue := valueStr[0 : i+1]
|
||||
err = json.Unmarshal([]byte(testValue), &subTestSlice)
|
||||
if err == nil {
|
||||
hasValidJson = true
|
||||
valueStr = testValue
|
||||
break
|
||||
}
|
||||
i = i + 1
|
||||
}
|
||||
if hasValidJson {
|
||||
itemsStr := valueStr[1 : len(valueStr)-1]
|
||||
// get next item in the slice
|
||||
itemIndex := 0
|
||||
startItem := 0
|
||||
endItem := 0
|
||||
for endItem < len(itemsStr) {
|
||||
if itemsStr[endItem] != ',' && endItem < len(itemsStr)-1 {
|
||||
endItem = endItem + 1
|
||||
continue
|
||||
}
|
||||
// if this substring compiles to json, it's the next item
|
||||
possibleItemStr := strings.TrimSpace(itemsStr[startItem:endItem])
|
||||
var possibleItem interface{}
|
||||
err = json.Unmarshal([]byte(possibleItemStr), &possibleItem)
|
||||
if err != nil {
|
||||
endItem = endItem + 1
|
||||
continue
|
||||
}
|
||||
// if item is map, convert to orderedmap
|
||||
if possibleItemStr[0] == '{' {
|
||||
mkTyped := m[k].([]interface{})
|
||||
mkiTyped := mkTyped[itemIndex].(map[string]interface{})
|
||||
oo := &Map{}
|
||||
mapToOrderedMap(oo, possibleItemStr, mkiTyped)
|
||||
// replace original map with orderedmap
|
||||
mkTyped[itemIndex] = oo
|
||||
m[k] = mkTyped
|
||||
}
|
||||
// remove this item from itemsStr
|
||||
startItem = endItem + 1
|
||||
endItem = endItem + 1
|
||||
itemIndex = itemIndex + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
// Sort the keys
|
||||
sort.Sort(byIndex(orderedKeys))
|
||||
// Convert sorted keys to string slice
|
||||
k := []string{}
|
||||
for _, ki := range orderedKeys {
|
||||
k = append(k, ki.Key)
|
||||
}
|
||||
// Set the Map values
|
||||
o.values = m
|
||||
o.keys = k
|
||||
}
|
||||
|
||||
func (o *Map) Copy() *Map {
|
||||
new := New()
|
||||
|
||||
for _, k := range o.keys {
|
||||
v, _ := o.Get(k)
|
||||
new.Set(k, v)
|
||||
}
|
||||
|
||||
return new
|
||||
}
|
||||
|
||||
func (o *Map) MarshalJSON() ([]byte, error) {
|
||||
o.l.RLock()
|
||||
defer o.l.RUnlock()
|
||||
s := "{"
|
||||
for _, k := range o.keys {
|
||||
// add key
|
||||
kEscaped := strings.Replace(k, `"`, `\"`, -1)
|
||||
s = s + `"` + kEscaped + `":`
|
||||
// add value
|
||||
v := o.values[k]
|
||||
vBytes, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return []byte{}, errors.Err(err)
|
||||
}
|
||||
s = s + string(vBytes) + ","
|
||||
}
|
||||
if len(o.keys) > 0 {
|
||||
s = s[0 : len(s)-1]
|
||||
}
|
||||
s = s + "}"
|
||||
return []byte(s), nil
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
package orderedmap
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
func TestOrderedMap(t *testing.T) {
|
||||
o := New()
|
||||
// number
|
||||
o.Set("number", 3)
|
||||
v, _ := o.Get("number")
|
||||
if v.(int) != 3 {
|
||||
t.Error("Set number")
|
||||
}
|
||||
// string
|
||||
o.Set("string", "x")
|
||||
v, _ = o.Get("string")
|
||||
if v.(string) != "x" {
|
||||
t.Error("Set string")
|
||||
}
|
||||
// string slice
|
||||
o.Set("strings", []string{
|
||||
"t",
|
||||
"u",
|
||||
})
|
||||
v, _ = o.Get("strings")
|
||||
if v.([]string)[0] != "t" {
|
||||
t.Error("Set strings first index")
|
||||
}
|
||||
if v.([]string)[1] != "u" {
|
||||
t.Error("Set strings second index")
|
||||
}
|
||||
// mixed slice
|
||||
o.Set("mixed", []interface{}{
|
||||
1,
|
||||
"1",
|
||||
})
|
||||
v, _ = o.Get("mixed")
|
||||
if v.([]interface{})[0].(int) != 1 {
|
||||
t.Error("Set mixed int")
|
||||
}
|
||||
if v.([]interface{})[1].(string) != "1" {
|
||||
t.Error("Set mixed string")
|
||||
}
|
||||
// overriding existing key
|
||||
o.Set("number", 4)
|
||||
v, _ = o.Get("number")
|
||||
if v.(int) != 4 {
|
||||
t.Error("Override existing key")
|
||||
}
|
||||
// Keys method
|
||||
keys := o.Keys()
|
||||
expectedKeys := []string{
|
||||
"number",
|
||||
"string",
|
||||
"strings",
|
||||
"mixed",
|
||||
}
|
||||
for i := range keys {
|
||||
if keys[i] != expectedKeys[i] {
|
||||
t.Error("Keys method", keys[i], "!=", expectedKeys[i])
|
||||
}
|
||||
}
|
||||
for i := range expectedKeys {
|
||||
if keys[i] != expectedKeys[i] {
|
||||
t.Error("Keys method", keys[i], "!=", expectedKeys[i])
|
||||
}
|
||||
}
|
||||
// delete
|
||||
o.Delete("strings")
|
||||
o.Delete("not a key being used")
|
||||
if len(o.Keys()) != 3 {
|
||||
t.Error("Delete method")
|
||||
}
|
||||
_, ok := o.Get("strings")
|
||||
if ok {
|
||||
t.Error("Delete did not remove 'strings' key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlankMarshalJSON(t *testing.T) {
|
||||
o := New()
|
||||
// blank map
|
||||
b, err := json.Marshal(o)
|
||||
if err != nil {
|
||||
t.Error("Marshalling blank map to json", err)
|
||||
}
|
||||
s := string(b)
|
||||
// check json is correctly ordered
|
||||
if s != `{}` {
|
||||
t.Error("JSON Marshaling blank map value is incorrect", s)
|
||||
}
|
||||
// convert to indented json
|
||||
bi, err := json.MarshalIndent(o, "", " ")
|
||||
if err != nil {
|
||||
t.Error("Marshalling indented json for blank map", err)
|
||||
}
|
||||
si := string(bi)
|
||||
ei := `{}`
|
||||
if si != ei {
|
||||
fmt.Println(ei)
|
||||
fmt.Println(si)
|
||||
t.Error("JSON MarshalIndent blank map value is incorrect", si)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarshalJSON(t *testing.T) {
|
||||
o := New()
|
||||
// number
|
||||
o.Set("number", 3)
|
||||
// string
|
||||
o.Set("string", "x")
|
||||
// new value keeps key in old position
|
||||
o.Set("number", 4)
|
||||
// keys not sorted alphabetically
|
||||
o.Set("z", 1)
|
||||
o.Set("a", 2)
|
||||
o.Set("b", 3)
|
||||
// slice
|
||||
o.Set("slice", []interface{}{
|
||||
"1",
|
||||
1,
|
||||
})
|
||||
// orderedmap
|
||||
v := New()
|
||||
v.Set("e", 1)
|
||||
v.Set("a", 2)
|
||||
o.Set("orderedmap", v)
|
||||
// double quote in key
|
||||
o.Set(`test"ing`, 9)
|
||||
// convert to json
|
||||
b, err := json.Marshal(o)
|
||||
if err != nil {
|
||||
t.Error("Marshalling json", err)
|
||||
}
|
||||
s := string(b)
|
||||
// check json is correctly ordered
|
||||
if s != `{"number":4,"string":"x","z":1,"a":2,"b":3,"slice":["1",1],"orderedmap":{"e":1,"a":2},"test\"ing":9}` {
|
||||
t.Error("JSON Marshal value is incorrect", s)
|
||||
}
|
||||
// convert to indented json
|
||||
bi, err := json.MarshalIndent(o, "", " ")
|
||||
if err != nil {
|
||||
t.Error("Marshalling indented json", err)
|
||||
}
|
||||
si := string(bi)
|
||||
ei := `{
|
||||
"number": 4,
|
||||
"string": "x",
|
||||
"z": 1,
|
||||
"a": 2,
|
||||
"b": 3,
|
||||
"slice": [
|
||||
"1",
|
||||
1
|
||||
],
|
||||
"orderedmap": {
|
||||
"e": 1,
|
||||
"a": 2
|
||||
},
|
||||
"test\"ing": 9
|
||||
}`
|
||||
if si != ei {
|
||||
fmt.Println(ei)
|
||||
fmt.Println(si)
|
||||
t.Error("JSON MarshalIndent value is incorrect", si)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalJSON(t *testing.T) {
|
||||
s := `{
|
||||
"number": 4,
|
||||
"string": "x",
|
||||
"z": 1,
|
||||
"a": "should not break with unclosed { character in value",
|
||||
"b": 3,
|
||||
"slice": [
|
||||
"1",
|
||||
1
|
||||
],
|
||||
"orderedmap": {
|
||||
"e": 1,
|
||||
"a { nested key with brace": "with a }}}} }} {{{ brace value",
|
||||
"after": {
|
||||
"link": "test {{{ with even deeper nested braces }"
|
||||
}
|
||||
},
|
||||
"test\"ing": 9,
|
||||
"after": 1,
|
||||
"multitype_array": [
|
||||
"test",
|
||||
1,
|
||||
{ "map": "obj", "it" : 5, ":colon in key": "colon: in value" }
|
||||
],
|
||||
"should not break with { character in key": 1
|
||||
}`
|
||||
o := New()
|
||||
err := json.Unmarshal([]byte(s), &o)
|
||||
if err != nil {
|
||||
t.Error("JSON Unmarshal error", err)
|
||||
}
|
||||
// Check the root keys
|
||||
expectedKeys := []string{
|
||||
"number",
|
||||
"string",
|
||||
"z",
|
||||
"a",
|
||||
"b",
|
||||
"slice",
|
||||
"orderedmap",
|
||||
"test\"ing",
|
||||
"after",
|
||||
"multitype_array",
|
||||
"should not break with { character in key",
|
||||
}
|
||||
k := o.Keys()
|
||||
for i := range k {
|
||||
if k[i] != expectedKeys[i] {
|
||||
t.Error("Unmarshal root key order", i, k[i], "!=", expectedKeys[i])
|
||||
}
|
||||
}
|
||||
// Check nested maps are converted to orderedmaps
|
||||
// nested 1 level deep
|
||||
expectedKeys = []string{
|
||||
"e",
|
||||
"a { nested key with brace",
|
||||
"after",
|
||||
}
|
||||
vi, ok := o.Get("orderedmap")
|
||||
if !ok {
|
||||
t.Error("Missing key for nested map 1 deep")
|
||||
}
|
||||
v := vi.(*Map)
|
||||
k = v.Keys()
|
||||
for i := range k {
|
||||
if k[i] != expectedKeys[i] {
|
||||
t.Error("Key order for nested map 1 deep ", i, k[i], "!=", expectedKeys[i])
|
||||
}
|
||||
}
|
||||
// nested 2 levels deep
|
||||
expectedKeys = []string{
|
||||
"link",
|
||||
}
|
||||
vi, ok = v.Get("after")
|
||||
if !ok {
|
||||
t.Error("Missing key for nested map 2 deep")
|
||||
}
|
||||
v = vi.(*Map)
|
||||
k = v.Keys()
|
||||
for i := range k {
|
||||
if k[i] != expectedKeys[i] {
|
||||
t.Error("Key order for nested map 2 deep", i, k[i], "!=", expectedKeys[i])
|
||||
}
|
||||
}
|
||||
// multitype array
|
||||
expectedKeys = []string{
|
||||
"map",
|
||||
"it",
|
||||
":colon in key",
|
||||
}
|
||||
vislice, ok := o.Get("multitype_array")
|
||||
if !ok {
|
||||
t.Error("Missing key for multitype array")
|
||||
}
|
||||
vslice := vislice.([]interface{})
|
||||
vmap := vslice[2].(*Map)
|
||||
k = vmap.Keys()
|
||||
for i := range k {
|
||||
if k[i] != expectedKeys[i] {
|
||||
t.Error("Key order for nested map 2 deep", i, k[i], "!=", expectedKeys[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalJSONSpecialChars(t *testing.T) {
|
||||
s := `{ " \\\\\\\\\\\\ " : { "\\\\\\" : "\\\\\"\\" }, "\\": " \\\\ test " }`
|
||||
o := New()
|
||||
err := json.Unmarshal([]byte(s), &o)
|
||||
if err != nil {
|
||||
t.Error("JSON Unmarshal error with special chars", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalJSONArrayOfMaps(t *testing.T) {
|
||||
s := `
|
||||
{
|
||||
"name": "test",
|
||||
"percent": 6,
|
||||
"breakdown": [
|
||||
{
|
||||
"name": "a",
|
||||
"percent": 0.9
|
||||
},
|
||||
{
|
||||
"name": "b",
|
||||
"percent": 0.9
|
||||
},
|
||||
{
|
||||
"name": "d",
|
||||
"percent": 0.4
|
||||
},
|
||||
{
|
||||
"name": "e",
|
||||
"percent": 2.7
|
||||
}
|
||||
]
|
||||
}
|
||||
`
|
||||
o := New()
|
||||
err := json.Unmarshal([]byte(s), &o)
|
||||
if err != nil {
|
||||
t.Error("JSON Unmarshal error", err)
|
||||
}
|
||||
// Check the root keys
|
||||
expectedKeys := []string{
|
||||
"name",
|
||||
"percent",
|
||||
"breakdown",
|
||||
}
|
||||
k := o.Keys()
|
||||
for i := range k {
|
||||
if k[i] != expectedKeys[i] {
|
||||
t.Error("Unmarshal root key order", i, k[i], "!=", expectedKeys[i])
|
||||
}
|
||||
}
|
||||
// Check nested maps are converted to orderedmaps
|
||||
// nested 1 level deep
|
||||
expectedKeys = []string{
|
||||
"name",
|
||||
"percent",
|
||||
}
|
||||
vi, ok := o.Get("breakdown")
|
||||
if !ok {
|
||||
t.Error("Missing key for nested map 1 deep")
|
||||
}
|
||||
vs := vi.([]interface{})
|
||||
for _, vInterface := range vs {
|
||||
v := vInterface.(*Map)
|
||||
k = v.Keys()
|
||||
for i := range k {
|
||||
if k[i] != expectedKeys[i] {
|
||||
t.Error("Key order for nested map 1 deep ", i, k[i], "!=", expectedKeys[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsertAt(t *testing.T) {
|
||||
om := New()
|
||||
om.Set("zero", 0)
|
||||
om.Set("one", 1)
|
||||
om.Set("two", 2)
|
||||
|
||||
err := om.InsertAt("TEST", 10000, 4) //3 is this added one in size of map
|
||||
if err == nil {
|
||||
t.Error("expected insert at greater position than size of map to produce error")
|
||||
}
|
||||
|
||||
err = om.InsertAt("A", 100, 2)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
// Test it's at end
|
||||
if om.values[om.keys[2]] != 100 {
|
||||
t.Error("expected entry A to be at position 2", om.keys)
|
||||
}
|
||||
if om.values[om.keys[3]] != 2 {
|
||||
t.Error("expected two to be in position 1", om.keys)
|
||||
}
|
||||
|
||||
err = om.InsertAt("B", 200, 0)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if om.values[om.keys[0]] != 200 {
|
||||
t.Error("expected B to be position 0", om.keys)
|
||||
}
|
||||
|
||||
err = om.InsertAt("C", 300, -1)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
// Should show up at the end
|
||||
if om.values[om.keys[len(om.keys)-1]] != 300 {
|
||||
t.Error(fmt.Sprintf("expected C to be in position %d", len(om.keys)-1), om.keys)
|
||||
}
|
||||
|
||||
err = om.InsertAt("D", 400, 1)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if om.values[om.keys[1]] != 400 {
|
||||
t.Error("expceted D to be position 1", om.keys)
|
||||
}
|
||||
|
||||
err = om.InsertAt("F", 600, -8)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if om.values[om.keys[0]] != 600 {
|
||||
t.Error("expected F to be in position 0", om.keys)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrency(t *testing.T) {
|
||||
wg := sync.WaitGroup{}
|
||||
type concurrency struct {
|
||||
a string
|
||||
b int
|
||||
c time.Time
|
||||
d bool
|
||||
}
|
||||
|
||||
//Starting Map
|
||||
m := New()
|
||||
m.Set("A", concurrency{"string", 10, time.Now(), true})
|
||||
m.Set("B", concurrency{"string", 10, time.Now(), true})
|
||||
m.Set("C", concurrency{"string", 10, time.Now(), true})
|
||||
m.Set("D", concurrency{"string", 10, time.Now(), true})
|
||||
m.Set("E", concurrency{"string", 10, time.Now(), true})
|
||||
m.Set("F", concurrency{"string", 10, time.Now(), true})
|
||||
m.Set("G", concurrency{"string", 10, time.Now(), true})
|
||||
m.Set("H", concurrency{"string", 10, time.Now(), true})
|
||||
//Inserts
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 50; i++ {
|
||||
wg.Add(1)
|
||||
go func(index int) {
|
||||
defer wg.Done()
|
||||
m.Set("New"+strconv.Itoa(index), concurrency{"string", index, time.Now(), cast.ToBool(index % 2)})
|
||||
}(i)
|
||||
}
|
||||
}()
|
||||
//Reads
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 50; i++ {
|
||||
wg.Add(1)
|
||||
go func(index int) {
|
||||
defer wg.Done()
|
||||
_, _ = m.Get("New" + strconv.Itoa(rand.Intn(99)))
|
||||
}(i)
|
||||
}
|
||||
}()
|
||||
//Marshalling like endpoint
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
for i := 0; i < 50; i++ {
|
||||
wg.Add(1)
|
||||
go func(index int) {
|
||||
defer wg.Done()
|
||||
_, err := m.MarshalJSON()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
}()
|
||||
|
||||
wg.Wait()
|
||||
|
||||
}
|
||||
@@ -1,35 +1,51 @@
|
||||
module github.com/lbryio/lbry.go/v2
|
||||
module github.com/lbryio/lbry.go
|
||||
|
||||
require (
|
||||
github.com/asaskevich/govalidator v0.0.0-20180720115003-f9ffefc3facf // indirect
|
||||
github.com/btcsuite/btcd v0.0.0-20190213025234-306aecffea32
|
||||
github.com/btcsuite/btcutil v0.0.0-20190207003914-4c204d697803
|
||||
github.com/davecgh/go-spew v1.1.1
|
||||
github.com/fatih/structs v1.1.0
|
||||
github.com/go-errors/errors v1.0.1
|
||||
github.com/go-ini/ini v1.38.2
|
||||
github.com/go-ozzo/ozzo-validation v3.5.0+incompatible // indirect
|
||||
github.com/golang/protobuf v1.3.0
|
||||
github.com/google/go-cmp v0.2.0 // indirect
|
||||
github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e // indirect
|
||||
github.com/gorilla/context v1.1.1 // indirect
|
||||
github.com/gorilla/mux v1.6.2
|
||||
github.com/gorilla/rpc v1.1.0
|
||||
github.com/lbryio/lbry.go v1.1.2
|
||||
github.com/lbryio/lbryschema.go v0.0.0-20190602173230-6d2f69a36f46
|
||||
github.com/gorilla/websocket v1.2.0 // indirect
|
||||
github.com/jtolds/gls v4.2.1+incompatible // indirect
|
||||
github.com/lbryio/errors.go v0.0.0-20180223142025-ad03d3cc6a5c
|
||||
github.com/lbryio/lbryschema.go v0.0.0-20190428231007-c54836bca002
|
||||
github.com/lbryio/ozzo-validation v0.0.0-20170323141101-d1008ad1fd04
|
||||
github.com/lbryio/types v0.0.0-20190422033210-321fb2abda9c
|
||||
github.com/lusis/go-slackbot v0.0.0-20180109053408-401027ccfef5 // indirect
|
||||
github.com/lusis/slack-test v0.0.0-20180109053238-3c758769bfa6 // indirect
|
||||
github.com/lyoshenka/bencode v0.0.0-20180323155644-b7abd7672df5
|
||||
github.com/mitchellh/mapstructure v0.0.0-20180511142126-bb74f1db0675
|
||||
github.com/nlopes/slack v0.5.0
|
||||
github.com/pkg/errors v0.8.1 // indirect
|
||||
github.com/sebdah/goldie v0.0.0-20180424091453-8784dd1ab561
|
||||
github.com/sergi/go-diff v1.0.0
|
||||
github.com/shopspring/decimal v0.0.0-20180607144847-19e3cb6c2930
|
||||
github.com/sirupsen/logrus v1.2.0
|
||||
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d // indirect
|
||||
github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c // indirect
|
||||
github.com/spf13/cast v1.2.0
|
||||
github.com/stretchr/testify v1.3.0
|
||||
github.com/uber-go/atomic v1.3.2
|
||||
github.com/ybbus/jsonrpc v0.0.0-20180411222309-2a548b7d822d
|
||||
go.uber.org/atomic v1.3.2 // indirect
|
||||
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793
|
||||
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f // indirect
|
||||
golang.org/x/sys v0.0.0-20190520201301-c432e742b0af // indirect
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c
|
||||
google.golang.org/genproto v0.0.0-20181004005441-af9cb2a35e7f // indirect
|
||||
google.golang.org/grpc v1.17.0
|
||||
gopkg.in/ini.v1 v1.41.0 // indirect
|
||||
gopkg.in/nullbio/null.v6 v6.0.0-20161116030900-40264a2e6b79
|
||||
gotest.tools v2.2.0+incompatible // indirect
|
||||
)
|
||||
|
||||
go 1.12
|
||||
@@ -66,12 +66,10 @@ github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23 h1:FOOIBWrEkLgmlgGfM
|
||||
github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/lbryio/errors.go v0.0.0-20180223142025-ad03d3cc6a5c h1:BhdcWGsuKif/XoSZnqVGNqJ1iEmH0czWR5upj+AuR8M=
|
||||
github.com/lbryio/errors.go v0.0.0-20180223142025-ad03d3cc6a5c/go.mod h1:muH7wpUqE8hRA3OrYYosw9+Sl681BF9cwcjzE+OCNK8=
|
||||
github.com/lbryio/lbry.go v1.1.2 h1:Dyxc+glT/rVWJwHfIf7vjlPYYbjzrQz5ARmJd5Hp69c=
|
||||
github.com/lbryio/lbry.go v1.1.2/go.mod h1:JtyI30bU51rm0LZ/po3mQuzf++14OWb6kR/6mMRAmKU=
|
||||
github.com/lbryio/lbryschema.go v0.0.0-20190428231007-c54836bca002 h1:urfYK5ElpUrAv90auPLldoVC60LwiGAcY0OE6HJB9KI=
|
||||
github.com/lbryio/lbryschema.go v0.0.0-20190428231007-c54836bca002/go.mod h1:dAzPCBj3CKKWBGYBZxK6tKBP5SCgY2tqd9SnQd/OyKo=
|
||||
github.com/lbryio/lbryschema.go v0.0.0-20190602173230-6d2f69a36f46 h1:LemfR+rMxhf7nnOrzy2HqS7Me7SZ5gEwOcNFzKC8ySQ=
|
||||
github.com/lbryio/lbryschema.go v0.0.0-20190602173230-6d2f69a36f46/go.mod h1:dAzPCBj3CKKWBGYBZxK6tKBP5SCgY2tqd9SnQd/OyKo=
|
||||
github.com/lbryio/ozzo-validation v0.0.0-20170323141101-d1008ad1fd04 h1:Nze+C2HbeKvhjI/kVn+9Poj/UuEW5sOQxcsxqO7L3GI=
|
||||
github.com/lbryio/ozzo-validation v0.0.0-20170323141101-d1008ad1fd04/go.mod h1:fbG/dzobG8r95KzMwckXiLMHfFjZaBRQqC9hPs2XAQ4=
|
||||
github.com/lbryio/types v0.0.0-20190422033210-321fb2abda9c h1:m3O7561xBQ00lfUVayW4c6SnpVbUDQtPUwGcGYSUYQA=
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
package lbrycrd
|
||||
|
||||
import (
|
||||
"github.com/btcsuite/btcd/btcec"
|
||||
"github.com/lbryio/lbry.go/extras/errors"
|
||||
c "github.com/lbryio/lbryschema.go/claim"
|
||||
pb "github.com/lbryio/types/v2/go"
|
||||
)
|
||||
|
||||
func NewChannel() (*c.ClaimHelper, *btcec.PrivateKey, error) {
|
||||
claimChannel := new(pb.Claim_Channel)
|
||||
channel := new(pb.Channel)
|
||||
claimChannel.Channel = channel
|
||||
|
||||
pbClaim := new(pb.Claim)
|
||||
pbClaim.Type = claimChannel
|
||||
|
||||
privateKey, err := btcec.NewPrivateKey(btcec.S256())
|
||||
if err != nil {
|
||||
return nil, nil, errors.Err(err)
|
||||
}
|
||||
pubkeyBytes, err := c.PublicKeyToDER(privateKey.PubKey())
|
||||
if err != nil {
|
||||
return nil, nil, errors.Err(err)
|
||||
}
|
||||
|
||||
helper := c.ClaimHelper{Claim: pbClaim}
|
||||
helper.Version = c.NoSig
|
||||
helper.GetChannel().PublicKey = pubkeyBytes
|
||||
helper.Tags = []string{}
|
||||
coverSrc := new(pb.Source)
|
||||
helper.GetChannel().Cover = coverSrc
|
||||
helper.Languages = []*pb.Language{}
|
||||
thumbnailSrc := new(pb.Source)
|
||||
helper.Thumbnail = thumbnailSrc
|
||||
helper.Locations = []*pb.Location{}
|
||||
|
||||
return &helper, privateKey, nil
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
package lbrycrd
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
|
||||
"github.com/lbryio/lbry.go/extras/errors"
|
||||
c "github.com/lbryio/lbryschema.go/claim"
|
||||
pb "github.com/lbryio/types/v2/go"
|
||||
|
||||
"github.com/btcsuite/btcd/btcec"
|
||||
"github.com/btcsuite/btcd/wire"
|
||||
)
|
||||
|
||||
func NewImageStreamClaim() (*c.ClaimHelper, error) {
|
||||
streamClaim := new(pb.Claim_Stream)
|
||||
stream := new(pb.Stream)
|
||||
image := new(pb.Stream_Image)
|
||||
image.Image = new(pb.Image)
|
||||
stream.Type = image
|
||||
|
||||
streamClaim.Stream = stream
|
||||
|
||||
pbClaim := new(pb.Claim)
|
||||
pbClaim.Type = streamClaim
|
||||
|
||||
helper := c.ClaimHelper{Claim: pbClaim}
|
||||
|
||||
return &helper, nil
|
||||
}
|
||||
|
||||
func NewVideoStreamClaim() (*c.ClaimHelper, error) {
|
||||
streamClaim := new(pb.Claim_Stream)
|
||||
stream := new(pb.Stream)
|
||||
video := new(pb.Stream_Video)
|
||||
video.Video = new(pb.Video)
|
||||
stream.Type = video
|
||||
streamClaim.Stream = stream
|
||||
|
||||
pbClaim := new(pb.Claim)
|
||||
pbClaim.Type = streamClaim
|
||||
|
||||
helper := c.ClaimHelper{Claim: pbClaim}
|
||||
|
||||
return &helper, nil
|
||||
}
|
||||
|
||||
func NewStreamClaim(title, description string) (*c.ClaimHelper, error) {
|
||||
streamClaim := new(pb.Claim_Stream)
|
||||
stream := new(pb.Stream)
|
||||
streamClaim.Stream = stream
|
||||
|
||||
pbClaim := new(pb.Claim)
|
||||
pbClaim.Type = streamClaim
|
||||
|
||||
helper := c.ClaimHelper{Claim: pbClaim}
|
||||
helper.Title = title
|
||||
helper.Description = description
|
||||
|
||||
return &helper, nil
|
||||
}
|
||||
|
||||
func SignClaim(rawTx *wire.MsgTx, privKey btcec.PrivateKey, claim, channel *c.ClaimHelper, channelClaimID string) error {
|
||||
claimIDHexBytes, err := hex.DecodeString(channelClaimID)
|
||||
if err != nil {
|
||||
return errors.Err(err)
|
||||
}
|
||||
claim.Version = c.WithSig
|
||||
claim.ClaimID = rev(claimIDHexBytes)
|
||||
hash, err := c.GetOutpointHash(rawTx.TxIn[0].PreviousOutPoint.Hash.String(), rawTx.TxIn[0].PreviousOutPoint.Index)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sig, err := c.Sign(privKey, *channel, *claim, hash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
lbrySig, err := sig.LBRYSDKEncode()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
claim.Signature = lbrySig
|
||||
|
||||
return nil
|
||||
|
||||
}
|
||||
+24
-214
@@ -1,20 +1,15 @@
|
||||
package lbrycrd
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/lbryio/lbry.go/extras/errors"
|
||||
c "github.com/lbryio/lbryschema.go/claim"
|
||||
|
||||
"github.com/btcsuite/btcd/btcec"
|
||||
"github.com/btcsuite/btcd/btcjson"
|
||||
"github.com/btcsuite/btcd/chaincfg"
|
||||
"github.com/btcsuite/btcd/chaincfg/chainhash"
|
||||
"github.com/btcsuite/btcd/rpcclient"
|
||||
"github.com/btcsuite/btcd/wire"
|
||||
"github.com/btcsuite/btcutil"
|
||||
"github.com/go-ini/ini"
|
||||
)
|
||||
@@ -38,39 +33,6 @@ var MainNetParams = chaincfg.Params{
|
||||
Name: "mainnet",
|
||||
}
|
||||
|
||||
const (
|
||||
lbrycrdMainPubkeyPrefix = byte(85)
|
||||
lbrycrdMainScriptPrefix = byte(122)
|
||||
lbrycrdTestnetPubkeyPrefix = byte(111)
|
||||
lbrycrdTestnetScriptPrefix = byte(196)
|
||||
lbrycrdRegtestPubkeyPrefix = byte(111)
|
||||
lbrycrdRegtestScriptPrefix = byte(196)
|
||||
|
||||
LbrycrdMain = "lbrycrd_main"
|
||||
LbrycrdTestnet = "lbrycrd_testnet"
|
||||
LbrycrdRegtest = "lbrycrd_regtest"
|
||||
)
|
||||
|
||||
var mainNetParams = chaincfg.Params{
|
||||
PubKeyHashAddrID: lbrycrdMainPubkeyPrefix,
|
||||
ScriptHashAddrID: lbrycrdMainScriptPrefix,
|
||||
PrivateKeyID: 0x1c,
|
||||
}
|
||||
|
||||
var testNetParams = chaincfg.Params{
|
||||
PubKeyHashAddrID: lbrycrdTestnetPubkeyPrefix,
|
||||
ScriptHashAddrID: lbrycrdTestnetScriptPrefix,
|
||||
PrivateKeyID: 0x1c,
|
||||
}
|
||||
|
||||
var regTestNetParams = chaincfg.Params{
|
||||
PubKeyHashAddrID: lbrycrdRegtestPubkeyPrefix,
|
||||
ScriptHashAddrID: lbrycrdRegtestScriptPrefix,
|
||||
PrivateKeyID: 0x1c,
|
||||
}
|
||||
|
||||
var ChainParamsMap = map[string]chaincfg.Params{LbrycrdMain: mainNetParams, LbrycrdTestnet: testNetParams, LbrycrdRegtest: regTestNetParams}
|
||||
|
||||
func init() {
|
||||
// Register lbrycrd network
|
||||
err := chaincfg.Register(&MainNetParams)
|
||||
@@ -153,6 +115,30 @@ func (c *Client) SimpleSend(toAddress string, amount float64) (*chainhash.Hash,
|
||||
return hash, nil
|
||||
}
|
||||
|
||||
//func (c *Client) SendWithSplit(toAddress string, amount float64, numUTXOs int) (*chainhash.Hash, error) {
|
||||
// decodedAddress, err := DecodeAddress(toAddress, &MainNetParams)
|
||||
// if err != nil {
|
||||
// return nil, errors.Wrap(err, 0)
|
||||
// }
|
||||
//
|
||||
// amountPerAddress, err := btcutil.NewAmount(amount / float64(numUTXOs))
|
||||
// if err != nil {
|
||||
// return nil, errors.Wrap(err, 0)
|
||||
// }
|
||||
//
|
||||
// amounts := map[btcutil.Address]btcutil.Amount{}
|
||||
// for i := 0; i < numUTXOs; i++ {
|
||||
// addr := decodedAddress // to give it a new address, so
|
||||
// amounts[addr] = amountPerAddress
|
||||
// }
|
||||
//
|
||||
// hash, err := c.Client.SendManyMinConf("", amounts, 0)
|
||||
// if err != nil && err.Error() == "-6: Insufficient funds" {
|
||||
// err = errors.Wrap(errInsufficientFunds, 0)
|
||||
// }
|
||||
// return hash, errors.Wrap(err, 0)
|
||||
//}
|
||||
|
||||
func getLbrycrdURLFromConfFile() (string, error) {
|
||||
if os.Getenv("HOME") == "" {
|
||||
return "", errors.Err("no $HOME var found")
|
||||
@@ -194,179 +180,3 @@ func getLbrycrdURLFromConfFile() (string, error) {
|
||||
|
||||
return "rpc://" + userpass + host + ":" + port, nil
|
||||
}
|
||||
|
||||
func (c *Client) CreateBaseRawTx(inputs []btcjson.TransactionInput, change float64) (*wire.MsgTx, error) {
|
||||
addresses := make(map[btcutil.Address]btcutil.Amount)
|
||||
changeAddress, err := c.GetNewAddress("")
|
||||
if err != nil {
|
||||
return nil, errors.Err(err)
|
||||
}
|
||||
changeAmount, err := btcutil.NewAmount(change)
|
||||
if err != nil {
|
||||
return nil, errors.Err(err)
|
||||
}
|
||||
addresses[changeAddress] = changeAmount
|
||||
lockTime := int64(0)
|
||||
return c.CreateRawTransaction(inputs, addresses, &lockTime)
|
||||
}
|
||||
|
||||
func (c *Client) GetEmptyTx(totalOutputSpend float64) (*wire.MsgTx, error) {
|
||||
totalFees := 0.1
|
||||
unspentResults, err := c.ListUnspentMin(1)
|
||||
if err != nil {
|
||||
return nil, errors.Err(err)
|
||||
}
|
||||
finder := newOutputFinder(unspentResults)
|
||||
|
||||
outputs, err := finder.nextBatch(totalOutputSpend + totalFees)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(outputs) == 0 {
|
||||
return nil, errors.Err("Not enough spendable outputs to create transaction")
|
||||
}
|
||||
inputs := make([]btcjson.TransactionInput, len(outputs))
|
||||
var totalInputSpend float64
|
||||
for i, output := range outputs {
|
||||
inputs[i] = btcjson.TransactionInput{Txid: output.TxID, Vout: output.Vout}
|
||||
totalInputSpend = totalInputSpend + output.Amount
|
||||
}
|
||||
|
||||
change := totalInputSpend - totalOutputSpend - totalFees
|
||||
return c.CreateBaseRawTx(inputs, change)
|
||||
}
|
||||
|
||||
func (c *Client) SignTxAndSend(rawTx *wire.MsgTx) (*chainhash.Hash, error) {
|
||||
signedTx, allInputsSigned, err := c.SignRawTransaction(rawTx)
|
||||
if err != nil {
|
||||
return nil, errors.Err(err)
|
||||
}
|
||||
if !allInputsSigned {
|
||||
return nil, errors.Err("Not all inputs for the tx could be signed!")
|
||||
}
|
||||
|
||||
return c.SendRawTransaction(signedTx, false)
|
||||
}
|
||||
|
||||
type ScriptType int
|
||||
|
||||
const (
|
||||
ClaimName ScriptType = iota
|
||||
ClaimUpdate
|
||||
ClaimSupport
|
||||
)
|
||||
|
||||
func (c *Client) AddStakeToTx(rawTx *wire.MsgTx, claim *c.ClaimHelper, name string, claimAmount float64, scriptType ScriptType) error {
|
||||
|
||||
address, err := c.GetNewAddress("")
|
||||
if err != nil {
|
||||
return errors.Err(err)
|
||||
}
|
||||
amount, err := btcutil.NewAmount(claimAmount)
|
||||
if err != nil {
|
||||
return errors.Err(err)
|
||||
}
|
||||
|
||||
value, err := claim.CompileValue()
|
||||
if err != nil {
|
||||
return errors.Err(err)
|
||||
}
|
||||
var claimID string
|
||||
if len(claim.ClaimID) > 0 {
|
||||
claimID = hex.EncodeToString(rev(claim.ClaimID))
|
||||
}
|
||||
var script []byte
|
||||
switch scriptType {
|
||||
case ClaimName:
|
||||
script, err = getClaimNamePayoutScript(name, value, address)
|
||||
if err != nil {
|
||||
return errors.Err(err)
|
||||
}
|
||||
case ClaimUpdate:
|
||||
script, err = getUpdateClaimPayoutScript(name, claimID, value, address)
|
||||
if err != nil {
|
||||
return errors.Err(err)
|
||||
}
|
||||
case ClaimSupport:
|
||||
script, err = getUpdateClaimPayoutScript(name, claimID, value, address)
|
||||
if err != nil {
|
||||
return errors.Err(err)
|
||||
}
|
||||
}
|
||||
|
||||
rawTx.AddTxOut(wire.NewTxOut(int64(amount), script))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) CreateChannel(name string, amount float64) (*c.ClaimHelper, *btcec.PrivateKey, error) {
|
||||
channel, key, err := NewChannel()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
rawTx, err := c.GetEmptyTx(amount)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
err = c.AddStakeToTx(rawTx, channel, name, amount, ClaimName)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
_, err = c.SignTxAndSend(rawTx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
return channel, key, nil
|
||||
}
|
||||
|
||||
func (c *Client) SupportClaim(name, claimID, address, blockchainName string, claimAmount float64) (*chainhash.Hash, error) {
|
||||
const DefaultFeePerSupport = float64(0.0001)
|
||||
unspentResults, err := c.ListUnspentMin(1)
|
||||
if err != nil {
|
||||
return nil, errors.Err(err)
|
||||
}
|
||||
|
||||
finder := newOutputFinder(unspentResults)
|
||||
outputs, err := finder.nextBatch(claimAmount + DefaultFeePerSupport)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(outputs) == 0 {
|
||||
return nil, errors.Err("Not enough spendable outputs to create transaction")
|
||||
}
|
||||
inputs := make([]btcjson.TransactionInput, len(outputs))
|
||||
|
||||
var totalInputSpend float64
|
||||
for i, output := range outputs {
|
||||
inputs[i] = btcjson.TransactionInput{Txid: output.TxID, Vout: output.Vout}
|
||||
totalInputSpend = totalInputSpend + output.Amount
|
||||
}
|
||||
|
||||
change := totalInputSpend - claimAmount - DefaultFeePerSupport
|
||||
rawTx, err := c.CreateBaseRawTx(inputs, change)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
chainParams, ok := ChainParamsMap[blockchainName]
|
||||
if !ok {
|
||||
return nil, errors.Err("invalid blockchain name %s", blockchainName)
|
||||
}
|
||||
decodedAddress, err := DecodeAddress(address, &chainParams)
|
||||
if err != nil {
|
||||
return nil, errors.Err(err)
|
||||
}
|
||||
amount, err := btcutil.NewAmount(claimAmount)
|
||||
if err != nil {
|
||||
return nil, errors.Err(err)
|
||||
}
|
||||
script, err := getClaimSupportPayoutScript(name, claimID, decodedAddress)
|
||||
if err != nil {
|
||||
return nil, errors.Err(err)
|
||||
}
|
||||
rawTx.AddTxOut(wire.NewTxOut(int64(amount), script))
|
||||
|
||||
return c.SignTxAndSend(rawTx)
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package lbrycrd
|
||||
|
||||
import (
|
||||
"github.com/lbryio/lbry.go/extras/errors"
|
||||
|
||||
"github.com/btcsuite/btcd/btcjson"
|
||||
)
|
||||
|
||||
type outputFinder struct {
|
||||
unspent []btcjson.ListUnspentResult
|
||||
lastChecked int
|
||||
}
|
||||
|
||||
func newOutputFinder(unspentResults []btcjson.ListUnspentResult) *outputFinder {
|
||||
return &outputFinder{unspent: unspentResults, lastChecked: -1}
|
||||
}
|
||||
|
||||
func (f *outputFinder) nextBatch(minAmount float64) ([]btcjson.ListUnspentResult, error) {
|
||||
var batch []btcjson.ListUnspentResult
|
||||
var lbcBatched float64
|
||||
for i, unspent := range f.unspent {
|
||||
if i > f.lastChecked {
|
||||
if unspent.Spendable {
|
||||
batch = append(batch, unspent)
|
||||
lbcBatched = lbcBatched + unspent.Amount
|
||||
}
|
||||
}
|
||||
if lbcBatched >= minAmount {
|
||||
f.lastChecked = i
|
||||
break
|
||||
}
|
||||
if i == len(f.unspent)-1 {
|
||||
return nil, errors.Err("Not enough unspent outputs to spend %d on supports.", minAmount)
|
||||
}
|
||||
}
|
||||
|
||||
return batch, nil
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package lbrycrd
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
|
||||
"github.com/lbryio/lbry.go/extras/errors"
|
||||
|
||||
"github.com/btcsuite/btcd/txscript"
|
||||
"github.com/btcsuite/btcutil"
|
||||
)
|
||||
|
||||
func getClaimSupportPayoutScript(name, claimid string, address btcutil.Address) ([]byte, error) {
|
||||
//OP_SUPPORT_CLAIM <name> <claimid> OP_2DROP OP_DROP OP_DUP OP_HASH160 <address> OP_EQUALVERIFY OP_CHECKSIG
|
||||
|
||||
pkscript, err := txscript.PayToAddrScript(address)
|
||||
if err != nil {
|
||||
return nil, errors.Err(err)
|
||||
}
|
||||
|
||||
bytes, err := hex.DecodeString(claimid)
|
||||
if err != nil {
|
||||
return nil, errors.Err(err)
|
||||
}
|
||||
|
||||
return txscript.NewScriptBuilder().
|
||||
AddOp(txscript.OP_NOP7). //OP_SUPPORT_CLAIM
|
||||
AddData([]byte(name)). //<name>
|
||||
AddData(rev(bytes)). //<claimid>
|
||||
AddOp(txscript.OP_2DROP). //OP_2DROP
|
||||
AddOp(txscript.OP_DROP). //OP_DROP
|
||||
AddOps(pkscript). //OP_DUP OP_HASH160 <address> OP_EQUALVERIFY OP_CHECKSIG
|
||||
Script()
|
||||
|
||||
}
|
||||
|
||||
func getClaimNamePayoutScript(name string, value []byte, address btcutil.Address) ([]byte, error) {
|
||||
//OP_CLAIM_NAME <name> <value> OP_2DROP OP_DROP OP_DUP OP_HASH160 <address> OP_EQUALVERIFY OP_CHECKSIG
|
||||
|
||||
pkscript, err := txscript.PayToAddrScript(address)
|
||||
if err != nil {
|
||||
return nil, errors.Err(err)
|
||||
}
|
||||
|
||||
return txscript.NewScriptBuilder().
|
||||
AddOp(txscript.OP_NOP6). //OP_CLAIMNAME
|
||||
AddData([]byte(name)). //<name>
|
||||
AddData(value). //<value>
|
||||
AddOp(txscript.OP_2DROP). //OP_2DROP
|
||||
AddOp(txscript.OP_DROP). //OP_DROP
|
||||
AddOps(pkscript). //OP_DUP OP_HASH160 <address> OP_EQUALVERIFY OP_CHECKSIG
|
||||
Script()
|
||||
}
|
||||
|
||||
func getUpdateClaimPayoutScript(name, claimid string, value []byte, address btcutil.Address) ([]byte, error) {
|
||||
//OP_UPDATE_CLAIM <name> <claimid> <value> OP_2DROP OP_DROP OP_DUP OP_HASH160 <address> OP_EQUALVERIFY OP_CHECKSIG
|
||||
|
||||
pkscript, err := txscript.PayToAddrScript(address)
|
||||
if err != nil {
|
||||
return nil, errors.Err(err)
|
||||
}
|
||||
|
||||
bytes, err := hex.DecodeString(claimid)
|
||||
if err != nil {
|
||||
return nil, errors.Err(err)
|
||||
}
|
||||
|
||||
return txscript.NewScriptBuilder().
|
||||
AddOp(txscript.OP_NOP8). //OP_UPDATE_CLAIM
|
||||
AddData([]byte(name)). //<name>
|
||||
AddData(rev(bytes)). //<claimid>
|
||||
AddData(value). //<value>
|
||||
AddOp(txscript.OP_2DROP). //OP_2DROP
|
||||
AddOp(txscript.OP_DROP). //OP_DROP
|
||||
AddOps(pkscript). //OP_DUP OP_HASH160 <address> OP_EQUALVERIFY OP_CHECKSIG
|
||||
Script()
|
||||
}
|
||||
+1
-5
@@ -11,11 +11,7 @@ import (
|
||||
"github.com/lbryio/lbry.go/extras/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
MaxBlobSize = 2097152 // 2mb, or 2 * 2^20
|
||||
BlobHashSize = sha512.Size384
|
||||
BlobHashHexLength = BlobHashSize * 2 // in hex, each byte is 2 chars
|
||||
)
|
||||
const MaxBlobSize = 2097152 // 2mb, or 2 * 2^20
|
||||
|
||||
type Blob []byte
|
||||
|
||||
|
||||
Reference in new issue
Block a user