ribc/index.html
2019-09-27 21:34:16 +05:30

1126 lines
39 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<title>FLO Operators</title>
</head>
<script>
/* Constants for FLO blockchain operations !!Make sure to add this at begining!! */
floGlobals = {
//Required for all
blockchain: "FLO_TEST",
//Required for blockchain API operators
apiURL: {
FLO: 'https://flosight.duckdns.org',
FLO_TEST: 'https://testnet-flosight.duckdns.org'
},
adminID: "oTZw3ydCRKDhcYC5Bp6mRJMGTTVv9JHtg8",
sendAmt: 0.001,
fee: 0.0005,
//Required for Supernode operations
supernodes = {}, //each supnernode must be stored as floID : {uri:<uri>,pubKey:<publicKey>}
}
</script>
<body>
use console
</body>
<script>
/* Reactor Event handling */
if (typeof reactor == "undefined" || !reactor) {
(function () {
function Event(name) {
this.name = name;
this.callbacks = [];
}
Event.prototype.registerCallback = function (callback) {
this.callbacks.push(callback);
};
function Reactor() {
this.events = {};
}
Reactor.prototype.registerEvent = function (eventName) {
var event = new Event(eventName);
this.events[eventName] = event;
};
Reactor.prototype.dispatchEvent = function (eventName, eventArgs) {
this.events[eventName].callbacks.forEach(function (callback) {
callback(eventArgs);
});
};
Reactor.prototype.addEventListener = function (eventName, callback) {
this.events[eventName].registerCallback(callback);
};
window.reactor = new Reactor();
})();
}
/* Sample Usage
--Creating and defining the event--
reactor.registerEvent('<eventName>');
reactor.addEventListener('<eventName>', function(someObject){
do something...
});
--Firing the event--
reactor.dispatchEvent('<eventName>',<someObject>);
*/
</script>
<script>
/* FLO Crypto Operators*/
floCryptoOperators = {
p: BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16),
ecparams: EllipticCurve.getSECCurveByName("secp256k1"),
exponent1: function () {
return this.p.add(BigInteger.ONE).divide(BigInteger("4"))
},
calculateY: function (x) {
let p = this.p;
let exp = this.exponent1();
// x is x value of public key in BigInteger format without 02 or 03 or 04 prefix
return x.modPow(BigInteger("3"), p).add(BigInteger("7")).mod(p).modPow(exp, p)
},
getUncompressedPublicKey: function (compressedPublicKey) {
const p = this.p;
// Fetch x from compressedPublicKey
let pubKeyBytes = Crypto.util.hexToBytes(compressedPublicKey);
const prefix = pubKeyBytes.shift() // remove prefix
let prefix_modulus = prefix % 2;
pubKeyBytes.unshift(0) // add prefix 0
let x = new BigInteger(pubKeyBytes)
let xDecimalValue = x.toString()
// Fetch y
let y = this.calculateY(x);
let yDecimalValue = y.toString();
// verify y value
let resultBigInt = y.mod(BigInteger("2"));
let check = resultBigInt.toString() % 2;
if (prefix_modulus !== check) {
yDecimalValue = y.negate().mod(p).toString();
}
return {
x: xDecimalValue,
y: yDecimalValue
};
},
getSenderPublicKeyString: function () {
privateKey = ellipticCurveEncryption.senderRandom();
senderPublicKeyString = ellipticCurveEncryption.senderPublicString(privateKey);
return {
privateKey: privateKey,
senderPublicKeyString: senderPublicKeyString
}
},
deriveSharedKeySender: function (receiverCompressedPublicKey, senderPrivateKey) {
try {
let receiverPublicKeyString = this.getUncompressedPublicKey(receiverCompressedPublicKey);
var senderDerivedKey = ellipticCurveEncryption.senderSharedKeyDerivation(
receiverPublicKeyString.x, receiverPublicKeyString.y, senderPrivateKey);
return senderDerivedKey;
} catch (error) {
return new Error(error);
}
},
deriveReceiverSharedKey: function (senderPublicKeyString, receiverPrivateKey) {
return ellipticCurveEncryption.receiverSharedKeyDerivation(
senderPublicKeyString.XValuePublicString, senderPublicKeyString.YValuePublicString,
receiverPrivateKey);
},
getReceiverPublicKeyString: function (privateKey) {
return ellipticCurveEncryption.receiverPublicString(privateKey);
},
deriveSharedKeyReceiver: function (senderPublicKeyString, receiverPrivateKey) {
try {
return ellipticCurveEncryption.receiverSharedKeyDerivation(senderPublicKeyString.XValuePublicString,
senderPublicKeyString.YValuePublicString, receiverPrivateKey);
} catch (error) {
return new Error(error);
}
},
wifToDecimal: function (pk_wif, isPubKeyCompressed = false) {
let pk = Bitcoin.Base58.decode(pk_wif)
pk.shift()
pk.splice(-4, 4)
//If the private key corresponded to a compressed public key, also drop the last byte (it should be 0x01).
if (isPubKeyCompressed == true) pk.pop()
pk.unshift(0)
privateKeyDecimal = BigInteger(pk).toString()
privateKeyHex = Crypto.util.bytesToHex(pk)
return {
privateKeyDecimal: privateKeyDecimal,
privateKeyHex: privateKeyHex
}
},
//Encrypt Data using public-key
encryptData: function (data, receiverCompressedPublicKey) {
var senderECKeyData = this.getSenderPublicKeyString();
var senderDerivedKey = this.deriveSharedKeySender(receiverCompressedPublicKey, senderECKeyData.privateKey);
let senderKey = senderDerivedKey.XValue + senderDerivedKey.YValue;
let secret = Crypto.AES.encrypt(data, senderKey);
return {
secret: secret,
senderPublicKeyString: senderECKeyData.senderPublicKeyString
};
},
//Decrypt Data using private-key
decryptData: function (data, myPrivateKey) {
var receiverECKeyData = {};
if (typeof myPrivateKey !== "string") throw new Error("No private key found.");
let privateKey = this.wifToDecimal(myPrivateKey, true);
if (typeof privateKey.privateKeyDecimal !== "string") throw new Error(
"Failed to detremine your private key.");
receiverECKeyData.privateKey = privateKey.privateKeyDecimal;
var receiverDerivedKey = this.deriveReceiverSharedKey(data.senderPublicKeyString, receiverECKeyData
.privateKey);
console.log("receiverDerivedKey", receiverDerivedKey);
let receiverKey = receiverDerivedKey.XValue + receiverDerivedKey.YValue;
let decryptMsg = Crypto.AES.decrypt(data.secret, receiverKey);
return decryptMsg;
},
//Sign data using private-key
signData: function (data, privateKeyHex) {
var key = new Bitcoin.ECKey(privateKeyHex);
key.setCompressed(true);
var privateKeyArr = key.getBitcoinPrivateKeyByteArray();
privateKey = BigInteger.fromByteArrayUnsigned(privateKeyArr);
var messageHash = Crypto.SHA256(data);
var messageHashBigInteger = new BigInteger(messageHash);
var messageSign = Bitcoin.ECDSA.sign(messageHashBigInteger, key.priv);
var sighex = Crypto.util.bytesToHex(messageSign);
return sighex;
},
//Verify signatue of the data using public-key
verifySign: function (data, signatureHex, publicKeyHex) {
var msgHash = Crypto.SHA256(data);
var messageHashBigInteger = new BigInteger(msgHash);
var sigBytes = Crypto.util.hexToBytes(signatureHex);
var signature = Bitcoin.ECDSA.parseSig(sigBytes);
var publicKeyPoint = this.ecparams.getCurve().decodePointHex(publicKeyHex);
var verify = Bitcoin.ECDSA.verifyRaw(messageHashBigInteger, signature.r, signature.s,
publicKeyPoint);
return verify;
},
//Generates a new flo ID and returns private-key, public-key and floID
generateNewID: function () {
try {
var key = new Bitcoin.ECKey(false);
key.setCompressed(true);
return {
floID: key.getBitcoinAddress(),
pubKey: key.getPubKeyHex(),
privKey: key.getBitcoinWalletImportFormat()
}
} catch (e) {
console.log(e);
}
},
//Returns public-key from private-key
getPubKeyHex: function (privateKeyHex) {
var key = new Bitcoin.ECKey(privateKeyHex);
if (key.priv == null) {
alert("Invalid Private key");
return;
}
key.setCompressed(true);
var pubkeyHex = key.getPubKeyHex();
return pubkeyHex;
},
//Returns flo-ID from public-key
getFloIDfromPubkeyHex: function (pubkeyHex) {
var key = new Bitcoin.ECKey().setPub(pubkeyHex);
var floID = key.getBitcoinAddress();
return floID;
},
//Verify the private-key for the given public-key or flo-ID
verifyPrivKey: function (privateKeyHex, pubKey_floID, isfloID = true) {
try {
var key = new Bitcoin.ECKey(privateKeyHex);
if (key.priv == null)
return false;
key.setCompressed(true);
if (isfloID && pubKey_floID == key.getBitcoinAddress())
return true;
else if (!isfloID && pubKey_floID == key.getPubKeyHex())
return true;
else
return false;
} catch (e) {
console.log(e);
}
},
//Check if the given Address is valid or not
validateAddr: function (inpAddr) {
try {
var addr = new Bitcoin.Address(inpAddr);
return true;
} catch {
return false;
}
}
}
</script>
<script>
/* FLO Blockchain Operator to send/receive data from blockchain using API calls*/
floBlockchainOperator = {
//Promised AJAX function to get data from API
promisedAJAX: function (method, uri) {
return new Promise((resolve, reject) => {
var request = new XMLHttpRequest();
var url = `${floGlobals.apiURL[floGlobals.blockchain]}/${uri}`;
console.log(url)
request.open(method, url, true);
request.onload = (evt) => {
if (request.readyState == 4 && request.status == 200)
resolve(request.response);
else
reject(request.response);
};
request.send();
});
},
//Get balance for the given Address
getBalance: function (addr) {
return new Promise((resolve, reject) => {
this.promisedAJAX("GET", `api/addr/${addr}/balance`).then(balance => {
resolve(parseFloat(balance));
}).catch(error => {
reject(error);
});
});
},
//Write Data into blockchain
writeData: function (senderAddr, Data, PrivKey, receiverAddr = floGlobals.adminID) {
return new Promise((resolve, reject) => {
this.sendTx(senderAddr, receiverAddr, floGlobals.sendAmt, PrivKey, Data).then(txid => {
resolve(txid);
}).catch(error => {
reject(error);
});
});
},
//Send Tx to blockchain
sendTx: function (senderAddr, receiverAddr, sendAmt, PrivKey, floData = '') {
return new Promise((resolve, reject) => {
if (!floCryptoOperators.validateAddr(senderAddr))
reject(`Invalid address : ${senderAddr}`);
else if (!floCryptoOperators.validateAddr(receiverAddr))
reject(`Invalid address : ${receiverAddr}`);
if (PrivKey.length < 1 || !floCryptoOperators.verifyPrivKey(PrivKey, senderAddr))
reject("Invalid Private key!");
else if (typeof sendAmt !== 'number' || sendAmt <= 0)
reject(`Invalid sendAmt : ${sendAmt}`);
else {
var trx = bitjs.transaction();
var utxoAmt = 0.0;
var fee = floGlobals.fee;
this.promisedAJAX("GET", `api/addr/${senderAddr}/utxo`).then(response => {
var utxos = JSON.parse(response);
for (var i = utxos.length - 1;
(i >= 0) && (utxoAmt < sendAmt + fee); i--) {
if (utxos[i].confirmations) {
trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey)
utxoAmt += utxos[i].amount;
} else break;
}
if (utxoAmt < sendAmt + fee)
reject("Insufficient balance!");
else {
trx.addoutput(receiverAddr, sendAmt);
var change = utxoAmt - sendAmt - fee;
if (change > 0)
trx.addoutput(senderAddr, change);
trx.addflodata(floData);
var signedTxHash = trx.sign(PrivKey, 1);
this.broadcastTx(signedTxHash).then(txid => {
resolve(txid)
}).catch(error => {
reject(error);
});
}
}).catch(error => {
reject(error);
});
}
});
},
//Broadcast signed Tx in blockchain using API
broadcastTx: function (signedTxHash) {
return new Promise((resolve, reject) => {
var request = new XMLHttpRequest();
var url = `${floGlobals.apiURL[floGlobals.blockchain]}/api/tx/send`;
if (signedTxHash.length < 1)
reject("Empty Signature");
else {
var params = `{"rawtx":"${signedTxHash}"}`;
var result;
request.open('POST', url, false);
//Send the proper header information along with the request
request.setRequestHeader('Content-type', 'application/json');
request.onload = function () {
if (request.readyState == 4 && request.status == 200) {
console.log(request.response);
resolve(JSON.parse(request.response).txid.result);
} else
reject(request.responseText);
}
request.send(params);
return result;
}
})
},
//Read Txs of Address between from and to
readData: function (addr, from, to) {
return new Promise((resolve, reject) => {
this.promisedAJAX("GET", `api/addrs/${addr}/txs?from=${from}&to=${to}`).then(response => {
resolve(JSON.parse(response));
}).catch(error => {
reject(error);
});
});
},
//Read All Txs of Address (newest first)
readAllData: function (addr) {
return new Promise((resolve, reject) => {
this.promisedAJAX("GET", `api/addrs/${addr}/txs?from=0&to=1`).then(response => {
var totalItems = JSON.parse(response).totalItems;
this.promisedAJAX("GET", `api/addrs/${addr}/txs?from=0&to=${totalItems}0`).then(response => {
resolve(JSON.parse(response).items);
}).catch(error => {
reject(error);
});
}).catch(error => {
reject(error);
});
});
},
//Read Data Sent from Address (if limit is specified, only return newest sent data)
readSentData: function (addr, limit = 0) {
return new Promise((resolve, reject) => {
this.readAllData(addr).then(items => {
var filteredItems = [];
if (limit <= 0) limit = items.length;
for (i = 0; i < items.length && filteredItems.length < limit; i++)
if (items[i].vin[0].addr === addr)
filteredItems.push(items[i]);
console.log(filteredItems);
resolve(filteredItems);
}).catch(error => {
reject(error)
});
});
},
//Read newest 'limit' Data matching 'pattern'
readDataPattern: function (addr, pattern, jsonType = false, limit = 1000) {
return new Promise((resolve, reject) => {
this.readAllData(addr).then(items => {
var filteredItems = [];
var pos = (jsonType ? 2 : 0);
for (i = 0; i < items.length && filteredItems.length < limit; i++)
if (items[i].floData.startsWith(pattern, pos))
filteredItems.push(items[i]);
resolve(filteredItems);
}).catch(error => {
reject(error)
});
});
},
//Read newest 'limit' Data Sent from Address and matching 'pattern'
readSentDataPattern: function (addr, pattern, jsonType = false, limit = 1000) {
return new Promise((resolve, reject) => {
this.readAllData(addr).then(items => {
var filteredItems = [];
var pos = (jsonType ? 2 : 0);
for (i = 0; i < items.length && filteredItems.length < limit; i++)
if (items[i].vin[0].addr === addr && items[i].floData.startsWith(pattern, pos))
filteredItems.push(items[i]);
resolve(filteredItems);
}).catch(error => {
reject(error)
});
});
},
//Read newest 'limit' Data containing 'keyword'
readDataContains: function (addr, keyword, limit = 1000) {
return new Promise((resolve, reject) => {
this.readAllData(addr).then(items => {
var filteredItems = [];
for (i = 0; i < items.length && filteredItems.length < limit; i++)
if (items[i].floData.includes(keyword))
filteredItems.push(items[i]);
resolve(filteredItems);
}).catch(error => {
reject(error)
});
});
},
//Read newest 'limit' Data Sent from Address and containing 'keyword'
readSentDataContains: function (addr, keyword, limit = 1000) {
return new Promise((resolve, reject) => {
this.readAllData(addr).then(items => {
var filteredItems = [];
for (i = 0; i < items.length && filteredItems.length < limit; i++)
if (items[i].vin[0].addr === addr && items[i].floData.includes(keyword))
filteredItems.push(items[i]);
resolve(filteredItems);
}).catch(error => {
reject(error)
});
});
}
}
</script>
<script>
/* flo Supernode Operators to send/receive data from supernodes using websocket */
floSupernodeOperator = {
//kBucket object
kBucket: {
supernodeKBucket = null,
decodeBase58Address: function (address) {
let k = bitjs.Base58.decode(address)
k.shift()
k.splice(-4, 4)
return Crypto.util.bytesToHex(k)
},
floIdToKbucketId: function (address) {
const decodedId = this.decodeBase58Address(address);
const nodeIdBigInt = new BigInteger(decodedId, 16);
const nodeIdBytes = nodeIdBigInt.toByteArrayUnsigned();
const nodeIdNewInt8Array = new Uint8Array(nodeIdBytes);
return nodeIdNewInt8Array;
},
launch: function (superNodeList, master_floID) {
return new Promise((resolve, reject) => {
try {
const SuKBucketId = this.floIdToKbucketId(master_floID);
const SukbOptions = {
localNodeId: SuKBucketId
}
this.supernodeKBucket = new BuildKBucket(SukbOptions);
for (var i = 0; i < superNodeList.length; i++) {
this.addNewNode(superNodeList[i])
}
resolve('SuperNode KBucket formed');
} catch (error) {
reject(error);
}
});
},
addContact: function (id, floID, KB = this.supernodeKBucket) {
const contact = {
id: id,
floID: floID
};
KB.add(contact)
},
addNewNode: function (address, KB = this.supernodeKBucket) {
let decodedId = address;
try {
decodedId = this.floIdToKbucketId(address);
} catch (e) {
decodedId = address;
}
this.addContact(decodedId, address, KB);
},
isNodePresent: function (flo_id, KB = this.supernodeKBucket) {
return new Promise((resolve, reject) => {
let kArray = KB.toArray();
let kArrayFloIds = kArray.map(k => k.data.id);
if (kArrayFloIds.includes(flo_id)) {
resolve(true);
} else {
reject(false);
}
});
},
determineClosestSupernode: function (flo_addr, n = 1, KB = this.supernodeKBucket) {
return new Promise((resolve, reject) => {
try {
let isFloIdUint8 = flo_addr instanceof Uint8Array;
if (!isFloIdUint8)
flo_addr = this.floIdToKbucketId(flo_addr);
const closestSupernode = KB.closest(flo_addr, n);
resolve(closestSupernode);
} catch (error) {
reject(error);
}
});
}
},
//Sends data to the supernode
sendData: function (data, floID) {
return new Promise((resolve, reject) => {
this.kBucket.determineClosestSupernode(floID).then(result => {
var websocket = new WebSocket("ws://" + floGlobals.supernodes[result].uri + "/ws");
websocket.onopen = (evt) => {
websocket.send(data);
resolve(`Data sent to ${floID}'s supernode`);
websocket.close();
};
websocket.onerror = (evt) => {
reject(evt);
};
}).catch(error => {
reject(error);
});
});
},
//Request data from supernode
requestData: function (request, floID) {
return new Promise((resolve, reject) => {
this.kBucket.determineClosestSupernode(floID).then(result => {
var websocket = new WebSocket("ws://" + floGlobals.supernodes[result].uri + "/ws");
websocket.onopen = (evt) => {
websocket.send(`?${request}`);
};
selfwebsocket.onmessage = (evt) => {
resolve(evt.data);
websocket.close();
};
selfwebsocket.onerror = (evt) => {
reject(evt);
};
}).catch(error => {
reject(error);
});
});
},
//Supernode initate (call this function only when client is authorized as supernode)
/* DO NOT edit this function
To edit the response or callback, edit the reactor eventListener given below
*/
initSupernode: function (pwd, floID) {
return new Promise((resolve, reject) => {
try {
this.supernodeClientWS = new WebSocket("ws://" + floGlobals.supernodes[floID].uri + "/ws");
this.supernodeClientWS.onopen = (evt) => {
supernodeClientWS.send("$" + pwd);
reactor.dispatchEvent('supernode_open', evt);
};
this.supernodeClientWS.onclose = (evt) => {
reactor.dispatchEvent('supernode_close', evt);
};
this.supernodeClientWS.onmessage = (evt) => {
if (evt.data[0] == '$') {
reactor.dispatchEvent('supernode_admin', evt.data.substr(1));
if (evt.data == '$Access Granted!')
resolve("Access Granted! Initiated Supernode client");
else if (evt.data == '$Access Denied!')
reject("Access Denied! Failed to initiate Supernode client");
} else if (evt.data[0] == '?')
reactor.dispatchEvent('supernode_processRequest', evt.data.substr(1));
else
reactor.dispatchEvent('supernode_processData', evt.data);
};
selfwebsocket.onerror = (evt) => {
reactor.dispatchEvent('supernode_error', evt);
reject(evt);
};
} catch (error) {
reject(error)
}
});
}
}
//Event fired when connected to supernode websocket
reactor.registerEvent('supernode_open');
reactor.addEventListener('supernode_open', function (event) {
console.log('Connected to supernode websocket!');
});
//Event fired when disconnected from supernode websocket
reactor.registerEvent('supernode_close');
reactor.addEventListener('supernode_close', function (event) {
console.log('Disconnected from supernode websocket!');
});
//Event fired when connection error with supernode websocket
reactor.registerEvent('supernode_error');
reactor.addEventListener('supernode_error', function (event) {
console.log('Error! Unable to connect supernode websocket!');
});
//Event fired during incoming request
reactor.registerEvent('supernode_processRequest');
reactor.addEventListener('supernode_processRequest', function (request) {
console.log('Request : ' + request);
});
//Event fired during incoming data
reactor.registerEvent('supernode_processData');
reactor.addEventListener('supernode_processData', function (data) {
console.log('Data : ' + data);
});
</script>
<script>
/*Kademlia DHT K-bucket implementation as a binary tree.*/
/**
* Implementation of a Kademlia DHT k-bucket used for storing
* contact (peer node) information.
*
* @extends EventEmitter
*/
function BuildKBucket(options = {}) {
/**
* `options`:
* `distance`: Function
* `function (firstId, secondId) { return distance }` An optional
* `distance` function that gets two `id` Uint8Arrays
* and return distance (as number) between them.
* `arbiter`: Function (Default: vectorClock arbiter)
* `function (incumbent, candidate) { return contact; }` An optional
* `arbiter` function that givent two `contact` objects with the same `id`
* returns the desired object to be used for updating the k-bucket. For
* more details, see [arbiter function](#arbiter-function).
* `localNodeId`: Uint8Array An optional Uint8Array representing the local node id.
* If not provided, a local node id will be created via `randomBytes(20)`.
* `metadata`: Object (Default: {}) Optional satellite data to include
* with the k-bucket. `metadata` property is guaranteed not be altered by,
* it is provided as an explicit container for users of k-bucket to store
* implementation-specific data.
* `numberOfNodesPerKBucket`: Integer (Default: 20) The number of nodes
* that a k-bucket can contain before being full or split.
* `numberOfNodesToPing`: Integer (Default: 3) The number of nodes to
* ping when a bucket that should not be split becomes full. KBucket will
* emit a `ping` event that contains `numberOfNodesToPing` nodes that have
* not been contacted the longest.
*
* @param {Object=} options optional
*/
this.localNodeId = options.localNodeId || window.crypto.getRandomValues(new Uint8Array(20))
this.numberOfNodesPerKBucket = options.numberOfNodesPerKBucket || 20
this.numberOfNodesToPing = options.numberOfNodesToPing || 3
this.distance = options.distance || this.distance
// use an arbiter from options or vectorClock arbiter by default
this.arbiter = options.arbiter || this.arbiter
this.metadata = Object.assign({}, options.metadata)
this.createNode = function () {
return {
contacts: [],
dontSplit: false,
left: null,
right: null
}
}
this.ensureInt8 = function (name, val) {
if (!(val instanceof Uint8Array)) {
throw new TypeError(name + ' is not a Uint8Array')
}
}
/**
* @param {Uint8Array} array1
* @param {Uint8Array} array2
* @return {Boolean}
*/
this.arrayEquals = function (array1, array2) {
if (array1 === array2) {
return true
}
if (array1.length !== array2.length) {
return false
}
for (let i = 0, length = array1.length; i < length; ++i) {
if (array1[i] !== array2[i]) {
return false
}
}
return true
}
this.ensureInt8('option.localNodeId as parameter 1', this.localNodeId)
this.root = this.createNode()
/**
* Default arbiter function for contacts with the same id. Uses
* contact.vectorClock to select which contact to update the k-bucket with.
* Contact with larger vectorClock field will be selected. If vectorClock is
* the same, candidat will be selected.
*
* @param {Object} incumbent Contact currently stored in the k-bucket.
* @param {Object} candidate Contact being added to the k-bucket.
* @return {Object} Contact to updated the k-bucket with.
*/
this.arbiter = function (incumbent, candidate) {
return incumbent.vectorClock > candidate.vectorClock ? incumbent : candidate
}
/**
* Default distance function. Finds the XOR
* distance between firstId and secondId.
*
* @param {Uint8Array} firstId Uint8Array containing first id.
* @param {Uint8Array} secondId Uint8Array containing second id.
* @return {Number} Integer The XOR distance between firstId
* and secondId.
*/
this.distance = function (firstId, secondId) {
let distance = 0
let i = 0
const min = Math.min(firstId.length, secondId.length)
const max = Math.max(firstId.length, secondId.length)
for (; i < min; ++i) {
distance = distance * 256 + (firstId[i] ^ secondId[i])
}
for (; i < max; ++i) distance = distance * 256 + 255
return distance
}
/**
* Adds a contact to the k-bucket.
*
* @param {Object} contact the contact object to add
*/
this.add = function (contact) {
this.ensureInt8('contact.id', (contact || {}).id)
let bitIndex = 0
let node = this.root
while (node.contacts === null) {
// this is not a leaf node but an inner node with 'low' and 'high'
// branches; we will check the appropriate bit of the identifier and
// delegate to the appropriate node for further processing
node = this._determineNode(node, contact.id, bitIndex++)
}
// check if the contact already exists
const index = this._indexOf(node, contact.id)
if (index >= 0) {
this._update(node, index, contact)
return this
}
if (node.contacts.length < this.numberOfNodesPerKBucket) {
node.contacts.push(contact)
return this
}
// the bucket is full
if (node.dontSplit) {
// we are not allowed to split the bucket
// we need to ping the first this.numberOfNodesToPing
// in order to determine if they are alive
// only if one of the pinged nodes does not respond, can the new contact
// be added (this prevents DoS flodding with new invalid contacts)
return this
}
this._split(node, bitIndex)
return this.add(contact)
}
/**
* Get the n closest contacts to the provided node id. "Closest" here means:
* closest according to the XOR metric of the contact node id.
*
* @param {Uint8Array} id Contact node id
* @param {Number=} n Integer (Default: Infinity) The maximum number of
* closest contacts to return
* @return {Array} Array Maximum of n closest contacts to the node id
*/
this.closest = function (id, n = Infinity) {
this.ensureInt8('id', id)
if ((!Number.isInteger(n) && n !== Infinity) || n <= 0) {
throw new TypeError('n is not positive number')
}
let contacts = []
for (let nodes = [this.root], bitIndex = 0; nodes.length > 0 && contacts.length < n;) {
const node = nodes.pop()
if (node.contacts === null) {
const detNode = this._determineNode(node, id, bitIndex++)
nodes.push(node.left === detNode ? node.right : node.left)
nodes.push(detNode)
} else {
contacts = contacts.concat(node.contacts)
}
}
return contacts
.map(a => [this.distance(a.id, id), a])
.sort((a, b) => a[0] - b[0])
.slice(0, n)
.map(a => a[1])
}
/**
* Counts the total number of contacts in the tree.
*
* @return {Number} The number of contacts held in the tree
*/
this.count = function () {
// return this.toArray().length
let count = 0
for (const nodes = [this.root]; nodes.length > 0;) {
const node = nodes.pop()
if (node.contacts === null) nodes.push(node.right, node.left)
else count += node.contacts.length
}
return count
}
/**
* Determines whether the id at the bitIndex is 0 or 1.
* Return left leaf if `id` at `bitIndex` is 0, right leaf otherwise
*
* @param {Object} node internal object that has 2 leafs: left and right
* @param {Uint8Array} id Id to compare localNodeId with.
* @param {Number} bitIndex Integer (Default: 0) The bit index to which bit
* to check in the id Uint8Array.
* @return {Object} left leaf if id at bitIndex is 0, right leaf otherwise.
*/
this._determineNode = function (node, id, bitIndex) {
// *NOTE* remember that id is a Uint8Array and has granularity of
// bytes (8 bits), whereas the bitIndex is the bit index (not byte)
// id's that are too short are put in low bucket (1 byte = 8 bits)
// (bitIndex >> 3) finds how many bytes the bitIndex describes
// bitIndex % 8 checks if we have extra bits beyond byte multiples
// if number of bytes is <= no. of bytes described by bitIndex and there
// are extra bits to consider, this means id has less bits than what
// bitIndex describes, id therefore is too short, and will be put in low
// bucket
const bytesDescribedByBitIndex = bitIndex >> 3
const bitIndexWithinByte = bitIndex % 8
if ((id.length <= bytesDescribedByBitIndex) && (bitIndexWithinByte !== 0)) {
return node.left
}
const byteUnderConsideration = id[bytesDescribedByBitIndex]
// byteUnderConsideration is an integer from 0 to 255 represented by 8 bits
// where 255 is 11111111 and 0 is 00000000
// in order to find out whether the bit at bitIndexWithinByte is set
// we construct (1 << (7 - bitIndexWithinByte)) which will consist
// of all bits being 0, with only one bit set to 1
// for example, if bitIndexWithinByte is 3, we will construct 00010000 by
// (1 << (7 - 3)) -> (1 << 4) -> 16
if (byteUnderConsideration & (1 << (7 - bitIndexWithinByte))) {
return node.right
}
return node.left
}
/**
* Get a contact by its exact ID.
* If this is a leaf, loop through the bucket contents and return the correct
* contact if we have it or null if not. If this is an inner node, determine
* which branch of the tree to traverse and repeat.
*
* @param {Uint8Array} id The ID of the contact to fetch.
* @return {Object|Null} The contact if available, otherwise null
*/
this.get = function (id) {
this.ensureInt8('id', id)
let bitIndex = 0
let node = this.root
while (node.contacts === null) {
node = this._determineNode(node, id, bitIndex++)
}
// index of uses contact id for matching
const index = this._indexOf(node, id)
return index >= 0 ? node.contacts[index] : null
}
/**
* Returns the index of the contact with provided
* id if it exists, returns -1 otherwise.
*
* @param {Object} node internal object that has 2 leafs: left and right
* @param {Uint8Array} id Contact node id.
* @return {Number} Integer Index of contact with provided id if it
* exists, -1 otherwise.
*/
this._indexOf = function (node, id) {
for (let i = 0; i < node.contacts.length; ++i) {
if (this.arrayEquals(node.contacts[i].id, id)) return i
}
return -1
}
/**
* Removes contact with the provided id.
*
* @param {Uint8Array} id The ID of the contact to remove.
* @return {Object} The k-bucket itself.
*/
this.remove = function (id) {
this.ensureInt8('the id as parameter 1', id)
let bitIndex = 0
let node = this.root
while (node.contacts === null) {
node = this._determineNode(node, id, bitIndex++)
}
const index = this._indexOf(node, id)
if (index >= 0) {
const contact = node.contacts.splice(index, 1)[0]
}
return this
}
/**
* Splits the node, redistributes contacts to the new nodes, and marks the
* node that was split as an inner node of the binary tree of nodes by
* setting this.root.contacts = null
*
* @param {Object} node node for splitting
* @param {Number} bitIndex the bitIndex to which byte to check in the
* Uint8Array for navigating the binary tree
*/
this._split = function (node, bitIndex) {
node.left = this.createNode()
node.right = this.createNode()
// redistribute existing contacts amongst the two newly created nodes
for (const contact of node.contacts) {
this._determineNode(node, contact.id, bitIndex).contacts.push(contact)
}
node.contacts = null // mark as inner tree node
// don't split the "far away" node
// we check where the local node would end up and mark the other one as
// "dontSplit" (i.e. "far away")
const detNode = this._determineNode(node, this.localNodeId, bitIndex)
const otherNode = node.left === detNode ? node.right : node.left
otherNode.dontSplit = true
}
/**
* Returns all the contacts contained in the tree as an array.
* If this is a leaf, return a copy of the bucket. `slice` is used so that we
* don't accidentally leak an internal reference out that might be
* accidentally misused. If this is not a leaf, return the union of the low
* and high branches (themselves also as arrays).
*
* @return {Array} All of the contacts in the tree, as an array
*/
this.toArray = function () {
let result = []
for (const nodes = [this.root]; nodes.length > 0;) {
const node = nodes.pop()
if (node.contacts === null) nodes.push(node.right, node.left)
else result = result.concat(node.contacts)
}
return result
}
/**
* Updates the contact selected by the arbiter.
* If the selection is our old contact and the candidate is some new contact
* then the new contact is abandoned (not added).
* If the selection is our old contact and the candidate is our old contact
* then we are refreshing the contact and it is marked as most recently
* contacted (by being moved to the right/end of the bucket array).
* If the selection is our new contact, the old contact is removed and the new
* contact is marked as most recently contacted.
*
* @param {Object} node internal object that has 2 leafs: left and right
* @param {Number} index the index in the bucket where contact exists
* (index has already been computed in a previous
* calculation)
* @param {Object} contact The contact object to update.
*/
this._update = function (node, index, contact) {
// sanity check
if (!this.arrayEquals(node.contacts[index].id, contact.id)) {
throw new Error('wrong index for _update')
}
const incumbent = node.contacts[index]
const selection = this.arbiter(incumbent, contact)
// if the selection is our old contact and the candidate is some new
// contact, then there is nothing to do
if (selection === incumbent && incumbent !== contact) return
node.contacts.splice(index, 1) // remove old contact
node.contacts.push(selection) // add more recent contact version
}
}
</script>
</html>