Compare commits

...
26 Commits
Author SHA1 Message Date
Niko Storni 1155ea6b9d add stream_list 2019-10-10 04:29:11 +02:00
Alex Grin 6918a2436a Merge pull request #74 from StrikerRUS/patch-1
bump year in license
2019-10-09 10:37:13 -04:00
Nikita Titov 7e524c6b08 bump year in license 2019-10-09 00:06:05 +03:00
sayplastic 9c278d131d Merge pull request #73 from lbryio/feature/wallet
Add wallet commands to JSON-RPC client
2019-10-08 13:08:57 +07:00
Niko Storni b1c090e28d fix claim search not returning claim values 2019-10-03 22:50:07 +02:00
Andrey Beletsky b03e0a7db8 Go mod tidy 2019-10-04 01:09:42 +07:00
Andrey Beletsky 33071ff6c1 Add test for wallet-less ChannelImport call 2019-10-04 00:51:24 +07:00
Andrey Beletsky 30a9a39248 Add ChannelImport method 2019-10-03 20:03:31 +07:00
Andrey Beletsky 49c9531404 Fix wallet opts passing 2019-10-02 14:56:37 +07:00
Andrey Beletsky c68c7e05fe Bring back versioning to the module 2019-10-02 14:36:04 +07:00
Andrey Beletsky 534831e6e5 Improve args passing to SDK for WalletCreate command 2019-10-02 14:29:13 +07:00
Niko Storni deab868c53 add bid to channel update params 2019-09-27 15:36:23 +02:00
Andrey Beletsky d5102a9cf6 Add WalletList command 2019-09-25 18:00:37 +07:00
Andrey Beletsky ac75979453 Add wallet commands to JSON-RPC client 2019-09-25 17:47:12 +07:00
Niko Storni 712e346bd2 woopsy 2019-09-24 20:37:03 +02:00
Niko Storni 85e34cb335 add accountAdd support
refactor account management
2019-09-24 20:35:04 +02:00
Niko Storni c36c67961f Merge branch 'accountid-and-missing' 2019-09-24 18:31:17 +02:00
Niko Storni 025c715ab4 align to new SDK v0.42.0 2019-09-24 18:31:01 +02:00
Thomas Zarebczan af728f12d9 add new types
Wasn't sure about type `UTXOReleaseResponse *string` 

This is the response: ```
{
  "jsonrpc": "2.0",
  "result": null
}
```
2019-09-24 16:04:13 +02:00
Thomas Zarebczan 1f1848a408 Adds account_id to channel create (and update), missing functions 2019-09-24 16:04:13 +02:00
Niko Storni d032c842d5 remove problematic data 2019-09-24 16:03:49 +02:00
Niko Storni d6f5199acd tidy up go mods 2019-09-24 16:02:26 +02:00
sayplastic 28aad86e4a Merge pull request #72 from lbryio/feature/remote_ip
Forward real IP in internal-api client calls
2019-09-20 13:52:07 +07:00
Andrey Beletsky c5c634e477 Pass user method url as a constant 2019-09-20 13:47:45 +07:00
Andrey Beletsky a8c339e5b4 Forward real IP in internal-api client calls 2019-09-18 18:02:03 +07:00
Alex Grintsvayg fd916d9eae expose blob hash sizes as constants 2019-09-10 16:42:36 -04:00
10 changed files with 522 additions and 133 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2016-2018 LBRY Inc
Copyright (c) 2016-2019 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
View File
@@ -134,7 +134,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
jsonResponse, err = json.MarshalIndent(&apiResponse{
Success: false,
Error: util.PtrToString(err.Error()),
Data: rsp.Data,
Data: nil,
Trace: getTraceFromError(err),
}, "", " ")
if err != nil {
+132 -23
View File
@@ -10,9 +10,8 @@ import (
"strings"
"time"
"github.com/lbryio/lbry.go/extras/errors"
"github.com/fatih/structs"
"github.com/lbryio/lbry.go/extras/errors"
"github.com/mitchellh/mapstructure"
"github.com/shopspring/decimal"
log "github.com/sirupsen/logrus"
@@ -138,11 +137,17 @@ 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})
@@ -190,16 +195,16 @@ func (d *Client) AccountFund(fromAccount string, toAccount string, amount string
})
}
func (d *Client) AccountCreate(accountName string, singleKey bool) (*AccountCreateResponse, error) {
response := new(AccountCreateResponse)
func (d *Client) AccountCreate(accountName string, singleKey bool) (*Account, error) {
response := new(Account)
return response, d.call(response, "account_create", map[string]interface{}{
"account_name": accountName,
"single_key": singleKey,
})
}
func (d *Client) AccountRemove(accountID string) (*AccountRemoveResponse, error) {
response := new(AccountRemoveResponse)
func (d *Client) AccountRemove(accountID string) (*Account, error) {
response := new(Account)
return response, d.call(response, "account_remove", map[string]interface{}{
"account_id": accountID,
})
@@ -212,7 +217,7 @@ func (d *Client) AddressUnused(account *string) (*AddressUnusedResponse, error)
})
}
func (d *Client) ChannelList(account *string, page uint64, pageSize uint64) (*ChannelListResponse, error) {
func (d *Client) ChannelList(account *string, page uint64, pageSize uint64, wid *string) (*ChannelListResponse, error) {
if page == 0 {
return nil, errors.Err("pages start from 1")
}
@@ -222,6 +227,7 @@ func (d *Client) ChannelList(account *string, page uint64, pageSize uint64) (*Ch
"page": page,
"page_size": pageSize,
"include_protobuf": true,
"wallet_id": wid,
})
}
@@ -259,6 +265,7 @@ 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) {
@@ -283,11 +290,12 @@ 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"`
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"`
}
func (d *Client) ChannelUpdate(claimID string, options ChannelUpdateOptions) (*TransactionSummary, error) {
@@ -407,11 +415,30 @@ func (d *Client) ChannelAbandon(txID string, nOut uint64, accountID *string, blo
return response, nil
}
func (d *Client) AddressList(account *string) (*AddressListResponse, error) {
func (d *Client) AddressList(account *string, address *string) (*AddressListResponse, error) {
response := new(AddressListResponse)
return response, d.call(response, "address_list", map[string]interface{}{
"account_id": account,
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,
})
if err != nil {
return nil, err
}
return response, nil
}
func (d *Client) ClaimList(account *string, page uint64, pageSize uint64) (*ClaimListResponse, error) {
@@ -436,6 +463,13 @@ 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{}{
@@ -443,6 +477,13 @@ 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{}{
@@ -474,15 +515,17 @@ 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"`
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: claimID,
TXID: txid,
Nout: nout,
Name: claimName,
ClaimID: claimID,
TXID: txid,
Nout: nout,
Name: claimName,
IncludeProtobuf: true,
}
structs.DefaultTagName = "json"
return response, d.call(response, "claim_search", structs.Map(args))
@@ -497,6 +540,14 @@ func (d *Client) ChannelExport(channelClaimID string, channelName, accountID *st
})
}
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{}{
@@ -552,3 +603,61 @@ func (d *Client) SupportAbandon(claimID *string, txid *string, nout *uint, keep
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})
}
+220 -11
View File
@@ -3,6 +3,7 @@ package jsonrpc
import (
"encoding/json"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
@@ -21,6 +22,12 @@ 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()
@@ -59,17 +66,20 @@ func TestClient_AccountList(t *testing.T) {
func TestClient_SingleAccountList(t *testing.T) {
d := NewClient("")
createdAccount, err := d.AccountCreate("test"+fmt.Sprintf("%d", time.Now().Unix())+"@lbry.com", false)
name := "test" + fmt.Sprintf("%d", rand.Int()) + "@lbry.com"
createdAccount, err := d.AccountCreate(name, 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
}
prettyPrint(*account)
if account.Name != name {
t.Fatalf("account name mismatch: %v != %v", account.Name, name)
}
}
func TestClient_AccountBalance(t *testing.T) {
@@ -94,7 +104,7 @@ func TestClient_AddressUnused(t *testing.T) {
func TestClient_ChannelList(t *testing.T) {
d := NewClient("")
got, err := d.ChannelList(nil, 1, 50)
got, err := d.ChannelList(nil, 1, 50, nil)
if err != nil {
t.Error(err)
return
@@ -186,6 +196,7 @@ func TestClient_StreamCreate(t *testing.T) {
func TestClient_ChannelUpdate(t *testing.T) {
d := NewClient("")
got, err := d.ChannelUpdate(channelID, ChannelUpdateOptions{
Bid: util.PtrToString("0.01"),
ClearLanguages: util.PtrToBool(true),
ClearLocations: util.PtrToBool(true),
ClearTags: util.PtrToBool(true),
@@ -250,7 +261,7 @@ func TestClient_ChannelAbandon(t *testing.T) {
func TestClient_AddressList(t *testing.T) {
d := NewClient("")
got, err := d.AddressList(nil)
got, err := d.AddressList(nil, nil)
if err != nil {
t.Error(err)
return
@@ -269,6 +280,28 @@ 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("")
@@ -421,7 +454,7 @@ func TestClient_AccountSet(t *testing.T) {
func TestClient_AccountCreate(t *testing.T) {
d := NewClient("")
name := "test" + fmt.Sprintf("%d", time.Now().Unix()) + "@lbry.com"
name := "lbry#user#id:" + fmt.Sprintf("%d", rand.Int())
account, err := d.AccountCreate(name, false)
if err != nil {
t.Fatal(err)
@@ -434,9 +467,30 @@ 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("")
createdAccount, err := d.AccountCreate("test"+fmt.Sprintf("%d", time.Now().Unix())+"@lbry.com", false)
name := "lbry#user#id:" + fmt.Sprintf("%d", rand.Int())
createdAccount, err := d.AccountCreate(name, false)
if err != nil {
t.Fatal(err)
return
@@ -456,9 +510,7 @@ func TestClient_AccountRemove(t *testing.T) {
prettyPrint(*removedAccount)
return
}
t.Error(err)
return
t.Fatal(err)
}
t.Error("account was not removed")
prettyPrint(*account)
@@ -475,3 +527,160 @@ 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)
}
}
+68 -21
View File
@@ -204,14 +204,21 @@ 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"`
Name string `json:"name"`
PublicKey string `json:"public_key"`
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"`
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"`
}
type AccountListResponse struct {
@@ -227,18 +234,6 @@ type AccountBalanceResponse struct {
Total decimal.Decimal `json:"total"`
}
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"`
@@ -270,8 +265,15 @@ type AccountFundResponse TransactionSummary
type Address string
type AddressUnusedResponse Address
type AddressListResponse []Address
type AddressListResponse []struct {
Account string `json:"account"`
Address Address `json:"address"`
Pubkey string `json:"pubkey"`
UsedTimes uint64 `json:"used_times"`
}
type ChannelExportResponse string
type ChannelImportResponse string
type ChannelListResponse struct {
Items []Transaction `json:"items"`
@@ -394,6 +396,8 @@ 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"`
@@ -471,6 +475,42 @@ 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"`
@@ -502,3 +542,10 @@ type NumClaimsInChannelResponse map[string]struct {
}
type ClaimShowResponse *Claim
type Wallet struct {
ID string `json:"id"`
Name string `json:"name"`
}
type WalletList []Wallet
+40 -12
View File
@@ -13,11 +13,29 @@ 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.
@@ -30,24 +48,29 @@ 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) Client {
return Client{
ServerAddress: defaultAPIHost,
func NewClient(authToken string, opts *ClientOpts) Client {
c := Client{
serverAddress: defaultServerAddress,
extraHeaders: make(map[string]string),
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) {
@@ -69,9 +92,14 @@ 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 {
@@ -107,5 +135,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, "me", map[string]interface{}{})
return c.Call(userObjectPath, userMeMethod, map[string]interface{}{})
}
+49 -41
View File
@@ -1,8 +1,8 @@
package lbryinc
import (
"log"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
@@ -10,56 +10,64 @@ import (
)
func TestUserMeWrongToken(t *testing.T) {
c := NewClient("abc")
c := NewClient("abc", nil)
r, err := c.UserMe()
require.NotNil(t, err)
assert.Equal(t, "could not authenticate user", err.Error())
assert.Nil(t, r)
}
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 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)
}))
}
func TestUserMe(t *testing.T) {
go launchDummyServer()
c := NewClient("realToken")
c.ServerAddress = dummyServerURL
var req *http.Request
ts := launchDummyServer(&req)
defer ts.Close()
c := NewClient("realToken", &ClientOpts{ServerAddress: ts.URL})
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"])
}
+4 -20
View File
@@ -1,51 +1,35 @@
module github.com/lbryio/lbry.go
module github.com/lbryio/lbry.go/v2
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/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/lbry.go v1.1.2
github.com/lbryio/lbryschema.go v0.0.0-20190602173230-6d2f69a36f46
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
+2 -2
View File
@@ -66,9 +66,9 @@ 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/lbryschema.go v0.0.0-20190428231007-c54836bca002 h1:urfYK5ElpUrAv90auPLldoVC60LwiGAcY0OE6HJB9KI=
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/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=
+5 -1
View File
@@ -11,7 +11,11 @@ import (
"github.com/lbryio/lbry.go/extras/errors"
)
const MaxBlobSize = 2097152 // 2mb, or 2 * 2^20
const (
MaxBlobSize = 2097152 // 2mb, or 2 * 2^20
BlobHashSize = sha512.Size384
BlobHashHexLength = BlobHashSize * 2 // in hex, each byte is 2 chars
)
type Blob []byte