Merge pull request #269 from nodar-chkuaselidze/docs/examples

Docs/examples
This commit is contained in:
Christopher Jeffrey (JJ) 2017-08-17 17:24:16 -07:00 committed by GitHub
commit b7789c763c
18 changed files with 403 additions and 285 deletions

View File

@ -1,86 +0,0 @@
``` js
var bcoin = require('bcoin').set('main');
// Create a blockchain and store it in leveldb.
// `db` also accepts `rocksdb` and `lmdb`.
var prefix = process.env.HOME + '/my-bcoin-environment';
var chain = new bcoin.chain({ db: 'leveldb', location: prefix + '/chain' });
var mempool = new bcoin.mempool({ chain: chain });
// Create a network pool of peers with a limit of 8 peers.
var pool = new bcoin.pool({ chain: chain, mempool: mempool, maxPeers: 8 });
// Open the pool (implicitly opens mempool and chain).
(async function() {
await pool.open();
// Connect, start retrieving and relaying txs
await pool.connect();
// Start the blockchain sync.
pool.startSync();
// Watch the action
chain.on('block', function(block) {
console.log('Connected block to blockchain:');
console.log(block);
});
mempool.on('tx', function(tx) {
console.log('Added tx to mempool:');
console.log(tx);
});
pool.on('tx', function(tx) {
console.log('Saw transaction:');
console.log(tx.rhash);
});
})();
// Start up a segnet4 sync in-memory
// while we're at it (because we can).
var tchain = new bcoin.chain({
network: 'segnet4',
db: 'memory'
});
var tmempool = new bcoin.mempool({
network: 'segnet4',
chain: tchain
});
var tpool = new bcoin.pool({
network: 'segnet4',
chain: tchain,
mempool: tmempool,
size: 8
});
(async function() {
await pool.open();
// Connect, start retrieving and relaying txs
await tpool.connect();
// Start the blockchain sync.
tpool.startSync();
tchain.on('block', function(block) {
console.log('Added segnet4 block:');
console.log(block);
});
tmempool.on('tx', function(tx) {
console.log('Added segnet4 tx to mempool:');
console.log(tx);
});
tpool.on('tx', function(tx) {
console.log('Saw segnet4 transaction:');
console.log(tx);
});
})();
```

View File

@ -1,35 +0,0 @@
``` js
var bcoin = require('bcoin');
bcoin.set({
// Default network (so we can avoid passing
// the `network` option into every object below.
network: 'regtest',
// Enable the global worker pool
// for mining and transaction verification.
useWorkers: true
});
// Start up a blockchain, mempool, and miner using in-memory
// databases (stored in a red-black tree instead of on-disk).
var chain = new bcoin.chain({ db: 'memory' });
var mempool = new bcoin.mempool({ chain: chain });
var miner = new bcoin.miner({ chain: chain, mempool: mempool });
// Open the miner (initialize the databases, etc).
// Miner will implicitly call `open` on chain and mempool.
miner.open().then(function() {
// Create a Cpu miner job
return miner.createJob();
}).then(function(job) {
// Mine the block on the worker pool (use mine() for the master process)
return job.mineAsync();
}).then(function(block) {
// Add the block to the chain
console.log('Adding %s to the blockchain.', block.rhash);
console.log(block);
return chain.add(block);
}).then(function() {
console.log('Added block!');
});
```

View File

@ -1,72 +0,0 @@
``` js
var bcoin = require('bcoin').set('main');
var node = bcoin.fullnode({
checkpoints: true,
// Primary wallet passphrase
passsphrase: 'node',
logLevel: 'info'
});
// We get a lot of errors sometimes,
// usually from peers hanging up on us.
// Just ignore them for now.
node.on('error', function(err) {
;
});
// Start the node
node.open().then(function() {
// Create a new wallet (or get an existing one with the same ID)
var options = {
id: 'mywallet',
passphrase: 'foo',
witness: false,
type: 'pubkeyhash'
};
return node.walletdb.create(options);
}).then(function(wallet) {
console.log('Created wallet with address: %s', wallet.getAddress('base58'));
node.connect().then(function() {
// Start syncing the blockchain
node.startSync();
});
// Wait for balance and send it to a new address.
wallet.once('balance', function(balance) {
// Create a transaction, fill
// it with coins, and sign it.
var options = {
subtractFee: true,
outputs: [{
address: newReceiving,
value: balance.total
}]
};
wallet.createTX(options).then(function(tx) {
// Need to pass our passphrase back in to sign!
return wallet.sign(tx, 'foo');
}).then(function(tx) {
console.log('sending tx:');
console.log(tx);
return node.sendTX(tx);
}).then(function() {
console.log('tx sent!');
});
});
});
node.chain.on('block', function(block) {
;
});
node.mempool.on('tx', function(tx) {
;
});
node.chain.on('full', function() {
node.mempool.getHistory().then(console.log);
});
```

View File

@ -1,44 +0,0 @@
``` js
var bcoin = require('bcoin').set('testnet');
// SPV chains only store the chain headers.
var chain = new bcoin.chain({
db: 'leveldb',
location: process.env.HOME + '/spvchain',
spv: true
});
var pool = new bcoin.pool({
chain: chain,
spv: true,
maxPeers: 8
});
var walletdb = new bcoin.walletdb({ db: 'memory' });
pool.open().then(function() {
return walletdb.open();
}).then(function() {
return walletdb.create();
}).then(function(wallet) {
console.log('Created wallet with address %s', wallet.getAddress('base58'));
// Add our address to the spv filter.
pool.watchAddress(wallet.getAddress());
// Connect, start retrieving and relaying txs
pool.connect().then(function() {
// Start the blockchain sync.
pool.startSync();
pool.on('tx', function(tx) {
walletdb.addTX(tx);
});
wallet.on('balance', function(balance) {
console.log('Balance updated.');
console.log(bcoin.amount.btc(balance.unconfirmed));
});
});
});
```

View File

@ -1,12 +1,13 @@
'use strict';
const encoding = require('bcoin/lib/utils/encoding');
const co = require('bcoin/lib/utils/co');
const Outpoint = require('bcoin/lib/primitives/outpoint');
const MTX = require('bcoin/lib/primitives/mtx');
const HTTP = require('bcoin/lib/http');
const FullNode = require('bcoin/lib/node/fullnode');
const plugin = require('bcoin/lib/wallet/plugin');
const bcoin = require('../..');
const encoding = bcoin.encoding;
const co = bcoin.co;
const Outpoint = bcoin.outpoint;
const MTX = bcoin.mtx;
const HTTP = bcoin.http;
const FullNode = bcoin.fullnode;
const plugin = bcoin.wallet.plugin;
const node = new FullNode({
network: 'regtest',
@ -113,4 +114,7 @@ async function callNodeApi() {
console.log(tx);
await callNodeApi();
})();
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -1,10 +1,11 @@
'use strict';
// Usage: $ node ./examples/peer.js [ip]:[port]
// Usage: $ node ./docs/Examples/connect-to-peer.js [ip]:[port]
const Peer = require('bcoin/lib/net/peer');
const NetAddress = require('bcoin/lib/primitives/netaddress');
const Network = require('bcoin/lib/protocol/network');
const bcoin = require('../..');
const Peer = bcoin.peer;
const NetAddress = bcoin.netaddress;
const Network = bcoin.network;
const network = Network.get('testnet');
const peer = Peer.fromOptions({
@ -17,6 +18,8 @@ const peer = Peer.fromOptions({
const addr = NetAddress.fromHostname(process.argv[2], 'testnet');
console.log(`Connecting to ${addr.hostname}`);
peer.connect(addr);
peer.tryOpen();

View File

@ -0,0 +1,98 @@
'use strict';
const bcoin = require('../..').set('main');
const Chain = bcoin.chain;
const Mempool = bcoin.mempool;
const Pool = bcoin.pool;
// Create a blockchain and store it in leveldb.
// `db` also accepts `rocksdb` and `lmdb`.
const prefix = process.env.HOME + '/my-bcoin-environment';
const chain = new Chain({
db: 'leveldb',
location: prefix + '/chain',
network: 'main'
});
const mempool = new Mempool({ chain: chain });
// Create a network pool of peers with a limit of 8 peers.
const pool = new Pool({
chain: chain,
mempool: mempool,
maxPeers: 8
});
// Open the pool (implicitly opens mempool and chain).
(async function() {
await pool.open();
// Connect, start retrieving and relaying txs
await pool.connect();
// Start the blockchain sync.
pool.startSync();
// Watch the action
chain.on('block', (block) => {
console.log('Connected block to blockchain:');
console.log(block);
});
mempool.on('tx', (tx) => {
console.log('Added tx to mempool:');
console.log(tx);
});
pool.on('tx', (tx) => {
console.log('Saw transaction:');
console.log(tx.rhash);
});
})();
// Start up a testnet sync in-memory
// while we're at it (because we can).
const tchain = new Chain({
network: 'testnet',
db: 'memory'
});
const tmempool = new Mempool({
network: 'testnet',
chain: tchain
});
const tpool = new Pool({
network: 'testnet',
chain: tchain,
mempool: tmempool,
size: 8
});
(async function() {
await tpool.open();
// Connect, start retrieving and relaying txs
await tpool.connect();
// Start the blockchain sync.
tpool.startSync();
tchain.on('block', (block) => {
console.log('Added testnet block:');
console.log(block);
});
tmempool.on('tx', (tx) => {
console.log('Added testnet tx to mempool:');
console.log(tx);
});
tpool.on('tx', (tx) => {
console.log('Saw testnet transaction:');
console.log(tx);
});
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -0,0 +1,42 @@
'use strict';
const bcoin = require('../..');
const Chain = bcoin.chain;
const Mempool = bcoin.mempool;
const Miner = bcoin.miner;
// Default network (so we can avoid passing
// the `network` option into every object below.)
bcoin.set('regtest');
// Start up a blockchain, mempool, and miner using in-memory
// databases (stored in a red-black tree instead of on-disk).
const chain = new Chain({ db: 'memory' });
const mempool = new Mempool({ chain: chain });
const miner = new Miner({
chain: chain,
mempool: mempool,
// Make sure miner won't block the main thread.
useWorkers: true
});
(async () => {
// Open the miner (initialize the databases, etc).
// Miner will implicitly call `open` on chain and mempool.
await miner.open();
// Create a Cpu miner job
const job = await miner.createJob();
// run miner
const block = await job.mineAsync();
// Add the block to the chain
console.log('Adding %s to the blockchain.', block.rhash);
console.log(block);
await chain.add(block);
console.log('Added block!');
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -2,7 +2,7 @@
/* eslint new-cap: "off" */
const bcoin = require('bcoin');
const bcoin = require('../..');
const assert = require('assert');
(async () => {

View File

@ -0,0 +1,83 @@
'use strict';
const bcoin = require('../..').set('main');
const walletPlugin = bcoin.wallet.plugin;
const node = bcoin.fullnode({
checkpoints: true,
// Primary wallet passphrase
passsphrase: 'node',
logLevel: 'info'
});
node.use(walletPlugin);
// We get a lot of errors sometimes,
// usually from peers hanging up on us.
// Just ignore them for now.
node.on('error', (err) => {
;
});
// New Address we'll be sending to.
const newReceiving = 'AddressHere';
// Start the node
(async () => {
await node.open();
const options = {
id: 'mywallet',
passphrase: 'foo',
witness: false,
type: 'pubkeyhash'
};
const walletdb = node.require('walletdb');
await walletdb.open();
const wallet = await walletdb.create(options);
console.log('Created wallet with address: %s', wallet.getAddress('base58'));
await node.connect();
// Start syncing the blockchain
node.startSync();
// Wait for balance and send it to a new address.
wallet.once('balance', async (balance) => {
// Create a transaction, fill
// it with coins, and sign it.
const options = {
subtractFee: true,
outputs: [{
address: newReceiving,
value: balance.total
}]
};
const tx = await wallet.createTX(options);
const stx = await wallet.sign(tx, 'foo');
console.log('sending tx:');
console.log(stx);
await node.sendTX(stx);
console.log('tx sent!');
});
node.chain.on('block', (block) => {
;
});
node.mempool.on('tx', (tx) => {
;
});
node.chain.on('full', () => {
node.mempool.getHistory().then(console.log);
});
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -1,6 +1,7 @@
'use strict';
const FullNode = require('bcoin/lib/node/fullnode');
const bcoin = require('../..');
const FullNode = bcoin.fullnode;
const node = new FullNode({
network: 'testnet',
@ -21,4 +22,7 @@ const node = new FullNode({
});
node.startSync();
})();
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -0,0 +1,52 @@
'use strict';
const path = require('path');
const bcoin = require('../..');
const Chain = bcoin.chain;
const Logger = bcoin.logger;
const util = bcoin.util;
const HOME = process.env.HOME;
// Setup logger to see what's Bcoin doing.
const logger = new Logger({
level: 'debug'
});
// Create chain for testnet, specify chain directory
const chain = new Chain({
logger: logger,
network: 'testnet',
db: 'leveldb',
prefix: path.join(HOME, '.bcoin/testnet'),
indexTX: true,
indexAddress: true
});
(async () => {
await logger.open();
await chain.open();
console.log('Current height:', chain.height);
const entry = await chain.getEntry(50000);
console.log('Block at 50k:', entry);
// eslint-disable-next-line max-len
const txhash = '4dd628123dcde4f2fb3a8b8a18b806721b56007e32497ebe76cde598ce1652af';
const txmeta = await chain.db.getMeta(util.revHex(txhash));
const tx = txmeta.tx;
const coinview = await chain.db.getSpentView(tx);
console.log(`Tx with hash ${txhash}:`, txmeta);
console.log(`Tx input: ${tx.getInputValue(coinview)},` +
` output: ${tx.getOutputValue()}, fee: ${tx.getFee(coinview)}`);
// eslint-disable-next-line max-len
const bhash = '00000000077eacdd2c803a742195ba430a6d9545e43128ba55ec3c80beea6c0c';
const block = await chain.db.getBlock(util.revHex(bhash));
console.log(`Block with hash ${bhash}:`, block);
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -1,9 +1,10 @@
'use strict';
const KeyRing = require('bcoin/lib/primitives/keyring');
const WorkerPool = require('bcoin/lib/workers/workerpool');
const Chain = require('bcoin/lib/blockchain/chain');
const Miner = require('bcoin/lib/mining/miner');
const bcoin = require('../..');
const KeyRing = bcoin.keyring;
const WorkerPool = bcoin.workerpool;
const Chain = bcoin.chain;
const Miner = bcoin.miner;
const key = KeyRing.generate('regtest');
@ -31,7 +32,7 @@ const miner = new Miner({
console.log('Block template:');
console.log(tmpl);
const job = await miner.cpu.createJob();
const job = await miner.createJob();
const block = await job.mineAsync();
console.log('Mined block:');
@ -42,4 +43,7 @@ const miner = new Miner({
console.log('New tip:');
console.log(chain.tip);
})();
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -1,6 +1,7 @@
'use strict';
const FullNode = require('bcoin/lib/node/fullnode');
const bcoin = require('../..');
const FullNode = bcoin.fullnode;
function MyPlugin(node) {
this.node = node;
@ -52,4 +53,7 @@ node.use(MyPlugin);
});
node.startSync();
})();
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -0,0 +1,56 @@
'use strict';
const bcoin = require('../..');
const Chain = bcoin.chain;
const Pool = bcoin.pool;
const WalletDB = bcoin.walletdb;
bcoin.set('testnet');
// SPV chains only store the chain headers.
const chain = Chain({
db: 'leveldb',
location: process.env.HOME + '/spvchain',
spv: true
});
const pool = new Pool({
chain: chain,
spv: true,
maxPeers: 8
});
const walletdb = new WalletDB({ db: 'memory' });
(async () => {
await pool.open();
await walletdb.open();
const wallet = await walletdb.create();
console.log('Created wallet with address %s', wallet.getAddress('base58'));
// Add our address to the spv filter.
pool.watchAddress(wallet.getAddress());
// Connect, start retrieving and relaying txs
await pool.connect();
// Start the blockchain sync.
pool.startSync();
pool.on('tx', async (tx) => {
console.log('received TX');
await walletdb.addTX(tx);
console.log('Transaction added to walletDB');
});
wallet.on('balance', (balance) => {
console.log('Balance updated.');
console.log(bcoin.amount.btc(balance.unconfirmed));
});
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -1,9 +1,10 @@
'use strict';
const random = require('bcoin/lib/crypto/random');
const WalletDB = require('bcoin/lib/wallet/walletdb');
const MTX = require('bcoin/lib/primitives/mtx');
const Outpoint = require('bcoin/lib/primitives/outpoint');
const bcoin = require('../..');
const random = bcoin.crypto.random;
const WalletDB = bcoin.walletdb;
const MTX = bcoin.mtx;
const Outpoint = bcoin.outpoint;
function dummy() {
const hash = random.randomBytes(32).toString('hex');
@ -42,4 +43,7 @@ const walletdb = new WalletDB({
console.log('Added transaction');
console.log(wtx);
})();
})().catch((err) => {
console.error(err.stack);
process.exit(1);
});

View File

@ -13,10 +13,18 @@ Welcome to the bcoin docs!
- [REST and RPC API][rest-rpc]
## Code Examples
- [Simple Fullnode][example-simple-fullnode]
- [Connect to Peer][example-connect-peer]
- [Connecting to the P2P Network][example-p2p]
- [Creating a Blockchain and Mempool][example-blockchain]
- [Fullnode Object][example-fullnode]
- [Wallet with Dummy TX][example-wallet-dummy]
- [Fullnode Object][example-fullnode-wallet]
- [SPV Sync][example-spv]
- [Plugin Example][example-peers-plugin]
- [Client API Usage][example-client-api]
- [Miner with WorkerPool][example-miner-configs]
- [Create and Sign TX][example-tx-create-sign]
- [Get Transaction from Chain][example-tx-from-chain]
## Advanced
- [Working with transactions][work-transactions]
@ -36,7 +44,15 @@ Welcome to the bcoin docs!
[work-transactions]: Working-with-transactions.md
[scripting]: Scripting.md
[example-p2p]: Example-Connecting-to-the-P2P-Network.md
[example-blockchain]: Example-Creating-a-Blockchain-and-Mempool.md
[example-fullnode]: Example-Fullnode-Object.md
[example-spv]: Example-SPV-Sync.md
[example-p2p]: Examples/connect-to-the-p2p-network.js
[example-blockchain]: Examples/create-a-blockchain-and-mempool.js
[example-fullnode-wallet]: Examples/fullnode-and-wallet.js
[example-spv]: Examples/spv-sync-wallet.js
[example-wallet-dummy]: Examples/wallet.js
[example-peers-plugin]: Examples/peers-plugin.js
[example-client-api]: Examples/client-api.js
[example-miner-configs]: Examples/miner-configs.js
[example-connect-peer]: Examples/connect-to-peer.js
[example-simple-fullnode]: Examples/fullnode.js
[example-tx-create-sign]: Examples/create-sign-tx.js
[example-tx-from-chain]: Examples/get-tx-from-chain.js

View File

@ -1,15 +0,0 @@
'use strict';
const Chain = require('bcoin/lib/blockchain/chain');
const chain = new Chain({
network: 'testnet'
});
(async () => {
await chain.open();
const entry = await chain.getEntry(0);
console.log(entry);
})();