Skip to content

Commit

Permalink
WIP: p2p begins again
Browse files Browse the repository at this point in the history
  • Loading branch information
coolaj86 committed Aug 15, 2024
1 parent 64d9087 commit be817f7
Show file tree
Hide file tree
Showing 3 changed files with 229 additions and 21 deletions.
203 changes: 203 additions & 0 deletions public/dashjoin.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,21 @@ var DashJoin = ('object' === typeof module && exports) || {};
(function (window, DashJoin) {
'use strict';

let DashTx = window.DashTx || require('dashtx');

//@ts-ignore
let Packer = window.CJPacker || require('./packer.js');
//@ts-ignore
let Parser = window.CJParser || require('./parser.js');

const DENOM_LOWEST = 100001;
const PREDENOM_MIN = DENOM_LOWEST + 193;
const COLLATERAL = 10000; // DENOM_LOWEST / 10

// https://github.com/dashpay/dash/blob/v19.x/src/coinjoin/coinjoin.h#L39
// const COINJOIN_ENTRY_MAX_SIZE = 9; // real
// const COINJOIN_ENTRY_MAX_SIZE = 2; // just for testing right now

DashJoin.DENOM_LOWEST = DENOM_LOWEST;
DashJoin.COLLATERAL = COLLATERAL;
DashJoin.PREDENOM_MIN = PREDENOM_MIN;
Expand All @@ -31,6 +42,198 @@ var DashJoin = ('object' === typeof module && exports) || {};
return 0;
};

DashJoin.utils = {};

DashJoin.utils.hexToBytes = function (hex) {
let bufLen = hex.length / 2;
let u8 = new Uint8Array(bufLen);

let i = 0;
let index = 0;
let lastIndex = hex.length - 2;
for (;;) {
if (i > lastIndex) {
break;
}

let h = hex.slice(i, i + 2);
let b = parseInt(h, 16);
u8[index] = b;

i += 2;
index += 1;
}

return u8;
};

// {
// let versionP = dj.once('version', { timeout: 1500 });
// dj.send('version', packVersion())
// for (;;) {
// versionP = dj.once('version', { timeout: 1500 });
// let version = await versionP;
// if (version.isTheRightOne) {
// break;
// }
// }
// }

DashJoin.utils.bytesToHex = function (u8) {
/** @type {Array<String>} */
let hex = [];

u8.forEach(function (b) {
let h = b.toString(16).padStart(2, '0');
hex.push(h);
});

return hex.join('');
};

DashJoin.wsConnect = function (p2pWebProxyUrl, evonode) {
if (!p2pWebProxyUrl) {
//p2pWebProxyUrl = 'wss://tp2p.digitalcash.dev/ws';
p2pWebProxyUrl = 'wss://ubuntu-127.scratch-dev.digitalcash.dev/ws';
}

let query = {
access_token: 'secret',
hostname: evonode.hostname,
port: evonode.port,
};
let searchParams = new URLSearchParams(query);
let search = searchParams.toString();
let wsc = new WebSocket(`${p2pWebProxyUrl}?${search}`);

// TODO listen to all messages that are CJ Pool messages
// (and build current pools)

let dataCount = 0;
wsc.addEventListener('message', async function (wsevent) {
console.log('[DEBUG] onReadableHeader wsc.onmessage');
let ab = await wsevent.data.arrayBuffer();
let bytes = new Uint8Array(ab);
dataCount += bytes.length;
console.log('[DEBUG] bytes (readable header)');
console.log(dataCount, bytes.length, DashJoin.utils.bytesToHex(bytes));
// onReadableHeader(bytes);

let currentHeader = Parser.parseHeader(bytes);
console.log(currentHeader);
});

return wsc;
};

DashJoin.sendVersion = function (
wsc,
evonode,
blockHeight,
agentVersion,
network,
) {
//
// version / verack
//
let versionMsg = Packer.version({
network: network, // Packer.NETWORKS.regtest,
//protocol_version: Packer.PROTOCOL_VERSION,
//addr_recv_services: [Packer.IDENTIFIER_SERVICES.NETWORK],
addr_recv_ip: evonode.hostname,
addr_recv_port: evonode.port,
//addr_trans_services: [],
//addr_trans_ip: '127.0.01',
//addr_trans_port: null,
// addr_trans_ip: conn.localAddress,
// addr_trans_port: conn.localPort,
start_height: blockHeight,
//nonce: null,
user_agent: `DashJoin.js/${agentVersion}`,
// optional-ish
relay: false,
mnauth_challenge: null,
mn_connection: false,
});
wsc.send(versionMsg);
};

DashJoin.utils._evonodeMapToList = function (evonodesMap) {
console.log('[debug] get evonode list...');
let evonodes = [];
{
//let resp = await rpc.masternodelist();
let evonodeProTxIds = Object.keys(evonodesMap);
for (let id of evonodeProTxIds) {
let evonode = evonodesMap[id];
if (evonode.status !== 'ENABLED') {
continue;
}

let hostParts = evonode.address.split(':');
let evodata = {
id: evonode.id,
host: evonode.address,
hostname: hostParts[0],
port: hostParts[1],
type: evonode.type,
};
evonodes.push(evodata);
}
if (!evonodes.length) {
throw new Error('Sanity Fail: no evonodes online');
}
}

// void shuffle(evonodes);
evonodes.sort(DashJoin.utils.sortMnListById);
return evonodes;
};

/**
* @param {Object} a
* @param {String} a.id
* @param {Object} b
* @param {String} b.id
*/
DashJoin.utils.sortMnListById = function (a, b) {
if (a.id > b.id) {
return 1;
}
if (a.id < b.id) {
return -1;
}
return 0;
};

/**
* @param {Array<Uint8Array>} byteArrays
* @param {Number?} [len]
* @returns {Uint8Array}
*/
function concatBytes(byteArrays, len) {
if (!len) {
for (let bytes of byteArrays) {
len += bytes.length;
}
}

let allBytes = new Uint8Array(len);
let offset = 0;
for (let bytes of byteArrays) {
allBytes.set(bytes, offset);
offset += bytes.length;
}

return allBytes;
}

function sleep(ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms);
});
}

//@ts-ignore
window.DashJoin = DashJoin;
})(globalThis.window || {}, DashJoin);
Expand Down
2 changes: 2 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
<script src="./node_modules/dashkeys/dashkeys.js"></script>
<script src="./node_modules/dashhd/dashhd.js"></script>
<script src="./node_modules/dashtx/dashtx.js"></script>
<script src="./parser.js"></script>
<script src="./packer.js"></script>
<script src="./dashjoin.js"></script>
<style>
nav {
Expand Down
45 changes: 24 additions & 21 deletions public/wallet-app.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@
const MIN_BALANCE = 100001 * 1000;

let network = 'testnet';
let rpcBaseUrl = 'https://trpc.digitalcash.dev/';
let rpcBasicAuth = `api:null`;
let rpcBaseUrl = `https://${rpcBasicAuth}@trpc.digitalcash.dev/`;
let rpcExplorer = 'https://trpc.digitalcash.dev/';
let rpcBasicAuth = btoa(`api:null`);

let addresses = [];
let changeAddrs = [];
Expand Down Expand Up @@ -81,25 +81,8 @@
console.log('DEBUG dashTx instance', dashTx);

async function rpc(method, ...params) {
// typically http://localhost:19998/
let payload = JSON.stringify({ method, params });
let resp = await fetch(rpcBaseUrl, {
method: 'POST',
headers: {
Authorization: `Basic ${rpcBasicAuth}`,
'Content-Type': 'application/json',
},
body: payload,
});

let data = await resp.json();
if (data.error) {
let err = new Error(data.error.message);
Object.assign(err, data.error);
throw err;
}

return data.result;
let result = await DashTx.utils.rpc(rpcBaseUrl, method, ...params);
return result;
}

function dbGet(key, defVal) {
Expand Down Expand Up @@ -1039,9 +1022,29 @@
}

await init();

siftDenoms();
renderCashDrawer();
App.syncCashDrawer();

App._rawmnlist = await rpc('masternodelist');
App._chaininfo = await rpc('getblockchaininfo');
console.log(App._rawmnlist);
App._evonodes = DashJoin.utils._evonodeMapToList(App._rawmnlist);
App._evonode = App._evonodes.at(-1);
console.info('[info] chosen evonode:');
console.log(JSON.stringify(App._evonode, null, 2));

let wsc = DashJoin.wsConnect('', App._evonode);
wsc.addEventListener('open', async function () {
await DashJoin.sendVersion(
wsc,
App._evonode,
App._chaininfo.blocks,
'v0.x.x',
network,
);
});
}

main().catch(function (err) {
Expand Down

0 comments on commit be817f7

Please sign in to comment.