Guest User

Untitled

a guest
Oct 23rd, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. const ChainUtil = require('../chain-util');
  2.  
  3. class Transaction{
  4. constructor(){
  5. this.id = ChainUtil.id();
  6. this.input = null;
  7. this.outputs = [];
  8. }
  9.  
  10. /**
  11. * add extra ouputs to the transactions
  12. */
  13.  
  14. update(senderWallet,recipient,amount){
  15. const senderOutput = this.outputs.find(output => output.address === senderWallet.publicKey);
  16.  
  17. if(amount > senderWallet.amount){
  18. console.log(`Amount ${amount} exceeds balance`);
  19. return;
  20. }
  21.  
  22. senderOutput.amount = senderOutput.amount - amount;
  23. this.outputs.push({amount: amount,address: recipient});
  24. Transaction.signTransaction(this,senderWallet);
  25.  
  26. return this;
  27. }
  28.  
  29. /**
  30. * create a new transaction
  31. */
  32.  
  33. static newTransaction(senderWallet,recipient,amount){
  34. if(amount > senderWallet.balance){
  35. console.log(`Amount : ${amount} exceeds the balance`);
  36. return;
  37. }
  38.  
  39. transaction.outputs.push(...[
  40. {amount: senderWallet.balance -amount,address:
  41. senderWallet.publicKey},
  42. {amount: amount,address: recipient}
  43. ]);
  44. Transaction.signTransaction(transaction,senderWallet);
  45.  
  46. return transaction;
  47. }
  48.  
  49.  
  50. /**
  51. * create input and sign the outputs
  52. */
  53.  
  54. static signTransaction(transaction,senderWallet){
  55. transaction.input = {
  56. timestamp: Date.now(),
  57. amount: senderWallet.balance,
  58. address: senderWallet.publicKey,
  59. signature: senderWallet.sign(ChainUtil.hash(transaction.outputs))
  60. }
  61. }
  62.  
  63. /**
  64. * verify the transaction by decrypting and matching
  65. */
  66.  
  67. static verifyTransaction(transaction){
  68. return ChainUtil.verifySignature(
  69. transaction.input.address,
  70. transaction.input.signature,
  71. ChainUtil.hash(transaction.outputs)
  72. )
  73. }
  74. }
  75.  
  76. module.exports = Transaction;
Add Comment
Please, Sign In to add comment