http-api.js source code

Note: before running this Node Server, ensure you execute:

$ npm install

and have setup the .env in the same directory as this script.

PKS="9038d1a01a3c1d34840f0a49ab1fb54b29e48f659a749df260db3ea432d77ebf"
HTTP="http://localhost:8545"
WS="ws://localhost:8545"
WEBHOOK="http://localhost:8000/webhook"
HTTP_PORT=9090

then run:

$ node http-api.js
listening on 9090

See here for the full source code.

const Web3 = require('web3');
const HDWalletProvider = require("@truffle/hdwallet-provider");
const BN = require('bn.js');
const ethers = require("ethers");
const pako = require('pako');
const web3_eth_abi = require("web3-eth-abi");
const express = require('express');
const axios = require('axios');
const dotenv = require('dotenv');
dotenv.config();
const testNetHttpUrl = process.env.HTTP;
const testNetWsUrl = process.env.WS;
const webhookUrl = process.env.WEBHOOK;
const privateKeys = process.env.PKS.split(",");
const httpPort = process.env.HTTP_PORT;
let hdWalletProvider = new HDWalletProvider(privateKeys, testNetHttpUrl);
let web3 = new Web3(new Web3.providers.HttpProvider(testNetHttpUrl));
const TruffleContract = require('truffle-contract');
const web3Provider = new Web3.providers.WebsocketProvider(testNetWsUrl);
const TrustAnchorManagerArtifact = require('./build/contracts/TrustAnchorManager.json');
const TrustAnchorManager = TruffleContract(TrustAnchorManagerArtifact);
TrustAnchorManager.setProvider(web3Provider);
TrustAnchorManager.setProvider(hdWalletProvider);
const TrustAnchorStorageArtifact = require('./build/contracts/TrustAnchorStorage.json');
const TrustAnchorStorage = TruffleContract(TrustAnchorStorageArtifact);
TrustAnchorStorage.setProvider(web3Provider);
TrustAnchorStorage.setProvider(hdWalletProvider);
const TrustAnchorExtraData_UniqueArtifact = require('./build/contracts/TrustAnchorExtraData_Unique.json');
const TrustAnchorExtraData_Unique = TruffleContract(TrustAnchorExtraData_UniqueArtifact);
TrustAnchorExtraData_Unique.setProvider(web3Provider);
TrustAnchorExtraData_Unique.setProvider(hdWalletProvider);
const TrustAnchorExtraData_GenericArtifact = require('./build/contracts/TrustAnchorExtraData_Generic.json');
const TrustAnchorExtraData_Generic = TruffleContract(TrustAnchorExtraData_GenericArtifact);
TrustAnchorExtraData_Generic.setProvider(web3Provider);
TrustAnchorExtraData_Generic.setProvider(hdWalletProvider);
function decodeDocument(_documentEncoded) {
const hex = Uint8Array.from(Buffer.from(_documentEncoded, 'hex'));
try {
let inflated = pako.inflate(hex);
let inflatedToHex = Buffer.from(inflated).toString('hex');
let unzippedEncodedDocumentsMatrix = "0x" + inflatedToHex;
let decodedDocumentsMatrix = web3_eth_abi.decodeParameter(
{
"DocumentsMatrixStruct": {
"bitsMatrix": 'uint256',
"versionCode": 'uint16',
"encryptedData": 'bytes'
}
},
unzippedEncodedDocumentsMatrix
);
return decodedDocumentsMatrix;
} catch (err) {
console.log(err);
return null;
}
}
function decodeDocumentMatrixInPlace(_dataTemplate) {
if (_dataTemplate.versionCode == 2) {
let bytesDocumentMatrixEncodedPacked = ethers.utils.toUtf8String(_dataTemplate.encryptedData);
let encodedDocumentMatrixDataPacked = JSON.parse(bytesDocumentMatrixEncodedPacked);
_dataTemplate["decryptedData"] = encodedDocumentMatrixDataPacked;
return _dataTemplate;
} else {
return null;
}
}
function unpackCryptoAddress(decodeDocumentMatrix) {
return ethers.utils.toUtf8String(decodeDocumentMatrix.decryptedData.data);
}
function unpackDocumentsMatrixEncrypted(documentMatrix) {
let decodedDocument = decodeDocument(documentMatrix);
let decodeDocumentMatrix = decodeDocumentMatrixInPlace(decodedDocument);
let unpackedCryptoAddress = unpackCryptoAddress(decodeDocumentMatrix);
return unpackedCryptoAddress;
}
function convertComponentsFromHex(hex) {
return web3.utils.hexToAscii(hex);
}
function convertToByte32(string) {
var temp = web3.utils.asciiToHex(string);
temp = web3.utils.hexToBytes(temp);
return temp;
}
function createTravelRuleTemplate(_documentMatrixDataBytes) {
let documentsMatrixBitString = "";
let documentsMatrixBits = new Array(256);
documentsMatrixBitString += "1";
let i = 0;
for (i = 1 ; i < 255; i++) {
documentsMatrixBitString += "0";
}
documentsMatrixBitString += "0";
let documentMatrixBignum = new BN(documentsMatrixBitString, 2);
let versionCode = 2;
return {"bitsMatrix" : documentMatrixBignum, "versionCode" : versionCode, "documentMatrixDataBytes" : _documentMatrixDataBytes};
}
function encodeDocumentMatrixInPlace(_dataTemplate) {
if (_dataTemplate.versionCode === 2 && _dataTemplate.documentMatrixDataBytes != null) {
let encodedDocumentMatrixDataPacked = JSON.stringify(_dataTemplate.documentMatrixDataBytes);
let bytesDocumentMatrixEncodedPacked = ethers.utils.toUtf8Bytes(encodedDocumentMatrixDataPacked);
_dataTemplate["encryptedData"] = bytesDocumentMatrixEncodedPacked;
return _dataTemplate;
} else {
return null;
}
}
function encodeDocument(_bitsMatrix, _versionCode, _encryptedData) {
if (_versionCode === 1 || _versionCode == 2) {
let encodedDocumentsMatrix = web3_eth_abi.encodeParameter(
{
"DocumentsMatrixStruct": {
"bitsMatrix": 'uint256',
"versionCode": 'uint16',
"encryptedData": 'bytes'
}
},
{
"bitsMatrix": _bitsMatrix.toString(),
"versionCode": _versionCode.toString(),
"encryptedData": _encryptedData
}
);
const hex = Uint8Array.from(Buffer.from(encodedDocumentsMatrix.substr(2), 'hex'));
let zippedEncodedDocumentsMatrix = pako.deflate(hex).buffer;
const zippedHex = Buffer.from(zippedEncodedDocumentsMatrix).toString('hex');
return zippedHex;
} else {
return null;
}
}
function packDocumentsMatrixEncrypted(address) {
let addressBuffer = new Buffer(address);
let travelRuleTemplate = createTravelRuleTemplate(addressBuffer);
let encodedDocumentMatrix = encodeDocumentMatrixInPlace(travelRuleTemplate);
let encodedDocument = encodeDocument(encodedDocumentMatrix.bitsMatrix, encodedDocumentMatrix.versionCode, encodedDocumentMatrix.encryptedData);
return encodedDocument;
}
//WEBHOOK
function sendWebhookMessage(obj) {
axios.post(webhookUrl, {
obj:obj
})
.then((res) => {
console.log(`statusCode: ${res.statusCode}`)
})
.catch((error) => {
console.error(error)
});
}
//APIS
const app = express();
app.listen(httpPort, () => {
console.log('listening on '+httpPort);
});
/*
create trust anchor account
url: /ta-create-account
request: GET
params: nil
response:
{
request: 'ta-create-account'
address: '0x68c1a65E3456b6cEc5561156E2430921144E15ef',
privateKey: '0x9038d1a01a3c1d34840f0a49ab1fb54b29e48f659a749df260db3ea432d77ebf',
signTransaction: [Function: signTransaction],
sign: [Function: sign],
encrypt: [Function: encrypt]
}
*/
// eg: /ta-create-account
app.get('/ta-create-account', (req, res) => {
trustAnchorCreateAccount();
res.sendStatus(201);
});
function trustAnchorCreateAccount() {
var result = web3.eth.accounts.create();
console.log(result);
sendWebhookMessage(result);
}
/*
is trust anchor account verified
request: GET
params:
account: 0x68c1a65E3456b6cEc5561156E2430921144E15ef
response:
{
request: 'is-ta-verified',
result: true,
account: '0x68c1a65E3456b6cEc5561156E2430921144E15ef'
}
*/
// eg: /is-ta-verified?account=0x68c1a65E3456b6cEc5561156E2430921144E15ef
app.get('/is-ta-verified', (req, res) => {
var account = req.param('account');
getIsTrustAnchorVerified(account);
res.sendStatus(201);
});
function getIsTrustAnchorVerified(account) {
(async () => {
var tam = await TrustAnchorManager.deployed();
result = await tam.isTrustAnchorVerified.call(account)
console.log('isTrustAnchorVerified result');
console.log(result);
var obj = {request: 'is-ta-verified', result: result, account: account};
sendWebhookMessage(obj);
})();
}
/*
get balance
request: GET
params:
account: 0x68c1a65E3456b6cEc5561156E2430921144E15ef
note balance in WEI
response:
{
request: 'get-balance',
balance: '10000000000000000000',
account: '0x68c1a65E3456b6cEc5561156E2430921144E15ef'
}
*/
// eg: /get-balance?account=0x68c1a65E3456b6cEc5561156E2430921144E15ef
app.get('/get-balance', (req, res) => {
var account = req.param('account');
getBalance(account);
res.sendStatus(201);
});
function getBalance(account) {
(async () => {
var balance = await web3.eth.getBalance(account);
var obj = {request: 'get-balance', balance: balance, account: account};
sendWebhookMessage(obj);
})();
}
/*
trust anchor set unique address
request: GET
params: account (0x719bb7FE970d9Ee375149a156dB93aD128ce0b07)
response:
{
request: 'ta-set-unique-address',
result: BN {
negative: 0,
words: [ 1, <1 empty item> ],
length: 1,
red: null
},
account: '0x68c1a65E3456b6cEc5561156E2430921144E15ef'
}
{
request: 'ta-set-unique-address',
hash: {
tx: '0xeafa1d82be139d8418440b67e909c33693a581dca73b7507e76f2071b467ef22',
receipt: {
transactionHash: '0xeafa1d82be139d8418440b67e909c33693a581dca73b7507e76f2071b467ef22',
transactionIndex: 0,
blockHash: '0xd216cc8da74e8227a5b672af291657101c61d8264c93e72a2ade071fd45d4298',
blockNumber: 543,
from: '0x68c1a65e3456b6cec5561156e2430921144e15ef',
to: '0x284e91d6047ba49737154a45ebc3fba5ebf4e17f',
gasUsed: 45580,
cumulativeGasUsed: 45580,
contractAddress: null,
logs: [Array],
status: true,
logsBloom: '0x00000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000002000000000000000000',
rawLogs: [Array]
},
logs: [ [Object] ]
},
account: '0x68c1a65E3456b6cEc5561156E2430921144E15ef'
}
*/
// eg: /ta-set-unique-address?account=0x68c1a65E3456b6cEc5561156E2430921144E15ef
app.get('/ta-set-unique-address', (req, res) => {
var account = req.param('account');
trustAnchorSetUniqueAddress(account);
res.sendStatus(201);
});
function trustAnchorSetUniqueAddress(account) {
(async () => {
var tam = await TrustAnchorManager.deployed();
var taed_unique = await TrustAnchorExtraData_Unique.deployed();
result = await tam.setUniqueTrustAnchorExtraDataAddress.call(taed_unique.address, {from: account})
console.log('setUniqueTrustAnchorExtraDataAddress result');
console.log(result);
var obj = {request: 'ta-set-unique-address', result: result, account: account};
sendWebhookMessage(obj);
hash = await tam.setUniqueTrustAnchorExtraDataAddress(taed_unique.address, {from: account})
console.log('setUniqueTrustAnchorExtraDataAddress hash');
console.log(hash);
var obj = {request: 'ta-set-unique-address', hash: hash, account: account};
sendWebhookMessage(obj);
})();
}
/*
trust anchor set key value pair
request: GET
params:
account: 0x68c1a65E3456b6cEc5561156E2430921144E15ef
key_name: ENTITY
key_value: ACME INC.
response:
{
request: 'ta-set-key-value-pair',
result: BN {
negative: 0,
words: [ 1, <1 empty item> ],
length: 1,
red: null
},
account: '0x68c1a65E3456b6cEc5561156E2430921144E15ef'
}
{
request: 'ta-set-key-value-pair',
hash: {
tx: '0xbcf9668bf653e39f12c132da53fa819a6227dcb4901199d14adbe6addf78dcf6',
receipt: {
transactionHash: '0xbcf9668bf653e39f12c132da53fa819a6227dcb4901199d14adbe6addf78dcf6',
transactionIndex: 0,
blockHash: '0x180ba3bbd71afc6695df8673893d87cb890da9b9a206f58cf044e0ec2981d743',
blockNumber: 544,
from: '0x68c1a65e3456b6cec5561156e2430921144e15ef',
to: '0xc37f608ff7b0edb779c0660de912f12ce0bbc864',
gasUsed: 157213,
cumulativeGasUsed: 157213,
contractAddress: null,
logs: [Array],
status: true,
logsBloom: '0x00000000000000000000000000000000000000000020000010000000000000000000000000000000000000008002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000001000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
rawLogs: [Array]
},
logs: [ [Object] ]
},
account: '0x68c1a65E3456b6cEc5561156E2430921144E15ef'
}
*/
// eg: /ta-set-key-value-pair?account=0x68c1a65E3456b6cEc5561156E2430921144E15ef&key_name=ENTITY&key_value=ACME INC.
app.get('/ta-set-key-value-pair', (req, res) => {
var account = req.param('account');
var key_name = req.param('key_name');
var key_value = req.param('key_value');
trustAnchorSetKeyValuePair(account, key_name, key_value);
res.sendStatus(201);
});
function trustAnchorSetKeyValuePair(account, key_name, key_value) {
(async () => {
taed_unique = await TrustAnchorExtraData_Unique.deployed();
result = await taed_unique.setTrustAnchorKeyValuePair.call(key_name, key_value, {from: account})
console.log('setTrustAnchorKeyValuePair result');
console.log(result);
var obj = {request: 'ta-set-key-value-pair', result: result, account: account};
sendWebhookMessage(obj);
hash = await taed_unique.setTrustAnchorKeyValuePair(key_name, key_value, {from: account})
console.log('setTrustAnchorKeyValuePair hash');
console.log(hash);
var obj = {request: 'ta-set-key-value-pair', hash: hash, account: account};
sendWebhookMessage(obj);
})();
}
/*
trust anchor set endpoint
request: GET
params:
account: 0x68c1a65E3456b6cEc5561156E2430921144E15ef
key_name: acme.com
key_value: "127.0.0.1"
response:
{
request: 'ta-set-endpoint',
result: BN {
negative: 0,
words: [ 1, <1 empty item> ],
length: 1,
red: null
},
account: '0x68c1a65E3456b6cEc5561156E2430921144E15ef'
}
{
request: 'ta-set-endpoint',
hash: {
tx: '0xec2cf8cee06da82fc0dabb96ea5773b70651a0419b6854c1db627c64a83440f8',
receipt: {
transactionHash: '0xec2cf8cee06da82fc0dabb96ea5773b70651a0419b6854c1db627c64a83440f8',
transactionIndex: 0,
blockHash: '0x0aa1107196b870929cd03b48dbdc3ad5fb0f44aaf6cc204faaf31152239be077',
blockNumber: 545,
from: '0x68c1a65e3456b6cec5561156e2430921144e15ef',
to: '0xcea2c0c5f2c05d88a497a85fc7999125233661a5',
gasUsed: 136423,
cumulativeGasUsed: 136423,
contractAddress: null,
logs: [Array],
status: true,
logsBloom: '0x00000000000000000000000000000000000000000020008000000000000000000000000000000000000000000002000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
rawLogs: [Array]
},
logs: [ [Object] ]
},
account: '0x68c1a65E3456b6cEc5561156E2430921144E15ef'
}
*/
// eg: /ta-set-endpoint?account=0x68c1a65E3456b6cEc5561156E2430921144E15ef&endpoint_name=acme.com&ip_address=127.0.0.1
app.get('/ta-set-endpoint', (req, res) => {
var account = req.param('account');
var endpoint_name = req.param('endpoint_name');
var ip_address = req.param('ip_address');
trustAnchorSetEndpoint(account, endpoint_name, ip_address);
res.sendStatus(201);
});
function trustAnchorSetEndpoint(account, endpoint_name, ip_address) {
(async () => {
ip_address = ip_address.split('.');
taed_generic = await TrustAnchorExtraData_Generic.deployed();
result = await taed_generic.setTrustAnchorDataRetrievalParameters.call(endpoint_name, ip_address, {from: account})
console.log('setTrustAnchorDataRetrievalParameters result');
console.log(result);
var obj = {request: 'ta-set-endpoint', result: result, account: account};
sendWebhookMessage(obj);
hash = await taed_generic.setTrustAnchorDataRetrievalParameters(endpoint_name, ip_address, {from: account})
console.log('setTrustAnchorDataRetrievalParameters hash');
console.log(hash);
var obj = {request: 'ta-set-endpoint', hash: hash, account: account};
sendWebhookMessage(obj);
})();
}
/*
trust anchor create user account
request: GET
params: user_id
response:
{
address: '0x98f23e2E65f32d45b1F4D6e65259A980670872b4',
privateKey: '0x62458e1701f29ac59e1d86aeb8f4084dc0aea0f682bd8df4addd83f8cb88deb4',
signTransaction: [Function: signTransaction],
sign: [Function: sign],
encrypt: [Function: encrypt],
user_id: '1'
}
*/
// eg: /ta-create-user-account?user_id=1
app.get('/ta-create-user-account', (req, res) => {
var user_id = req.param('user_id');
trustAnchorCreateUserAccount(user_id);
res.sendStatus(201);
});
function trustAnchorCreateUserAccount(user_id) {
var result = web3.eth.accounts.create();
console.log(result);
result['user_id'] = user_id;
sendWebhookMessage(result);
}
/*
trust anchor set attestation
request: GET
params:
user_account: 0x98f23e2E65f32d45b1F4D6e65259A980670872b4
jurisdiction: INT
effective_time: UNIX TIMESTAMP
expiry_time: UNIX TIMESTAMP
public_data: "WALLET"
documents_matrix_encrypted: "16Qygw3QgX4TgZxneVWQeVVxp2XNYf9vP9"
availability_address_encrypted: "BTC"
is_managed: true
ta_account: 0x719bb7FE970d9Ee375149a156dB93aD128ce0b07
response:
{
request: 'ta-set-attestation',
result: Result {
'0': BN { negative: 0, words: [Array], length: 1, red: null },
'1': '0x380800f183bd8c803976f14230c8a3521db9f5631efc865238577f2954d745eb',
result: BN { negative: 0, words: [Array], length: 1, red: null },
resultAttestationKeccak: '0x380800f183bd8c803976f14230c8a3521db9f5631efc865238577f2954d745eb'
}
}
{
request: 'ta-set-attestation',
hash: {
tx: '0x8068d2017b5b9f6fcb53c758b5a8f7c4eabde96f753cbd8b194c6ceba398799e',
receipt: {
transactionHash: '0x8068d2017b5b9f6fcb53c758b5a8f7c4eabde96f753cbd8b194c6ceba398799e',
transactionIndex: 0,
blockHash: '0x9076a2e235720cceef48da52cb9e4efebefcceb567efb32ae1e20622e23bac9e',
blockNumber: 546,
from: '0x68c1a65e3456b6cec5561156e2430921144e15ef',
to: '0x5b7f41346df7636b52a3b227019f62affaa5c3de',
gasUsed: 506590,
cumulativeGasUsed: 506590,
contractAddress: null,
logs: [Array],
status: true,
logsBloom: '0x00000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000008010000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
rawLogs: [Array]
},
logs: [ [Object] ]
}
}
*/
// eg: /ta-set-attestation?user_account=0x98f23e2E65f32d45b1F4D6e65259A980670872b4&jurisdiction=1&effective_time=1564449732&expiry_time=1627694532&public_data=WALLET&documents_matrix_encrypted=16Qygw3QgX4TgZxneVWQeVVxp2XNYf9vP9&availability_address_encrypted=BTC&is_managed=true&ta_account=0x68c1a65E3456b6cEc5561156E2430921144E15ef
app.get('/ta-set-attestation', (req, res) => {
var user_account = req.param('user_account');
var jurisdiction = req.param('jurisdiction');
var effective_time = req.param('effective_time');
var expiry_time = req.param('expiry_time');
var public_data = req.param('public_data');
var documents_matrix_encrypted = req.param('documents_matrix_encrypted');
var availability_address_encrypted = req.param('availability_address_encrypted');
var is_managed = req.param('is_managed');
var ta_account = req.param('ta_account');
trustAnchorSetAttestation(user_account, jurisdiction, effective_time, expiry_time, public_data, documents_matrix_encrypted, availability_address_encrypted, is_managed, ta_account);
res.sendStatus(201);
});
function trustAnchorSetAttestation(user_account, jurisdiction, effective_time, expiry_time, public_data, documents_matrix_encrypted, availability_address_encrypted, is_managed, ta_account) {
public_data = convertToByte32(public_data);
console.log('public_data');
console.log(public_data);
documents_matrix_encrypted = packDocumentsMatrixEncrypted(documents_matrix_encrypted);
documents_matrix_encrypted = convertToByte32(documents_matrix_encrypted);
console.log('documents_matrix_encrypted');
console.log(documents_matrix_encrypted);
availability_address_encrypted = convertToByte32(availability_address_encrypted);
console.log('availability_address_encrypted');
console.log(availability_address_encrypted);
(async () => {
tas = await TrustAnchorStorage.deployed();
result = await tas.setAttestation.call(user_account, jurisdiction, effective_time, expiry_time, public_data, documents_matrix_encrypted, availability_address_encrypted, is_managed, {from: ta_account});
console.log('setAttestation result');
console.log(result);
var obj = {request: 'ta-set-attestation', result: result};
sendWebhookMessage(obj);
hash = await tas.setAttestation(user_account, jurisdiction, effective_time, expiry_time, public_data, documents_matrix_encrypted, availability_address_encrypted, is_managed, {from: ta_account});
console.log('setAttestation hash');
console.log(hash);
var obj = {request: 'ta-set-attestation', hash: hash};
sendWebhookMessage(obj);
})();
}
/*
trust anchor get attestation array for trust anchor account
request: GET
params:
account: 0x719bb7FE970d9Ee375149a156dB93aD128ce0b07
response:
{
request: 'ta-get-attestation-array-for-ta-account',
result: [
'0x380800f183bd8c803976f14230c8a3521db9f5631efc865238577f2954d745eb'
]
}
*/
// eg: /ta-get-attestation-array-for-ta-account?account=0x68c1a65E3456b6cEc5561156E2430921144E15ef
app.get('/ta-get-attestation-array-for-ta-account', (req, res) => {
var account = req.param('account');
trustAnchorGetAttestationArrayForTrustAnchorAccount(account);
res.sendStatus(201);
});
function trustAnchorGetAttestationArrayForTrustAnchorAccount(account) {
(async () => {
tas = await TrustAnchorStorage.deployed();
result = await tas.getAttestationKeccakArrayForTrustAnchor.call(account)
console.log('getAttestationKeccakArrayForTrustAnchor result');
console.log(result);
var obj = {request: 'ta-get-attestation-array-for-ta-account', result: result};
sendWebhookMessage(obj);
})();
}
/*
trust anchor set attestation
request: GET
params:
account: 0x719bb7FE970d9Ee375149a156dB93aD128ce0b07
response:
{
request: 'ta-get-attestation-array-for-user-account',
result: [
'0x380800f183bd8c803976f14230c8a3521db9f5631efc865238577f2954d745eb'
]
}
*/
// eg: /ta-get-attestation-array-for-user-account?account=0x98f23e2E65f32d45b1F4D6e65259A980670872b4
app.get('/ta-get-attestation-array-for-user-account', (req, res) => {
var account = req.param('account');
trustAnchorGetAttestationArrayForUserAccount(account);
res.sendStatus(201);
});
function trustAnchorGetAttestationArrayForUserAccount(account) {
(async () => {
tas = await TrustAnchorStorage.deployed();
result = await tas.getAttestationKeccakArrayForIdentifiedAddress.call(account)
console.log('getAttestationKeccakArrayForIdentifiedAddress result');
console.log(result);
var obj = {request: 'ta-get-attestation-array-for-user-account', result: result};
sendWebhookMessage(obj);
})();
}
/*
trust anchor get attestation components
request: GET
params:
attestation_hash: TODO
response:
{
request: 'ta-get-attestation-components',
result: Result {
'0': '0x68c1a65E3456b6cEc5561156E2430921144E15ef',
'1': BN { negative: 0, words: [Array], length: 1, red: null },
'2': BN { negative: 0, words: [Array], length: 2, red: null },
'3': BN { negative: 0, words: [Array], length: 2, red: null },
'4': '0x57414c4c4554',
'5': '0x37383963363336306330306231343161663063623133303234633034653431333038633866373536326239353534313661343261353932393339393561366135613531363239653932386135323439363234326135393435396235386561393839616538353831386561313831613031623138316231386561313231353063343130326330326534353935386538393831616539353839383830333939363036343035353430366330386334303634303235363633613136653631303835313038653139353464613438633764343030613464336463343263376332313232383062653439623033383538313363303332303262623631363862303330316336313032303637',
'6': '0x4254430000000000000000000000000000000000000000000000000000000000',
'7': true,
trustAnchorAddress: '0x68c1a65E3456b6cEc5561156E2430921144E15ef',
jurisdiction: BN { negative: 0, words: [Array], length: 1, red: null },
effectiveTime: BN { negative: 0, words: [Array], length: 2, red: null },
expiryTime: BN { negative: 0, words: [Array], length: 2, red: null },
publicData: 'WALLET',
documentsMatrixEncrypted: '16Qygw3QgX4TgZxneVWQeVVxp2XNYf9vP9',
availabilityAddressEncrypted: 'BTC',
isManaged: true
}
}
*/
app.get('/ta-get-attestation-components', (req, res) => {
var attestation_hash = req.param('attestation_hash');
trustAnchorGetAttestationComponents(attestation_hash);
res.sendStatus(201);
});
function trustAnchorGetAttestationComponents(attestation_hash) {
(async () => {
tas = await TrustAnchorStorage.deployed();
result = await tas.getAttestationComponents.call(attestation_hash)
console.log('getAttestationComponents result');
console.log(result);
var documentsMatrixEncrypted = convertComponentsFromHex(result['documentsMatrixEncrypted']);
documentsMatrixEncrypted = unpackDocumentsMatrixEncrypted(documentsMatrixEncrypted);
result['documentsMatrixEncrypted'] = documentsMatrixEncrypted;
result['publicData'] = convertComponentsFromHex(result['publicData']);
result['availabilityAddressEncrypted'] = convertComponentsFromHex(result['availabilityAddressEncrypted']).replace(/\0/g, '');
console.log('decoded components');
console.log(result);
var obj = {request: 'ta-get-attestation-components', result: result};
sendWebhookMessage(obj);
})();
}
//Encryption Decryption
const ecies = require("eth-ecies");
const EthCrypto = require('eth-crypto');
const EthUtil = require('ethereumjs-util');
function getEthAddressFromPublicKey(_publicKey) {
const publicAddress = EthCrypto.publicKey.toAddress(_publicKey);
return publicAddress;
}
function getEthPublicKey(_privateKey) {
let privateKey = _privateKey;
if (Buffer.isBuffer(_privateKey)) {
privateKey = "0x" + _privateKey.toString('hex');
}
const publicKey = EthCrypto.publicKeyByPrivateKey(
privateKey
);
return publicKey;
}
function encryptData(publicKey, data) {
let userPublicKey = new Buffer(publicKey, 'hex');
let bufferData = new Buffer(data);
let encryptedData = ecies.encrypt(userPublicKey, bufferData);
return encryptedData.toString('base64')
}
function decryptData(privateKey, data) {
console.log('decryptData');
let userPrivateKey = new Buffer(privateKey, 'hex');
let bufferEncryptedData = new Buffer(data, 'base64');
let decryptedData = ecies.decrypt(userPrivateKey, bufferEncryptedData);
return decryptedData.toString('utf8');
}
function bufferToHex(buffer) {
var result = EthUtil.bufferToHex(buffer);
return result;
}
function signSignature(message, privateKey) {
var messageBuffer = new Buffer(JSON.stringify(message));
var hash = EthUtil.hashPersonalMessage(messageBuffer);
var ecprivkey = Buffer.from(privateKey.substr(2),'hex');
var result = EthUtil.ecsign(hash, ecprivkey, 1);
var template = {};
template['SignatureHash'] = bufferToHex(hash);
template['Signature'] = {r: bufferToHex(result['r']),s: bufferToHex(result['s']),v: bufferToHex(result['v'])};
return template;
}
function recoverSignature(signature, signatureHash) {
var messageHash = Buffer.from(signatureHash.substr(2),'hex');
result = EthUtil.ecrecover(messageHash, signature['v'], signature['r'], signature['s'], 1);
var pubkeyString = bufferToHex(result).substr(2);
return pubkeyString;
}
const bodyParser = require('body-parser');
app.use(bodyParser.json());
//KYC TEMPLATE
var kycTemplate = {
AttestationHash: '',
BeneficiaryTAAddress: '',
BeneficiaryTAPublicKey: '',
BeneficiaryTASignatureHash: '',
BeneficiaryTASignature: {},
BeneficiaryUserAddress: '',
BeneficiaryUserPublicKey: '',
BeneficiaryUserSignatureHash: '',
BeneficiaryUserSignature: {},
CryptoAddressType: '',
CryptoAddress: '',
CryptoPublicKey: '',
CryptoSignatureHash: '',
CryptoSignature: {},
SenderTAAddress: '',
SenderTAPublicKey: '',
SenderTASignatureHash: '',
SenderTASignature: {},
SenderUserAddress: '',
SenderUserPublicKey: '',
SenderUserSignatureHash: '',
SenderUserSignature: {},
BeneficiaryKYC: '',
SenderKYC: ''
};
/*
get kyc template (JSON)
url: /kyc-get-template
request: GET
params: nil
response:
{
"AttestationHash": "",
"BeneficiaryTAAddress": "",
"BeneficiaryTAPublicKey": "",
"BeneficiaryTASignatureHash": "",
"BeneficiaryTASignature": {},
"BeneficiaryUserAddress": "",
"BeneficiaryUserPublicKey": "",
"BeneficiaryUserSignatureHash": "",
"BeneficiaryUserSignature": {},
"CryptoAddressType": "",
"CryptoAddress": "",
"CryptoPublicKey": "",
"CryptoSignatureHash": "",
"CryptoSignature": {},
"SenderTAAddress": "",
"SenderTAPublicKey": "",
"SenderTASignatureHash": "",
"SenderTASignature": {},
"SenderUserAddress": "",
"SenderUserPublicKey": "",
"SenderUserSignatureHash": "",
"SenderUserSignature": {},
"BeneficiaryKYC": "",
"SenderKYC": ""
}
*/
app.get('/kyc-get-template', (req, res) => {
res.json(kycTemplate);
});
/*
get ETH address from public key
url: /kyc-get-eth-address-from-public-key
request: POST
params: {"public_key": string}
response:
{
"address": "0xbC11D726e5A6081d940eF452D5e50Be0623BB24c"
}
*/
/* eg: {
"public_key": "0730e063e946848bea3ae6334fee192085fc3859b8116719e818a1e4a2f0341c22461ddd66e98fe5bd405d1cff35be335a3bdd366ed1523c42d4e73f86250f30"
}
*/
app.post('/kyc-get-eth-address-from-public-key', (req, res) => {
var json = req.body;
var public_key = json['public_key'];
var address = getEthAddressFromPublicKey(public_key);
res.json({address: address});
});
// (_publicKey)
/*
get eth public key
url: /kyc-get-eth-public-key
request: GET
params: private_key
response:
{
"publicKey": "8870c2e326b9b7ad0fad7c58475e5d29867debaf0f8a0de7d6a24266c258a3e9d70977250325bf15bcbddaa3c5d8f320a7b93ad99801cd9b64c6f841f1be87f1"
}
*/
// eg: /kyc-get-eth-public-key?private_key=fba556045b439f709efc0abecb8bcf7bdd661b2186fbbdfd4db157aa451936f5
app.get('/kyc-get-eth-public-key', (req, res) => {
var private_key = req.param('private_key');
var public_key = getEthPublicKey(private_key);
res.json({publicKey:public_key});
});
/*
encrypt data with public key
url: /kyc-encrypt-data
request: POST
params: {"public_key": string, "data": json}
response:
{
"kycEncryptData": "zWF72XKgSXfOAXxjjG9d/gSD9zIIRY2/qFL+aVc3b2OiktpSG3OJwO/wSuyeEtmG0rJ63LnKncdliE93dFlPByhIFsYDQM7vXR+oa3vCU3EzH8LUxIgK2GwFdiM4y9tI7h9uwo+DSAy3GYG8RuLWaCJoUgrv9b0xeyvYxwbUhAxf9c9yUHnXrdbTCZ5ec4NZ8GDmC9uBvO1A40rQF+n2Vio+kiSFGIhY6QCfXqKI2mJLt/FbajPLQw1EYT55sLprLg=="
}
*/
// eg: {"public_key": "8870c2e326b9b7ad0fad7c58475e5d29867debaf0f8a0de7d6a24266c258a3e9d70977250325bf15bcbddaa3c5d8f320a7b93ad99801cd9b64c6f841f1be87f1", "data":{"fullname": "John Smith", "dob":"1990-01-30", "jurisdiction": "SG"}}
app.post('/kyc-encrypt-data', (req, res) => {
var json = req.body;
var public_key = json['public_key'];
var data = json['data'];
var kyc_data = JSON.stringify(data);
var kyc_encrypt = encryptData(public_key, kyc_data);
res.json({kycEncryptData:kyc_encrypt});
});
/*
decrypt data with private key
url: /kyc-decrypt-data
request: POST
params: {"private_key": string, "data": string}
response:
{
"fullname": "John Smith",
"dob": "1990-01-30",
"jurisdiction": "SG"
}
*/
// eg: {"private_key": "fba556045b439f709efc0abecb8bcf7bdd661b2186fbbdfd4db157aa451936f5", "data":"zWF72XKgSXfOAXxjjG9d/gSD9zIIRY2/qFL+aVc3b2OiktpSG3OJwO/wSuyeEtmG0rJ63LnKncdliE93dFlPByhIFsYDQM7vXR+oa3vCU3EzH8LUxIgK2GwFdiM4y9tI7h9uwo+DSAy3GYG8RuLWaCJoUgrv9b0xeyvYxwbUhAxf9c9yUHnXrdbTCZ5ec4NZ8GDmC9uBvO1A40rQF+n2Vio+kiSFGIhY6QCfXqKI2mJLt/FbajPLQw1EYT55sLprLg=="}
app.post('/kyc-decrypt-data', (req, res) => {
var json = req.body;
var private_key = json['private_key'];
var data = json['data'];
var kycDecryptData = decryptData(private_key, data);
kycDecryptData = JSON.parse(kycDecryptData);
res.json(kycDecryptData);
});
/*
get signature and hash
url: /kyc-get-signature-and-hash
request: POST
params: {"signature_message": string, "private_key": string}
response:
{
"SignatureHash": "0x6d22b5cb8615f6dd22982cce1c76fedcdc7e314a36ce6b50413a60024f10c19b",
"Signature": {
"r": "0x45ef55683adfcc5aa2569e0584b2f64e2a6f1cf230adaa43879ffc6e4d8aa891",
"s": "0x4dead30c6719bfd3f2b2ca30bbcd3f0d8401897bf6a49a8938796180d0e4b2b8",
"v": "0x25"
}
}
*/
// eg: {"signature_message": "ACME VASP", "private_key": "0x455bd988c72fbd91a42043f02dd07d720e59044127510a47eac694c7933a5af7"}
app.post('/kyc-get-signature-and-hash', (req, res) => {
var json = req.body;
var signature_message = json['signature_message'];
var private_key = json['private_key'];
var template = signSignature(signature_message, private_key);
res.json(template);
});
/*
recover public key from signature and signature hash
url: /kyc-recover-public-key-from-signature-and-hash
request: POST
params: {"signature_hash": string, "signature": json}
response:
{
"publicKey": "0730e063e946848bea3ae6334fee192085fc3859b8116719e818a1e4a2f0341c22461ddd66e98fe5bd405d1cff35be335a3bdd366ed1523c42d4e73f86250f30"
}
*/
/* eg: {
"signature_hash": "0x6d22b5cb8615f6dd22982cce1c76fedcdc7e314a36ce6b50413a60024f10c19b",
"signature": {
"r": "0x45ef55683adfcc5aa2569e0584b2f64e2a6f1cf230adaa43879ffc6e4d8aa891",
"s": "0x4dead30c6719bfd3f2b2ca30bbcd3f0d8401897bf6a49a8938796180d0e4b2b8",
"v": "0x25"
}
}
*/
app.post('/kyc-recover-public-key-from-signature-and-hash', (req, res) => {
var json = req.body;
var signature = json['signature'];
var signature_hash = json['signature_hash'];
var public_key = recoverSignature(signature, signature_hash);
res.json({publicKey: public_key});
});