forked from kaspanet/kaspad
/
split_transaction.go
293 lines (255 loc) · 11.1 KB
/
split_transaction.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
package server
import (
"github.com/kaspanet/go-secp256k1"
"github.com/pkg/errors"
"github.com/Kash-Protocol/kashd/cmd/kashwallet/libkashwallet"
"github.com/Kash-Protocol/kashd/cmd/kashwallet/libkashwallet/serialization"
"github.com/Kash-Protocol/kashd/domain/consensus/model/externalapi"
"github.com/Kash-Protocol/kashd/domain/consensus/utils/consensushashing"
"github.com/Kash-Protocol/kashd/domain/consensus/utils/constants"
"github.com/Kash-Protocol/kashd/domain/consensus/utils/utxo"
"github.com/Kash-Protocol/kashd/domain/miningmanager/mempool"
"github.com/Kash-Protocol/kashd/util"
)
// maybeAutoCompoundTransaction checks if a transaction's mass is higher that what is allowed for a standard
// transaction.
// If it is - the transaction is split into multiple transactions, each with a portion of the inputs and a single output
// into a change address.
// An additional `mergeTransaction` is generated - which merges the outputs of the above splits into a single output
// paying to the original transaction's payee.
func (s *server) maybeAutoCompoundTransaction(transactionBytes []byte, toAddress util.Address,
changeAddress util.Address, changeWalletAddress *walletAddress, assetType externalapi.AssetType) ([][]byte, error) {
transaction, err := serialization.DeserializePartiallySignedTransaction(transactionBytes)
if err != nil {
return nil, err
}
splitTransactions, err := s.maybeSplitAndMergeTransaction(transaction, toAddress, changeAddress, changeWalletAddress, assetType)
if err != nil {
return nil, err
}
splitTransactionsBytes := make([][]byte, len(splitTransactions))
for i, splitTransaction := range splitTransactions {
splitTransactionsBytes[i], err = serialization.SerializePartiallySignedTransaction(splitTransaction)
if err != nil {
return nil, err
}
}
return splitTransactionsBytes, nil
}
func (s *server) mergeTransaction(
splitTransactions []*serialization.PartiallySignedTransaction,
originalTransaction *serialization.PartiallySignedTransaction,
toAddress util.Address,
changeAddress util.Address,
changeWalletAddress *walletAddress,
assetType externalapi.AssetType,
) (*serialization.PartiallySignedTransaction, error) {
numOutputs := len(originalTransaction.Tx.Outputs)
if numOutputs > 2 || numOutputs == 0 {
// This is a sanity check to make sure originalTransaction has either 1 or 2 outputs:
// 1. For the payment itself
// 2. (optional) for change
return nil, errors.Errorf("original transaction has %d outputs, while 1 or 2 are expected",
len(originalTransaction.Tx.Outputs))
}
totalValue := uint64(0)
sentValue := originalTransaction.Tx.Outputs[0].Value
utxos := make([]*libkashwallet.UTXO, len(splitTransactions))
for i, splitTransaction := range splitTransactions {
output := splitTransaction.Tx.Outputs[0]
utxos[i] = &libkashwallet.UTXO{
Outpoint: &externalapi.DomainOutpoint{
TransactionID: *consensushashing.TransactionID(splitTransaction.Tx),
Index: 0,
},
UTXOEntry: utxo.NewUTXOEntry(output.Value, assetType, output.ScriptPublicKey,
false, constants.UnacceptedDAAScore),
DerivationPath: s.walletAddressPath(changeWalletAddress),
}
totalValue += output.Value
totalValue -= feePerInput
}
if totalValue < sentValue {
// sometimes the fees from compound transactions make the total output higher than what's available from selected
// utxos, in such cases - find one more UTXO and use it.
additionalUTXOs, totalValueAdded, err := s.moreUTXOsForMergeTransaction(utxos, sentValue-totalValue)
if err != nil {
return nil, err
}
utxos = append(utxos, additionalUTXOs...)
totalValue += totalValueAdded
}
payments := []*libkashwallet.Payment{{
Address: toAddress,
AssetType: assetType,
Amount: sentValue,
}}
if totalValue > sentValue {
payments = append(payments, &libkashwallet.Payment{
Address: changeAddress,
Amount: totalValue - sentValue,
})
}
mergeTransactionBytes, err := libkashwallet.CreateUnsignedTransaction(s.keysFile.ExtendedPublicKeys,
s.keysFile.MinimumSignatures, payments, utxos, originalTransaction.Tx.Type) // Use the original transaction type
if err != nil {
return nil, err
}
return serialization.DeserializePartiallySignedTransaction(mergeTransactionBytes)
}
func (s *server) maybeSplitAndMergeTransaction(transaction *serialization.PartiallySignedTransaction, toAddress util.Address,
changeAddress util.Address, changeWalletAddress *walletAddress, assetType externalapi.AssetType) ([]*serialization.PartiallySignedTransaction, error) {
transactionMass, err := s.estimateMassAfterSignatures(transaction)
if err != nil {
return nil, err
}
if transactionMass < mempool.MaximumStandardTransactionMass {
return []*serialization.PartiallySignedTransaction{transaction}, nil
}
splitCount, inputCountPerSplit, err := s.splitAndInputPerSplitCounts(transaction, transactionMass,
changeAddress, assetType)
if err != nil {
return nil, err
}
splitTransactions := make([]*serialization.PartiallySignedTransaction, splitCount)
for i := 0; i < splitCount; i++ {
startIndex := i * inputCountPerSplit
endIndex := startIndex + inputCountPerSplit
var err error
splitTransactions[i], err = s.createSplitTransaction(transaction, changeAddress,
startIndex, endIndex, assetType, transaction.Tx.Type)
if err != nil {
return nil, err
}
}
if len(splitTransactions) > 1 {
mergeTransaction, err := s.mergeTransaction(splitTransactions, transaction, toAddress,
changeAddress, changeWalletAddress, assetType)
if err != nil {
return nil, err
}
// Recursion will be 2-3 iterations deep even in the rarest` cases, so considered safe..
splitMergeTransaction, err := s.maybeSplitAndMergeTransaction(mergeTransaction, toAddress,
changeAddress, changeWalletAddress, assetType)
if err != nil {
return nil, err
}
splitTransactions = append(splitTransactions, splitMergeTransaction...)
}
return splitTransactions, nil
}
func (s *server) splitAndInputPerSplitCounts(transaction *serialization.PartiallySignedTransaction, transactionMass uint64,
changeAddress util.Address, assetType externalapi.AssetType) (splitCount, inputsPerSplitCount int, err error) {
// Create a dummy transaction which is a clone of the original transaction, but without inputs,
// to calculate how much mass do all the inputs have
transactionWithoutInputs := transaction.Tx.Clone()
transactionWithoutInputs.Inputs = []*externalapi.DomainTransactionInput{}
massWithoutInputs := s.txMassCalculator.CalculateTransactionMass(transactionWithoutInputs)
massOfAllInputs := transactionMass - massWithoutInputs
// Since the transaction was generated by kashwallet, we assume all inputs have the same number of signatures, and
// thus - the same mass.
inputCount := len(transaction.Tx.Inputs)
massPerInput := massOfAllInputs / uint64(inputCount)
if massOfAllInputs%uint64(inputCount) > 0 {
massPerInput++
}
// Create another dummy transaction, this time one similar to the split transactions we wish to generate,
// but with 0 inputs, to calculate how much mass for inputs do we have available in the split transactions
splitTransactionWithoutInputs, err := s.createSplitTransaction(transaction, changeAddress,
0, 0, assetType, transaction.Tx.Type) // Use the original transaction type
if err != nil {
return 0, 0, err
}
massForEverythingExceptInputsInSplitTransaction :=
s.txMassCalculator.CalculateTransactionMass(splitTransactionWithoutInputs.Tx)
massForInputsInSplitTransaction := mempool.MaximumStandardTransactionMass - massForEverythingExceptInputsInSplitTransaction
inputsPerSplitCount = int(massForInputsInSplitTransaction / massPerInput)
splitCount = inputCount / inputsPerSplitCount
if inputCount%inputsPerSplitCount > 0 {
splitCount++
}
return splitCount, inputsPerSplitCount, nil
}
func (s *server) createSplitTransaction(transaction *serialization.PartiallySignedTransaction,
changeAddress util.Address, startIndex int, endIndex int, assetType externalapi.AssetType, txType externalapi.DomainTransactionType) (*serialization.PartiallySignedTransaction, error) {
selectedUTXOs := make([]*libkashwallet.UTXO, 0, endIndex-startIndex)
totalSompi := uint64(0)
for i := startIndex; i < endIndex && i < len(transaction.PartiallySignedInputs); i++ {
partiallySignedInput := transaction.PartiallySignedInputs[i]
selectedUTXOs = append(selectedUTXOs, &libkashwallet.UTXO{
Outpoint: &transaction.Tx.Inputs[i].PreviousOutpoint,
UTXOEntry: utxo.NewUTXOEntry(
partiallySignedInput.PrevOutput.Value, assetType,
partiallySignedInput.PrevOutput.ScriptPublicKey,
false, constants.UnacceptedDAAScore),
DerivationPath: partiallySignedInput.DerivationPath,
})
totalSompi += selectedUTXOs[i-startIndex].UTXOEntry.Amount()
totalSompi -= feePerInput
}
unsignedTransactionBytes, err := libkashwallet.CreateUnsignedTransaction(s.keysFile.ExtendedPublicKeys,
s.keysFile.MinimumSignatures,
[]*libkashwallet.Payment{{
Address: changeAddress,
AssetType: assetType,
Amount: totalSompi,
}}, selectedUTXOs, txType)
if err != nil {
return nil, err
}
return serialization.DeserializePartiallySignedTransaction(unsignedTransactionBytes)
}
func (s *server) estimateMassAfterSignatures(transaction *serialization.PartiallySignedTransaction) (uint64, error) {
transaction = transaction.Clone()
var signatureSize uint64
if s.keysFile.ECDSA {
signatureSize = secp256k1.SerializedECDSASignatureSize
} else {
signatureSize = secp256k1.SerializedSchnorrSignatureSize
}
for i, input := range transaction.PartiallySignedInputs {
for j, pubKeyPair := range input.PubKeySignaturePairs {
if uint32(j) >= s.keysFile.MinimumSignatures {
break
}
pubKeyPair.Signature = make([]byte, signatureSize+1) // +1 for SigHashType
}
transaction.Tx.Inputs[i].SigOpCount = byte(len(input.PubKeySignaturePairs))
}
transactionWithSignatures, err := libkashwallet.ExtractTransactionDeserialized(transaction, s.keysFile.ECDSA)
if err != nil {
return 0, err
}
return s.txMassCalculator.CalculateTransactionMass(transactionWithSignatures), nil
}
func (s *server) moreUTXOsForMergeTransaction(alreadySelectedUTXOs []*libkashwallet.UTXO, requiredAmount uint64) (
additionalUTXOs []*libkashwallet.UTXO, totalValueAdded uint64, err error) {
dagInfo, err := s.rpcClient.GetBlockDAGInfo()
if err != nil {
return nil, 0, err
}
alreadySelectedUTXOsMap := make(map[externalapi.DomainOutpoint]struct{}, len(alreadySelectedUTXOs))
for _, alreadySelectedUTXO := range alreadySelectedUTXOs {
alreadySelectedUTXOsMap[*alreadySelectedUTXO.Outpoint] = struct{}{}
}
for _, utxo := range s.utxosSortedByAmount {
if _, ok := alreadySelectedUTXOsMap[*utxo.Outpoint]; ok {
continue
}
if !isUTXOSpendable(utxo, dagInfo.VirtualDAAScore, s.params.BlockCoinbaseMaturity) {
continue
}
additionalUTXOs = append(additionalUTXOs, &libkashwallet.UTXO{
Outpoint: utxo.Outpoint,
UTXOEntry: utxo.UTXOEntry,
DerivationPath: s.walletAddressPath(utxo.address)})
totalValueAdded += utxo.UTXOEntry.Amount() - feePerInput
if totalValueAdded >= requiredAmount {
break
}
}
if totalValueAdded < requiredAmount {
return nil, 0, errors.Errorf("Insufficient funds for merge transaction")
}
return additionalUTXOs, totalValueAdded, nil
}