Skip to content
This repository has been archived by the owner on Apr 2, 2024. It is now read-only.

Commit

Permalink
refactor(BUX-451): examples using broadcastclient-bux, removed unused…
Browse files Browse the repository at this point in the history
… exposed parts
  • Loading branch information
chris-4chain committed Jan 15, 2024
1 parent 9081074 commit 2987346
Show file tree
Hide file tree
Showing 19 changed files with 127 additions and 226 deletions.
16 changes: 2 additions & 14 deletions authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ import (
//
// Sets req.Context(xpub) and req.Context(xpub_hash)
func (c *Client) AuthenticateRequest(ctx context.Context, req *http.Request, adminXPubs []string,
adminRequired, requireSigning, signingDisabled bool) (*http.Request, error) {

adminRequired, requireSigning, signingDisabled bool,
) (*http.Request, error) {
// Get the xPub/Access Key from the header
xPub := strings.TrimSpace(req.Header.Get(AuthHeader))
authAccessKey := strings.TrimSpace(req.Header.Get(AuthAccessKey))
Expand Down Expand Up @@ -105,7 +105,6 @@ func (c *Client) AuthenticateRequest(ctx context.Context, req *http.Request, adm

// checkSignature check the signature for the provided auth payload
func (c *Client) checkSignature(ctx context.Context, xPubOrAccessKey string, auth *AuthPayload) error {

// Check that we have the basic signature components
if err := checkSignatureRequirements(auth); err != nil {
return err
Expand All @@ -120,7 +119,6 @@ func (c *Client) checkSignature(ctx context.Context, xPubOrAccessKey string, aut

// checkSignatureRequirements will check the payload for basic signature requirements
func checkSignatureRequirements(auth *AuthPayload) error {

// Check that we have a signature
if auth == nil || auth.Signature == "" {
return ErrMissingSignature
Expand All @@ -141,7 +139,6 @@ func checkSignatureRequirements(auth *AuthPayload) error {

// verifyKeyXPub will verify the xPub key and the signature payload
func verifyKeyXPub(xPub string, auth *AuthPayload) error {

// Validate that the xPub is an HD key (length, validation)
if _, err := utils.ValidateXPub(xPub); err != nil {
return err
Expand Down Expand Up @@ -182,7 +179,6 @@ func verifyKeyXPub(xPub string, auth *AuthPayload) error {

// verifyAccessKey will verify the access key and the signature payload
func verifyAccessKey(ctx context.Context, key string, auth *AuthPayload, opts ...ModelOps) error {

// Get access key from DB
// todo: add caching in the future, faster than DB
accessKey, err := getAccessKey(ctx, utils.Hash(key), opts...)
Expand Down Expand Up @@ -214,7 +210,6 @@ func verifyAccessKey(ctx context.Context, key string, auth *AuthPayload, opts ..

// SetSignature will set the signature on the header for the request
func SetSignature(header *http.Header, xPriv *bip32.ExtendedKey, bodyString string) error {

// Create the signature
authData, err := createSignature(xPriv, bodyString)
if err != nil {
Expand All @@ -229,7 +224,6 @@ func SetSignature(header *http.Header, xPriv *bip32.ExtendedKey, bodyString stri

// SetSignatureFromAccessKey will set the signature on the header for the request from an access key
func SetSignatureFromAccessKey(header *http.Header, privateKeyHex, bodyString string) error {

// Create the signature
authData, err := createSignatureAccessKey(privateKeyHex, bodyString)
if err != nil {
Expand All @@ -243,7 +237,6 @@ func SetSignatureFromAccessKey(header *http.Header, privateKeyHex, bodyString st
}

func setSignatureHeaders(header *http.Header, authData *AuthPayload) error {

// Create the auth header hash
header.Set(AuthHeaderHash, authData.AuthHash)

Expand Down Expand Up @@ -287,8 +280,3 @@ func GetXpubIDFromRequest(req *http.Request) (string, bool) {
func IsAdminRequest(req *http.Request) (bool, bool) {
return getBoolFromRequest(req, ParamAdminRequest)
}

// GetXpubHashFromRequest gets the stored xPub hash from the request if found
func GetXpubHashFromRequest(req *http.Request) (string, bool) {
return getFromRequest(req, ParamXPubHashKey)
}
15 changes: 7 additions & 8 deletions authentication_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func TestClient_AuthenticateRequest(t *testing.T) {
assert.Equal(t, testXpubAuth, x)
assert.Equal(t, true, ok)

x, ok = GetXpubHashFromRequest(req)
x, ok = GetXpubIDFromRequest(req)
assert.Equal(t, testXpubAuthHash, x)
assert.Equal(t, true, ok)
})
Expand Down Expand Up @@ -233,7 +233,7 @@ func TestClient_AuthenticateRequest(t *testing.T) {
assert.Equal(t, "", x)
assert.Equal(t, false, ok)

x, ok = GetXpubHashFromRequest(req)
x, ok = GetXpubIDFromRequest(req)
assert.Equal(t, "", x)
assert.Equal(t, false, ok)
})
Expand All @@ -259,7 +259,7 @@ func TestClient_AuthenticateRequest(t *testing.T) {
assert.Equal(t, "", x)
assert.Equal(t, false, ok)

x, ok = GetXpubHashFromRequest(req)
x, ok = GetXpubIDFromRequest(req)
assert.Equal(t, "", x)
assert.Equal(t, false, ok)
})
Expand Down Expand Up @@ -367,7 +367,6 @@ func Test_verifyKeyXPub(t *testing.T) {
t.Parallel()

t.Run("error - missing auth data", func(t *testing.T) {

err := verifyKeyXPub(testXpubAuth, nil)
require.Error(t, err)
assert.ErrorIs(t, err, ErrMissingSignature)
Expand Down Expand Up @@ -659,8 +658,8 @@ func TestIsAdminRequest(t *testing.T) {
})
}

// TestGetXpubHashFromRequest will test the method GetXpubHashFromRequest()
func TestGetXpubHashFromRequest(t *testing.T) {
// TestGetXpubHashFromRequest will test the method GetXpubIDFromRequest()
func TestGetXpubIDFromRequest(t *testing.T) {
t.Parallel()

t.Run("valid value", func(t *testing.T) {
Expand All @@ -670,7 +669,7 @@ func TestGetXpubHashFromRequest(t *testing.T) {

req = setOnRequest(req, ParamXPubHashKey, testXpubAuthHash)

xPubHash, success := GetXpubHashFromRequest(req)
xPubHash, success := GetXpubIDFromRequest(req)
assert.Equal(t, testXpubAuthHash, xPubHash)
assert.Equal(t, true, success)
})
Expand All @@ -680,7 +679,7 @@ func TestGetXpubHashFromRequest(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, req)

xPubHash, success := GetXpubHashFromRequest(req)
xPubHash, success := GetXpubIDFromRequest(req)
assert.Equal(t, "", xPubHash)
assert.Equal(t, false, success)
})
Expand Down
4 changes: 2 additions & 2 deletions client_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -552,8 +552,8 @@ func WithTaskqConfig(config *taskq.QueueOptions) ClientOps {
}
}

// WithCronCustmPeriod will set the custom cron jobs period which will override the default
func WithCronCustmPeriod(cronJobName string, period time.Duration) ClientOps {
// WithCronCustomPeriod will set the custom cron jobs period which will override the default
func WithCronCustomPeriod(cronJobName string, period time.Duration) ClientOps {
return func(c *clientOptions) {
if c.taskManager != nil {
c.taskManager.cronCustomPeriods[cronJobName] = period
Expand Down
2 changes: 1 addition & 1 deletion cron_job_declarations.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/BuxOrg/bux/taskmanager"
)

// Cron job names; defined as public constants to be used in WithCronCustmPeriod
// Cron job names to be used in WithCronCustomPeriod
const (
CronJobNameDraftTransactionCleanUp = "draft_transaction_clean_up"
CronJobNameIncomingTransaction = "incoming_transaction_process"
Expand Down
3 changes: 0 additions & 3 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,6 @@ var ErrUtxoAlreadySpent = errors.New("utxo has already been spent")
// ErrDraftNotFound is when the requested draft transaction was not found
var ErrDraftNotFound = errors.New("corresponding draft transaction not found")

// ErrTaskManagerNotLoaded is when the taskmanager was not loaded
var ErrTaskManagerNotLoaded = errors.New("taskmanager must be loaded")

// ErrTransactionNotParsed is when the transaction is not parsed but was expected
var ErrTransactionNotParsed = errors.New("transaction is not parsed")

Expand Down
43 changes: 20 additions & 23 deletions examples/client/broadcast_miners/broadcast_miners.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,39 +6,36 @@ import (
"os"

"github.com/BuxOrg/bux"
"github.com/tonicpow/go-minercraft/v2"
"github.com/BuxOrg/bux/logging"
"github.com/bitcoin-sv/go-broadcast-client/broadcast"
broadcastclient "github.com/bitcoin-sv/go-broadcast-client/broadcast/broadcast-client"
)

func main() {
// Create a custom miner (using your api key for custom rates)
miners, _ := minercraft.DefaultMiners()
minerTaal := minercraft.MinerByName(miners, minercraft.MinerTaal)
minerCraftApis := []*minercraft.MinerAPIs{
{
MinerID: minerTaal.MinerID,
APIs: []minercraft.API{
{
Token: os.Getenv("BUX_TAAL_API_KEY"),
URL: "https://tapi.taal.com/arc",
Type: minercraft.Arc,
},
},
func buildBroadcastClient() broadcast.Client {
logger := logging.GetDefaultLogger()
builder := broadcastclient.Builder().WithArc(
broadcastclient.ArcClientConfig{
APIUrl: "https://tapi.taal.com/arc",
Token: os.Getenv("BUX_TAAL_API_KEY"),
},
}
logger,
)

return builder.Build()
}

func main() {
ctx := context.Background()

// Create the client
client, err := bux.NewClient(
context.Background(), // Set context
bux.WithMinercraftAPIs(minerCraftApis),
bux.WithArc(),
ctx,
bux.WithBroadcastClient(buildBroadcastClient()),
)
if err != nil {
log.Fatalln("error: " + err.Error())
}

defer func() {
_ = client.Close(context.Background())
}()
defer client.Close(ctx)

log.Println("client loaded!", client.UserAgent())
}
4 changes: 2 additions & 2 deletions examples/client/custom_cron/custom_cron.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (
func main() {
client, err := bux.NewClient(
context.Background(), // Set context
bux.WithCronCustmPeriod(bux.CronJobNameDraftTransactionCleanUp, 2*time.Second),
bux.WithCronCustmPeriod(bux.CronJobNameIncomingTransaction, 4*time.Second),
bux.WithCronCustomPeriod(bux.CronJobNameDraftTransactionCleanUp, 2*time.Second),
bux.WithCronCustomPeriod(bux.CronJobNameIncomingTransaction, 4*time.Second),
)
if err != nil {
log.Fatalln("error: " + err.Error())
Expand Down
60 changes: 25 additions & 35 deletions examples/client/custom_rates/custom_rates.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,57 +7,47 @@ import (
"time"

"github.com/BuxOrg/bux"
"github.com/tonicpow/go-minercraft/v2"
"github.com/BuxOrg/bux/logging"
"github.com/bitcoin-sv/go-broadcast-client/broadcast"
broadcastclient "github.com/bitcoin-sv/go-broadcast-client/broadcast/broadcast-client"
)

func buildBroadcastClient() broadcast.Client {
logger := logging.GetDefaultLogger()
builder := broadcastclient.Builder().WithArc(
broadcastclient.ArcClientConfig{
APIUrl: "https://tapi.taal.com/arc",
Token: os.Getenv("BUX_TAAL_API_KEY"),
},
logger,
)

return builder.Build()
}

func main() {
ctx := context.Background()
const testXPub = "xpub661MyMwAqRbcFrBJbKwBGCB7d3fr2SaAuXGM95BA62X41m6eW2ehRQGW4xLi9wkEXUGnQZYxVVj4PxXnyrLk7jdqvBAs1Qq9gf6ykMvjR7J"

// Create a custom miner (using your api key for custom rates)
miners, _ := minercraft.DefaultMiners()
minerTaal := minercraft.MinerByName(miners, minercraft.MinerTaal)
minerCraftApis := []*minercraft.MinerAPIs{
{
MinerID: minerTaal.MinerID,
APIs: []minercraft.API{
{
Token: os.Getenv("BUX_TAAL_API_KEY"),
URL: "https://tapi.taal.com/arc",
Type: minercraft.Arc,
},
},
},
}

// Create the client
client, err := bux.NewClient(
context.Background(), // Set context
bux.WithAutoMigrate(bux.BaseModels...), // All models
bux.WithMinercraftAPIs(minerCraftApis),
bux.WithArc(),
ctx,
bux.WithAutoMigrate(bux.BaseModels...),
bux.WithBroadcastClient(buildBroadcastClient()),
)
if err != nil {
log.Fatalln("error: " + err.Error())
}

defer func() {
_ = client.Close(context.Background())
}()
defer client.Close(ctx)

// Create an xPub
var xpub *bux.Xpub
if xpub, err = client.NewXpub(
context.Background(),
testXPub,
); err != nil {
xpub, err := client.NewXpub(ctx, testXPub)
if err != nil {
log.Fatalln("error: " + err.Error())
}

// Create a draft transaction
var draft *bux.DraftTransaction
draft, err = client.NewTransaction(context.Background(), xpub.RawXpub(), &bux.TransactionConfig{
draft, err := client.NewTransaction(ctx, xpub.RawXpub(), &bux.TransactionConfig{
ExpiresIn: 10 * time.Second,
SendAllTo: &bux.TransactionOutput{To: "mrz@moneybutton.com"},
SendAllTo: &bux.TransactionOutput{To: os.Getenv("BUX_MY_PAYMAIL")},
})
if err != nil {
log.Fatalln("error: " + err.Error())
Expand Down
20 changes: 4 additions & 16 deletions model_bump.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,14 +288,8 @@ func (bump *BUMP) Scan(value interface{}) error {
return nil
}

xType := fmt.Sprintf("%T", value)
var byteValue []byte
if xType == ValueTypeString {
byteValue = []byte(value.(string))
} else {
byteValue = value.([]byte)
}
if bytes.Equal(byteValue, []byte("")) || bytes.Equal(byteValue, []byte("\"\"")) {
byteValue, err := utils.ToByteArray(value)
if err != nil || bytes.Equal(byteValue, []byte("")) || bytes.Equal(byteValue, []byte("\"\"")) {
return nil
}

Expand All @@ -321,14 +315,8 @@ func (bumps *BUMPs) Scan(value interface{}) error {
return nil
}

xType := fmt.Sprintf("%T", value)
var byteValue []byte
if xType == ValueTypeString {
byteValue = []byte(value.(string))
} else {
byteValue = value.([]byte)
}
if bytes.Equal(byteValue, []byte("")) || bytes.Equal(byteValue, []byte("\"\"")) {
byteValue, err := utils.ToByteArray(value)
if err != nil || bytes.Equal(byteValue, []byte("")) || bytes.Equal(byteValue, []byte("\"\"")) {
return nil
}

Expand Down
Loading

0 comments on commit 2987346

Please sign in to comment.