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 6
/
model_destinations.go
439 lines (362 loc) · 13.4 KB
/
model_destinations.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
package bux
import (
"context"
"errors"
"fmt"
"github.com/BuxOrg/bux/cluster"
"github.com/BuxOrg/bux/notifications"
"github.com/BuxOrg/bux/utils"
"github.com/bitcoinschema/go-bitcoin/v2"
"github.com/mrz1836/go-datastore"
customTypes "github.com/mrz1836/go-datastore/custom_types"
)
// Destination is an object representing a BitCoin destination (address, script, etc)
//
// Gorm related models & indexes: https://gorm.io/docs/models.html - https://gorm.io/docs/indexes.html
type Destination struct {
// Base model
Model `bson:",inline"`
// Model specific fields
ID string `json:"id" toml:"id" yaml:"id" gorm:"<-:create;type:char(64);primaryKey;comment:This is the hash of the locking script" bson:"_id"`
XpubID string `json:"xpub_id" toml:"xpub_id" yaml:"xpub_id" gorm:"<-:create;type:char(64);index;comment:This is the related xPub" bson:"xpub_id"`
LockingScript string `json:"locking_script" toml:"locking_script" yaml:"locking_script" gorm:"<-:create;type:text;comment:This is Bitcoin output script in hex" bson:"locking_script"`
Type string `json:"type" toml:"type" yaml:"type" gorm:"<-:create;type:text;comment:Type of output" bson:"type"`
Chain uint32 `json:"chain" toml:"chain" yaml:"chain" gorm:"<-:create;type:int;comment:This is the (chain)/num location of the address related to the xPub" bson:"chain"`
Num uint32 `json:"num" toml:"num" yaml:"num" gorm:"<-:create;type:int;comment:This is the chain/(num) location of the address related to the xPub" bson:"num"`
Address string `json:"address" toml:"address" yaml:"address" gorm:"<-:create;type:varchar(35);index;comment:This is the BitCoin address" bson:"address"`
DraftID string `json:"draft_id" toml:"draft_id" yaml:"draft_id" gorm:"<-:create;type:varchar(64);index;comment:This is the related draft id (if internal tx)" bson:"draft_id,omitempty"`
Monitor customTypes.NullTime `json:"monitor" toml:"monitor" yaml:"monitor" gorm:";index;comment:When this address was last used for an external transaction, for monitoring" bson:"monitor,omitempty"`
}
// newDestination will start a new Destination model for a locking script
func newDestination(xPubID, lockingScript string, opts ...ModelOps) *Destination {
// Determine the type if the locking script is provided
destinationType := utils.ScriptTypeNonStandard
address := ""
if len(lockingScript) > 0 {
destinationType = utils.GetDestinationType(lockingScript)
address = utils.GetAddressFromScript(lockingScript)
}
// Return the model
return &Destination{
ID: utils.Hash(lockingScript),
LockingScript: lockingScript,
Model: *NewBaseModel(ModelDestination, opts...),
Type: destinationType,
XpubID: xPubID,
Address: address,
}
}
// newAddress will start a new Destination model for a legacy Bitcoin address
func newAddress(rawXpubKey string, chain, num uint32, opts ...ModelOps) (*Destination, error) {
// Create the model
destination := &Destination{
Chain: chain,
Model: *NewBaseModel(ModelDestination, opts...),
Num: num,
}
// Set the default address
err := destination.setAddress(rawXpubKey)
if err != nil {
return nil, err
}
// Set the locking script
if destination.LockingScript, err = bitcoin.ScriptFromAddress(
destination.Address,
); err != nil {
return nil, err
}
// Determine the type if the locking script is provided
destination.Type = utils.GetDestinationType(destination.LockingScript)
destination.ID = utils.Hash(destination.LockingScript)
// Return the destination (address)
return destination, nil
}
// getDestinationByID will get the destination by the given id
func getDestinationByID(ctx context.Context, id string, opts ...ModelOps) (*Destination, error) {
// Construct an empty model
destination := &Destination{
ID: id,
Model: *NewBaseModel(ModelDestination, opts...),
}
// Get the record
if err := Get(ctx, destination, nil, true, defaultDatabaseReadTimeout, false); err != nil {
if errors.Is(err, datastore.ErrNoResults) {
return nil, nil
}
return nil, err
}
return destination, nil
}
// getDestinationByAddress will get the destination by the given address
func getDestinationByAddress(ctx context.Context, address string, opts ...ModelOps) (*Destination, error) {
// Construct an empty model
destination := &Destination{
Model: *NewBaseModel(ModelDestination, opts...),
}
conditions := map[string]interface{}{
"address": address,
}
// Get the record
if err := Get(ctx, destination, conditions, true, defaultDatabaseReadTimeout, false); err != nil {
if errors.Is(err, datastore.ErrNoResults) {
return nil, nil
}
return nil, err
}
return destination, nil
}
// getDestinationByLockingScript will get the destination by the given locking script
func getDestinationByLockingScript(ctx context.Context, lockingScript string, opts ...ModelOps) (*Destination, error) {
// Construct an empty model
destination := newDestination("", lockingScript, opts...)
// Get the record
if err := Get(ctx, destination, nil, true, defaultDatabaseReadTimeout, false); err != nil {
if errors.Is(err, datastore.ErrNoResults) {
return nil, nil
}
return nil, err
}
return destination, nil
}
// getDestinations will get all the destinations with the given conditions
func getDestinations(ctx context.Context, metadata *Metadata, conditions *map[string]interface{},
queryParams *datastore.QueryParams, opts ...ModelOps) ([]*Destination, error) {
modelItems := make([]*Destination, 0)
if err := getModelsByConditions(ctx, ModelDestination, &modelItems, metadata, conditions, queryParams, opts...); err != nil {
return nil, err
}
return modelItems, nil
}
// getDestinationsCount will get a count of all the destinations with the given conditions
func getDestinationsCount(ctx context.Context, metadata *Metadata, conditions *map[string]interface{},
opts ...ModelOps) (int64, error) {
return getModelCountByConditions(ctx, ModelDestination, Destination{}, metadata, conditions, opts...)
}
// getDestinationsByXpubID will get the destination(s) by the given xPubID
func getDestinationsByXpubID(ctx context.Context, xPubID string, usingMetadata *Metadata, conditions *map[string]interface{},
queryParams *datastore.QueryParams, opts ...ModelOps) ([]*Destination, error) {
// Construct an empty model
var models []Destination
var dbConditions = map[string]interface{}{}
if conditions != nil {
dbConditions = *conditions
}
dbConditions[xPubIDField] = xPubID
if usingMetadata != nil {
dbConditions[metadataField] = usingMetadata
}
// Get the records
if err := getModels(
ctx, NewBaseModel(ModelNameEmpty, opts...).Client().Datastore(),
&models, dbConditions, queryParams, defaultDatabaseReadTimeout,
); err != nil {
if errors.Is(err, datastore.ErrNoResults) {
return nil, nil
}
return nil, err
}
// Loop and enrich
destinations := make([]*Destination, 0)
for index := range models {
models[index].enrich(ModelDestination, opts...)
destinations = append(destinations, &models[index])
}
return destinations, nil
}
// getDestinationsCountByXPubID will get a count of the destination(s) by the given xPubID
func getDestinationsCountByXPubID(ctx context.Context, xPubID string, usingMetadata *Metadata,
conditions *map[string]interface{}, opts ...ModelOps) (int64, error) {
var dbConditions = map[string]interface{}{}
if conditions != nil {
dbConditions = *conditions
}
dbConditions[xPubIDField] = xPubID
if usingMetadata != nil {
dbConditions[metadataField] = usingMetadata
}
// Get the records
count, err := getModelCount(
ctx,
NewBaseModel(ModelNameEmpty, opts...).Client().Datastore(),
Destination{},
dbConditions,
defaultDatabaseReadTimeout,
)
if err != nil {
if errors.Is(err, datastore.ErrNoResults) {
return 0, nil
}
return 0, err
}
return count, nil
}
// getXpubWithCache will try to get from cache first, then datastore
//
// key is the raw xPub key or use xPubID
func getDestinationWithCache(ctx context.Context, client ClientInterface,
id, address, lockingScript string, opts ...ModelOps) (*Destination, error) {
// Create the cache key
var cacheKey string
if len(id) > 0 {
cacheKey = fmt.Sprintf(cacheKeyDestinationModel, id)
} else if len(address) > 0 {
cacheKey = fmt.Sprintf(cacheKeyDestinationModelByAddress, address)
} else if len(lockingScript) > 0 {
cacheKey = fmt.Sprintf(cacheKeyDestinationModelByLockingScript, lockingScript)
}
if len(cacheKey) == 0 {
return nil, ErrMissingFieldID
}
// Attempt to get from cache
destination := new(Destination)
found, err := getModelFromCache(
ctx, client.Cachestore(), cacheKey, destination,
)
if err != nil { // Found a real error
return nil, err
} else if found { // Return the cached model
destination.enrich(ModelDestination, opts...) // Enrich the model with our parent options
return destination, nil
}
// Get via ID, address or locking script
if len(id) > 0 {
destination, err = getDestinationByID(
ctx, id, opts...,
)
} else if len(address) > 0 {
destination, err = getDestinationByAddress(
ctx, address, opts...,
)
} else if len(lockingScript) > 0 {
destination, err = getDestinationByLockingScript(
ctx, lockingScript, opts...,
)
}
// Check for errors and if the destination is returned
if err != nil {
return nil, err
} else if destination == nil {
return nil, ErrMissingDestination
}
// Save to cache
// todo: run in a go routine
if err = saveToCache(
ctx, []string{
fmt.Sprintf(cacheKeyDestinationModel, destination.GetID()),
fmt.Sprintf(cacheKeyDestinationModelByAddress, destination.Address),
fmt.Sprintf(cacheKeyDestinationModelByLockingScript, destination.LockingScript),
}, destination, 0,
); err != nil {
return nil, err
}
// Return the model
return destination, nil
}
// GetModelName will get the name of the current model
func (m *Destination) GetModelName() string {
return ModelDestination.String()
}
// GetModelTableName will get the db table name of the current model
func (m *Destination) GetModelTableName() string {
return tableDestinations
}
// Save will save the model into the Datastore
func (m *Destination) Save(ctx context.Context) (err error) {
return Save(ctx, m)
}
// GetID will get the model ID
func (m *Destination) GetID() string {
return m.ID
}
// BeforeCreating will fire before the model is being inserted into the Datastore
func (m *Destination) BeforeCreating(_ context.Context) error {
m.DebugLog("starting: " + m.Name() + " BeforeCreating hook...")
// Set the ID and Type (from LockingScript) (if not set)
if len(m.LockingScript) > 0 && (len(m.ID) == 0 || len(m.Type) == 0) {
m.ID = utils.Hash(m.LockingScript)
m.Type = utils.GetDestinationType(m.LockingScript)
}
m.DebugLog("end: " + m.Name() + " BeforeCreating hook")
return nil
}
// AfterCreated will fire after the model is created in the Datastore
func (m *Destination) AfterCreated(ctx context.Context) error {
m.DebugLog("starting: " + m.Name() + " AfterCreated hook...")
err := m.client.Cluster().Publish(cluster.DestinationNew, m.LockingScript)
if err != nil {
return err
}
// Store in the cache
if err = saveToCache(
ctx, []string{
fmt.Sprintf(cacheKeyDestinationModel, m.GetID()),
fmt.Sprintf(cacheKeyDestinationModelByAddress, m.Address),
fmt.Sprintf(cacheKeyDestinationModelByLockingScript, m.LockingScript),
}, m, 0,
); err != nil {
return err
}
notify(notifications.EventTypeCreate, m)
m.DebugLog("end: " + m.Name() + " AfterCreated hook")
return nil
}
// setAddress will derive and set the address based on the chain (internal vs external)
func (m *Destination) setAddress(rawXpubKey string) error {
// Check the xPub
hdKey, err := utils.ValidateXPub(rawXpubKey)
if err != nil {
return err
}
// Set the ID
m.XpubID = utils.Hash(rawXpubKey)
// Derive the address to ensure it is correct
if m.Address, err = utils.DeriveAddress(
hdKey, m.Chain, m.Num,
); err != nil {
return err
}
return nil
}
// Migrate model specific migration on startup
func (m *Destination) Migrate(client datastore.ClientInterface) error {
return client.IndexMetadata(client.GetTableName(tableDestinations), metadataField)
}
// AfterUpdated will fire after the model is updated in the Datastore
func (m *Destination) AfterUpdated(ctx context.Context) error {
m.DebugLog("starting: " + m.Name() + " AfterUpdated hook...")
// Store in the cache
if err := saveToCache(
ctx, []string{
fmt.Sprintf(cacheKeyDestinationModel, m.GetID()),
fmt.Sprintf(cacheKeyDestinationModelByAddress, m.Address),
fmt.Sprintf(cacheKeyDestinationModelByLockingScript, m.LockingScript),
}, m, 0,
); err != nil {
return err
}
notify(notifications.EventTypeUpdate, m)
m.DebugLog("end: " + m.Name() + " AfterUpdated hook")
return nil
}
// AfterDeleted will fire after the model is deleted in the Datastore
func (m *Destination) AfterDeleted(ctx context.Context) error {
m.DebugLog("starting: " + m.Name() + " AfterDelete hook...")
// Only if we have a client, remove all keys
if m.Client() != nil {
keys := map[string]string{
cacheKeyDestinationModel: m.GetID(),
cacheKeyDestinationModelByAddress: m.Address,
cacheKeyDestinationModelByLockingScript: m.LockingScript,
}
for key, val := range keys {
if err := m.Client().Cachestore().Delete(
ctx, fmt.Sprintf(key, val),
); err != nil {
return err
}
}
}
notify(notifications.EventTypeDelete, m)
m.DebugLog("end: " + m.Name() + " AfterDelete hook")
return nil
}