【问题标题】:How to update an object in a class如何更新类中的对象
【发布时间】:2021-05-15 11:08:36
【问题描述】:

我已经在 nodejs 中构建了一个简单的 BlockChain。在钱包类中,我可以减去余额,但不能添加。这是 Wallet 类:

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;
       }
    }
}

这是我发起交易的方式:

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

satoshi.publicKey.balance = 500;

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

我怎样才能将金额添加到余额中?

【问题讨论】:

    标签: javascript node.js blockchain bitcoin cryptocurrency


    【解决方案1】:

    当您拨打satoshi.sendMoney() 时,“this”将指的是 satoshi 的钱包。 这意味着,通过执行this.publicKey.balance += amount;,您正在尝试更新 satoshi 的余额,而不是 bob 的。您可以改用receiverPublicKey 来增加接收者的余额。

    下面的示例更新了两个钱包。它仍然可能是错误的,因为我删除了一些检查,但我希望它有所帮助。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-21
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 2013-02-01
      • 2020-03-12
      • 2022-01-03
      • 1970-01-01
      相关资源
      最近更新 更多