private UTXOPool utxoPool; /** * Creates a public ledger whose current UTXOPool (collection of unspent transaction outputs) is * {@code utxoPool}. This should make a copy of utxoPool by using the UTXOPool(UTXOPool uPool) * constructor. */ publicTxHandler(UTXOPool utxoPool){ this.utxoPool = new UTXOPool(utxoPool); }
/** * @return true if: * (1) all outputs claimed by {@code tx} are in the current UTXO pool, * (2) the signatures on each input of {@code tx} are valid, * (3) no UTXO is claimed multiple times by {@code tx}, * (4) all of {@code tx}s output values are non-negative, and * (5) the sum of {@code tx}s input values is greater than or equal to the sum of its output * values; and false otherwise. */ publicbooleanisValidTx(Transaction tx){ UTXOPool utxoSet = new UTXOPool(); double pSum = 0; double sum = 0;
for (int i = 0; i < tx.numInputs(); i++) { Transaction.Input in = tx.getInput(i); UTXO u = new UTXO(in.prevTxHash, in.outputIndex); Transaction.Output out = utxoPool.getTxOutput(u);
for (Transaction.Output out : tx.getOutputs()) { if (out.value < 0) { returnfalse; } sum += out.value; }
if (pSum < sum) { returnfalse; }
returntrue; }
/** * Handles each epoch by receiving an unordered array of proposed transactions, checking each * transaction for correctness, returning a mutually valid array of accepted transactions, and * updating the current UTXO pool as appropriate. */ public Transaction[] handleTxs(Transaction[] possibleTxs) { Set<Transaction> vTxs = new HashSet<>();
for (Transaction tx : possibleTxs) { if (isValidTx(tx)) { vTxs.add(tx);
for (Transaction.Input in : tx.getInputs()) { UTXO u = new UTXO(in.prevTxHash, in.outputIndex); utxoPool.removeUTXO(u); }
for (int i = 0; i < tx.numOutputs(); i++) { Transaction.Output out = tx.getOutput(i); UTXO u = new UTXO(tx.getHash(), i); utxoPool.addUTXO(u, out); } } }
Transaction[] vTxArr = new Transaction[vTxs.size()]; return vTxs.toArray(vTxArr); }