Adding the getHash() public method to the Transaction class

This commit is contained in:
Nelson R. Perez 2018-12-06 15:55:44 -05:00
parent ef41f3c44a
commit 84515d5296
2 changed files with 31 additions and 0 deletions

View file

@ -20,6 +20,7 @@ import java.lang.reflect.Type;
import java.text.ParsePosition; import java.text.ParsePosition;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.TimeZone; import java.util.TimeZone;
@ -97,6 +98,7 @@ public class Transaction implements ByteSerializable, JsonSerializable {
public Transaction(BlockData blockData, List<BaseOperation> operationList){ public Transaction(BlockData blockData, List<BaseOperation> operationList){
this.blockData = blockData; this.blockData = blockData;
this.operations = operationList; this.operations = operationList;
this.extensions = new Extensions();
} }
/** /**
@ -267,7 +269,19 @@ public class Transaction implements ByteSerializable, JsonSerializable {
obj.addProperty(KEY_REF_BLOCK_PREFIX, blockData.getRefBlockPrefix()); obj.addProperty(KEY_REF_BLOCK_PREFIX, blockData.getRefBlockPrefix());
return obj; return obj;
}
/**
* Method that will return a hash of this transaction's data. The hash covers only the transaction
* attributes and not the signature or the chain id.
*
* @return A hash of the serialized transaction.
*/
public byte[] getHash(){
byte[] txBytes = toBytes();
byte[] toHash = Arrays.copyOfRange(txBytes, 32, txBytes.length); //Tx data only, without chain id
Sha256Hash hash = Sha256Hash.wrap(Sha256Hash.hash(toHash));
return Arrays.copyOfRange(hash.getBytes(), 0, 20); // The hash is only the first 20 bytes
} }
/** /**

View file

@ -345,4 +345,21 @@ public class TransactionTest {
// Broadcasting transaction // Broadcasting transaction
broadcastTransaction(sourcePrivateKey, operationList, listener, null); broadcastTransaction(sourcePrivateKey, operationList, listener, null);
} }
@Test
public void testTransactionHash(){
ArrayList<BaseOperation> operations = new ArrayList<>();
TransferOperation transferOperation = new TransferOperationBuilder()
.setTransferAmount(new AssetAmount(UnsignedLong.valueOf("363"), new Asset("1.3.0")))
.setFee(new AssetAmount(UnsignedLong.valueOf("10420"), new Asset("1.3.0")))
.setSource(new UserAccount("1.2.1029856"))
.setDestination(new UserAccount("1.2.390320"))
.build();
BlockData blockData = new BlockData(50885, 2948192884L, 1543548351);
operations.add(transferOperation);
Transaction transaction = new Transaction(blockData, operations);
byte[] testHash = transaction.getHash();
// Making sure the generated hash matches the one we expect from the block explorer
Assert.assertArrayEquals(Util.hexToBytes("4fec588ccdd04daaf80666a3646a48b5189df041"), testHash);
}
} }