Search code examples
javascriptnode.jsblockchainbitcoincryptocurrency

How to update an object in a class


i have build a simple BlockChain in nodejs. in the wallet class, i can subtract the balance, but it cant be added. Here is the Wallet class:

class Wallet {
    constructor(){
        const keyPair = crypto.generateKeyPairSync('rsa',{
            modulusLength: 2048,
            publicKeyEncoding: {type: 'spki', format: 'pem'},
            privateKeyEncoding: {type: 'pkcs8', format: 'pem'}
        });
        this.privateKey = keyPair.privateKey;
        this.publicKey = {key: keyPair.publicKey, balance: 0}
    }
    sendMoney(amount,receiverPublicKey,senderPrivateKey){
        const transaction = new Transaction(this.publicKey.key,receiverPublicKey,amount);

        const sign = crypto.createSign("SHA256");
        sign.update(transaction.toString()).end();

        const signature = sign.sign(this.privateKey);
        Bitcoin.addBlock(transaction,this.publicKey.key,signature);
       if(senderPrivateKey === this.privateKey && receiverPublicKey !== this.publicKey.key){
           this.publicKey.balance -= amount;
       }else if(receiverPublicKey === this.publicKey.key && senderPrivateKey !== this.privateKey){
           this.publicKey.balance += amount;
       }
    }
}

and here is how i initiate a transaction :

const satoshi = new Wallet();
const bob = new Wallet();

satoshi.publicKey.balance = 500;

satoshi.sendMoney(400,bob.publicKey.key,satoshi.privateKey);

How can i make the amount be added to the balance?


Solution

  • When you call satoshi.sendMoney(), then "this" will refer to satoshi's wallet. This means, by doing this.publicKey.balance += amount;, you are trying to update satoshi's balance, not bob's. You could use receiverPublicKey instead, to increase the receiver's balance.

    The example below updates both wallets. It could still be wrong because I removed some checks, but I hope it helps.

    sendMoney(amount, receiverPublicKey, senderPrivateKey) {
        const transaction = new Transaction(this.publicKey.key,receiverPublicKey.key,amount);
        const sign = crypto.createSign("SHA256");
        sign.update(transaction.toString()).end();
        const signature = sign.sign(this.privateKey);
        Bitcoin.addBlock(transaction,this.publicKey.key,signature);
    
        if (senderPrivateKey === this.privateKey && receiverPublicKey.key !== this.publicKey.key) {
            this.publicKey.balance -= amount;
            receiverPublicKey.balance += amount;
        }
    }
    
    console.log(satoshi.publicKey.balance) // 500
    console.log(bob.publicKey.balance)     // 0
    
    satoshi.sendMoney(400, bob.publicKey/*.key*/, satoshi.privateKey);
    
    console.log(satoshi.publicKey.balance) // 100
    console.log(bob.publicKey.balance)     // 400