conflict_resolution
stringlengths 27
16k
|
---|
<<<<<<<
=======
describe('when storageStub.entities.Block.begin fails', () => {
beforeEach(async () => {
storageStub.entities.Block.begin.rejects(new Error('db-tx_ERR'));
});
it('should call a callback with proper error message', async () => {
try {
await blocksChainModule.popLastBlock(
storageStub,
interfaceAdapters,
genesisBlockWithTransactions,
roundsModuleStub,
slots,
blockWithTransactions,
exceptions,
);
} catch (error) {
expect(error.message).to.eql('db-tx_ERR');
}
});
});
>>>>>>>
<<<<<<<
=======
beforeEach(async () => {
storageStub.entities.Block.begin.rejects(
new Error('popLastBlock-ERR'),
);
});
>>>>>>> |
<<<<<<<
=======
this.blocksChain = new BlocksChain({
storage: this.storage,
interfaceAdapters: this.interfaceAdapters,
roundsModule: this.roundsModule,
dposModule: this.dposModule,
slots: this.slots,
exceptions: this.exceptions,
genesisBlock: this.genesisBlock,
});
>>>>>>> |
<<<<<<<
Migration: new Migration(adapter),
=======
Peer: new Peer(adapter),
Transaction: new Transaction(adapter),
>>>>>>>
Migration: new Migration(adapter),
Peer: new Peer(adapter),
Transaction: new Transaction(adapter), |
<<<<<<<
var getTransactionByIdPromise = node.Promise.promisify(getTransactionById);
=======
/**
* Validate if the validation response contains error for a specific param
*
* @param {object} res - Response object got from server
* @param {string} param - Param name to check
*/
function expectSwaggerParamError (res, param) {
res.body.message.should.be.eql('Validation errors');
res.body.errors.map(function (p) { return p.name; }).should.contain(param);
}
var getTransactionPromise = node.Promise.promisify(getTransaction);
>>>>>>>
/**
* Validate if the validation response contains error for a specific param
*
* @param {object} res - Response object got from server
* @param {string} param - Param name to check
*/
function expectSwaggerParamError (res, param) {
res.body.message.should.be.eql('Validation errors');
res.body.errors.map(function (p) { return p.name; }).should.contain(param);
}
var getTransactionByIdPromise = node.Promise.promisify(getTransactionById); |
<<<<<<<
if (appConfig.coverage) {
var im = require('istanbul-middleware');
logger.debug('Hook loader for coverage - do not use in production environment!');
im.hookLoader(__dirname);
app.use('/coverage', im.createHandler());
}
=======
if (appConfig.coverage) {
var im = require('istanbul-middleware');
logger.debug('Hook loader for coverage - ensure this is not production!');
im.hookLoader(__dirname);
app.use('/coverage', im.createHandler());
}
>>>>>>>
if (appConfig.coverage) {
var im = require('istanbul-middleware');
logger.debug('Hook loader for coverage - do not use in production environment!');
im.hookLoader(__dirname);
app.use('/coverage', im.createHandler());
}
<<<<<<<
scope.logic.transaction.bindModules(scope.modules);
=======
scope.logic.peers.bind(scope);
>>>>>>>
scope.logic.transaction.bindModules(scope.modules);
scope.logic.peers.bind(scope); |
<<<<<<<
class AccountsRepository {
constructor (db, pgp) {
=======
class AccountsRepo {
constructor(db, pgp) {
>>>>>>>
class AccountsRepository {
constructor (db, pgp) {
<<<<<<<
countMemAccounts () {
return this.db.one(sql.countMemAccounts, [], a => +a.count);
=======
countMemAccounts() {
return this.db.one(sql.countMemAccounts);
>>>>>>>
countMemAccounts () {
return this.db.one(sql.countMemAccounts, [], a => +a.count);
<<<<<<<
getOrphanedMemAccounts () {
return this.db.any(sql.getOrphanedMemAccounts);
=======
getOrphanedMemAccounts() {
return this.db.query(sql.getOrphanedMemAccounts);
>>>>>>>
getOrphanedMemAccounts () {
return this.db.any(sql.getOrphanedMemAccounts);
<<<<<<<
getDelegates () {
return this.db.any(sql.getDelegates);
=======
getDelegates() {
return this.db.query(sql.getDelegates);
>>>>>>>
getDelegates () {
return this.db.any(sql.getDelegates);
<<<<<<<
return Promise.reject(new TypeError('Error: db.accounts.upsert - invalid conflictingFields argument'));
=======
return Promise.reject('Error: db.accounts.upsert - invalid conflictingFields argument'); // eslint-disable-line prefer-promise-reject-errors
>>>>>>>
return Promise.reject(new TypeError('Error: db.accounts.upsert - invalid conflictingFields argument'));
<<<<<<<
return Promise.reject(new Error('Unknown field provided to db.accounts.upsert'));
=======
return Promise.reject('Unknown field provided to db.accounts.upsert'); // eslint-disable-line prefer-promise-reject-errors
>>>>>>>
return Promise.reject(new Error('Unknown field provided to db.accounts.upsert')); // eslint-disable-line prefer-promise-reject-errors
<<<<<<<
return Promise.reject(new TypeError('Error: db.accounts.update - invalid address argument'));
=======
return Promise.reject('Error: db.accounts.update - invalid address argument'); // eslint-disable-line prefer-promise-reject-errors
>>>>>>>
return Promise.reject(new TypeError('Error: db.accounts.update - invalid address argument')); // eslint-disable-line prefer-promise-reject-errors
<<<<<<<
});
sql = sql + `ORDER BY ${sortSQL.join()}`;
=======
});
sql += `ORDER BY ${sortSQL.join(', ')}`;
>>>>>>>
});
sql += `ORDER BY ${sortSQL.join()}`;
<<<<<<<
return Promise.reject(new TypeError(`Error: db.accounts.removeDependencies called with invalid argument dependency=${dependency}`));
=======
return Promise.reject(`Error: db.account.removeDependencies called with invalid argument dependency=${dependency}`); // eslint-disable-line prefer-promise-reject-errors
>>>>>>>
return Promise.reject(new TypeError(`Error: db.accounts.removeDependencies called with invalid argument dependency=${dependency}`)); // eslint-disable-line prefer-promise-reject-errors
<<<<<<<
return Promise.reject(new TypeError(`Error: db.accounts.insertDependencies called with invalid argument dependency=${dependency}`));
=======
return Promise.reject(`Error: db.account.removeDependencies called with invalid argument dependency=${dependency}`); // eslint-disable-line prefer-promise-reject-errors
>>>>>>>
return Promise.reject(new TypeError(`Error: db.accounts.insertDependencies called with invalid argument dependency=${dependency}`)); // eslint-disable-line prefer-promise-reject-errors |
<<<<<<<
=======
const Rules = require('../../../../../../src/modules/chain/api/ws/workers/rules');
const {
registeredTransactions,
} = require('../../../../common/registered_transactions');
const InitTransaction = require('../../../../../../src/modules/chain/logic/init_transaction');
const initTransaction = new InitTransaction(registeredTransactions);
>>>>>>>
const {
registeredTransactions,
} = require('../../../../common/registered_transactions');
const InitTransaction = require('../../../../../../src/modules/chain/logic/init_transaction');
const initTransaction = new InitTransaction(registeredTransactions);
<<<<<<<
transaction: transactionStub,
=======
initTransaction,
peers: peersStub,
>>>>>>>
initTransaction,
<<<<<<<
=======
describe('removePeer', () => {
describe('when options.nonce is undefined', () => {
let result;
beforeEach(done => {
result = __private.removePeer({}, 'Custom peer remove message');
done();
});
it('should call library.logger.debug with "Cannot remove peer without nonce"', async () => {
expect(library.logger.debug.called).to.be.true;
return expect(
library.logger.debug.calledWith('Cannot remove peer without nonce')
).to.be.true;
});
it('should return false', async () => expect(result).to.be.false);
});
describe('when options.nonce is defined', () => {
let removeSpy;
let auxValidNonce;
beforeEach(done => {
removeSpy = sinonSandbox.spy();
modules.peers = {
remove: removeSpy,
};
library.logic = {
peers: {
peersManager: {
getByNonce: sinonSandbox.stub().returns(peerMock),
getAddress: sinonSandbox.stub(),
},
},
};
auxValidNonce = randomstring.generate(16);
__private.removePeer(
{
nonce: auxValidNonce,
},
'Custom peer remove message'
);
done();
});
it('should call library.logger.debug', async () =>
expect(library.logger.debug.called).to.be.true);
it('should call modules.peers.remove with options.peer', async () =>
expect(removeSpy.calledWith(peerMock)).to.be.true);
});
});
>>>>>>>
<<<<<<<
transaction: {
objectNormalize: sinonSandbox.stub().returns(transaction),
},
peers: {},
=======
initTransaction,
peers: {
peersManager: {
getAddress: sinonSandbox.stub().returns(peerAddressString),
},
},
>>>>>>>
initTransaction,
<<<<<<<
extraLogMessage = 'This is a log message';
objectNormalizeError = 'Unknown transaction type 0';
library.logic.transaction.objectNormalize = sinonSandbox
.stub()
.throws(objectNormalizeError);
=======
invalidTransaction = {
...transaction,
amount: '0',
};
>>>>>>>
invalidTransaction = {
...transaction,
amount: '0',
};
<<<<<<<
it('should call library.logger.debug with "Transaction normalization failed" error message and error details object', async () => {
const errorDetails = {
id: transaction.id,
err: 'Unknown transaction type 0',
module: 'transport',
transaction,
};
return expect(
library.logger.debug.calledWith(
'Transaction normalization failed',
errorDetails
)
).to.be.true;
});
it('should call callback with error = "Invalid transaction body"', async () =>
expect(error).to.equal(
`Invalid transaction body - ${objectNormalizeError}`
));
=======
it('should call the call back with error message', async () => {
initTransaction.jsonRead(invalidTransaction).validate();
expect(errorResult).to.be.an('array');
errorResult.forEach(anError => {
expect(anError).to.be.instanceOf(TransactionError);
});
});
>>>>>>>
it('should call the call back with error message', async () => {
initTransaction.jsonRead(invalidTransaction).validate();
expect(errorResult).to.be.an('array');
errorResult.forEach(anError => {
expect(anError).to.be.instanceOf(TransactionError);
});
});
<<<<<<<
channel: {
invokeSync: sinonSandbox.stub(),
publish: sinonSandbox.stub(),
=======
initTransaction,
block: {
objectNormalize: sinonSandbox.stub().returns(new Block()),
>>>>>>>
channel: {
invokeSync: sinonSandbox.stub(),
publish: sinonSandbox.stub(),
},
initTransaction,
block: {
objectNormalize: sinonSandbox.stub().returns(new Block()),
<<<<<<<
describe('getSignatures', () => {
=======
describe('when __private.receiveSignature fails', () => {
const receiveSignatureError = new TransactionError('Invalid signature body');
>>>>>>>
describe('getSignatures', () => {
<<<<<<<
it('should call modules.transactions.getMultisignatureTransactionList with true and MAX_SHARED_TRANSACTIONS', async () =>
=======
it('should invoke callback with error array', async () => {
expect(error).to.equal(null);
expect(result)
.to.have.property('success')
.which.is.equal(false);
return expect(result)
.to.have.property('errors')
.which.is.equal(receiveSignatureError);
});
});
});
describe('postSignatures', () => {
beforeEach(done => {
query = {
signatures: [SAMPLE_SIGNATURE_1],
};
__private.receiveSignatures = sinonSandbox.stub();
done();
});
describe('when library.config.broadcasts.active option is false', () => {
beforeEach(done => {
library.config.broadcasts.active = false;
library.schema.validate = sinonSandbox.stub().callsArg(2);
transportInstance.shared.postSignatures(query);
done();
});
it('should call library.logger.debug', async () =>
>>>>>>>
it('should call modules.transactions.getMultisignatureTransactionList with true and MAX_SHARED_TRANSACTIONS', async () =>
<<<<<<<
=======
modules.transactions.getMultisignatureTransactionList = sinonSandbox
.stub()
.returns(multisignatureTransactionsList);
transportInstance.shared.getSignatures(
getSignaturesReq,
(err, res) => {
error = err;
result = res;
done();
}
);
});
it('should call callback with error = null', async () =>
expect(error).to.equal(null));
it('should call callback with result = {success: true, signatures: signatures} where signatures does not contain multisignature registration transactions', async () => {
expect(result)
.to.have.property('success')
.which.equals(true);
return expect(result)
.to.have.property('signatures')
.which.is.an('array')
.that.has.property('length')
.which.equals(1);
});
});
});
describe('getTransactions', () => {
beforeEach(done => {
query = {};
transportInstance.shared.getTransactions(query, (err, res) => {
error = err;
result = res;
done();
});
});
it('should call modules.transactions.getMergedTransactionList with true and MAX_SHARED_TRANSACTIONS', async () =>
expect(
modules.transactions.getMergedTransactionList.calledWith(
true,
MAX_SHARED_TRANSACTIONS
)
).to.be.true);
it('should call callback with error = null', async () =>
expect(error).to.equal(null));
it('should call callback with result = {success: true, transactions: transactions}', async () => {
expect(result)
.to.have.property('success')
.which.is.equal(true);
return expect(result)
.to.have.property('transactions')
.which.is.an('array')
.that.has.property('length')
.which.equals(2);
});
});
describe('postTransaction', () => {
beforeEach(done => {
query = {
transaction,
nonce: validNonce,
extraLogMessage: 'This is a log message',
};
__private.receiveTransaction = sinonSandbox
.stub()
.callsArgWith(3, null, transaction.id);
transportInstance.shared.postTransaction(query, (err, res) => {
error = err;
result = res;
done();
});
});
it('should call __private.receiveTransaction with query.transaction, query.peer and query.extraLogMessage as arguments', async () =>
expect(
__private.receiveTransaction.calledWith(
query.transaction,
validNonce,
query.extraLogMessage
)
).to.be.true);
describe('when __private.receiveTransaction succeeds', () => {
it('should invoke callback with object { success: true, transactionId: id }', async () => {
expect(error).to.equal(null);
expect(result)
.to.have.property('transactionId')
.which.is.a('string');
return expect(result)
.to.have.property('success')
.which.is.equal(true);
});
});
describe('when __private.receiveTransaction fails', () => {
const receiveTransactionError = 'Invalid transaction body';
beforeEach(done => {
>>>>>>> |
<<<<<<<
var transactionTypes = require('../../helpers/transactionTypes.js');
=======
var crypto = require('crypto');
var transactionTypes = require('../../helpers/transaction_types.js');
>>>>>>>
var transactionTypes = require('../../helpers/transaction_types.js'); |
<<<<<<<
const Promise = require('bluebird');
const lisk = require('lisk-elements').default;
const accountFixtures = require('../../../fixtures/accounts');
const constants = require('../../../../config/mainnet/constants');
const randomUtil = require('../../../common/utils/random');
const waitFor = require('../../../common/utils/wait_for');
const sendTransactionsPromise = require('../../../common/helpers/api')
=======
var Promise = require('bluebird');
var lisk = require('lisk-elements').default;
var accountFixtures = require('../../../fixtures/accounts');
var randomUtil = require('../../../common/utils/random');
var waitFor = require('../../../common/utils/wait_for');
var sendTransactionsPromise = require('../../../common/helpers/api')
>>>>>>>
const Promise = require('bluebird');
const lisk = require('lisk-elements').default;
const accountFixtures = require('../../../fixtures/accounts');
const randomUtil = require('../../../common/utils/random');
const waitFor = require('../../../common/utils/wait_for');
const sendTransactionsPromise = require('../../../common/helpers/api')
<<<<<<<
const broadcasting = process.env.BROADCASTING !== 'false';
=======
const constants = __testContext.config.constants;
var broadcastingDisabled = process.env.BROADCASTING_DISABLED === 'true';
>>>>>>>
const broadcasting = process.env.BROADCASTING !== 'false';
const constants = __testContext.config.constants; |
<<<<<<<
scope.logic.block.bindModules(scope.modules);
=======
this.channel.subscribe('lisk:state:updated', event => {
Object.assign(scope.applicationState, event.data);
});
>>>>>>>
scope.logic.block.bindModules(scope.modules);
this.channel.subscribe('lisk:state:updated', event => {
Object.assign(scope.applicationState, event.data);
}); |
<<<<<<<
checkIfCan(['nlu-data:w', 'stories:w'], projectId);
=======
>>>>>>>
checkIfCan(['nlu-data:w', 'stories:w'], projectId);
<<<<<<<
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
=======
>>>>>>>
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
<<<<<<<
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
=======
>>>>>>>
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
<<<<<<<
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
=======
>>>>>>>
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
<<<<<<<
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
=======
>>>>>>>
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
<<<<<<<
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
=======
>>>>>>>
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
<<<<<<<
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
=======
>>>>>>>
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
<<<<<<<
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
=======
>>>>>>>
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
<<<<<<<
checkIfCan('nlu-model:w', getProjectIdFromModelId(modelId));
=======
>>>>>>>
checkIfCan('nlu-model:w', getProjectIdFromModelId(modelId));
<<<<<<<
'nlu.update.general'(modelId, item) {
check(item, Object);
check(modelId, String);
checkIfCan('nlu-model:x', getProjectIdFromModelId(modelId));
const newItem = {};
newItem.config = item.config;
newItem.name = item.name;
newItem.language = item.language;
newItem.logActivity = item.logActivity;
newItem.instance = item.instance;
newItem.description = item.description;
NLUModels.update({ _id: modelId }, { $set: newItem });
return modelId;
},
=======
'nlu.update.general'(modelId, item) {
check(item, Object);
check(modelId, String);
const newItem = {};
newItem.config = item.config;
newItem.name = item.name;
newItem.language = item.language;
newItem.logActivity = item.logActivity;
newItem.instance = item.instance;
newItem.description = item.description;
NLUModels.update({ _id: modelId }, { $set: newItem });
return modelId;
},
>>>>>>>
'nlu.update.general'(modelId, item) {
check(item, Object);
check(modelId, String);
checkIfCan('nlu-model:x', getProjectIdFromModelId(modelId));
const newItem = {};
newItem.config = item.config;
newItem.name = item.name;
newItem.language = item.language;
newItem.logActivity = item.logActivity;
newItem.instance = item.instance;
newItem.description = item.description;
NLUModels.update({ _id: modelId }, { $set: newItem });
return modelId;
},
<<<<<<<
checkIfCan('nlu-model:w', getProjectIdFromModelId(modelId));
=======
>>>>>>>
checkIfCan('nlu-model:w', getProjectIdFromModelId(modelId));
<<<<<<<
checkIfCan('nlu-model:w', projectId);
=======
>>>>>>>
checkIfCan('nlu-model:w', projectId);
<<<<<<<
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
=======
>>>>>>>
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
<<<<<<<
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
=======
/*
Right now, overwriting replaces training_data array, and non-overwrite
adds items whose filterExistent<identifier> doesn't already exist. Behavior to update existing
data is not implemented.
*/
>>>>>>>
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
/*
Right now, overwriting replaces training_data array, and non-overwrite
adds items whose filterExistent<identifier> doesn't already exist. Behavior to update existing
data is not implemented.
*/
<<<<<<<
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
=======
>>>>>>>
checkIfCan('nlu-data:w', getProjectIdFromModelId(modelId));
<<<<<<<
checkIfCan('nlu-model:w', getProjectIdFromModelId(modelId));
=======
>>>>>>>
checkIfCan('nlu-model:w', getProjectIdFromModelId(modelId));
<<<<<<<
checkIfCan(['nlu-data:r', 'responses:r', 'conversations:r', 'project-settings:r'], projectId);
=======
>>>>>>>
checkIfCan(['nlu-data:r', 'responses:r', 'conversations:r', 'project-settings:r'], projectId);
<<<<<<<
async 'nlu.getUtteranceFromPayload'(projectId, payload, lang = 'en') {
check(projectId, String);
check(lang, String);
check(payload, Object);
checkIfCan(['nlu-data:r', 'stories:r', 'responses:r'], projectId);
if (!payload.intent) throw new Meteor.Error('400', 'Intent missing from payload');
const { nlu_models: nluModelIds } = Projects.findOne(
{ _id: projectId },
{ fields: { nlu_models: 1 } },
);
const entitiesQuery = [];
if (payload.entities && payload.entities.length) {
entitiesQuery.push({
$match: {
'training_data.common_examples.entities': {
$size: payload.entities.length,
},
},
});
payload.entities.forEach((entity) => {
entitiesQuery.push({
$match: {
'training_data.common_examples.entities.entity':
entity && entity.entity,
'training_data.common_examples.entities.value':
entity && entity.value,
},
});
});
} else {
entitiesQuery.push({
$match: { 'training_data.common_examples.entities': { $size: 0 } },
});
}
const models = await NLUModels.aggregate([
{ $match: { language: lang, _id: { $in: nluModelIds } } },
{
$project: {
'training_data.common_examples': {
$filter: {
input: '$training_data.common_examples',
as: 'training_data',
cond: { $eq: ['$$training_data.intent', payload.intent] },
},
},
},
},
{ $unwind: '$training_data.common_examples' },
...entitiesQuery,
{ $sort: { 'training_data.common_examples.canonical': -1, 'training_data.common_examples.updatedAt': -1 } },
]).toArray();
const model = models[0];
if (
!model
|| !model.training_data
|| !model.training_data.common_examples.text
) throw new Meteor.Error('400', 'No correponding utterance');
const { text, intent, entities } = model.training_data.common_examples;
return { text, intent, entities };
},
=======
async 'nlu.getUtteranceFromPayload'(projectId, payload, lang = 'en') {
check(projectId, String);
check(lang, String);
check(payload, Object);
if (!payload.intent) throw new Meteor.Error('400', 'Intent missing from payload');
const { nlu_models: nluModelIds } = Projects.findOne(
{ _id: projectId },
{ fields: { nlu_models: 1 } },
);
const entitiesQuery = [];
if (payload.entities && payload.entities.length) {
entitiesQuery.push({
$match: {
'training_data.common_examples.entities': {
$size: payload.entities.length,
},
},
});
payload.entities.forEach((entity) => {
entitiesQuery.push({
$match: {
'training_data.common_examples.entities.entity':
entity && entity.entity,
'training_data.common_examples.entities.value':
entity && entity.value,
},
});
});
} else {
entitiesQuery.push({
$match: { 'training_data.common_examples.entities': { $size: 0 } },
});
}
const models = await NLUModels.aggregate([
{ $match: { language: lang, _id: { $in: nluModelIds } } },
{
$project: {
'training_data.common_examples': {
$filter: {
input: '$training_data.common_examples',
as: 'training_data',
cond: { $eq: ['$$training_data.intent', payload.intent] },
},
},
},
},
{ $unwind: '$training_data.common_examples' },
...entitiesQuery,
{ $sort: { 'training_data.common_examples.canonical': -1, 'training_data.common_examples.updatedAt': -1 } },
]).toArray();
const model = models[0];
if (
!model
|| !model.training_data
|| !model.training_data.common_examples.text
) throw new Meteor.Error('400', 'No correponding utterance');
const { text, intent, entities } = model.training_data.common_examples;
return { text, intent, entities };
},
>>>>>>>
async 'nlu.getUtteranceFromPayload'(projectId, payload, lang = 'en') {
check(projectId, String);
check(lang, String);
check(payload, Object);
checkIfCan(['nlu-data:r', 'stories:r', 'responses:r'], projectId);
if (!payload.intent) throw new Meteor.Error('400', 'Intent missing from payload');
const { nlu_models: nluModelIds } = Projects.findOne(
{ _id: projectId },
{ fields: { nlu_models: 1 } },
);
const entitiesQuery = [];
if (payload.entities && payload.entities.length) {
entitiesQuery.push({
$match: {
'training_data.common_examples.entities': {
$size: payload.entities.length,
},
},
});
payload.entities.forEach((entity) => {
entitiesQuery.push({
$match: {
'training_data.common_examples.entities.entity':
entity && entity.entity,
'training_data.common_examples.entities.value':
entity && entity.value,
},
});
});
} else {
entitiesQuery.push({
$match: { 'training_data.common_examples.entities': { $size: 0 } },
});
}
const models = await NLUModels.aggregate([
{ $match: { language: lang, _id: { $in: nluModelIds } } },
{
$project: {
'training_data.common_examples': {
$filter: {
input: '$training_data.common_examples',
as: 'training_data',
cond: { $eq: ['$$training_data.intent', payload.intent] },
},
},
},
},
{ $unwind: '$training_data.common_examples' },
...entitiesQuery,
{ $sort: { 'training_data.common_examples.canonical': -1, 'training_data.common_examples.updatedAt': -1 } },
]).toArray();
const model = models[0];
if (
!model
|| !model.training_data
|| !model.training_data.common_examples.text
) throw new Meteor.Error('400', 'No correponding utterance');
const { text, intent, entities } = model.training_data.common_examples;
return { text, intent, entities };
}, |
<<<<<<<
const _ = require('lodash');
const ip = require('ip');
const wsRPC = require('../api/ws/rpc/ws_rpc').wsRPC;
=======
const _ = require('lodash');
const ip = require('ip');
>>>>>>>
const _ = require('lodash');
const ip = require('ip');
<<<<<<<
=======
/**
* Normalizes headers.
*
* @param {Object} headers
* @returns {Object} Normalized headers
* @todo Add description for the params
*/
Peer.prototype.applyHeaders = function(headers) {
headers = headers || {};
headers = this.normalize(headers);
this.update(headers);
return headers;
};
/**
* Updates peer values if mutable.
*
* @param {peer} peer
* @returns {Object} this
* @todo Add description for the params
*/
Peer.prototype.update = function(peer) {
peer = this.normalize(peer);
// Accept only supported properties
_.each(this.properties, key => {
// Change value only when is defined
if (
peer[key] !== null &&
peer[key] !== undefined &&
!_.includes(this.immutable, key)
) {
this[key] = peer[key];
}
});
return this;
};
/**
* Description of the function.
*
* @returns {peer} Clone of peer
* @todo Add description for the function
*/
Peer.prototype.object = function() {
const copy = {};
_.each(this.properties, key => {
copy[key] = this[key];
});
delete copy.rpc;
return copy;
};
>>>>>>> |
<<<<<<<
library.storage.entities.Block.count({}, t),
library.storage.entities.Block.get({ height: 1 }, {}, t),
library.storage.entities.Round.getUniqueRounds(),
t.delegates.countDuplicatedDelegates(),
=======
t.blocks.count(),
t.blocks.getGenesisBlock(),
library.storage.entities.Round.getUniqueRounds(t),
library.storage.entities.Account.countDuplicatedDelegates(t),
>>>>>>>
library.storage.entities.Block.count({}, t),
library.storage.entities.Block.get({ height: 1 }, {}, t),
library.storage.entities.Round.getUniqueRounds(t),
library.storage.entities.Account.countDuplicatedDelegates(t), |
<<<<<<<
var removeSpy;
var auxValidNonce;
=======
let removeSpy;
let validNonce;
>>>>>>>
let removeSpy;
let auxValidNonce;
<<<<<<<
for (var j = 0; j < 10; j++) {
var auxBlock = new Block();
blocksList.push(auxBlock);
=======
for (let j = 0; j < 10; j++) {
const block = new Block();
blocksList.push(block);
>>>>>>>
for (let j = 0; j < 10; j++) {
const auxBlock = new Block();
blocksList.push(auxBlock);
<<<<<<<
var postBlockQuery;
=======
let query;
>>>>>>>
let postBlockQuery;
<<<<<<<
var getSignaturesReq;
=======
let req;
>>>>>>>
let getSignaturesReq; |
<<<<<<<
const {
uploadImage, deleteImage, uploadImageValidator, deleteImageValidator,
} = require('./images');
const {
restartRasa, restartRasaValidator,
} = require('./webhooks');
=======
const { version } = require('../package-lock.json')
>>>>>>>
const {
uploadImage, deleteImage, uploadImageValidator, deleteImageValidator,
} = require('./images');
const {
restartRasa, restartRasaValidator,
} = require('./webhooks');
const { version } = require('../package-lock.json')
<<<<<<<
router.post('/image/upload', uploadImageValidator, uploadImage);
router.delete('/image/delete', deleteImageValidator, deleteImage);
router.get('/health-check', (req, res) => res.status(200).json());
=======
router.get('/health-check', (req, res) => res.status(200).json({ version, healthy: true }));
>>>>>>>
router.post('/image/upload', uploadImageValidator, uploadImage);
router.delete('/image/delete', deleteImageValidator, deleteImage);
router.get('/health-check', (req, res) => res.status(200).json({ version, healthy: true })); |
<<<<<<<
const {
lookupPeerIPs,
createHttpServer,
createBus,
bootstrapStorage,
bootstrapCache,
createSocketCluster,
initLogicStructure,
initModules,
attachSwagger,
} = require('./init_steps');
=======
const { createSystemComponent } = require('../../components/system');
>>>>>>>
const { createSystemComponent } = require('../../components/system');
const {
lookupPeerIPs,
createHttpServer,
createBus,
bootstrapStorage,
bootstrapCache,
createSocketCluster,
initLogicStructure,
initModules,
attachSwagger,
} = require('./init_steps');
<<<<<<<
=======
const config = {
modules: {
accounts: './modules/accounts.js',
blocks: './modules/blocks.js',
dapps: './modules/dapps.js',
delegates: './modules/delegates.js',
rounds: './modules/rounds.js',
loader: './modules/loader.js',
multisignatures: './modules/multisignatures.js',
peers: './modules/peers.js',
signatures: './modules/signatures.js',
transactions: './modules/transactions.js',
transport: './modules/transport.js',
},
};
const modules = [];
>>>>>>>
<<<<<<<
try {
// Cache
this.logger.debug('Initiating cache...');
const cache = createCacheComponent(cacheConfig, this.logger);
=======
// Domain error handler
d.on('error', err => {
this.logger.fatal('Domain master', {
message: err.message,
stack: err.stack,
});
process.emit('cleanup', err);
});
// Cache
this.logger.debug('Initiating cache...');
const cache = createCacheComponent(cacheConfig, this.logger);
// Storage
this.logger.debug('Initiating storage...');
const storage = createStorageComponent(storageConfig, dbLogger);
// System
this.logger.debug('Initiating system...');
const system = createSystemComponent(systemConfig, this.logger, storage);
// Config
const appConfig = this.options.config;
const self = this;
async.auto(
{
config(cb) {
if (!appConfig.nethash) {
throw Error('Failed to assign nethash from genesis block');
}
// If peers layer is not enabled there is no need to create the peer's list
if (!appConfig.peers.enabled) {
appConfig.peers.list = [];
return cb(null, appConfig);
}
// In case domain names are used, resolve those to IP addresses.
const peerDomainLookupTasks = appConfig.peers.list.map(peer =>
async.reflect(callback => {
if (net.isIPv4(peer.ip)) {
return setImmediate(() => callback(null, peer));
}
return dns.lookup(peer.ip, { family: 4 }, (err, address) => {
if (err) {
console.error(
`Failed to resolve peer domain name ${
peer.ip
} to an IP address`
);
return callback(err, peer);
}
return callback(null, Object.assign({}, peer, { ip: address }));
});
})
);
return async.parallel(peerDomainLookupTasks, (_, results) => {
appConfig.peers.list = results
.filter(result =>
Object.prototype.hasOwnProperty.call(result, 'value')
)
.map(result => result.value);
return cb(null, appConfig);
});
},
logger(cb) {
cb(null, self.logger);
},
build(cb) {
cb(null, versionBuild);
},
lastCommit(cb) {
cb(null, lastCommit);
},
genesisBlock(cb) {
cb(null, {
block: appConfig.genesisBlock,
});
},
schema(cb) {
cb(null, swaggerHelper.getValidator());
},
network: [
'config',
/**
* Initalizes express, middleware, socket.io.
*
* @func network[1]
* @memberof! app
* @param {Object} scope
* @param {function} cb - Callback function
*/
function(scope, cb) {
const express = require('express');
const app = express();
if (appConfig.coverage) {
// eslint-disable-next-line import/no-extraneous-dependencies
const im = require('istanbul-middleware');
self.logger.debug(
'Hook loader for coverage - Do not use in production environment!'
);
im.hookLoader(__dirname);
app.use('/coverage', im.createHandler());
}
if (appConfig.trustProxy) {
app.enable('trust proxy');
}
const server = require('http').createServer(app);
const io = require('socket.io')(server);
let privateKey;
let certificate;
let https;
let https_io;
if (scope.config.api.ssl && scope.config.api.ssl.enabled) {
privateKey = fs.readFileSync(scope.config.api.ssl.options.key);
certificate = fs.readFileSync(scope.config.api.ssl.options.cert);
https = require('https').createServer(
{
key: privateKey,
cert: certificate,
ciphers:
'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA',
},
app
);
https_io = require('socket.io')(https);
}
cb(null, {
express,
app,
server,
io,
https,
https_io,
});
},
],
>>>>>>>
try {
// Cache
this.logger.debug('Initiating cache...');
const cache = createCacheComponent(cacheConfig, this.logger);
<<<<<<<
// Lookup for peers ips from dns
scope.config.peers.list = await lookupPeerIPs(
scope.config.peers.list,
scope.config.peers.enabled
);
=======
system(cb) {
return cb(null, system);
},
components: [
'cache',
'storage',
'system',
(scope, cb) => {
cb(null, {
cache: scope.cache,
storage: scope.storage,
logger: scope.logger,
system: scope.system,
});
},
],
webSocket: [
'config',
'logger',
'network',
'storage',
/**
* Description of the function.
*
* @func webSocket[5]
* @memberof! app
* @param {Object} scope
* @param {function} cb - Callback function
* @todo Add description for the function and its params
*/
function(scope, cb) {
if (!appConfig.peers.enabled) {
scope.logger.info(
'Skipping P2P server initialization due to the config settings - "peers.enabled" is set to false.'
);
return cb();
}
const webSocketConfig = {
workers: 1,
port: scope.config.wsPort,
host: '0.0.0.0',
wsEngine: scope.config.peers.options.wsEngine,
workerController: workersControllerPath,
perMessageDeflate: false,
secretKey: 'liskSecretKey',
// Because our node is constantly sending messages, we don't
// need to use the ping feature to detect bad connections.
pingTimeoutDisabled: true,
// Maximum amount of milliseconds to wait before force-killing
// a process after it was passed a 'SIGTERM' or 'SIGUSR2' signal
processTermTimeout: 10000,
logLevel: 0,
};
const childProcessOptions = {
version: scope.config.version,
minVersion: scope.config.minVersion,
protocolVersion: scope.config.protocolVersion,
nethash: scope.config.nethash,
port: scope.config.wsPort,
nonce: scope.config.nonce,
blackListedPeers: scope.config.peers.access.blackList,
};
scope.socketCluster = new SocketCluster(webSocketConfig);
const MasterWAMPServer = require('wamp-socket-cluster/MasterWAMPServer');
scope.network.app.rpc = wsRPC.setServer(
new MasterWAMPServer(scope.socketCluster, childProcessOptions)
);
scope.socketCluster.on('ready', () => {
scope.logger.info(
'Socket Cluster ready for incoming connections'
);
return cb();
});
// The 'fail' event aggregates errors from all SocketCluster processes.
scope.socketCluster.on('fail', err => {
scope.logger.error(err);
if (err.name === 'WSEngineInitError') {
const extendedError = scope.logger.error(extendedError);
}
});
return scope.socketCluster.on('workerExit', workerInfo => {
let exitMessage = `Worker with pid ${workerInfo.pid} exited`;
if (workerInfo.signal) {
exitMessage += ` due to signal: '${workerInfo.signal}'`;
}
scope.logger.error(exitMessage);
});
},
],
logic: [
'components',
'bus',
'schema',
'genesisBlock',
/**
* Description of the function.
*
* @func logic[4]
* @memberof! app
* @param {Object} scope
* @param {function} cb - Callback function
*/
function(scope, cb) {
const Transaction = require('./logic/transaction.js');
const Block = require('./logic/block.js');
const Account = require('./logic/account.js');
const Peers = require('./logic/peers.js');
async.auto(
{
bus(busCb) {
busCb(null, scope.bus);
},
config(configCb) {
configCb(null, scope.config);
},
storage(storageCb) {
storageCb(null, scope.storage);
},
ed(edCb) {
edCb(null, scope.ed);
},
logger(loggerCb) {
loggerCb(null, scope.logger);
},
schema(schemaCb) {
schemaCb(null, scope.schema);
},
genesisBlock(genesisBlockCb) {
genesisBlockCb(null, scope.genesisBlock);
},
account: [
'storage',
'bus',
'ed',
'schema',
'genesisBlock',
'logger',
function(accountScope, accountCb) {
new Account(
accountScope.storage,
accountScope.schema,
accountScope.logger,
accountCb
);
},
],
transaction: [
'storage',
'bus',
'ed',
'schema',
'genesisBlock',
'account',
'logger',
function(transactionScope, transactionCb) {
new Transaction(
transactionScope.storage,
transactionScope.ed,
transactionScope.schema,
transactionScope.genesisBlock,
transactionScope.account,
transactionScope.logger,
transactionCb
);
},
],
block: [
'storage',
'bus',
'ed',
'schema',
'genesisBlock',
'account',
'transaction',
function(blockScope, blockCb) {
new Block(
blockScope.ed,
blockScope.schema,
blockScope.transaction,
blockCb
);
},
],
peers: [
'logger',
'config',
function(peersScope, peersCb) {
new Peers(
peersScope.logger,
peersScope.config,
scope.components.system,
peersCb
);
},
],
},
cb
);
},
],
modules: [
'network',
'webSocket',
'config',
'logger',
'bus',
'sequence',
'balancesSequence',
'storage',
'logic',
/**
* Description of the function.
*
* @func modules[12]
* @param {Object} modulesScope
* @param {function} modulesCb - Callback function
*/
function(modulesScope, modulesCb) {
const tasks = {};
Object.keys(config.modules).forEach(name => {
tasks[name] = function(configModulesCb) {
const domain = require('domain').create();
domain.on('error', err => {
modulesScope.logger.fatal(`Domain ${name}`, {
message: err.message,
stack: err.stack,
});
});
domain.run(() => {
self.logger.debug('Loading module', name);
// eslint-disable-next-line import/no-dynamic-require
const DynamicModule = require(config.modules[name]);
const obj = new DynamicModule(configModulesCb, modulesScope);
modules.push(obj);
});
};
});
async.parallel(tasks, (err, results) => {
modulesCb(err, results);
});
},
],
ready: [
'components',
'swagger',
'modules',
'bus',
'logic',
/**
* Description of the function.
*
* @func ready[4]
* @memberof! app
* @param {Object} scope
* @param {function} cb - Callback function
* @todo Add description for the function and its params
*/
function(scope, cb) {
scope.modules.swagger = scope.swagger;
// Fire onBind event in every module
scope.bus.message('bind', scope);
scope.logic.peers.bindModules(scope.modules);
cb();
},
],
listenWebSocket: [
'ready',
/**
* Description of the function.
*
* @func api[1]
* @param {Object} scope
* @param {function} cb - Callback function
*/
function(scope, cb) {
if (!appConfig.peers.enabled) {
return cb();
}
new WsTransport(scope.modules.transport);
return cb();
},
],
listenHttp: [
'ready',
/**
* Description of the function.
*
* @func listen[1]
* @memberof! app
* @param {Object} scope
* @param {function} cb - Callback function
*/
function(scope, cb) {
// Security vulnerabilities fixed by Node v8.14.0 - "Slowloris (cve-2018-12122)"
scope.network.server.headersTimeout =
appConfig.api.options.limits.headersTimeout;
// Disconnect idle clients
scope.network.server.setTimeout(
appConfig.api.options.limits.serverSetTimeout
);
scope.network.server.on('timeout', socket => {
scope.logger.info(
`Disconnecting idle socket: ${socket.remoteAddress}:${
socket.remotePort
}`
);
socket.destroy();
});
return scope.network.server.listen(
scope.config.httpPort,
scope.config.address,
serverListenErr => {
scope.logger.info(
`Lisk started: ${scope.config.address}:${
scope.config.httpPort
}`
);
if (!serverListenErr) {
if (scope.config.api.ssl.enabled) {
// Security vulnerabilities fixed by Node v8.14.0 - "Slowloris (cve-2018-12122)"
scope.network.https.headersTimeout =
appConfig.api.options.limits.headersTimeout;
scope.network.https.setTimeout(
appConfig.api.options.limits.serverTimeout
);
scope.network.https.on('timeout', socket => {
scope.logger.info(
`Disconnecting idle socket: ${socket.remoteAddress}:${
socket.remotePort
}`
);
socket.destroy();
});
return scope.network.https.listen(
scope.config.api.ssl.options.port,
scope.config.api.ssl.options.address,
httpsListenErr => {
scope.logger.info(
`Lisk https started: ${
scope.config.api.ssl.options.address
}:${scope.config.api.ssl.options.port}`
);
>>>>>>>
// Lookup for peers ips from dns
scope.config.peers.list = await lookupPeerIPs(
scope.config.peers.list,
scope.config.peers.enabled
);
<<<<<<<
if (components !== undefined) {
components.map(component => component.cleanup());
=======
if (this.scope.components !== undefined) {
Object.keys(this.scope.components)
.filter(key => typeof this.scope.components[key].cleanup === 'function')
.map(key => this.scope.components[key].cleanup());
>>>>>>>
if (components !== undefined) {
components.map(component => component.cleanup()); |
<<<<<<<
// Transactions to rewind in case of error.
let appliedTransactions = {};
const undoUnconfirmedListStep = function(tx) {
return new Promise((resolve, reject) => {
modules.transactions.undoUnconfirmedList(err => {
if (err) {
// Fatal error, memory tables will be inconsistent
library.logger.error('Failed to undo unconfirmed list', err);
const errObj = new Error('Failed to undo unconfirmed list');
reject(errObj);
} else {
return setImmediate(resolve);
}
}, tx);
=======
var undoUnconfirmedListStep = function(cb) {
modules.transactions.undoUnconfirmedList(err => {
if (err) {
// Fatal error, memory tables will be inconsistent
library.logger.error('Failed to undo unconfirmed list', err);
var errObj = new Error('Failed to undo unconfirmed list');
return setImmediate(cb, errObj);
}
return setImmediate(cb);
>>>>>>>
const undoUnconfirmedListStep = function(cb) {
modules.transactions.undoUnconfirmedList(err => {
if (err) {
// Fatal error, memory tables will be inconsistent
library.logger.error('Failed to undo unconfirmed list', err);
const errObj = new Error('Failed to undo unconfirmed list');
return setImmediate(cb, errObj);
}
return setImmediate(cb);
<<<<<<<
const errObj = new Error('Failed to save block');
reject(errObj);
=======
var errObj = new Error('Failed to save block');
return setImmediate(reject, errObj);
>>>>>>>
const errObj = new Error('Failed to save block');
return setImmediate(reject, errObj); |
<<<<<<<
const constants = require('../../../../../../framework/src/controller/schema/constants_schema');
const configurator = require('../../../../../src/controller/helpers/configurator');
=======
>>>>>>>
<<<<<<<
beforeEach(() => {
// Mock the method and return what ever came as parameter
configurator.getConfig.mockImplementation(c => _.cloneDeep(c));
});
afterEach(() => {
configurator.getConfig.mockReset();
});
it('should accept function as label argument', () => {
// Arrange
const labelFn = () => 'jest-unit';
// Act
const app = new Application(labelFn, params.genesisBlock, params.config);
expect(app.label).toBe(labelFn);
});
=======
>>>>>>>
<<<<<<<
it('should contain all framework related transactions.', () => {
// Act
const app = new Application(
params.label,
params.genesisBlock,
params.config
);
// Assert
expect(Object.keys(app.getTransactions())).toEqual(frameworkTxTypes);
});
// Skipped because `new Application` is mutating params.config making the other tests to fail
// eslint-disable-next-line jest/no-disabled-tests
it.skip('[feature/improve_transactions_processing_efficiency] should throw validation error if constants are overriden by the user', () => {
configurator.getConfig.mockImplementation(() => {
throw new Error('Schema validation error');
});
=======
it('should throw validation error if constants are overridden by the user', () => {
>>>>>>>
it('should contain all framework related transactions.', () => {
// Act
const app = new Application(
params.label,
params.genesisBlock,
params.config
);
// Assert
expect(Object.keys(app.getTransactions())).toEqual(frameworkTxTypes);
});
// Skipped because `new Application` is mutating params.config making the other tests to fail
// eslint-disable-next-line jest/no-disabled-tests
it.skip('[feature/improve_transactions_processing_efficiency] should throw validation error if constants are overriden by the user', () => { |
<<<<<<<
if (modules.loader.syncing()) {
return setImmediate(cb);
}
const unconfirmedCount = self.countUnconfirmed();
=======
var unconfirmedCount = self.countUnconfirmed();
>>>>>>>
const unconfirmedCount = self.countUnconfirmed(); |
<<<<<<<
// TODO: Will be fixed in separate PR
// eslint-disable-next-line import/no-unresolved
const configSchema = require('../schema/config.js');
const Z_schema = require('./z_schema.js');
const deepFreeze = require('./deep_freeze_object.js');
=======
const configSchema = require('../schema/config');
const { ZSchema } = require('../../../controller/helpers/validator');
const validator = new ZSchema();
const rootPath = path.dirname(path.resolve(__filename, '../../../../..'));
const deepFreeze = function(o) {
Object.freeze(o);
Object.getOwnPropertyNames(o).forEach(prop => {
if (
o[prop] !== null &&
typeof o[prop] === 'object' &&
!Object.isFrozen(o[prop])
) {
deepFreeze(o[prop]);
}
});
>>>>>>>
// TODO: Will be fixed in separate PR
// eslint-disable-next-line import/no-unresolved
const configSchema = require('../schema/config.js');
const { ZSchema } = require('../../../controller/helpers/validator');
const validator = new ZSchema();
const rootPath = path.dirname(path.resolve(__filename, '../../../../..'));
const deepFreeze = function(o) {
Object.freeze(o);
Object.getOwnPropertyNames(o).forEach(prop => {
if (
o[prop] !== null &&
typeof o[prop] === 'object' &&
!Object.isFrozen(o[prop])
) {
deepFreeze(o[prop]);
}
}); |
<<<<<<<
const constants = require('../../helpers/constants.js');
const bignum = require('../../helpers/bignum.js');
=======
>>>>>>>
const bignum = require('../../helpers/bignum.js'); |
<<<<<<<
export const getAllTemplates = (projectId, language = '') => {
=======
const getAllTemplates = async (projectId, language = '') => {
>>>>>>>
export const getAllTemplates = async (projectId, language = '') => { |
<<<<<<<
if (__private.loaded && !self.syncing() && modules.blocks.lastReceipt.isStale()) {
library.sequence.add(function (sequenceCb) {
__private.sync(sequenceCb);
}, function (err) {
if (err) {
library.logger.error('Sync timer', err);
=======
if (
__private.loaded &&
!self.syncing() &&
modules.blocks.lastReceipt.isStale()
) {
library.sequence.add(
function(sequenceCb) {
async.retry(__private.retries, __private.sync, sequenceCb);
},
function(err) {
if (err) {
library.logger.error('Sync timer', err);
__private.initialize();
}
return setImmediate(cb);
>>>>>>>
if (
__private.loaded &&
!self.syncing() &&
modules.blocks.lastReceipt.isStale()
) {
library.sequence.add(
function(sequenceCb) {
__private.sync(sequenceCb);
},
function(err) {
if (err) {
library.logger.error('Sync timer', err);
}
return setImmediate(cb);
<<<<<<<
Loader.prototype.getNetwork = function (cb) {
modules.peers.list({ normalized: false }, function (err, peers) {
=======
Loader.prototype.getNetwork = function(cb) {
if (
__private.network.height > 0 &&
Math.abs(
__private.network.height - modules.blocks.lastBlock.get().height
) === 1
) {
return setImmediate(cb, null, __private.network);
}
modules.peers.list({ normalized: false }, function(err, peers) {
>>>>>>>
Loader.prototype.getNetwork = function(cb) {
modules.peers.list({ normalized: false }, function(err, peers) {
<<<<<<<
});
} else {
return setImmediate(seriesCb);
}
}
}, function (err) {
library.logger.trace('Transactions and signatures pulled', err);
});
=======
}
},
},
function(err) {
library.logger.trace('Transactions and signatures pulled');
if (err) {
__private.initialize();
}
}
);
>>>>>>>
}
},
},
function(err) {
library.logger.trace('Transactions and signatures pulled', err);
}
); |
<<<<<<<
getActiveDelegatesForRound: jest
.fn()
.mockReturnValue(delegatePublicKeys),
},
Round: {
=======
getRoundDelegates: jest.fn().mockReturnValue(delegatePublicKeys),
>>>>>>>
getActiveDelegatesForRound: jest
.fn()
.mockReturnValue(delegatePublicKeys), |
<<<<<<<
const constants = require('../../../../../../framework/src/controller/schema/constants');
const applicationSchema = require('../../../../../src/controller/schema/application');
const constantsSchema = require('../../../../../src/controller/schema/constants');
=======
const configurator = require('../../../../../src/controller/helpers/configurator');
const {
genesisBlockSchema,
constantsSchema,
} = require('../../../../../src/controller/schema');
>>>>>>>
const constants = require('../../../../../../framework/src/controller/schema/constants_schema');
const configurator = require('../../../../../src/controller/helpers/configurator');
const {
genesisBlockSchema,
constantsSchema,
} = require('../../../../../src/controller/schema');
<<<<<<<
it('should contain all framework related transactions.', () => {
// Act
const app = new Application(
params.label,
params.genesisBlock,
params.config
);
// Assert
expect(Object.keys(app.getTransactions())).toEqual(frameworkTxTypes);
});
// Skipped because `new Application` is mutating params.config making the other tests to fail
// eslint-disable-next-line jest/no-disabled-tests
it.skip('[feature/improve_transactions_processing_efficiency] should throw validation error if constants are overriden by the user', () => {
const customConfig = [
...[
{
app: {
genesisConfig: {
CONSTANT: 'aConstant',
},
},
},
],
...params.config,
];
=======
it('should throw validation error if constants are overridden by the user', () => {
configurator.getConfig.mockImplementation(() => {
throw new Error('Schema validation error');
});
const customConfig = _.cloneDeep(config);
customConfig.app.genesisConfig = {
CONSTANT: 'aConstant',
};
>>>>>>>
it('should contain all framework related transactions.', () => {
// Act
const app = new Application(
params.label,
params.genesisBlock,
params.config
);
// Assert
expect(Object.keys(app.getTransactions())).toEqual(frameworkTxTypes);
});
// Skipped because `new Application` is mutating params.config making the other tests to fail
// eslint-disable-next-line jest/no-disabled-tests
it.skip('[feature/improve_transactions_processing_efficiency] should throw validation error if constants are overriden by the user', () => {
configurator.getConfig.mockImplementation(() => {
throw new Error('Schema validation error');
});
const customConfig = _.cloneDeep(config);
customConfig.app.genesisConfig = {
CONSTANT: 'aConstant',
}; |
<<<<<<<
let txPool;
beforeEach(async () => {
sinonSandbox.spy(ProcessTransactions, 'composeProcessTransactionSteps');
txPool = new TransactionPool(
config.broadcasts.broadcastInterval,
config.broadcasts.releaseLimit,
=======
it('should create pool instance', async () => {
const tp = new TransactionPool(
config.modules.chain.broadcasts.broadcastInterval,
config.modules.chain.broadcasts.releaseLimit,
>>>>>>>
let txPool;
beforeEach(async () => {
sinonSandbox.spy(ProcessTransactions, 'composeProcessTransactionSteps');
txPool = new TransactionPool(
config.modules.chain.broadcasts.broadcastInterval,
config.modules.chain.broadcasts.releaseLimit, |
<<<<<<<
conversation._id,
(event) => event.timestamp > oldestImport,
=======
(event) => event.timestamp > latestImport,
>>>>>>>
conversation._id,
(event) => event.timestamp > latestImport, |
<<<<<<<
=======
if (scope.config.network.enabled) {
// Lookup for peers ips from dns
scope.config.network.list = await lookupPeerIPs(
scope.config.network.list,
scope.config.network.enabled
);
// Listen to websockets
scope.webSocket = await createSocketCluster(scope);
await scope.webSocket.listen();
} else {
this.logger.info(
'Skipping P2P server initialization due to the config settings - "peers.enabled" is set to false.'
);
}
// Ready to bind modules
scope.logic.peers.bindModules(scope.modules);
scope.logic.block.bindModules(scope.modules);
>>>>>>>
scope.logic.block.bindModules(scope.modules); |
<<<<<<<
this.registerModule(HttpAPIModule);
this.registerModule(NetworkModule, this.config.modules.network);
=======
this.registerModule(HttpAPIModule, {
constants: this.constants,
loadAsChildProcess: childProcessModules.includes(HttpAPIModule.alias),
});
>>>>>>>
this.registerModule(NetworkModule, this.config.modules.network);
this.registerModule(HttpAPIModule, {
constants: this.constants,
loadAsChildProcess: childProcessModules.includes(HttpAPIModule.alias),
}); |
<<<<<<<
const transactionTypes = require('../../helpers/transaction_types.js');
=======
const constants = require('../../helpers/constants.js');
>>>>>>>
const transactionTypes = require('../../helpers/transaction_types.js');
<<<<<<<
// Sort block's transactions
block.transactions = block.transactions.sort(a => {
if (block.id === library.genesisBlock.block.id) {
if (a.type === transactionTypes.VOTE) {
return 1;
}
}
if (a.type === transactionTypes.SIGNATURE) {
return 1;
}
return 0;
});
=======
>>>>>>> |
<<<<<<<
var constants = require('../../../helpers/constants');
var bignum = require('../../../helpers/bignum.js');
=======
const constants = require('../../../config/mainnet/constants');
>>>>>>>
var bignum = require('../../../helpers/bignum.js');
const constants = require('../../../config/mainnet/constants'); |
<<<<<<<
var RoundChanges = require('../helpers/round_changes.js');
=======
var RoundChanges = require('../helpers/RoundChanges.js');
var Promise = require('bluebird');
>>>>>>>
var RoundChanges = require('../helpers/round_changes.js');
var Promise = require('bluebird'); |
<<<<<<<
var transfer1 = lisk.transaction.transfer({
=======
const transaction = lisk.transaction.transfer({
>>>>>>>
const transfer1 = lisk.transaction.transfer({
<<<<<<<
var transfer2 = lisk.transaction.transfer({
=======
const transaction = lisk.transaction.transfer({
>>>>>>>
const transfer2 = lisk.transaction.transfer({
<<<<<<<
var delegateRegistration = lisk.transaction.registerDelegate({
=======
const transaction = lisk.transaction.registerDelegate({
>>>>>>>
const delegateRegistration = lisk.transaction.registerDelegate({
<<<<<<<
var promisesDelegatesMaxVotesPerTransaction = [];
var transactionsDelegateMaxForPerTransaction = [];
for (var i = 0; i < MAX_VOTES_PER_TRANSACTION; i++) {
var delegateRegistration = lisk.transaction.registerDelegate({
=======
const promisesDelegatesMaxVotesPerTransaction = [];
const transactionsDelegateMaxForPerTransaction = [];
for (let i = 0; i < MAX_VOTES_PER_TRANSACTION; i++) {
const transaction = lisk.transaction.registerDelegate({
>>>>>>>
const promisesDelegatesMaxVotesPerTransaction = [];
const transactionsDelegateMaxForPerTransaction = [];
for (let i = 0; i < MAX_VOTES_PER_TRANSACTION; i++) {
const delegateRegistration = lisk.transaction.registerDelegate({
<<<<<<<
var transactionsDelegateMaxVotesPerAccount = [];
var promisesDelegatesMaxVotesPerAccount = [];
for (var i = 0; i < ACTIVE_DELEGATES; i++) {
var delegateRegistration = lisk.transaction.registerDelegate({
=======
const transactionsDelegateMaxVotesPerAccount = [];
const promisesDelegatesMaxVotesPerAccount = [];
for (let i = 0; i < ACTIVE_DELEGATES; i++) {
const transaction = lisk.transaction.registerDelegate({
>>>>>>>
const transactionsDelegateMaxVotesPerAccount = [];
const promisesDelegatesMaxVotesPerAccount = [];
for (let i = 0; i < ACTIVE_DELEGATES; i++) {
const delegateRegistration = lisk.transaction.registerDelegate({ |
<<<<<<<
* Get round information from mem tables
* @return {Promise}
*/
getMemRounds() {
=======
* Get round information from mem tables.
*
* @return {Promise}
*/
getMemRounds () {
>>>>>>>
* Get round information from mem tables.
*
* @return {Promise}
*/
getMemRounds() {
<<<<<<<
* Remove a particular round from database
* @param {string} round - Id of the round
* @return {Promise}
*/
flush(round) {
=======
* Remove a particular round from database.
*
* @param {string} round - Id of the round
* @return {Promise}
*/
flush (round) {
>>>>>>>
* Remove a particular round from database.
*
* @param {string} round - Id of the round
* @return {Promise}
*/
flush(round) {
<<<<<<<
* Delete all blocks above a particular height
* @param {int} height
* @return {Promise}
*/
truncateBlocks(height) {
=======
* Delete all blocks above a particular height.
*
* @param {int} height
* @return {Promise}
*/
truncateBlocks (height) {
>>>>>>>
* Delete all blocks above a particular height.
*
* @param {int} height
* @return {Promise}
*/
truncateBlocks(height) {
<<<<<<<
* Update the missedblocks attribute for an account
* @param {boolean} backwards - Backward flag
* @param {string} outsiders - Comma separated string of ids
* @return {*}
*/
updateMissedBlocks(backwards, outsiders) {
=======
* Update the missedBlocks attribute for an account.
*
* @param {boolean} backwards - Backwards flag
* @param {string} outsiders - Comma separated string of ids
* @return {*}
*/
updateMissedBlocks (backwards, outsiders) {
>>>>>>>
* Update the missedBlocks attribute for an account.
*
* @param {boolean} backwards - Backwards flag
* @param {string} outsiders - Comma separated string of ids
* @return {*}
*/
updateMissedBlocks(backwards, outsiders) {
<<<<<<<
* Get votes for a round
* @param {string} round - Id of the round
* @return {Promise}
*/
getVotes(round) {
=======
* Get votes for a round.
*
* @param {string} round - Id of the round
* @return {Promise}
*/
getVotes (round) {
>>>>>>>
* Get votes for a round.
*
* @param {string} round - Id of the round
* @return {Promise}
*/
getVotes(round) {
<<<<<<<
* Update the votes of for a particular account
* @param {string} address - Address of the account
* @param {int} amount - Votes to update
*/
updateVotes(address, amount) {
=======
* Update the votes of for a particular account.
*
* @param {string} address - Address of the account
* @param {int} amount - Votes to update
*/
updateVotes (address, amount) {
>>>>>>>
* Update the votes of for a particular account.
*
* @param {string} address - Address of the account
* @param {int} amount - Votes to update
*/
updateVotes(address, amount) {
<<<<<<<
* Update id of a particular block for an account
* @param {string} newId
* @param {string} oldId
* @return {Promise}
*/
updateBlockId(newId, oldId) {
=======
* Update the blockId attribute for an account.
*
* @param {string} newId
* @param {string} oldId
* @return {Promise}
*/
updateBlockId (newId, oldId) {
>>>>>>>
* Update the blockId attribute for an account.
*
* @param {string} newId
* @param {string} oldId
* @return {Promise}
*/
updateBlockId(newId, oldId) {
<<<<<<<
* Summarize the results for a round
* @param {string} round - Id of the round
* @param {int} activeDelegates - Number of active delegates
* @return {Promise}
*/
summedRound(round, activeDelegates) {
=======
* Summarize the results for a round.
*
* @param {string} round - Id of the round
* @param {int} activeDelegates - Number of active delegates
* @return {Promise}
*/
summedRound (round, activeDelegates) {
>>>>>>>
* Summarize the results for a round.
*
* @param {string} round - Id of the round
* @param {int} activeDelegates - Number of active delegates
* @return {Promise}
*/
summedRound(round, activeDelegates) {
<<<<<<<
* Drop the table for round snapshot
* @return {Promise}
*/
clearRoundSnapshot() {
=======
* Drop the table for round snapshot.
*
* @return {Promise}
*/
clearRoundSnapshot () {
>>>>>>>
* Drop the table for round snapshot.
*
* @return {Promise}
*/
clearRoundSnapshot() {
<<<<<<<
* Create table for the round snapshot
* @return {Promise}
*/
performRoundSnapshot() {
=======
* Create table for the round snapshot.
*
* @return {Promise}
*/
performRoundSnapshot () {
>>>>>>>
* Create table for the round snapshot.
*
* @return {Promise}
*/
performRoundSnapshot() {
<<<<<<<
* Create table for the round snapshot
* @return {Promise}
*/
getDelegatesSnapshot(limit) {
=======
* Create table for the round snapshot.
*
* @return {Promise}
*/
getDelegatesSnapshot (limit) {
>>>>>>>
* Create table for the round snapshot.
*
* @return {Promise}
*/
getDelegatesSnapshot(limit) {
<<<<<<<
* Delete table for votes snapshot
* @return {Promise}
*/
clearVotesSnapshot() {
=======
* Delete table for votes snapshot.
*
* @return {Promise}
*/
clearVotesSnapshot () {
>>>>>>>
* Delete table for votes snapshot.
*
* @return {Promise}
*/
clearVotesSnapshot() {
<<<<<<<
* Take a snapshot of the votes by creating table and populating records from votes
* @return {Promise}
*/
performVotesSnapshot() {
=======
* Take a snapshot of the votes by creating table and populating records from votes.
*
* @return {Promise}
*/
performVotesSnapshot () {
>>>>>>>
* Take a snapshot of the votes by creating table and populating records from votes.
*
* @return {Promise}
*/
performVotesSnapshot() {
<<<<<<<
* Update accounts from the round snapshot
* @return {Promise}
*/
restoreRoundSnapshot() {
=======
* Update accounts from the round snapshot.
*
* @return {Promise}
*/
restoreRoundSnapshot () {
>>>>>>>
* Update accounts from the round snapshot.
*
* @return {Promise}
*/
restoreRoundSnapshot() {
<<<<<<<
* Update votes for account from a snapshot
* @return {Promise}
*/
restoreVotesSnapshot() {
=======
* Update votes for account from a snapshot.
*
* @return {Promise}
*/
restoreVotesSnapshot () {
>>>>>>>
* Update votes for account from a snapshot.
*
* @return {Promise}
*/
restoreVotesSnapshot() {
<<<<<<<
=======
/**
* Insert round information record into mem_rounds.
*
* @param {string} address - Address of the account
* @param {string} blockId - Associated block id
* @param {Number} round - Associated round number
* @param {Number} amount - Amount updated on account
* @return {Promise}
*/
insertRoundInformationWithAmount (address, blockId, round, amount) {
return this.db.none(sql.insertRoundInformationWithAmount, {
address: address,
amount: amount,
blockId: blockId,
round: round
});
}
/**
* Insert round information record into mem_rounds.
*
* @param {string} address - Address of the account
* @param {string} blockId - Associated block id
* @param {Number} round - Associated round number
* @param {string} delegateId - Associated delegate id
* @param {string} mode - Possible values of '+' or '-' represents behaviour of adding or removing delegate
* @return {Promise}
*/
insertRoundInformationWithDelegate (address, blockId, round, delegateId, mode) {
return this.db.none(sql.insertRoundInformationWithDelegate, {
address: address,
blockId: blockId,
round: round,
delegate: delegateId,
balanceMode: ( mode === '-' ? '-' : '')
});
}
>>>>>>>
/**
* Insert round information record into mem_rounds.
*
* @param {string} address - Address of the account
* @param {string} blockId - Associated block id
* @param {Number} round - Associated round number
* @param {Number} amount - Amount updated on account
* @return {Promise}
*/
insertRoundInformationWithAmount(address, blockId, round, amount) {
return this.db.none(sql.insertRoundInformationWithAmount, {
address: address,
amount: amount,
blockId: blockId,
round: round
});
}
/**
* Insert round information record into mem_rounds.
*
* @param {string} address - Address of the account
* @param {string} blockId - Associated block id
* @param {Number} round - Associated round number
* @param {string} delegateId - Associated delegate id
* @param {string} mode - Possible values of '+' or '-' represents behaviour of adding or removing delegate
* @return {Promise}
*/
insertRoundInformationWithDelegate(address, blockId, round, delegateId, mode) {
return this.db.none(sql.insertRoundInformationWithDelegate, {
address: address,
blockId: blockId,
round: round,
delegate: delegateId,
balanceMode: (mode === '-' ? '-' : '')
});
} |
<<<<<<<
var constants = require('../../../../../helpers/constants');
const bignum = require('../../../../../helpers/bignum.js');
=======
const constants = global.constants;
>>>>>>>
const bignum = require('../../../../../helpers/bignum.js');
const constants = global.constants; |
<<<<<<<
requester: keypair,
secondKeypair: secondKeypair,
data: req.body.data
=======
secondKeypair: secondKeypair
>>>>>>>
secondKeypair: secondKeypair,
data: req.body.data
<<<<<<<
});
} else {
modules.accounts.setAccountAndGet({publicKey: keypair.publicKey.toString('hex')}, function (err, account) {
if (err) {
return setImmediate(cb, err);
}
if (!account || !account.publicKey) {
return setImmediate(cb, 'Account not found');
}
if (account.secondSignature && !req.body.secondSecret) {
return setImmediate(cb, 'Missing second passphrase');
}
var secondKeypair = null;
if (account.secondSignature) {
var secondHash = crypto.createHash('sha256').update(req.body.secondSecret, 'utf8').digest();
secondKeypair = library.ed.makeKeypair(secondHash);
}
var transaction;
try {
transaction = library.logic.transaction.create({
type: transactionTypes.SEND,
amount: req.body.amount,
sender: account,
recipientId: recipientId,
keypair: keypair,
secondKeypair: secondKeypair,
data: req.body.data
});
} catch (e) {
return setImmediate(cb, e.toString());
}
modules.transactions.receiveTransactions([transaction], true, cb);
});
=======
}
});
}, function (err, transaction) {
if (err) {
return setImmediate(cb, err);
>>>>>>>
}
});
}, function (err, transaction) {
if (err) {
return setImmediate(cb, err); |
<<<<<<<
describe('createTables', function () {
it('should create the tables', function (done) {
accountLogic.createTables(function (err, res) {
expect(err).to.not.exist;
expect(res).to.be.undefined;
done();
});
});
});
describe('removeTables', function () {
=======
describe('resetMemTables', function () {
>>>>>>>
describe('resetMemTables', function () {
<<<<<<<
account.merge(validAccount.address, { balance: 'Not a Number' }, function (err) {
expect(err).to.equal('Encountered unsane number: Not a Number');
=======
account.merge(validAccount.address, {balance: 'Not a Number'}, function (err, res) {
expect(err).to.equal('Encountered insane number: Not a Number');
>>>>>>>
account.merge(validAccount.address, { balance: 'Not a Number' }, function (err) {
expect(err).to.equal('Encountered insane number: Not a Number'); |
<<<<<<<
if (!appConfig.api.enabled) {
return cb();
}
return scope.network.server.listen(
=======
// Security vulnerabilities fixed by Node v8.14.0 - "Slowloris (cve-2018-12122)"
scope.network.server.headersTimeout =
appConfig.api.options.limits.headersTimeout;
// Disconnect idle clients
scope.network.server.setTimeout(
appConfig.api.options.limits.serverSetTimeout
);
scope.network.server.on('timeout', socket => {
scope.logger.info(
`Disconnecting idle socket: ${socket.remoteAddress}:${
socket.remotePort
}`
);
socket.destroy();
});
scope.network.server.listen(
>>>>>>>
if (!appConfig.api.enabled) {
return cb();
}
// Security vulnerabilities fixed by Node v8.14.0 - "Slowloris (cve-2018-12122)"
scope.network.server.headersTimeout =
appConfig.api.options.limits.headersTimeout;
// Disconnect idle clients
scope.network.server.setTimeout(
appConfig.api.options.limits.serverSetTimeout
);
scope.network.server.on('timeout', socket => {
scope.logger.info(
`Disconnecting idle socket: ${socket.remoteAddress}:${
socket.remotePort
}`
);
socket.destroy();
});
return scope.network.server.listen( |
<<<<<<<
=======
describe('#generateAccount', () => {
const expectedRessult = {
privateKey:
'7683ba873c5e5aa6c12df564a60a93a519e2a5682cf5358a6a5b9ccc70607e96d803281f421e35ca585682829119c270a094fa9a1da2edc3dd65a3dc0dc46497',
publicKey: 'd803281f421e35ca585682829119c270a094fa9a1da2edc3dd65a3dc0dc46497',
};
it('should get publicKey', () => {
const callback = sinon.spy();
const secret = 'dream capable public heart sauce pilot ordinary fever final brand flock boring';
LSK.generateAccount(secret, callback);
(callback.called).should.be.true();
(callback.calledWith(expectedRessult)).should.be.true();
});
});
describe('#listMultisignatureTransactions', () => {
it('should list all current not signed multisignature transactions', () => {
return liskApi().listMultisignatureTransactions((result) => {
(result).should.be.ok();
(result).should.be.type('object');
});
});
});
describe('#getMultisignatureTransaction', () => {
it('should get a multisignature transaction by id', () => {
return liskApi().getMultisignatureTransaction('123', (result) => {
(result).should.be.ok();
(result).should.be.type('object');
});
});
});
>>>>>>>
describe('#generateAccount', () => {
const expectedRessult = {
privateKey:
'7683ba873c5e5aa6c12df564a60a93a519e2a5682cf5358a6a5b9ccc70607e96d803281f421e35ca585682829119c270a094fa9a1da2edc3dd65a3dc0dc46497',
publicKey: 'd803281f421e35ca585682829119c270a094fa9a1da2edc3dd65a3dc0dc46497',
};
it('should get publicKey', () => {
const callback = sinon.spy();
const secret = 'dream capable public heart sauce pilot ordinary fever final brand flock boring';
LSK.generateAccount(secret, callback);
(callback.called).should.be.true();
(callback.calledWith(expectedRessult)).should.be.true();
});
});
describe('#listMultisignatureTransactions', () => {
it('should list all current not signed multisignature transactions', () => {
return liskApi().listMultisignatureTransactions((result) => {
(result).should.be.ok();
(result).should.be.type('object');
});
});
});
describe('#getMultisignatureTransaction', () => {
it('should get a multisignature transaction by id', () => {
return liskApi().getMultisignatureTransaction('123', (result) => {
(result).should.be.ok();
(result).should.be.type('object');
});
});
});
<<<<<<<
describe('#checkReDial', () => {
it('should check if all the peers are already banned', () => {
const thisLSK = liskApi();
(privateApi.checkReDial.call(thisLSK)).should.be.equal(true);
});
it('should be able to get a new node when current one is not reachable', () => {
return liskApi({ node: externalNode, randomPeer: true }).sendRequest(GET, 'blocks/getHeight', {}, (result) => {
(result).should.be.type('object');
});
});
it('should recognize that now all the peers are banned for mainnet', () => {
const thisLSK = liskApi();
thisLSK.bannedPeers = liskApi().defaultPeers;
(privateApi.checkReDial.call(thisLSK)).should.be.equal(false);
});
it('should recognize that now all the peers are banned for testnet', () => {
const thisLSK = liskApi({ testnet: true });
thisLSK.bannedPeers = liskApi().defaultTestnetPeers;
(privateApi.checkReDial.call(thisLSK)).should.be.equal(false);
});
it('should recognize that now all the peers are banned for ssl', () => {
const thisLSK = liskApi({ ssl: true });
thisLSK.bannedPeers = liskApi().defaultSSLPeers;
(privateApi.checkReDial.call(thisLSK)).should.be.equal(false);
});
it('should stop redial when all the peers are banned already', () => {
const thisLSK = liskApi();
thisLSK.bannedPeers = liskApi().defaultPeers;
thisLSK.currentPeer = '';
return thisLSK.sendRequest(GET, 'blocks/getHeight').then((e) => {
(e.message).should.be.equal('could not create http request to any of the given peers');
});
});
it('should redial to new node when randomPeer is set true', () => {
const thisLSK = liskApi({ randomPeer: true, node: externalNode });
return thisLSK.getAccount('12731041415715717263L', (data) => {
(data).should.be.ok();
(data.success).should.be.equal(true);
});
});
it('should not redial to new node when randomPeer is set to true but unknown nethash provided', () => {
const thisLSK = liskApi({ randomPeer: true, node: externalNode, nethash: '123' });
(privateApi.checkReDial.call(thisLSK)).should.be.equal(false);
});
it('should redial to mainnet nodes when nethash is set and randomPeer is true', () => {
const thisLSK = liskApi({ randomPeer: true, node: externalNode, nethash: 'ed14889723f24ecc54871d058d98ce91ff2f973192075c0155ba2b7b70ad2511' });
(privateApi.checkReDial.call(thisLSK)).should.be.equal(true);
(thisLSK.testnet).should.be.equal(false);
});
it('should redial to testnet nodes when nethash is set and randomPeer is true', () => {
const thisLSK = liskApi({ randomPeer: true, node: externalNode, nethash: 'da3ed6a45429278bac2666961289ca17ad86595d33b31037615d4b8e8f158bba' });
(privateApi.checkReDial.call(thisLSK)).should.be.equal(true);
(thisLSK.testnet).should.be.equal(true);
});
it('should not redial when randomPeer is set false', () => {
const thisLSK = liskApi({ randomPeer: false });
(privateApi.checkReDial.call(thisLSK)).should.be.equal(false);
});
});
describe('#sendRequest with promise', () => {
it('should be able to use sendRequest as a promise for GET', () => {
return liskApi().sendRequest(GET, 'blocks/getHeight', {}).then((result) => {
(result).should.be.type('object');
(result.success).should.be.equal(true);
(result.height).should.be.type('number');
});
});
it('should be able to use sendRequest as a promise for POST', () => {
const options = {
ssl: false,
node: '',
randomPeer: true,
testnet: true,
port: testPort,
bannedPeers: [],
};
const LSKnode = liskApi(options);
const secret = 'soap arm custom rhythm october dove chunk force own dial two odor';
const secondSecret = 'spider must salmon someone toe chase aware denial same chief else human';
const recipient = '10279923186189318946L';
const amount = 100000000;
return LSKnode.sendRequest(GET, 'transactions', { recipientId: recipient, secret, secondSecret, amount }).then((result) => {
(result).should.be.type('object');
(result).should.be.ok();
});
});
it('should retry timestamp in future failures', () => {
const thisLSK = liskApi();
const successResponse = { body: { success: true } };
const futureTimestampResponse = {
body: { success: false, message: 'Invalid transaction timestamp. Timestamp is in the future' },
};
const stub = sinon.stub(privateApi, 'sendRequestPromise');
const spy = sinon.spy(thisLSK, 'sendRequest');
stub.resolves(futureTimestampResponse);
stub.onThirdCall().resolves(successResponse);
return thisLSK.sendRequest(POST, 'transactions')
.then(() => {
(spy.callCount).should.equal(3);
(spy.args[1][2]).should.have.property('timeOffset').equal(10);
(spy.args[2][2]).should.have.property('timeOffset').equal(20);
stub.restore();
spy.restore();
});
});
it('should not retry timestamp in future failures forever', () => {
const thisLSK = liskApi();
const futureTimestampResponse = {
body: { success: false, message: 'Invalid transaction timestamp. Timestamp is in the future' },
};
const stub = sinon.stub(privateApi, 'sendRequestPromise');
const spy = sinon.spy(thisLSK, 'sendRequest');
stub.resolves(futureTimestampResponse);
return thisLSK.sendRequest(POST, 'transactions')
.then((response) => {
(response).should.equal(futureTimestampResponse.body);
stub.restore();
spy.restore();
});
});
});
describe('#listMultisignatureTransactions', () => {
it('should list all current not signed multisignature transactions', () => {
return liskApi().listMultisignatureTransactions((result) => {
(result).should.be.ok();
(result).should.be.type('object');
});
});
});
describe('#getMultisignatureTransaction', () => {
it('should get a multisignature transaction by id', () => {
return liskApi().getMultisignatureTransaction('123', (result) => {
(result).should.be.ok();
(result).should.be.type('object');
});
});
});
=======
>>>>>>>
<<<<<<<
describe('#createRequestObject', () => {
let options;
let LSKAPI;
let expectedObject;
beforeEach(() => {
options = { limit: 5, offset: 3, details: defaultData };
LSKAPI = liskApi({ node: localNode });
expectedObject = {
method: GET,
url: 'http://localhost:8000/api/transaction',
headers: {
'Content-Type': 'application/json',
nethash: 'ed14889723f24ecc54871d058d98ce91ff2f973192075c0155ba2b7b70ad2511',
broadhash: 'ed14889723f24ecc54871d058d98ce91ff2f973192075c0155ba2b7b70ad2511',
os: 'lisk-js-api',
version: '1.0.0',
minVersion: '>=0.5.0',
port: 8000,
},
body: {},
};
});
it('should create a valid request Object for GET request', () => {
const requestObject = privateApi.createRequestObject.call(LSKAPI, GET, 'transaction', options);
expectedObject.url = 'http://localhost:8000/api/transaction?limit=5&offset=3&details=testData';
(requestObject).should.be.eql(expectedObject);
});
it('should create a valid request Object for POST request', () => {
const requestObject = privateApi.createRequestObject.call(LSKAPI, POST, 'transaction', options);
expectedObject.body = { limit: 5, offset: 3, details: 'testData' };
expectedObject.method = POST;
(requestObject).should.be.eql(expectedObject);
});
it('should create a valid request Object for POST request without options', () => {
const requestObject = privateApi.createRequestObject.call(LSKAPI, POST, 'transaction');
expectedObject.method = POST;
(requestObject).should.be.eql(expectedObject);
});
it('should create a valid request Object for undefined request without options', () => {
const requestObject = privateApi.createRequestObject.call(LSKAPI, undefined, 'transaction');
expectedObject.method = undefined;
(requestObject).should.be.eql(expectedObject);
});
});
describe('#constructRequestData', () => {
it('should construct optional request data for API helper functions', () => {
const address = '123';
const requestData = {
limit: '123',
offset: 5,
};
const expectedObject = {
address: '123',
limit: '123',
offset: 5,
};
const createObject = privateApi.constructRequestData({ address }, requestData);
(createObject).should.be.eql(expectedObject);
});
it('should construct with variable and callback', () => {
const address = '123';
const expectedObject = {
address: '123',
};
const createObject = privateApi.constructRequestData({ address }, () => { return '123'; });
(createObject).should.be.eql(expectedObject);
});
});
=======
>>>>>>>
describe('#constructRequestData', () => {
it('should construct optional request data for API helper functions', () => {
const address = '123';
const requestData = {
limit: '123',
offset: 5,
};
const expectedObject = {
address: '123',
limit: '123',
offset: 5,
};
const createObject = privateApi.constructRequestData({ address }, requestData);
(createObject).should.be.eql(expectedObject);
});
it('should construct with variable and callback', () => {
const address = '123';
const expectedObject = {
address: '123',
};
const createObject = privateApi.constructRequestData({ address }, () => { return '123'; });
(createObject).should.be.eql(expectedObject);
});
}); |
<<<<<<<
=======
applicationState,
registeredTransactions,
>>>>>>>
registeredTransactions,
<<<<<<<
const Transaction = require('../logic/transaction');
const Block = require('../logic/block');
const Account = require('../logic/account');
=======
const InitTransaction = require('../logic/init_transaction.js');
const Block = require('../logic/block.js');
const Account = require('../logic/account.js');
const Peers = require('../logic/peers.js');
const StateManager = require('../logic/state_store/index.js');
>>>>>>>
const InitTransaction = require('../logic/init_transaction.js');
const Block = require('../logic/block.js');
const Account = require('../logic/account.js');
const StateManager = require('../logic/state_store/index.js');
<<<<<<<
=======
const peersLogic = await new Promise((resolve, reject) => {
new Peers(logger, config, applicationState, (err, object) => {
err ? reject(err) : resolve(object);
});
});
const stateManager = await new Promise((resolve, reject) => {
new StateManager(storage, (err, object) => {
err ? reject(err) : resolve(object);
});
});
>>>>>>>
const stateManager = await new Promise((resolve, reject) => {
new StateManager(storage, (err, object) => {
err ? reject(err) : resolve(object);
});
});
<<<<<<<
=======
peers: peersLogic,
stateManager,
>>>>>>>
stateManager, |
<<<<<<<
const { FEES } = __testContext.config.constants;
=======
const constants = __testContext.config.constants;
const exceptions = __testContext.config.exceptions;
>>>>>>>
const { FEES } = __testContext.config.constants;
const exceptions = __testContext.config.exceptions; |
<<<<<<<
{ chain: require('@liskhq/lisk-chain') },
{ loader: require('../../../src/application/node/loader') },
=======
{ blocks: require('@liskhq/lisk-blocks') },
>>>>>>>
{ chain: require('@liskhq/lisk-chain') }, |
<<<<<<<
var apiCodes = require('../../helpers/apiCodes.js');
var ApiError = require('../../helpers/apiError.js');
=======
var apiCodes = require('../../helpers/api_codes.js');
var ApiError = require('../../helpers/api_error.js');
var blockReward = require('../../logic/block_reward.js');
var constants = require('../../helpers/constants.js');
>>>>>>>
var apiCodes = require('../../helpers/api_codes.js');
var ApiError = require('../../helpers/api_error.js'); |
<<<<<<<
const { Status: TransactionStatus } = require('@liskhq/lisk-transactions');
const slots = require('../../helpers/slots.js');
=======
const slots = require('../../helpers/slots');
>>>>>>>
const { Status: TransactionStatus } = require('@liskhq/lisk-transactions');
const slots = require('../../helpers/slots'); |
<<<<<<<
this.subSocket.once(eventName, data => {
setImmediate(cb, data);
=======
this.subSocket.on(eventName, data => {
cb(data);
>>>>>>>
this.subSocket.once(eventName, data => {
cb(data);
<<<<<<<
this.subSocket.sock.once(eventName, data => {
setImmediate(cb, data);
=======
// TODO: make it `once` instead of `on`
this.subSocket.on(eventName, data => {
cb(data);
>>>>>>>
this.subSocket.sock.once(eventName, data => {
cb(data); |
<<<<<<<
(everyTransaction, callback) => {
var filter = {
id: everyTransaction.id,
=======
(transaction, callback) => {
const filter = {
id: transaction.id,
>>>>>>>
(everyTransaction, callback) => {
const filter = {
id: everyTransaction.id,
<<<<<<<
(everyTransaction, callback) => {
var filter = {
id: everyTransaction.id,
=======
(transaction, callback) => {
const filter = {
id: transaction.id,
>>>>>>>
(everyTransaction, callback) => {
const filter = {
id: everyTransaction.id, |
<<<<<<<
processorModule,
roundsModule,
=======
dposModule,
>>>>>>>
processorModule,
dposModule,
<<<<<<<
this.processorModule = processorModule;
this.roundsModule = roundsModule;
=======
this.dposModule = dposModule;
>>>>>>>
this.processorModule = processorModule;
this.dposModule = dposModule; |
<<<<<<<
forging: {
waitThreshold: 2,
},
=======
transactions: {
maxTransactionsPerQueue: 1000,
},
>>>>>>>
forging: {
waitThreshold: 2,
},
transactions: {
maxTransactionsPerQueue: 1000,
}, |
<<<<<<<
'mem_round',
'rounds_rewards',
=======
'peers',
>>>>>>>
'mem_round',
'rounds_rewards',
'peers', |
<<<<<<<
const constants = require('../helpers/constants.js');
const bignum = require('../helpers/bignum.js');
=======
>>>>>>>
const bignum = require('../helpers/bignum.js'); |
<<<<<<<
const networkHeight = await library.channel.invoke(
'chain:getNetworkHeight',
{
options: {
normalized: false,
},
}
);
const { height, broadhash } = library.applicationState;
const consensus =
(await library.channel.invoke('chain:getLastConsensus')) || 0;
const loaded = await library.channel.invoke('chain:loaderLoaded');
const syncing = await library.channel.invoke('chain:loaderSyncing');
const transactions = await library.channel.invoke(
'chain:getAllTransactionsCount'
);
const slotTime = await library.channel.invoke('chain:getSlotTime');
=======
const {
broadhash,
consensus,
secondsSinceEpoch,
loaded,
networkHeight,
syncing,
transactions,
lastBlock,
} = await library.channel.invoke('chain:getNodeStatus');
>>>>>>>
const {
consensus,
secondsSinceEpoch,
loaded,
networkHeight,
syncing,
transactions,
lastBlock,
} = await library.channel.invoke('chain:getNodeStatus'); |
<<<<<<<
import { checkIfCan } from '../roles/roles';
import { ActivityCollection } from '../activity';
import { Deployments } from '../deployment/deployment.collection';
=======
import Activity from '../graphql/activity/activity.model';
>>>>>>>
import { checkIfCan } from '../roles/roles';
import { Deployments } from '../deployment/deployment.collection';
import Activity from '../graphql/activity/activity.model';
<<<<<<<
check(nolog, Boolean);
checkIfCan('nlu-data:r', instance.projectId);
=======
>>>>>>> |
<<<<<<<
var check = blocksVerify.verifyBlock(invalidBlock);
expect(check).to.equal(['Invalid block reward:', invalidBlock.reward, 'expected:', validBlock1.reward].join(' '));
done();
=======
blocksVerify.verifyBlock(invalidBlock, function (err) {
expect(err).to.equal(['Invalid block reward:', invalidBlock.reward, 'expected:', validBlock.reward].join(' '));
done();
});
>>>>>>>
blocksVerify.verifyBlock(invalidBlock, function (err) {
expect(err).to.equal(['Invalid block reward:', invalidBlock.reward, 'expected:', validBlock1.reward].join(' '));
done();
});
<<<<<<<
invalidBlock.transactions.push(invalidBlock.transactions[0]);
invalidBlock.numberOfTransactions = 2;
var check = blocksVerify.verifyBlock(invalidBlock);
expect(check).to.equal('Encountered duplicate transaction: ' + invalidBlock.transactions[1].id);
done();
=======
invalidBlock.transactions[1] = invalidBlock.transactions[0];
blocksVerify.verifyBlock(invalidBlock, function (err) {
expect(err).to.equal('Encountered duplicate transaction: ' + invalidBlock.transactions[1].id);
done();
});
>>>>>>>
invalidBlock.transactions.push(invalidBlock.transactions[0]);
invalidBlock.numberOfTransactions = 2;
blocksVerify.verifyBlock(invalidBlock, function (err) {
expect(err).to.equal('Encountered duplicate transaction: ' + invalidBlock.transactions[1].id);
done();
}); |
<<<<<<<
* Validate Block Slot - Validates if block generator is valid delegate.
*
* @private
* @async
* @method validateBlockSlot
* @param {Object} block Full normalized block
* @param {Object} lastBlock Full normalized block
* @param {Function} cb Callback function
*/
__private.validateBlockSlot = function (block, lastBlock, cb) {
var roundNextBlock = slots.calcRound(block.height);
var roundLastBlock = slots.calcRound(lastBlock.height);
if (lastBlock.height % slots.delegates === 0 || roundLastBlock < roundNextBlock) {
// Check if block was generated by the right active delagate from previous round.
// DATABASE: Read only to mem_accounts to extract active delegate list
modules.delegates.validateBlockSlotAgainstPreviousRound(block, function (err) {
return setImmediate(cb, err);
});
} else {
// Check if block was generated by the right active delagate.
// DATABASE: Read only to mem_accounts to extract active delegate list
modules.delegates.validateBlockSlot(block, function (err) {
return setImmediate(cb, err);
});
}
};
/**
=======
* Validate if block generator is valid delegate.
*
* @private
* @async
* @method validateBlockSlot
* @param {Object} block - Current normalized block
* @param {Object} lastBlock - Last normalized block
* @param {Function} cb - Callback function
*/
__private.validateBlockSlot = function (block, lastBlock, cb) {
var roundNextBlock = modules.rounds.calc(block.height);
var roundLastBlock = modules.rounds.calc(lastBlock.height);
if (lastBlock.height % slots.delegates === 0 || roundLastBlock < roundNextBlock) {
// Check if block was generated by the right active delagate from previous round.
// DATABASE: Read only to mem_accounts to extract active delegate list
modules.delegates.validateBlockSlotAgainstPreviousRound(block, function (err) {
return setImmediate(cb, err);
});
} else {
// Check if block was generated by the right active delagate.
// DATABASE: Read only to mem_accounts to extract active delegate list
modules.delegates.validateBlockSlot(block, function (err) {
return setImmediate(cb, err);
});
}
};
/**
>>>>>>>
* Validate if block generator is valid delegate.
*
* @private
* @async
* @method validateBlockSlot
* @param {Object} block - Current normalized block
* @param {Object} lastBlock - Last normalized block
* @param {Function} cb - Callback function
*/
__private.validateBlockSlot = function (block, lastBlock, cb) {
var roundNextBlock = slots.calcRound(block.height);
var roundLastBlock = slots.calcRound(lastBlock.height);
if (lastBlock.height % slots.delegates === 0 || roundLastBlock < roundNextBlock) {
// Check if block was generated by the right active delagate from previous round.
// DATABASE: Read only to mem_accounts to extract active delegate list
modules.delegates.validateBlockSlotAgainstPreviousRound(block, function (err) {
return setImmediate(cb, err);
});
} else {
// Check if block was generated by the right active delagate.
// DATABASE: Read only to mem_accounts to extract active delegate list
modules.delegates.validateBlockSlot(block, function (err) {
return setImmediate(cb, err);
});
}
};
/** |
<<<<<<<
=======
var Bignum = require('../../../helpers/bignum.js');
var Vote = require('../../../logic/vote');
>>>>>>>
var Bignum = require('../../../helpers/bignum.js');
var Vote = require('../../../logic/vote'); |
<<<<<<<
=======
// Public methods
/**
* Checks if private constant syncIntervalId has value.
*
* @returns {boolean} True if syncIntervalId has value
*/
Loader.prototype.syncing = function() {
return !!__private.syncIntervalId;
};
/**
* Checks if `modules` is loaded.
*
* @returns {boolean} True if `modules` is loaded
*/
Loader.prototype.isLoaded = function() {
return !!modules;
};
/**
* Checks private constant loaded.
*
* @returns {boolean} False if not loaded
*/
Loader.prototype.loaded = function() {
return !!__private.loaded;
};
// Events
/**
* Pulls Transactions and signatures.
*
* @returns {function} Calling __private.syncTimer()
*/
Loader.prototype.onNetworkReady = function() {
library.logger.trace('Peers ready', { module: 'loader' });
// Enforce sync early
if (library.config.syncing.active) {
__private.syncTimer();
}
setImmediate(() => {
async.series(
{
loadTransactions(seriesCb) {
if (__private.loaded) {
return async.retry(
__private.retries,
__private.getTransactionsFromNetwork,
err => {
if (err) {
library.logger.error('Unconfirmed transactions loader', err);
}
return setImmediate(seriesCb);
}
);
}
return setImmediate(seriesCb);
},
loadSignatures(seriesCb) {
if (__private.loaded) {
return async.retry(
__private.retries,
__private.getSignaturesFromNetwork,
err => {
if (err) {
library.logger.error('Signatures loader', err);
}
return setImmediate(seriesCb);
}
);
}
return setImmediate(seriesCb);
},
},
err => {
library.logger.trace('Transactions and signatures pulled', err);
}
);
});
};
/**
* It assigns components & modules from scope to private constants.
*
* @param {components, modules} scope modules & components
* @returns {function} Calling __private.loadBlockChain
* @todo Add description for the params
*/
Loader.prototype.onBind = function(scope) {
components = {
cache: scope.components ? scope.components.cache : undefined,
};
modules = {
transactions: scope.modules.transactions,
blocks: scope.modules.blocks,
peers: scope.modules.peers,
rounds: scope.modules.rounds,
multisignatures: scope.modules.multisignatures,
};
__private.loadBlockChain();
};
/**
* Sets private constant loaded to true.
*/
Loader.prototype.onBlockchainReady = function() {
__private.loaded = true;
};
/**
* Sets private constant loaded to false.
*
* @param {function} cb
* @todo Add description for the params
*/
Loader.prototype.cleanup = function() {
__private.loaded = false;
};
>>>>>>> |
<<<<<<<
var busMessage = get('library.bus.message');
expect(busMessage.calledOnce).to.be.true;
return expect(busMessage.calledWith('finishRound', roundScope.round))
.to.be.true;
=======
const bus = get('library.bus.message');
expect(bus.calledOnce).to.be.true;
return expect(bus.calledWith('finishRound', roundScope.round)).to.be
.true;
>>>>>>>
const busMessage = get('library.bus.message');
expect(busMessage.calledOnce).to.be.true;
return expect(busMessage.calledWith('finishRound', roundScope.round))
.to.be.true;
<<<<<<<
var busMessage = get('library.bus.message');
return expect(busMessage.called).to.be.false;
=======
const bus = get('library.bus.message');
return expect(bus.called).to.be.false;
>>>>>>>
const busMessage = get('library.bus.message');
return expect(busMessage.called).to.be.false; |
<<<<<<<
export function theSecondPassphraseIsProvidedViaStdIn() {
const { passphrase, secondPassphrase } = this.test.ctx;
inputUtils.getStdIn.resolves({ passphrase, data: secondPassphrase });
inputUtils.getPassphrase.onSecondCall().resolves(secondPassphrase);
}
export function thePassphraseAndTheSecondPassphraseAreProvidedViaStdIn() {
const { passphrase, secondPassphrase } = this.test.ctx;
inputUtils.getStdIn.resolves({ passphrase, data: secondPassphrase });
inputUtils.getPassphrase.onFirstCall().resolves(passphrase);
inputUtils.getPassphrase.onSecondCall().resolves(secondPassphrase);
}
=======
export function thePassphraseAndThePasswordAreProvidedViaStdIn() {
const { passphrase, password } = this.test.ctx;
inputUtils.getStdIn.resolves({ passphrase, data: password });
inputUtils.getPassphrase.onFirstCall().resolves(passphrase);
inputUtils.getPassphrase.onSecondCall().resolves(password);
}
export function thePasswordIsProvidedViaStdIn() {
const { password } = this.test.ctx;
inputUtils.getStdIn.resolves({ data: password });
}
>>>>>>>
export function theSecondPassphraseIsProvidedViaStdIn() {
const { passphrase, secondPassphrase } = this.test.ctx;
inputUtils.getStdIn.resolves({ passphrase, data: secondPassphrase });
inputUtils.getPassphrase.onSecondCall().resolves(secondPassphrase);
}
export function thePassphraseAndTheSecondPassphraseAreProvidedViaStdIn() {
const { passphrase, secondPassphrase } = this.test.ctx;
inputUtils.getStdIn.resolves({ passphrase, data: secondPassphrase });
inputUtils.getPassphrase.onFirstCall().resolves(passphrase);
inputUtils.getPassphrase.onSecondCall().resolves(secondPassphrase);
}
export function thePassphraseAndThePasswordAreProvidedViaStdIn() {
const { passphrase, password } = this.test.ctx;
inputUtils.getStdIn.resolves({ passphrase, data: password });
inputUtils.getPassphrase.onFirstCall().resolves(passphrase);
inputUtils.getPassphrase.onSecondCall().resolves(password);
}
export function thePasswordIsProvidedViaStdIn() {
const { password } = this.test.ctx;
inputUtils.getStdIn.resolves({ data: password });
}
<<<<<<<
export function anOptionsObjectWithPassphraseSetToAndSecondPassphraseSetTo() {
const { secondPassphrase, passphrase } = this.test.ctx;
const [passphraseSource, secondPassphraseSource] = getQuotedStrings(this.test.parent.title);
if (typeof inputUtils.getPassphrase.resolves === 'function') {
inputUtils.getPassphrase.onFirstCall().resolves(passphrase);
inputUtils.getPassphrase.onSecondCall().resolves(secondPassphrase);
}
this.test.ctx.options = { passphrase: passphraseSource, 'second-passphrase': secondPassphraseSource };
}
=======
export function anOptionsObjectWithOutputPublicKeySetToBoolean() {
const outputPublicKey = getFirstBoolean(this.test.parent.title);
this.test.ctx.options = { 'output-public-key': outputPublicKey };
}
export function anOptionsObjectWithPassphraseSetToAndPasswordSetTo() {
const [passphrase, password] = getQuotedStrings(this.test.parent.title);
this.test.ctx.options = { passphrase, password };
}
export function anOptionsObjectWithPasswordSetTo() {
const { password } = this.test.ctx;
const passwordSource = getFirstQuotedString(this.test.parent.title);
if (typeof inputUtils.getPassphrase.resolves === 'function') {
inputUtils.getPassphrase.onSecondCall().resolves(password);
}
this.test.ctx.options = { password: passwordSource };
}
export function anOptionsObjectWithPasswordSetToUnknownSource() {
const password = getFirstQuotedString(this.test.parent.title);
if (typeof inputUtils.getPassphrase.resolves === 'function') {
inputUtils.getPassphrase.onSecondCall().rejects(new Error('Unknown data source type. Must be one of `file`, or `stdin`.'));
}
this.test.ctx.options = { password };
}
>>>>>>>
export function anOptionsObjectWithPassphraseSetToAndSecondPassphraseSetTo() {
const { secondPassphrase, passphrase } = this.test.ctx;
const [passphraseSource, secondPassphraseSource] = getQuotedStrings(this.test.parent.title);
if (typeof inputUtils.getPassphrase.resolves === 'function') {
inputUtils.getPassphrase.onFirstCall().resolves(passphrase);
inputUtils.getPassphrase.onSecondCall().resolves(secondPassphrase);
}
this.test.ctx.options = { passphrase: passphraseSource, 'second-passphrase': secondPassphraseSource };
}
export function anOptionsObjectWithOutputPublicKeySetToBoolean() {
const outputPublicKey = getFirstBoolean(this.test.parent.title);
this.test.ctx.options = { 'output-public-key': outputPublicKey };
}
export function anOptionsObjectWithPassphraseSetToAndPasswordSetTo() {
const [passphrase, password] = getQuotedStrings(this.test.parent.title);
this.test.ctx.options = { passphrase, password };
}
export function anOptionsObjectWithPasswordSetTo() {
const { password } = this.test.ctx;
const passwordSource = getFirstQuotedString(this.test.parent.title);
if (typeof inputUtils.getPassphrase.resolves === 'function') {
inputUtils.getPassphrase.onSecondCall().resolves(password);
}
this.test.ctx.options = { password: passwordSource };
}
export function anOptionsObjectWithPasswordSetToUnknownSource() {
const password = getFirstQuotedString(this.test.parent.title);
if (typeof inputUtils.getPassphrase.resolves === 'function') {
inputUtils.getPassphrase.onSecondCall().rejects(new Error('Unknown data source type. Must be one of `file`, or `stdin`.'));
}
this.test.ctx.options = { password };
}
<<<<<<<
inputUtils.getPassphrase.rejects(new Error('Unknown passphrase source type. Must be one of `file`, or `stdin`.'));
=======
inputUtils.getPassphrase.onFirstCall().rejects(new Error('Unknown data source type. Must be one of `file`, or `stdin`.'));
>>>>>>>
inputUtils.getPassphrase.onFirstCall().rejects(new Error('Unknown passphrase source type. Must be one of `file`, or `stdin`.')); |
<<<<<<<
importTest("transactions newCrypto", './transactions/crypto/index.js');
=======
importTest("api", './api/liskApi.js');
importTest("api", './api/parseTransaction.js');
>>>>>>>
importTest("transactions newCrypto", './transactions/crypto/index.js');
importTest("api", './api/liskApi.js');
importTest("api", './api/parseTransaction.js'); |
<<<<<<<
import { check } from 'meteor/check';
import { can, checkIfCan } from '../../lib/scopes';
=======
import { can } from '../../lib/scopes';
import { GlobalSettingsSchema } from './globalSettings.schema';
>>>>>>>
import { can } from '../../lib/scopes';
import { GlobalSettingsSchema } from './globalSettings.schema';
<<<<<<<
const orchestration = process.env.ORCHESTRATOR ? process.env.ORCHESTRATOR : 'docker-compose';
import(`./globalSettings.schema.${orchestration}`)
.then(({ GlobalSettingsSchema }) => {
GlobalSettings.attachSchema(GlobalSettingsSchema);
if (Meteor.isServer) {
Meteor.publish('settings', function () {
if (can('global-settings:r', { anyScope: true })) return GlobalSettings.find({ _id: 'SETTINGS' });
return GlobalSettings.find({ _id: 'SETTINGS' }, { fields: { 'settings.public': 1 } });
});
}
});
=======
GlobalSettings.attachSchema(GlobalSettingsSchema);
if (Meteor.isServer) {
Meteor.publish('settings', function() {
if (can('global-admin', this.userId)) return GlobalSettings.find({ _id: 'SETTINGS' });
return GlobalSettings.find({ _id: 'SETTINGS' }, { fields: { 'settings.public': 1 } });
});
}
>>>>>>>
GlobalSettings.attachSchema(GlobalSettingsSchema);
if (Meteor.isServer) {
Meteor.publish('settings', function() {
if (can('global-settings:r', { anyScope: true })) return GlobalSettings.find({ _id: 'SETTINGS' });
return GlobalSettings.find({ _id: 'SETTINGS' }, { fields: { 'settings.public': 1 } });
});
} |
<<<<<<<
promises.push(creditAccountPromise(account.address, 1000 * node.normalizer));
promises.push(creditAccountPromise(accountMinimalFunds.address, constants.fees.secondsignature));
promises.push(creditAccountPromise(accountNoSecondPassword.address, constants.fees.secondsignature));
promises.push(creditAccountPromise(accountDuplicate.address, constants.fees.secondsignature));
=======
promises.push(creditAccountPromise(account.address, 100000000000));
promises.push(creditAccountPromise(accountMinimalFunds.address, constants.fees.secondSignature));
promises.push(creditAccountPromise(accountNoSecondPassword.address, constants.fees.secondSignature));
promises.push(creditAccountPromise(accountDuplicate.address, constants.fees.secondSignature));
>>>>>>>
promises.push(creditAccountPromise(account.address, 1000 * node.normalizer));
promises.push(creditAccountPromise(accountMinimalFunds.address, constants.fees.secondSignature));
promises.push(creditAccountPromise(accountNoSecondPassword.address, constants.fees.secondSignature));
promises.push(creditAccountPromise(accountDuplicate.address, constants.fees.secondSignature)); |
<<<<<<<
const { BFT } = require('./bft');
const { Synchronizer } = require('./synchronizer');
=======
>>>>>>>
const { Synchronizer } = require('./synchronizer'); |
<<<<<<<
=======
* Loads full blocks from database, used when rebuilding blockchain, snapshotting,
* see: loader.loadBlockChain (private).
*
* @param {number} blocksAmount - Amount of blocks
* @param {number} fromHeight - Height to start at
* @param {function} cb - Callback function
* @returns {function} cb - Callback function from params (through setImmediate)
* @returns {Object} cb.err - Error if occurred
* @returns {Object} cb.lastBlock - Current last block
*/
Process.prototype.loadBlocksOffset = function(
blocksAmount,
fromHeight = 0,
cb
) {
// Calculate toHeight
const toHeight = fromHeight + blocksAmount;
library.logger.debug('Loading blocks offset', {
limit: toHeight,
offset: fromHeight,
});
const filters = {
height_gte: fromHeight,
height_lt: toHeight,
};
const options = {
limit: null,
sort: ['height:asc', 'rowId:asc'],
extended: true,
};
// Loads extended blocks from storage
library.storage.entities.Block.get(filters, options)
.then(rows => {
// Normalize blocks
const blocks = modules.blocks.utils.readStorageRows(rows);
async.eachSeries(
blocks,
(block, eachBlockSeriesCb) => {
// Stop processing if node shutdown was requested
if (modules.blocks.isCleaning.get()) {
return setImmediate(eachBlockSeriesCb);
}
library.logger.debug('Processing block', block.id);
if (block.id === library.genesisBlock.block.id) {
// Apply block - saveBlock: false
return modules.blocks.chain.applyGenesisBlock(block, err =>
setImmediate(eachBlockSeriesCb, err)
);
}
// Process block - broadcast: false, saveBlock: false
return modules.blocks.verify.processBlock(
block,
false,
false,
err => {
if (err) {
library.logger.debug('Block processing failed', {
id: block.id,
err: err.toString(),
module: 'blocks',
block,
});
}
return setImmediate(eachBlockSeriesCb, err);
}
);
},
err => setImmediate(cb, err, modules.blocks.lastBlock.get())
);
})
.catch(err => {
library.logger.error(err);
return setImmediate(
cb,
new Error(`Blocks#loadBlocksOffset error: ${err}`)
);
});
};
/**
* Ask the network for blocks and process them.
*
* @param {function} cb - Callback function
* @returns {function} cb - Callback function from params (through setImmediate)
* @returns {Object} cb.err - Error if occurred
* @returns {Object} cb.lastValidBlock - Normalized new last block
*/
Process.prototype.loadBlocksFromNetwork = function(cb) {
let lastValidBlock = modules.blocks.lastBlock.get();
library.logger.debug('Loading blocks from the network');
async function getBlocksFromNetwork() {
// TODO: If there is an error, invoke the applyPenalty action on the Network module once it is implemented.
// TODO: Rename procedure to include target module name. E.g. chain:blocks
let data;
try {
const response = await library.channel.invoke('network:request', {
procedure: 'blocks',
data: {
lastBlockId: lastValidBlock.id,
},
});
data = response.data;
} catch (p2pError) {
library.logger.error('Failed to load block from network', p2pError);
return [];
}
if (!data) {
throw new Error('Received an invalid blocks response from the network');
}
// Check for strict equality for backwards compatibility reasons.
if (data.success === false) {
throw new Error(
`Peer did not have a matching lastBlockId. ${data.message}`
);
}
return data.blocks;
}
function validateBlocks(blocks, seriesCb) {
const report = library.schema.validate(blocks, definitions.WSBlocksList);
if (!report) {
return setImmediate(seriesCb, new Error('Received invalid blocks data'));
}
return setImmediate(seriesCb, null, blocks);
}
// Process all received blocks
function processBlocks(blocks, seriesCb) {
// Skip if ther is no blocks
if (blocks.length === 0) {
return setImmediate(seriesCb);
}
// Iterate over received blocks, normalize block first...
return async.eachSeries(
modules.blocks.utils.readDbRows(blocks),
(block, eachSeriesCb) => {
if (modules.blocks.isCleaning.get()) {
// Cancel processing if node shutdown was requested
return setImmediate(eachSeriesCb);
}
// ...then process block
// TODO: If there is an error, invoke the applyPenalty action on the Network module once it is implemented.
return processBlock(block, err => eachSeriesCb(err));
},
err => setImmediate(seriesCb, err)
);
}
// Process single block
function processBlock(block, seriesCb) {
// Start block processing - broadcast: false, saveBlock: true
modules.blocks.verify.processBlock(block, false, true, err => {
if (!err) {
// Update last valid block
lastValidBlock = block;
library.logger.info(
`Block ${block.id} loaded from the network`,
`height: ${block.height}`
);
} else {
const id = block ? block.id : 'null';
library.logger.debug('Block processing failed', {
id,
err: err.toString(),
module: 'blocks',
block,
});
}
return seriesCb(err);
});
}
async.waterfall(
[getBlocksFromNetwork, validateBlocks, processBlocks],
err => {
if (err) {
return setImmediate(
cb,
`Error loading blocks: ${err.message || err}`,
lastValidBlock
);
}
return setImmediate(cb, null, lastValidBlock);
}
);
};
/**
* Generate new block, see: loader.loadBlockChain (private).
*
* @param {Object} keypair - Pair of private and public keys, see: helpers.ed.makeKeypair
* @param {number} timestamp - Slot time, see: helpers.slots.getSlotTime
* @param {function} cb - Callback function
* @returns {function} cb - Callback function from params (through setImmediate)
* @returns {Object} cb.err - Error message if error occurred
*/
Process.prototype.generateBlock = function(keypair, timestamp, cb) {
// Get transactions that will be included in block
const transactions =
modules.transactions.getUnconfirmedTransactionList(
false,
MAX_TRANSACTIONS_PER_BLOCK
) || [];
const context = {
blockTimestamp: timestamp,
blockHeight: modules.blocks.lastBlock.get().height + 1,
blockVersion: blockVersion.currentBlockVersion,
};
const allowedTransactionsIds = modules.processTransactions
.checkAllowedTransactions(transactions, context)
.transactionsResponses.filter(
transactionResponse => transactionResponse.status === TransactionStatus.OK
)
.map(transactionReponse => transactionReponse.id);
const allowedTransactions = transactions.filter(transaction =>
allowedTransactionsIds.includes(transaction.id)
);
modules.processTransactions
.verifyTransactions(allowedTransactions)
.then(({ transactionsResponses: responses }) => {
const readyTransactions = transactions.filter(transaction =>
responses
.filter(response => response.status === TransactionStatus.OK)
.map(response => response.id)
.includes(transaction.id)
);
// Create a block
const block = library.logic.block.create({
keypair,
timestamp,
previousBlock: modules.blocks.lastBlock.get(),
transactions: readyTransactions,
});
// Start block processing - broadcast: true, saveBlock: true
return modules.blocks.verify.processBlock(block, true, true, cb);
})
.catch(e => {
library.logger.error(e.stack);
return setImmediate(cb, e);
});
};
/**
>>>>>>> |
<<<<<<<
var config = require('../../data/config.json');
var Peer = require('../../../logic/peer');
var PeersLogic = require('../../../logic/peers');
var PeersModule = require('../../../modules/peers');
=======
var constants = require('../../../helpers/constants');
var generateMatchedAndUnmatchedBroadhashes = require('../common/helpers/peers').generateMatchedAndUnmatchedBroadhashes;
var generateRandomActivePeer = require('../../common/objectStubs').generateRandomActivePeer;
>>>>>>>
var test = require('../../test');
var _ = test._;
var prefixedPeer = require('../../fixtures/peers').randomNormalizedPeer;
var generateRandomActivePeer = require('../../fixtures/peers').generateRandomActivePeer;
var config = require('../../data/config.json');
var constants = require('../../../helpers/constants');
var generateMatchedAndUnmatchedBroadhashes = require('../common/helpers/peers').generateMatchedAndUnmatchedBroadhashes;
<<<<<<<
var prefixedPeer = require('../../fixtures/peers').peer;
var wsRPC = require('../../../api/ws/rpc/wsRPC').wsRPC;
=======
var randomInt = require('../../common/helpers').randomInt;
var randomPeer = require('../../common/objectStubs').randomNormalizedPeer;
>>>>>>>
var randomInt = require('../../common/helpers').randomInt;
<<<<<<<
it('should insert new peer', function (done) {
peers.update(prefixedPeer);
getPeers(function (err, __peers) {
expect(__peers).to.be.an('array').and.to.have.lengthOf(1);
expect(__peers[0]).to.have.property('string').equal(prefixedPeer.ip + ':' + prefixedPeer.port);
done();
=======
it('should return an empty array', function () {
expect(listResult).to.be.an('array').and.to.be.empty;
>>>>>>>
it('should return an empty array', function () {
expect(listResult).to.be.an('array').and.to.be.empty;
<<<<<<<
beforeEach(function () {
peers.update(prefixedPeer);
=======
before(function () {
PeersRewired.__set__('library.config.forging.force', false);
peersLogicMock.list = sinon.stub().returns([]);
>>>>>>>
before(function () {
PeersRewired.__set__('library.config.forging.force', false);
peersLogicMock.list = sinon.stub().returns([]);
<<<<<<<
var peer = _.clone(prefixedPeer);
peer.nonce = systemNonce;
=======
var peer = _.clone(randomPeer);
peer.nonce = NONCE;
>>>>>>>
var peer = _.clone(prefixedPeer);
peer.nonce = NONCE; |
<<<<<<<
const { DappTransaction } = require('@liskhq/lisk-transactions');
=======
const _ = require('lodash');
>>>>>>>
const { DappTransaction } = require('@liskhq/lisk-transactions');
const _ = require('lodash');
<<<<<<<
genesisBlock: {},
constants,
config: { components: { logger: null } },
=======
genesisBlock,
config: [networkConfig, appConfig],
>>>>>>>
genesisBlock,
constants,
config: [networkConfig, appConfig],
<<<<<<<
it('should contain all framework related transactions.', () => {
// Act
const app = new Application(
params.label,
params.genesisBlock,
params.constants,
params.config
);
// Assert
expect(Object.keys(app.getTransactions())).toEqual(frameworkTxTypes);
});
});
describe('#registerTransaction', () => {
it('should throw error when transaction type is missing.', () => {
// Arrange
const app = new Application(
params.label,
params.genesisBlock,
params.constants,
params.config
);
// Act && Assert
expect(() => app.registerTransaction()).toThrow(
'Transaction type is required as an integer'
);
});
it('should throw error when transaction type is not integer.', () => {
// Arrange
const app = new Application(
params.label,
params.genesisBlock,
params.constants,
params.config
);
// Act && Assert
expect(() => app.registerTransaction('5')).toThrow(
'Transaction type is required as an integer'
);
});
it('should throw error when transaction class is missing.', () => {
// Arrange
const app = new Application(
params.label,
params.genesisBlock,
params.constants,
params.config
);
// Act && Assert
expect(() => app.registerTransaction(5)).toThrow(
'Transaction implementation is required'
);
});
it('should throw error when transaction type is already registered.', () => {
// Arrange
const app = new Application(
params.label,
params.genesisBlock,
params.constants,
params.config
);
// Act && Assert
expect(() => app.registerTransaction(1, DappTransaction)).toThrow(
'A transaction type "1" is already registered.'
);
});
it('should register transaction when passing a new transaction type and a transaction implementation.', () => {
// Arrange
const app = new Application(
params.label,
params.genesisBlock,
params.constants,
params.config
);
// Act
app.registerTransaction(5, DappTransaction);
// Assert
expect(app.getTransaction(5)).toBe(DappTransaction);
});
=======
it('should throw validation error if constants are overriden by the user', () => {
const customConfig = [
...[
{
app: {
genesisConfig: {
CONSTANT: 'aConstant',
},
},
},
],
...params.config,
];
expect(() => {
new Application(params.label, params.genesisBlock, customConfig);
}).toThrow('Schema validation error');
});
>>>>>>>
it('should contain all framework related transactions.', () => {
// Act
const app = new Application(
params.label,
params.genesisBlock,
params.constants,
params.config
);
// Assert
expect(Object.keys(app.getTransactions())).toEqual(frameworkTxTypes);
});
it('should throw validation error if constants are overriden by the user', () => {
const customConfig = [
...[
{
app: {
genesisConfig: {
CONSTANT: 'aConstant',
},
},
},
],
...params.config,
];
expect(() => {
new Application(params.label, params.genesisBlock, customConfig);
}).toThrow('Schema validation error');
});
});
describe('#registerTransaction', () => {
it('should throw error when transaction type is missing.', () => {
// Arrange
const app = new Application(
params.label,
params.genesisBlock,
params.constants,
params.config
);
// Act && Assert
expect(() => app.registerTransaction()).toThrow(
'Transaction type is required as an integer'
);
});
it('should throw error when transaction type is not integer.', () => {
// Arrange
const app = new Application(
params.label,
params.genesisBlock,
params.constants,
params.config
);
// Act && Assert
expect(() => app.registerTransaction('5')).toThrow(
'Transaction type is required as an integer'
);
});
it('should throw error when transaction class is missing.', () => {
// Arrange
const app = new Application(
params.label,
params.genesisBlock,
params.constants,
params.config
);
// Act && Assert
expect(() => app.registerTransaction(5)).toThrow(
'Transaction implementation is required'
);
});
it('should throw error when transaction type is already registered.', () => {
// Arrange
const app = new Application(
params.label,
params.genesisBlock,
params.constants,
params.config
);
// Act && Assert
expect(() => app.registerTransaction(1, DappTransaction)).toThrow(
'A transaction type "1" is already registered.'
);
});
it('should register transaction when passing a new transaction type and a transaction implementation.', () => {
// Arrange
const app = new Application(
params.label,
params.genesisBlock,
params.constants,
params.config
);
// Act
app.registerTransaction(5, DappTransaction);
// Assert
expect(app.getTransaction(5)).toBe(DappTransaction);
}); |
<<<<<<<
init({ id, blockId, type, asset, dapp, inTransfer, delegateName }) {
=======
init({ id, blockId, type, asset, dapp, inTransfer, votes }) {
>>>>>>>
init({ id, blockId, type, asset, dapp, inTransfer, delegateName, votes }) {
<<<<<<<
case 2:
this.asset.delegate.username = delegateName || 'DummyDelegate';
break;
=======
case 3:
this.asset.votes = votes || [];
break;
>>>>>>>
case 2:
this.asset.delegate.username = delegateName || 'DummyDelegate';
break;
case 3:
this.asset.votes = votes || [];
break; |
<<<<<<<
config: self.options.config,
genesisBlock: { block: self.options.config.genesisBlock },
registeredTransactions: self.options.registeredTransactions,
=======
config: self.options,
genesisBlock: { block: self.options.genesisBlock },
>>>>>>>
config: self.options,
genesisBlock: { block: self.options.genesisBlock },
registeredTransactions: self.options.registeredTransactions, |
<<<<<<<
// System
this.logger.debug('Initiating system...');
this.system = createSystemComponent(systemConfig, this.logger, storage);
// Publish an event whenever the system headers are updated.
this.system.on('update', nodeInfo => {
this.channel.publish('chain:system:updateNodeInfo', nodeInfo);
});
=======
>>>>>>>
// TODO: Use the channel application state for update node info
// Publish an event whenever the system headers are updated.
this.system.on('update', nodeInfo => {
this.channel.publish('chain:system:updateNodeInfo', nodeInfo);
});
<<<<<<<
system: this.system,
=======
>>>>>>>
<<<<<<<
getNodeInfo: () => this.system.headers,
calculateSupply: action => this.blockReward.calcSupply(action.params[0]),
=======
calculateSupply: action =>
this.blockReward.calcSupply(action.params.height),
>>>>>>>
getNodeInfo: () => this.system.headers,
calculateSupply: action =>
this.blockReward.calcSupply(action.params.height), |
<<<<<<<
parseBlockToJson,
saveBlock,
=======
saveBlockStep,
undoBlockStep,
>>>>>>>
saveBlock,
<<<<<<<
=======
await undoBlockStep(this.dposModule, block, tx);
}
async save({ block, blockJSON, tx, skipSave }) {
await saveBlockStep(
this.storage,
this.dposModule,
block,
blockJSON,
skipSave,
tx,
);
this._lastBlock = block;
>>>>>>> |
<<<<<<<
var modulesLoader = require('../../common/initModule').modulesLoader;
var Transaction = require('../../../logic/transaction.js');
var AccountLogic = require('../../../logic/account.js');
var AccountModule = require('../../../modules/accounts.js');
var Multisignature = rewire('../../../logic/multisignature.js');
var slots = require('../../../helpers/slots.js');
var Diff = require('../../../helpers/diff.js');
=======
var modulesLoader = require('../../common/modulesLoader');
>>>>>>>
var modulesLoader = require('../../common/modulesLoader');
var Transaction = require('../../../logic/transaction.js');
var AccountLogic = require('../../../logic/account.js');
var AccountModule = require('../../../modules/accounts.js');
var Multisignature = rewire('../../../logic/multisignature.js');
var slots = require('../../../helpers/slots.js');
var Diff = require('../../../helpers/diff.js');
<<<<<<<
var trs;
var rawTrs;
=======
>>>>>>>
var trs;
var rawTrs; |
<<<<<<<
=======
const { Application } = require('../framework/src');
>>>>>>> |
<<<<<<<
describe('#sendRequest with promise', function () {
it('should be able to use sendRequest as a promise for GET', function (done) {
lisk.api().sendRequest('blocks/getHeight', {}).then(function(result) {
(result).should.be.type('object');
(result.success).should.be.equal(true);
(result.height).should.be.type('number');
done();
});
});
it('should be able to use sendRequest as a promise for POST', function (done) {
var options = {
ssl: false,
node: '',
randomPeer: true,
testnet: true,
port: '7000',
bannedPeers: []
};
var LSKnode = lisk.api(options);
var secret = 'soap arm custom rhythm october dove chunk force own dial two odor';
var secondSecret = 'spider must salmon someone toe chase aware denial same chief else human';
var recipient = '10279923186189318946L';
var amount = 100000000;
LSKnode.sendRequest('transactions', { recipientId: recipient, secret: secret, secondSecret: secondSecret, amount: amount }).then(function(result) {
(result).should.be.type('object');
(result.request.success).should.be.equal(true);
done();
});
});
});
=======
describe('#getAccount', function() {
it('should get account information', function (done) {
lisk.api().getAccount('12731041415715717263L', function (data) {
(data).should.be.ok;
(data.account.publicKey).should.be.equal('a81d59b68ba8942d60c74d10bc6488adec2ae1fa9b564a22447289076fe7b1e4');
(data.account.address).should.be.equal('12731041415715717263L');
done();
});
});
});
describe('#sendLSK', function() {
it('should send testnet LSK', function (done) {
var options = {
ssl: false,
node: '',
randomPeer: true,
testnet: true,
port: '7000',
bannedPeers: []
};
var LSKnode = lisk.api(options);
var secret = 'soap arm custom rhythm october dove chunk force own dial two odor';
var secondSecret = 'spider must salmon someone toe chase aware denial same chief else human';
var recipient = '10279923186189318946L';
var amount = 100000000;
LSKnode.sendLSK(recipient, amount, secret, secondSecret, function (result) {
(result).should.be.ok;
done();
});
});
});
>>>>>>>
describe('#getAccount', function() {
it('should get account information', function (done) {
lisk.api().getAccount('12731041415715717263L', function (data) {
(data).should.be.ok;
(data.account.publicKey).should.be.equal('a81d59b68ba8942d60c74d10bc6488adec2ae1fa9b564a22447289076fe7b1e4');
(data.account.address).should.be.equal('12731041415715717263L');
done();
});
});
});
describe('#sendLSK', function() {
it('should send testnet LSK', function (done) {
var options = {
ssl: false,
node: '',
randomPeer: true,
testnet: true,
port: '7000',
bannedPeers: []
};
var LSKnode = lisk.api(options);
var secret = 'soap arm custom rhythm october dove chunk force own dial two odor';
var secondSecret = 'spider must salmon someone toe chase aware denial same chief else human';
var recipient = '10279923186189318946L';
var amount = 100000000;
LSKnode.sendLSK(recipient, amount, secret, secondSecret, function (result) {
(result).should.be.ok;
done();
});
});
});
describe('#sendRequest with promise', function () {
it('should be able to use sendRequest as a promise for GET', function (done) {
lisk.api().sendRequest('blocks/getHeight', {}).then(function(result) {
(result).should.be.type('object');
(result.success).should.be.equal(true);
(result.height).should.be.type('number');
done();
});
});
it('should be able to use sendRequest as a promise for POST', function (done) {
var options = {
ssl: false,
node: '',
randomPeer: true,
testnet: true,
port: '7000',
bannedPeers: []
};
var LSKnode = lisk.api(options);
var secret = 'soap arm custom rhythm october dove chunk force own dial two odor';
var secondSecret = 'spider must salmon someone toe chase aware denial same chief else human';
var recipient = '10279923186189318946L';
var amount = 100000000;
LSKnode.sendRequest('transactions', { recipientId: recipient, secret: secret, secondSecret: secondSecret, amount: amount }).then(function(result) {
(result).should.be.type('object');
(result.request.success).should.be.equal(true);
done();
});
});
}); |
<<<<<<<
accounts.forEach(account => {
block = fixtures.blocks.Block({
id: account.blockId,
previousBlock: block ? block.id : null,
height: blocks.length + 1,
});
=======
const blocks = [];
accounts.forEach((account, index) => {
if (index === 0) {
block = fixtures.blocks.GenesisBlock({
generatorPublicKey: account.publicKey,
});
} else {
block = fixtures.blocks.Block({
id: account.blockId,
generatorPublicKey: account.publicKey,
previousBlock: block ? block.id : null,
height: blocks.length + 1,
});
}
>>>>>>>
accounts.forEach((account, index) => {
if (index === 0) {
block = fixtures.blocks.GenesisBlock({
generatorPublicKey: account.publicKey,
});
} else {
block = fixtures.blocks.Block({
id: account.blockId,
generatorPublicKey: account.publicKey,
previousBlock: block ? block.id : null,
height: blocks.length + 1,
});
} |
<<<<<<<
// jest.mock('../../../../../../../src/modules/chain/blocks/verify');
=======
>>>>>>> |
<<<<<<<
receiveTransactions(seriesCb) {
=======
broadcastHeaders(seriesCb) {
// Notify all remote peers about our new headers
modules.transport.broadcastHeaders(seriesCb);
},
addDeletedTransactions(seriesCb) {
>>>>>>>
addDeletedTransactions(seriesCb) {
<<<<<<<
=======
transport: scope.modules.transport,
processTransactions: scope.modules.processTransactions,
>>>>>>>
processTransactions: scope.modules.processTransactions, |
<<<<<<<
var data = 'extra information';
var transferTrs = node.lisk.transaction.createTransaction(node.gAccount.address, 112340000, transferAccount.password, null, data);
addTransaction(transferTrs, mergeResponseAndTransaction(transferTrs, cb));
=======
var transferTrs = node.lisk.transaction.createTransaction(node.gAccount.address, 112340000, transferAccount.password);
postTransaction(transferTrs, mergeResponseAndTransaction(transferTrs, cb));
>>>>>>>
var data = 'extra information';
var transferTrs = node.lisk.transaction.createTransaction(node.gAccount.address, 112340000, transferAccount.password, null, data);
postTransaction(transferTrs, mergeResponseAndTransaction(transferTrs, cb)); |
<<<<<<<
/**
* Description.
*
* @func create_compression
* @memberof api/fittings
* @requires compression
* @requires debug
* @requires lodash
* @param {Object} fittingDef - Description of the param
* @param {Object} bagpipes - Description of the param
* @returns {function} {@link api/fittings.lisk_compression}
* @todo: Add description of the function and its parameters
*/
module.exports = function create (fittingDef, bagpipes) {
=======
module.exports = function create(fittingDef) {
>>>>>>>
/**
* Description.
*
* @func create_compression
* @memberof api/fittings
* @requires compression
* @requires debug
* @requires lodash
* @param {Object} fittingDef - Description of the param
* @param {Object} bagpipes - Description of the param
* @returns {function} {@link api/fittings.lisk_compression}
* @todo: Add description of the function and its parameters
*/
module.exports = function create(fittingDef) {
<<<<<<<
/**
* Description.
*
* @func lisk_compression
* @memberof api/fittings
* @param {Object} context - Description of the param
* @param {function} cb - Description of the param
* @todo: Add description of the function and its parameters
*/
return function lisk_compression (context, cb) {
=======
return function lisk_compression(context, cb) {
>>>>>>>
/**
* Description.
*
* @func lisk_compression
* @memberof api/fittings
* @param {Object} context - Description of the param
* @param {function} cb - Description of the param
* @todo: Add description of the function and its parameters
*/
return function lisk_compression(context, cb) { |
<<<<<<<
const { BlockReward } = require('./block_reward');
const forkChoiceRule = require('./fork_choice_rule');
=======
const {
calculateSupply,
calculateReward,
calculateMilestone,
} = require('./block_reward');
>>>>>>>
const {
calculateSupply,
calculateReward,
calculateMilestone,
} = require('./block_reward');
const forkChoiceRule = require('./fork_choice_rule'); |
<<<<<<<
tasks[name] = function(tasksCb) {
var Instance = rewire(modulesInit[name]);
=======
tasks[name] = function(cb) {
const Instance = rewire(modulesInit[name]);
>>>>>>>
tasks[name] = function(tasksCb) {
const Instance = rewire(modulesInit[name]);
<<<<<<<
var obj = new rewiredModules[name](tasksCb, scope);
=======
const obj = new rewiredModules[name](cb, scope);
>>>>>>>
const obj = new rewiredModules[name](tasksCb, scope);
<<<<<<<
loadDelegates(loadDelegatesErr => {
var keypairs = scope.rewiredModules.delegates.__get__(
=======
loadDelegates(err => {
const keypairs = scope.rewiredModules.delegates.__get__(
>>>>>>>
loadDelegates(loadDelegatesErr => {
const keypairs = scope.rewiredModules.delegates.__get__( |
<<<<<<<
const { MAX_SHARED_TRANSACTIONS } = global.constants;
=======
const {
MIN_BROADHASH_CONSENSUS,
MAX_PEERS,
MAX_SHARED_TRANSACTIONS,
} = global.constants;
>>>>>>>
const { MAX_SHARED_TRANSACTIONS } = global.constants;
<<<<<<<
transaction: scope.logic.transaction,
=======
initTransaction: scope.logic.initTransaction,
peers: scope.logic.peers,
>>>>>>>
initTransaction: scope.logic.initTransaction,
<<<<<<<
scope.logic.transaction,
scope.components.logger,
scope.channel
=======
scope.logic.peers,
scope.logic.initTransaction,
scope.components.logger,
scope.components.storage
>>>>>>>
scope.logic.transaction,
scope.components.logger,
scope.logic.initTransaction,
scope.components.logger,
scope.channel,
scope.components.storage
<<<<<<<
// TODO: If there is an error, invoke the applyPenalty action on the Network module once it is implemented.
return setImmediate(cb, `Invalid transaction body - ${e.toString()}`);
}
=======
__private.removePeer(
{
nonce,
code: 'ETRANSACTION',
},
extraLogMessage
);
>>>>>>>
// TODO: If there is an error, invoke the applyPenalty action on the Network module once it is implemented.
<<<<<<<
=======
* Update all remote peers with our headers
*
* @param {function} cb - Callback function
* @returns {setImmediateCallback} cb
*/
Transport.prototype.broadcastHeaders = cb => {
// Grab a random list of connected peers.
const peers = library.logic.peers.listRandomConnected({
limit: MAX_PEERS,
});
if (peers.length === 0) {
library.logger.debug('Transport->broadcastHeaders: No peers found');
return setImmediate(cb);
}
library.logger.debug(
'Transport->broadcastHeaders: Broadcasting headers to remote peers',
{
count: peers.length,
}
);
// Execute remote procedure updateMyself for every peer
return async.each(
peers,
(peer, eachCb) => {
peer.rpc.updateMyself(library.logic.peers.me(), err => {
if (err) {
library.logger.debug(
'Transport->broadcastHeaders: Failed to notify peer about self',
{
peer: peer.string,
err,
}
);
} else {
library.logger.debug(
'Transport->broadcastHeaders: Successfully notified peer about self',
{
peer: peer.string,
}
);
}
return eachCb();
});
},
() => setImmediate(cb)
);
};
/**
>>>>>>>
<<<<<<<
{ api: 'postBlock', data: { block } }
=======
{
api: 'postBlock',
data: {
block,
},
immediate: true,
}
>>>>>>>
{ api: 'postBlock', data: { block } }
<<<<<<<
// TODO: If there is an error, invoke the applyPenalty action on the Network module once it is implemented.
=======
__private.removePeer({
nonce: query.nonce,
code: 'EBLOCK',
});
>>>>>>>
// TODO: If there is an error, invoke the applyPenalty action on the Network module once it is implemented.
<<<<<<<
=======
* Description of list.
*
* @todo Add @param tags
* @todo Add @returns tag
* @todo Add description of the function
*/
list(req, cb) {
req = req || {};
const peersFinder = !req.query
? modules.peers.list
: modules.peers.shared.getPeers;
peersFinder(
Object.assign(
{},
{
limit: MAX_PEERS,
},
req.query
),
(err, peers) => {
peers = !err ? peers : [];
return setImmediate(cb, null, {
success: !err,
peers,
});
}
);
},
/**
* Description of height.
*
* @todo Add @param tags
* @todo Add @returns tag
* @todo Add description of the function
*/
height(req, cb) {
const { height } = library.applicationState;
return setImmediate(cb, null, {
success: true,
height,
});
},
/**
* Description of status.
*
* @todo Add @param tags
* @todo Add @returns tag
* @todo Add description of the function
*/
status(req, cb) {
const {
height,
broadhash,
nonce,
httpPort,
version,
protocolVersion,
os,
} = library.applicationState;
return setImmediate(cb, null, {
success: true,
height,
broadhash,
nonce,
httpPort,
version,
protocolVersion,
os,
});
},
/**
>>>>>>>
<<<<<<<
=======
/**
* Validation of all internal requests.
*
* @param {Object} query
* @param {string} query.authKey - Key shared between master and slave processes. Not shared with the rest of network
* @param {Object} query.peer - Peer to update
* @param {number} query.updateType - 0 (insert) or 1 (remove)
* @param {function} cb
* @todo Add description for the params
* @todo Add @returns tag
*/
__private.checkInternalAccess = function(query, cb) {
library.schema.validate(query, definitions.WSAccessObject, err => {
if (err) {
return setImmediate(cb, err[0].message);
}
if (query.authKey !== wsRPC.getServerAuthKey()) {
return setImmediate(
cb,
'Unable to access internal function - Incorrect authKey'
);
}
return setImmediate(cb, null);
});
};
Transport.prototype.internal = {
/**
* Inserts or updates a peer on peers list.
*
* @param {Object} query
* @param {Object} query.peer
* @param {string} query.authKey - Signed peer data with in hex format
* @param {number} query.updateType - 0 (insert) or 1 (remove)
* @param {function} cb
* @todo Add description for the params
* @todo Add @returns tag
*/
updatePeer(query, cb) {
__private.checkInternalAccess(query, err => {
if (err) {
return setImmediate(cb, err);
}
const updates = {};
updates[Rules.UPDATES.INSERT] = modules.peers.update;
updates[Rules.UPDATES.REMOVE] = modules.peers.remove;
const updateResult = updates[query.updateType](query.peer);
return setImmediate(
cb,
updateResult === true
? null
: new PeerUpdateError(
updateResult,
failureCodes.errorMessages[updateResult]
)
);
});
},
};
>>>>>>> |
<<<<<<<
=======
var transactionTypes = require('../../helpers/transaction_types');
>>>>>>>
require('../../helpers/transaction_types'); |
<<<<<<<
config: this.options,
=======
config: this.options.config,
applicationState,
>>>>>>>
config: this.options,
applicationState, |
<<<<<<<
return library.balancesSequence.add(async balancesSequenceCb => {
if (!nonce) {
library.logger.debug(
`Received transaction ${transaction.id} from public client`
);
} else {
library.logger.debug(
`Received transaction ${transaction.id} from network`
);
}
=======
return library.balancesSequence.add(balancesSequenceCb => {
library.logger.debug(`Received transaction ${transaction.id}`);
>>>>>>>
return library.balancesSequence.add(async balancesSequenceCb => {
library.logger.debug(`Received transaction ${transaction.id}`); |
<<<<<<<
// System
this.logger.debug('Initiating system...');
this.system = createSystemComponent(systemConfig, this.logger, storage);
if (!this.options.genesisBlock) {
=======
if (!this.options.config) {
>>>>>>>
if (!this.options.genesisBlock) { |
<<<<<<<
scenarios.network.peersBlackList(params);
scenarios.network.peerDisconnect(params);
=======
// When broadcasting is disabled, there are only
// two nodes available for testing sync only
// so skipping peer disconnect test
if (!broadcastingDisabled) {
scenarios.network.peerDisconnect(params);
}
>>>>>>>
scenarios.network.peersBlackList(params);
// When broadcasting is disabled, there are only
// two nodes available for testing sync only
// so skipping peer disconnect test
if (!broadcastingDisabled) {
scenarios.network.peerDisconnect(params);
} |
<<<<<<<
var Round = rewire('../../../logic/round.js'); // eslint-disable-line
var DBSandbox = require('../../common/DBSandbox').DBSandbox;
=======
var Round = rewire('../../../logic/round.js');
var DBSandbox = require('../../common/db_sandbox').DBSandbox;
>>>>>>>
var Round = rewire('../../../logic/round.js'); // eslint-disable-line
var DBSandbox = require('../../common/db_sandbox').DBSandbox; |
<<<<<<<
=======
it('should throw AssertionError if broadhash undefined', async () => {
// Arrange
newState = {
broadhash: undefined,
height: '10',
};
const broadhashAssertionError = new AssertionError({
message: broadhashErrorMessage,
operator: '==',
expected: true,
actual: undefined,
});
// Act && Assert
await expect(applicationState.update(newState)).rejects.toThrow(
broadhashAssertionError,
);
});
it('should throw AssertionError if broadhash is null', async () => {
// Arrange
newState = {
broadhash: null,
height: '10',
};
const broadhashAssertionError = new AssertionError({
message: broadhashErrorMessage,
operator: '==',
expected: true,
actual: null,
});
// Act && Assert
await expect(applicationState.update(newState)).rejects.toThrow(
broadhashAssertionError,
);
});
>>>>>>> |
<<<<<<<
transfer.applyConfirmed(
validTransaction,
dummyBlock,
validSender,
err => {
expect(err).to.not.exist;
accountModule.getAccount(
{ address: validTransaction.recipientId },
(err, accountAfter) => {
expect(err).to.not.exist;
expect(accountAfter).to.exist;
var balanceAfter = new Bignum(
accountAfter.balance.toString()
);
expect(balanceBefore.plus(amount).toString()).to.equal(
balanceAfter.toString()
);
undoConfirmedTransaction(validTransaction, validSender, done);
}
);
}
);
=======
transfer.apply(validTransaction, dummyBlock, validSender, err => {
expect(err).to.not.exist;
accountModule.getAccount(
{ address: validTransaction.recipientId },
(err, accountAfter) => {
expect(err).to.not.exist;
expect(accountAfter).to.exist;
var balanceAfter = new Bignum(accountAfter.balance.toString());
expect(
balanceBefore.plus(amount).equals(balanceAfter.toString())
).to.be.true;
undoTransaction(validTransaction, validSender, done);
}
);
});
>>>>>>>
transfer.applyConfirmed(
validTransaction,
dummyBlock,
validSender,
err => {
expect(err).to.not.exist;
accountModule.getAccount(
{ address: validTransaction.recipientId },
(err, accountAfter) => {
expect(err).to.not.exist;
expect(accountAfter).to.exist;
var balanceAfter = new Bignum(
accountAfter.balance.toString()
);
expect(
balanceBefore.plus(amount).equals(balanceAfter.toString())
).to.be.true;
undoConfirmedTransaction(validTransaction, validSender, done);
}
);
}
);
<<<<<<<
transfer.undoConfirmed(
validTransaction,
dummyBlock,
validSender,
err => {
expect(err).to.not.exist;
accountModule.getAccount(
{ address: validTransaction.recipientId },
(err, accountAfter) => {
var balanceAfter = new Bignum(
accountAfter.balance.toString()
);
expect(err).to.not.exist;
expect(balanceAfter.plus(amount).toString()).to.equal(
balanceBefore.toString()
);
applyConfirmedTransaction(
validTransaction,
validSender,
done
);
}
);
}
);
=======
transfer.undo(validTransaction, dummyBlock, validSender, err => {
expect(err).to.not.exist;
accountModule.getAccount(
{ address: validTransaction.recipientId },
(err, accountAfter) => {
var balanceAfter = new Bignum(accountAfter.balance.toString());
expect(err).to.not.exist;
expect(
balanceAfter.plus(amount).equals(balanceBefore.toString())
).to.be.true;
applyTransaction(validTransaction, validSender, done);
}
);
});
>>>>>>>
transfer.undoConfirmed(
validTransaction,
dummyBlock,
validSender,
err => {
expect(err).to.not.exist;
accountModule.getAccount(
{ address: validTransaction.recipientId },
(err, accountAfter) => {
var balanceAfter = new Bignum(
accountAfter.balance.toString()
);
expect(err).to.not.exist;
expect(
balanceAfter.plus(amount).equals(balanceBefore.toString())
).to.be.true;
applyConfirmedTransaction(
validTransaction,
validSender,
done
);
}
);
}
); |
<<<<<<<
var multisigRegistration = lisk.transaction.registerMultisignature({
=======
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const multisigRegistration = lisk.transaction.registerMultisignature({
<<<<<<<
var minimum = MULTISIG_CONSTRAINTS.MIN.MAXIMUM + 1;
var keysgroup = [multiSigAccount1.publicKey, multiSigAccount2.publicKey];
var multisigRegistration2 = lisk.transaction.registerMultisignature({
=======
const minimum = MULTISIG_CONSTRAINTS.MIN.MAXIMUM + 1;
const keysgroup = [
multiSigAccount1.publicKey,
multiSigAccount2.publicKey,
];
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const minimum = MULTISIG_CONSTRAINTS.MIN.MAXIMUM + 1;
const keysgroup = [
multiSigAccount1.publicKey,
multiSigAccount2.publicKey,
];
const multisigRegistration2 = lisk.transaction.registerMultisignature({
<<<<<<<
var multisigRegistration3 = lisk.transaction.registerMultisignature({
=======
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const multisigRegistration3 = lisk.transaction.registerMultisignature({
<<<<<<<
var multisigRegistration4 = lisk.transaction.registerMultisignature({
=======
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const multisigRegistration4 = lisk.transaction.registerMultisignature({
<<<<<<<
var multisigRegistration5 = lisk.transaction.registerMultisignature({
=======
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const multisigRegistration5 = lisk.transaction.registerMultisignature({
<<<<<<<
var multisigRegistration6 = lisk.transaction.registerMultisignature({
=======
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const multisigRegistration6 = lisk.transaction.registerMultisignature({
<<<<<<<
var multisigRegistration7 = lisk.transaction.registerMultisignature({
=======
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const multisigRegistration7 = lisk.transaction.registerMultisignature({
<<<<<<<
var multisigRegistration8 = lisk.transaction.registerMultisignature({
=======
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const multisigRegistration8 = lisk.transaction.registerMultisignature({
<<<<<<<
var multisigRegistration9 = lisk.transaction.registerMultisignature({
=======
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const multisigRegistration9 = lisk.transaction.registerMultisignature({
<<<<<<<
var multisigRegistration10 = lisk.transaction.registerMultisignature({
=======
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const multisigRegistration10 = lisk.transaction.registerMultisignature({
<<<<<<<
var multisigRegistration11 = lisk.transaction.registerMultisignature({
=======
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const multisigRegistration11 = lisk.transaction.registerMultisignature({
<<<<<<<
var keysgroup = [multiSigAccount1.publicKey];
var multisigRegistration12 = lisk.transaction.registerMultisignature({
=======
const keysgroup = [multiSigAccount1.publicKey];
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const keysgroup = [multiSigAccount1.publicKey];
const multisigRegistration12 = lisk.transaction.registerMultisignature({
<<<<<<<
var keysgroup = [multiSigAccount1.publicKey];
var multisigRegistration13 = lisk.transaction.registerMultisignature({
=======
const keysgroup = [multiSigAccount1.publicKey];
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const keysgroup = [multiSigAccount1.publicKey];
const multisigRegistration13 = lisk.transaction.registerMultisignature({
<<<<<<<
var multisigRegistration14 = lisk.transaction.registerMultisignature({
=======
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const multisigRegistration14 = lisk.transaction.registerMultisignature({
<<<<<<<
var multisigRegistration15 = lisk.transaction.registerMultisignature({
=======
const transaction = lisk.transaction.registerMultisignature({
>>>>>>>
const multisigRegistration15 = lisk.transaction.registerMultisignature({ |
<<<<<<<
multisignature.calculateFee(transaction).isEqualTo('1000000000')
);
=======
multisignature.calculateFee(transaction).equals('1000000000')
).to.be.true;
>>>>>>>
multisignature.calculateFee(transaction).isEqualTo('1000000000')
).to.be.true;
<<<<<<<
multisignature.calculateFee(transaction).isEqualTo('2500000000')
);
=======
multisignature.calculateFee(transaction).equals('2500000000')
).to.be.true;
>>>>>>>
multisignature.calculateFee(transaction).isEqualTo('2500000000')
).to.be.true;
<<<<<<<
multisignature.calculateFee(transaction).isEqualTo('4500000000')
);
=======
multisignature.calculateFee(transaction).equals('4500000000')
).to.be.true;
>>>>>>>
multisignature.calculateFee(transaction).isEqualTo('4500000000')
).to.be.true;
<<<<<<<
multisignature.calculateFee(transaction).isEqualTo('8500000000')
);
=======
multisignature.calculateFee(transaction).equals('8500000000')
).to.be.true;
>>>>>>>
multisignature.calculateFee(transaction).isEqualTo('8500000000')
).to.be.true; |
<<<<<<<
exports.should = should;
=======
// See https://github.com/shouldjs/should.js/issues/41
Object.defineProperty(exports, 'should', { value: should });
>>>>>>>
Object.defineProperty(exports, 'should', { value: should }); |
<<<<<<<
const sortBy = require('../helpers/sort_by.js').sortBy;
const TransactionPool = require('../logic/transaction_pool.js');
=======
const TransactionPool = require('../logic/transaction_pool');
const Transfer = require('../logic/transfer');
const { TRANSACTION_TYPES } = global.constants;
>>>>>>>
const TransactionPool = require('../logic/transaction_pool.js');
<<<<<<<
=======
__private.assetTypes[
TRANSACTION_TYPES.SEND
] = library.logic.transaction.attachAssetType(
TRANSACTION_TYPES.SEND,
new Transfer({
components: {
logger: library.logger,
},
schema: library.schema,
})
);
>>>>>>>
<<<<<<<
=======
__private.assetTypes[TRANSACTION_TYPES.SEND].bind(scope.modules.accounts);
>>>>>>> |
<<<<<<<
// Normalize transaction
const transaction = library.logic.initTransaction.dbRead(rows[i]);
// Set empty object if there are no transactions in block
blocks[block.id].transactions = blocks[block.id].transactions || {};
=======
// Normalize transaction
const transaction = library.logic.initTransaction.dbRead(rows[i]);
// Set empty object if there are no transactions in block
blocks[block.id].transactions = blocks[block.id].transactions || {};
>>>>>>>
// Normalize transaction
const transaction = library.logic.initTransaction.dbRead(rows[i]);
// Set empty object if there are no transactions in block
blocks[block.id].transactions = blocks[block.id].transactions || {};
<<<<<<<
return setImmediate(cb, err, blocks);
},
tx
);
}
=======
/**
* Loads full blocks from database and normalize them.
*
* @param {Object} filter - Filter options
* @param {Object} filter.limit - Limit blocks to amount
* @param {Object} filter.lastId - ID of block to begin with
* @param {function} cb - Callback function
* @param {Object} tx - database transaction
* @returns {function} cb - Callback function from params (through setImmediate)
* @returns {Object} cb.err - Error if occurred
* @returns {Object} cb.rows - List of normalized blocks
*/
Utils.prototype.loadBlocksPart = function(filter, cb, tx) {
self.loadBlocksData(
filter,
(err, rows) => {
let blocks;
if (!err) {
// Normalize list of blocks
blocks = self.readDbRows(rows);
}
>>>>>>>
return setImmediate(cb, err, blocks);
},
tx
);
}
<<<<<<<
/* eslint-disable no-restricted-globals */
transactions.forEach(t => {
parsedBlocks.push({
b_id: _.get(block, 'id', null),
b_version: isNaN(+block.version) ? null : +block.version,
b_timestamp: isNaN(+block.timestamp) ? null : +block.timestamp,
b_height: isNaN(+block.height) ? null : +block.height,
b_previousBlock: _.get(block, 'previousBlockId', null),
b_numberOfTransactions: isNaN(+block.numberOfTransactions)
? null
: +block.numberOfTransactions,
b_totalAmount: _.get(block, 'totalAmount', null),
b_totalFee: _.get(block, 'totalFee', null),
b_reward: _.get(block, 'reward', null),
b_payloadLength: isNaN(+block.payloadLength)
? null
: +block.payloadLength,
b_payloadHash: _.get(block, 'payloadHash', null),
b_generatorPublicKey: _.get(block, 'generatorPublicKey', null),
b_blockSignature: _.get(block, 'blockSignature', null),
t_id: _.get(t, 'id', null),
t_type: _.get(t, 'type', null),
t_timestamp: _.get(t, 'timestamp', null),
t_senderPublicKey: _.get(t, 'senderPublicKey', null),
t_senderId: _.get(t, 'senderId', null),
t_recipientId: _.get(t, 'recipientId', null),
t_amount: _.get(t, 'amount', null),
t_fee: _.get(t, 'fee', null),
t_signature: _.get(t, 'signature', null),
t_signSignature: _.get(t, 'signSignature', null),
t_requesterPublicKey: _.get(t, 'requesterPublicKey', null),
t_signatures: t.signatures ? t.signatures.join(',') : null,
tf_data: _.get(t, 'asset.data', null),
s_publicKey: _.get(t, 'asset.signature.publicKey', null),
d_username: _.get(t, 'asset.delegate.username', null),
v_votes: t.asset && t.asset.votes ? t.asset.votes.join(',') : null,
m_min: _.get(t, 'asset.multisignature.min', null),
m_lifetime: _.get(t, 'asset.multisignature.lifetime', null),
m_keysgroup: _.get(t, 'asset.multisignature.keysgroup', null),
dapp_name: _.get(t, 'asset.dapp.name', null),
dapp_description: _.get(t, 'asset.dapp.description', null),
dapp_tags: _.get(t, 'asset.dapp.tags', null),
dapp_type: _.get(t, 'asset.dapp.type', null),
dapp_link: _.get(t, 'asset.dapp.link', null),
dapp_category: _.get(t, 'asset.dapp.category', null),
dapp_icon: _.get(t, 'asset.dapp.icon', null),
in_dappId: _.get(t, 'asset.inTransfer.dappId', null),
ot_dappId: _.get(t, 'asset.outTransfer.dappId', null),
ot_outTransactionId: _.get(t, 'asset.outTransfer.transactionId', null),
});
=======
/* eslint-disable no-restricted-globals */
transactions.forEach(t => {
parsedBlocks.push({
b_id: _.get(block, 'id', null),
b_version: isNaN(+block.version) ? null : +block.version,
b_timestamp: isNaN(+block.timestamp) ? null : +block.timestamp,
b_height: isNaN(+block.height) ? null : +block.height,
b_previousBlock: _.get(block, 'previousBlockId', null),
b_numberOfTransactions: isNaN(+block.numberOfTransactions)
? null
: +block.numberOfTransactions,
b_totalAmount: _.get(block, 'totalAmount', null),
b_totalFee: _.get(block, 'totalFee', null),
b_reward: _.get(block, 'reward', null),
b_payloadLength: isNaN(+block.payloadLength)
? null
: +block.payloadLength,
b_payloadHash: _.get(block, 'payloadHash', null),
b_generatorPublicKey: _.get(block, 'generatorPublicKey', null),
b_blockSignature: _.get(block, 'blockSignature', null),
t_id: _.get(t, 'id', null),
t_type: _.get(t, 'type', null),
t_timestamp: _.get(t, 'timestamp', null),
t_senderPublicKey: _.get(t, 'senderPublicKey', null),
t_senderId: _.get(t, 'senderId', null),
t_recipientId: _.get(t, 'recipientId', null),
t_amount: _.get(t, 'amount', null),
t_fee: _.get(t, 'fee', null),
t_signature: _.get(t, 'signature', null),
t_signSignature: _.get(t, 'signSignature', null),
t_requesterPublicKey: _.get(t, 'requesterPublicKey', null),
t_signatures: t.signatures ? t.signatures.join(',') : null,
tf_data: _.get(t, 'asset.data', null),
s_publicKey: _.get(t, 'asset.signature.publicKey', null),
d_username: _.get(t, 'asset.delegate.username', null),
v_votes: t.asset && t.asset.votes ? t.asset.votes.join(',') : null,
m_min: _.get(t, 'asset.multisignature.min', null),
m_lifetime: _.get(t, 'asset.multisignature.lifetime', null),
m_keysgroup:
t.asset && t.asset.multisignature && t.asset.multisignature.keysgroup
? t.asset.multisignature.keysgroup.join(',')
: null,
dapp_name: _.get(t, 'asset.dapp.name', null),
dapp_description: _.get(t, 'asset.dapp.description', null),
dapp_tags: _.get(t, 'asset.dapp.tags', null),
dapp_type: _.get(t, 'asset.dapp.type', null),
dapp_link: _.get(t, 'asset.dapp.link', null),
dapp_category: _.get(t, 'asset.dapp.category', null),
dapp_icon: _.get(t, 'asset.dapp.icon', null),
in_dappId: _.get(t, 'asset.inTransfer.dappId', null),
ot_dappId: _.get(t, 'asset.outTransfer.dappId', null),
ot_outTransactionId: _.get(t, 'asset.outTransfer.transactionId', null),
>>>>>>>
/* eslint-disable no-restricted-globals */
transactions.forEach(t => {
parsedBlocks.push({
b_id: _.get(block, 'id', null),
b_version: isNaN(+block.version) ? null : +block.version,
b_timestamp: isNaN(+block.timestamp) ? null : +block.timestamp,
b_height: isNaN(+block.height) ? null : +block.height,
b_previousBlock: _.get(block, 'previousBlockId', null),
b_numberOfTransactions: isNaN(+block.numberOfTransactions)
? null
: +block.numberOfTransactions,
b_totalAmount: _.get(block, 'totalAmount', null),
b_totalFee: _.get(block, 'totalFee', null),
b_reward: _.get(block, 'reward', null),
b_payloadLength: isNaN(+block.payloadLength)
? null
: +block.payloadLength,
b_payloadHash: _.get(block, 'payloadHash', null),
b_generatorPublicKey: _.get(block, 'generatorPublicKey', null),
b_blockSignature: _.get(block, 'blockSignature', null),
t_id: _.get(t, 'id', null),
t_type: _.get(t, 'type', null),
t_timestamp: _.get(t, 'timestamp', null),
t_senderPublicKey: _.get(t, 'senderPublicKey', null),
t_senderId: _.get(t, 'senderId', null),
t_recipientId: _.get(t, 'recipientId', null),
t_amount: _.get(t, 'amount', null),
t_fee: _.get(t, 'fee', null),
t_signature: _.get(t, 'signature', null),
t_signSignature: _.get(t, 'signSignature', null),
t_requesterPublicKey: _.get(t, 'requesterPublicKey', null),
t_signatures: t.signatures ? t.signatures.join(',') : null,
tf_data: _.get(t, 'asset.data', null),
s_publicKey: _.get(t, 'asset.signature.publicKey', null),
d_username: _.get(t, 'asset.delegate.username', null),
v_votes: t.asset && t.asset.votes ? t.asset.votes.join(',') : null,
m_min: _.get(t, 'asset.multisignature.min', null),
m_lifetime: _.get(t, 'asset.multisignature.lifetime', null),
m_keysgroup:
t.asset && t.asset.multisignature && t.asset.multisignature.keysgroup
? t.asset.multisignature.keysgroup.join(',')
: null,
dapp_name: _.get(t, 'asset.dapp.name', null),
dapp_description: _.get(t, 'asset.dapp.description', null),
dapp_tags: _.get(t, 'asset.dapp.tags', null),
dapp_type: _.get(t, 'asset.dapp.type', null),
dapp_link: _.get(t, 'asset.dapp.link', null),
dapp_category: _.get(t, 'asset.dapp.category', null),
dapp_icon: _.get(t, 'asset.dapp.icon', null),
in_dappId: _.get(t, 'asset.inTransfer.dappId', null),
ot_dappId: _.get(t, 'asset.outTransfer.dappId', null),
ot_outTransactionId: _.get(t, 'asset.outTransfer.transactionId', null),
}); |
<<<<<<<
constructor(logger, block, storage, config) {
=======
constructor(logger, block, transaction, storage, config, channel) {
>>>>>>>
constructor(logger, block, storage, config, channel) { |
<<<<<<<
scenarios.stress.register(params);
scenarios.stress.vote(params);
it('there should exactly 180 established connections from 500[0-9] ports', done => {
// Each peer connected to 9 other pairs and have 2 connection for bi-directional communication
var expectedOutgoingConnections =
(totalPeers - 1) * totalPeers * 2;
utils.getEstablishedConnections(
wsPorts,
(err, numOfConnections) => {
if (err) {
return done(err);
}
if (numOfConnections === expectedOutgoingConnections) {
done();
} else {
done(
`There are ${numOfConnections} established connections on web socket ports.`
);
}
}
);
});
=======
scenarios.stress.transfer_with_data(params);
scenarios.stress.register_multisignature(params);
scenarios.stress.second_passphrase(params);
scenarios.stress.register_dapp(params);
scenarios.stress.register_delegate(params);
scenarios.stress.cast_vote(params);
>>>>>>>
scenarios.stress.transfer_with_data(params);
scenarios.stress.register_multisignature(params);
scenarios.stress.second_passphrase(params);
scenarios.stress.register_dapp(params);
scenarios.stress.register_delegate(params);
scenarios.stress.cast_vote(params);
it('there should exactly 180 established connections from 500[0-9] ports', done => {
// Each peer connected to 9 other pairs and have 2 connection for bi-directional communication
var expectedOutgoingConnections =
(totalPeers - 1) * totalPeers * 2;
utils.getEstablishedConnections(
wsPorts,
(err, numOfConnections) => {
if (err) {
return done(err);
}
if (numOfConnections === expectedOutgoingConnections) {
done();
} else {
done(
`There are ${numOfConnections} established connections on web socket ports.`
);
}
}
);
}); |
<<<<<<<
maxOutboundConnections: {
type: 'integer',
},
=======
emitPeerLimit: {
type: 'integer',
minimum: 1,
maximum: 100,
},
>>>>>>>
maxOutboundConnections: {
type: 'integer',
},
emitPeerLimit: {
type: 'integer',
minimum: 1,
maximum: 100,
},
<<<<<<<
maxOutboundConnections: 20,
=======
emitPeerLimit: 25,
>>>>>>>
maxOutboundConnections: 20,
emitPeerLimit: 25, |
<<<<<<<
LiskAPI.prototype.listStandyDelegates = function (limit, callback) {
var standByOffset = 101;
=======
LiskAPI.prototype.listStandbyDelegates = function (limit, callback) {
var standByOffset = +101 + +limit;
>>>>>>>
LiskAPI.prototype.listStandbyDelegates = function (limit, callback) {
var standByOffset = 101; |
<<<<<<<
await this._createSchema();
=======
this.registerEntity('Account', Account);
this.registerEntity('Block', Block);
this.registerEntity('Delegate', Delegate);
this.registerEntity('Migration', Migration);
this.registerEntity('Peer', Peer);
this.registerEntity('Round', Round);
this.registerEntity('Transaction', Transaction);
await this._createSchema(this.adapter.db);
>>>>>>>
this.registerEntity('Account', Account);
this.registerEntity('Block', Block);
this.registerEntity('Delegate', Delegate);
this.registerEntity('Migration', Migration);
this.registerEntity('Peer', Peer);
this.registerEntity('Round', Round);
this.registerEntity('Transaction', Transaction);
await this._createSchema(); |
<<<<<<<
const milestones = require('../helpers/milestones.js');
const bignum = require('../helpers/bignum.js');
=======
>>>>>>>
const bignum = require('../helpers/bignum.js'); |
<<<<<<<
/**
* Description.
*
* @func create_caches
* @memberof api/fittings
* @requires debug
* @requires helpers/swagger_module_registry.getCache
* @requires helpers/swagger_module_registry.getLogger
* @param {Object} fittingDef - Description of the param
* @param {Object} bagpipes - Description of the param
* @returns {function} {@link api/fittings.lisk_cache}
* @todo: Add description of the function and its parameters
*/
module.exports = function create (fittingDef, bagpipes) {
=======
module.exports = function create(fittingDef) {
>>>>>>>
/**
* Description.
*
* @func create_caches
* @memberof api/fittings
* @requires debug
* @requires helpers/swagger_module_registry.getCache
* @requires helpers/swagger_module_registry.getLogger
* @param {Object} fittingDef - Description of the param
* @param {Object} bagpipes - Description of the param
* @returns {function} {@link api/fittings.lisk_cache}
* @todo: Add description of the function and its parameters
*/
module.exports = function create(fittingDef) {
<<<<<<<
/**
* Description of the function.
*
* @func lisk_cache
* @memberof api/fittings
* @param {Object} context - Description of the param
* @param {function} next - Description of the param
* @todo: Add description of the function and its parameters
* @todo: Add @returns-tag
*/
return function lisk_cache (context, next) {
=======
return function lisk_cache(context, next) {
>>>>>>>
/**
* Description of the function.
*
* @func lisk_cache
* @memberof api/fittings
* @param {Object} context - Description of the param
* @param {function} next - Description of the param
* @todo: Add description of the function and its parameters
* @todo: Add @returns-tag
*/
return function lisk_cache(context, next) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.