This repository has been archived by the owner on Oct 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
bp.js
88 lines (64 loc) · 2.19 KB
/
bp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* @module bp
*/
'use strict';
const wait = require('util').promisify(setTimeout);
const Account = require('core/account');
const transport = require('core/transport');
const pool = require('core/db').pool;
const chaindata = require('core/db').chain;
const events = require('lib/events');
const peer = require('core/file-peer');
/**
* Block producing timeout.
*
* @type {Number}
*/
const TIMEOUT = 1000;
/**
* Secret key used for testing.
*
* @type {String}
*/
const SECRET_KEY = Buffer.from('557dce58018cf502a32b9b7723024805399350d006a4f71c3b9f489f7085cb50', 'hex');
const producer = Account(SECRET_KEY);
console.log(producer.secretKey.toString('hex'));
console.log('producer', {address: '0x' + producer.address.toString('hex'), publicKey: '0x' + producer.publicKey.toString('hex')});
require('services/observer');
(async function newBlock() {
const parentBlock = await chaindata.getLatest();
const transactions = await pool.drain();
const block = producer.produceBlock(parentBlock, transactions);
await chaindata.add(block);
await streamBlock(block);
// transport.send(events.NEW_BLOCK, block);
return wait(TIMEOUT).then(newBlock);
})().catch(console.error);
(async function newTx() {
const target = () => new Account().address;
const acc = producer;
[
acc.tx('0x' + target().toString('hex'), '0xff'),
acc.stake(100),
acc.stake(200),
acc.vote('0x' + target().toString('hex'), 100),
acc.vote('0x' + target().toString('hex'), 200),
acc.vote('0x' + target().toString('hex'), 300)
].forEach((tx) => transport.send(events.NEW_TRANSACTION, tx));
return wait(TIMEOUT / 2).then(newTx);
})().catch(console.error);
async function streamBlock(block) {
const nodesCount = transport.knownNodes.size - 1;
if (nodesCount === 0) {
return null;
}
console.log('streaming new block %d to %d nodes', block.number, nodesCount);
const {port} = peer.peerString(block, nodesCount);
transport.send(events.NEW_BLOCK, {
port, block: {
number: block.number,
hash: block.hash,
parentHash: block.parentHash
}
});
}