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
/
paymail_service_provider.go
285 lines (244 loc) · 8.58 KB
/
paymail_service_provider.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
package bux
import (
"context"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"time"
"github.com/BuxOrg/bux/utils"
"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/mrz1836/go-datastore"
customTypes "github.com/mrz1836/go-datastore/custom_types"
"github.com/tonicpow/go-paymail"
"github.com/tonicpow/go-paymail/server"
)
// PaymailDefaultServiceProvider is an interface for overriding the paymail actions in go-paymail/server
//
// This is an example and the default functionality for all the basic Paymail actions
type PaymailDefaultServiceProvider struct {
client ClientInterface // (pointer) to the Client for accessing BUX model methods & etc
}
// createMetadata will create a new metadata seeded from the server information
func (p *PaymailDefaultServiceProvider) createMetadata(serverMetaData *server.RequestMetadata, request string) (metadata Metadata) {
metadata = make(Metadata)
metadata["paymail_request"] = request
if serverMetaData != nil {
if serverMetaData.UserAgent != "" {
metadata["user_agent"] = serverMetaData.UserAgent
}
if serverMetaData.Note != "" {
metadata["note"] = serverMetaData.Note
}
if serverMetaData.Domain != "" {
metadata[domainField] = serverMetaData.Domain
}
if serverMetaData.IPAddress != "" {
metadata["ip_address"] = serverMetaData.IPAddress
}
}
return
}
// GetPaymailByAlias will get a paymail address and information by alias
func (p *PaymailDefaultServiceProvider) GetPaymailByAlias(ctx context.Context, alias, domain string,
requestMetadata *server.RequestMetadata) (*paymail.AddressInformation, error) {
// Create the metadata
metadata := p.createMetadata(requestMetadata, "GetPaymailByAlias")
// Create the paymail information
paymailAddress, pubKey, destination, err := p.createPaymailInformation(
ctx, alias, domain, true, append(p.client.DefaultModelOptions(), WithMetadatas(metadata))...,
)
if err != nil {
return nil, err
}
// Return the information required by go-paymail
return &paymail.AddressInformation{
Alias: paymailAddress.Alias,
Avatar: paymailAddress.Avatar,
Domain: paymailAddress.Domain,
ID: paymailAddress.ID,
LastAddress: destination.Address,
Name: paymailAddress.PublicName,
PubKey: pubKey,
}, nil
}
// CreateAddressResolutionResponse will create the address resolution response
func (p *PaymailDefaultServiceProvider) CreateAddressResolutionResponse(ctx context.Context, alias, domain string,
_ bool, requestMetadata *server.RequestMetadata) (*paymail.ResolutionPayload, error) {
// Create the metadata
metadata := p.createMetadata(requestMetadata, "CreateAddressResolutionResponse")
// Create the paymail information
_, _, destination, err := p.createPaymailInformation(
ctx, alias, domain, true, append(p.client.DefaultModelOptions(), WithMetadatas(metadata))...,
)
if err != nil {
return nil, err
}
// Create the address resolution payload response
return &paymail.ResolutionPayload{
Address: destination.Address,
Output: destination.LockingScript,
Signature: "", // todo: add the signature if senderValidation is enabled
}, nil
}
// CreateP2PDestinationResponse will create a p2p destination response
func (p *PaymailDefaultServiceProvider) CreateP2PDestinationResponse(ctx context.Context, alias, domain string,
satoshis uint64, requestMetadata *server.RequestMetadata) (*paymail.PaymentDestinationPayload, error) {
// Generate a unique reference ID
referenceID, err := utils.RandomHex(16)
if err != nil {
return nil, err
}
// Create the metadata
metadata := p.createMetadata(requestMetadata, "CreateP2PDestinationResponse")
metadata[ReferenceIDField] = referenceID
metadata[satoshisField] = satoshis
// Create the paymail information
// todo: strategy to break apart outputs based on satoshis (return x Outputs)
var destination *Destination
_, _, destination, err = p.createPaymailInformation(
ctx, alias, domain, false, append(p.client.DefaultModelOptions(), WithMetadatas(metadata))...,
)
if err != nil {
return nil, err
}
// Append the output(s)
var outputs []*paymail.PaymentOutput
outputs = append(outputs, &paymail.PaymentOutput{
Address: destination.Address,
Satoshis: satoshis,
Script: destination.LockingScript,
})
return &paymail.PaymentDestinationPayload{
Outputs: outputs,
Reference: referenceID,
}, nil
}
// RecordTransaction will record the transaction
func (p *PaymailDefaultServiceProvider) RecordTransaction(ctx context.Context,
p2pTx *paymail.P2PTransaction, requestMetadata *server.RequestMetadata) (*paymail.P2PTransactionPayload, error) {
// Create the metadata
metadata := p.createMetadata(requestMetadata, "RecordTransaction")
metadata[p2pMetadataField] = p2pTx.MetaData
metadata[ReferenceIDField] = p2pTx.Reference
// Record the transaction
transaction, err := p.client.RecordTransaction(
ctx, "", p2pTx.Hex, "", []ModelOps{WithMetadatas(metadata)}...,
)
// do not return an error if we already have the transaction
if err != nil && !errors.Is(err, datastore.ErrDuplicateKey) {
return nil, err
}
// we need to set the tx ID here, since our transaction will be empty if we already had it in the DB
txID := ""
if transaction != nil {
txID = transaction.ID
} else {
var btTx *bt.Tx
btTx, err = bt.NewTxFromString(p2pTx.Hex)
if err != nil {
return nil, err
}
txID = btTx.TxID()
}
// Return the response from the p2p request
return &paymail.P2PTransactionPayload{
Note: p2pTx.MetaData.Note,
TxID: txID,
}, nil
}
// createPaymailInformation will get & create the paymail information (dynamic addresses)
func (p *PaymailDefaultServiceProvider) createPaymailInformation(ctx context.Context, alias, domain string,
monitor bool, opts ...ModelOps) (paymailAddress *PaymailAddress, pubKey string, destination *Destination, err error) {
// Get the paymail address record
paymailAddress, err = getPaymailAddress(ctx, alias+"@"+domain, opts...)
if err != nil {
return nil, "", nil, err
}
// Create the lock and set the release for after the function completes
var unlock func()
unlock, err = newWaitWriteLock(
ctx, fmt.Sprintf(lockKeyProcessXpub, paymailAddress.XpubID), p.client.Cachestore(),
)
defer unlock()
if err != nil {
return nil, "", nil, err
}
// Get the corresponding xPub related to the paymail address
var xPub *Xpub
if xPub, err = getXpubWithCache(
ctx, p.client, "", paymailAddress.XpubID, opts...,
); err != nil {
return nil, "", nil, err
}
// Get the external key (decrypted if needed)
var externalXpub *bip32.ExtendedKey
if externalXpub, err = paymailAddress.GetExternalXpub(); err != nil {
return nil, "", nil, err
}
// Increment and save
var chainNum uint32
if chainNum, err = xPub.incrementNextNum(ctx, utils.ChainExternal); err != nil {
return nil, "", nil, err
}
// Generate the new xPub and address with locking script
var lockingScript string
if pubKey, _, lockingScript, err = getPaymailKeyInfo(
externalXpub.String(),
chainNum,
); err != nil {
return nil, "", nil, err
}
// create a new destination, based on the External xPub child
// this is not yet possible using the xpub struct. That needs the full xPub, which we don't have.
destination = newDestination(paymailAddress.XpubID, lockingScript, append(opts, New())...)
destination.Chain = utils.ChainExternal
destination.Num = chainNum
// Only on for basic address resolution, not enabled for p2p
if monitor {
destination.Monitor = customTypes.NullTime{NullTime: sql.NullTime{
Valid: true,
Time: time.Now(),
}}
}
// Create the new destination
if err = destination.Save(ctx); err != nil {
return nil, "", nil, err
}
return
}
// getPaymailKeyInfo will get all the paymail key information
func getPaymailKeyInfo(rawXPubKey string, num uint32) (pubKey, address, lockingScript string, err error) {
// Get the xPub from string
var hdKey *bip32.ExtendedKey
hdKey, err = utils.ValidateXPub(rawXPubKey)
if err != nil {
return
}
// Get the child key
var derivedKey *bip32.ExtendedKey
if derivedKey, err = bitcoin.GetHDKeyChild(hdKey, num); err != nil {
return
}
// Get the next key
var nextKey *bec.PublicKey
if nextKey, err = derivedKey.ECPubKey(); err != nil {
return
}
pubKey = hex.EncodeToString(nextKey.SerialiseCompressed())
// Get the address from the xPub
var bsvAddress *bscript.Address
if bsvAddress, err = bitcoin.GetAddressFromPubKey(
nextKey, true,
); err != nil {
return
}
address = bsvAddress.AddressString
// Generate a locking script for the address
lockingScript, err = bitcoin.ScriptFromAddress(address)
return
}