Compare commits

...
11 Commits
Author SHA1 Message Date
Niko Storni 2d45f059ec improve error handling on json marshalling 2019-09-10 16:07:44 +02:00
sayplastic e5850035dd Merge pull request #70 from lbryio/feature/stream_create_account_id
Add account ID to StreamCreateOptions
2019-09-03 01:08:10 +07:00
Andrey Beletsky 0cfc8e230c Add account ID to StreamCreateOptions 2019-09-03 00:47:52 +07:00
Niko Storni f3a1fbdd53 use the right library 2019-08-28 15:12:28 +02:00
Mark ecbd404da0 Merge pull request #69 from lbryio/supports
Add ClaimSupport ( tippable too)
2019-08-27 23:12:44 -04:00
Mark Beamer Jr 2768cdd312 Add ClaimSupport ( tippable too) 2019-08-27 21:31:39 -04:00
Mark 564595cfc3 Merge pull request #66 from lbryio/claims
Add claim management for lbrycrd client
2019-08-27 21:05:07 -04:00
Niko Storni 3a3377d0e5 add support related commands
improve tests
2019-08-27 00:25:47 +02:00
Niko Storni 38861421f8 Merge branch '0.39.0_changes' 2019-08-26 23:15:58 +02:00
Mark Beamer Jr a7bb3cf336 Update AccountBalanceResponse 2019-08-26 23:15:47 +02:00
Mark Beamer Jr 4d17553a23 Add claim management for lbrycrd client 2019-08-14 00:44:27 -04:00
12 changed files with 642 additions and 68 deletions

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@ package bits
import (
"math/big"
"github.com/lbryio/errors.go"
"github.com/lbryio/lbry.go/extras/errors"
)
// Range has a start and end
+24 -9
View File
@@ -113,21 +113,17 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var trace []string
if TraceEnabled && errors.HasTrace(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)
}
}
trace = getTraceFromError(rsp.Error)
}
// http://choly.ca/post/go-json-marshalling/
jsonResponse, err := json.MarshalIndent(&struct {
type apiResponse 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,
@@ -135,10 +131,29 @@ 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: rsp.Data,
Trace: getTraceFromError(err),
}, "", " ")
if err != nil {
Log(r, &rsp, errors.Prefix("Error encoding JSON response: ", err))
}
}
w.WriteHeader(rsp.Status)
w.Write(jsonResponse)
_, _ = 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
}
// IgnoredFormFields are ignored by FormValues() when checking for extraneous fields
+57
View File
@@ -323,6 +323,7 @@ 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) {
@@ -495,3 +496,59 @@ func (d *Client) ChannelExport(channelClaimID string, channelName, accountID *st
"account_id": accountID,
})
}
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))
}
+92 -32
View File
@@ -11,6 +11,8 @@ import (
"github.com/shopspring/decimal"
"github.com/lbryio/lbry.go/extras/errors"
"github.com/lbryio/lbry.go/extras/util"
)
@@ -32,7 +34,7 @@ func TestClient_AccountFund(t *testing.T) {
t.Error(err)
return
}
balance, err := strconv.ParseFloat(string(*balanceString), 64)
balance, err := strconv.ParseFloat(balanceString.Available.String(), 64)
if err != nil {
t.Error(err)
return
@@ -100,6 +102,35 @@ 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("")
@@ -142,7 +173,7 @@ func TestClient_StreamCreate(t *testing.T) {
Preview: nil,
AllowDuplicateName: nil,
ChannelName: nil,
ChannelID: util.PtrToString("dd0b559b4f17a7af984f173efb5438534eb6ab27"),
ChannelID: util.PtrToString(channelID),
ChannelAccountID: nil,
})
if err != nil {
@@ -152,35 +183,9 @@ 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("2a8b6d061c5ecb2515f1dd7e04729e9fafac660d", ChannelUpdateOptions{
got, err := d.ChannelUpdate(channelID, ChannelUpdateOptions{
ClearLanguages: util.PtrToBool(true),
ClearLocations: util.PtrToBool(true),
ClearTags: util.PtrToBool(true),
@@ -264,9 +269,65 @@ func TestClient_ClaimList(t *testing.T) {
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("2a8b6d061c5ecb2515f1dd7e04729e9fafac660d"), nil, nil)
got, err := d.ClaimSearch(nil, util.PtrToString(channelID), nil, nil)
if err != nil {
t.Error(err)
return
@@ -405,8 +466,7 @@ func TestClient_AccountRemove(t *testing.T) {
func TestClient_ChannelExport(t *testing.T) {
d := NewClient("")
channelClaimID := "f1ad0d72eae6b471cfd72b7956768c0c191b22d7"
response, err := d.ChannelExport(channelClaimID, nil, nil)
response, err := d.ChannelExport(channelID, nil, nil)
if err != nil {
t.Error(err)
}
+12 -1
View File
@@ -220,7 +220,12 @@ type AccountListResponse struct {
LBCRegtest []Account `json:"lbc_regtest"`
}
type AccountBalanceResponse string
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 AccountCreateResponse struct {
ID string `json:"id"`
@@ -397,6 +402,12 @@ 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"`
+1 -1
View File
@@ -18,7 +18,7 @@ require (
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/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
+2
View File
@@ -70,6 +70,8 @@ github.com/lbryio/errors.go v0.0.0-20180223142025-ad03d3cc6a5c h1:BhdcWGsuKif/Xo
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/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=
+39
View File
@@ -0,0 +1,39 @@
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
}
+86
View File
@@ -0,0 +1,86 @@
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
}
+214 -24
View File
@@ -1,15 +1,20 @@
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"
)
@@ -33,6 +38,39 @@ 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)
@@ -115,30 +153,6 @@ 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")
@@ -180,3 +194,179 @@ 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)
}
+38
View File
@@ -0,0 +1,38 @@
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
}
+76
View File
@@ -0,0 +1,76 @@
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()
}