From e32996d30fb5751dbf26916f6dac795da2fe1883 Mon Sep 17 00:00:00 2001
From: cgeek <cem.moreau@gmail.com>
Date: Mon, 24 Jul 2017 17:57:19 +0200
Subject: [PATCH] [fix] #1037 Migrating ex duniter-common JS files to TS (1/?)

---
 app/common/index.js                           |  6 --
 app/common/lib/buid.js                        |  4 +-
 app/common/lib/crypto/base58.js               |  9 --
 app/common/lib/crypto/keyring.js              | 75 ---------------
 app/common/lib/crypto/nacl-util.js            | 50 ----------
 app/common/lib/document/block.js              |  2 +-
 app/common/lib/document/certification.js      |  1 -
 app/common/lib/document/identity.js           |  2 +-
 app/common/lib/document/transaction.js        |  2 +-
 app/common/lib/dos2unix.js                    | 23 -----
 app/common/lib/hashf.js                       |  8 --
 app/common/lib/parsers/GenericParser.js       |  2 +-
 app/common/lib/parsers/block.js               |  4 +-
 app/common/lib/parsers/certification.js       |  2 +-
 app/common/lib/parsers/identity.js            |  4 +-
 app/common/lib/parsers/membership.js          |  2 +-
 app/common/lib/parsers/peer.js                |  2 +-
 app/common/lib/parsers/revocation.js          |  4 +-
 app/common/lib/parsers/transaction.js         |  2 +-
 app/common/lib/rawer.js                       | 92 ------------------
 app/lib/common-libs/dos2unix.ts               |  3 +
 app/lib/common-libs/index.ts                  | 16 ++++
 app/lib/common-libs/rawer.ts                  | 95 +++++++++++++++++++
 .../common-libs/txunlock.ts}                  | 14 +--
 app/lib/common.ts                             | 10 +-
 app/lib/dal/sqliteDAL/MetaDAL.ts              |  2 +-
 app/lib/indexer.ts                            |  6 +-
 app/lib/rules/global_rules.ts                 |  5 +-
 app/lib/rules/local_rules.ts                  |  2 +-
 .../bma/lib/controllers/AbstractController.ts |  3 +-
 app/modules/bma/lib/dos2unix.ts               |  3 -
 app/modules/crawler/index.ts                  |  9 +-
 app/modules/crawler/lib/req2fwd.ts            | 12 ++-
 app/modules/crawler/lib/sandbox.ts            |  2 +-
 app/modules/crawler/lib/sync.ts               |  9 +-
 app/modules/prover/lib/blockGenerator.ts      |  4 +-
 app/modules/prover/lib/permanentProver.ts     |  2 +-
 app/modules/prover/lib/proof.ts               |  4 +-
 app/service/MembershipService.ts              |  1 -
 app/service/PeeringService.ts                 |  5 +-
 server.ts                                     |  2 -
 test/fast/modules/common/crypto.js            | 14 +--
 test/fast/modules/common/grammar-test.js      |  2 +-
 test/fast/modules/common/randomKey.js         | 11 ++-
 test/integration/cli.js                       |  2 +-
 test/integration/tools/user.js                | 18 ++--
 46 files changed, 198 insertions(+), 354 deletions(-)
 delete mode 100644 app/common/lib/crypto/base58.js
 delete mode 100644 app/common/lib/crypto/keyring.js
 delete mode 100644 app/common/lib/crypto/nacl-util.js
 delete mode 100644 app/common/lib/dos2unix.js
 delete mode 100644 app/common/lib/hashf.js
 delete mode 100644 app/common/lib/rawer.js
 create mode 100644 app/lib/common-libs/dos2unix.ts
 create mode 100644 app/lib/common-libs/index.ts
 create mode 100644 app/lib/common-libs/rawer.ts
 rename app/{common/lib/txunlock.js => lib/common-libs/txunlock.ts} (86%)
 delete mode 100644 app/modules/bma/lib/dos2unix.ts

diff --git a/app/common/index.js b/app/common/index.js
index 1606e4446..2a9483b86 100644
--- a/app/common/index.js
+++ b/app/common/index.js
@@ -1,14 +1,8 @@
 "use strict";
 
 module.exports = {
-  hashf: require('./lib/hashf'),
-  dos2unix: require('./lib/dos2unix'),
-  keyring: require('./lib/crypto/keyring'),
-  base58: require('./lib/crypto/base58'),
-  rawer: require('./lib/rawer'),
   buid: require('./lib/buid'),
   document: require('./lib/document'),
   constants: require('./lib/constants'),
-  txunlock: require('./lib/txunlock'),
   parsers: require('./lib/parsers')
 }
diff --git a/app/common/lib/buid.js b/app/common/lib/buid.js
index 55d12bb47..a08fb70e4 100644
--- a/app/common/lib/buid.js
+++ b/app/common/lib/buid.js
@@ -1,6 +1,4 @@
 "use strict";
-const hashf = require('./hashf');
-
 const BLOCK_UID = /^(0|[1-9]\d{0,18})-[A-F0-9]{64}$/;
 
 const buidFunctions = function(number, hash) {
@@ -20,7 +18,7 @@ module.exports = {
 
   format: {
 
-    hashf: (value) => hashf(String(value)).toUpperCase(),
+    hashf: (value) => require('../../lib/common-libs').hashf(String(value)),
 
     isBuid: (value) => {
       return (typeof value === 'string') && value.match(BLOCK_UID) ? true : false;
diff --git a/app/common/lib/crypto/base58.js b/app/common/lib/crypto/base58.js
deleted file mode 100644
index db14015cb..000000000
--- a/app/common/lib/crypto/base58.js
+++ /dev/null
@@ -1,9 +0,0 @@
-"use strict"
-
-const assert = require('assert')
-const bs58 = require('bs58')
-
-module.exports = {
-  encode: (bytes) => bs58.encode(bytes),
-  decode: (data) => new Uint8Array(bs58.decode(data))
-};
diff --git a/app/common/lib/crypto/keyring.js b/app/common/lib/crypto/keyring.js
deleted file mode 100644
index ca74b8450..000000000
--- a/app/common/lib/crypto/keyring.js
+++ /dev/null
@@ -1,75 +0,0 @@
-"use strict";
-const nacl        = require('tweetnacl');
-const base58      = require('./base58');
-const seedrandom  = require('seedrandom');
-const naclBinding = require('naclb');
-
-nacl.util = require('./nacl-util');
-
-const crypto_sign_BYTES = 64;
-
-/**
- * Verify a signature against data & public key.
- * Return true of false as callback argument.
- */
-function verify(rawMsg, rawSig, rawPub) {
-  const msg = nacl.util.decodeUTF8(rawMsg);
-  const sig = nacl.util.decodeBase64(rawSig);
-  const pub = base58.decode(rawPub);
-  const m = new Uint8Array(crypto_sign_BYTES + msg.length);
-  const sm = new Uint8Array(crypto_sign_BYTES + msg.length);
-  let i;
-  for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
-  for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
-
-  // Call to verification lib...
-  return naclBinding.verify(m, sm, pub);
-}
-
-function Key(pub, sec) {
-  /*****************************
-  *
-  *      GENERAL CRYPTO
-  *
-  *****************************/
-
-  this.publicKey = pub;
-  this.secretKey = sec;
-
-  const rawSec = () => base58.decode(this.secretKey);
-
-  this.json = () => { return {
-    pub: this.publicKey,
-    sec: this.secretKey
-  }};
-
-  this.sign = (msg) => Promise.resolve(this.signSync(msg));
-
-  this.signSync = (msg) => {
-    const m = nacl.util.decodeUTF8(msg);
-    const signedMsg = naclBinding.sign(m, rawSec());
-    const sig = new Uint8Array(crypto_sign_BYTES);
-    for (let i = 0; i < sig.length; i++) {
-      sig[i] = signedMsg[i];
-    }
-    return nacl.util.encodeBase64(sig);
-  };
-}
-
-function randomKey() {
-  const byteseed = new Uint8Array(32)
-  for (let i = 0; i < 32; i++) {
-    byteseed[i] = Math.floor(seedrandom()() *  255) + 1
-  }
-  const keypair = nacl.sign.keyPair.fromSeed(byteseed)
-  return new Key(
-    base58.encode(keypair.publicKey),
-    base58.encode(keypair.secretKey)
-  )
-}
-
-module.exports ={
-  randomKey,
-  Key: (pub, sec) => new Key(pub, sec),
-  verify: verify
-};
diff --git a/app/common/lib/crypto/nacl-util.js b/app/common/lib/crypto/nacl-util.js
deleted file mode 100644
index 05cebc0f4..000000000
--- a/app/common/lib/crypto/nacl-util.js
+++ /dev/null
@@ -1,50 +0,0 @@
-// Written in 2014-2016 by Dmitry Chestnykh and Devi Mandiri.
-// Public domain.
-(function(root, f) {
-  'use strict';
-  if (typeof module !== 'undefined' && module.exports) module.exports = f();
-  else if (root.nacl) root.nacl.util = f();
-  else {
-    root.nacl = {};
-    root.nacl.util = f();
-  }
-}(this, function() {
-  'use strict';
-
-  let util = {};
-
-  util.decodeUTF8 = function(s) {
-    let i, d = unescape(encodeURIComponent(s)), b = new Uint8Array(d.length);
-    for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i);
-    return b;
-  };
-
-  util.encodeUTF8 = function(arr) {
-    let i, s = [];
-    for (i = 0; i < arr.length; i++) s.push(String.fromCharCode(arr[i]));
-    return decodeURIComponent(escape(s.join('')));
-  };
-
-  util.encodeBase64 = function(arr) {
-    if (typeof btoa === 'undefined' || !window) {
-      return (new Buffer(arr)).toString('base64');
-    } else {
-      let i, s = [], len = arr.length;
-      for (i = 0; i < len; i++) s.push(String.fromCharCode(arr[i]));
-      return btoa(s.join(''));
-    }
-  };
-
-  util.decodeBase64 = function(s) {
-    if (typeof atob === 'undefined' || !window) {
-      return new Uint8Array(Array.prototype.slice.call(new Buffer(s, 'base64'), 0));
-    } else {
-      let i, d = atob(s), b = new Uint8Array(d.length);
-      for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i);
-      return b;
-    }
-  };
-
-  return util;
-
-}));
diff --git a/app/common/lib/document/block.js b/app/common/lib/document/block.js
index c0c3f9eea..0abe95475 100644
--- a/app/common/lib/document/block.js
+++ b/app/common/lib/document/block.js
@@ -2,7 +2,6 @@
 const _ = require('underscore')
 const constants = require('../constants');
 const regex = require('../regex');
-const hashf = require('../hashf');
 const Transaction = require('./transaction');
 
 // Constants
@@ -151,6 +150,7 @@ module.exports = class Block {
 
   static getHash(json) {
     const raw = Block.toRAWHashAndNonce(json)
+    const hashf = require('../../../lib/common-libs').hashf
     return hashf(raw).toUpperCase()
   }
 
diff --git a/app/common/lib/document/certification.js b/app/common/lib/document/certification.js
index 3cc70e69e..490d2ede4 100644
--- a/app/common/lib/document/certification.js
+++ b/app/common/lib/document/certification.js
@@ -1,7 +1,6 @@
 "use strict";
 const constants = require('../constants');
 const regex = require('../regex');
-const hashf = require('../hashf');
 
 // Constants
 const SIGNED = true
diff --git a/app/common/lib/document/identity.js b/app/common/lib/document/identity.js
index 2792fe73e..23c5c93f8 100644
--- a/app/common/lib/document/identity.js
+++ b/app/common/lib/document/identity.js
@@ -1,7 +1,6 @@
 "use strict";
 const constants = require('../constants');
 const regex = require('../regex');
-const hashf = require('../hashf');
 
 // Constants
 const SIGNED = true
@@ -74,6 +73,7 @@ module.exports = class Identity {
    */
 
   getTargetHash() {
+    const hashf = require('../../../lib/common-libs').hashf
     return hashf(this.uid + this.buid + this.pubkey).toUpperCase();
   }
 
diff --git a/app/common/lib/document/transaction.js b/app/common/lib/document/transaction.js
index aad1e08c7..f19dbd629 100644
--- a/app/common/lib/document/transaction.js
+++ b/app/common/lib/document/transaction.js
@@ -1,7 +1,7 @@
 "use strict";
 const constants = require('../constants');
 const regex = require('../regex');
-const hashf = require('../hashf');
+const hashf = require('../../../lib/common-libs').hashf
 
 // Constants
 const SIGNED = false
diff --git a/app/common/lib/dos2unix.js b/app/common/lib/dos2unix.js
deleted file mode 100644
index 32fdce593..000000000
--- a/app/common/lib/dos2unix.js
+++ /dev/null
@@ -1,23 +0,0 @@
-"use strict";
-const util     = require('util');
-const stream   = require('stream');
-
-module.exports = function (str) {
-  if (str)
-    return dos2unix(str);
-  else
-    return new Dos2UnixStream();
-};
-
-const dos2unix = (str) => str.replace(/\r\n/g, '\n');
-
-function Dos2UnixStream () {
-  stream.Transform.apply(this);
-
-  this._write = function (str, enc, done) {
-    this.push(dos2unix(str.toString()));
-    done();
-  }
-}
-
-util.inherits(Dos2UnixStream, stream.Transform);
diff --git a/app/common/lib/hashf.js b/app/common/lib/hashf.js
deleted file mode 100644
index f1a1bd2ee..000000000
--- a/app/common/lib/hashf.js
+++ /dev/null
@@ -1,8 +0,0 @@
-"use strict";
-
-module.exports = function (str){
-  return require("crypto")
-    .createHash("sha256")
-    .update(str)
-    .digest("hex");
-};
diff --git a/app/common/lib/parsers/GenericParser.js b/app/common/lib/parsers/GenericParser.js
index a1424acee..255c47aba 100644
--- a/app/common/lib/parsers/GenericParser.js
+++ b/app/common/lib/parsers/GenericParser.js
@@ -1,7 +1,7 @@
 "use strict";
 const util                 = require('util');
 const stream               = require('stream');
-const hashf                = require('../hashf');
+const hashf                = require('../../../lib/common-libs').hashf
 const constants            = require('../constants');
 
 module.exports = GenericParser;
diff --git a/app/common/lib/parsers/block.js b/app/common/lib/parsers/block.js
index 31118f50f..6bf04985b 100644
--- a/app/common/lib/parsers/block.js
+++ b/app/common/lib/parsers/block.js
@@ -2,8 +2,8 @@
 const util          = require('util');
 const GenericParser = require('./GenericParser');
 const Block         = require('../../../../app/common/lib/document/block');
-const hashf         = require('../../../../app/common/lib/hashf');
-const rawer         = require('../../../../app/common/lib/rawer');
+const hashf         = require('../../../../app/lib/common-libs').hashf
+const rawer         = require('../../../../app/lib/common-libs').rawer
 const constants     = require('../../../../app/common/lib/constants');
 
 module.exports = BlockParser;
diff --git a/app/common/lib/parsers/certification.js b/app/common/lib/parsers/certification.js
index 11d0321f5..554eb22c8 100644
--- a/app/common/lib/parsers/certification.js
+++ b/app/common/lib/parsers/certification.js
@@ -1,7 +1,7 @@
 "use strict";
 const GenericParser = require('./GenericParser');
 const util          = require('util');
-const rawer         = require('../../../../app/common/lib/rawer');
+const rawer         = require('../../../../app/lib/common-libs').rawer
 const constants     = require('../../../../app/common/lib/constants');
 
 module.exports = CertificationParser;
diff --git a/app/common/lib/parsers/identity.js b/app/common/lib/parsers/identity.js
index 4f0c41ff6..1cde03e90 100644
--- a/app/common/lib/parsers/identity.js
+++ b/app/common/lib/parsers/identity.js
@@ -1,8 +1,8 @@
 "use strict";
 const GenericParser = require('./GenericParser');
 const util          = require('util');
-const rawer         = require('../../../../app/common/lib/rawer');
-const hashf         = require('../../../../app/common/lib/hashf');
+const rawer         = require('../../../../app/lib/common-libs').rawer
+const hashf         = require('../../../../app/lib/common-libs').hashf
 const constants     = require('../../../../app/common/lib/constants');
 
 module.exports = IdentityParser;
diff --git a/app/common/lib/parsers/membership.js b/app/common/lib/parsers/membership.js
index 2435ae526..6cad68653 100644
--- a/app/common/lib/parsers/membership.js
+++ b/app/common/lib/parsers/membership.js
@@ -1,7 +1,7 @@
 "use strict";
 const GenericParser = require('./GenericParser');
 const ucp           = require('../buid');
-const rawer         = require('../rawer');
+const rawer         = require('../../../lib/common-libs/index').rawer
 const util          = require('util');
 const constants     = require('../constants');
 
diff --git a/app/common/lib/parsers/peer.js b/app/common/lib/parsers/peer.js
index 122f6ee34..9d106084d 100644
--- a/app/common/lib/parsers/peer.js
+++ b/app/common/lib/parsers/peer.js
@@ -1,6 +1,6 @@
 "use strict";
 const GenericParser = require('./GenericParser');
-const rawer         = require('../rawer');
+const rawer         = require('../../../lib/common-libs/index').rawer
 const util          = require('util');
 const constants     = require('../constants');
 
diff --git a/app/common/lib/parsers/revocation.js b/app/common/lib/parsers/revocation.js
index f86528bde..1713f7407 100644
--- a/app/common/lib/parsers/revocation.js
+++ b/app/common/lib/parsers/revocation.js
@@ -1,8 +1,8 @@
 "use strict";
 const GenericParser = require('./GenericParser');
 const util          = require('util');
-const rawer         = require('../rawer');
-const hashf         = require('../hashf');
+const rawer         = require('../../../lib/common-libs').rawer
+const hashf         = require('../../../lib/common-libs').hashf
 const constants     = require('../constants');
 
 module.exports = RevocationParser;
diff --git a/app/common/lib/parsers/transaction.js b/app/common/lib/parsers/transaction.js
index 727607e19..7b552a19c 100644
--- a/app/common/lib/parsers/transaction.js
+++ b/app/common/lib/parsers/transaction.js
@@ -1,6 +1,6 @@
 "use strict";
 const GenericParser = require('./GenericParser');
-const rawer         = require('../rawer');
+const rawer         = require('../../../lib/common-libs/index').rawer
 const constants     = require('../constants');
 const util          = require('util');
 
diff --git a/app/common/lib/rawer.js b/app/common/lib/rawer.js
deleted file mode 100644
index a99aa2a11..000000000
--- a/app/common/lib/rawer.js
+++ /dev/null
@@ -1,92 +0,0 @@
-"use strict";
-const dos2unix = require('./dos2unix');
-const document = require('./document');
-
-const DOCUMENTS_VERSION = 10;
-const SIGNED = false
-const UNSIGNED = true
-
-module.exports = new function() {
-
-  this.getOfficialIdentity = (json, withSig) => {
-    return document.Identity.toRAW(json, withSig !== false) // Defaut with sig
-  };
-
-  this.getOfficialCertification = (json) => {
-    let raw = getNormalHeader('Certification', json);
-    raw += "IdtyIssuer: " + json.idty_issuer + '\n';
-    raw += "IdtyUniqueID: " + json.idty_uid + '\n';
-    raw += "IdtyTimestamp: " + json.idty_buid + '\n';
-    raw += "IdtySignature: " + json.idty_sig + '\n';
-    raw += "CertTimestamp: " + json.buid + '\n';
-    if (json.sig) {
-      raw += json.sig + '\n';
-    }
-    return dos2unix(raw);
-  };
-
-  this.getOfficialRevocation = (json) => {
-    let raw = getNormalHeader('Revocation', json);
-    raw += "IdtyUniqueID: " + json.uid + '\n';
-    raw += "IdtyTimestamp: " + json.buid + '\n';
-    raw += "IdtySignature: " + json.sig + '\n';
-    if (json.revocation) {
-      raw += json.revocation + '\n';
-    }
-    return dos2unix(raw);
-  };
-
-  this.getPeerWithoutSignature = (json) => document.Peer.fromJSON(json).getRawUnsigned()
-
-  this.getPeer = (json) => document.Peer.fromJSON(json).getRaw()
-
-  this.getMembershipWithoutSignature = (json) => {
-    return document.Membership.toRAW(json)
-  };
-
-  this.getMembership = (json) => {
-    return dos2unix(signed(this.getMembershipWithoutSignature(json), json));
-  };
-
-  this.getBlockInnerPart = (json) => {
-    return document.Block.toRAWInnerPart(json)
-  };
-
-  this.getBlockWithInnerHashAndNonce = (json) => {
-    return document.Block.toRAWinnerPartWithHashAndNonce(json)
-  };
-
-  this.getBlockInnerHashAndNonce = (json) => {
-    return document.Block.toRAWHashAndNonce(json, UNSIGNED)
-  };
-
-  this.getBlockInnerHashAndNonceWithSignature = (json) => {
-    return document.Block.toRAWHashAndNonce(json, SIGNED)
-  };
-
-  this.getBlock = (json) => {
-    return dos2unix(signed(this.getBlockWithInnerHashAndNonce(json), json));
-  };
-
-  this.getTransaction = (json) => {
-    return document.Transaction.toRAW(json)
-  };
-
-  this.getCompactTransaction = (json) => {
-    return document.Transaction.getCompactTransaction(json)
-  };
-
-  let getNormalHeader = (doctype, json) => {
-    let raw = "";
-    raw += "Version: " + (json.version || DOCUMENTS_VERSION) + "\n";
-    raw += "Type: " + doctype + "\n";
-    raw += "Currency: " + json.currency + "\n";
-    raw += "Issuer: " + json.issuer + "\n";
-    return raw;
-  };
-
-  let signed = (raw, json) => {
-    raw += json.signature + '\n';
-    return raw;
-  };
-};
diff --git a/app/lib/common-libs/dos2unix.ts b/app/lib/common-libs/dos2unix.ts
new file mode 100644
index 000000000..cf7ee5ebc
--- /dev/null
+++ b/app/lib/common-libs/dos2unix.ts
@@ -0,0 +1,3 @@
+export function dos2unix(str:string) {
+  return str.replace(/\r\n/g, '\n')
+}
diff --git a/app/lib/common-libs/index.ts b/app/lib/common-libs/index.ts
new file mode 100644
index 000000000..5ff95cdec
--- /dev/null
+++ b/app/lib/common-libs/index.ts
@@ -0,0 +1,16 @@
+import * as rawer from './rawer'
+import {Base58decode, Base58encode} from "./crypto/base58"
+import {unlock as txunlock} from "./txunlock"
+import {hashf} from "../common";
+
+const base58 = {
+  decode: Base58decode,
+  encode: Base58encode
+}
+
+export {
+  rawer,
+  base58,
+  txunlock,
+  hashf
+}
diff --git a/app/lib/common-libs/rawer.ts b/app/lib/common-libs/rawer.ts
new file mode 100644
index 000000000..6aea2554b
--- /dev/null
+++ b/app/lib/common-libs/rawer.ts
@@ -0,0 +1,95 @@
+import {dos2unix} from "./dos2unix"
+
+const DOCUMENTS_VERSION = 10;
+const SIGNED = false
+const UNSIGNED = true
+
+function document() {
+  return require('../../common/lib/document')
+}
+
+export const getOfficialIdentity = (json:any, withSig = true) => {
+  return document().Identity.toRAW(json, withSig !== false) // Defaut with sig
+}
+
+export const getOfficialCertification = (json:any) => {
+  let raw = getNormalHeader('Certification', json);
+  raw += "IdtyIssuer: " + json.idty_issuer + '\n';
+  raw += "IdtyUniqueID: " + json.idty_uid + '\n';
+  raw += "IdtyTimestamp: " + json.idty_buid + '\n';
+  raw += "IdtySignature: " + json.idty_sig + '\n';
+  raw += "CertTimestamp: " + json.buid + '\n';
+  if (json.sig) {
+    raw += json.sig + '\n';
+  }
+  return dos2unix(raw);
+}
+
+export const getOfficialRevocation = (json:any) => {
+  let raw = getNormalHeader('Revocation', json);
+  raw += "IdtyUniqueID: " + json.uid + '\n';
+  raw += "IdtyTimestamp: " + json.buid + '\n';
+  raw += "IdtySignature: " + json.sig + '\n';
+  if (json.revocation) {
+    raw += json.revocation + '\n';
+  }
+  return dos2unix(raw);
+}
+
+export const getPeerWithoutSignature = (json:any) => {
+  return document().Peer.fromJSON(json).getRawUnsigned()
+}
+
+export const getPeer = (json:any) => {
+  return document().Peer.fromJSON(json).getRaw()
+}
+
+export const getMembershipWithoutSignature = (json:any) => {
+  return document().Membership.toRAW(json)
+}
+
+export const getMembership = (json:any) => {
+  return dos2unix(signed(getMembershipWithoutSignature(json), json));
+}
+
+export const getBlockInnerPart = (json:any) => {
+  return document().Block.toRAWInnerPart(json)
+}
+
+export const getBlockWithInnerHashAndNonce = (json:any) => {
+  return document().Block.toRAWinnerPartWithHashAndNonce(json)
+}
+
+export const getBlockInnerHashAndNonce = (json:any) => {
+  return document().Block.toRAWHashAndNonce(json, UNSIGNED)
+}
+
+export const getBlockInnerHashAndNonceWithSignature = (json:any) => {
+  return document().Block.toRAWHashAndNonce(json, SIGNED)
+}
+
+export const getBlock = (json:any) => {
+  return dos2unix(signed(getBlockWithInnerHashAndNonce(json), json));
+}
+
+export const getTransaction = (json:any) => {
+  return document().Transaction.toRAW(json)
+}
+
+export const getCompactTransaction = (json:any) => {
+  return document().Transaction.getCompactTransaction(json)
+}
+
+function getNormalHeader(doctype:string, json:any) {
+  let raw = "";
+  raw += "Version: " + (json.version || DOCUMENTS_VERSION) + "\n";
+  raw += "Type: " + doctype + "\n";
+  raw += "Currency: " + json.currency + "\n";
+  raw += "Issuer: " + json.issuer + "\n";
+  return raw;
+}
+
+function signed(raw:string, json:any) {
+  raw += json.signature + '\n';
+  return raw;
+}
diff --git a/app/common/lib/txunlock.js b/app/lib/common-libs/txunlock.ts
similarity index 86%
rename from app/common/lib/txunlock.js
rename to app/lib/common-libs/txunlock.ts
index e423355f0..a136cfd30 100644
--- a/app/common/lib/txunlock.js
+++ b/app/lib/common-libs/txunlock.ts
@@ -1,7 +1,7 @@
 "use strict";
 
 let Parser = require("jison").Parser;
-let buid = require('./buid');
+let buid = require('../../../app/common/lib/buid')
 
 let grammar = {
   "lex": {
@@ -43,24 +43,24 @@ let grammar = {
   }
 };
 
-module.exports = function unlock(conditionsStr, executions, metadata) {
+export function unlock(conditionsStr:string, executions:any, metadata:any) {
 
   let parser = new Parser(grammar);
 
   parser.yy = {
     i: 0,
-    sig: function (pubkey) {
+    sig: function (pubkey:string) {
       let sigParam = executions[this.i++];
       return (sigParam && pubkey === sigParam.pubkey && sigParam.sigOK) || false;
     },
-    xHx: function(hash) {
+    xHx: function(hash:string) {
       let xhxParam = executions[this.i++];
       return buid.format.hashf(xhxParam) === hash;
     },
-    cltv: function(deadline) {
+    cltv: function(deadline:string) {
       return metadata.currentTime && metadata.currentTime >= parseInt(deadline);
     },
-    csv: function(amountToWait) {
+    csv: function(amountToWait:string) {
       return metadata.elapsedTime && metadata.elapsedTime >= parseInt(amountToWait);
     }
   };
@@ -70,4 +70,4 @@ module.exports = function unlock(conditionsStr, executions, metadata) {
   } catch(e) {
     return false;
   }
-};
+}
\ No newline at end of file
diff --git a/app/lib/common.ts b/app/lib/common.ts
index edf0ef092..e644a73d7 100644
--- a/app/lib/common.ts
+++ b/app/lib/common.ts
@@ -1,5 +1,9 @@
-const common = require('../../app/common')
+import * as crypto from 'crypto'
 
-export function hashf(str:string) {
-  return common.hashf(str).toUpperCase()
+export const hashf = function hashf(str:string) {
+  return crypto
+    .createHash("sha256")
+    .update(str)
+    .digest("hex")
+    .toUpperCase()
 }
diff --git a/app/lib/dal/sqliteDAL/MetaDAL.ts b/app/lib/dal/sqliteDAL/MetaDAL.ts
index 8dccc0eef..073ef5730 100644
--- a/app/lib/dal/sqliteDAL/MetaDAL.ts
+++ b/app/lib/dal/sqliteDAL/MetaDAL.ts
@@ -11,11 +11,11 @@ import {WalletDAL} from "./WalletDAL"
 import {MIndexDAL} from "./index/MIndexDAL"
 import {DBBlock} from "../../db/DBBlock"
 import {IdentityDTO} from "../../dto/IdentityDTO"
+import {rawer} from "../../common-libs/index";
 
 const _ = require('underscore')
 const logger = require('../../logger').NewLogger('metaDAL');
 const common = require('../../../../app/common');
-const rawer = require('../../../../app/common').rawer;
 const constants = require('./../../constants');
 
 export interface DBMeta {
diff --git a/app/lib/indexer.ts b/app/lib/indexer.ts
index cb2f4b22e..7ef5df43f 100644
--- a/app/lib/indexer.ts
+++ b/app/lib/indexer.ts
@@ -8,14 +8,12 @@ import {TransactionDTO} from "./dto/TransactionDTO"
 import {DBHead} from "./db/DBHead"
 import {LOCAL_RULES_HELPERS} from "./rules/local_rules"
 import {verify} from "./common-libs/crypto/keyring";
+import {rawer, txunlock} from "./common-libs/index";
 
-const co              = require('co');
 const _               = require('underscore');
 const common          = require('../../app/common');
 
 const constants       = common.constants
-const rawer           = common.rawer
-const unlock          = common.txunlock
 const Block           = common.document.Block
 const Membership      = common.document.Membership
 
@@ -2011,7 +2009,7 @@ function txSourceUnlock(ENTRY:SindexEntry, source:SindexEntry, HEAD: DBHead) {
       unlocksMetadata.elapsedTime = HEAD.medianTime - source.written_time;
     }
 
-    if (unlock(source.conditions, unlocksForCondition, unlocksMetadata)) {
+    if (txunlock(source.conditions, unlocksForCondition, unlocksMetadata)) {
       return true;
     }
   }
diff --git a/app/lib/rules/global_rules.ts b/app/lib/rules/global_rules.ts
index ca4eff2c4..077323c77 100644
--- a/app/lib/rules/global_rules.ts
+++ b/app/lib/rules/global_rules.ts
@@ -6,16 +6,15 @@ import {TransactionDTO} from "../dto/TransactionDTO"
 import * as local_rules from "./local_rules"
 import {BlockDTO} from "../dto/BlockDTO"
 import {verify} from "../common-libs/crypto/keyring"
+import {rawer, txunlock} from "../common-libs/index";
 
 const _              = require('underscore');
 const common         = require('../../../app/common');
 const indexer        = require('../indexer').Indexer
 
 const constants      = common.constants
-const rawer          = common.rawer
 const Identity       = common.document.Identity
 const Transaction    = common.document.Transaction
-const unlock         = common.txunlock
 
 // Empty logger by default
 let logger = {
@@ -127,7 +126,7 @@ export const GLOBAL_RULES_FUNCTIONS = {
           }
 
           try {
-            if (!unlock(dbSrc.conditions, unlocksForCondition, unlocksMetadata)) {
+            if (!txunlock(dbSrc.conditions, unlocksForCondition, unlocksMetadata)) {
               throw Error('Locked');
             }
           } catch (e) {
diff --git a/app/lib/rules/local_rules.ts b/app/lib/rules/local_rules.ts
index b67f44b6f..7913db391 100644
--- a/app/lib/rules/local_rules.ts
+++ b/app/lib/rules/local_rules.ts
@@ -5,12 +5,12 @@ import {CindexEntry, IndexEntry, Indexer, MindexEntry, SindexEntry} from "../ind
 import {BaseDTO, TransactionDTO} from "../dto/TransactionDTO"
 import {DBBlock} from "../db/DBBlock"
 import {verify} from "../common-libs/crypto/keyring"
+import {hashf} from "../common"
 
 const _          = require('underscore');
 const common     = require('../../../app/common');
 
 const constants       = common.constants
-const hashf           = common.hashf
 const Block           = common.document.Block
 const Identity        = common.document.Identity
 const Membership      = common.document.Membership
diff --git a/app/modules/bma/lib/controllers/AbstractController.ts b/app/modules/bma/lib/controllers/AbstractController.ts
index baf52825a..9206e3f68 100644
--- a/app/modules/bma/lib/controllers/AbstractController.ts
+++ b/app/modules/bma/lib/controllers/AbstractController.ts
@@ -1,6 +1,5 @@
 import {Server} from "../../../../../server"
-
-const dos2unix = require('../dos2unix')
+import {dos2unix} from "../../../../lib/common-libs/dos2unix"
 
 export abstract class AbstractController {
 
diff --git a/app/modules/bma/lib/dos2unix.ts b/app/modules/bma/lib/dos2unix.ts
deleted file mode 100644
index bbc290fc2..000000000
--- a/app/modules/bma/lib/dos2unix.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-module.exports = function dos2unix(str:string) {
-  return str.replace(/\r\n/g, '\n')
-}
diff --git a/app/modules/crawler/index.ts b/app/modules/crawler/index.ts
index 3a777527c..4cfdda9e3 100644
--- a/app/modules/crawler/index.ts
+++ b/app/modules/crawler/index.ts
@@ -5,6 +5,7 @@ import {Crawler} from "./lib/crawler"
 import {Synchroniser} from "./lib/sync"
 import {req2fwd} from "./lib/req2fwd"
 import {CrawlerConstants} from "./lib/constants"
+import {rawer} from "../../lib/common-libs/index";
 
 const common = require('../../../app/common');
 const Peer = common.document.Peer
@@ -180,7 +181,7 @@ export const CrawlerDependency = {
           const lookup = await sourcePeer.getLookup(search);
           for (const res of lookup.results) {
             for (const uid of res.uids) {
-              const rawIdty = common.rawer.getOfficialIdentity({
+              const rawIdty = rawer.getOfficialIdentity({
                 currency: 'g1',
                 issuer: res.pubkey,
                 uid: uid.uid,
@@ -194,7 +195,7 @@ export const CrawlerDependency = {
                 logger.error(e);
               }
               for (const received of uid.others) {
-                const rawCert = common.rawer.getOfficialCertification({
+                const rawCert = rawer.getOfficialCertification({
                   currency: 'g1',
                   issuer: received.pubkey,
                   idty_issuer: res.pubkey,
@@ -233,7 +234,7 @@ export const CrawlerDependency = {
                 block = await sourcePeer.getBlock(signed.cert_time.block)
                 mapBlocks[block.number] = block
               }
-              const rawCert = common.rawer.getOfficialCertification({
+              const rawCert = rawer.getOfficialCertification({
                 currency: 'g1',
                 issuer: certBy.pubkey,
                 idty_issuer: signed.pubkey,
@@ -302,7 +303,7 @@ export const CrawlerDependency = {
           for (const theMS of pendingMSS) {
             console.log('New membership pending for %s', theMS.uid);
             try {
-              rawMS = common.rawer.getMembership({
+              rawMS = rawer.getMembership({
                 currency: 'g1',
                 issuer: theMS.issuer,
                 block: theMS.block,
diff --git a/app/modules/crawler/lib/req2fwd.ts b/app/modules/crawler/lib/req2fwd.ts
index bccb576bf..31fbd703d 100644
--- a/app/modules/crawler/lib/req2fwd.ts
+++ b/app/modules/crawler/lib/req2fwd.ts
@@ -1,4 +1,6 @@
 import {Contacter} from "./contacter"
+import {verify} from "../../../lib/common-libs/crypto/keyring"
+import {rawer} from "../../../lib/common-libs/index";
 
 const common = require('../../../../app/common')
 
@@ -15,7 +17,7 @@ export const req2fwd = async (requirements:any, toHost:string, toPort:number, lo
         logger.info('New identity %s', idty.uid);
         identities[iid] = idty;
         try {
-          const rawIdty = common.rawer.getOfficialIdentity({
+          const rawIdty = rawer.getOfficialIdentity({
             currency: 'g1',
             issuer: idty.pubkey,
             uid: idty.uid,
@@ -33,7 +35,7 @@ export const req2fwd = async (requirements:any, toHost:string, toPort:number, lo
         if (!certs[cid]) {
           await new Promise((res) => setTimeout(res, 300));
           certs[cid] = received;
-          const rawCert = common.rawer.getOfficialCertification({
+          const rawCert = rawer.getOfficialCertification({
             currency: 'g1',
             issuer: received.from,
             idty_issuer: idty.pubkey,
@@ -43,7 +45,7 @@ export const req2fwd = async (requirements:any, toHost:string, toPort:number, lo
             buid: received.blockstamp,
             sig: received.sig
           });
-          const rawCertNoSig = common.rawer.getOfficialCertification({
+          const rawCertNoSig = rawer.getOfficialCertification({
             currency: 'g1',
             issuer: received.from,
             idty_issuer: idty.pubkey,
@@ -53,7 +55,7 @@ export const req2fwd = async (requirements:any, toHost:string, toPort:number, lo
             buid: received.blockstamp
           });
           try {
-            const chkSig = common.keyring.verify(rawCertNoSig, received.sig, received.from)
+            const chkSig = verify(rawCertNoSig, received.sig, received.from)
             if (!chkSig) {
               throw "Wrong signature for certification?!"
             }
@@ -70,7 +72,7 @@ export const req2fwd = async (requirements:any, toHost:string, toPort:number, lo
         if (!mss[id]) {
           mss[id] = theMS
           try {
-            const rawMS = common.rawer.getMembership({
+            const rawMS = rawer.getMembership({
               currency: 'g1',
               issuer: idty.pubkey,
               userid: idty.uid,
diff --git a/app/modules/crawler/lib/sandbox.ts b/app/modules/crawler/lib/sandbox.ts
index af03705e1..954bd3158 100644
--- a/app/modules/crawler/lib/sandbox.ts
+++ b/app/modules/crawler/lib/sandbox.ts
@@ -1,8 +1,8 @@
 "use strict";
 import {Contacter} from "./contacter"
 import {Server} from "../../../../server"
+import {rawer} from "../../../lib/common-libs/index";
 
-const rawer = require('../../../../app/common').rawer;
 const parsers = require('../../../../app/common').parsers;
 
 export const pullSandbox = async (currency:string, fromHost:string, fromPort:number, toHost:string, toPort:number, logger:any) => {
diff --git a/app/modules/crawler/lib/sync.ts b/app/modules/crawler/lib/sync.ts
index 95981ede9..d42e5c56e 100644
--- a/app/modules/crawler/lib/sync.ts
+++ b/app/modules/crawler/lib/sync.ts
@@ -11,6 +11,9 @@ import { tx_cleaner } from "./tx_cleaner";
 import { AbstractDAO } from "./pulling";
 import { DBBlock } from "../../../lib/db/DBBlock";
 import { BlockchainService } from "../../../service/BlockchainService";
+import {rawer} from "../../../lib/common-libs/index";
+import {dos2unix} from "../../../lib/common-libs/dos2unix"
+import {hashf} from "../../../lib/common"
 
 const util         = require('util');
 const _            = require('underscore');
@@ -19,9 +22,6 @@ const multimeter   = require('multimeter');
 const makeQuerablePromise = require('querablep');
 const common       = require('../../../../app/common');
 const Peer         = common.document.Peer;
-const dos2unix = common.dos2unix;
-const hashf = common.hashf;
-const rawer = common.rawer;
 
 const CONST_BLOCKS_CHUNK = 250;
 const EVAL_REMAINING_INTERVAL = 1000;
@@ -188,7 +188,7 @@ export class Synchroniser extends stream.Duplex {
       // We use cautious mode if it is asked, or not particulary asked but blockchain has been started
       const cautious = (askedCautious === true || localNumber >= 0);
       const shuffledPeers = noShufflePeers ? peers : _.shuffle(peers);
-      const downloader = new P2PDownloader(localNumber, to, rCurrent.hash, shuffledPeers, this.watcher, this.logger, hashf, rawer, this.dal, this.slowOption);
+      const downloader = new P2PDownloader(localNumber, to, rCurrent.hash, shuffledPeers, this.watcher, this.logger, hashf, this.dal, this.slowOption);
 
       downloader.start();
 
@@ -618,7 +618,6 @@ class P2PDownloader {
     private watcher:Watcher,
     private logger:any,
     private hashf:any,
-    private rawer:any,
     private dal:FileDAL,
     private slowOption:any) {
 
diff --git a/app/modules/prover/lib/blockGenerator.ts b/app/modules/prover/lib/blockGenerator.ts
index 2854cb6f3..7e49eef84 100644
--- a/app/modules/prover/lib/blockGenerator.ts
+++ b/app/modules/prover/lib/blockGenerator.ts
@@ -8,14 +8,14 @@ import {Indexer} from "../../../lib/indexer"
 import {FileDAL} from "../../../lib/dal/fileDAL"
 import {DBBlock} from "../../../lib/db/DBBlock"
 import {verify} from "../../../lib/common-libs/crypto/keyring"
+import {rawer} from "../../../lib/common-libs/index";
+import {hashf} from "../../../lib/common";
 
 const _               = require('underscore');
 const moment          = require('moment');
 const inquirer        = require('inquirer');
 const common          = require('../../../../app/common');
 
-const hashf         = common.hashf;
-const rawer         = common.rawer;
 const Block         = common.document.Block;
 const Membership    = common.document.Membership;
 const Transaction   = common.document.Transaction;
diff --git a/app/modules/prover/lib/permanentProver.ts b/app/modules/prover/lib/permanentProver.ts
index 42ac4442c..09c0ff6a4 100644
--- a/app/modules/prover/lib/permanentProver.ts
+++ b/app/modules/prover/lib/permanentProver.ts
@@ -3,10 +3,10 @@ import {ConfDTO} from "../../../lib/dto/ConfDTO"
 import {BlockProver} from "./blockProver"
 import {Constants} from "./constants"
 import {DBBlock} from "../../../lib/db/DBBlock"
+import {dos2unix} from "../../../lib/common-libs/dos2unix"
 
 const querablep = require('querablep');
 const common = require('../../../../app/common');
-const dos2unix = common.dos2unix;
 const parsers = common.parsers;
 
 export class PermanentProver {
diff --git a/app/modules/prover/lib/proof.ts b/app/modules/prover/lib/proof.ts
index 96c597842..e569f5a36 100644
--- a/app/modules/prover/lib/proof.ts
+++ b/app/modules/prover/lib/proof.ts
@@ -4,11 +4,11 @@ import {DBBlock} from "../../../lib/db/DBBlock"
 import {ConfDTO} from "../../../lib/dto/ConfDTO"
 import {Constants} from "./constants"
 import {KeyGen} from "../../../lib/common-libs/crypto/keyring"
+import {dos2unix} from "../../../lib/common-libs/dos2unix"
+import {rawer} from "../../../lib/common-libs/index";
 
 const moment = require('moment');
-const dos2unix = require('../../../../app/common').dos2unix;
 const querablep = require('querablep');
-const rawer = require('../../../../app/common').rawer;
 
 const PAUSES_PER_TURN = 5;
 
diff --git a/app/service/MembershipService.ts b/app/service/MembershipService.ts
index 6c6d83a4f..a64b16de3 100644
--- a/app/service/MembershipService.ts
+++ b/app/service/MembershipService.ts
@@ -6,7 +6,6 @@ import {LOCAL_RULES_HELPERS} from "../lib/rules/local_rules"
 import {GLOBAL_RULES_HELPERS} from "../lib/rules/global_rules"
 import {MembershipDTO} from "../lib/dto/MembershipDTO"
 
-const hashf           = require('../../app/common').hashf;
 const constants       = require('../lib/constants');
 
 export class MembershipService {
diff --git a/app/service/PeeringService.ts b/app/service/PeeringService.ts
index 70d515191..bba228ff6 100644
--- a/app/service/PeeringService.ts
+++ b/app/service/PeeringService.ts
@@ -6,15 +6,14 @@ import {DBBlock} from "../lib/db/DBBlock"
 import {Multicaster} from "../lib/streams/multicaster"
 import {PeerDTO} from "../lib/dto/PeerDTO"
 import {verify} from "../lib/common-libs/crypto/keyring"
+import {dos2unix} from "../lib/common-libs/dos2unix"
+import {rawer} from "../lib/common-libs/index";
 
 const util           = require('util');
 const _              = require('underscore');
 const events         = require('events');
 const rp             = require('request-promise');
 const logger         = require('../lib/logger').NewLogger('peering');
-const dos2unix       = require('../../app/common').dos2unix;
-const hashf          = require('../../app/common').hashf;
-const rawer          = require('../../app/common').rawer;
 const constants      = require('../lib/constants');
 
 export interface Keyring {
diff --git a/server.ts b/server.ts
index 5756973ac..7a76c5f54 100644
--- a/server.ts
+++ b/server.ts
@@ -30,7 +30,6 @@ const parsers     = require('./app/common').parsers;
 const constants   = require('./app/lib/constants');
 const jsonpckg    = require('./package.json');
 const directory   = require('./app/lib/system/directory');
-const rawer       = require('./app/common').rawer;
 const logger      = require('./app/lib/logger').NewLogger('server');
 
 export class Server extends stream.Duplex implements HookableServer {
@@ -62,7 +61,6 @@ export class Server extends stream.Duplex implements HookableServer {
     this.conf = ConfDTO.mock()
     this.version = jsonpckg.version;
     this.logger = logger;
-    this.rawer = rawer;
 
     this.paramsP = directory.getHomeParams(memoryOnly, home)
 
diff --git a/test/fast/modules/common/crypto.js b/test/fast/modules/common/crypto.js
index ce72bc5c5..1bdd4f6a3 100644
--- a/test/fast/modules/common/crypto.js
+++ b/test/fast/modules/common/crypto.js
@@ -2,11 +2,11 @@
 const should = require('should');
 const co  = require('co');
 const nacl   = require('tweetnacl');
-const base58 = require('../../../../app/common/lib/crypto/base58');
-const keyring      = require('../../../../app/common/lib/crypto/keyring');
+const base58 = require('../../../../app/lib/common-libs').base58
+const keyring      = require('../../../../app/lib/common-libs/crypto/keyring');
 
-const enc = nacl.util.encodeBase64,
-    dec = nacl.util.decodeBase64;
+const enc = require('../../../../app/lib/common-libs/crypto/nacl-util').encodeBase64,
+       dec = require('../../../../app/lib/common-libs/crypto/nacl-util').decodeBase64
 
 let pub, sec, rawPub, rawSec;
 
@@ -14,7 +14,7 @@ describe('ed25519 tests:', function(){
 
   before(() => co(function*() {
     // Generate the keypair
-    const keyPair = keyring.Key('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP');
+    const keyPair = keyring.KeyGen('HgTTJLAQ5sqfknMq7yLPZbehtuLSsKj9CxWN7k8QvYJd', '51w4fEShBk1jCMauWu4mLpmDVfHksKmWcygpxriqCEZizbtERA6de4STKRkQBpxmMUwsKXRjSzuQ8ECwmqN1u2DP');
     pub = base58.decode(keyPair.publicKey);
     sec = base58.decode(keyPair.secretKey);
     rawPub = base58.encode(pub);
@@ -33,7 +33,7 @@ describe('ed25519 tests:', function(){
 
   it('good signature from generated key should be verified', function(done){
     const msg = "Some message to be signed";
-    const sig = keyring.Key(rawPub, rawSec).signSync(msg);
+    const sig = keyring.KeyGen(rawPub, rawSec).signSync(msg);
     const verified = keyring.verify(msg, sig, rawPub);
     verified.should.equal(true);
     done();
@@ -42,7 +42,7 @@ describe('ed25519 tests:', function(){
   it('wrong signature from generated key should NOT be verified', function(done){
     const msg = "Some message to be signed";
     const cor = dec(enc(msg) + 'delta');
-    const sig = keyring.Key(rawPub, rawSec).signSync(msg);
+    const sig = keyring.KeyGen(rawPub, rawSec).signSync(msg);
     const verified = keyring.verify(cor, sig, rawPub);
     verified.should.equal(false);
     done();
diff --git a/test/fast/modules/common/grammar-test.js b/test/fast/modules/common/grammar-test.js
index 3e27dcc86..72270bf8d 100644
--- a/test/fast/modules/common/grammar-test.js
+++ b/test/fast/modules/common/grammar-test.js
@@ -1,6 +1,6 @@
 "use strict";
 
-const unlock    = require('../../../../app/common/lib/txunlock');
+const unlock    = require('../../../../app/lib/common-libs').txunlock
 const should    = require('should');
 
 describe('Grammar', () => {
diff --git a/test/fast/modules/common/randomKey.js b/test/fast/modules/common/randomKey.js
index 7a21f9cf8..6bc1f4135 100644
--- a/test/fast/modules/common/randomKey.js
+++ b/test/fast/modules/common/randomKey.js
@@ -2,10 +2,11 @@
 const should = require('should');
 const co  = require('co');
 const nacl   = require('tweetnacl');
-const keyring      = require('../../../../app/common/lib/crypto/keyring');
+const keyring      = require('../../../../app/lib/common-libs/crypto/keyring');
 
-const enc = nacl.util.encodeBase64,
-    dec = nacl.util.decodeBase64;
+
+const enc = require('../../../../app/lib/common-libs/crypto/nacl-util').encodeBase64,
+  dec = require('../../../../app/lib/common-libs/crypto/nacl-util').decodeBase64
 
 let key;
 
@@ -18,7 +19,7 @@ describe('Random keypair', function(){
 
   it('good signature from generated key should be verified', function(done){
     const msg = "Some message to be signed";
-    const sig = keyring.Key(key.publicKey, key.secretKey).signSync(msg);
+    const sig = keyring.KeyGen(key.publicKey, key.secretKey).signSync(msg);
     const verified = keyring.verify(msg, sig, key.publicKey);
     verified.should.equal(true);
     done();
@@ -27,7 +28,7 @@ describe('Random keypair', function(){
   it('wrong signature from generated key should NOT be verified', function(done){
     const msg = "Some message to be signed";
     const cor = dec(enc(msg) + 'delta');
-    const sig = keyring.Key(key.publicKey, key.secretKey).signSync(msg);
+    const sig = keyring.KeyGen(key.publicKey, key.secretKey).signSync(msg);
     const verified = keyring.verify(cor, sig, key.publicKey);
     verified.should.equal(false);
     done();
diff --git a/test/integration/cli.js b/test/integration/cli.js
index a6bdcfe2b..7f7fd57fc 100644
--- a/test/integration/cli.js
+++ b/test/integration/cli.js
@@ -8,7 +8,7 @@ const _         = require('underscore');
 const toolbox   = require('./tools/toolbox');
 const duniter   = require('../../index');
 const merkleh   = require('../../app/lib/helpers/merkle');
-const hashf     = require('../../app/common').hashf;
+const hashf     = require('../../app/lib/common-libs').hashf
 const constants = require('../../app/lib/constants');
 const MerkleDTO = require('../../app/lib/dto/MerkleDTO').MerkleDTO
 
diff --git a/test/integration/tools/user.js b/test/integration/tools/user.js
index c25105a7d..cbf62fa4f 100644
--- a/test/integration/tools/user.js
+++ b/test/integration/tools/user.js
@@ -7,8 +7,8 @@ const contacter = require('../../../app/modules/crawler').CrawlerDependency.duni
 const common  = require('../../../app/common');
 const ucp     = common.buid;
 const parsers = require('../../../app/common').parsers;
-const keyring	= common.keyring;
-const rawer		= common.rawer;
+const rawer = require('../../../app/lib/common-libs').rawer
+const keyring = require('../../../app/lib/common-libs/crypto/keyring')
 const constants = require('../../../app/lib/constants');
 const CertificationDTO = require('../../../app/lib/dto/CertificationDTO').CertificationDTO
 const MembershipDTO = require('../../../app/lib/dto/MembershipDTO').MembershipDTO
@@ -55,7 +55,7 @@ function User (uid, options, node) {
       issuer: pub,
       currency: node.server.conf.currency
     });
-    createdIdentity += keyring.Key(pub, sec).signSync(createdIdentity) + '\n';
+    createdIdentity += keyring.KeyGen(pub, sec).signSync(createdIdentity) + '\n';
     yield that.submitIdentity(createdIdentity, fromServer);
   });
 
@@ -82,7 +82,7 @@ function User (uid, options, node) {
     };
     _.extend(cert, overrideProps || {});
     const rawCert = rawer.getOfficialCertification(cert);
-    cert.sig = keyring.Key(pub, sec).signSync(rawCert, sec);
+    cert.sig = keyring.KeyGen(pub, sec).signSync(rawCert, sec);
     return CertificationDTO.fromJSONObject(cert);
   });
 
@@ -118,7 +118,7 @@ function User (uid, options, node) {
     };
     _.extend(revocation, overrideProps || {});
     const rawRevocation = rawer.getOfficialRevocation(revocation);
-    revocation.revocation = keyring.Key(pub, sec).signSync(rawRevocation);
+    revocation.revocation = keyring.KeyGen(pub, sec).signSync(rawRevocation);
     return RevocationDTO.fromJSONObject(revocation);
   });
 
@@ -145,7 +145,7 @@ function User (uid, options, node) {
     };
     _.extend(join, overrideProps || {});
     const rawJoin = rawer.getMembershipWithoutSignature(join);
-    join.signature = keyring.Key(pub, sec).signSync(rawJoin);
+    join.signature = keyring.KeyGen(pub, sec).signSync(rawJoin);
     return MembershipDTO.fromJSONObject(join)
   });
 
@@ -275,9 +275,9 @@ function User (uid, options, node) {
   });
 
   function signed(raw, user2) {
-    let signatures = [keyring.Key(pub, sec).signSync(raw)];
+    let signatures = [keyring.KeyGen(pub, sec).signSync(raw)];
     if (user2) {
-      signatures.push(keyring.Key(user2.pub, user2.sec).signSync(raw));
+      signatures.push(keyring.KeyGen(user2.pub, user2.sec).signSync(raw));
     }
     return raw + signatures.join('\n') + '\n';
   }
@@ -325,7 +325,7 @@ function User (uid, options, node) {
     });
     _.extend(peer, overrideProps || {});
     const rawPeer = rawer.getPeerWithoutSignature(peer);
-    peer.signature = keyring.Key(pub, sec).signSync(rawPeer);
+    peer.signature = keyring.KeyGen(pub, sec).signSync(rawPeer);
     return PeerDTO.fromJSONObject(peer)
   });
 
-- 
GitLab