forked from LiskArchive/lisk-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblocks.js
374 lines (344 loc) Β· 8.89 KB
/
blocks.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
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
/*
* Copyright Β© 2018 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
'use strict';
const sql = require('../sql').blocks;
const cs = {}; // Reusable ColumnSet objects
/**
* Blocks database interaction class.
*
* @class
* @memberof db.repos.blocks
* @requires db/sql
* @see Parent: {@link db.repos.blocks}
* @param {Database} db - Instance of database object from pg-promise
* @param {Object} pgp - pg-promise instance to utilize helpers
* @returns {Object} An instance of a BlocksRepository
*/
class BlocksRepository {
constructor(db, pgp) {
this.db = db;
this.pgp = pgp;
this.dbTable = 'blocks';
this.sortFields = [
'id',
'timestamp',
'height',
'previousBlock',
'totalAmount',
'totalFee',
'reward',
'numberOfTransactions',
'generatorPublicKey',
];
this.dbFields = [
'id',
'version',
'timestamp',
'height',
'previousBlock',
'numberOfTransactions',
'totalAmount',
'totalFee',
'reward',
'payloadLength',
'payloadHash',
'generatorPublicKey',
'blockSignature',
];
this.cs = cs;
if (!cs.insert) {
cs.insert = new pgp.helpers.ColumnSet(this.dbFields, {
table: this.dbTable,
});
}
}
// TODO: Merge BlocksRepository#getGenesisBlock with BlocksRepository#getGenesisBlockId
/**
* Get the genesis block.
*
* @returns {Promise}
* @todo Add description for the return value
*/
getGenesisBlock() {
return this.db.any(sql.getGenesisBlock);
}
/**
* Get genesis block by id.
*
* @param {string} id
* @returns {Promise}
* @todo Add description for the params and the return value
*/
getGenesisBlockId(id) {
// TODO: Must use a result-specific method, not .query
return this.db.query(sql.getGenesisBlockId, [id]);
}
/**
* Delete a block from database.
*
* @param {string} id
* @returns {Promise}
* @todo Add description for the params and the return value
*/
deleteBlock(id) {
return this.db.none(sql.deleteBlock, [id]);
}
/**
* Aggregate rewards for a block.
*
* @param {Object} params
* @param {string} params.generatorPublicKey
* @param {int} params.start - Start time of aggregation period
* @param {int} params.end - End time for aggregation period
* @returns {Promise}
* @todo Add description for the params and the return value
*/
aggregateBlocksReward(params) {
// TODO: Must use a result-specific method, not .query
return this.db.query(sql.aggregateBlocksReward, [
params.generatorPublicKey,
params.start,
params.end,
]);
}
/**
* Counts all blocks.
*
* @returns {Promise<number>}
* @todo Add description for the return value
*/
count() {
return this.db.one(sql.count, [], a => +a.count);
}
/**
* Search blocks in database.
*
* @param {Object} params
* @param {array} params.where
* @param {string} params.sortField
* @param {string} params.sortMethod
* @param {int} params.limit
* @param {int} params.offset
* @returns {Promise<[]>}
* Array of blocks.
*/
list(params) {
if (params.where && !Array.isArray(params.where)) {
return Promise.reject(
new TypeError('Invalid parameter "where" provided.')
);
}
return this.db.any(Queries.list, params);
}
/**
* Get sequence of blocks ids for delegates.
*
* @param {Object} params
* @param {int} params.delegates - Number of delegates
* @param {int} params.height
* @param {int} params.limit
* @returns {Promise<[]>}
* Array of blocks.
*/
getIdSequence(params) {
return this.db.any(sql.getIdSequence, params);
}
/**
* Get common block among peers.
*
* @param {Object} params
* @param {string} params.id
* @param {string} params.previousBlock
* @param {int} params.height
* @returns {Promise}
* @todo Add description for the params and the return value
*/
getCommonBlock(params) {
const query = values => {
values.comparePreviousBlock = values.previousBlock
? this.pgp.as.format('AND "previousBlock" = ${previousBlock}', values)
: '';
return sql.getCommonBlock;
};
return this.db.any(query, params);
}
// TODO: Merge BlocksRepository#getHeightByLastId with BlocksRepository#list
/**
* Get height of the block with id.
*
* @param {string} lastId - Id of the block to search
* @returns {Promise}
* @todo Add description for the return value
*/
getHeightByLastId(lastId) {
// TODO: Must use a result-specific method, not .query
return this.db.query(sql.getHeightByLastId, [lastId]);
}
/**
* Load block including transactions.
*
* @param {Object} params
* @param {string} params.id
* @param {string} params.lastId
* @param {int} params.height
* @param {int} params.limit
* @returns {Promise<[]>}
* @todo Add description for the params and the return value
*/
loadBlocksData(params) {
return this.db.any(Queries.loadBlocksData, params);
}
/**
* Load blocks including transactions with an offset and limit.
*
* @param {int} offset
* @param {int} limit
* @returns {Promise<[]>}
* List of blocks.
*/
loadBlocksOffset(offset, limit) {
return this.db.any(sql.loadBlocksOffset, [offset, limit]);
}
/**
* Load the last block including transactions.
*
* @returns {Promise}
* @todo Add description for the return value
*/
loadLastBlock() {
// TODO: Must use a result-specific method, not .query
return this.db.query(sql.loadLastBlock);
}
/**
* Load last N block ids from the database.
*
* @param {limit} - Number of blocks to load
* @todo Add @returns tag
*/
loadLastNBlockIds(limit) {
return this.db.query(sql.loadLastNBlockIds, [limit]);
}
/**
* Check if a block exits with a particular ID.
*
* @param {string} id
* @throws {QueryResultError} - If multiple rows were not expected - in the case of multiple blocks found with same id
* @returns {Promise}
* @todo Add description for the params and the return value
*/
blockExists(id) {
return this.db.oneOrNone(sql.blockExists, [id]);
}
/**
* Delete all blocks after a particular height.
*
* @param {string} id
* @returns {Promise}
*/
deleteAfterBlock(id) {
return this.db.none(sql.deleteAfterBlock, [id]);
}
/**
* Get multiple blocks to be transported to peers.
*
* @param {string} ids - Comma separated string of ids
* @returns {Promise}
* @todo Add description for the return value
*
*/
getBlocksForTransport(ids) {
// TODO: Must use a result-specific method, not .query
return this.db.query(sql.getBlocksForTransport, [ids]);
}
/**
* Insert a block to database.
*
* @param {Object} block - Attributes to be inserted, can be any of [BlocksRepo's dbFields property]{@link BlocksRepo#dbFields}
* @returns {Promise}
* @todo Add description for the return value
*/
save(block) {
const query = () => {
const saveBlock = Object.assign({}, block);
saveBlock.payloadHash = Buffer.from(block.payloadHash, 'hex');
saveBlock.generatorPublicKey = Buffer.from(
block.generatorPublicKey,
'hex'
);
saveBlock.blockSignature = Buffer.from(block.blockSignature, 'hex');
saveBlock.reward = block.reward || 0;
return this.pgp.helpers.insert(saveBlock, cs.insert);
};
return this.db.none(query);
}
}
// TODO: All these queries need to be thrown away, and use proper implementation inside corresponding methods.
/**
* Description of the object.
*
* @namespace Queries
* @memberof db.repos.blocks
*/
const Queries = {
/**
* Description of the function.
*
* @func list
* @memberof db.repos.blocks.Queries
* @param {Object} params
* @todo Add description for the function and the params
* @todo Add @returns tag
*/
list(params) {
return [
'SELECT * FROM blocks_list',
params.where && params.where.length
? `WHERE ${params.where.join(' AND ')}`
: '',
params.sortField
? `ORDER BY ${[params.sortField, params.sortMethod].join(' ')}`
: '',
'LIMIT ${limit} OFFSET ${offset}',
]
.filter(Boolean)
.join(' ');
},
/**
* Description of the function.
*
* @func loadBlocksData
* @memberof db.repos.blocks.Queries
* @param {Object} params
* @todo Add description for the function and the params
* @todo Add @returns tag
*/
loadBlocksData(params) {
var limitPart;
if (!params.id && !params.lastId) {
limitPart = 'WHERE "b_height" < ${limit}';
}
return [
'SELECT * FROM full_blocks_list',
limitPart,
params.id || params.lastId ? 'WHERE' : '',
params.id ? '"b_id" = ${id}' : '',
params.id && params.lastId ? ' AND ' : '',
params.lastId ? '"b_height" > ${height} AND "b_height" < ${limit}' : '',
'ORDER BY "b_height", "t_rowId"',
]
.filter(Boolean)
.join(' ');
},
};
module.exports = BlocksRepository;