Commit 92a579fd authored by Cédric Moreau's avatar Cédric Moreau

[fix] #1037 Migrating ex duniter-common JS files to TS (3/3)

parent b8c7046d
app/cli.js
app/common/*.js
app/common/lib/*.js
app/common/lib/document/*.js
app/lib/blockchain/*.js
app/lib/blockchain/interfaces/*.js
app/lib/computation/*.js
......
"use strict";
module.exports = {
document: require('./lib/document')
}
This diff is collapsed.
"use strict";
module.exports = {
Block: require('./block'),
Transaction: require('./transaction')
}
\ No newline at end of file
"use strict";
const constants = require('../../../../app/lib/common-libs/constants').CommonConstants
const hashf = require('../../../lib/common-libs').hashf
module.exports = class Transaction {
constructor(
version,
currency,
issuers,
signatures,
inputs,
unlocks,
outputs,
comment,
blockstamp,
blockstampTime,
locktime,
hash
) {
this.version = version
this.currency = currency
this.issuers = (issuers || [])
this.signatures = (signatures || [])
this.inputsRAW = (inputs || []).map(i => typeof i === 'string' ? i : Transaction.inputObj2Str(i))
this.outputsRAW = (outputs || []).map(o => typeof o === 'string' ? o : Transaction.outputObj2Str(o))
this.inputs = this.inputsRAW.map(i => Transaction.inputStr2Obj(i))
this.outputs = this.outputsRAW.map(o => Transaction.outputStr2Obj(o))
this.unlocks = (unlocks || [])
this.output_amount = this.outputs.reduce((sum, output) => sum + output.amount * Math.pow(10, output.base), 0)
this.output_base = this.outputs.reduce((maxBase, output) => Math.max(maxBase, parseInt(output.base)), 0)
this.comment = comment
this.blockstamp = blockstamp
this.blockstampTime = blockstampTime
this.locktime = locktime || 0
this.hash = hash
}
json() {
return {
'version': parseInt(this.version, 10),
'currency': this.currency,
'issuers': this.issuers.slice(),
'inputs': this.inputsRAW.slice(),
'unlocks': this.unlocks.slice(),
'outputs': this.outputsRAW.slice(),
'comment': this.comment,
'locktime': this.locktime,
'blockstamp': this.blockstamp,
'blockstampTime': this.blockstampTime,
'signatures': this.signatures.slice(),
'raw': Transaction.toRAW(this),
'hash': this.hash
}
}
compact() {
return Transaction.getCompactTransaction(this)
}
getHash(json) {
const raw = Transaction.toRAW(this)
return hashf(raw).toUpperCase()
}
/**
* Aliases
*/
/**
* Methods
*/
static getLen(tx) {
return 2 // header + blockstamp
+ tx.issuers.length * 2 // issuers + signatures
+ tx.inputs.length * 2 // inputs + unlocks
+ (tx.comment ? 1 : 0)
+ tx.outputs.length
}
static fromJSON(json) {
return new Transaction(
json.version || constants.DOCUMENTS_VERSION,
json.currency,
json.issuers,
json.signatures,
json.inputsRAW || json.inputs,
json.unlocks,
json.outputsRAW || json.outputs,
json.comment,
json.blockstamp,
json.blockstampTime,
json.locktime,
json.hash
)
}
static toRAW(json) {
const tx = Transaction.fromJSON(json)
let raw = ""
raw += "Version: " + (tx.version) + "\n"
raw += "Type: Transaction\n"
raw += "Currency: " + tx.currency + "\n"
raw += "Blockstamp: " + tx.blockstamp + "\n"
raw += "Locktime: " + tx.locktime + "\n"
raw += "Issuers:\n";
(tx.issuers || []).forEach((issuer) => {
raw += issuer + '\n'
})
raw += "Inputs:\n";
(tx.inputsRAW || []).forEach((input) => {
raw += input + '\n'
})
raw += "Unlocks:\n";
(tx.unlocks || []).forEach((unlock) => {
raw += unlock + '\n'
})
raw += "Outputs:\n";
(tx.outputsRAW || []).forEach((output) => {
raw += output + '\n'
})
raw += "Comment: " + (tx.comment || "") + "\n";
(tx.signatures || []).forEach((signature) => {
raw += signature + '\n'
})
return raw
}
static inputObj2Str(inputObj) {
return [inputObj.amount, inputObj.base, inputObj.type, inputObj.identifier, inputObj.pos].join(':')
}
static outputObj2Str(oupoutObj) {
return [oupoutObj.amount, oupoutObj.base, oupoutObj.conditions].join(':')
}
static inputStr2Obj(inputStr) {
const sp = inputStr.split(':')
return {
amount: sp[0],
base: sp[1],
type: sp[2],
identifier: sp[3],
pos: parseInt(sp[4]),
raw: inputStr
}
}
static outputStr2Obj(outputStr) {
const sp = outputStr.split(':')
return {
amount: parseInt(sp[0]),
base: parseInt(sp[1]),
conditions: sp[2],
raw: outputStr
}
}
static getCompactTransaction(json) {
const tx = Transaction.fromJSON(json)
let issuers = tx.issuers;
let raw = ["TX", tx.version, issuers.length, tx.inputs.length, tx.unlocks.length, tx.outputs.length, tx.comment ? 1 : 0, tx.locktime || 0].join(':') + '\n';
raw += tx.blockstamp + "\n";
(issuers || []).forEach((issuer) => {
raw += issuer + '\n';
});
(tx.inputsRAW || []).forEach((input) => {
raw += input + '\n';
});
(tx.unlocks || []).forEach((input) => {
raw += input + '\n';
});
(tx.outputsRAW || []).forEach((output) => {
raw += output + '\n';
});
if (tx.comment)
raw += tx.comment + '\n';
(tx.signatures || []).forEach((signature) => {
raw += signature + '\n'
})
return raw
}
}
......@@ -14,7 +14,6 @@ import {TransactionDTO} from "../dto/TransactionDTO"
import {CommonConstants} from "../common-libs/constants"
const _ = require('underscore')
const common = require('../../../app/common')
export class DuniterBlockchain extends MiscIndexedBlockchain {
......
......@@ -2,8 +2,7 @@ import {CommonConstants} from "../../../lib/common-libs/constants"
import {GenericParser} from "./GenericParser"
import {hashf} from "../../../lib/common"
import {rawer} from "../../../lib/common-libs/index"
const Block = require('../../../../app/common/lib/document/block');
import {BlockDTO} from "../../dto/BlockDTO"
export class BlockParser extends GenericParser {
......@@ -69,7 +68,7 @@ export class BlockParser extends GenericParser {
tx.currency = obj.currency;
tx.hash = hashf(rawer.getTransaction(tx)).toUpperCase();
});
obj.len = Block.getLen(obj);
obj.len = BlockDTO.getLen(obj);
};
_verify(obj:any) {
......
......@@ -2,15 +2,13 @@ import {dos2unix} from "./dos2unix"
import {PeerDTO} from "../dto/PeerDTO"
import {IdentityDTO} from "../dto/IdentityDTO"
import {MembershipDTO} from "../dto/MembershipDTO"
import {TransactionDTO} from "../dto/TransactionDTO"
import {BlockDTO} from "../dto/BlockDTO"
const DOCUMENTS_VERSION = 10;
const SIGNED = false
const UNSIGNED = true
function document() {
return require('../../common/lib/document')
}
export const getOfficialIdentity = (json:any, withSig = true) => {
const dto = IdentityDTO.fromJSONObject(json)
if (withSig !== false) {
......@@ -61,19 +59,15 @@ export const getMembership = (json:any) => {
}
export const getBlockInnerPart = (json:any) => {
return document().Block.toRAWInnerPart(json)
return BlockDTO.fromJSONObject(json).getRawInnerPart()
}
export const getBlockWithInnerHashAndNonce = (json:any) => {
return document().Block.toRAWinnerPartWithHashAndNonce(json)
}
export const getBlockInnerHashAndNonce = (json:any) => {
return document().Block.toRAWHashAndNonce(json, UNSIGNED)
return BlockDTO.fromJSONObject(json).getRawUnSigned()
}
export const getBlockInnerHashAndNonceWithSignature = (json:any) => {
return document().Block.toRAWHashAndNonce(json, SIGNED)
return BlockDTO.fromJSONObject(json).getSignedPartSigned()
}
export const getBlock = (json:any) => {
......@@ -81,11 +75,7 @@ export const getBlock = (json:any) => {
}
export const getTransaction = (json:any) => {
return document().Transaction.toRAW(json)
}
export const getCompactTransaction = (json:any) => {
return document().Transaction.getCompactTransaction(json)
return TransactionDTO.toRAW(json)
}
function getNormalHeader(doctype:string, json:any) {
......
"use strict";
import {CommonConstants} from "./common-libs/constants"
const common = require('../../app/common')
const UDID2 = "udid2;c;([A-Z-]*);([A-Z-]*);(\\d{4}-\\d{2}-\\d{2});(e\\+\\d{2}\\.\\d{2}(\\+|-)\\d{3}\\.\\d{2});(\\d+)(;?)";
const PUBKEY = CommonConstants.FORMATS.PUBKEY
const TIMESTAMP = CommonConstants.FORMATS.TIMESTAMP
......
......@@ -20,7 +20,6 @@ const fs = require('fs')
const path = require('path')
const readline = require('readline')
const _ = require('underscore');
const common = require('../../../app/common');
const indexer = require('../indexer').Indexer
const logger = require('../logger').NewLogger('filedal');
const constants = require('../constants');
......
......@@ -16,7 +16,6 @@ import {CommonConstants} from "../../common-libs/constants"
const _ = require('underscore')
const logger = require('../../logger').NewLogger('metaDAL');
const common = require('../../../../app/common');
const constants = require('./../../constants');
export interface DBMeta {
......
......@@ -4,7 +4,6 @@ import {CindexEntry} from "../../../indexer"
import {CommonConstants} from "../../../common-libs/constants"
const constants = require('./../../../constants');
const common = require('../../../../../app/common');
const indexer = require('../../../indexer').Indexer
export class CIndexDAL extends AbstractIndex<CindexEntry> {
......
......@@ -3,7 +3,6 @@ import {SQLiteDriver} from "../../drivers/SQLiteDriver"
import {AbstractIndex} from "../AbstractIndex"
import {CommonConstants} from "../../../common-libs/constants"
const _ = require('underscore');
const common = require('../../../../../app/common');
const constants = require('../../../constants');
export class SIndexDAL extends AbstractIndex<SindexEntry> {
......
import {TransactionDTO} from "./TransactionDTO"
import {CurrencyConfDTO} from "./ConfDTO"
import {hashf} from "../common"
const DEFAULT_DOCUMENT_VERSION = 10
export class BlockDTO {
version: number
......@@ -18,14 +22,14 @@ export class BlockDTO {
issuersCount: number
issuersFrame: number
issuersFrameVar: number
identities: string[]
joiners: string[]
actives: string[]
leavers: string[]
revoked: string[]
excluded: string[]
certifications: string[]
transactions: TransactionDTO[]
identities: string[] = []
joiners: string[] = []
actives: string[] = []
leavers: string[] = []
revoked: string[] = []
excluded: string[] = []
certifications: string[] = []
transactions: TransactionDTO[] = []
medianTime: number
nonce: number
fork: boolean
......@@ -120,6 +124,10 @@ export class BlockDTO {
"Nonce: " + this.nonce + "\n"
}
getSignedPartSigned() {
return this.getSignedPart() + this.signature + "\n"
}
getRawInnerPart() {
let raw = "";
raw += "Version: " + this.version + "\n";
......@@ -178,15 +186,19 @@ export class BlockDTO {
return raw
}
getHash() {
return hashf(this.getSignedPartSigned())
}
static fromJSONObject(obj:any) {
const dto = new BlockDTO()
dto.version = parseInt(obj.version)
dto.version = parseInt(obj.version) || DEFAULT_DOCUMENT_VERSION
dto.number = parseInt(obj.number)
dto.currency = obj.currency
dto.hash = obj.hash
dto.currency = obj.currency || ""
dto.hash = obj.hash || ""
dto.inner_hash = obj.inner_hash
dto.previousHash = obj.previousHash
dto.issuer = obj.issuer
dto.issuer = obj.issuer || ""
dto.previousIssuer = obj.previousIssuer
dto.dividend = obj.dividend || null
dto.time = parseInt(obj.time)
......@@ -203,11 +215,11 @@ export class BlockDTO {
dto.revoked = obj.revoked || []
dto.excluded = obj.excluded || []
dto.certifications = obj.certifications || []
dto.transactions = (obj.transactions || []).map(TransactionDTO.fromJSONObject)
dto.transactions = (obj.transactions || []).map((tx:any) => TransactionDTO.fromJSONObject(tx))
dto.medianTime = parseInt(obj.medianTime)
dto.fork = !!obj.fork
dto.parameters = obj.parameters
dto.signature = obj.signature
dto.parameters = obj.parameters || ""
dto.signature = obj.signature || ""
dto.nonce = parseInt(obj.nonce)
return dto
}
......@@ -239,4 +251,12 @@ export class BlockDTO {
msPeriod: parseInt(sp[9])
}
}
static getLen(block:any) {
return BlockDTO.fromJSONObject(block).len
}
static getHash(block:any) {
return BlockDTO.fromJSONObject(block).getHash()
}
}
\ No newline at end of file
......@@ -247,6 +247,18 @@ export class TransactionDTO {
};
}
static inputStr2Obj(inputStr:string) {
const sp = inputStr.split(':')
return {
amount: sp[0],
base: sp[1],
type: sp[2],
identifier: sp[3],
pos: parseInt(sp[4]),
raw: inputStr
}
}
static mock() {
return new TransactionDTO(1, "", 0, "", "", 0, [], [], [], [], [], "")
}
......
......@@ -13,10 +13,8 @@ import {CommonConstants} from "./common-libs/constants"
import {MembershipDTO} from "./dto/MembershipDTO"
const _ = require('underscore');
const common = require('../../app/common');
const constants = CommonConstants
const Block = common.document.Block
export interface IndexEntry {
index: string,
......@@ -437,8 +435,8 @@ export class Indexer {
HEAD.version = block.version
HEAD.currency = block.currency
HEAD.bsize = Block.getLen(block)
HEAD.hash = Block.getHash(block)
HEAD.bsize = BlockDTO.getLen(block)
HEAD.hash = BlockDTO.getHash(block)
HEAD.issuer = block.issuer
HEAD.time = block.time
HEAD.medianTime = block.medianTime
......@@ -515,8 +513,8 @@ export class Indexer {
const HEAD = new DBHead()
HEAD.version = block.version
HEAD.bsize = Block.getLen(block)
HEAD.hash = Block.getHash(block)
HEAD.bsize = BlockDTO.getLen(block)
HEAD.hash = BlockDTO.getHash(block)
HEAD.issuer = block.issuer
HEAD.time = block.time
HEAD.powMin = block.powMin
......
......@@ -11,11 +11,9 @@ import {CommonConstants} from "../common-libs/constants"
import {IdentityDTO} from "../dto/IdentityDTO"
const _ = require('underscore');
const common = require('../../../app/common');
const indexer = require('../indexer').Indexer
const constants = CommonConstants
const Transaction = common.document.Transaction
// Empty logger by default
let logger = {
......@@ -71,12 +69,12 @@ export const GLOBAL_RULES_FUNCTIONS = {
// For chained transactions which are checked on sandbox submission, we accept them if there is already
// a previous transaction of the chain already recorded in the pool
dbSrc = await (async () => {
let hypotheticSrc = null;
let hypotheticSrc:any = null;
let targetTX = await dal.getTxByHash(src.identifier);
if (targetTX) {
let outputStr = targetTX.outputs[src.pos];
if (outputStr) {
hypotheticSrc = Transaction.outputStr2Obj(outputStr);
hypotheticSrc = TransactionDTO.outputStr2Obj(outputStr);
hypotheticSrc.consumed = false;
hypotheticSrc.time = 0;
}
......
......@@ -4,9 +4,6 @@ import {ConfDTO} from "../dto/ConfDTO"
import {IndexEntry} from "../indexer"
import {LOCAL_RULES_FUNCTIONS} from "./local_rules"
const common = require('../../../app/common');
const Block = common.document.Block
export const ALIAS = {
ALL_LOCAL: async (block:BlockDTO, conf:ConfDTO, index:IndexEntry[]) => {
......@@ -76,7 +73,7 @@ export const CHECK = {
function checkLocal(contract:(block:BlockDTO, conf:ConfDTO, index:IndexEntry[]) => Promise<void>) {
return async (b:BlockDTO, conf:ConfDTO, index:IndexEntry[], done:any = undefined) => {
try {
const block = Block.fromJSON(b);
const block = BlockDTO.fromJSONObject(b)
await contract(block, conf, index)
done && done();
} catch (err) {
......
......@@ -11,11 +11,8 @@ import {IdentityDTO} from "../dto/IdentityDTO"
import {MembershipDTO} from "../dto/MembershipDTO"
const _ = require('underscore');
const common = require('../../../app/common');
const constants = CommonConstants
const Block = common.document.Block
const Transaction = common.document.Transaction
const maxAcceleration = require('./helpers').maxAcceleration
export const LOCAL_RULES_FUNCTIONS = {
......@@ -289,7 +286,7 @@ export const LOCAL_RULES_FUNCTIONS = {
const txs = block.transactions
// Check rule against each transaction
for (const tx of txs) {
const txLen = Transaction.getLen(tx);
const txLen = TransactionDTO.fromJSONObject(tx).getLen()
if (txLen > constants.MAXIMUM_LEN_OF_COMPACT_TX) {
throw constants.ERRORS.A_TRANSACTION_HAS_A_MAX_SIZE;
}
......@@ -297,7 +294,7 @@ export const LOCAL_RULES_FUNCTIONS = {
// Check rule against each output of each transaction
for (const tx of txs) {
for (const output of tx.outputs) {
const out = typeof output === 'string' ? output : Transaction.outputObj2Str(output)
const out = typeof output === 'string' ? output : TransactionDTO.outputObj2Str(output)
if (out.length > constants.MAXIMUM_LEN_OF_OUTPUT) {
throw constants.ERRORS.MAXIMUM_LEN_OF_OUTPUT
}
......
import {AbstractController} from "./AbstractController"
import {ParametersService} from "../parameters"
import {Source} from "../entity/source"
import {BMAConstants} from "../constants";
import {BMAConstants} from "../constants"
import {TransactionDTO} from "../../../../lib/dto/TransactionDTO"
const _ = require('underscore');
const common = require('../../../../../app/common');
const http2raw = require('../http2raw');
const Transaction = common.document.Transaction
export class TransactionBinding extends AbstractController {
parseTransaction(req:any) {
......@@ -90,7 +88,7 @@ export class TransactionBinding extends AbstractController {
"pending": pending
};
pending.map(function(tx:any, index:number) {
pending[index] = _.omit(Transaction.fromJSON(tx).json(), 'currency', 'raw');
pending[index] = _.omit(TransactionDTO.fromJSONObject(tx).json(), 'currency', 'raw');
});
return res;
}
......@@ -104,7 +102,7 @@ export class TransactionBinding extends AbstractController {
};
_.keys(history).map((key:any) => {
history[key].map((tx:any, index:number) => {
history[key][index] = _.omit(Transaction.fromJSON(tx).json(), 'currency', 'raw');
history[key][index] = _.omit(TransactionDTO.fromJSONObject(tx).json(), 'currency', 'raw');
_.extend(history[key][index], {block_number: tx && tx.block_number, time: tx && tx.time});
});
});
......
import {CommonConstants} from "../../../lib/common-libs/constants"
const common = require('../../../../app/common')
export const CrawlerConstants = {
......
import {Contacter} from "./contacter"
import {verify} from "../../../lib/common-libs/crypto/keyring"
import {rawer} from "../../../lib/common-libs/index";
const common = require('../../../../app/common')
import {rawer} from "../../../lib/common-libs/index"
export const req2fwd = async (requirements:any, toHost:string, toPort:number, logger:any) => {
const mss:any = {};
......
......@@ -14,14 +14,12 @@ import {CommonConstants} from "../../../lib/common-libs/constants"
import {IdentityDTO} from "../../../lib/dto/IdentityDTO"
import {CertificationDTO} from "../../../lib/dto/CertificationDTO"
import {MembershipDTO} from "../../../lib/dto/MembershipDTO"
import {BlockDTO} from "../../../lib/dto/BlockDTO"
const _ = require('underscore');