@aztec/p2p 0.1.0-alpha11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.cjs +1 -0
- package/.tsbuildinfo +1 -0
- package/README.md +7 -0
- package/dest/bootstrap/bootstrap.d.ts +26 -0
- package/dest/bootstrap/bootstrap.d.ts.map +1 -0
- package/dest/bootstrap/bootstrap.js +92 -0
- package/dest/client/index.d.ts +5 -0
- package/dest/client/index.d.ts.map +1 -0
- package/dest/client/index.js +8 -0
- package/dest/client/mocks.d.ts +33 -0
- package/dest/client/mocks.d.ts.map +1 -0
- package/dest/client/mocks.js +52 -0
- package/dest/client/p2p_client.d.ts +170 -0
- package/dest/client/p2p_client.d.ts.map +1 -0
- package/dest/client/p2p_client.js +206 -0
- package/dest/client/p2p_client.test.d.ts +2 -0
- package/dest/client/p2p_client.test.d.ts.map +1 -0
- package/dest/client/p2p_client.test.js +58 -0
- package/dest/config.d.ts +67 -0
- package/dest/config.d.ts.map +1 -0
- package/dest/config.js +25 -0
- package/dest/index.d.ts +6 -0
- package/dest/index.d.ts.map +1 -0
- package/dest/index.js +6 -0
- package/dest/service/dummy_service.d.ts +28 -0
- package/dest/service/dummy_service.d.ts.map +1 -0
- package/dest/service/dummy_service.js +30 -0
- package/dest/service/index.d.ts +3 -0
- package/dest/service/index.d.ts.map +1 -0
- package/dest/service/index.js +3 -0
- package/dest/service/known_txs.d.ts +31 -0
- package/dest/service/known_txs.d.ts.map +1 -0
- package/dest/service/known_txs.js +52 -0
- package/dest/service/known_txs.test.d.ts +2 -0
- package/dest/service/known_txs.test.d.ts.map +1 -0
- package/dest/service/known_txs.test.js +34 -0
- package/dest/service/libp2p_service.d.ts +74 -0
- package/dest/service/libp2p_service.d.ts.map +1 -0
- package/dest/service/libp2p_service.js +335 -0
- package/dest/service/service.d.ts +27 -0
- package/dest/service/service.d.ts.map +1 -0
- package/dest/service/service.js +2 -0
- package/dest/service/tx_messages.d.ts +78 -0
- package/dest/service/tx_messages.d.ts.map +1 -0
- package/dest/service/tx_messages.js +191 -0
- package/dest/service/tx_messages.test.d.ts +2 -0
- package/dest/service/tx_messages.test.d.ts.map +1 -0
- package/dest/service/tx_messages.test.js +56 -0
- package/dest/tx_pool/index.d.ts +3 -0
- package/dest/tx_pool/index.d.ts.map +1 -0
- package/dest/tx_pool/index.js +3 -0
- package/dest/tx_pool/memory_tx_pool.d.ts +52 -0
- package/dest/tx_pool/memory_tx_pool.d.ts.map +1 -0
- package/dest/tx_pool/memory_tx_pool.js +70 -0
- package/dest/tx_pool/tx_pool.d.ts +39 -0
- package/dest/tx_pool/tx_pool.d.ts.map +1 -0
- package/dest/tx_pool/tx_pool.js +2 -0
- package/dest/tx_pool/tx_pool.test.d.ts +2 -0
- package/dest/tx_pool/tx_pool.test.d.ts.map +1 -0
- package/dest/tx_pool/tx_pool.test.js +20 -0
- package/package.json +24 -0
- package/src/bootstrap/bootstrap.ts +107 -0
- package/src/client/index.ts +10 -0
- package/src/client/mocks.ts +63 -0
- package/src/client/p2p_client.test.ts +79 -0
- package/src/client/p2p_client.ts +304 -0
- package/src/config.ts +113 -0
- package/src/index.ts +5 -0
- package/src/service/dummy_service.ts +35 -0
- package/src/service/index.ts +2 -0
- package/src/service/known_txs.test.ts +45 -0
- package/src/service/known_txs.ts +56 -0
- package/src/service/libp2p_service.ts +385 -0
- package/src/service/service.ts +30 -0
- package/src/service/tx_messages.test.ts +83 -0
- package/src/service/tx_messages.ts +211 -0
- package/src/tx_pool/index.ts +2 -0
- package/src/tx_pool/memory_tx_pool.ts +82 -0
- package/src/tx_pool/tx_pool.test.ts +24 -0
- package/src/tx_pool/tx_pool.ts +44 -0
- package/tsconfig.json +20 -0
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { Libp2p, Libp2pOptions, ServiceFactoryMap, createLibp2p } from 'libp2p';
|
|
2
|
+
import { tcp } from '@libp2p/tcp';
|
|
3
|
+
import { noise } from '@chainsafe/libp2p-noise';
|
|
4
|
+
import { mplex } from '@libp2p/mplex';
|
|
5
|
+
import { kadDHT } from '@libp2p/kad-dht';
|
|
6
|
+
import { createFromProtobuf } from '@libp2p/peer-id-factory';
|
|
7
|
+
import { createDebugLogger } from '@aztec/foundation/log';
|
|
8
|
+
import { P2PConfig } from '../config.js';
|
|
9
|
+
import { yamux } from '@chainsafe/libp2p-yamux';
|
|
10
|
+
import { identifyService } from 'libp2p/identify';
|
|
11
|
+
import type { ServiceMap } from '@libp2p/interface-libp2p';
|
|
12
|
+
import { createLibP2PPeerId } from '../index.js';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Encapsulates a 'Bootstrap' node, used for the purpose of assisting new joiners in acquiring peers.
|
|
16
|
+
*/
|
|
17
|
+
export class BootstrapNode {
|
|
18
|
+
private node?: Libp2p = undefined;
|
|
19
|
+
|
|
20
|
+
constructor(private logger = createDebugLogger('aztec:p2p_bootstrap')) {}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Starts the bootstrap node.
|
|
24
|
+
* @param config - The P2P configuration.
|
|
25
|
+
* @returns An empty promise.
|
|
26
|
+
*/
|
|
27
|
+
public async start(config: P2PConfig) {
|
|
28
|
+
const { peerIdPrivateKey, tcpListenIp, tcpListenPort, announceHostname, announcePort, minPeerCount, maxPeerCount } =
|
|
29
|
+
config;
|
|
30
|
+
const peerId = peerIdPrivateKey
|
|
31
|
+
? await createFromProtobuf(Buffer.from(peerIdPrivateKey, 'hex'))
|
|
32
|
+
: await createLibP2PPeerId();
|
|
33
|
+
this.logger(
|
|
34
|
+
`Starting bootstrap node ${peerId} on ${tcpListenIp}:${tcpListenPort} announced at ${announceHostname}:${announcePort}`,
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
const opts: Libp2pOptions<ServiceMap> = {
|
|
38
|
+
start: false,
|
|
39
|
+
peerId,
|
|
40
|
+
addresses: {
|
|
41
|
+
listen: [`/ip4/${tcpListenIp}/tcp/${tcpListenPort}`],
|
|
42
|
+
announce: [`/ip4/${announceHostname}/tcp/${announcePort ?? tcpListenPort}`],
|
|
43
|
+
},
|
|
44
|
+
transports: [tcp()],
|
|
45
|
+
streamMuxers: [yamux(), mplex()],
|
|
46
|
+
connectionEncryption: [noise()],
|
|
47
|
+
connectionManager: {
|
|
48
|
+
minConnections: minPeerCount,
|
|
49
|
+
maxConnections: maxPeerCount,
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const services: ServiceFactoryMap = {
|
|
54
|
+
identify: identifyService({
|
|
55
|
+
protocolPrefix: 'aztec',
|
|
56
|
+
}),
|
|
57
|
+
kadDHT: kadDHT({
|
|
58
|
+
protocolPrefix: 'aztec',
|
|
59
|
+
clientMode: false,
|
|
60
|
+
}),
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
this.node = await createLibp2p({
|
|
64
|
+
...opts,
|
|
65
|
+
services,
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
await this.node.start();
|
|
69
|
+
this.logger(`lib p2p has started`);
|
|
70
|
+
|
|
71
|
+
// print out listening addresses
|
|
72
|
+
this.logger('listening on addresses:');
|
|
73
|
+
this.node.getMultiaddrs().forEach(addr => {
|
|
74
|
+
this.logger(addr.toString());
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
this.node.addEventListener('peer:discovery', evt => {
|
|
78
|
+
this.logger('Discovered %s', evt.detail.id.toString()); // Log discovered peer
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
this.node.addEventListener('peer:connect', evt => {
|
|
82
|
+
this.logger('Connected to %s', evt.detail.toString()); // Log connected peer
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
this.node.addEventListener('peer:disconnect', evt => {
|
|
86
|
+
this.logger('Disconnected from %s', evt.detail.toString()); // Log connected peer
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Stops the bootstrap node.
|
|
92
|
+
* @returns And empty promise.
|
|
93
|
+
*/
|
|
94
|
+
public async stop() {
|
|
95
|
+
// stop libp2p
|
|
96
|
+
await this.node?.stop();
|
|
97
|
+
this.logger('libp2p has stopped');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Returns the peerId of this node.
|
|
102
|
+
* @returns The node's peer Id
|
|
103
|
+
*/
|
|
104
|
+
public getPeerId() {
|
|
105
|
+
return this.node?.peerId;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { L2BlockSource } from '@aztec/types';
|
|
2
|
+
import { LibP2PService, P2PClient, P2PConfig, TxPool } from '../index.js';
|
|
3
|
+
import { DummyP2PService } from '../service/dummy_service.js';
|
|
4
|
+
|
|
5
|
+
export * from './p2p_client.js';
|
|
6
|
+
|
|
7
|
+
export const createP2PClient = async (config: P2PConfig, txPool: TxPool, l2BlockSource: L2BlockSource) => {
|
|
8
|
+
const p2pService = config.p2pEnabled ? await LibP2PService.new(config, txPool) : new DummyP2PService();
|
|
9
|
+
return new P2PClient(l2BlockSource, txPool, p2pService);
|
|
10
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { KERNEL_PUBLIC_CALL_STACK_LENGTH, Proof } from '@aztec/circuits.js';
|
|
2
|
+
import { makeKernelPublicInputs, makePublicCallRequest } from '@aztec/circuits.js/factories';
|
|
3
|
+
import { Tx, TxL2Logs, L2BlockSource, L2Block } from '@aztec/types';
|
|
4
|
+
import times from 'lodash.times';
|
|
5
|
+
|
|
6
|
+
export const MockTx = () => {
|
|
7
|
+
return new Tx(
|
|
8
|
+
makeKernelPublicInputs(),
|
|
9
|
+
new Proof(Buffer.alloc(0)),
|
|
10
|
+
TxL2Logs.random(8, 3), // 8 priv function invocations creating 3 encrypted logs each
|
|
11
|
+
TxL2Logs.random(11, 2), // 8 priv + 3 pub function invocations creating 2 unencrypted logs each
|
|
12
|
+
[],
|
|
13
|
+
times(KERNEL_PUBLIC_CALL_STACK_LENGTH, makePublicCallRequest),
|
|
14
|
+
);
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A mocked implementation of L2BlockSource to be used in p2p tests.
|
|
19
|
+
*/
|
|
20
|
+
export class MockBlockSource implements L2BlockSource {
|
|
21
|
+
private l2Blocks: L2Block[];
|
|
22
|
+
|
|
23
|
+
constructor(private numBlocks = 100) {
|
|
24
|
+
this.l2Blocks = [];
|
|
25
|
+
for (let i = 0; i < this.numBlocks; i++) {
|
|
26
|
+
this.l2Blocks.push(L2Block.random(i));
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Gets the number of the latest L2 block processed by the block source implementation.
|
|
32
|
+
* @returns In this mock instance, returns the number of L2 blocks that we've mocked.
|
|
33
|
+
*/
|
|
34
|
+
public getBlockHeight() {
|
|
35
|
+
return Promise.resolve(this.l2Blocks.length - 1);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Gets the `take` amount of L2 blocks starting from `from`.
|
|
40
|
+
* @param from - Number of the first block to return (inclusive).
|
|
41
|
+
* @param take - The number of blocks to return.
|
|
42
|
+
* @returns The requested mocked L2 blocks.
|
|
43
|
+
*/
|
|
44
|
+
public getL2Blocks(from: number, take: number) {
|
|
45
|
+
return Promise.resolve(this.l2Blocks.slice(from, from + take));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Starts the block source. In this mock implementation, this is a noop.
|
|
50
|
+
* @returns A promise that signals the initialization of the l2 block source on compmletion.
|
|
51
|
+
*/
|
|
52
|
+
public start(): Promise<void> {
|
|
53
|
+
return Promise.resolve();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Stops the block source. In this mock implementation, this is a noop.
|
|
58
|
+
* @returns A promise that signals the l2 block source is now stopped.
|
|
59
|
+
*/
|
|
60
|
+
public stop(): Promise<void> {
|
|
61
|
+
return Promise.resolve();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { expect, jest } from '@jest/globals';
|
|
2
|
+
import { L2BlockSource } from '@aztec/types';
|
|
3
|
+
|
|
4
|
+
import { P2PClient } from './p2p_client.js';
|
|
5
|
+
import { TxPool } from '../tx_pool/index.js';
|
|
6
|
+
import { MockBlockSource } from './mocks.js';
|
|
7
|
+
import { MockTx } from './mocks.js';
|
|
8
|
+
import { P2PService } from '../index.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Mockify helper for testing purposes.
|
|
12
|
+
*/
|
|
13
|
+
type Mockify<T> = {
|
|
14
|
+
[P in keyof T]: ReturnType<typeof jest.fn>;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
describe('In-Memory P2P Client', () => {
|
|
18
|
+
let txPool: Mockify<TxPool>;
|
|
19
|
+
let blockSource: L2BlockSource;
|
|
20
|
+
let p2pService: Mockify<P2PService>;
|
|
21
|
+
|
|
22
|
+
beforeEach(() => {
|
|
23
|
+
txPool = {
|
|
24
|
+
addTxs: jest.fn(),
|
|
25
|
+
getTxByHash: jest.fn().mockReturnValue(undefined),
|
|
26
|
+
deleteTxs: jest.fn(),
|
|
27
|
+
getAllTxs: jest.fn().mockReturnValue([]),
|
|
28
|
+
getAllTxHashes: jest.fn().mockReturnValue([]),
|
|
29
|
+
hasTx: jest.fn().mockReturnValue(false),
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
p2pService = {
|
|
33
|
+
start: jest.fn(),
|
|
34
|
+
stop: jest.fn(),
|
|
35
|
+
propagateTx: jest.fn(),
|
|
36
|
+
settledTxs: jest.fn(),
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
blockSource = new MockBlockSource();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('can start & stop', async () => {
|
|
43
|
+
const client = new P2PClient(blockSource, txPool, p2pService);
|
|
44
|
+
expect(await client.isReady()).toEqual(false);
|
|
45
|
+
|
|
46
|
+
await client.start();
|
|
47
|
+
expect(await client.isReady()).toEqual(true);
|
|
48
|
+
|
|
49
|
+
await client.stop();
|
|
50
|
+
expect(await client.isReady()).toEqual(false);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it('adds txs to pool', async () => {
|
|
54
|
+
const client = new P2PClient(blockSource, txPool, p2pService);
|
|
55
|
+
await client.start();
|
|
56
|
+
const tx1 = MockTx();
|
|
57
|
+
const tx2 = MockTx();
|
|
58
|
+
await client.sendTx(tx1);
|
|
59
|
+
await client.sendTx(tx2);
|
|
60
|
+
|
|
61
|
+
expect(txPool.addTxs).toHaveBeenCalledTimes(2);
|
|
62
|
+
await client.stop();
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('rejects txs after being stopped', async () => {
|
|
66
|
+
const client = new P2PClient(blockSource, txPool, p2pService);
|
|
67
|
+
await client.start();
|
|
68
|
+
const tx1 = MockTx();
|
|
69
|
+
const tx2 = MockTx();
|
|
70
|
+
await client.sendTx(tx1);
|
|
71
|
+
await client.sendTx(tx2);
|
|
72
|
+
|
|
73
|
+
expect(txPool.addTxs).toHaveBeenCalledTimes(2);
|
|
74
|
+
await client.stop();
|
|
75
|
+
const tx3 = MockTx();
|
|
76
|
+
await expect(client.sendTx(tx3)).rejects.toThrow();
|
|
77
|
+
expect(txPool.addTxs).toHaveBeenCalledTimes(2);
|
|
78
|
+
});
|
|
79
|
+
});
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import { L2Block, L2BlockContext, L2BlockDownloader, L2BlockSource } from '@aztec/types';
|
|
2
|
+
import { Tx, TxHash } from '@aztec/types';
|
|
3
|
+
|
|
4
|
+
import { TxPool } from '../tx_pool/index.js';
|
|
5
|
+
import { getP2PConfigEnvVars } from '../config.js';
|
|
6
|
+
import { createDebugLogger } from '@aztec/foundation/log';
|
|
7
|
+
import { P2PService } from '../service/service.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Enum defining the possible states of the p2p client.
|
|
11
|
+
*/
|
|
12
|
+
export enum P2PClientState {
|
|
13
|
+
IDLE,
|
|
14
|
+
SYNCHING,
|
|
15
|
+
RUNNING,
|
|
16
|
+
STOPPED,
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The synchronisation status of the P2P client.
|
|
21
|
+
*/
|
|
22
|
+
export interface P2PSyncState {
|
|
23
|
+
/**
|
|
24
|
+
* The current state of the p2p client.
|
|
25
|
+
*/
|
|
26
|
+
state: P2PClientState;
|
|
27
|
+
/**
|
|
28
|
+
* The block number that the p2p client is synced to.
|
|
29
|
+
*/
|
|
30
|
+
syncedToL2Block: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Interface of a P2P client.
|
|
35
|
+
**/
|
|
36
|
+
export interface P2P {
|
|
37
|
+
/**
|
|
38
|
+
* Verifies the 'tx' and, if valid, adds it to local tx pool and forwards it to other peers.
|
|
39
|
+
**/
|
|
40
|
+
sendTx(tx: Tx): Promise<void>;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Deletes 'txs' from the pool, given hashes.
|
|
44
|
+
* NOT used if we use sendTx as reconcileTxPool will handle this.
|
|
45
|
+
**/
|
|
46
|
+
deleteTxs(txHashes: TxHash[]): Promise<void>;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Returns all transactions in the transaction pool.
|
|
50
|
+
* @returns An array of Txs.
|
|
51
|
+
*/
|
|
52
|
+
getTxs(): Promise<Tx[]>;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Returns a transaction in the transaction pool by its hash.
|
|
56
|
+
* @returns A single tx or undefined.
|
|
57
|
+
*/
|
|
58
|
+
getTxByhash(txHash: TxHash): Promise<Tx | undefined>;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Starts the p2p client.
|
|
62
|
+
* @returns A promise signalling the completion of the block sync.
|
|
63
|
+
*/
|
|
64
|
+
start(): Promise<void>;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Stops the p2p client.
|
|
68
|
+
* @returns A promise signalling the completion of the stop process.
|
|
69
|
+
*/
|
|
70
|
+
stop(): Promise<void>;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Indicates if the p2p client is ready for transaction submission.
|
|
74
|
+
* @returns A boolean flag indicating readiness.
|
|
75
|
+
*/
|
|
76
|
+
isReady(): Promise<boolean>;
|
|
77
|
+
|
|
78
|
+
/*
|
|
79
|
+
* Returns the current status of the p2p client.
|
|
80
|
+
*/
|
|
81
|
+
getStatus(): Promise<P2PSyncState>;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The P2P client implementation.
|
|
86
|
+
*/
|
|
87
|
+
export class P2PClient implements P2P {
|
|
88
|
+
/**
|
|
89
|
+
* L2 Block download that p2p client uses to stay in sync with latest blocks.
|
|
90
|
+
*/
|
|
91
|
+
private blockDownloader: L2BlockDownloader;
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Property that indicates whether the client is running.
|
|
95
|
+
*/
|
|
96
|
+
private stopping = false;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The JS promise that will be running to keep the client's data in sync. Can be interrupted if the client is stopped.
|
|
100
|
+
*/
|
|
101
|
+
private runningPromise!: Promise<void>;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Store the ID of the latest block the client has synced to.
|
|
105
|
+
*/
|
|
106
|
+
private currentL2BlockNum = 0;
|
|
107
|
+
|
|
108
|
+
private currentState = P2PClientState.IDLE;
|
|
109
|
+
private syncPromise = Promise.resolve();
|
|
110
|
+
private latestBlockNumberAtStart = -1;
|
|
111
|
+
private syncResolve?: () => void = undefined;
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* In-memory P2P client constructor.
|
|
115
|
+
* @param l2BlockSource - P2P client's source for fetching existing block data.
|
|
116
|
+
* @param txPool - The client's instance of a transaction pool. Defaults to in-memory implementation.
|
|
117
|
+
* @param p2pService - The concrete instance of p2p networking to use.
|
|
118
|
+
* @param log - A logger.
|
|
119
|
+
*/
|
|
120
|
+
constructor(
|
|
121
|
+
private l2BlockSource: L2BlockSource,
|
|
122
|
+
private txPool: TxPool,
|
|
123
|
+
private p2pService: P2PService,
|
|
124
|
+
private log = createDebugLogger('aztec:p2p'),
|
|
125
|
+
) {
|
|
126
|
+
const { checkInterval, l2QueueSize } = getP2PConfigEnvVars();
|
|
127
|
+
this.blockDownloader = new L2BlockDownloader(l2BlockSource, l2QueueSize, checkInterval);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Starts the P2P client.
|
|
132
|
+
* @returns An empty promise signalling the synching process.
|
|
133
|
+
*/
|
|
134
|
+
public async start() {
|
|
135
|
+
if (this.currentState === P2PClientState.STOPPED) {
|
|
136
|
+
throw new Error('P2P client already stopped');
|
|
137
|
+
}
|
|
138
|
+
if (this.currentState !== P2PClientState.IDLE) {
|
|
139
|
+
return this.syncPromise;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// get the current latest block number
|
|
143
|
+
this.latestBlockNumberAtStart = await this.l2BlockSource.getBlockHeight();
|
|
144
|
+
|
|
145
|
+
const blockToDownloadFrom = this.currentL2BlockNum + 1;
|
|
146
|
+
|
|
147
|
+
// if there are blocks to be retrieved, go to a synching state
|
|
148
|
+
if (blockToDownloadFrom <= this.latestBlockNumberAtStart) {
|
|
149
|
+
this.setCurrentState(P2PClientState.SYNCHING);
|
|
150
|
+
this.syncPromise = new Promise(resolve => {
|
|
151
|
+
this.syncResolve = resolve;
|
|
152
|
+
});
|
|
153
|
+
this.log(`Starting sync from ${blockToDownloadFrom}, latest block ${this.latestBlockNumberAtStart}`);
|
|
154
|
+
} else {
|
|
155
|
+
// if no blocks to be retrieved, go straight to running
|
|
156
|
+
this.setCurrentState(P2PClientState.RUNNING);
|
|
157
|
+
this.syncPromise = Promise.resolve();
|
|
158
|
+
await this.p2pService.start();
|
|
159
|
+
this.log(`Next block ${blockToDownloadFrom} already beyond latest block at ${this.latestBlockNumberAtStart}`);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// start looking for further blocks
|
|
163
|
+
const blockProcess = async () => {
|
|
164
|
+
while (!this.stopping) {
|
|
165
|
+
const blocks = await this.blockDownloader.getL2Blocks();
|
|
166
|
+
await this.handleL2Blocks(blocks);
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
this.runningPromise = blockProcess();
|
|
170
|
+
this.blockDownloader.start(blockToDownloadFrom);
|
|
171
|
+
this.log(`Started block downloader from block ${blockToDownloadFrom}`);
|
|
172
|
+
return this.syncPromise;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Allows consumers to stop the instance of the P2P client.
|
|
177
|
+
* 'ready' will now return 'false' and the running promise that keeps the client synced is interrupted.
|
|
178
|
+
*/
|
|
179
|
+
public async stop() {
|
|
180
|
+
this.log('Stopping p2p client...');
|
|
181
|
+
this.stopping = true;
|
|
182
|
+
await this.p2pService.stop();
|
|
183
|
+
await this.blockDownloader.stop();
|
|
184
|
+
await this.runningPromise;
|
|
185
|
+
this.setCurrentState(P2PClientState.STOPPED);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Returns all transactions in the transaction pool.
|
|
190
|
+
* @returns An array of Txs.
|
|
191
|
+
*/
|
|
192
|
+
public getTxs(): Promise<Tx[]> {
|
|
193
|
+
return Promise.resolve(this.txPool.getAllTxs());
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Returns a transaction in the transaction pool by its hash.
|
|
198
|
+
* @param txHash - Hash of the transaction to look for in the pool.
|
|
199
|
+
* @returns A single tx or undefined.
|
|
200
|
+
*/
|
|
201
|
+
getTxByhash(txHash: TxHash): Promise<Tx | undefined> {
|
|
202
|
+
return Promise.resolve(this.txPool.getTxByHash(txHash));
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Verifies the 'tx' and, if valid, adds it to local tx pool and forwards it to other peers.
|
|
207
|
+
* @param tx - The tx to verify.
|
|
208
|
+
* @returns Empty promise.
|
|
209
|
+
**/
|
|
210
|
+
public async sendTx(tx: Tx): Promise<void> {
|
|
211
|
+
const ready = await this.isReady();
|
|
212
|
+
if (!ready) {
|
|
213
|
+
throw new Error('P2P client not ready');
|
|
214
|
+
}
|
|
215
|
+
await this.txPool.addTxs([tx]);
|
|
216
|
+
this.p2pService.propagateTx(tx);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Deletes the 'txs' from the pool.
|
|
221
|
+
* NOT used if we use sendTx as reconcileTxPool will handle this.
|
|
222
|
+
* @param txHashes - Hashes of the transactions to delete.
|
|
223
|
+
* @returns Empty promise.
|
|
224
|
+
**/
|
|
225
|
+
public async deleteTxs(txHashes: TxHash[]): Promise<void> {
|
|
226
|
+
const ready = await this.isReady();
|
|
227
|
+
if (!ready) {
|
|
228
|
+
throw new Error('P2P client not ready');
|
|
229
|
+
}
|
|
230
|
+
this.txPool.deleteTxs(txHashes);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Public function to check if the p2p client is fully synced and ready to receive txs.
|
|
235
|
+
* @returns True if the P2P client is ready to receive txs.
|
|
236
|
+
*/
|
|
237
|
+
public isReady() {
|
|
238
|
+
return Promise.resolve(this.currentState === P2PClientState.RUNNING);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Public function to check the latest block number that the P2P client is synced to.
|
|
243
|
+
* @returns Block number of latest L2 Block we've synced with.
|
|
244
|
+
*/
|
|
245
|
+
public getSyncedBlockNum() {
|
|
246
|
+
return this.currentL2BlockNum;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Method to check the status the p2p client.
|
|
251
|
+
* @returns Information about p2p client status: state & syncedToBlockNum.
|
|
252
|
+
*/
|
|
253
|
+
public getStatus(): Promise<P2PSyncState> {
|
|
254
|
+
return Promise.resolve({
|
|
255
|
+
state: this.currentState,
|
|
256
|
+
syncedToL2Block: this.currentL2BlockNum,
|
|
257
|
+
} as P2PSyncState);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Internal method that uses the provided blocks to check against the client's tx pool.
|
|
262
|
+
* @param blocks - A list of existing blocks with txs that the P2P client needs to ensure the tx pool is reconciled with.
|
|
263
|
+
* @returns Empty promise.
|
|
264
|
+
*/
|
|
265
|
+
private reconcileTxPool(blocks: L2Block[]): Promise<void> {
|
|
266
|
+
for (let i = 0; i < blocks.length; i++) {
|
|
267
|
+
const blockContext = new L2BlockContext(blocks[i]);
|
|
268
|
+
const txHashes = blockContext.getTxHashes();
|
|
269
|
+
this.txPool.deleteTxs(txHashes);
|
|
270
|
+
this.p2pService.settledTxs(txHashes);
|
|
271
|
+
}
|
|
272
|
+
return Promise.resolve();
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Method for processing new blocks.
|
|
277
|
+
* @param blocks - A list of existing blocks with txs that the P2P client needs to ensure the tx pool is reconciled with.
|
|
278
|
+
* @returns Empty promise.
|
|
279
|
+
*/
|
|
280
|
+
private async handleL2Blocks(blocks: L2Block[]): Promise<void> {
|
|
281
|
+
if (!blocks.length) {
|
|
282
|
+
return Promise.resolve();
|
|
283
|
+
}
|
|
284
|
+
await this.reconcileTxPool(blocks);
|
|
285
|
+
this.currentL2BlockNum = blocks[blocks.length - 1].number;
|
|
286
|
+
this.log(`Synched to block ${this.currentL2BlockNum}`);
|
|
287
|
+
if (this.currentState === P2PClientState.SYNCHING && this.currentL2BlockNum >= this.latestBlockNumberAtStart) {
|
|
288
|
+
this.setCurrentState(P2PClientState.RUNNING);
|
|
289
|
+
if (this.syncResolve !== undefined) {
|
|
290
|
+
this.syncResolve();
|
|
291
|
+
await this.p2pService.start();
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Method to set the value of the current state.
|
|
298
|
+
* @param newState - New state value.
|
|
299
|
+
*/
|
|
300
|
+
private setCurrentState(newState: P2PClientState) {
|
|
301
|
+
this.currentState = newState;
|
|
302
|
+
this.log(`Moved to state ${P2PClientState[this.currentState]}`);
|
|
303
|
+
}
|
|
304
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* P2P client configuration values.
|
|
3
|
+
*/
|
|
4
|
+
export interface P2PConfig {
|
|
5
|
+
/**
|
|
6
|
+
* A flag dictating whether the P2P subsystem should be enabled.
|
|
7
|
+
*/
|
|
8
|
+
p2pEnabled: boolean;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The frequency in which to check.
|
|
12
|
+
*/
|
|
13
|
+
checkInterval: number;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Size of queue of L2 blocks to store.
|
|
17
|
+
*/
|
|
18
|
+
l2QueueSize: number;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The tcp port on which the P2P service should listen for connections.
|
|
22
|
+
*/
|
|
23
|
+
tcpListenPort: number;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The tcp IP on which the P2P service should listen for connections.
|
|
27
|
+
*/
|
|
28
|
+
tcpListenIp: string;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* An optional peer id private key. If blank, will generate a random key.
|
|
32
|
+
*/
|
|
33
|
+
peerIdPrivateKey?: string;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A list of bootstrap peers to connect to.
|
|
37
|
+
*/
|
|
38
|
+
bootstrapNodes: string[];
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Protocol identifier for transaction gossiping.
|
|
42
|
+
*/
|
|
43
|
+
transactionProtocol: string;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Hostname to announce.
|
|
47
|
+
*/
|
|
48
|
+
announceHostname?: string;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Port to announce.
|
|
52
|
+
*/
|
|
53
|
+
announcePort?: number;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Optional specification to run as a server node.
|
|
57
|
+
*/
|
|
58
|
+
serverMode: boolean;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Whether to enable NAT from libp2p (ignored for bootstrap node).
|
|
62
|
+
*/
|
|
63
|
+
enableNat?: boolean;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The minimum number of peers (a peer count below this will cause the node to look for more peers)
|
|
67
|
+
*/
|
|
68
|
+
minPeerCount: number;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The maximum number of peers (a peer count above this will cause the node to refuse connection attempts)
|
|
72
|
+
*/
|
|
73
|
+
maxPeerCount: number;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Gets the config values for p2p client from environment variables.
|
|
78
|
+
* @returns The config values for p2p client.
|
|
79
|
+
*/
|
|
80
|
+
export function getP2PConfigEnvVars(): P2PConfig {
|
|
81
|
+
const {
|
|
82
|
+
P2P_ENABLED,
|
|
83
|
+
P2P_CHECK_INTERVAL,
|
|
84
|
+
P2P_L2_BLOCK_QUEUE_SIZE,
|
|
85
|
+
P2P_TCP_LISTEN_PORT,
|
|
86
|
+
P2P_TCP_LISTEN_IP,
|
|
87
|
+
PEER_ID_PRIVATE_KEY,
|
|
88
|
+
BOOTSTRAP_NODES,
|
|
89
|
+
P2P_ANNOUNCE_HOSTNAME,
|
|
90
|
+
P2P_ANNOUNCE_PORT,
|
|
91
|
+
P2P_SERVER,
|
|
92
|
+
P2P_NAT_ENABLED,
|
|
93
|
+
P2P_MIN_PEERS,
|
|
94
|
+
P2P_MAX_PEERS,
|
|
95
|
+
} = process.env;
|
|
96
|
+
const envVars: P2PConfig = {
|
|
97
|
+
p2pEnabled: P2P_ENABLED === 'true',
|
|
98
|
+
checkInterval: P2P_CHECK_INTERVAL ? +P2P_CHECK_INTERVAL : 100,
|
|
99
|
+
l2QueueSize: P2P_L2_BLOCK_QUEUE_SIZE ? +P2P_L2_BLOCK_QUEUE_SIZE : 1000,
|
|
100
|
+
tcpListenPort: P2P_TCP_LISTEN_PORT ? +P2P_TCP_LISTEN_PORT : 0,
|
|
101
|
+
tcpListenIp: P2P_TCP_LISTEN_IP ? P2P_TCP_LISTEN_IP : '0.0.0.0',
|
|
102
|
+
peerIdPrivateKey: PEER_ID_PRIVATE_KEY,
|
|
103
|
+
bootstrapNodes: BOOTSTRAP_NODES ? BOOTSTRAP_NODES.split(',') : [],
|
|
104
|
+
transactionProtocol: '',
|
|
105
|
+
announceHostname: P2P_ANNOUNCE_HOSTNAME,
|
|
106
|
+
announcePort: P2P_ANNOUNCE_PORT ? +P2P_ANNOUNCE_PORT : undefined,
|
|
107
|
+
serverMode: P2P_SERVER === 'true',
|
|
108
|
+
enableNat: P2P_NAT_ENABLED === 'true',
|
|
109
|
+
minPeerCount: P2P_MIN_PEERS ? +P2P_MIN_PEERS : 10,
|
|
110
|
+
maxPeerCount: P2P_MAX_PEERS ? +P2P_MAX_PEERS : 100,
|
|
111
|
+
};
|
|
112
|
+
return envVars;
|
|
113
|
+
}
|