0% found this document useful (0 votes)
2 views

Assignment

Uploaded by

yashvirbudhwar5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Assignment

Uploaded by

yashvirbudhwar5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Assignment by YASHVIR BUDHWAR

Step-by-Step Implementation
1. TxHandler Class

implementation for TxHandler:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TxHandler {


private UTXOPool utxoPool;

public TxHandler(UTXOPool utxoPool) {


// Create a defensive copy of utxoPool
this.utxoPool = new UTXOPool(utxoPool);
}

public boolean isValidTx(Transaction tx) {


double inputSum = 0;
double outputSum = 0;
Set<UTXO> seenUTXOs = new HashSet<>();

// Check each input


for (int i = 0; i < tx.numInputs(); i++) {
Transaction.Input input = tx.getInput(i);
UTXO utxo = new UTXO(input.prevTxHash, input.outputIndex);

// (1) Check if the UTXO is in the pool


if (!utxoPool.contains(utxo)) {
return false;
}

// (2) Check if the signature is valid


Transaction.Output output = utxoPool.getTxOutput(utxo);
if (!Crypto.verifySignature(output.address, tx.getRawDataToSign(i), input.signature)) {
return false;
}

// (3) Check for double spending


if (seenUTXOs.contains(utxo)) {
return false;
}
seenUTXOs.add(utxo);

// Add to input sum


inputSum += output.value;
}

// Check each output


for (Transaction.Output output : tx.getOutputs()) {
// (4) Check that the output values are non-negative
if (output.value < 0) {
return false;
}
outputSum += output.value;
}

// (5) Check that the sum of input values is at least equal to the sum of output values
if (inputSum < outputSum) {
return false;
}

return true;
}

public Transaction[] handleTxs(Transaction[] possibleTxs) {


List<Transaction> validTxs = new ArrayList<>();

for (Transaction tx : possibleTxs) {


if (isValidTx(tx)) {
validTxs.add(tx);

// Update the UTXOPool


for (Transaction.Input input : tx.getInputs()) {
UTXO utxo = new UTXO(input.prevTxHash, input.outputIndex);
utxoPool.removeUTXO(utxo);
}

byte[] txHash = tx.getHash();


for (int i = 0; i < tx.numOutputs(); i++) {
UTXO utxo = new UTXO(txHash, i);
utxoPool.addUTXO(utxo, tx.getOutput(i));
}
}
}

return validTxs.toArray(new Transaction[validTxs.size()]);


}
}

Explanation

TxHandler Constructor: Creates a new instance and copies the provided UTXOPool.
isValidTx(): Checks if a transaction is valid by verifying UTXO presence, signatures, and
ensuring no double-spending and valid value sums.
handleTxs(): Processes transactions to select valid ones and updates the UTXOPool.

Dated: 9 July 2024.

You might also like