-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathe2e.spec.ts
1726 lines (1627 loc) · 55.4 KB
/
e2e.spec.ts
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable max-lines */
import { readFileSync } from 'fs';
import { dirname, resolve } from 'path';
import { fileURLToPath } from 'url';
import { inspect } from 'util';
import {
binToHex,
encodeDataPush,
flattenBinArray,
hexToBin,
swapEndianness,
utf8ToBin,
} from '@bitauth/libauth';
import type {
BitcoreBlock,
GetDataMessage,
GetHeadersMessage,
Peer,
} from '@chaingraph/bitcore-p2p-cash';
import bitcoreP2pCash, {
BitcoreInventoryType,
} from '@chaingraph/bitcore-p2p-cash';
import test from 'ava';
import type { ExecaChildProcess } from 'execa';
import { execa } from 'execa';
import got from 'got';
import pg from 'pg';
import { chaingraphE2eLogPath, logger } from './e2e.spec.logging.helper.js';
import {
chipnetCashTokensTx,
chipnetCashTokensTxHash,
generateMockchain,
generateMockDoubleSpend,
genesisBlock,
genesisBlockRaw,
halTxHash,
halTxRaw,
halTxSpent,
halTxSpentRaw,
selectHeaders,
testnetGenesisBlockRaw,
Transaction,
} from './e2e.spec.mockchain.helper.js';
// eslint-disable-next-line @typescript-eslint/naming-convention
const { Pool, internalBitcore } = bitcoreP2pCash;
/**
* Set to `true` to log all P2P messages.
*/
const logP2pMessage = false as boolean;
logger.info('\n\n---- Beginning new E2E test run. ----\n');
const e2eTestDbName = 'chaingraph_e2e_test';
const recreateDbOnStartup = true as boolean;
const dir = dirname(fileURLToPath(import.meta.url));
const migration = (path: string) =>
resolve(dir, '../../images/hasura/hasura-data/migrations/', path);
const dbUpMigrationPaths = [
migration('default/1616195337538_init/up.sql'),
migration('default/1673124945608_tokens/up.sql'),
migration('default/1676794104752_parse_bytecode_pattern/up.sql'),
];
const chaingraphInternalApiPort = '3201';
/**
* TODO: test multiple network magic values
*/
/* eslint-disable no-bitwise, @typescript-eslint/no-magic-numbers */
// cspell:disable-next-line
const e2eTestNetworkMagic = Buffer.from(utf8ToBin('grph').map((x) => x | 128));
/* eslint-enable no-bitwise, @typescript-eslint/no-magic-numbers */
const e2eTestNetworkMagicHex = e2eTestNetworkMagic.toString('hex');
const e2eTestNetworkMagicAsNum = parseInt(e2eTestNetworkMagicHex, 16);
const e2eTestNetworkNode1Port = 19333;
const e2eTestNetworkNode2Port = 19334;
const e2eTestNetworkNode3Port = 19335;
const node1Version = 70012;
const node1UserAgent = '/chaingraph-e2e-node-1:0.0.0/';
const node2Version = 70013;
const node2UserAgent = '/chaingraph-e2e-node-2:0.0.0/';
const node3Version = 70014;
const node3UserAgent = '/chaingraph-e2e-node-3:0.0.0/';
const e2eTrustedNodesSet1 = `node1:127.0.0.1:${e2eTestNetworkNode1Port}:${e2eTestNetworkMagicHex},node2:127.0.0.1:${e2eTestNetworkNode2Port}:${e2eTestNetworkMagicHex},node3:127.0.0.1:${e2eTestNetworkNode3Port}:${e2eTestNetworkMagicHex}`;
const e2eTrustedNodesSet2 = `node1:127.0.0.1:${e2eTestNetworkNode1Port}:${e2eTestNetworkMagicHex},node2:127.0.0.1:${e2eTestNetworkNode2Port}:${e2eTestNetworkMagicHex},node4:127.0.0.1:${e2eTestNetworkNode3Port}:${e2eTestNetworkMagicHex}`;
internalBitcore.Networks.add({
name: 'node1net',
networkMagic: e2eTestNetworkMagicAsNum,
port: e2eTestNetworkNode1Port,
});
internalBitcore.Networks.add({
name: 'node2net',
networkMagic: e2eTestNetworkMagicAsNum,
port: e2eTestNetworkNode2Port,
});
internalBitcore.Networks.add({
name: 'node3net',
networkMagic: e2eTestNetworkMagicAsNum,
port: e2eTestNetworkNode3Port,
});
const node1 = new Pool({
dnsSeed: false,
listenAddr: false,
network: 'node1net',
subversion: node1UserAgent,
version: node1Version,
});
const node2 = new Pool({
dnsSeed: false,
listenAddr: false,
network: 'node2net',
subversion: node2UserAgent,
version: node2Version,
});
const node3 = new Pool({
dnsSeed: false,
listenAddr: false,
network: 'node3net',
subversion: node3UserAgent,
version: node3Version,
});
const host = process.env.CHAINGRAPH_E2E_POSTGRES_HOST ?? 'localhost';
const port = process.env.CHAINGRAPH_E2E_POSTGRES_PORT ?? '5432';
logger.debug(`Connecting to Postgres at port: ${port}`);
const postgresE2eConnectionStringBase = `postgres://chaingraph:very_insecure_postgres_password@${host}:${port}`;
const postgresE2eConnectionStringDefaultDb = `${postgresE2eConnectionStringBase}/postgres`;
const postgresE2eConnectionStringTestDb = `${postgresE2eConnectionStringBase}/${e2eTestDbName}`;
const e2eEnvVariables = {
/* eslint-disable @typescript-eslint/naming-convention */
CHAINGRAPH_GENESIS_BLOCKS: `${e2eTestNetworkMagicHex}:${genesisBlockRaw},e3e1f3e8:${genesisBlockRaw},dab5bffa:${testnetGenesisBlockRaw}`,
CHAINGRAPH_INTERNAL_API_PORT: chaingraphInternalApiPort,
CHAINGRAPH_LOG_FIREHOSE: logP2pMessage.toString(),
CHAINGRAPH_LOG_PATH: chaingraphE2eLogPath,
CHAINGRAPH_POSTGRES_CONNECTION_STRING: postgresE2eConnectionStringTestDb,
CHAINGRAPH_TRUSTED_NODES: e2eTrustedNodesSet1,
NODE_ENV: 'production',
/* eslint-enable @typescript-eslint/naming-convention */
};
const e2eEnvVariables2 = {
/* eslint-disable @typescript-eslint/naming-convention */
...e2eEnvVariables,
CHAINGRAPH_TRUSTED_NODES: e2eTrustedNodesSet2,
/* eslint-enable @typescript-eslint/naming-convention */
};
const placeholder = undefined as unknown as Peer;
/**
* Object which holds a reference to each node's `peer`. Set to `undefined`
* before Chaingraph connects to each node.
*/
const peers = {
node1: placeholder,
node2: placeholder,
node3: placeholder,
};
test.beforeEach((t) => {
logger.debug(`Starting test: ${t.title}`);
});
test.afterEach((t) => {
logger.debug(`Completed test: ${t.title}`);
});
// eslint-disable-next-line functional/no-let, @typescript-eslint/init-declarations
let client: pg.Client;
/**
* Before connecting to the e2e test database, drop and recreate it:
*/
test.before(async () => {
if (recreateDbOnStartup) {
const defaultClient = new pg.Client({
connectionString: postgresE2eConnectionStringDefaultDb,
});
await defaultClient.connect();
await defaultClient.query(
`DROP DATABASE IF EXISTS ${e2eTestDbName} WITH (FORCE);`
);
logger.info(`Dropped database: ${e2eTestDbName}`);
await defaultClient.query(`CREATE DATABASE ${e2eTestDbName};`);
logger.info(`Created database: ${e2eTestDbName}`);
await defaultClient.end();
}
client = new pg.Client({
connectionString: postgresE2eConnectionStringTestDb,
});
await client.connect();
if (recreateDbOnStartup) {
await dbUpMigrationPaths.reduce<Promise<pg.QueryResult | undefined>>(
async (chain, path) => {
const dbUpMigration = readFileSync(path, 'utf8');
return chain.then(async () => client.query(dbUpMigration));
},
Promise.resolve(undefined)
);
}
node1.listen();
node2.listen();
node3.listen();
const logPeerConnection = (nodeName: string, peer: Peer) => {
logger.info(
`${nodeName} inbound connection from host ${peer.host} at port ${peer.port}; user-agent: ${peer.subversion}`
);
};
node1.on('peerready', (peer) => {
logPeerConnection(`node1`, peer);
if (!peer.subversion.includes('tx-broadcast')) peers.node1 = peer;
});
node2.on('peerready', (peer) => {
logPeerConnection(`node2`, peer);
if (!peer.subversion.includes('tx-broadcast')) peers.node2 = peer;
});
node3.on('peerready', (peer) => {
logPeerConnection(`node3`, peer);
if (!peer.subversion.includes('tx-broadcast')) peers.node3 = peer;
});
if (logP2pMessage) {
const logNodeMessage = (
nodeName: string,
eventName: string,
message: unknown
) => {
logger.trace(
`${eventName} received from chaingraph to ${nodeName}: ${inspect(
message,
{
compact: true,
depth: 5,
maxArrayLength: 20,
maxStringLength: 1_000,
}
)}`
);
};
node1.on('*', (_, message, eventName) => {
logNodeMessage('node1', eventName, message);
});
node2.on('*', (_, message, eventName) => {
logNodeMessage('node2', eventName, message);
});
node3.on('*', (_, message, eventName) => {
logNodeMessage('node3', eventName, message);
});
logger.info('E2e tests are set to log all P2P messages.');
}
});
/**
* Prepare each "mockchain"
*/
const splitHeight = 3000;
const mockchainBeforeFork = [
genesisBlock,
...generateMockchain({
length: splitHeight,
previousBlockHash: genesisBlock.header.hash,
}),
];
const preSplitLastBlockHash =
mockchainBeforeFork[mockchainBeforeFork.length - 1]!.header.hash;
/**
* At `splitHeight`, the mockchain splits into two tips (A) and (B):
* - Node1 follows (A).
* - Node2 follows (B).
* - Node3 can support either, and switches between tips when one tip finds
* more blocks than the other. (Note, few real implementations would allow
* deep reorgs, but this contrived example allows for most of Chaingraph's
* expected functionality to be tested.)
*
* Node3 later accepts `tipAStale150`, but switches back to tip A, testing a
* string of stale blocks.
*/
const tipLengths = 200;
const tipA = generateMockchain({
length: tipLengths,
previousBlockHash: preSplitLastBlockHash,
});
const tipB = generateMockchain({
length: tipLengths,
previousBlockHash: preSplitLastBlockHash,
});
const tipAStale150 = generateMockchain({
length: 3,
previousBlockHash: tipA[149]!.header.hash,
});
/**
* Initially, all nodes agree on `mockchainBeforeFork`:
*/
const chainStates = {
node1: [...mockchainBeforeFork],
node2: [...mockchainBeforeFork],
node3: [...mockchainBeforeFork],
};
const respondWithChainState =
(peerName: string, chain: BitcoreBlock[]) =>
(peer: Peer, message: GetHeadersMessage) => {
const selected = selectHeaders(
message.starts.map((hash) => hash.slice().reverse().toString('hex')),
chain
);
if (selected === false) {
logger.error(
'Chaingraph requested headers beginning with an unknown genesis block. This is a bug in the E2E tests.'
);
return;
}
logger.debug(
`e2e: getheaders received by ${peerName}, sending ${selected.length} headers.`
);
const headerMessage = new peer.messages.Headers(selected);
peer.sendMessage(headerMessage);
};
node1.on('peergetheaders', respondWithChainState('node1', chainStates.node1));
node2.on('peergetheaders', respondWithChainState('node2', chainStates.node2));
node3.on('peergetheaders', respondWithChainState('node3', chainStates.node3));
const invTestTx =
'deadbeef00000000000000000000000000000000000000000000000000000000';
const mempool: { [x: string]: string | false | undefined } = {
[swapEndianness(halTxSpent)]: halTxSpentRaw,
[swapEndianness(invTestTx)]: false,
};
const respondToGetData = ({
chain,
message,
nodeName,
peer,
}: {
chain: BitcoreBlock[];
message: GetDataMessage;
nodeName: string;
peer: Peer;
}) => {
// eslint-disable-next-line complexity
message.inventory.forEach((inv) => {
const hash = inv.hash.slice().reverse().toString('hex');
if (inv.type === BitcoreInventoryType.MSG_BLOCK) {
const block = chain.find((b) => b.header.hash === hash);
if (block === undefined) {
logger.error(
`No matching block found in ${nodeName} chain for hash: ${hash}`
);
return;
}
peer.sendMessage(new peer.messages.Block(block));
return;
} else if (inv.type === BitcoreInventoryType.MSG_TX) {
const txRaw = mempool[hash];
logger.debug(`e2e: getdata received for hash: ${hash}`);
if (txRaw === undefined) {
logger.error(
`No matching transaction found in e2e mempool for hash: ${hash}`
);
return;
} else if (txRaw === false) {
logger.debug(`e2e: ignoring request.`);
return;
}
const tx = new Transaction(txRaw);
logger.debug(`e2e: sending transaction with hash: ${tx.hash}`);
peer.sendMessage(new peer.messages.Transaction(tx));
}
logger.warn(`Unhandled INV type in GetData from ${nodeName}.`);
});
};
/**
* Respond to `GetData` messages:
*/
node1.on('peergetdata', (peer, message) => {
respondToGetData({
chain: chainStates.node1,
message,
nodeName: 'node1',
peer,
});
});
node2.on('peergetdata', (peer, message) => {
respondToGetData({
chain: chainStates.node2,
message,
nodeName: 'node2',
peer,
});
});
node3.on('peergetdata', (peer, message) => {
respondToGetData({
chain: chainStates.node3,
message,
nodeName: 'node3',
peer,
});
});
logger.info(
`Mockchain generated (${mockchainBeforeFork.length} initial blocks, ${tipLengths} blocks after split), mock nodes prepared to respond to P2P messages.`
);
// eslint-disable-next-line functional/no-let, @typescript-eslint/init-declarations
let chaingraphProcess: ExecaChildProcess | undefined;
// eslint-disable-next-line functional/no-let, @typescript-eslint/init-declarations
let chaingraphProcess2: ExecaChildProcess | undefined;
// eslint-disable-next-line functional/no-let, @typescript-eslint/init-declarations
let chaingraphProcess3: ExecaChildProcess | undefined;
// eslint-disable-next-line functional/no-let
let stdoutBuffer = '';
// eslint-disable-next-line functional/no-let
let waitingForStdout: { pattern: RegExp | string; resolver: () => void }[] = [];
const handleStdout = () => {
waitingForStdout = waitingForStdout.filter((task) => {
if (
typeof task.pattern === 'string'
? stdoutBuffer.includes(task.pattern)
: task.pattern.test(stdoutBuffer)
) {
task.resolver();
return false;
}
return true;
});
};
const seconds = 1000;
const tenSeconds = 10_000;
/**
* Returns a promise that resolves when the `search` string is found in stdout.
* @param search - the string to search for in stdout
*
* TODO: if AVA is running in debug mode, disable timeout (https://github.com/avajs/ava/issues/3152)
*/
const waitForStdout = async (search: RegExp | string, timeout = tenSeconds) => {
logger.debug(`Waiting for stdout: ${search.toString()}`);
const timeoutId = setTimeout(() => {
// eslint-disable-next-line functional/no-throw-statement
throw new Error(
`Test failed after waiting ${
timeout / seconds
}s for the stdout search: ${search.toString()}`
);
}, timeout);
const promise = new Promise<void>((res) => {
waitingForStdout.push({
pattern: search,
resolver: () => {
logger.debug(`Heard stdout: ${search.toString()}`);
clearTimeout(timeoutId);
res();
},
});
});
handleStdout();
return promise;
};
const clearStdoutBuffer = () => {
stdoutBuffer = '';
};
test.serial('[e2e] spawn chaingraph', async (t) => {
chaingraphProcess = execa('node', ['./bin/chaingraph.js'], {
env: e2eEnvVariables,
stdio: 'pipe',
});
if (chaingraphProcess.stdout === null) {
t.fail('`chaingraphProcess` stdout is not available.');
return;
}
chaingraphProcess.stdout.on('data', (chunk) => {
stdoutBuffer += chunk;
handleStdout();
});
await waitForStdout('Starting Chaingraph...');
t.pass();
});
const enum StatusCode {
success = 200,
badRequest = 400,
notFound = 404,
}
test.serial('[e2e] api /health-check is alive', async (t) => {
const healthCheckResponse = await got(
`http://localhost:${chaingraphInternalApiPort}/health-check`
);
t.deepEqual(healthCheckResponse.statusCode, StatusCode.success);
t.deepEqual(healthCheckResponse.body, '{"status":"alive"}');
});
test.serial('[e2e] connects to trusted nodes', async (t) => {
await waitForStdout('node1: connected to node');
await waitForStdout('node2: connected to node');
await waitForStdout('node3: connected to node');
t.pass();
});
test.serial('[e2e] downloads all header chains', async (t) => {
await waitForStdout(/node1[^\n]+headers-syncing completed/u);
await waitForStdout(/node2[^\n]+headers-syncing completed/u);
await waitForStdout(/node3[^\n]+headers-syncing completed/u);
t.pass();
});
test.serial(
'[e2e] restores sync-state from database on restart (during initial sync)',
async (t) => {
await waitForStdout(
/Saved new block – height:\s+10[^\n]+nodes: node1, node2, node3/u
);
logger.info('e2e: testing sync restoration on restart. Sending SIGTERM...');
chaingraphProcess!.kill('SIGINT');
// chaingraphProcess!.kill('SIGTERM');
await waitForStdout('Shutting down...');
await waitForStdout('Exiting...');
chaingraphProcess2 = execa('node', ['./bin/chaingraph.js'], {
env: e2eEnvVariables,
stdio: 'pipe',
});
if (chaingraphProcess2.stdout === null) {
t.fail('`chaingraphProcess2` stdout is not available.');
return;
}
chaingraphProcess2.stdout.on('data', (chunk) => {
stdoutBuffer += chunk;
handleStdout();
});
await waitForStdout('Starting Chaingraph...');
await waitForStdout('Restored chain for node node1');
await waitForStdout('Restored chain for node node2');
await waitForStdout('Restored chain for node node3');
t.pass();
}
);
const sleep = async (ms: number) =>
new Promise((res) => {
setTimeout(res, ms);
});
test.serial(
'[e2e] ignores inbound transactions before initial sync is complete',
async (t) => {
peers.node1.sendMessage(
new peers.node1.messages.Transaction(new Transaction(halTxRaw))
);
const delay = 1000;
await sleep(delay);
const result = await client.query<{ encode: string }>(
/* sql */ `SELECT encode(hash, 'hex') FROM transaction WHERE hash = $1;`,
[hexToBin(halTxHash)]
);
t.deepEqual(result.rowCount, 0);
t.pass();
}
);
const oneMinute = 60_000;
test.serial('[e2e] completes initial sync', async (t) => {
t.timeout(oneMinute);
await waitForStdout(
/Saved new block – height:\s+3000[^\n]+nodes: node1, node2, node3/u,
oneMinute
);
await waitForStdout('Agent: initial sync is complete.');
t.pass();
});
test.serial('[e2e] creates expected indexes after initial sync', async (t) => {
await waitForStdout('Agent: all managed indexes have been created.');
await waitForStdout('Agent: enabled mempool tracking.');
const indexes = (
await client.query<{
indexname: string;
}>(/* sql */ `
SELECT indexname FROM pg_indexes WHERE schemaname = 'public' ORDER BY indexname;
`)
).rows.map((row) => row.indexname);
t.deepEqual(indexes, [
'block_hash_key',
'block_height_index',
'block_inclusions_index',
'block_internal_id_key',
'block_pkey',
'block_transaction_pkey',
'input_pkey',
'node_block_history_pkey',
'node_block_pkey',
'node_internal_id_key',
'node_name_key',
'node_pkey',
'node_transaction_pkey',
'output_pkey',
'output_search_index',
'spent_by_index',
'transaction_hash_key',
'transaction_pkey',
]);
clearStdoutBuffer();
t.pass();
});
test.serial(
'[e2e] after initial sync is complete, requests transactions as they are announced',
async (t) => {
const node3RequestedTx = new Promise((res) => {
node3.once('peergetdata', (_, message) => {
res(message.inventory);
});
});
const announcedHash = Buffer.from(invTestTx, 'hex');
peers.node3.sendMessage(
peers.node3.messages.Inventory.forTransaction(announcedHash)
);
const result = await node3RequestedTx;
t.deepEqual(result, [{ hash: announcedHash.reverse(), type: 1 }]);
}
);
test.serial(
'[e2e] after initial sync is complete, saves inbound transactions as they are received',
async (t) => {
peers.node1.sendMessage(
new peers.node1.messages.Transaction(new Transaction(halTxRaw))
);
const delay = 1000;
await sleep(delay);
const result = await client.query<{ encode: string }>(
/* sql */ `SELECT encode(encode_transaction(transaction), 'hex') FROM transaction WHERE hash = $1;`,
[hexToBin(halTxHash)]
);
t.deepEqual(result.rows[0]!.encode, halTxRaw);
t.pass();
}
);
test.serial('[e2e] handles first chipnet CashTokens transaction', async (t) => {
peers.node1.sendMessage(
new peers.node1.messages.Transaction(new Transaction(chipnetCashTokensTx))
);
const delay = 1000;
await sleep(delay);
const result = await client.query<{ encode: string }>(
/* sql */ `SELECT encode(encode_transaction(transaction), 'hex') FROM transaction WHERE hash = $1;`,
[hexToBin(chipnetCashTokensTxHash)]
);
t.deepEqual(result.rows[0]!.encode, chipnetCashTokensTx);
t.pass();
});
test.serial(
'[e2e] after initial sync is complete, requests and saves inbound transactions as they are announced',
async (t) => {
peers.node1.sendMessage(
peers.node1.messages.Inventory.forTransaction(
Buffer.from(halTxSpent, 'hex')
)
);
const delay = 1000;
await sleep(delay);
const result = await client.query<{ encode: string }>(
/* sql */ `SELECT encode(encode_transaction(transaction), 'hex') FROM transaction WHERE hash = $1;`,
[hexToBin(halTxSpent)]
);
t.deepEqual(result.rows[0]!.encode, halTxSpentRaw);
t.pass();
}
);
test.serial('[e2e] get hex-encoded genesis block header', async (t) => {
/* eslint-disable @typescript-eslint/naming-convention */
const encodedHex = (
await client.query<{ block_header_encoded_hex: string }>(
/* sql */ `SELECT block_header_encoded_hex (block) FROM block WHERE height = 0;`
)
).rows[0]!.block_header_encoded_hex;
/* eslint-enable @typescript-eslint/naming-convention */
t.deepEqual(
encodedHex,
'0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c'
);
});
test.serial('[e2e] get hex-encoded genesis block transaction', async (t) => {
const genesisTxHash = hexToBin(
'4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b'
);
/* eslint-disable @typescript-eslint/naming-convention */
const encodedHex = (
await client.query<{ transaction_encoded_hex: string }>(
/* sql */ `SELECT transaction_encoded_hex (transaction) FROM transaction WHERE hash = $1::bytea;`,
[genesisTxHash]
)
).rows[0]!.transaction_encoded_hex;
/* eslint-enable @typescript-eslint/naming-convention */
t.deepEqual(
encodedHex,
'01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000'
);
});
test.serial(
'[e2e] get hex-encoded genesis block (with transaction)',
async (t) => {
/* eslint-disable @typescript-eslint/naming-convention */
const encodedHex = (
await client.query<{ block_encoded_hex: string }>(
/* sql */ `SELECT block_encoded_hex (block) FROM block WHERE height = 0;`
)
).rows[0]!.block_encoded_hex;
/* eslint-enable @typescript-eslint/naming-convention */
t.deepEqual(encodedHex, genesisBlockRaw);
}
);
const newBlocks = (
node: 'node1' | 'node2' | 'node3',
blocks: BitcoreBlock[]
) => {
chainStates[node].push(...blocks);
peers[node].sendMessage(
new peers[node].messages.Headers(blocks.map((block) => block.header))
);
};
test.serial(
'[e2e] syncs blocks as they arrive, handles multiple chain tips',
async (t) => {
const [, tx1] = tipA[0]!.transactions;
peers.node1.sendMessage(new peers.node1.messages.Transaction(tx1));
logger.debug(`node1: sent tipA[0] transaction 0: ${tx1!.hash}`);
newBlocks('node1', [tipA[0]!]);
newBlocks('node2', [tipB[0]!]);
newBlocks('node3', [tipB[0]!]);
t.deepEqual(
chainStates.node2.map((block) => block.header.hash),
chainStates.node3.map((block) => block.header.hash)
);
await waitForStdout(/Saved new block – height:\s+3001[^\n]+nodes: node1/u);
t.true(
/Saved new block – height:\s+3001[^\n]+new txs: 3\/4[^\n]+nodes: node1/u.test(
stdoutBuffer
),
'3 of 4 transactions should be new in tip A block 3001. Has the mockchain changed? (If so, update this test.)'
);
await waitForStdout(
/Saved new block – height:\s+3001[^\n]+nodes: node2, node3/u
);
t.pass();
}
);
test.serial('[e2e] handles re-org of a single block', async (t) => {
newBlocks('node1', [tipA[1]!]);
newBlocks('node2', [tipB[1]!]);
chainStates.node3.pop();
newBlocks('node3', [tipA[0]!, tipA[1]!]);
t.deepEqual(
chainStates.node1.map((block) => block.header.hash),
chainStates.node3.map((block) => block.header.hash)
);
await waitForStdout(
/node3: re-organization detected beginning at height: 3001. The following stale blocks were removed:/u
);
await waitForStdout(
/Saved new block – height:\s+3002[^\n]+hash: a44a664d5acc560305fceb9ba3c7f195a5d78236c1705d5ae7434ba784005689[^\n]+nodes: node2/u
);
await waitForStdout(
/Saved new block – height:\s+3002[^\n]+hash: 9c4feec6f35a54f2244f2ab14e1370e60713097be2ead8402e4ef68f96e07c8c[^\n]+nodes: node1, node3/u
);
t.pass();
});
test.serial('[e2e] handles reversal of single-block re-org', async (t) => {
const tipStartIndex = 2;
const tipEnd = 6;
newBlocks('node1', tipA.slice(tipStartIndex, tipEnd));
newBlocks('node2', tipB.slice(tipStartIndex, tipEnd));
chainStates.node3.splice(splitHeight + 1);
newBlocks('node3', tipB.slice(0, tipEnd));
t.deepEqual(
chainStates.node2.map((block) => block.header.hash),
chainStates.node3.map((block) => block.header.hash)
);
await waitForStdout(
/node3: re-organization detected beginning at height: 3001. The following stale blocks were removed:/u
);
await waitForStdout(/Saved new block – height:\s+3006[^\n]+nodes: node1/u);
await waitForStdout(
/Saved new block – height:\s+3006[^\n]+nodes: node2, node3/u
);
t.pass();
});
test.serial('[e2e] handles re-org of 6 blocks', async (t) => {
const tipStartIndex = 6;
const tipEnd = 7;
newBlocks('node1', tipA.slice(tipStartIndex, tipEnd));
chainStates.node3.splice(splitHeight + 1);
newBlocks('node3', tipA.slice(0, tipEnd));
t.deepEqual(
chainStates.node1.map((block) => block.header.hash),
chainStates.node3.map((block) => block.header.hash)
);
await waitForStdout(
/node3: re-organization detected beginning at height: 3001. The following stale blocks were removed:/u
);
await waitForStdout(
/Saved new block – height:\s+3007[^\n]+nodes: node1, node3/u
);
t.pass();
});
test.serial('[e2e] handles reversal of 6 block re-org', async (t) => {
const tipStartIndex = 6;
const tipEnd = 8;
newBlocks('node2', tipB.slice(tipStartIndex, tipEnd));
chainStates.node3.splice(splitHeight + 1);
newBlocks('node3', tipB.slice(0, tipEnd));
t.deepEqual(
chainStates.node2.map((block) => block.header.hash),
chainStates.node3.map((block) => block.header.hash)
);
await waitForStdout(
/node3: re-organization detected beginning at height: 3001. The following stale blocks were removed:/u
);
await waitForStdout(
/Saved new block – height:\s+3008[^\n]+nodes: node2, node3/u
);
t.pass();
});
/**
* Re-orgs larger than 8 blocks are only announced via INV message; this method
* simulates blocks coming in as expected via headers messages.
*/
/* eslint-disable @typescript-eslint/no-magic-numbers */
const slowFeedBlocks = (
node: 'node1' | 'node2' | 'node3',
blocks: BitcoreBlock[],
chunk = 6
) => {
// eslint-disable-next-line functional/no-loop-statement, functional/no-let
for (let i = 0; i < blocks.length; i += chunk) {
newBlocks(node, blocks.slice(i, i + chunk));
}
};
test.serial('[e2e] handles re-org of 100 blocks', async (t) => {
const tipEnd = 101;
slowFeedBlocks('node1', tipA.slice(7, tipEnd));
slowFeedBlocks('node2', tipB.slice(8, tipEnd));
chainStates.node3.splice(splitHeight + 1);
chainStates.node3.push(...tipA.slice(0, tipEnd));
t.deepEqual(
chainStates.node1.map((block) => block.header.hash),
chainStates.node3.map((block) => block.header.hash)
);
peers.node3.sendMessage(
peers.node3.messages.Inventory.forBlock(tipA[tipEnd - 1]!.header.hash)
);
await waitForStdout(
`node3: received unexpected block inventory item with hash: ${swapEndianness(
tipA[tipEnd - 1]!.header.hash
)}`
);
await waitForStdout(
/node3: re-organization detected beginning at height: 3001. The following stale blocks were removed:/u
);
await waitForStdout(/Saved new block – height:\s+3100[^\n]+nodes: node2/u);
await waitForStdout(
/Saved new block – height:\s+3100[^\n]+nodes: node1, node3/u
);
t.pass();
});
test.serial('[e2e] records stale blocks', async (t) => {
const tipStartIndex = 101;
const tipEnd1 = 150;
const tipEnd2 = 160;
slowFeedBlocks('node1', tipA.slice(tipStartIndex, tipEnd1));
slowFeedBlocks('node2', tipB.slice(tipStartIndex, tipEnd1));
slowFeedBlocks('node3', tipA.slice(tipStartIndex, tipEnd1));
newBlocks('node3', tipAStale150);
await waitForStdout(/Saved new block – height:\s+3153[^\n]+nodes: node3/u);
chainStates.node3.splice(splitHeight + tipEnd1 + 1);
slowFeedBlocks('node1', tipA.slice(tipEnd1, tipEnd2));
slowFeedBlocks('node2', tipB.slice(tipEnd1, tipEnd2));
slowFeedBlocks('node3', tipA.slice(tipEnd1, tipEnd2));
t.deepEqual(
chainStates.node1.map((block) => block.header.hash),
chainStates.node3.map((block) => block.header.hash)
);
await waitForStdout(
/node3: re-organization detected beginning at height: 3151. The following stale blocks were removed:/u
);
await waitForStdout(/Saved new block – height:\s+3160[^\n]+nodes: node2/u);
await waitForStdout(
/Saved new block – height:\s+3160[^\n]+nodes: node1, node3/u
);
t.pass();
});
/* eslint-enable @typescript-eslint/no-magic-numbers */
test.serial(
'[e2e] records double-spends accepted via mempool and via block',
async (t) => {
// eslint-disable-next-line prefer-destructuring
const tx1 = tipA[160]!.transactions[1];
const mock1 = generateMockDoubleSpend(tx1!.inputs, true);
// TODO: race condition – this should work without a delay?
const delay = 1000;
peers.node1.sendMessage(new peers.node1.messages.Transaction(tx1));
logger.debug(
`node1: sent original transaction to double-spend: ${tx1!.hash}`
);
await sleep(delay);
peers.node1.sendMessage(new peers.node1.messages.Transaction(mock1));
logger.debug(`node1: sent double-spending transaction: ${mock1.hash}`);
await sleep(delay);
newBlocks('node1', [tipA[160]!]);
newBlocks('node2', [tipB[160]!]);
newBlocks('node3', [tipA[160]!]);
logger.debug(
`node1: sent block including original transaction: ${tx1!.hash}`
);
await waitForStdout(/Saved new block – height:\s+3161[^\n]+nodes: node2/u);
await waitForStdout(
/Saved new block – height:\s+3161[^\n]+nodes: node1, node3/u
);
/* eslint-disable @typescript-eslint/naming-convention */
const res = await client.query<{
internal_id: number;
node_internal_id: number;
transaction_internal_id: number;
validated_at: string;
replaced_at: string;
}>(
/* sql */ `SELECT * FROM node_transaction_history WHERE transaction_internal_id IN (SELECT internal_id FROM transaction WHERE hash IN ($1::bytea, $2::bytea)) ORDER BY validated_at ASC;
`,
[hexToBin(tx1!.hash), hexToBin(mock1.hash)]
);
/* eslint-enable @typescript-eslint/naming-convention */
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
t.deepEqual(res.rows.length, 2);
t.deepEqual(res.rows[0]!.node_internal_id, res.rows[1]!.node_internal_id);
t.deepEqual(res.rows[0]!.replaced_at, res.rows[1]!.validated_at);
t.true(
new Date(res.rows[0]!.validated_at) <= new Date(res.rows[0]!.replaced_at)
);
t.true(
new Date(res.rows[1]!.validated_at) <= new Date(res.rows[1]!.replaced_at)
);
t.pass();
}
);
test.serial(
'[e2e] removes node_transaction entries which are confirmed by a block',
async (t) => {
const [, tx1, tx2, tx3] = tipA[161]!.transactions;
peers.node1.sendMessage(new peers.node1.messages.Transaction(tx1));
logger.debug(`node1: sent tx1: ${tx1!.hash}`);
peers.node1.sendMessage(new peers.node1.messages.Transaction(tx2));
logger.debug(`node1: sent tx2: ${tx2!.hash}`);
peers.node1.sendMessage(new peers.node1.messages.Transaction(tx3));
logger.debug(`node1: sent tx3: ${tx2!.hash}`);
const delay = 100;
await sleep(delay);
const mempool1 = await client.query<{ encode: string }>(
/* sql */ `SELECT encode(hash, 'hex') FROM node_transaction JOIN transaction ON node_transaction.transaction_internal_id = transaction.internal_id ORDER BY hash ASC;`
);
t.deepEqual(mempool1.rows, [
{ encode: tx1!.hash },
{ encode: tx3!.hash },
{ encode: tx2!.hash },
{ encode: chipnetCashTokensTxHash },
{ encode: halTxSpent },
{ encode: halTxHash },
]);