| 5 | const debug = require('debug')('savjeecoin:blockchain'); |
| 6 | |
| 7 | class Transaction { |
| 8 | /** |
| 9 | * @param {string} fromAddress |
| 10 | * @param {string} toAddress |
| 11 | * @param {number} amount |
| 12 | */ |
| 13 | constructor(fromAddress, toAddress, amount) { |
| 14 | this.fromAddress = fromAddress; |
| 15 | this.toAddress = toAddress; |
| 16 | this.amount = amount; |
| 17 | this.timestamp = Date.now(); |
| 18 | } |
| 19 | |
| 20 | /** |
| 21 | * Creates a SHA256 hash of the transaction |
| 22 | * |
| 23 | * @returns {string} |
| 24 | */ |
| 25 | calculateHash() { |
| 26 | return crypto |
| 27 | .createHash('sha256') |
| 28 | .update(this.fromAddress + this.toAddress + this.amount + this.timestamp) |
| 29 | .digest('hex'); |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Signs a transaction with the given signingKey (which is an Elliptic keypair |
| 34 | * object that contains a private key). The signature is then stored inside the |
| 35 | * transaction object and later stored on the blockchain. |
| 36 | * |
| 37 | * @param {string} signingKey |
| 38 | */ |
| 39 | sign(signingKey) { |
| 40 | // You can only send a transaction from the wallet that is linked to your |
| 41 | // key. So here we check if the fromAddress matches your publicKey |
| 42 | if (signingKey.getPublic('hex') !== this.fromAddress) { |
| 43 | throw new Error('You cannot sign transactions for other wallets!'); |
| 44 | } |
| 45 | |
| 46 | // Calculate the hash of this transaction, sign it with the key |
| 47 | // and store it inside the transaction object |
| 48 | const hashTx = this.calculateHash(); |
| 49 | const sig = signingKey.sign(hashTx, 'base64'); |
| 50 | |
| 51 | this.signature = sig.toDER('hex'); |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Checks if the signature is valid (transaction has not been tampered with). |
| 56 | * It uses the fromAddress as the public key. |
| 57 | * |
| 58 | * @returns {boolean} |
| 59 | */ |
| 60 | isValid() { |
| 61 | // If the transaction doesn't have a from address we assume it's a |
| 62 | // mining reward and that it's valid. You could verify this in a |
| 63 | // different way (special field for instance) |
| 64 | if (this.fromAddress === null) return true; |
nothing calls this directly
no outgoing calls
no test coverage detected