forked from hive-engine/steemsmartcontracts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Block.js
291 lines (248 loc) · 11.8 KB
/
Block.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
const SHA256 = require('crypto-js/sha256');
const enchex = require('crypto-js/enc-hex');
const log = require('loglevel');
const { CONSTANTS } = require('../libs/Constants');
const { SmartContracts } = require('./SmartContracts');
const { Transaction } = require('../libs/Transaction');
const { setupContractPayload } = require('../libs/util/contractUtil');
const revertCommentsContractPayload = setupContractPayload('comments', './contracts/revert/comments_minify_20211027.js');
class Block {
constructor(timestamp, refHiveBlockNumber, refHiveBlockId, prevRefHiveBlockId, transactions, previousBlockNumber, previousHash = '', previousDatabaseHash = '') {
this.blockNumber = previousBlockNumber + 1;
this.refHiveBlockNumber = refHiveBlockNumber;
this.refHiveBlockId = refHiveBlockId;
this.prevRefHiveBlockId = prevRefHiveBlockId;
this.previousHash = previousHash;
this.previousDatabaseHash = previousDatabaseHash;
this.timestamp = timestamp;
this.transactions = transactions;
this.virtualTransactions = [];
this.hash = this.calculateHash();
this.databaseHash = '';
this.merkleRoot = '';
this.round = null;
this.roundHash = '';
this.witness = '';
this.signingKey = '';
this.roundSignature = '';
}
// calculate the hash of the block
calculateHash() {
return SHA256(
this.previousHash
+ this.previousDatabaseHash
+ this.blockNumber.toString()
+ this.refHiveBlockNumber.toString()
+ this.refHiveBlockId
+ this.prevRefHiveBlockId
+ this.timestamp
+ this.merkleRoot
+ JSON.stringify(this.transactions) // eslint-disable-line
)
.toString(enchex);
}
// calculate the Merkle root of the block ((#TA + #TB) + (#TC + #TD) )
calculateMerkleRoot(transactions) {
if (transactions.length <= 0) return '';
const tmpTransactions = transactions.slice(0, transactions.length);
const newTransactions = [];
const nbTransactions = tmpTransactions.length;
for (let index = 0; index < nbTransactions; index += 2) {
const left = tmpTransactions[index].hash;
const right = index + 1 < nbTransactions ? tmpTransactions[index + 1].hash : left;
const leftDbHash = tmpTransactions[index].databaseHash;
const rightDbHash = index + 1 < nbTransactions
? tmpTransactions[index + 1].databaseHash
: leftDbHash;
newTransactions.push({
hash: SHA256(left + right).toString(enchex),
databaseHash: SHA256(leftDbHash + rightDbHash).toString(enchex),
});
}
if (newTransactions.length === 1) {
return {
hash: newTransactions[0].hash,
databaseHash: newTransactions[0].databaseHash,
};
}
return this.calculateMerkleRoot(newTransactions);
}
async blockAdjustments(database) {
if (this.refHiveBlockNumber === 43447729 || this.refHiveBlockNumber === 44870101) {
// main node skipped this due to space issue
this.transactions = [];
}
// To keep in sync with primary node history after hack
if (this.refHiveBlockNumber === 50352631) {
const tokenBalances = database.database.collection('tokens_balances');
await tokenBalances.updateOne({ _id: 8416 }, { $set: { account: 'nightowl1', balance: '1.05000000' } });
await tokenBalances.updateOne({ _id: 21725 }, { $set: { account: 'nightowl1', balance: '1010.00000000' } });
} else if (this.refHiveBlockNumber === 50354478) {
const tokenBalances = database.database.collection('tokens_balances');
await tokenBalances.updateOne({ _id: 8416 }, { $set: { account: 'nightowl1', balance: '0.50000000' } });
} else if (this.refHiveBlockNumber === 50354625) {
const tokenBalances = database.database.collection('tokens_balances');
await tokenBalances.updateOne({ _id: 21725 }, { $set: { account: 'nightowl1', balance: '500000.00000000' } });
}
// Comments contract causing issues and needs to be reverted. put at beginning
if (this.refHiveBlockNumber === 58637536) {
this.transactions.unshift(new Transaction(this.blockNumber, 'FIXTX_COMMENTS_REVERT', CONSTANTS.HIVE_ENGINE_ACCOUNT, 'contract', 'update', JSON.stringify(revertCommentsContractPayload)));
}
}
/**
* Try cleaning up blocks after every 100 blocks if node is a light node.
* @param database
* @returns {Promise<void>}
*/
async cleanupLightNode(database) {
if (this.blockNumber % 100 === 0) {
await database.cleanupLightNode();
}
}
// produce the block (deploy a smart contract or execute a smart contract)
async produceBlock(database, jsVMTimeout, mainBlock) {
await this.cleanupLightNode(database);
await this.blockAdjustments(database);
const nbTransactions = this.transactions.length;
let currentDatabaseHash = this.previousDatabaseHash;
let relIndex = 0;
const allowCommentContract = this.refHiveBlockNumber > 54560500;
for (let i = 0; i < nbTransactions; i += 1) {
const transaction = this.transactions[i];
log.info('Processing tx ', transaction);
await this.processTransaction(database, jsVMTimeout, transaction, currentDatabaseHash); // eslint-disable-line
currentDatabaseHash = transaction.databaseHash;
if ((transaction.contract !== 'comments' || allowCommentContract) || transaction.logs === '{}') {
if (mainBlock && currentDatabaseHash !== mainBlock.transactions[relIndex].databaseHash) {
log.warn(mainBlock.transactions[relIndex]); // eslint-disable-line no-console
log.warn(transaction); // eslint-disable-line no-console
throw new Error('tx hash mismatch with api');
}
relIndex += 1;
}
}
// remove comment, comment_options and votes if not relevant
this.transactions = this.transactions.filter(value => (value.contract !== 'comments' || allowCommentContract) || value.logs === '{}');
// handle virtual transactions
const virtualTransactions = [];
// reset in case block processing loops
this.virtualTransactions = [];
// use contracts_config contractTicks to trigger ticking contract actions.
const contractsConfig = await database.getContractsConfig();
for (let i = 0; i < contractsConfig.contractTicks.length; i += 1) {
const contractTick = contractsConfig.contractTicks[i];
if (this.refHiveBlockNumber >= contractTick.startRefBlock) {
virtualTransactions.push(new Transaction(0, '', 'null', contractTick.contract, contractTick.action, ''));
}
}
if (this.refHiveBlockNumber % 1200 === 0) {
virtualTransactions.push(new Transaction(0, '', 'null', 'inflation', 'issueNewTokens', '{ "isSignedWithActiveKey": true }'));
}
relIndex = 0;
const nbVirtualTransactions = virtualTransactions.length;
for (let i = 0; i < nbVirtualTransactions; i += 1) {
const transaction = virtualTransactions[i];
transaction.refHiveBlockNumber = this.refHiveBlockNumber;
transaction.transactionId = `${this.refHiveBlockNumber}-${i}`;
await this.processTransaction(database, jsVMTimeout, transaction, currentDatabaseHash); // eslint-disable-line
currentDatabaseHash = transaction.databaseHash;
// if there are outputs in the virtual transaction we save the transaction into the block
// the "unknown error" errors are removed as they are related to a non existing action
if (transaction.logs !== '{}'
&& transaction.logs !== '{"errors":["unknown error"]}') {
let tickingAction = false;
for (let j = 0; j < contractsConfig.contractTicks.length; j += 1) {
const contractTick = contractsConfig.contractTicks[j];
if (transaction.contract === contractTick.contract
&& transaction.action === contractTick.action
&& transaction.logs === '{"errors":["contract doesn\'t exist"]}') {
tickingAction = true;
}
}
if (transaction.contract === 'inflation'
&& transaction.action === 'issueNewTokens'
&& transaction.logs === '{"errors":["contract doesn\'t exist"]}') {
// don't save logs
} else if (tickingAction) {
// don't save logs
} else {
this.virtualTransactions.push(transaction);
if (mainBlock && currentDatabaseHash
!== mainBlock.virtualTransactions[relIndex].databaseHash) {
log.warn(mainBlock.virtualTransactions[relIndex]); // eslint-disable-line no-console
log.warn(transaction); // eslint-disable-line no-console
throw new Error('tx hash mismatch with api');
}
relIndex += 1;
}
}
}
// add odd blocks, consensus appended double virtual transactions
if (this.refHiveBlockNumber === 59376574) {
this.virtualTransactions = this.virtualTransactions.concat(this.virtualTransactions);
}
if (this.transactions.length > 0 || this.virtualTransactions.length > 0) {
// calculate the merkle root of the transactions' hashes and the transactions' database hashes
const finalTransactions = this.transactions.concat(this.virtualTransactions);
const merkleRoots = this.calculateMerkleRoot(finalTransactions);
this.merkleRoot = merkleRoots.hash;
this.databaseHash = merkleRoots.databaseHash;
this.hash = this.calculateHash();
} else if (currentDatabaseHash !== this.previousDatabaseHash) {
await database.noteHashChange(this.refHiveBlockNumber);
}
}
async processTransaction(database, jsVMTimeout, transaction, currentDatabaseHash) {
const {
sender,
contract,
action,
payload,
} = transaction;
let results = null;
let newCurrentDatabaseHash = currentDatabaseHash;
// init the database hash for that transactions
database.initDatabaseHash(newCurrentDatabaseHash);
if (sender && contract && action) {
if (contract === 'contract' && (action === 'deploy' || action === 'update') && payload) {
const authorizedAccountContractDeployment = ['null', CONSTANTS.HIVE_ENGINE_ACCOUNT, CONSTANTS.HIVE_PEGGED_ACCOUNT];
if (authorizedAccountContractDeployment.includes(sender)) {
results = await SmartContracts.deploySmartContract( // eslint-disable-line
database, transaction, this.blockNumber, this.timestamp,
this.refHiveBlockId, this.prevRefHiveBlockId, jsVMTimeout,
);
} else {
results = { logs: { errors: ['the contract deployment is currently unavailable'] } };
}
} else if (contract === 'contract' && action === 'registerTick' && payload) {
const authorizedAccountTickRegister = [
CONSTANTS.HIVE_ENGINE_ACCOUNT, CONSTANTS.HIVE_PEGGED_ACCOUNT];
if (authorizedAccountTickRegister.includes(sender)) {
results = await SmartContracts.registerTick(database, transaction);
} else {
results = { logs: { errors: ['registerTick unauthorized'] } };
}
} else {
results = await SmartContracts.executeSmartContract(// eslint-disable-line
database, transaction, this.blockNumber, this.timestamp,
this.refHiveBlockId, this.prevRefHiveBlockId, jsVMTimeout,
);
}
} else {
results = { logs: { errors: ['the parameters sender, contract and action are required'] } };
}
if (results.logs && results.logs.errors && results.logs.errors.find(m => m.includes('MongoError'))) {
throw new Error(`Mongo tx error, transaction: ${JSON.stringify(transaction)}, result: ${JSON.stringify(results)}`);
}
await database.flushCache();
await database.flushContractCache();
// get the database hash
newCurrentDatabaseHash = database.getDatabaseHash();
log.info('Tx results: ', results);
transaction.addLogs(results.logs);
transaction.executedCodeHash = results.executedCodeHash || ''; // eslint-disable-line
transaction.databaseHash = newCurrentDatabaseHash; // eslint-disable-line
transaction.calculateHash();
}
}
module.exports.Block = Block;