-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
TransactionUtils.java
289 lines (235 loc) · 10.3 KB
/
TransactionUtils.java
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
/*
* java-tron is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* java-tron is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.tron.core;
import com.google.protobuf.ByteString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tron.crypto.ECKey;
import org.tron.protos.core.TronTXInput.TXInput;
import org.tron.protos.core.TronTXOutput.TXOutput;
import org.tron.protos.core.TronTransaction.Transaction;
import org.tron.utils.ByteArray;
import org.tron.wallet.Wallet;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.tron.crypto.Hash.sha256;
import static org.tron.utils.Utils.getRandom;
public class TransactionUtils {
private static final Logger logger = LoggerFactory.getLogger("Transaction");
private final static int RESERVE_BALANCE = 10;
public static Transaction newTransaction(Wallet wallet, String to, long amount, UTXOSet utxoSet) {
ArrayList<TXInput> txInputs = new ArrayList<>();
ArrayList<TXOutput> txOutputs = new ArrayList<>();
byte[] pubKeyHash = wallet.getEcKey().getPubKey();
SpendableOutputs spendableOutputs = utxoSet.findSpendableOutputs(pubKeyHash, amount);
if (spendableOutputs.getAmount() < amount) {
logger.error("Not enough funds");
return null;
}
Set<Map.Entry<String, long[]>> entrySet = spendableOutputs.getUnspentOutputs().entrySet();
for (Map.Entry<String, long[]> entry : entrySet) {
String txID = entry.getKey();
long[] outs = entry.getValue();
for (long out : outs) {
TXInput txInput = TXInputUtils.newTXInput(ByteArray.fromHexString(txID), out, new byte[0], pubKeyHash);
txInputs.add(txInput);
}
}
txOutputs.add(TXOutputUtils.newTXOutput(amount, to));
if (spendableOutputs.getAmount() > amount) {
txOutputs.add(TXOutputUtils.newTXOutput(spendableOutputs.getAmount() - amount, ByteArray.toHexString
(wallet.getAddress())));
}
Transaction.Builder transactionBuilder = Transaction.newBuilder();
for (int i = 0; i < txInputs.size(); i++) {
transactionBuilder.addVin(txInputs.get(i));
}
for (int i = 0; i < txOutputs.size(); i++) {
transactionBuilder.addVout(txOutputs.get(i));
}
Transaction transaction = transactionBuilder.build();
transaction = utxoSet.getBlockchain().signTransaction(transaction, wallet.getEcKey());
return transaction;
}
/**
* new coinbase transaction
*
* @param to String to sender's address
* @param data String transaction data
* @return {@link Transaction}
*/
public static Transaction newCoinbaseTransaction(String to, String data) {
if (data == null || data.equals("")) {
byte[] randBytes = new byte[20];
SecureRandom random = getRandom();
random.nextBytes(randBytes);
data = "" + ByteArray.toHexString(randBytes);
}
TXInput txi = TXInputUtils.newTXInput(new byte[]{}, -1, new byte[]{},
ByteArray.fromHexString(data));
TXOutput txo = TXOutputUtils.newTXOutput(RESERVE_BALANCE, to);
Transaction.Builder coinbaseTransaction = Transaction.newBuilder()
.addVin(txi)
.addVout(txo);
coinbaseTransaction.setId(ByteString.copyFrom(getHash
(coinbaseTransaction.build())));
return coinbaseTransaction.build();
}
/**
* Obtain a data bytes after removing the id and SHA-256(data)
*
* @param transaction {@link Transaction} transaction
* @return byte[] the hash of the transaction's data bytes which have no id
*/
public static byte[] getHash(Transaction transaction) {
Transaction.Builder tmp = transaction.toBuilder();
tmp.clearId();
return sha256(tmp.build().toByteArray());
}
/**
* get print string of the transaction
*
* @param transaction {@link Transaction} transaction
* @return String format string of the transaction
*/
public static String toPrintString(Transaction transaction) {
if (transaction == null) {
return "";
}
String str =
"\nTransaction {\n" +
"\tid=" + ByteArray.toHexString(transaction.getId()
.toByteArray()) + "\n" +
"\tvin=[\n";
int i = 0;
for (TXInput vin : transaction.getVinList()) {
str += "\t\t{\n" +
"\t\t\ttxID=" + ByteArray.toHexString(vin.getTxID()
.toByteArray()) + "\n" +
"\t\t\tvout=" + vin.getVout() + "\n" +
"\t\t\tsignature=" + ByteArray.toHexString(vin
.getSignature().toByteArray()) + "\n" +
"\t\t\tpubKey=" + ByteArray.toHexString(vin.getPubKey()
.toByteArray()) + "\n" +
"\t\t}";
if (i != transaction.getVinList().size() - 1) {
str += ",";
}
i++;
str += "\n";
}
str += "\t],\n\tvout=[\n";
i = 0;
for (TXOutput vout : transaction.getVoutList()) {
str += "\t\t{\n" +
"\t\t\tvalue=" + vout.getValue() + "\n" +
"\t\t\tpubKeyHash=" + ByteArray.toHexString(vout
.getPubKeyHash().toByteArray()) + "\n" +
"\t\t}";
if (i != transaction.getVoutList().size() - 1) {
str += ",";
}
i++;
str += "\n";
}
str += "\t]\n}";
return str;
}
/**
* Determine whether the transaction is a coinbase transaction
*
* @param transaction {@link Transaction} transaction
* @return boolean true for coinbase, false for not coinbase
*/
public static boolean isCoinbaseTransaction(Transaction transaction) {
return transaction.getVinList().size() == 1 && transaction.getVin(0)
.getTxID().size() == 0 && transaction.getVin(0).getVout() == -1;
}
public static Transaction sign(Transaction transaction, ECKey myKey,
HashMap<String, Transaction> prevTXs) {
if (TransactionUtils.isCoinbaseTransaction(transaction)) {
return null;
}
for (TXInput vin : transaction.getVinList()) {
if (prevTXs.get(ByteArray.toHexString(vin.getTxID().toByteArray()
)).getId().toByteArray().length == 0) {
logger.error("ERROR: Previous transaction is not correct");
return null;
}
}
for (int i = 0; i < transaction.getVinList().size(); i++) {
TXInput vin = transaction.getVin(i);
Transaction prevTx = prevTXs.get(ByteArray.toHexString(vin
.getTxID().toByteArray()));
Transaction.Builder transactionCopyBuilder = transaction
.toBuilder();
TXInput.Builder vinBuilder = vin.toBuilder();
vinBuilder.clearSignature();
vinBuilder.setPubKey(prevTx.getVout((int) vin.getVout()).getPubKeyHash());
transactionCopyBuilder.setVin(i, vinBuilder.build());
transactionCopyBuilder.setId(ByteString.copyFrom(TransactionUtils
.getHash(transactionCopyBuilder.build())));
vinBuilder.clearPubKey();
transactionCopyBuilder.setVin(i, vinBuilder.build());
Transaction.Builder transactionBuilder = transaction.toBuilder().setVin(i, vin.toBuilder()
.setSignature(ByteString.copyFrom(myKey.sign
(transactionCopyBuilder.getId().toByteArray())
.toByteArray())).build());
transactionBuilder.setId(ByteString.copyFrom(TransactionUtils.getHash(transactionBuilder.build())));
transaction = transactionBuilder.build();
}
return transaction;
}
public static boolean verify(ECKey myKey, Transaction transaction,
HashMap<String, Transaction> prevTXs) {
if (TransactionUtils.isCoinbaseTransaction(transaction)) {
return true;
}
for (TXInput vin : transaction.getVinList()) {
if (prevTXs.get(ByteArray.toHexString(vin.getTxID().toByteArray()
)).getId().toByteArray().length == 0) {
logger.error("ERROR: Previous transaction is not correct");
}
}
for (int i = 0; i < transaction.getVinList().size(); i++) {
TXInput vin = transaction.getVin(i);
Transaction prevTx = prevTXs.get(ByteArray.toHexString(vin
.getTxID().toByteArray()));
Transaction.Builder transactionCopyBuilder = transaction
.toBuilder();
TXInput.Builder vinBuilder = vin.toBuilder();
vinBuilder.clearSignature();
vinBuilder.setPubKey(prevTx.getVout((int) vin.getVout()).getPubKeyHash());
transactionCopyBuilder.setVin(i, vinBuilder.build());
transactionCopyBuilder.setId(ByteString.copyFrom(TransactionUtils
.getHash(transactionCopyBuilder.build())));
vinBuilder.clearPubKey();
transactionCopyBuilder.setVin(i, vinBuilder.build());
if (!myKey.verify(transactionCopyBuilder.getId().toByteArray(),
vin.getSignature().toByteArray())) {
return false;
}
}
return true;
}
// get sender
public static byte[] getSender(Transaction tx) {
byte[] pubKey = tx.getVin(0).getPubKey().toByteArray();
return ECKey.computeAddress(pubKey);
}
}