Wallet

如何製作持久的 SPV 錢包?(比特幣)

  • August 19, 2018

我在 SPV 節點上創建了一個錢包。錢包是從助記詞初始化的。收到一些交易後,錢包的餘額如下所示:

{ account: -1, tx: 3, coin: 3, unconfirmed: 136300, confirmed: 0 }

但是當我重新初始化錢包時,它看起來是這樣的:

{ account: -1, tx: 0, coin: 0, unconfirmed: 0, confirmed: 0 }

在每次初始化時,錢包都有相同的地址。

這是我的程式碼:

const bcoin = require('bcoin');
bcoin.set('testnet');
const KeyRing = bcoin.keyring;
const Mnemonic = bcoin.hd.Mnemonic;
const HD = bcoin.hd;

const node = new bcoin.node.SPVNode({
   config: true,
   argv: true,
   env: true,
   logFile: true,
   logConsole: true,
   logLevel: 'debug',
   db: 'leveldb',
   memory: false,
   persistent: true,
   workers: true,
   listen: true,
   loader: require,
   network: 'testnet'
});

// Temporary hack
if (!node.has('walletdb')) {
   const plugin = require('./node_modules/bcoin/lib/wallet/plugin');
   node.use(plugin);
}

process.on('unhandledRejection', (err, promise) => {
 throw err;
});

const walletdb = new bcoin.wallet.WalletDB({ memory: false, network: 'testnet', prefix: '/Users/alestsurko/.bcoin/spvchain' });

(async () => {
   await node.ensure();
   await node.open();
   await node.connect();
   await walletdb.open();
   const mnemonic = new Mnemonic('uncover cash coral neglect upon nurse argue deal right song hood tennis');
   const masterKey = HD.fromMnemonic(mnemonic);

   const wallet = await walletdb.create({master: masterKey});

   console.log('Created wallet with address %s', await wallet.receiveAddress());
   const bl = await wallet.getBalance();
   console.log(bl.toJSON());

   // Add our address to the spv filter.
   node.pool.watchAddress(await wallet.receiveAddress());

   node.startSync();

   node.on('error', async (err) => {
       console.log(err);
   });

   node.pool.on('tx', async (tx) => {
       console.log('------ New tx. Adding to walletdb...');
       console.log(tx);
       await walletdb.addTX(tx);
   });

   wallet.on('balance', async (balance) => {
       console.log('Balance updated.');
       console.log(balance.toJSON());
   });
})().catch((err) => {
   console.error(err.stack);
   process.exit(1);
});

正如這裡所評論的,問題的原因是我

sorta 創建了兩個錢包。第一個由頂部的外掛語句實例化,然後您還可以立即創建一個新的 walletDB。

所以解決方案是使用WalletClient

const {WalletClient} = require('bclient');
const {Network} = require('bcoin');
const network = Network.get('regtest');

const walletOptions = {
 network: network.type,
 port: network.walletPort,
 apiKey: 'api-key'
}

const walletClient = new WalletClient(walletOptions);
const id = 'primary'; // or whatever your wallet name is
const wallet = walletClient.wallet(id);

而不是walletdb.create().

引用自:https://bitcoin.stackexchange.com/questions/78272