Changelly

Cryptocurrency

bitcoind – Why the receiver doesn’t get any bitcoin if sendtoaddress is used?

3 Mins read


I want to do a transaction (sendtoaddress), but I see that the receiver doesn’t get the amount sent.

The regtest node started

bitcoind -rpcuser=test -rpcpassword=test -regtest -rpcport=16591 -fallbackfee=0.000045

My service class to interact with bitcoind API

const httpClient = require('axios');

const bitcoindConfig = {
  url: 'http://localhost:16591',
  headers: { 'content-type': 'text-plain' },
  auth: {
    username: 'test',
    password: 'test'
  },
};

class BitcoinService {
  _bitcoindRpcCall({ reqMethod = 'POST', walletName, method, params = [] } = {}) {
    const options = {
      url: walletName ? bitcoindConfig.url + `/wallet/${walletName}` : bitcoindConfig.url,
      method: reqMethod,
      data: JSON.stringify({'jsonrpc': '1.0', 'id': 'curltext', 'method': method, 'params': params}),
      headers: bitcoindConfig.headers,
      auth: bitcoindConfig.auth
    };
    return httpClient(options);
  }

  listWallets() {
    return this._bitcoindRpcCall({ method: 'listwallets' });
  }

  createWallet({ walletName }) {
    return this._bitcoindRpcCall({ method: 'createwallet', params: [walletName] });
  }

  getNewAddress({ walletName }) {
    return this._bitcoindRpcCall({ method: 'getnewaddress', walletName });
  }

  getBalance({ walletName }) {
    return this._bitcoindRpcCall({ method: 'getbalance', walletName });
  }

  listUnspent({ walletName }) {
    return this._bitcoindRpcCall({ method: 'listunspent', walletName });
  }

  dumpPrivKey({ address, walletName }) {
    return this._bitcoindRpcCall({ method: 'dumpprivkey', params: [address], walletName });
  }

  listTransactions({ walletName }) {
    return this._bitcoindRpcCall({ method: 'listtransactions', walletName });
  }

  generateToAddress({ address, nBlocks, walletName }) {
    return this._bitcoindRpcCall({ method: 'generatetoaddress', params: [nBlocks, address], walletName });
  }

  getTransaction({ txId, walletName }) {
    return this._bitcoindRpcCall({ method: 'gettransaction', params: [txId], walletName });
  }

  getRawTransaction({ txId, walletName }) {
    return this._bitcoindRpcCall({ method: 'getrawtransaction', params: [txId], walletName });
  }

  decodeRawTransaction({ hexString }) {
    return this._bitcoindRpcCall({ method: 'decoderawtransaction', params: [hexString] });
  }

  // https://bitcoincore.org/en/doc/0.17.0/rpc/wallet/sendtoaddress/
  async sendToAddress({ walletName, amount, toAddress, comment="", commentTo = '', subtractFeeFromAmount = true } = {}) {
    return this._bitcoindRpcCall({
      method: 'sendtoaddress',
      params: [toAddress, amount, comment, commentTo, subtractFeeFromAmount],
      walletName
    });
  }

  // https://bitcoincore.org/en/doc/0.17.0/rpc/rawtransactions/createrawtransaction/
  async createRawTransaction({ walletName, amount, toAddress }) {
    const { data: { result: txs } } = await this.listUnspent({ walletName }); 
    
    const inputs = [];
    let n = amount;
    let i = 0;
    while (n > 0 && i < txs.length) {
      const tx = txs[i];
      inputs.push({
        txid: tx.txid,
        vout: tx.vout        
      });
      n -= tx.amount;
    }
    
    const outputs = [
      { [toAddress]: amount }
    ];

    return this._bitcoindRpcCall({ method: 'createrawtransaction', params: [inputs, outputs] });
  }

  // https://bitcoincore.org/en/doc/0.17.0/rpc/rawtransactions/signrawtransaction/
  signRawTransaction({ hexString }) {
    return this._bitcoindRpcCall({ method: 'signrawtransaction', params: [hexString] });
  }

  // https://bitcoincore.org/en/doc/0.17.0/rpc/rawtransactions/sendrawtransaction/
  sendRawTransaction({ hexString, allowHighFees = true } = {}) {
    return this._bitcoindRpcCall({ method: 'sendrawtransaction', params: [hexString, allowHighFees] });
  }

  async rawTransaction({ walletName, amount, toAddress }) {
    const { data: { result: txHexString } } = await this.createRawTransaction({ walletName, amount, toAddress });
    const { data: { result: { signedTx } } } = await this.signRawTransaction({ hexString: txHexString });
    return this.sendRawTransaction({ hexString: signedTx.hex });
  }
}

Two wallets created: alice and bob

const btc = new BitcoinService();

res = await btc.createWallet({ walletName: 'bob' });
console.log('create bob wallet', res.data);
// { result: { name: 'bob', warning: '' }, error: null, id: 'curltext' }
res = await btc.createWallet({ walletName: 'alice' });
console.log('create alice wallet', res.data);
// { result: { name: 'alice', warning: '' }, error: null, id: 'curltext' }

Check whether the wallets exist

res = await btc.listWallets();
console.log('listwallets', res.data);
// { result: [ 'bob', 'alice' ], error: null, id: 'curltext' }

Create addresses for the wallets

let aliceAddr;
let bobAddr;

res = await btc.getNewAddress({ walletName: 'alice' });
aliceAddr = res.data.result;
console.log('alice addr', aliceAddr);
// bcrt1qn4w4futa4j0mrt6frqn9u9zg9n5s9dvaeh2mrl

res = await btc.getNewAddress({ walletName: 'bob' });
bobAddr = res.data.result;
console.log('bob addr', bobAddr);
// bcrt1qecashk27r403nkeq09gvpfnr7dgfeet9xk97m5

Generate bitcoin for alice

for (let i = 0; i < 5; i++) {
  res = await btc.generateToAddress({ address: aliceAddr, nBlocks: 101 });
  console.log('generate bitcon for alice', res.data);
  // hashes in the output
}

Check balance

// Get balance
res = await btc.getBalance({ walletName: 'alice' });
console.log('alice balance', res.data);
// { result: 126.85546875, error: null, id: 'curltext' }

res = await btc.getBalance({ walletName: 'bob' });
console.log('bob balance', res.data);
// { result: 0, error: null, id: 'curltext' }

Send bitcoin from alice to bob

res = await btc.sendToAddress({ walletName: 'alice', toAddress: bobAddr, amount: 0.1 });
console.log('alice sends to bob', res.data);
// {
//   result: '0ae84b140e3be5d4933daa4f25e3d1cd5c02b9485ede54ad4c24a91e7d0d28f2',
//   error: null,
//   id: 'curltext'
// }

Checking the balance again

res = await btc.getBalance({ walletName: 'alice' });
console.log('alice balance', res.data);
// { result: 126.75546875, error: null, id: 'curltext' }

res = await btc.getBalance({ walletName: 'bob' });
console.log('bob balance', res.data);
// { result: 0, error: null, id: 'curltext' }

The alice balance was decreased by 0.1 as expected. Why is there no amount on the bob balance?



Source link

Related posts
Cryptocurrency

Immersion Cooling Gets Attention From Miners Wanting to Squeeze More Power Out of Equipment – Mining Bitcoin News

2 Mins read
Bitcoin mining companies are now increasingly experimenting with immersion cooling, a form of cooling that allows them to get more hashpower out…
Cryptocurrency

Singaporean crypto exchange enters India amid regulatory uncertainty

1 Mins read
Despite India’s unpredictive stance towards crypto regulations, Singaporean crypto exchange Coinstore has allocated a $20 million fund to set up three new…
Cryptocurrency

The Price of the SNAKE (SNK) Game Token Is Growing as We Approach November 30. Wait for a Dump or Buy Now?

2 Mins read
Less than two weeks are left before the start of one of the most anticipated blockchain games of 2021 — Cryptosnake. Now…

Leave a Reply

Your email address will not be published. Required fields are marked *