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_transaction_config.go
398 lines (350 loc) · 13.5 KB
/
model_transaction_config.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
package bux
import (
"bytes"
"context"
"database/sql/driver"
"encoding/hex"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/BuxOrg/bux/cachestore"
"github.com/BuxOrg/bux/utils"
magic "github.com/bitcoinschema/go-map"
"github.com/libsv/go-bt/v2/bscript"
"github.com/tonicpow/go-paymail"
)
// TransactionConfig is the configuration used to start a transaction
type TransactionConfig struct {
// Conditions (utxo choices)
// NlockTime uint32
ChangeDestinations []*Destination `json:"change_destinations" toml:"change_destinations" yaml:"change_destinations"`
ChangeDestinationsStrategy ChangeStrategy `json:"change_destinations_strategy" toml:"change_destinations_strategy" yaml:"change_destinations_strategy"`
ChangeMinimumSatoshis uint64 `json:"change_minimum_satoshis" toml:"change_minimum_satoshis" yaml:"change_minimum_satoshis"`
ChangeNumberOfDestinations int `json:"change_number_of_destinations" toml:"change_number_of_destinations" yaml:"change_number_of_destinations"`
ChangeSatoshis uint64 `json:"change_satoshis" toml:"change_satoshis" yaml:"change_satoshis"`
ExpiresIn time.Duration `json:"expires_in" toml:"expires_in" yaml:"expires_in"`
Fee uint64 `json:"fee" toml:"fee" yaml:"fee"`
FeeUnit *utils.FeeUnit `json:"fee_unit" toml:"fee_unit" yaml:"fee_unit"`
FromUtxos []*UtxoPointer `json:"from_utxos" toml:"from_utxos" yaml:"from_utxos"`
Inputs []*TransactionInput `json:"inputs" toml:"inputs" yaml:"inputs"`
Miner string `json:"miner" toml:"miner" yaml:"miner"`
Outputs []*TransactionOutput `json:"outputs" toml:"outputs" yaml:"outputs"`
SendAllTo string `json:"send_all_to" toml:"send_all_to" yaml:"send_all_to"`
Sync *SyncConfig `json:"sync" toml:"sync" yaml:"sync"`
}
// TransactionInput is an input on the transaction config
type TransactionInput struct {
Utxo
Destination Destination `json:"destination" toml:"destination" yaml:"destination" bson:"destination"`
}
// MapProtocol is a specific MAP protocol interface for an op_return
type MapProtocol struct {
App string `json:"app,omitempty"`
Keys map[string]interface{} `json:"keys,omitempty"`
Type string `json:"type,omitempty"`
}
// OpReturn is the op_return definition for the output
type OpReturn struct {
Hex string `json:"hex,omitempty"`
HexParts []string `json:"hex_parts,omitempty"`
Map *MapProtocol `json:"map,omitempty"`
StringParts []string `json:"string_parts,omitempty"`
}
// TransactionOutput is an output on the transaction config
type TransactionOutput struct {
PaymailP4 *PaymailP4 `json:"paymail_p4,omitempty" toml:"paymail_p4" yaml:"paymail_p4" bson:"paymail_p4,omitempty"`
Satoshis uint64 `json:"satoshis" toml:"satoshis" yaml:"satoshis" bson:"satoshis"`
Scripts []*ScriptOutput `json:"scripts" toml:"scripts" yaml:"scripts" bson:"scripts"`
To string `json:"to,omitempty" toml:"to" yaml:"to" bson:"to,omitempty"`
OpReturn *OpReturn `json:"op_return" toml:"op_return" yaml:"op_return" bson:"op_return,omitempty"`
}
// PaymailP4 paymail configuration for the p2p payments on this output
type PaymailP4 struct {
Alias string `json:"alias" toml:"alias" yaml:"alias" bson:"alias,omitempty"`
Domain string `json:"domain" toml:"domain" yaml:"domain" bson:"domain,omitempty"`
FromPaymail string `json:"from_paymail,omitempty" toml:"from_paymail" yaml:"from_paymail" bson:"from_paymail,omitempty"`
Note string `json:"note,omitempty" toml:"note" yaml:"note" bson:"note,omitempty"`
PubKey string `json:"pub_key,omitempty" toml:"pub_key" yaml:"pub_key" bson:"pub_key,omitempty"`
ReceiveEndpoint string `json:"receive_endpoint,omitempty" toml:"receive_endpoint" yaml:"receive_endpoint" bson:"receive_endpoint,omitempty"`
ReferenceID string `json:"reference_id,omitempty" toml:"reference_id" yaml:"reference_id" bson:"reference_id,omitempty"`
ResolutionType string `json:"resolution_type" toml:"resolution_type" yaml:"resolution_type" bson:"resolution_type,omitempty"`
}
// Types of resolution methods
const (
// ResolutionTypeBasic is for the "deprecated" way to resolve an address from a Paymail
ResolutionTypeBasic = "basic_resolution"
// ResolutionTypeP2P is the current way to resolve a Paymail (prior to P4)
ResolutionTypeP2P = "p2p"
)
// ChangeStrategy strategy to use for change
type ChangeStrategy string
// Types of change destination strategies
const (
// ChangeStrategyDefault Change strategy just dividing the satoshis among the change destinations
ChangeStrategyDefault ChangeStrategy = "default"
// ChangeStrategyRandom Change strategy randomizing the output of satoshis among the change destinations
ChangeStrategyRandom ChangeStrategy = "random"
// ChangeStrategyNominations Change strategy using coin nominations for the outputs (10, 25, 50, 100, 250 etc.)
ChangeStrategyNominations ChangeStrategy = "nominations"
)
// ScriptOutput is the actual script record (could be several for one output record)
type ScriptOutput struct {
Address string `json:"address,omitempty"` // Hex encoded locking script
Satoshis uint64 `json:"satoshis,omitempty"` // Number of satoshis for that output
Script string `json:"script"` // Hex encoded locking script
ScriptType string `json:"script_type"` // The type of output
}
// Scan will scan the value into Struct, implements sql.Scanner interface
func (t *TransactionConfig) Scan(value interface{}) error {
if value == nil {
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("\"\"")) {
return nil
}
return json.Unmarshal(byteValue, &t)
}
// Value return json value, implement driver.Valuer interface
func (t TransactionConfig) Value() (driver.Value, error) {
marshal, err := json.Marshal(t)
if err != nil {
return nil, err
}
return string(marshal), nil
}
// processOutput will inspect the output to determine how to process
func (t *TransactionOutput) processOutput(ctx context.Context, cacheStore cachestore.ClientInterface,
paymailClient paymail.ClientInterface, defaultFromSender, defaultNote string, checkSats bool) error {
// Convert known handle formats ($handcash or 1relayx)
if strings.Contains(t.To, handleHandcashPrefix) ||
(len(t.To) < handleMaxLength && len(t.To) > 1 && t.To[:1] == handleRelayPrefix) {
// Convert the handle and check if it's changed (becomes a paymail address)
if p := paymail.ConvertHandle(t.To, false); p != t.To {
t.To = p
}
}
// Check for Paymail, Bitcoin Address or OP Return
if len(t.To) > 0 && strings.Contains(t.To, "@") { // Paymail output
if checkSats && t.Satoshis <= 0 {
return ErrOutputValueTooLow
}
return t.processPaymailOutput(ctx, cacheStore, paymailClient, defaultFromSender, defaultNote)
} else if len(t.To) > 0 { // Standard Bitcoin Address
if checkSats && t.Satoshis <= 0 {
return ErrOutputValueTooLow
}
return t.processAddressOutput()
} else if t.OpReturn != nil { // OP_RETURN output
if checkSats && t.Satoshis > 0 {
return ErrOutputValueUnSpendable
}
return t.processOpReturnOutput()
}
// No value set in either ToPaymail or ToAddress
return ErrOutputValueNotRecognized
}
// processPaymailOutput will detect how to process the Paymail output given
func (t *TransactionOutput) processPaymailOutput(ctx context.Context, cacheStore cachestore.ClientInterface,
paymailClient paymail.ClientInterface, defaultFromSender, defaultNote string) error {
// Standardize the paymail address (break into parts)
alias, domain, paymailAddress := paymail.SanitizePaymail(t.To)
if len(paymailAddress) == 0 {
return ErrPaymailAddressIsInvalid
}
// Set the sanitized version of the paymail address provided
t.To = paymailAddress
// Start setting the Paymail information (nil check might not be needed)
if t.PaymailP4 == nil {
t.PaymailP4 = &PaymailP4{
Alias: alias,
Domain: domain,
}
} else {
t.PaymailP4.Alias = alias
t.PaymailP4.Domain = domain
}
// Get the capabilities for the domain
capabilities, err := getCapabilities(
ctx, cacheStore, paymailClient, domain,
)
if err != nil {
return err
}
// Does the provider support P2P?
success, p2pDestinationURL, p2pSubmitTxURL := hasP2P(capabilities)
if success {
return t.processPaymailViaP2P(
paymailClient, p2pDestinationURL, p2pSubmitTxURL,
)
}
// Default is resolving using the deprecated address resolution method
return t.processPaymailViaAddressResolution(
ctx, cacheStore, paymailClient, capabilities,
defaultFromSender, defaultNote,
)
}
// processPaymailViaAddressResolution will use a deprecated way to resolve a Paymail address
func (t *TransactionOutput) processPaymailViaAddressResolution(ctx context.Context, cacheStore cachestore.ClientInterface,
paymailClient paymail.ClientInterface, capabilities *paymail.CapabilitiesPayload, defaultFromSender, defaultNote string) error {
// Requires a note value
if len(t.PaymailP4.Note) == 0 {
t.PaymailP4.Note = defaultNote
}
if len(t.PaymailP4.FromPaymail) == 0 {
t.PaymailP4.FromPaymail = defaultFromSender
}
// Resolve the address information
resolution, err := resolvePaymailAddress(
ctx, cacheStore, paymailClient, capabilities,
t.PaymailP4.Alias, t.PaymailP4.Domain,
t.PaymailP4.Note,
t.PaymailP4.FromPaymail,
)
if err != nil {
return err
} else if resolution == nil {
return ErrResolutionFailed
}
// Set the output data
t.Scripts = append(
t.Scripts,
&ScriptOutput{
Address: resolution.Address,
Satoshis: t.Satoshis,
Script: resolution.Output,
ScriptType: utils.ScriptTypePubKeyHash,
},
)
t.PaymailP4.ResolutionType = ResolutionTypeBasic
return nil
}
// processPaymailViaP2P will process the output for P2P Paymail resolution
func (t *TransactionOutput) processPaymailViaP2P(client paymail.ClientInterface, p2pDestinationURL, p2pSubmitTxURL string) error {
// Get the outputs and destination information from the Paymail provider
destinationInfo, err := startP2PTransaction(
client, t.PaymailP4.Alias, t.PaymailP4.Domain,
p2pDestinationURL, t.Satoshis,
)
if err != nil {
return err
}
// Loop all received P2P outputs and build scripts
for _, out := range destinationInfo.Outputs {
t.Scripts = append(
t.Scripts,
&ScriptOutput{
Address: out.Address,
Satoshis: out.Satoshis,
Script: out.Script,
ScriptType: utils.ScriptTypePubKeyHash,
},
)
}
// Set the remaining P2P information
t.PaymailP4.ReceiveEndpoint = p2pSubmitTxURL
t.PaymailP4.ReferenceID = destinationInfo.Reference
t.PaymailP4.ResolutionType = ResolutionTypeP2P
return nil
}
// processAddressOutput will process an output for a standard Bitcoin Address Transaction
func (t *TransactionOutput) processAddressOutput() (err error) {
// Create the script from the Bitcoin address
var s *bscript.Script
if s, err = bscript.NewP2PKHFromAddress(t.To); err != nil {
return
}
// Append the script
t.Scripts = append(
t.Scripts,
&ScriptOutput{
Address: t.To,
Satoshis: t.Satoshis,
Script: s.String(),
ScriptType: utils.ScriptTypePubKeyHash,
},
)
return
}
// processOpReturnOutput will process an op_return output
func (t *TransactionOutput) processOpReturnOutput() (err error) {
// Create the script from the Bitcoin address
var script string
if len(t.OpReturn.Hex) > 0 {
// raw op_return output in hex
var s *bscript.Script
if s, err = bscript.NewFromHexString(t.OpReturn.Hex); err != nil {
return
}
script = s.String()
} else if len(t.OpReturn.HexParts) > 0 {
// hex strings of the op_return output
bytesArray := make([][]byte, 0)
for _, h := range t.OpReturn.HexParts {
var b []byte
if b, err = hex.DecodeString(h); err != nil {
return
}
bytesArray = append(bytesArray, b)
}
s := &bscript.Script{}
_ = s.AppendOpcodes(bscript.OpFALSE, bscript.OpRETURN)
if err = s.AppendPushDataArray(bytesArray); err != nil {
return
}
script = s.String()
} else if len(t.OpReturn.StringParts) > 0 {
// strings for the op_return output
bytesArray := make([][]byte, 0)
for _, s := range t.OpReturn.StringParts {
bytesArray = append(bytesArray, []byte(s))
}
s := &bscript.Script{}
_ = s.AppendOpcodes(bscript.OpFALSE, bscript.OpRETURN)
if err = s.AppendPushDataArray(bytesArray); err != nil {
return
}
script = s.String()
} else if t.OpReturn.Map != nil {
// strings for the map op_return
bytesArray := [][]byte{
[]byte(magic.Prefix),
[]byte(magic.Set),
[]byte(magic.MapAppKey),
[]byte(t.OpReturn.Map.App),
[]byte(magic.MapTypeKey),
[]byte(t.OpReturn.Map.Type),
}
if len(t.OpReturn.Map.Keys) > 0 {
for key, value := range t.OpReturn.Map.Keys {
bytesArray = append(bytesArray, []byte(key))
bytesArray = append(bytesArray, []byte(value.(string)))
}
}
s := &bscript.Script{}
_ = s.AppendOpcodes(bscript.OpFALSE, bscript.OpRETURN)
if err = s.AppendPushDataArray(bytesArray); err != nil {
return
}
script = s.String()
} else {
return ErrInvalidOpReturnOutput
}
// Append the script
t.Scripts = append(
t.Scripts,
&ScriptOutput{
Satoshis: t.Satoshis,
Script: script,
ScriptType: utils.ScriptTypeNullData,
},
)
return
}