-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
TransactionOutput.java
362 lines (322 loc) · 15.8 KB
/
TransactionOutput.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
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
/**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.core;
import com.google.bitcoin.script.Script;
import com.google.bitcoin.script.ScriptBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.math.BigInteger;
import java.util.Arrays;
import static com.google.common.base.Preconditions.*;
/**
* A TransactionOutput message contains a scriptPubKey that controls who is able to spend its value. It is a sub-part
* of the Transaction message.
*/
public class TransactionOutput extends ChildMessage implements Serializable {
private static final Logger log = LoggerFactory.getLogger(TransactionOutput.class);
private static final long serialVersionUID = -590332479859256824L;
// A transaction output has some value and a script used for authenticating that the redeemer is allowed to spend
// this output.
private BigInteger value;
private byte[] scriptBytes;
// The script bytes are parsed and turned into a Script on demand.
private transient WeakReference<Script> scriptPubKey;
// These fields are Java serialized but not Bitcoin serialized. They are used for tracking purposes in our wallet
// only. If set to true, this output is counted towards our balance. If false and spentBy is null the tx output
// was owned by us and was sent to somebody else. If false and spentBy is set it means this output was owned by
// us and used in one of our own transactions (eg, because it is a change output).
private boolean availableForSpending;
@Nullable private TransactionInput spentBy;
// A reference to the transaction which holds this output, if any.
@Nullable Transaction parentTransaction;
private transient int scriptLen;
/**
* Deserializes a transaction output message. This is usually part of a transaction message.
*/
public TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload,
int offset) throws ProtocolException {
super(params, payload, offset);
parentTransaction = parent;
availableForSpending = true;
}
/**
* Deserializes a transaction output message. This is usually part of a transaction message.
*
* @param params NetworkParameters object.
* @param msg Bitcoin protocol formatted byte array containing message content.
* @param offset The location of the first msg byte within the array.
* @param parseLazy Whether to perform a full parse immediately or delay until a read is requested.
* @param parseRetain Whether to retain the backing byte array for quick reserialization.
* If true and the backing byte array is invalidated due to modification of a field then
* the cached bytes may be repopulated and retained if the message is serialized again in the future.
* @throws ProtocolException
*/
public TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] msg, int offset,
boolean parseLazy, boolean parseRetain) throws ProtocolException {
super(params, msg, offset, parent, parseLazy, parseRetain, UNKNOWN_LENGTH);
parentTransaction = parent;
availableForSpending = true;
}
/**
* Creates an output that sends 'value' to the given address (public key hash). The amount should be created with
* something like {@link Utils#toNanoCoins(int, int)}. Typically you would use
* {@link Transaction#addOutput(java.math.BigInteger, Address)} instead of creating a TransactionOutput directly.
*/
public TransactionOutput(NetworkParameters params, @Nullable Transaction parent, BigInteger value, Address to) {
this(params, parent, value, ScriptBuilder.createOutputScript(to).getProgram());
}
/**
* Creates an output that sends 'value' to the given public key using a simple CHECKSIG script (no addresses). The
* amount should be created with something like {@link Utils#toNanoCoins(int, int)}. Typically you would use
* {@link Transaction#addOutput(java.math.BigInteger, ECKey)} instead of creating an output directly.
*/
public TransactionOutput(NetworkParameters params, @Nullable Transaction parent, BigInteger value, ECKey to) {
this(params, parent, value, ScriptBuilder.createOutputScript(to).getProgram());
}
public TransactionOutput(NetworkParameters params, @Nullable Transaction parent, BigInteger value, byte[] scriptBytes) {
super(params);
// Negative values obviously make no sense, except for -1 which is used as a sentinel value when calculating
// SIGHASH_SINGLE signatures, so unfortunately we have to allow that here.
checkArgument(value.signum() >= 0 || value.equals(Utils.NEGATIVE_ONE), "Negative values not allowed");
checkArgument(value.compareTo(NetworkParameters.MAX_MONEY) < 0, "Values larger than MAX_MONEY not allowed");
this.value = value;
this.scriptBytes = scriptBytes;
parentTransaction = parent;
availableForSpending = true;
length = 8 + VarInt.sizeOf(scriptBytes.length) + scriptBytes.length;
}
public Script getScriptPubKey() throws ScriptException {
// Quick hack to try and reduce memory consumption on Androids. SoftReference is the same as WeakReference
// on Dalvik (by design), so this arrangement just means that we can avoid the cost of re-parsing the script
// bytes if getScriptPubKey is called multiple times in quick succession in between garbage collections.
Script script = scriptPubKey == null ? null : scriptPubKey.get();
if (script == null) {
maybeParse();
script = new Script(scriptBytes);
scriptPubKey = new WeakReference<Script>(script);
return script;
}
return script;
}
protected void parseLite() throws ProtocolException {
// TODO: There is no reason to use BigInteger for values, they are always smaller than 21 million * COIN
// The only reason to use BigInteger would be to properly read values from the reference implementation, however
// the reference implementation uses signed 64-bit integers for its values as well (though it probably shouldn't)
long outputValue = readInt64();
value = BigInteger.valueOf(outputValue);
scriptLen = (int) readVarInt();
length = cursor - offset + scriptLen;
}
void parse() throws ProtocolException {
scriptBytes = readBytes(scriptLen);
}
@Override
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
checkNotNull(scriptBytes);
Utils.int64ToByteStreamLE(getValue().longValue(), stream);
// TODO: Move script serialization into the Script class, where it belongs.
stream.write(new VarInt(scriptBytes.length).encode());
stream.write(scriptBytes);
}
/**
* Returns the value of this output in nanocoins. This is the amount of currency that the destination address
* receives.
*/
public BigInteger getValue() {
maybeParse();
return value;
}
/**
* Sets the value of this output in nanocoins.
*/
public void setValue(BigInteger value) {
checkNotNull(value);
unCache();
this.value = value;
}
int getIndex() {
checkNotNull(parentTransaction);
for (int i = 0; i < parentTransaction.getOutputs().size(); i++) {
if (parentTransaction.getOutputs().get(i) == this)
return i;
}
// Should never happen.
throw new RuntimeException("Output linked to wrong parent transaction?");
}
/**
* <p>Gets the minimum value for a txout of this size to be considered non-dust by a reference client
* (and thus relayed). See: CTxOut::IsDust() in the reference client. The assumption is that any output that would
* consume more than a third of its value in fees is not something the Bitcoin system wants to deal with right now,
* so we call them "dust outputs" and they're made non standard. The choice of one third is somewhat arbitrary and
* may change in future.</p>
*
* <p>You probably should use {@link com.google.bitcoin.core.TransactionOutput#getMinNonDustValue()} which uses
* a safe fee-per-kb by default.</p>
*
* @param feePerKbRequired The fee required per kilobyte. Note that this is the same as the reference client's -minrelaytxfee * 3
* If you want a safe default, use {@link Transaction#REFERENCE_DEFAULT_MIN_TX_FEE}*3
*/
public BigInteger getMinNonDustValue(BigInteger feePerKbRequired) {
// A typical output is 33 bytes (pubkey hash + opcodes) and requires an input of 148 bytes to spend so we add
// that together to find out the total amount of data used to transfer this amount of value. Note that this
// formula is wrong for anything that's not a pay-to-address output, unfortunately, we must follow the reference
// clients wrongness in order to ensure we're considered standard. A better formula would either estimate the
// size of data needed to satisfy all different script types, or just hard code 33 below.
final BigInteger size = BigInteger.valueOf(this.bitcoinSerialize().length + 148);
BigInteger[] nonDustAndRemainder = feePerKbRequired.multiply(size).divideAndRemainder(BigInteger.valueOf(1000));
return nonDustAndRemainder[1].equals(BigInteger.ZERO) ? nonDustAndRemainder[0] : nonDustAndRemainder[0].add(BigInteger.ONE);
}
/**
* Returns the minimum value for this output to be considered "not dust", i.e. the transaction will be relayable
* and mined by default miners. For normal pay to address outputs, this is 5460 satoshis, the same as
* {@link Transaction#MIN_NONDUST_OUTPUT}.
*/
public BigInteger getMinNonDustValue() {
return getMinNonDustValue(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.multiply(BigInteger.valueOf(3)));
}
/**
* Sets this objects availableForSpending flag to false and the spentBy pointer to the given input.
* If the input is null, it means this output was signed over to somebody else rather than one of our own keys.
* @throws IllegalStateException if the transaction was already marked as spent.
*/
public void markAsSpent(TransactionInput input) {
checkState(availableForSpending);
availableForSpending = false;
spentBy = input;
}
/**
* Resets the spent pointer / availableForSpending flag to null.
*/
public void markAsUnspent() {
availableForSpending = true;
spentBy = null;
}
/**
* Returns whether {@link TransactionOutput#markAsSpent(TransactionInput)} has been called on this class. A
* {@link Wallet} will mark a transaction output as spent once it sees a transaction input that is connected to it.
* Note that this flag can be false when an output has in fact been spent according to the rest of the network if
* the spending transaction wasn't downloaded yet, and it can be marked as spent when in reality the rest of the
* network believes it to be unspent if the signature or script connecting to it was not actually valid.
*/
public boolean isAvailableForSpending() {
return availableForSpending;
}
/**
* The backing script bytes which can be turned into a Script object.
* @return the scriptBytes
*/
public byte[] getScriptBytes() {
maybeParse();
return scriptBytes;
}
/**
* Returns true if this output is to a key in the wallet or to an address/script we are watching.
*/
public boolean isMineOrWatched(Wallet wallet) {
return isMine(wallet) || isWatched(wallet);
}
/**
* Returns true if this output is to a key, or an address we have the keys for, in the wallet.
*/
public boolean isWatched(Wallet wallet) {
try {
Script script = getScriptPubKey();
return wallet.isWatchedScript(script);
} catch (ScriptException e) {
// Just means we didn't understand the output of this transaction: ignore it.
log.debug("Could not parse tx output script: {}", e.toString());
return false;
}
}
/**
* Returns true if this output is to a key, or an address we have the keys for, in the wallet.
*/
public boolean isMine(Wallet wallet) {
try {
Script script = getScriptPubKey();
if (script.isSentToRawPubKey()) {
byte[] pubkey = script.getPubKey();
return wallet.isPubKeyMine(pubkey);
} else {
byte[] pubkeyHash = script.getPubKeyHash();
return wallet.isPubKeyHashMine(pubkeyHash);
}
} catch (ScriptException e) {
// Just means we didn't understand the output of this transaction: ignore it.
log.debug("Could not parse tx output script: {}", e.toString());
return false;
}
}
/**
* Returns a human readable debug string.
*/
public String toString() {
try {
return "TxOut of " + Utils.bitcoinValueToFriendlyString(value) + " to " +
getScriptPubKey().getToAddress(params).toString() + " script:" + getScriptPubKey().toString();
} catch (ScriptException e) {
throw new RuntimeException(e);
}
}
/**
* Returns the connected input.
*/
@Nullable
public TransactionInput getSpentBy() {
return spentBy;
}
/**
* Returns the transaction that owns this output, or throws NullPointerException if unowned.
*/
public Transaction getParentTransaction() {
return checkNotNull(parentTransaction, "Free-standing TransactionOutput");
}
/**
* Ensure object is fully parsed before invoking java serialization. The backing byte array
* is transient so if the object has parseLazy = true and hasn't invoked checkParse yet
* then data will be lost during serialization.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
maybeParse();
out.defaultWriteObject();
}
/** Returns a copy of the output detached from its containing transaction, if need be. */
public TransactionOutput duplicateDetached() {
return new TransactionOutput(params, null, value, org.spongycastle.util.Arrays.clone(scriptBytes));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TransactionOutput output = (TransactionOutput) o;
if (!Arrays.equals(scriptBytes, output.scriptBytes)) return false;
if (value != null ? !value.equals(output.value) : output.value != null) return false;
if (parentTransaction != null && parentTransaction != output.parentTransaction) return false;
return true;
}
@Override
public int hashCode() {
int result = value != null ? value.hashCode() : 0;
result = 31 * result + (scriptBytes != null ? Arrays.hashCode(scriptBytes) : 0);
return result;
}
}