-
Notifications
You must be signed in to change notification settings - Fork 73
/
txpool.ts
285 lines (236 loc) · 8 KB
/
txpool.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
import { EventEmitter } from 'eventemitter3'
import { GenericExtrinsic } from '@polkadot/types'
import { HexString } from '@polkadot/util/types'
import { hexToU8a } from '@polkadot/util/hex/toU8a'
import _ from 'lodash'
import { Blockchain } from './index.js'
import { Deferred, defer } from '../utils/index.js'
import { InherentProvider } from './inherent/index.js'
import { buildBlock } from './block-builder.js'
import { defaultLogger, truncate } from '../logger.js'
const logger = defaultLogger.child({ name: 'txpool' })
export const APPLY_EXTRINSIC_ERROR = 'TxPool::ApplyExtrinsicError'
export enum BuildBlockMode {
/** One block per batch (default) */
Batch = 'Batch',
/** One block per tx */
Instant = 'Instant',
/** Only build when triggered */
Manual = 'Manual',
}
export interface DownwardMessage {
sentAt: number
msg: HexString
}
export interface HorizontalMessage {
sentAt: number
data: HexString
}
export interface BuildBlockParams {
downwardMessages: DownwardMessage[]
upwardMessages: Record<number, HexString[]>
horizontalMessages: Record<number, HorizontalMessage[]>
transactions: HexString[]
unsafeBlockHeight?: number
}
export class TxPool {
readonly #chain: Blockchain
readonly #pool: { extrinsic: HexString; signer: string }[] = []
readonly #ump: Record<number, HexString[]> = {}
readonly #dmp: DownwardMessage[] = []
readonly #hrmp: Record<number, HorizontalMessage[]> = {}
#mode: BuildBlockMode
readonly #inherentProviders: InherentProvider[]
readonly #pendingBlocks: { params: BuildBlockParams; deferred: Deferred<void> }[] = []
readonly event = new EventEmitter()
#isBuilding = false
constructor(chain: Blockchain, inherentProviders: InherentProvider[], mode: BuildBlockMode = BuildBlockMode.Batch) {
this.#chain = chain
this.#mode = mode
this.#inherentProviders = inherentProviders
}
get pendingExtrinsics(): HexString[] {
return this.#pool.map(({ extrinsic }) => extrinsic)
}
get ump(): Record<number, HexString[]> {
return this.#ump
}
get dmp(): DownwardMessage[] {
return this.#dmp
}
get hrmp(): Record<number, HorizontalMessage[]> {
return this.#hrmp
}
get mode(): BuildBlockMode {
return this.#mode
}
set mode(mode: BuildBlockMode) {
this.#mode = mode
}
clear() {
this.#pool.length = 0
for (const id of Object.keys(this.#ump)) {
delete this.#ump[id]
}
this.#dmp.length = 0
for (const id of Object.keys(this.#hrmp)) {
delete this.#hrmp[id]
}
}
pendingExtrinsicsBy(address: string): HexString[] {
return this.#pool.filter(({ signer }) => signer === address).map(({ extrinsic }) => extrinsic)
}
async submitExtrinsic(extrinsic: HexString) {
logger.debug({ extrinsic: truncate(extrinsic) }, 'submit extrinsic')
this.#pool.push({ extrinsic, signer: await this.#getSigner(extrinsic) })
this.#maybeBuildBlock()
}
async #getSigner(extrinsic: HexString) {
const registry = await this.#chain.head.registry
const tx = registry.createType<GenericExtrinsic>('GenericExtrinsic', extrinsic)
return tx.signer.toString()
}
submitUpwardMessages(id: number, ump: HexString[]) {
logger.debug({ id, ump: truncate(ump) }, 'submit upward messages')
if (!this.#ump[id]) {
this.#ump[id] = []
}
this.#ump[id].push(...ump)
this.#maybeBuildBlock()
}
submitDownwardMessages(dmp: DownwardMessage[]) {
logger.debug({ dmp: truncate(dmp) }, 'submit downward messages')
this.#dmp.push(...dmp)
this.#maybeBuildBlock()
}
submitHorizontalMessages(id: number, hrmp: HorizontalMessage[]) {
logger.debug({ id, hrmp: truncate(hrmp) }, 'submit horizontal messages')
if (!this.#hrmp[id]) {
this.#hrmp[id] = []
}
this.#hrmp[id].push(...hrmp)
this.#maybeBuildBlock()
}
#maybeBuildBlock() {
switch (this.#mode) {
case BuildBlockMode.Batch:
this.#batchBuildBlock()
break
case BuildBlockMode.Instant:
this.buildBlock()
break
case BuildBlockMode.Manual:
// does nothing
break
}
}
#batchBuildBlock = _.debounce(this.buildBlock, 100, { maxWait: 1000 })
async buildBlockWithParams(params: BuildBlockParams) {
this.#pendingBlocks.push({
params,
deferred: defer<void>(),
})
this.#buildBlockIfNeeded()
await this.upcomingBlocks()
}
async buildBlock(params?: Partial<BuildBlockParams>) {
const transactions = params?.transactions || this.#pool.splice(0).map(({ extrinsic }) => extrinsic)
const upwardMessages = params?.upwardMessages || { ...this.#ump }
const downwardMessages = params?.downwardMessages || this.#dmp.splice(0)
const horizontalMessages = params?.horizontalMessages || { ...this.#hrmp }
const unsafeBlockHeight = params?.unsafeBlockHeight
if (!params?.upwardMessages) {
for (const id of Object.keys(this.#ump)) {
delete this.#ump[id]
}
}
if (!params?.horizontalMessages) {
for (const id of Object.keys(this.#hrmp)) {
delete this.#hrmp[id]
}
}
try {
await this.buildBlockWithParams({
transactions,
upwardMessages,
downwardMessages,
horizontalMessages,
unsafeBlockHeight,
})
// with the latest message queue, messages are processed in the upcoming block
if (!this.#chain.processQueuedMessages) return
// if block was built without horizontal or downward messages then skip
if (_.isEmpty(horizontalMessages) && _.isEmpty(downwardMessages)) return
// messageQueue.bookStateFor
const prefix = '0xb8753e9383841da95f7b8871e5de326954e062a2cf8df68178ee2e5dbdf00bff'
const meta = await this.#chain.head.meta
const keys = await this.#chain.head.getKeysPaged({ prefix, pageSize: 1000 })
for (const key of keys) {
const rawValue = await this.#chain.head.get(key)
if (!rawValue) continue
const message = meta.registry.createType('PalletMessageQueueBookState', hexToU8a(rawValue)).toJSON() as any
if (message.size > 0) {
logger.info('Queued messages detected, building a new block')
// build a new block to process the queued messages
await this.#chain.newBlock()
return
}
}
} catch (err) {
logger.error({ err }, 'build block failed')
}
}
async upcomingBlocks() {
const count = this.#pendingBlocks.length
if (count > 0) {
await this.#pendingBlocks[count - 1].deferred.promise
}
return count
}
async #buildBlockIfNeeded() {
if (this.#isBuilding) return
if (this.#pendingBlocks.length === 0) return
this.#isBuilding = true
try {
await this.#buildBlock()
} finally {
this.#isBuilding = false
}
this.#buildBlockIfNeeded()
}
async #buildBlock() {
await this.#chain.api.isReady
const pending = this.#pendingBlocks[0]
if (!pending) {
throw new Error('Unreachable')
}
const { params, deferred } = pending
logger.trace({ params }, 'build block')
const [newBlock, pendingExtrinsics] = await buildBlock(this.#chain.head, this.#inherentProviders, params, {
onApplyExtrinsicError: (extrinsic, error) => {
this.event.emit(APPLY_EXTRINSIC_ERROR, [extrinsic, error])
},
onPhaseApplied:
logger.level.toLowerCase() === 'trace'
? (phase, resp) => {
switch (phase) {
case 'initialize':
logger.trace(truncate(resp.storageDiff), 'Initialize block')
break
case 'finalize':
logger.trace(truncate(resp.storageDiff), 'Finalize block')
break
default:
logger.trace(truncate(resp.storageDiff), `Apply extrinsic ${phase}`)
}
}
: undefined,
})
for (const extrinsic of pendingExtrinsics) {
this.#pool.push({ extrinsic, signer: await this.#getSigner(extrinsic) })
}
await this.#chain.onNewBlock(newBlock)
this.#pendingBlocks.shift()
deferred.resolve()
}
}