/
Consensus.js
256 lines (231 loc) · 7.02 KB
/
Consensus.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/* @flow */
import { AsyncIterableX } from 'ix/asynciterable/asynciterablex';
import {
type ConsensusPayload,
type ECPoint,
type PrivateKey,
type Transaction,
type UInt160,
common,
crypto,
} from '@neo-one/client-core';
import type { Monitor } from '@neo-one/monitor';
import type { Observable } from 'rxjs';
import { finalize, mergeScanLatest } from '@neo-one/utils';
import { scan } from 'ix/asynciterable/pipe/index';
import { map, switchMap, take } from 'rxjs/operators';
import ConsensusContext from './ConsensusContext';
import ConsensusQueue from './ConsensusQueue';
import type { Context } from './context';
import type { Event, Result } from './types';
import type Node from '../Node';
import handleConsensusPayload from './handleConsensusPayload';
import handlePersistBlock from './handlePersistBlock';
import handleTransactionReceived from './handleTransactionReceived';
import { initializeNewConsensus } from './common';
import runConsensus from './runConsensus';
export type Options = {|
privateKey: string,
privateNet: boolean,
|};
export type InternalOptions = {|
privateKey: PrivateKey,
publicKey: ECPoint,
feeAddress: UInt160,
privateNet: boolean,
|};
const MS_IN_SECOND = 1000;
export default class Consensus {
_queue: ConsensusQueue;
_timer: ?TimeoutID;
_options$: Observable<InternalOptions>;
_node: Node;
_consensusContext: ConsensusContext;
_monitor: Monitor;
_startPromise: Promise<void> | null;
constructor({
options$,
node,
monitor,
}: {|
options$: Observable<Options>,
node: Node,
monitor: Monitor,
|}) {
this._queue = new ConsensusQueue();
this._timer = null;
this._options$ = options$.pipe(
map((options) => {
const privateKey = common.stringToPrivateKey(options.privateKey);
const publicKey = crypto.privateKeyToPublicKey(privateKey);
const feeAddress = crypto.publicKeyToScriptHash(publicKey);
return {
privateKey,
publicKey,
feeAddress,
privateNet: options.privateNet,
};
}),
);
this._node = node;
this._consensusContext = new ConsensusContext();
this._monitor = monitor.at('node_consensus');
this._startPromise = null;
}
start$(): Observable<void> {
return this._options$.pipe(
switchMap(async (options) => {
if (this._startPromise != null) {
await this.pause();
}
return options;
}),
mergeScanLatest(async (_, options) => {
this._startPromise = this._start(options).then(() => {
this._startPromise = null;
});
await this._startPromise;
}),
finalize(async () => {
await this.pause();
}),
);
}
async _start(options: InternalOptions): Promise<void> {
this._monitor.log({
name: 'neo_consensus_start',
message: 'Consensus started.',
level: 'verbose',
});
const initialResult = await initializeNewConsensus({
blockchain: this._node.blockchain,
publicKey: options.publicKey,
consensusContext: this._consensusContext,
});
await AsyncIterableX.from((this._queue: $FlowFixMe))
.pipe(
scan(async (context: Context, event: Event) => {
let result;
switch (event.type) {
case 'handlePersistBlock':
result = await handlePersistBlock({
blockchain: this._node.blockchain,
publicKey: options.publicKey,
consensusContext: this._consensusContext,
});
break;
case 'handleConsensusPayload':
result = await handleConsensusPayload({
context,
node: this._node,
privateKey: options.privateKey,
payload: event.payload,
consensusContext: this._consensusContext,
});
break;
case 'handleTransactionReceived':
result = await handleTransactionReceived({
context,
node: this._node,
privateKey: options.privateKey,
transaction: event.transaction,
consensusContext: this._consensusContext,
});
break;
case 'timer':
result = await runConsensus({
context,
node: this._node,
options,
consensusContext: this._consensusContext,
});
break;
default:
// eslint-disable-next-line
(event.type: empty);
throw new Error('For ESLint');
}
return this._handleResult(result);
}, this._handleResult(initialResult)),
)
.forEach(() => {});
this._monitor.log({
name: 'neo_consensus_stop',
message: 'Consensus stopped.',
level: 'verbose',
});
}
onPersistBlock(): void {
this._queue.write({ type: 'handlePersistBlock' });
}
onConsensusPayloadReceived(payload: ConsensusPayload): void {
this._queue.write({
type: 'handleConsensusPayload',
payload,
});
}
onTransactionReceived(transaction: Transaction): void {
this._queue.write({
type: 'handleTransactionReceived',
transaction,
});
}
async runConsensusNow(): Promise<void> {
const options = await this._options$.pipe(take(1)).toPromise();
if (options.privateNet) {
this._queue.write({ type: 'timer' });
} else {
throw new Error('Can only force consensus on a private network.');
}
}
nowSeconds(): number {
return this._consensusContext.nowSeconds();
}
async fastForwardOffset(seconds: number): Promise<void> {
const options = await this._options$.pipe(take(1)).toPromise();
if (options.privateNet) {
this._consensusContext.fastForwardOffset(seconds);
} else {
throw new Error('Can only fast forward on a private network.');
}
}
async fastForwardToTime(seconds: number): Promise<void> {
const options = await this._options$.pipe(take(1)).toPromise();
if (options.privateNet) {
this._consensusContext.fastForwardToTime(seconds);
} else {
throw new Error('Can only fast forward on a private network.');
}
}
async pause(): Promise<void> {
this._clearTimer();
this._queue.done();
this._queue = new ConsensusQueue();
if (this._startPromise != null) {
await this._startPromise;
}
}
async resume(): Promise<void> {
const options = await this._options$.pipe(take(1)).toPromise();
this._startPromise = this._start(options);
}
_handleResult(result: Result<Context>): Context {
if (result.timerSeconds != null) {
this._handleTimer(result.timerSeconds);
}
return result.context;
}
_handleTimer(timerSeconds: number): void {
this._clearTimer();
this._timer = setTimeout(
() => this._queue.write({ type: 'timer' }),
timerSeconds * MS_IN_SECOND,
);
}
_clearTimer(): void {
if (this._timer != null) {
clearTimeout(this._timer);
this._timer = null;
}
}
}