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

Commit 2987346

Browse files
committed
refactor(BUX-451): examples using broadcastclient-bux, removed unused exposed parts
1 parent 9081074 commit 2987346

19 files changed

+127
-226
lines changed

authentication.go

+2-14
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ import (
2121
//
2222
// Sets req.Context(xpub) and req.Context(xpub_hash)
2323
func (c *Client) AuthenticateRequest(ctx context.Context, req *http.Request, adminXPubs []string,
24-
adminRequired, requireSigning, signingDisabled bool) (*http.Request, error) {
25-
24+
adminRequired, requireSigning, signingDisabled bool,
25+
) (*http.Request, error) {
2626
// Get the xPub/Access Key from the header
2727
xPub := strings.TrimSpace(req.Header.Get(AuthHeader))
2828
authAccessKey := strings.TrimSpace(req.Header.Get(AuthAccessKey))
@@ -105,7 +105,6 @@ func (c *Client) AuthenticateRequest(ctx context.Context, req *http.Request, adm
105105

106106
// checkSignature check the signature for the provided auth payload
107107
func (c *Client) checkSignature(ctx context.Context, xPubOrAccessKey string, auth *AuthPayload) error {
108-
109108
// Check that we have the basic signature components
110109
if err := checkSignatureRequirements(auth); err != nil {
111110
return err
@@ -120,7 +119,6 @@ func (c *Client) checkSignature(ctx context.Context, xPubOrAccessKey string, aut
120119

121120
// checkSignatureRequirements will check the payload for basic signature requirements
122121
func checkSignatureRequirements(auth *AuthPayload) error {
123-
124122
// Check that we have a signature
125123
if auth == nil || auth.Signature == "" {
126124
return ErrMissingSignature
@@ -141,7 +139,6 @@ func checkSignatureRequirements(auth *AuthPayload) error {
141139

142140
// verifyKeyXPub will verify the xPub key and the signature payload
143141
func verifyKeyXPub(xPub string, auth *AuthPayload) error {
144-
145142
// Validate that the xPub is an HD key (length, validation)
146143
if _, err := utils.ValidateXPub(xPub); err != nil {
147144
return err
@@ -182,7 +179,6 @@ func verifyKeyXPub(xPub string, auth *AuthPayload) error {
182179

183180
// verifyAccessKey will verify the access key and the signature payload
184181
func verifyAccessKey(ctx context.Context, key string, auth *AuthPayload, opts ...ModelOps) error {
185-
186182
// Get access key from DB
187183
// todo: add caching in the future, faster than DB
188184
accessKey, err := getAccessKey(ctx, utils.Hash(key), opts...)
@@ -214,7 +210,6 @@ func verifyAccessKey(ctx context.Context, key string, auth *AuthPayload, opts ..
214210

215211
// SetSignature will set the signature on the header for the request
216212
func SetSignature(header *http.Header, xPriv *bip32.ExtendedKey, bodyString string) error {
217-
218213
// Create the signature
219214
authData, err := createSignature(xPriv, bodyString)
220215
if err != nil {
@@ -229,7 +224,6 @@ func SetSignature(header *http.Header, xPriv *bip32.ExtendedKey, bodyString stri
229224

230225
// SetSignatureFromAccessKey will set the signature on the header for the request from an access key
231226
func SetSignatureFromAccessKey(header *http.Header, privateKeyHex, bodyString string) error {
232-
233227
// Create the signature
234228
authData, err := createSignatureAccessKey(privateKeyHex, bodyString)
235229
if err != nil {
@@ -243,7 +237,6 @@ func SetSignatureFromAccessKey(header *http.Header, privateKeyHex, bodyString st
243237
}
244238

245239
func setSignatureHeaders(header *http.Header, authData *AuthPayload) error {
246-
247240
// Create the auth header hash
248241
header.Set(AuthHeaderHash, authData.AuthHash)
249242

@@ -287,8 +280,3 @@ func GetXpubIDFromRequest(req *http.Request) (string, bool) {
287280
func IsAdminRequest(req *http.Request) (bool, bool) {
288281
return getBoolFromRequest(req, ParamAdminRequest)
289282
}
290-
291-
// GetXpubHashFromRequest gets the stored xPub hash from the request if found
292-
func GetXpubHashFromRequest(req *http.Request) (string, bool) {
293-
return getFromRequest(req, ParamXPubHashKey)
294-
}

authentication_test.go

+7-8
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ func TestClient_AuthenticateRequest(t *testing.T) {
5757
assert.Equal(t, testXpubAuth, x)
5858
assert.Equal(t, true, ok)
5959

60-
x, ok = GetXpubHashFromRequest(req)
60+
x, ok = GetXpubIDFromRequest(req)
6161
assert.Equal(t, testXpubAuthHash, x)
6262
assert.Equal(t, true, ok)
6363
})
@@ -233,7 +233,7 @@ func TestClient_AuthenticateRequest(t *testing.T) {
233233
assert.Equal(t, "", x)
234234
assert.Equal(t, false, ok)
235235

236-
x, ok = GetXpubHashFromRequest(req)
236+
x, ok = GetXpubIDFromRequest(req)
237237
assert.Equal(t, "", x)
238238
assert.Equal(t, false, ok)
239239
})
@@ -259,7 +259,7 @@ func TestClient_AuthenticateRequest(t *testing.T) {
259259
assert.Equal(t, "", x)
260260
assert.Equal(t, false, ok)
261261

262-
x, ok = GetXpubHashFromRequest(req)
262+
x, ok = GetXpubIDFromRequest(req)
263263
assert.Equal(t, "", x)
264264
assert.Equal(t, false, ok)
265265
})
@@ -367,7 +367,6 @@ func Test_verifyKeyXPub(t *testing.T) {
367367
t.Parallel()
368368

369369
t.Run("error - missing auth data", func(t *testing.T) {
370-
371370
err := verifyKeyXPub(testXpubAuth, nil)
372371
require.Error(t, err)
373372
assert.ErrorIs(t, err, ErrMissingSignature)
@@ -659,8 +658,8 @@ func TestIsAdminRequest(t *testing.T) {
659658
})
660659
}
661660

662-
// TestGetXpubHashFromRequest will test the method GetXpubHashFromRequest()
663-
func TestGetXpubHashFromRequest(t *testing.T) {
661+
// TestGetXpubHashFromRequest will test the method GetXpubIDFromRequest()
662+
func TestGetXpubIDFromRequest(t *testing.T) {
664663
t.Parallel()
665664

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

671670
req = setOnRequest(req, ParamXPubHashKey, testXpubAuthHash)
672671

673-
xPubHash, success := GetXpubHashFromRequest(req)
672+
xPubHash, success := GetXpubIDFromRequest(req)
674673
assert.Equal(t, testXpubAuthHash, xPubHash)
675674
assert.Equal(t, true, success)
676675
})
@@ -680,7 +679,7 @@ func TestGetXpubHashFromRequest(t *testing.T) {
680679
require.NoError(t, err)
681680
require.NotNil(t, req)
682681

683-
xPubHash, success := GetXpubHashFromRequest(req)
682+
xPubHash, success := GetXpubIDFromRequest(req)
684683
assert.Equal(t, "", xPubHash)
685684
assert.Equal(t, false, success)
686685
})

client_options.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -552,8 +552,8 @@ func WithTaskqConfig(config *taskq.QueueOptions) ClientOps {
552552
}
553553
}
554554

555-
// WithCronCustmPeriod will set the custom cron jobs period which will override the default
556-
func WithCronCustmPeriod(cronJobName string, period time.Duration) ClientOps {
555+
// WithCronCustomPeriod will set the custom cron jobs period which will override the default
556+
func WithCronCustomPeriod(cronJobName string, period time.Duration) ClientOps {
557557
return func(c *clientOptions) {
558558
if c.taskManager != nil {
559559
c.taskManager.cronCustomPeriods[cronJobName] = period

cron_job_declarations.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"github.com/BuxOrg/bux/taskmanager"
88
)
99

10-
// Cron job names; defined as public constants to be used in WithCronCustmPeriod
10+
// Cron job names to be used in WithCronCustomPeriod
1111
const (
1212
CronJobNameDraftTransactionCleanUp = "draft_transaction_clean_up"
1313
CronJobNameIncomingTransaction = "incoming_transaction_process"

errors.go

-3
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,6 @@ var ErrUtxoAlreadySpent = errors.New("utxo has already been spent")
112112
// ErrDraftNotFound is when the requested draft transaction was not found
113113
var ErrDraftNotFound = errors.New("corresponding draft transaction not found")
114114

115-
// ErrTaskManagerNotLoaded is when the taskmanager was not loaded
116-
var ErrTaskManagerNotLoaded = errors.New("taskmanager must be loaded")
117-
118115
// ErrTransactionNotParsed is when the transaction is not parsed but was expected
119116
var ErrTransactionNotParsed = errors.New("transaction is not parsed")
120117

examples/client/broadcast_miners/broadcast_miners.go

+20-23
Original file line numberDiff line numberDiff line change
@@ -6,39 +6,36 @@ import (
66
"os"
77

88
"github.com/BuxOrg/bux"
9-
"github.com/tonicpow/go-minercraft/v2"
9+
"github.com/BuxOrg/bux/logging"
10+
"github.com/bitcoin-sv/go-broadcast-client/broadcast"
11+
broadcastclient "github.com/bitcoin-sv/go-broadcast-client/broadcast/broadcast-client"
1012
)
1113

12-
func main() {
13-
// Create a custom miner (using your api key for custom rates)
14-
miners, _ := minercraft.DefaultMiners()
15-
minerTaal := minercraft.MinerByName(miners, minercraft.MinerTaal)
16-
minerCraftApis := []*minercraft.MinerAPIs{
17-
{
18-
MinerID: minerTaal.MinerID,
19-
APIs: []minercraft.API{
20-
{
21-
Token: os.Getenv("BUX_TAAL_API_KEY"),
22-
URL: "https://tapi.taal.com/arc",
23-
Type: minercraft.Arc,
24-
},
25-
},
14+
func buildBroadcastClient() broadcast.Client {
15+
logger := logging.GetDefaultLogger()
16+
builder := broadcastclient.Builder().WithArc(
17+
broadcastclient.ArcClientConfig{
18+
APIUrl: "https://tapi.taal.com/arc",
19+
Token: os.Getenv("BUX_TAAL_API_KEY"),
2620
},
27-
}
21+
logger,
22+
)
23+
24+
return builder.Build()
25+
}
26+
27+
func main() {
28+
ctx := context.Background()
2829

29-
// Create the client
3030
client, err := bux.NewClient(
31-
context.Background(), // Set context
32-
bux.WithMinercraftAPIs(minerCraftApis),
33-
bux.WithArc(),
31+
ctx,
32+
bux.WithBroadcastClient(buildBroadcastClient()),
3433
)
3534
if err != nil {
3635
log.Fatalln("error: " + err.Error())
3736
}
3837

39-
defer func() {
40-
_ = client.Close(context.Background())
41-
}()
38+
defer client.Close(ctx)
4239

4340
log.Println("client loaded!", client.UserAgent())
4441
}

examples/client/custom_cron/custom_cron.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ import (
1111
func main() {
1212
client, err := bux.NewClient(
1313
context.Background(), // Set context
14-
bux.WithCronCustmPeriod(bux.CronJobNameDraftTransactionCleanUp, 2*time.Second),
15-
bux.WithCronCustmPeriod(bux.CronJobNameIncomingTransaction, 4*time.Second),
14+
bux.WithCronCustomPeriod(bux.CronJobNameDraftTransactionCleanUp, 2*time.Second),
15+
bux.WithCronCustomPeriod(bux.CronJobNameIncomingTransaction, 4*time.Second),
1616
)
1717
if err != nil {
1818
log.Fatalln("error: " + err.Error())

examples/client/custom_rates/custom_rates.go

+25-35
Original file line numberDiff line numberDiff line change
@@ -7,57 +7,47 @@ import (
77
"time"
88

99
"github.com/BuxOrg/bux"
10-
"github.com/tonicpow/go-minercraft/v2"
10+
"github.com/BuxOrg/bux/logging"
11+
"github.com/bitcoin-sv/go-broadcast-client/broadcast"
12+
broadcastclient "github.com/bitcoin-sv/go-broadcast-client/broadcast/broadcast-client"
1113
)
1214

15+
func buildBroadcastClient() broadcast.Client {
16+
logger := logging.GetDefaultLogger()
17+
builder := broadcastclient.Builder().WithArc(
18+
broadcastclient.ArcClientConfig{
19+
APIUrl: "https://tapi.taal.com/arc",
20+
Token: os.Getenv("BUX_TAAL_API_KEY"),
21+
},
22+
logger,
23+
)
24+
25+
return builder.Build()
26+
}
27+
1328
func main() {
29+
ctx := context.Background()
1430
const testXPub = "xpub661MyMwAqRbcFrBJbKwBGCB7d3fr2SaAuXGM95BA62X41m6eW2ehRQGW4xLi9wkEXUGnQZYxVVj4PxXnyrLk7jdqvBAs1Qq9gf6ykMvjR7J"
1531

16-
// Create a custom miner (using your api key for custom rates)
17-
miners, _ := minercraft.DefaultMiners()
18-
minerTaal := minercraft.MinerByName(miners, minercraft.MinerTaal)
19-
minerCraftApis := []*minercraft.MinerAPIs{
20-
{
21-
MinerID: minerTaal.MinerID,
22-
APIs: []minercraft.API{
23-
{
24-
Token: os.Getenv("BUX_TAAL_API_KEY"),
25-
URL: "https://tapi.taal.com/arc",
26-
Type: minercraft.Arc,
27-
},
28-
},
29-
},
30-
}
31-
32-
// Create the client
3332
client, err := bux.NewClient(
34-
context.Background(), // Set context
35-
bux.WithAutoMigrate(bux.BaseModels...), // All models
36-
bux.WithMinercraftAPIs(minerCraftApis),
37-
bux.WithArc(),
33+
ctx,
34+
bux.WithAutoMigrate(bux.BaseModels...),
35+
bux.WithBroadcastClient(buildBroadcastClient()),
3836
)
3937
if err != nil {
4038
log.Fatalln("error: " + err.Error())
4139
}
4240

43-
defer func() {
44-
_ = client.Close(context.Background())
45-
}()
41+
defer client.Close(ctx)
4642

47-
// Create an xPub
48-
var xpub *bux.Xpub
49-
if xpub, err = client.NewXpub(
50-
context.Background(),
51-
testXPub,
52-
); err != nil {
43+
xpub, err := client.NewXpub(ctx, testXPub)
44+
if err != nil {
5345
log.Fatalln("error: " + err.Error())
5446
}
5547

56-
// Create a draft transaction
57-
var draft *bux.DraftTransaction
58-
draft, err = client.NewTransaction(context.Background(), xpub.RawXpub(), &bux.TransactionConfig{
48+
draft, err := client.NewTransaction(ctx, xpub.RawXpub(), &bux.TransactionConfig{
5949
ExpiresIn: 10 * time.Second,
60-
SendAllTo: &bux.TransactionOutput{To: "[email protected]"},
50+
SendAllTo: &bux.TransactionOutput{To: os.Getenv("BUX_MY_PAYMAIL")},
6151
})
6252
if err != nil {
6353
log.Fatalln("error: " + err.Error())

model_bump.go

+4-16
Original file line numberDiff line numberDiff line change
@@ -288,14 +288,8 @@ func (bump *BUMP) Scan(value interface{}) error {
288288
return nil
289289
}
290290

291-
xType := fmt.Sprintf("%T", value)
292-
var byteValue []byte
293-
if xType == ValueTypeString {
294-
byteValue = []byte(value.(string))
295-
} else {
296-
byteValue = value.([]byte)
297-
}
298-
if bytes.Equal(byteValue, []byte("")) || bytes.Equal(byteValue, []byte("\"\"")) {
291+
byteValue, err := utils.ToByteArray(value)
292+
if err != nil || bytes.Equal(byteValue, []byte("")) || bytes.Equal(byteValue, []byte("\"\"")) {
299293
return nil
300294
}
301295

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

324-
xType := fmt.Sprintf("%T", value)
325-
var byteValue []byte
326-
if xType == ValueTypeString {
327-
byteValue = []byte(value.(string))
328-
} else {
329-
byteValue = value.([]byte)
330-
}
331-
if bytes.Equal(byteValue, []byte("")) || bytes.Equal(byteValue, []byte("\"\"")) {
318+
byteValue, err := utils.ToByteArray(value)
319+
if err != nil || bytes.Equal(byteValue, []byte("")) || bytes.Equal(byteValue, []byte("\"\"")) {
332320
return nil
333321
}
334322

0 commit comments

Comments
 (0)