Skip to content

Commit 70745b7

Browse files
authored
Merge pull request #170 from ainblockchain/develop
Release v0.5.1
2 parents 9646047 + 0331bc7 commit 70745b7

40 files changed

+2440
-911
lines changed

blockchain/block.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ const zipper = require('zip-local');
33
const sizeof = require('object-sizeof');
44
const ainUtil = require('@ainblockchain/ain-util');
55
const logger = require('../logger')('BLOCK');
6-
const ChainUtil = require('../chain-util');
6+
const ChainUtil = require('../common/chain-util');
77
const Transaction = require('../tx-pool/transaction');
88
const StateNode = require('../db/state-node');
99
const DB = require('../db');
@@ -18,7 +18,7 @@ const {
1818
AccountProperties,
1919
ProofProperties,
2020
StateVersions,
21-
} = require('../constants');
21+
} = require('../common/constants');
2222
const BlockFilePatterns = require('./block-file-patterns');
2323

2424
class Block {

blockchain/index.js

Lines changed: 16 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ const naturalSort = require('node-natural-sort');
77
const logger = require('../logger')('BLOCKCHAIN');
88
const {Block} = require('./block');
99
const BlockFilePatterns = require('./block-file-patterns');
10-
const {BLOCKCHAINS_DIR} = require('../constants');
10+
const {BLOCKCHAINS_DIR} = require('../common/constants');
1111
const CHAIN_SUBSECT_LENGTH = 20;
1212
const ON_MEM_CHAIN_LENGTH = 20;
1313

@@ -16,7 +16,6 @@ class Blockchain {
1616
// Finalized chain
1717
this.chain = [];
1818
this.blockchainDir = blockchainDir;
19-
this.syncedAfterStartup = false;
2019
}
2120

2221
init(isFirstNode) {
@@ -175,13 +174,13 @@ class Blockchain {
175174
return false;
176175
}
177176
// TODO (lia): Check if the tx nonces are correct.
178-
return Blockchain.isValidChainSubsection(chain);
177+
return Blockchain.isValidChainSegment(chain);
179178
}
180179

181-
static isValidChainSubsection(chainSubSection) {
182-
for (let i = 1; i < chainSubSection.length; i++) {
183-
const block = chainSubSection[i];
184-
const lastBlock = Block.parse(chainSubSection[i - 1]);
180+
static isValidChainSegment(chainSegment) {
181+
for (let i = 1; i < chainSegment.length; i++) {
182+
const block = chainSegment[i];
183+
const lastBlock = Block.parse(chainSegment[i - 1]);
185184
if (block.last_hash !== lastBlock.hash || !Block.validateHashes(block)) {
186185
return false;
187186
}
@@ -253,43 +252,19 @@ class Blockchain {
253252
return [this.lastBlock()];
254253
}
255254

256-
const chainSubSection = [];
255+
const chainSegment = [];
257256
blockFiles.forEach((blockFile) => {
258-
chainSubSection.push(Block.loadBlock(blockFile));
257+
chainSegment.push(Block.loadBlock(blockFile));
259258
});
260-
return chainSubSection.length > 0 ? chainSubSection : [];
259+
return chainSegment.length > 0 ? chainSegment : [];
261260
}
262261

263-
merge(chainSubSection, db) {
264-
// Call to shift here is important as it removes the first element from the list !!
262+
merge(chainSegment, db) {
265263
logger.info(`Last block number before merge: ${this.lastBlockNumber()}`);
266-
if (!chainSubSection || chainSubSection.length === 0) {
267-
logger.info(`Empty chain sub section`);
268-
if (!this.syncedAfterStartup) {
269-
// Regard this situation as if you're synced.
270-
// TODO (lia): ask the tracker server for another peer.
271-
this.syncedAfterStartup = true;
272-
}
273-
return false;
274-
}
275-
if (chainSubSection[chainSubSection.length - 1].number < this.lastBlockNumber()) {
276-
logger.info(`Received chain is of lower block number than current last block number`);
277-
return false;
278-
}
279-
if (chainSubSection[chainSubSection.length - 1].number === this.lastBlockNumber()) {
280-
logger.info(`Received chain is at the same block number`);
281-
if (!this.syncedAfterStartup) {
282-
// Regard this situation as if you're synced.
283-
// TODO (lia): ask the tracker server for another peer.
284-
this.syncedAfterStartup = true;
285-
}
286-
return false;
287-
}
288-
289-
const firstBlock = Block.parse(chainSubSection[0]);
264+
const firstBlock = Block.parse(chainSegment[0]);
290265
const lastBlockHash = this.lastBlockNumber() >= 0 ? this.lastBlock().hash : null;
291266
const overlap = lastBlockHash ?
292-
chainSubSection.filter((block) => block.number === this.lastBlockNumber()) : null;
267+
chainSegment.filter((block) => block.number === this.lastBlockNumber()) : null;
293268
const overlappingBlock = overlap ? overlap[0] : null;
294269
if (lastBlockHash) {
295270
// Case 1: Not a cold start.
@@ -306,12 +281,12 @@ class Blockchain {
306281
return false;
307282
}
308283
}
309-
if (!Blockchain.isValidChainSubsection(chainSubSection)) {
310-
logger.error(`Invalid chain subsection`);
284+
if (!Blockchain.isValidChainSegment(chainSegment)) {
285+
logger.error(`Invalid chain segment`);
311286
return false;
312287
}
313-
for (let i = 0; i < chainSubSection.length; i++) {
314-
const block = chainSubSection[i];
288+
for (let i = 0; i < chainSegment.length; i++) {
289+
const block = chainSegment[i];
315290

316291
if (block.number <= this.lastBlockNumber()) {
317292
continue;

client/index.js

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,13 @@ const jayson = require('jayson');
88
const logger = require('../logger')('CLIENT');
99
const BlockchainNode = require('../node');
1010
const P2pServer = require('../server');
11-
const ChainUtil = require('../chain-util');
12-
const {PORT, PROTOCOL_VERSIONS, WriteDbOperations, TransactionStatus} = require('../constants');
11+
const ChainUtil = require('../common/chain-util');
12+
const {
13+
PORT,
14+
PROTOCOL_VERSIONS,
15+
WriteDbOperations,
16+
TransactionStatus
17+
} = require('../common/constants');
1318
const {ConsensusStatus} = require('../consensus/constants');
1419
const CURRENT_PROTOCOL_VERSION = require('../package.json').version;
1520

@@ -244,6 +249,14 @@ app.post('/batch', (req, res, next) => {
244249
.end();
245250
});
246251

252+
app.get('/node_status', (req, res, next) => {
253+
const result = node.status;
254+
res.status(200)
255+
.set('Content-Type', 'application/json')
256+
.send({code: 0, result})
257+
.end();
258+
});
259+
247260
app.get('/blocks', (req, res, next) => {
248261
const blockEnd = node.bc.lastBlockNumber() + 1;
249262
const blockBegin = Math.max(blockEnd - MAX_BLOCKS, 0);
@@ -316,7 +329,7 @@ app.get('/protocol_versions', (req, res) => {
316329
app.get('/state_versions', (req, res) => {
317330
const result = {
318331
version_list: node.stateManager.getVersionList(),
319-
finalized_version: node.stateManager.getFinalizedVersion(),
332+
final_version: node.stateManager.getFinalVersion(),
320333
};
321334
res.status(200)
322335
.set('Content-Type', 'application/json')
@@ -325,8 +338,8 @@ app.get('/state_versions', (req, res) => {
325338
});
326339

327340
// TODO(seo): Support for subtree dumping (i.e. with ref path).
328-
app.get('/dump_finalized_version', (req, res) => {
329-
const result = node.dumpFinalizedVersion(true);
341+
app.get('/dump_final_version', (req, res) => {
342+
const result = node.dumpFinalVersion(true);
330343
res.status(200)
331344
.set('Content-Type', 'application/json')
332345
.send({code: 0, result})
@@ -464,10 +477,7 @@ function createAndExecuteTransaction(txBody, isNoncedTransaction) {
464477
result: false,
465478
};
466479
}
467-
return {
468-
tx_hash: tx.hash,
469-
result: p2pServer.executeAndBroadcastTransaction(tx)
470-
};
480+
return p2pServer.executeAndBroadcastTransaction(tx);
471481
}
472482

473483
function checkIfTransactionShouldBeNonced(input) {

client/protocol_versions.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,8 @@
1313
},
1414
"0.5.0": {
1515
"min": "0.5.0"
16+
},
17+
"0.5.1": {
18+
"min": "0.5.0"
1619
}
1720
}

chain-util.js renamed to common/chain-util.js

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ const EC = require('elliptic').ec;
22
const ec = new EC('secp256k1');
33
const stringify = require('fast-json-stable-stringify');
44
const ainUtil = require('@ainblockchain/ain-util');
5-
const RuleUtil = require('./db/rule-util');
5+
const RuleUtil = require('../db/rule-util');
66
const ruleUtil = new RuleUtil();
77
const PRIVATE_KEY = process.env.PRIVATE_KEY || null;
88

@@ -107,6 +107,20 @@ class ChainUtil {
107107
}
108108
}
109109

110+
static parseJsonOrNull(str) {
111+
let parsed = null;
112+
try {
113+
parsed = JSON.parse(str);
114+
} catch (e) {
115+
// parsed is not set
116+
}
117+
return parsed;
118+
}
119+
120+
static isJson(str) {
121+
return ChainUtil.parseJsonOrNull(str) !== null;
122+
}
123+
110124
static parsePath(path) {
111125
if (!path) {
112126
return [];
@@ -179,18 +193,41 @@ class ChainUtil {
179193

180194
static transactionFailed(response) {
181195
if (Array.isArray(response)) {
182-
response.forEach((res) => {
183-
if (ChainUtil.checkForTransactionErrorCode(res)) {
196+
for (const result of response) {
197+
if (ChainUtil.checkForTransactionErrorCode(result)) {
184198
return true;
185199
}
186-
});
200+
}
187201
return false;
188202
}
189203
return ChainUtil.checkForTransactionErrorCode(response);
190204
}
191205

192-
static checkForTransactionErrorCode(response) {
193-
return response === null || (response.code !== undefined && response.code !== 0);
206+
static checkForTransactionErrorCode(result) {
207+
return result === null || (result.code !== undefined && result.code !== 0);
208+
}
209+
210+
static returnError(code, message) {
211+
return { code, error_message: message };
212+
}
213+
214+
/**
215+
* Logs and returns error.
216+
*
217+
* @param {*} logger logger to log with
218+
* @param {*} code error code
219+
* @param {*} message error message
220+
* @param {*} level level to log with
221+
*/
222+
static logAndReturnError(logger, code, message, level = 1) {
223+
if (level === 0) {
224+
logger.error(message);
225+
} else if (level === 1) {
226+
logger.info(message);
227+
} else {
228+
logger.debug(message);
229+
}
230+
return ChainUtil.returnError(code, message);
194231
}
195232
}
196233

0 commit comments

Comments
 (0)