This repository has been archived by the owner on Apr 2, 2024. It is now read-only.
generated from mrz1836/go-template
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
bux_test.go
279 lines (237 loc) · 7.69 KB
/
bux_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package bux
import (
"context"
"database/sql"
"testing"
"github.com/BuxOrg/bux/chainstate"
"github.com/BuxOrg/bux/taskmanager"
"github.com/BuxOrg/bux/tester"
"github.com/DATA-DOG/go-sqlmock"
"github.com/bitcoinschema/go-bitcoin/v2"
"github.com/libsv/go-bk/bec"
"github.com/libsv/go-bk/bip32"
"github.com/libsv/go-bt/v2"
"github.com/libsv/go-bt/v2/bscript"
"github.com/libsv/go-bt/v2/sighash"
"github.com/libsv/go-bt/v2/unlocker"
"github.com/mrz1836/go-cache"
"github.com/mrz1836/go-datastore"
"github.com/rafaeljusto/redigomock"
"github.com/rs/zerolog"
"github.com/stretchr/testify/require"
)
// TestingClient is for testing the entire package using real/mocked services
type TestingClient struct {
client ClientInterface // Local bux client for testing
ctx context.Context // Current CTX
database datastore.Engine // Current database
mocking bool // If mocking is enabled
MockSQLDB sqlmock.Sqlmock // Mock Database client for SQL
redisClient *cache.Client // Current redis client (used for Mocking)
redisConn *redigomock.Conn // Current redis connection (used for Mocking)
SQLConn *sql.DB // Read test client
tablePrefix string // Current table prefix
}
// Close will close all test services and client
func (tc *TestingClient) Close(ctx context.Context) {
if tc.client != nil {
/*if !tc.mocking {
if err := dropAllTables(tc.client.Datastore(), tc.database); err != nil {
panic(err)
}
}*/
_ = tc.client.Close(ctx)
}
if tc.SQLConn != nil {
_ = tc.SQLConn.Close()
}
if tc.redisClient != nil {
tc.redisClient.Close()
}
if tc.redisConn != nil {
_ = tc.redisConn.Close()
}
}
// DefaultClientOpts will return a default set of client options required to load the new client
func DefaultClientOpts(debug, shared bool) []ClientOps {
tqc := taskmanager.DefaultTaskQConfig(tester.RandomTablePrefix())
tqc.MaxNumWorker = 2
tqc.MaxNumFetcher = 2
opts := make([]ClientOps, 0)
opts = append(
opts,
WithTaskqConfig(tqc),
WithSQLite(tester.SQLiteTestConfig(debug, shared)),
WithChainstateOptions(false, false, false, false),
WithMinercraft(&chainstate.MinerCraftBase{}),
)
if debug {
opts = append(opts, WithDebugging())
}
return opts
}
// CreateTestSQLiteClient will create a test client for SQLite
//
// NOTE: you need to close the client using the returned defer func
func CreateTestSQLiteClient(t *testing.T, debug, shared bool, clientOpts ...ClientOps) (context.Context, ClientInterface, func()) {
ctx := tester.GetNewRelicCtx(t, "app-test", "test-transaction")
logger := zerolog.Nop()
// Set the default options, add migrate models
opts := DefaultClientOpts(debug, shared)
opts = append(opts, WithAutoMigrate(BaseModels...))
opts = append(opts, WithLogger(&logger))
opts = append(opts, clientOpts...)
// Create the client
client, err := NewClient(ctx, opts...)
require.NoError(t, err)
require.NotNil(t, client)
// Create a defer function
f := func() {
_ = client.Close(context.Background())
}
return ctx, client, f
}
// CreateBenchmarkSQLiteClient will create a test client for SQLite
//
// NOTE: you need to close the client using the returned defer func
func CreateBenchmarkSQLiteClient(b *testing.B, debug, shared bool, clientOpts ...ClientOps) (context.Context, ClientInterface, func()) {
ctx := context.Background()
logger := zerolog.Nop()
// Set the default options, add migrate models
opts := DefaultClientOpts(debug, shared)
opts = append(opts, WithAutoMigrate(BaseModels...))
opts = append(opts, WithLogger(&logger))
opts = append(opts, clientOpts...)
// Create the client
client, err := NewClient(ctx, opts...)
if err != nil {
b.Fail()
}
// Create a defer function
f := func() {
_ = client.Close(context.Background())
}
return ctx, client, f
}
// CloseClient is function used in the "defer()" function
func CloseClient(ctx context.Context, t *testing.T, client ClientInterface) {
require.NoError(t, client.Close(ctx))
}
// we need to create an interface for the unlocker
type account struct {
PrivateKey *bec.PrivateKey
}
// Unlocker get the correct un-locker for a given locking script.
func (a *account) Unlocker(context.Context, *bscript.Script) (bt.Unlocker, error) {
return &unlocker.Simple{
PrivateKey: a.PrivateKey,
}, nil
}
// CreateFakeFundingTransaction will create a valid (fake) transaction for funding
func CreateFakeFundingTransaction(t *testing.T, masterKey *bip32.ExtendedKey,
destinations []*Destination, satoshis uint64,
) string {
// Create new tx
rawTx := bt.NewTx()
txErr := rawTx.From(testTxScriptSigID, 0, testTxScriptSigOut, satoshis+354)
require.NoError(t, txErr)
// Loop all destinations
for _, destination := range destinations {
s, err := bscript.NewFromHexString(destination.LockingScript)
require.NoError(t, err)
require.NotNil(t, s)
rawTx.AddOutput(&bt.Output{
Satoshis: satoshis,
LockingScript: s,
})
}
// Get private key
privateKey, err := bitcoin.GetPrivateKeyFromHDKey(masterKey)
require.NoError(t, err)
require.NotNil(t, privateKey)
// Sign the tx
myAccount := &account{PrivateKey: privateKey}
err = rawTx.FillAllInputs(context.Background(), myAccount)
require.NoError(t, err)
// Return the tx hex
return rawTx.String()
}
// CreateNewXPub will create a new xPub and return all the information to use the xPub
func CreateNewXPub(ctx context.Context, t *testing.T, buxClient ClientInterface,
opts ...ModelOps,
) (*bip32.ExtendedKey, *Xpub, string) {
// Generate a key pair
masterKey, err := bitcoin.GenerateHDKey(bitcoin.SecureSeedLength)
require.NoError(t, err)
require.NotNil(t, masterKey)
// Get the raw string of the xPub
var rawXPub string
rawXPub, err = bitcoin.GetExtendedPublicKey(masterKey)
require.NoError(t, err)
require.NotNil(t, masterKey)
// Create the new xPub
var xPub *Xpub
xPub, err = buxClient.NewXpub(ctx, rawXPub, opts...)
require.NoError(t, err)
require.NotNil(t, xPub)
return masterKey, xPub, rawXPub
}
// GetUnlockingScript will get a locking script for valid fake transactions
func GetUnlockingScript(t *testing.T, tx *bt.Tx, inputIndex uint32, privateKey *bec.PrivateKey) *bscript.Script {
sh, err := tx.CalcInputSignatureHash(inputIndex, sighash.AllForkID)
require.NoError(t, err)
var sig *bec.Signature
sig, err = privateKey.Sign(bt.ReverseBytes(sh))
require.NoError(t, err)
require.NotNil(t, sig)
var s *bscript.Script
s, err = bscript.NewP2PKHUnlockingScript(
privateKey.PubKey().SerialiseCompressed(), sig.Serialise(), sighash.AllForkID,
)
require.NoError(t, err)
require.NotNil(t, s)
return s
}
/*
// dbSchemaResult is the results
type dbSchemaResult struct {
TableName string `json:"table_name"`
}
// dropAllTables will drop all tables in the current database
func dropAllTables(ds datastore.ClientInterface, database datastore.Engine) error {
// Clearing DB is not implemented at this time
// todo: finish this clearing of db?
if database == datastore.MongoDB {
return nil
}
// Set the select string
var selectQuery string
if database == datastore.MySQL || database == datastore.PostgreSQL {
selectQuery = "SELECT table_name FROM information_schema.tables WHERE table_schema = '" + ds.GetDatabaseName() + "';"
} else {
selectQuery = "SELECT name FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%';"
}
// Get all tables
rows, err := ds.Raw(selectQuery).Rows()
if err != nil {
return err
}
defer func() {
_ = rows.Close()
}()
// Parse the records and build a list of table names
var result dbSchemaResult
for rows.Next() {
if err = rows.Scan(&result.TableName); err != nil {
return err
}
if len(result.TableName) > 0 {
db := ds.Execute("DROP TABLE IF EXISTS " + result.TableName + ";")
if db.Error != nil {
return db.Error
}
}
}
return nil
}
*/