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
| export class Transaction { type: string; id: string; txIns: TxIn[]; txOuts: TxOut[];
constructor(ins: TxIn[], outs: TxOut[]) { this.txIns = ins; this.txOuts = outs; this.id = this.setId(); }
setId(): string { let txInContent: string; if (this instanceof RegularTx) { txInContent = this.txIns .map((regularTxIn: RegularTxIn) => regularTxIn.txOutId + regularTxIn.txOutIndex) .reduce((a, b) => a + b, ''); } else { txInContent = this.txIns .map((coinbaseTxIn: CoinbaseTxIn) => coinbaseTxIn.blockHeight) .reduce((a, b) => a + b, ''); }
const txOutContent: string = this.txOuts .map((txOuts: TxOut) => txOuts.address + txOuts.amount) .reduce((a, b) => a + b, '');
return SHA256(SHA256(txInContent + txOutContent)).toString(); }
public static createRegularTx( senderPubKey: string, senderPriKey: string, receiverPubKey: string, receiveAmount: number, fee: number, ) { const utxo = this.findUTXO(senderPubKey); let sumUTXO = 0; const txIns = []; const txOuts = []; let i = 0; utxo.forEach((val) => { sumUTXO += val.amount; i++; txIns.push(new RegularTxIn(val.id, i, senderPriKey)); }); const totalAmountToSpend = receiveAmount + fee; if (sumUTXO < totalAmountToSpend) { return; } for (let n = 0; n < txIns.length; n++) { const checker = Signature.verify(utxo[i].address, txIns[i].signature, txIns[i].msgHash()); if (!checker) { return; } } txOuts.push(new TxOut(receiverPubKey, receiveAmount)); const change = sumUTXO - receiveAmount - fee; if (change > 0) { txOuts.push(new TxOut(senderPubKey, change)); } const tx = new Transaction(txIns, txOuts); return tx; }
public static findUTXO(senderPubKey) { const allBlock = []; const allTxOut = []; const allTxIn = []; allBlock.forEach((block) => { const txs = block.txs; txs.forEach((tx) => { const txOuts = tx.txOuts; txOuts.forEach((out) => { if (out.address == senderPubKey) { allTxOut.push(out); } }); }); }); return []; } }
|