/
transactionbuilder.go
672 lines (599 loc) · 24.4 KB
/
transactionbuilder.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
package wallet
import (
"bytes"
"errors"
"github.com/HyperspaceApp/Hyperspace/crypto"
"github.com/HyperspaceApp/Hyperspace/encoding"
"github.com/HyperspaceApp/Hyperspace/modules"
"github.com/HyperspaceApp/Hyperspace/types"
)
var (
// errBuilderAlreadySigned indicates that the transaction builder has
// already added at least one successful signature to the transaction,
// meaning that future calls to Sign will result in an invalid transaction.
errBuilderAlreadySigned = errors.New("sign has already been called on this transaction builder, multiple calls can cause issues")
// errDustOutput indicates an output is not spendable because it is dust.
errDustOutput = errors.New("output is too small")
// errOutputTimelock indicates an output's timelock is still active.
errOutputTimelock = errors.New("wallet consensus set height is lower than the output timelock")
// errSpendHeightTooHigh indicates an output's spend height is greater than
// the allowed height.
errSpendHeightTooHigh = errors.New("output spend height exceeds the allowed height")
// errMissingOutputKey indicates that we are missing the key corresponding to an output
errMissingOutputKey = errors.New("no corresponding key found for output")
)
// transactionBuilder allows transactions to be manually constructed, including
// the ability to fund transactions with space cash from the wallet.
type transactionBuilder struct {
// 'signed' indicates that at least one transaction signature has been
// added to the wallet, meaning that future calls to 'Sign' will fail.
parents []types.Transaction
signed bool
transaction types.Transaction
newParents []int
siacoinInputs []int
transactionSignatures []int
wallet *Wallet
}
// addSignatures will sign a transaction using a spendable key, with support
// for multisig spendable keys. Because of the restricted input, the function
// is compatible with space cash inputs.
func addSignatures(txn *types.Transaction, cf types.CoveredFields, uc types.UnlockConditions, parentID crypto.Hash, spendKey spendableKey) (newSigIndices []int) {
// Try to find the matching secret key for each public key - some public
// keys may not have a match. Some secret keys may be used multiple times,
// which is why public keys are used as the outer loop.
totalSignatures := uint64(0)
for i, siaPubKey := range uc.PublicKeys {
// Search for the matching secret key to the public key.
for j := range spendKey.SecretKeys {
pubKey := spendKey.SecretKeys[j].PublicKey()
if !bytes.Equal(siaPubKey.Key, pubKey[:]) {
continue
}
// Found the right secret key, add a signature.
sig := types.TransactionSignature{
ParentID: parentID,
CoveredFields: cf,
PublicKeyIndex: uint64(i),
}
newSigIndices = append(newSigIndices, len(txn.TransactionSignatures))
txn.TransactionSignatures = append(txn.TransactionSignatures, sig)
sigIndex := len(txn.TransactionSignatures) - 1 // the one just added
sigHash := txn.SigHash(sigIndex)
encodedSig := crypto.SignHash(sigHash, spendKey.SecretKeys[j])
txn.TransactionSignatures[sigIndex].Signature = encodedSig[:]
// Count that the signature has been added, and break out of the
// secret key loop.
totalSignatures++
break
}
// If there are enough signatures to satisfy the unlock conditions,
// break out of the outer loop.
if totalSignatures == uc.SignaturesRequired {
break
}
}
return newSigIndices
}
func calculateAmountFromOutputs(outputs []types.SiacoinOutput, fee types.Currency) types.Currency {
// Calculate the total amount we need to send
var amount types.Currency
for i := range outputs {
output := outputs[i]
amount = amount.Add(output.Value)
}
if fee.Cmp64(0) > 0 {
amount = amount.Add(fee)
}
return amount
}
// fund gather enough inputs to satisfy amountToFund, return
// the outputs so that the caller can decide to spend them or
// discard it eventually.
func (tb *transactionBuilder) fund(amountToFund types.Currency, refundID types.SiacoinOutputID, spendableOutputs sortedOutputs) (types.Currency, []types.SiacoinOutputID, error) {
dustThreshold, err := tb.wallet.DustThreshold()
if err != nil {
return types.Currency{}, nil, err
}
consensusHeight, err := dbGetConsensusHeight(tb.wallet.dbTx)
if err != nil {
return types.Currency{}, nil, err
}
// potentialFund tracks the balance of the wallet including outputs that
// have been spent in other unconfirmed transactions recently. This is to
// provide the user with a more useful error message in the event that they
// are overspending.
var potentialFund types.Currency
// Those are needed to the caller, to spend the outputs
var selectedOutputs []types.SiacoinOutputID
// Represent the total inOutput fund
var fundedAmount types.Currency
for i := range spendableOutputs.ids {
inOutputID := spendableOutputs.ids[i]
inOutput := spendableOutputs.outputs[i]
// Check that the output can be spent.
err := tb.wallet.checkOutput(tb.wallet.dbTx, consensusHeight, inOutputID, inOutput, dustThreshold)
// Avoid to discard the output due to spend height being too high
if err != nil && refundID != inOutputID {
if err == errSpendHeightTooHigh {
potentialFund = potentialFund.Add(inOutput.Value)
}
continue
}
// Add a siacoin input for this output.
spendInput := types.SiacoinInput{
ParentID: inOutputID,
UnlockConditions: tb.wallet.keys[inOutput.UnlockHash].UnlockConditions,
}
tb.siacoinInputs = append(tb.siacoinInputs, len(tb.transaction.SiacoinInputs))
tb.transaction.SiacoinInputs = append(tb.transaction.SiacoinInputs, spendInput)
selectedOutputs = append(selectedOutputs, inOutputID)
fundedAmount = fundedAmount.Add(inOutput.Value)
potentialFund = potentialFund.Add(inOutput.Value)
if fundedAmount.Cmp(amountToFund) >= 0 {
break
}
}
// TODO: Move this check to the caller?
if potentialFund.Cmp(amountToFund) >= 0 && fundedAmount.Cmp(amountToFund) < 0 {
return fundedAmount, selectedOutputs, modules.ErrIncompleteTransactions
}
if fundedAmount.Cmp(amountToFund) < 0 {
return fundedAmount, selectedOutputs, modules.ErrLowBalance
}
return fundedAmount, selectedOutputs, nil
}
func (tb *transactionBuilder) addRefund(refundAmount types.Currency) (types.SiacoinOutput, error) {
refundUnlockConditions, err := tb.wallet.nextPrimarySeedAddress(tb.wallet.dbTx)
if err != nil {
return types.SiacoinOutput{}, err
}
refundOutput := types.SiacoinOutput{
Value: refundAmount,
UnlockHash: refundUnlockConditions.UnlockHash(),
}
tb.transaction.SiacoinOutputs = append(tb.transaction.SiacoinOutputs, refundOutput)
//fmt.Println("refundID",tb.transaction.SiacoinOutputID(uint64(len(tb.transaction.SiacoinOutputs)-1)))
return refundOutput, nil
}
// FundSiacoins will add a siacoin input of exactly 'amount' to the
// transaction. A parent transaction may be needed to achieve an input with the
// correct value. The siacoin input will not be signed until 'Sign' is called
// on the transaction builder.
func (tb *transactionBuilder) FundSiacoins(amount types.Currency) error {
// dustThreshold has to be obtained separate from the lock
dustThreshold, err := tb.wallet.DustThreshold()
if err != nil {
return err
}
tb.wallet.mu.Lock()
defer tb.wallet.mu.Unlock()
consensusHeight, err := dbGetConsensusHeight(tb.wallet.dbTx)
if err != nil {
return err
}
so, err := tb.wallet.getSortedOutputs()
if err != nil {
return err
}
// Create and fund a parent transaction that will add the correct amount of
// siacoins to the transaction.
var fund types.Currency
// potentialFund tracks the balance of the wallet including outputs that
// have been spent in other unconfirmed transactions recently. This is to
// provide the user with a more useful error message in the event that they
// are overspending.
var potentialFund types.Currency
parentTxn := types.Transaction{}
var spentScoids []types.SiacoinOutputID
for i := range so.ids {
scoid := so.ids[i]
sco := so.outputs[i]
// Check that the output can be spent.
if err := tb.wallet.checkOutput(tb.wallet.dbTx, consensusHeight, scoid, sco, dustThreshold); err != nil {
if err == errSpendHeightTooHigh {
potentialFund = potentialFund.Add(sco.Value)
}
continue
}
key, ok := tb.wallet.keys[sco.UnlockHash]
if !ok {
return errMissingOutputKey
}
// Add a siacoin input for this output.
sci := types.SiacoinInput{
ParentID: scoid,
UnlockConditions: key.UnlockConditions,
}
parentTxn.SiacoinInputs = append(parentTxn.SiacoinInputs, sci)
spentScoids = append(spentScoids, scoid)
// Add the output to the total fund
fund = fund.Add(sco.Value)
potentialFund = potentialFund.Add(sco.Value)
if fund.Cmp(amount) >= 0 {
break
}
}
if potentialFund.Cmp(amount) >= 0 && fund.Cmp(amount) < 0 {
return modules.ErrIncompleteTransactions
}
if fund.Cmp(amount) < 0 {
return modules.ErrLowBalance
}
// Create and add the output that will be used to fund the standard
// transaction.
parentUnlockConditions, err := tb.wallet.nextPrimarySeedAddress(tb.wallet.dbTx)
if err != nil {
return err
}
exactOutput := types.SiacoinOutput{
Value: amount,
UnlockHash: parentUnlockConditions.UnlockHash(),
}
parentTxn.SiacoinOutputs = append(parentTxn.SiacoinOutputs, exactOutput)
// Create a refund output if needed.
if !amount.Equals(fund) {
refundUnlockConditions, err := tb.wallet.nextPrimarySeedAddress(tb.wallet.dbTx)
if err != nil {
return err
}
refundOutput := types.SiacoinOutput{
Value: fund.Sub(amount),
UnlockHash: refundUnlockConditions.UnlockHash(),
}
parentTxn.SiacoinOutputs = append(parentTxn.SiacoinOutputs, refundOutput)
}
// Sign all of the inputs to the parent transaction.
for _, sci := range parentTxn.SiacoinInputs {
addSignatures(&parentTxn, types.FullCoveredFields, sci.UnlockConditions, crypto.Hash(sci.ParentID), tb.wallet.keys[sci.UnlockConditions.UnlockHash()])
}
// Mark the parent output as spent. Must be done after the transaction is
// finished because otherwise the txid and output id will change.
err = dbPutSpentOutput(tb.wallet.dbTx, types.OutputID(parentTxn.SiacoinOutputID(0)), consensusHeight)
if err != nil {
return err
}
// Add the exact output.
newInput := types.SiacoinInput{
ParentID: parentTxn.SiacoinOutputID(0),
UnlockConditions: parentUnlockConditions,
}
tb.newParents = append(tb.newParents, len(tb.parents))
tb.parents = append(tb.parents, parentTxn)
tb.siacoinInputs = append(tb.siacoinInputs, len(tb.transaction.SiacoinInputs))
tb.transaction.SiacoinInputs = append(tb.transaction.SiacoinInputs, newInput)
// Mark all outputs that were spent as spent.
for _, scoid := range spentScoids {
err = dbPutSpentOutput(tb.wallet.dbTx, types.OutputID(scoid), consensusHeight)
if err != nil {
return err
}
}
return nil
}
// FundContracts will add enough inputs to cover the outputs to be
// sent in the transaction. It will try to use get address when new address failed
func (tb *transactionBuilder) FundContract(amount types.Currency) ([]types.SiacoinOutput, error) {
// dustThreshold has to be obtained separate from the lock
dustThreshold, err := tb.wallet.DustThreshold()
if err != nil {
return nil, err
}
tb.wallet.mu.Lock()
defer tb.wallet.mu.Unlock()
consensusHeight, err := dbGetConsensusHeight(tb.wallet.dbTx)
if err != nil {
return nil, err
}
so, err := tb.wallet.getSortedOutputs()
if err != nil {
return nil, err
}
var fund types.Currency
// potentialFund tracks the balance of the wallet including outputs that
// have been spent in other unconfirmed transactions recently. This is to
// provide the user with a more useful error message in the event that they
// are overspending.
var potentialFund types.Currency
var spentScoids []types.SiacoinOutputID
for i := range so.ids {
scoid := so.ids[i]
sco := so.outputs[i]
// Check that the output can be spent.
if err := tb.wallet.checkOutput(tb.wallet.dbTx, consensusHeight, scoid, sco, dustThreshold); err != nil {
if err == errSpendHeightTooHigh {
potentialFund = potentialFund.Add(sco.Value)
}
continue
}
key, ok := tb.wallet.keys[sco.UnlockHash]
if !ok {
return nil, errMissingOutputKey
}
// Add a siacoin input for this output.
sci := types.SiacoinInput{
ParentID: scoid,
UnlockConditions: key.UnlockConditions,
}
tb.siacoinInputs = append(tb.siacoinInputs, len(tb.transaction.SiacoinInputs))
tb.transaction.SiacoinInputs = append(tb.transaction.SiacoinInputs, sci)
spentScoids = append(spentScoids, scoid)
// Add the output to the total fund
fund = fund.Add(sco.Value)
potentialFund = potentialFund.Add(sco.Value)
if fund.Cmp(amount) >= 0 {
break
}
}
if potentialFund.Cmp(amount) >= 0 && fund.Cmp(amount) < 0 {
return nil, modules.ErrIncompleteTransactions
}
if fund.Cmp(amount) < 0 {
return nil, modules.ErrLowBalance
}
var refundOutput types.SiacoinOutput
// Create a refund output if needed.
if !amount.Equals(fund) {
refundUnlockConditions, err := tb.wallet.nextPrimarySeedAddress(tb.wallet.dbTx)
if err != nil {
refundUnlockConditions, err = tb.wallet.GetAddress() // try get address if generate address failed when funding contracts
if err != nil {
return nil, err
}
}
refundOutput = types.SiacoinOutput{
Value: fund.Sub(amount),
UnlockHash: refundUnlockConditions.UnlockHash(),
}
tb.transaction.SiacoinOutputs = append(tb.transaction.SiacoinOutputs, refundOutput)
}
// Mark all outputs that were spent as spent.
for _, scoid := range spentScoids {
err = dbPutSpentOutput(tb.wallet.dbTx, types.OutputID(scoid), consensusHeight)
if err != nil {
return nil, err
}
}
return []types.SiacoinOutput{refundOutput}, nil
}
// UnconfirmedParents returns the unconfirmed parents of the transaction set
// that is being constructed by the transaction builder.
func (tb *transactionBuilder) UnconfirmedParents() (parents []types.Transaction, err error) {
// Currently we don't need to call UnconfirmedParents after the transaction
// was signed so we don't allow doing that. If for some reason our
// requirements change, we can remove this check. The only downside is,
// that it might lead to transactions being returned that are not actually
// parents in case the signed transaction already has child transactions.
if tb.signed {
return nil, errBuilderAlreadySigned
}
addedParents := make(map[types.TransactionID]struct{})
for _, p := range tb.parents {
for _, sci := range p.SiacoinInputs {
tSet := tb.wallet.tpool.TransactionSet(crypto.Hash(sci.ParentID))
for _, txn := range tSet {
// Add the transaction to the parents.
txnID := txn.ID()
if _, exists := addedParents[txnID]; exists {
continue
}
addedParents[txnID] = struct{}{}
parents = append(parents, txn)
// When we found the transaction that contains the output that
// is spent by sci we stop to avoid adding child transactions.
for i := range txn.SiacoinOutputs {
if txn.SiacoinOutputID(uint64(i)) == sci.ParentID {
break
}
}
}
}
}
return
}
// AddParents adds a set of parents to the transaction.
func (tb *transactionBuilder) AddParents(newParents []types.Transaction) {
tb.parents = append(tb.parents, newParents...)
}
// AddMinerFee adds a miner fee to the transaction, returning the index of the
// miner fee within the transaction.
func (tb *transactionBuilder) AddMinerFee(fee types.Currency) uint64 {
tb.transaction.MinerFees = append(tb.transaction.MinerFees, fee)
return uint64(len(tb.transaction.MinerFees) - 1)
}
// AddSiacoinInput adds a siacoin input to the transaction, returning the index
// of the siacoin input within the transaction. When 'Sign' gets called, this
// input will be left unsigned.
func (tb *transactionBuilder) AddSiacoinInput(input types.SiacoinInput) uint64 {
tb.transaction.SiacoinInputs = append(tb.transaction.SiacoinInputs, input)
return uint64(len(tb.transaction.SiacoinInputs) - 1)
}
// AddSiacoinOutput adds a siacoin output to the transaction, returning the
// index of the siacoin output within the transaction.
func (tb *transactionBuilder) AddSiacoinOutput(output types.SiacoinOutput) uint64 {
tb.transaction.SiacoinOutputs = append(tb.transaction.SiacoinOutputs, output)
return uint64(len(tb.transaction.SiacoinOutputs) - 1)
}
// AddFileContract adds a file contract to the transaction, returning the index
// of the file contract within the transaction.
func (tb *transactionBuilder) AddFileContract(fc types.FileContract) uint64 {
tb.transaction.FileContracts = append(tb.transaction.FileContracts, fc)
return uint64(len(tb.transaction.FileContracts) - 1)
}
// AddFileContractRevision adds a file contract revision to the transaction,
// returning the index of the file contract revision within the transaction.
// When 'Sign' gets called, this revision will be left unsigned.
func (tb *transactionBuilder) AddFileContractRevision(fcr types.FileContractRevision) uint64 {
tb.transaction.FileContractRevisions = append(tb.transaction.FileContractRevisions, fcr)
return uint64(len(tb.transaction.FileContractRevisions) - 1)
}
// AddStorageProof adds a storage proof to the transaction, returning the index
// of the storage proof within the transaction.
func (tb *transactionBuilder) AddStorageProof(sp types.StorageProof) uint64 {
tb.transaction.StorageProofs = append(tb.transaction.StorageProofs, sp)
return uint64(len(tb.transaction.StorageProofs) - 1)
}
// AddArbitraryData adds arbitrary data to the transaction, returning the index
// of the data within the transaction.
func (tb *transactionBuilder) AddArbitraryData(arb []byte) uint64 {
tb.transaction.ArbitraryData = append(tb.transaction.ArbitraryData, arb)
return uint64(len(tb.transaction.ArbitraryData) - 1)
}
// AddTransactionSignature adds a transaction signature to the transaction,
// returning the index of the signature within the transaction. The signature
// should already be valid, and shouldn't sign any of the inputs that were
// added by calling 'FundSiacoins'.
func (tb *transactionBuilder) AddTransactionSignature(sig types.TransactionSignature) uint64 {
tb.transaction.TransactionSignatures = append(tb.transaction.TransactionSignatures, sig)
return uint64(len(tb.transaction.TransactionSignatures) - 1)
}
// Drop discards all of the outputs in a transaction, returning them to the
// pool so that other transactions may use them. 'Drop' should only be called
// if a transaction is both unsigned and will not be used any further.
func (tb *transactionBuilder) Drop() {
tb.wallet.mu.Lock()
defer tb.wallet.mu.Unlock()
// Iterate through all parents and the transaction itself and restore all
// outputs to the list of available outputs.
txns := append(tb.parents, tb.transaction)
for _, txn := range txns {
for _, sci := range txn.SiacoinInputs {
dbDeleteSpentOutput(tb.wallet.dbTx, types.OutputID(sci.ParentID))
}
}
tb.parents = nil
tb.signed = false
tb.transaction = types.Transaction{}
tb.newParents = nil
tb.siacoinInputs = nil
tb.transactionSignatures = nil
}
// Sign will sign any inputs added by 'FundSiacoins' and
// return a transaction set that contains all parents prepended to the
// transaction. If more fields need to be added, a new transaction builder will
// need to be created.
//
// If the whole transaction flag is set to true, then the whole transaction
// flag will be set in the covered fields object. If the whole transaction flag
// is set to false, then the covered fields object will cover all fields that
// have already been added to the transaction, but will also leave room for
// more fields to be added.
//
// Sign should not be called more than once. If, for some reason, there is an
// error while calling Sign, the builder should be dropped.
func (tb *transactionBuilder) Sign(wholeTransaction bool) ([]types.Transaction, error) {
if tb.signed {
return nil, errBuilderAlreadySigned
}
// Create the coveredfields struct.
var coveredFields types.CoveredFields
if wholeTransaction {
coveredFields = types.CoveredFields{WholeTransaction: true}
} else {
for i := range tb.transaction.MinerFees {
coveredFields.MinerFees = append(coveredFields.MinerFees, uint64(i))
}
for i := range tb.transaction.SiacoinInputs {
coveredFields.SiacoinInputs = append(coveredFields.SiacoinInputs, uint64(i))
}
for i := range tb.transaction.SiacoinOutputs {
coveredFields.SiacoinOutputs = append(coveredFields.SiacoinOutputs, uint64(i))
}
for i := range tb.transaction.FileContracts {
coveredFields.FileContracts = append(coveredFields.FileContracts, uint64(i))
}
for i := range tb.transaction.FileContractRevisions {
coveredFields.FileContractRevisions = append(coveredFields.FileContractRevisions, uint64(i))
}
for i := range tb.transaction.StorageProofs {
coveredFields.StorageProofs = append(coveredFields.StorageProofs, uint64(i))
}
for i := range tb.transaction.ArbitraryData {
coveredFields.ArbitraryData = append(coveredFields.ArbitraryData, uint64(i))
}
}
// TransactionSignatures don't get covered by the 'WholeTransaction' flag,
// and must be covered manually.
for i := range tb.transaction.TransactionSignatures {
coveredFields.TransactionSignatures = append(coveredFields.TransactionSignatures, uint64(i))
}
// For each siacoin input in the transaction that we added, provide a
// signature.
tb.wallet.mu.RLock()
defer tb.wallet.mu.RUnlock()
for _, inputIndex := range tb.siacoinInputs {
input := tb.transaction.SiacoinInputs[inputIndex]
key, ok := tb.wallet.keys[input.UnlockConditions.UnlockHash()]
if !ok {
return nil, errors.New("transaction builder added an input that it cannot sign")
}
newSigIndices := addSignatures(&tb.transaction, coveredFields, input.UnlockConditions, crypto.Hash(input.ParentID), key)
tb.transactionSignatures = append(tb.transactionSignatures, newSigIndices...)
tb.signed = true // Signed is set to true after one successful signature to indicate that future signings can cause issues.
}
// Get the transaction set and delete the transaction from the registry.
txnSet := append(tb.parents, tb.transaction)
return txnSet, nil
}
// ViewTransaction returns a transaction-in-progress along with all of its
// parents, specified by id. An error is returned if the id is invalid. Note
// that ids become invalid for a transaction after 'SignTransaction' has been
// called because the transaction gets deleted.
func (tb *transactionBuilder) View() (types.Transaction, []types.Transaction) {
return tb.transaction, tb.parents
}
// ViewAdded returns all of the space cash inputs and parent
// transactions that have been automatically added by the builder.
func (tb *transactionBuilder) ViewAdded() (newParents, siacoinInputs, transactionSignatures []int) {
return tb.newParents, tb.siacoinInputs, tb.transactionSignatures
}
// registerTransaction takes a transaction and its parents and returns a
// wallet.TransactionBuilder which can be used to expand the transaction. The
// most typical call is 'RegisterTransaction(types.Transaction{}, nil)', which
// registers a new transaction without parents.
func (w *Wallet) registerTransaction(t types.Transaction, parents []types.Transaction) *transactionBuilder {
// Create a deep copy of the transaction and parents by encoding them. A
// deep copy ensures that there are no pointer or slice related errors -
// the builder will be working directly on the transaction, and the
// transaction may be in use elsewhere (in this case, the host is using the
// transaction.
pBytes := encoding.Marshal(parents)
var pCopy []types.Transaction
err := encoding.Unmarshal(pBytes, &pCopy)
if err != nil {
panic(err)
}
tBytes := encoding.Marshal(t)
var tCopy types.Transaction
err = encoding.Unmarshal(tBytes, &tCopy)
if err != nil {
panic(err)
}
return &transactionBuilder{
parents: pCopy,
transaction: tCopy,
wallet: w,
}
}
// RegisterTransaction takes a transaction and its parents and returns a
// modules.TransactionBuilder which can be used to expand the transaction. The
// most typical call is 'RegisterTransaction(types.Transaction{}, nil)', which
// registers a new transaction without parents.
func (w *Wallet) RegisterTransaction(t types.Transaction, parents []types.Transaction) (modules.TransactionBuilder, error) {
if err := w.tg.Add(); err != nil {
return nil, err
}
defer w.tg.Done()
w.mu.Lock()
defer w.mu.Unlock()
return w.registerTransaction(t, parents), nil
}
// StartTransaction is a convenience function that calls
// RegisterTransaction(types.Transaction{}, nil).
func (w *Wallet) StartTransaction() (modules.TransactionBuilder, error) {
if err := w.tg.Add(); err != nil {
return nil, err
}
defer w.tg.Done()
return w.RegisterTransaction(types.Transaction{}, nil)
}