-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathtx.go
374 lines (320 loc) · 9.1 KB
/
tx.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
package microstellar
import (
"net/http"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/stellar/go/build"
"github.com/stellar/go/clients/horizon"
"github.com/stellar/go/xdr"
)
// Tx represents a unique stellar transaction. This is used by the MicroStellar
// library to abstract away the Horizon API and transport. To reuse Tx
// instances, you must call Tx.Reset() between operations.
//
// This struct is not thread-safe by design -- you must use separate instances
// in different goroutines.
//
// Unless you're hacking around in the guts, you should not need to use Tx.
type Tx struct {
client *horizon.Client
networkName string
network build.Network
fake bool
options *Options
builder *build.TransactionBuilder
payload string
submitted bool
response *horizon.TransactionSuccess
isMultiOp bool // is this a multi-op transaction
ops []build.TransactionMutator // all ops for multi-op
sourceAccount string
err error
}
// NewTx returns a new Tx that operates on the network specified by
// networkName. The supported networks are:
//
// public: the public horizon network
// test: the public horizon testnet
// fake: a fake network used for tests
// custom: a custom network specified by the parameters
//
// If you're using "custom", provide the URL and Passphrase to your
// horizon network server in the parameters.
//
// NewTx("custom", Params{
// "url": "https://my-horizon-server.com",
// "passphrase": "foobar"})
func NewTx(networkName string, params ...Params) *Tx {
var network build.Network
var client *horizon.Client
fake := false
switch networkName {
case "public":
network = build.PublicNetwork
client = horizon.DefaultPublicNetClient
case "test":
network = build.TestNetwork
client = horizon.DefaultTestNetClient
case "fake":
network = build.TestNetwork
client = horizon.DefaultTestNetClient
fake = true
case "custom":
if len(params) < 1 {
logrus.Errorf("missing parameters for custom network, connecting to testnet")
return NewTx("test")
}
url, ok1 := params[0]["url"]
passphrase, ok2 := params[0]["passphrase"]
if !(ok1 && ok2) {
logrus.Errorf("missing url or passphrase, connecting to testnet")
return NewTx("test")
}
network = build.Network{Passphrase: passphrase.(string)}
client = &horizon.Client{
URL: url.(string),
HTTP: http.DefaultClient,
}
default:
// use the test network
network = build.TestNetwork
client = horizon.DefaultTestNetClient
}
return &Tx{
networkName: networkName,
client: client,
network: network,
fake: fake,
options: nil,
builder: nil,
payload: "",
submitted: false,
response: nil,
isMultiOp: false,
ops: []build.TransactionMutator{},
err: nil,
}
}
// SetOptions sets the Tx options
func (tx *Tx) SetOptions(options *Options) {
tx.options = options
if options.isMultiOp {
tx.Start(options.multiOpSource)
}
}
// WithOptions sets the Tx options and returns the Tx
func (tx *Tx) WithOptions(options *Options) *Tx {
tx.SetOptions(options)
return tx
}
// GetClient returns the underlying horizon client handle.
func (tx *Tx) GetClient() *horizon.Client {
return tx.client
}
// Err returns the error from the most recent failed operation.
func (tx *Tx) Err() error {
return tx.err
}
// TxResponse is returned by the horizon server for a successful transaction.
type TxResponse horizon.TransactionSuccess
// Response returns the horison response for the submitted operation.
func (tx *Tx) Response() *TxResponse {
response := TxResponse(*tx.response)
return &response
}
// Payload returns the built (and possibly signed) payload for this transaction as a
// base64 string.
func (tx *Tx) Payload() (string, error) {
if tx.fake {
return "PAYLOAD", nil
}
if tx.isMultiOp {
var err error
tx.builder, err = build.Transaction(tx.ops...)
if err != nil {
return "", errors.Wrap(err, "could not build transaction")
}
}
if tx.builder == nil {
return "", errors.Errorf("transaction not built")
}
if tx.payload == "" {
// If there's no payload, build it.
var txe build.TransactionEnvelopeBuilder
txe.Mutate(tx.builder)
b64, err := txe.Base64()
if err != nil {
return "", errors.Wrap(err, "error generating payload")
}
return b64, nil
}
return tx.payload, nil
}
// Reset clears all internal sate, so you can run a new operation.
func (tx *Tx) Reset() {
tx.options = nil
tx.builder = nil
tx.payload = ""
tx.submitted = false
tx.response = nil
tx.isMultiOp = false
tx.err = nil
}
func sourceAccount(addressOrSeed string) build.SourceAccount {
return build.SourceAccount{AddressOrSeed: addressOrSeed}
}
// Start begins a new multi-op transaction with fees billed to account
func (tx *Tx) Start(account string) *Tx {
tx.sourceAccount = account
sourceAccount := sourceAccount(account)
tx.ops = []build.TransactionMutator{
build.TransactionMutator(sourceAccount),
tx.network,
build.AutoSequence{SequenceProvider: tx.client},
}
tx.isMultiOp = true
return tx
}
// Build creates a new operation out of the provided mutators.
func (tx *Tx) Build(sourceAccount build.TransactionMutator, muts ...build.TransactionMutator) error {
if tx.err != nil {
return tx.err
}
if tx.builder != nil {
tx.err = errors.Errorf("transaction already built")
return tx.err
}
if tx.fake && !tx.isMultiOp {
tx.builder = &build.TransactionBuilder{}
return nil
}
if tx.options != nil {
switch tx.options.memoType {
case MemoText:
if len(tx.options.memoText) > 28 {
return errors.Errorf("memo text >28 bytes: %v", tx.options.memoText)
}
muts = append(muts, build.MemoText{Value: tx.options.memoText})
case MemoID:
muts = append(muts, build.MemoID{Value: tx.options.memoID})
case MemoHash:
muts = append(muts, build.MemoHash{Value: xdr.Hash(tx.options.memoHash)})
case MemoReturn:
muts = append(muts, build.MemoReturn{Value: xdr.Hash(tx.options.memoHash)})
}
if tx.options.hasTimeBounds {
muts = append(muts, build.Timebounds{MinTime: uint64(tx.options.minTimeBound.Unix()), MaxTime: uint64(tx.options.maxTimeBound.Unix())})
}
}
if tx.isMultiOp {
tx.ops = append(tx.ops, muts...)
} else {
muts = append([]build.TransactionMutator{
sourceAccount,
tx.network,
build.AutoSequence{SequenceProvider: tx.client},
}, muts...)
builder, err := build.Transaction(muts...)
tx.builder = builder
tx.err = errors.Wrap(err, "could not build transaction")
}
return tx.err
}
// IsSigned returns true of the transaction is signed.
func (tx *Tx) IsSigned() bool {
return tx.payload != ""
}
// Sign signs the transaction with every key in keys.
func (tx *Tx) Sign(keys ...string) error {
if tx.err != nil {
return tx.err
}
if tx.builder == nil && !tx.isMultiOp {
tx.err = errors.Errorf("can't sign empty transaction")
return tx.err
}
if tx.IsSigned() {
tx.err = errors.Errorf("transaction already signed")
return tx.err
}
if tx.fake {
tx.payload = "FAKE"
return nil
}
var txe build.TransactionEnvelopeBuilder
var err error
if tx.isMultiOp {
tx.builder, err = build.Transaction(tx.ops...)
}
if tx.options != nil && tx.options.skipSignatures {
debugf("Tx.Sign", "skipping signatures")
txe.Mutate(tx.builder)
} else {
debugf("Tx.Sign", "signing transaction, seq: %v", tx.builder.TX.SeqNum)
if tx.options != nil && len(tx.options.signerSeeds) > 0 {
txe, err = tx.builder.Sign(tx.options.signerSeeds...)
} else {
if len(keys) == 0 {
keys = []string{tx.sourceAccount}
}
txe, err = tx.builder.Sign(keys...)
}
if err != nil {
tx.err = errors.Wrap(err, "signing error")
return tx.err
}
}
tx.payload, err = txe.Base64()
debugf("Tx.Sign", "signed transaction, payload: %s", tx.payload)
if err != nil {
tx.err = errors.Wrap(err, "base64 conversion error")
return tx.err
}
return nil
}
// Submit sends the transaction to the stellar network.
func (tx *Tx) Submit() error {
if tx.err != nil {
return tx.err
}
if !tx.IsSigned() {
tx.err = errors.Errorf("transaction not signed")
return tx.err
}
if tx.submitted {
tx.err = errors.Errorf("transaction already submitted")
return tx.err
}
if tx.options != nil {
// Call the presubmit handler, if set.
handler, ok := tx.options.handlers[EvBeforeSubmit]
if ok {
debugf("Tx.Submit", "calling presubmit handler")
f := (func(...interface{}) (bool, error))(*handler)
cont, err := f(tx.payload)
if tx.err != nil {
tx.err = errors.Wrap(err, "presubmit handler failed")
return tx.err
}
if !cont {
return nil
}
}
}
if tx.fake {
tx.response = &horizon.TransactionSuccess{Result: "fake_ok"}
return nil
}
debugf("Tx.Submit", "submitting transaction to network %s", tx.networkName)
resp, err := tx.client.SubmitTransaction(tx.payload)
if err != nil {
debugf("Tx.Submit", "submit failed: %s", ErrorString(err))
tx.err = errors.Wrap(err, "could not submit transaction")
return tx.err
}
debugf("Tx.Submit", "transaction submitted to ledger %d with hash %s", int32(resp.Ledger), resp.Hash)
tx.response = &resp
tx.submitted = true
tx.submitted = true
return nil
}