1
0
forked from circlecloud/tera

style: comment unused code and format

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
MiaoWoo 2019-07-10 17:53:52 +08:00
parent 812813da8d
commit f0d4952b27
32 changed files with 3958 additions and 5739 deletions

View File

@ -10,20 +10,16 @@
const ipcRenderer = require('electron').ipcRenderer; const ipcRenderer = require('electron').ipcRenderer;
function GetDataElectron(Method,ObjPost,Func) function GetDataElectron(Method, ObjPost, Func) {
{ if (Func === undefined) {
if(Func === undefined)
{
Func = ObjPost; Func = ObjPost;
ObjPost = null; ObjPost = null;
} }
var reply; var reply;
try try {
{
reply = ipcRenderer.sendSync('GetData', { path: Method, obj: ObjPost }); reply = ipcRenderer.sendSync('GetData', { path: Method, obj: ObjPost });
} }
catch(e) catch (e) {
{
reply = undefined; reply = undefined;
} }
if (Func) if (Func)

File diff suppressed because it is too large Load Diff

View File

@ -11,8 +11,7 @@
var MAX_SUPER_VALUE_POW = (1 << 30) * 2; var MAX_SUPER_VALUE_POW = (1 << 30) * 2;
window.TYPE_TRANSACTION_CREATE = 100; window.TYPE_TRANSACTION_CREATE = 100;
function GetHashWithValues(hash0,value1,value2,bNotCopy) function GetHashWithValues(hash0, value1, value2, bNotCopy) {
{
var hash; var hash;
if (bNotCopy) if (bNotCopy)
hash = hash0; hash = hash0;
@ -30,20 +29,15 @@ function GetHashWithValues(hash0,value1,value2,bNotCopy)
return arrhash; return arrhash;
}; };
function GetPowPower(arrhash) function GetPowPower(arrhash) {
{
var SumBit = 0; var SumBit = 0;
for(var i = 0; i < arrhash.length; i++) for (var i = 0; i < arrhash.length; i++) {
{
var byte = arrhash[i]; var byte = arrhash[i];
for(var b = 7; b >= 0; b--) for (var b = 7; b >= 0; b--) {
{ if ((byte >> b) & 1) {
if((byte >> b) & 1)
{
return SumBit; return SumBit;
} }
else else {
{
SumBit++; SumBit++;
} }
} }
@ -51,16 +45,14 @@ function GetPowPower(arrhash)
return SumBit; return SumBit;
}; };
function GetPowValue(arrhash) function GetPowValue(arrhash) {
{
var value = (arrhash[0] << 23) * 2 + (arrhash[1] << 16) + (arrhash[2] << 8) + arrhash[3]; var value = (arrhash[0] << 23) * 2 + (arrhash[1] << 16) + (arrhash[2] << 8) + arrhash[3];
value = value * 256 + arrhash[4]; value = value * 256 + arrhash[4];
value = value * 256 + arrhash[5]; value = value * 256 + arrhash[5];
return value; return value;
}; };
function CreateNoncePOWExtern(arr0,BlockNum,count,startnone) function CreateNoncePOWExtern(arr0, BlockNum, count, startnone) {
{
var arr = []; var arr = [];
for (var i = 0; i < arr0.length; i++) for (var i = 0; i < arr0.length; i++)
arr[i] = arr0[i]; arr[i] = arr0[i];
@ -68,12 +60,10 @@ function CreateNoncePOWExtern(arr0,BlockNum,count,startnone)
startnone = 0; startnone = 0;
var maxnonce = 0; var maxnonce = 0;
var supervalue = MAX_SUPER_VALUE_POW; var supervalue = MAX_SUPER_VALUE_POW;
for(var nonce = startnone; nonce <= startnone + count; nonce++) for (var nonce = startnone; nonce <= startnone + count; nonce++) {
{
var arrhash = GetHashWithValues(arr, nonce, BlockNum, true); var arrhash = GetHashWithValues(arr, nonce, BlockNum, true);
var value = GetPowValue(arrhash); var value = GetPowValue(arrhash);
if(value < supervalue) if (value < supervalue) {
{
maxnonce = nonce; maxnonce = nonce;
supervalue = value; supervalue = value;
} }
@ -82,8 +72,7 @@ function CreateNoncePOWExtern(arr0,BlockNum,count,startnone)
}; };
window.TR_TICKET_HASH_LENGTH = 10; window.TR_TICKET_HASH_LENGTH = 10;
function CreateHashBody(body,Num,Nonce) function CreateHashBody(body, Num, Nonce) {
{
var length = body.length - 12; var length = body.length - 12;
body[length + 0] = Num & 0xFF; body[length + 0] = Num & 0xFF;
body[length + 1] = (Num >>> 8) & 0xFF; body[length + 1] = (Num >>> 8) & 0xFF;
@ -111,8 +100,7 @@ window.MIN_POWER_POW_TR = 0;
window.CONSENSUS_PERIOD_TIME = 1000; window.CONSENSUS_PERIOD_TIME = 1000;
window.FIRST_TIME_BLOCK = 1530446400000; window.FIRST_TIME_BLOCK = 1530446400000;
window.NEW_SIGN_TIME = 25500000; window.NEW_SIGN_TIME = 25500000;
window.SetBlockChainConstant = function (Data) window.SetBlockChainConstant = function(Data) {
{
var DeltaServerClient = new Date() - Data.CurTime; var DeltaServerClient = new Date() - Data.CurTime;
if (!Data.DELTA_CURRENT_TIME) if (!Data.DELTA_CURRENT_TIME)
Data.DELTA_CURRENT_TIME = 0; Data.DELTA_CURRENT_TIME = 0;
@ -121,8 +109,7 @@ window.SetBlockChainConstant = function (Data)
window.FIRST_TIME_BLOCK = Data.FIRST_TIME_BLOCK; window.FIRST_TIME_BLOCK = Data.FIRST_TIME_BLOCK;
window.NEW_SIGN_TIME = Data.NEW_SIGN_TIME; window.NEW_SIGN_TIME = Data.NEW_SIGN_TIME;
window.CONSENSUS_PERIOD_TIME = Data.CONSENSUS_PERIOD_TIME; window.CONSENSUS_PERIOD_TIME = Data.CONSENSUS_PERIOD_TIME;
window.GetCurrentBlockNumByTime = function () window.GetCurrentBlockNumByTime = function() {
{
var CurrentTime = Date.now() + DELTA_CURRENT_TIME2; var CurrentTime = Date.now() + DELTA_CURRENT_TIME2;
var CurTimeNum = CurrentTime - FIRST_TIME_BLOCK; var CurTimeNum = CurrentTime - FIRST_TIME_BLOCK;
var StartBlockNum = Math.floor((CurTimeNum + CONSENSUS_PERIOD_TIME) / CONSENSUS_PERIOD_TIME); var StartBlockNum = Math.floor((CurTimeNum + CONSENSUS_PERIOD_TIME) / CONSENSUS_PERIOD_TIME);
@ -130,16 +117,13 @@ window.SetBlockChainConstant = function (Data)
}; };
window.NWMODE = Data.NWMODE; window.NWMODE = Data.NWMODE;
}; };
window.GetCurrentBlockNumByTime = function () window.GetCurrentBlockNumByTime = function() {
{
return 0; return 0;
}; };
function GetBlockNumTr(arr) function GetBlockNumTr(arr) {
{
var BlockNum = window.DELTA_FOR_TIME_TX + GetCurrentBlockNumByTime(); var BlockNum = window.DELTA_FOR_TIME_TX + GetCurrentBlockNumByTime();
if(arr[0] === TYPE_TRANSACTION_CREATE) if (arr[0] === TYPE_TRANSACTION_CREATE) {
{
var BlockNum2 = Math.floor(BlockNum / 10) * 10; var BlockNum2 = Math.floor(BlockNum / 10) * 10;
if (BlockNum2 < BlockNum) if (BlockNum2 < BlockNum)
BlockNum2 = BlockNum2 + 10; BlockNum2 = BlockNum2 + 10;
@ -151,26 +135,20 @@ var LastCreatePOWTrType = 0;
var LastCreatePOWBlockNum = 0; var LastCreatePOWBlockNum = 0;
var LastCreatePOWHash = [255, 255, 255, 255]; var LastCreatePOWHash = [255, 255, 255, 255];
function CreateHashBodyPOWInnerMinPower(arr,MinPow,startnonce) function CreateHashBodyPOWInnerMinPower(arr, MinPow, startnonce) {
{
var TrType = arr[0]; var TrType = arr[0];
var BlockNum = GetBlockNumTr(arr); var BlockNum = GetBlockNumTr(arr);
if(MinPow === undefined) if (MinPow === undefined) {
{
MinPow = MIN_POWER_POW_TR + Math.log2(arr.length / 128); MinPow = MIN_POWER_POW_TR + Math.log2(arr.length / 128);
} }
var nonce = startnonce; var nonce = startnonce;
while(1) while (1) {
{
var arrhash = CreateHashBody(arr, BlockNum, nonce); var arrhash = CreateHashBody(arr, BlockNum, nonce);
var power = GetPowPower(arrhash); var power = GetPowPower(arrhash);
if(power >= MinPow) if (power >= MinPow) {
{ if (LastCreatePOWBlockNum === BlockNum && LastCreatePOWTrType === TrType && CompareArr(LastCreatePOWHash, arrhash) > 0) {
if(LastCreatePOWBlockNum === BlockNum && LastCreatePOWTrType === TrType && CompareArr(LastCreatePOWHash, arrhash) > 0)
{
} }
else else {
{
LastCreatePOWBlockNum = BlockNum; LastCreatePOWBlockNum = BlockNum;
LastCreatePOWTrType = TrType; LastCreatePOWTrType = TrType;
LastCreatePOWHash = arrhash; LastCreatePOWHash = arrhash;
@ -178,20 +156,17 @@ function CreateHashBodyPOWInnerMinPower(arr,MinPow,startnonce)
} }
} }
nonce++; nonce++;
if(nonce % 2000 === 0) if (nonce % 2000 === 0) {
{
BlockNum = GetBlockNumTr(arr); BlockNum = GetBlockNumTr(arr);
} }
} }
}; };
function CalcHashFromArray(ArrHashes,bOriginalSeq) function CalcHashFromArray(ArrHashes, bOriginalSeq) {
{
if (bOriginalSeq === undefined) if (bOriginalSeq === undefined)
ArrHashes.sort(CompareArr); ArrHashes.sort(CompareArr);
var Buf = []; var Buf = [];
for(var i = 0; i < ArrHashes.length; i++) for (var i = 0; i < ArrHashes.length; i++) {
{
var Value = ArrHashes[i]; var Value = ArrHashes[i];
for (var n = 0; n < Value.length; n++) for (var n = 0; n < Value.length; n++)
Buf.push(Value[n]); Buf.push(Value[n]);
@ -205,8 +180,7 @@ function CalcHashFromArray(ArrHashes,bOriginalSeq)
return Hash; return Hash;
}; };
function GetArrFromValue(Num) function GetArrFromValue(Num) {
{
var arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; var arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
arr[0] = Num & 0xFF; arr[0] = Num & 0xFF;
arr[1] = (Num >>> 8) & 0xFF; arr[1] = (Num >>> 8) & 0xFF;
@ -218,52 +192,42 @@ function GetArrFromValue(Num)
return arr; return arr;
}; };
function LoadLib(Path) function LoadLib(Path) {
{
var item = document.createElement('script'); var item = document.createElement('script');
item.type = "text/javascript"; item.type = "text/javascript";
item.src = Path; item.src = Path;
document.getElementsByTagName('head')[0].appendChild(item); document.getElementsByTagName('head')[0].appendChild(item);
}; };
function IsMS() function IsMS() {
{
var ua = window.navigator.userAgent; var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE "); var msie = ua.indexOf("MSIE ");
if(msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
{
return 1; return 1;
} }
else else {
{
return 0; return 0;
} }
}; };
function LoadSignLib() function LoadSignLib() {
{
if (window.SignLib) if (window.SignLib)
return; return;
LoadLib("./JS/sign-lib-min.js"); LoadLib("./JS/sign-lib-min.js");
}; };
function ComputeSecretWithCheck(PubKey,StrPrivKey,F) function ComputeSecretWithCheck(PubKey, StrPrivKey, F) {
{ if (!window.SignLib) {
if(!window.SignLib)
{
SetError("Error - SignLib not installed"); SetError("Error - SignLib not installed");
return; return;
} }
if(!IsHexStr(StrPrivKey) || StrPrivKey.length !== 64) if (!IsHexStr(StrPrivKey) || StrPrivKey.length !== 64) {
{
SetError("Error set PrivKey"); SetError("Error set PrivKey");
return; return;
} }
var PrivKey = Buffer.from(GetArrFromHex(StrPrivKey)); var PrivKey = Buffer.from(GetArrFromHex(StrPrivKey));
if(typeof PubKey === "string") if (typeof PubKey === "string") {
{ if (!IsHexStr(PubKey) || PubKey.length !== 66) {
if(!IsHexStr(PubKey) || PubKey.length !== 66)
{
SetError("Error PubKey"); SetError("Error PubKey");
return; return;
} }
@ -273,16 +237,12 @@ function ComputeSecretWithCheck(PubKey,StrPrivKey,F)
F(sha3(Result)); F(sha3(Result));
}; };
function ComputeSecret(Account,PubKey,F) function ComputeSecret(Account, PubKey, F) {
{ if (GetPrivKey()) {
if(GetPrivKey())
{
ComputeSecretWithCheck(PubKey, GetPrivKey(), F); ComputeSecretWithCheck(PubKey, GetPrivKey(), F);
} }
else else {
{ GetData("GetWalletInfo", { Account: Account }, function(Data) {
GetData("GetWalletInfo", {Account:Account}, function (Data)
{
if (!Data || !Data.result) if (!Data || !Data.result)
return; return;
ComputeSecretWithCheck(PubKey, Data.PrivateKey, F); ComputeSecretWithCheck(PubKey, Data.PrivateKey, F);
@ -290,15 +250,13 @@ function ComputeSecret(Account,PubKey,F)
} }
}; };
function Encrypt(ArrSecret,StartEncrypt,StrName,StrValue) function Encrypt(ArrSecret, StartEncrypt, StrName, StrValue) {
{
var arrRnd = sha3arr2(ArrSecret, sha3(StrName + StartEncrypt)); var arrRnd = sha3arr2(ArrSecret, sha3(StrName + StartEncrypt));
var Arr = toUTF8Array(StrValue); var Arr = toUTF8Array(StrValue);
return DoSecret(Arr, arrRnd); return DoSecret(Arr, arrRnd);
}; };
function Decrypt(ArrSecret,StartEncrypt,StrName,Arr) function Decrypt(ArrSecret, StartEncrypt, StrName, Arr) {
{
if (!ArrSecret) if (!ArrSecret)
return "".padEnd(Arr.length / 2, "."); return "".padEnd(Arr.length / 2, ".");
if (typeof Arr === "string") if (typeof Arr === "string")
@ -309,18 +267,15 @@ function Decrypt(ArrSecret,StartEncrypt,StrName,Arr)
return Str; return Str;
}; };
function DoSecret(Arr,arrRnd) function DoSecret(Arr, arrRnd) {
{
var Arr2 = []; var Arr2 = [];
var CryptID = 0; var CryptID = 0;
var Pos = 0; var Pos = 0;
while(Pos < Arr.length) while (Pos < Arr.length) {
{
CryptID++; CryptID++;
WriteUintToArrOnPos(arrRnd, CryptID, 0); WriteUintToArrOnPos(arrRnd, CryptID, 0);
var CurBuf = sha3(arrRnd); var CurBuf = sha3(arrRnd);
for(var i = 0; i < 32 && Pos < Arr.length; i++, Pos++) for (var i = 0; i < 32 && Pos < Arr.length; i++ , Pos++) {
{
Arr2[Pos] = Arr[Pos] ^ CurBuf[i]; Arr2[Pos] = Arr[Pos] ^ CurBuf[i];
} }
} }
@ -328,26 +283,22 @@ function DoSecret(Arr,arrRnd)
}; };
var glEncryptInit = 0; var glEncryptInit = 0;
function EncryptInit() function EncryptInit() {
{
glEncryptInit++; glEncryptInit++;
var Time = Date.now() - new Date(2019, 0, 1); var Time = Date.now() - new Date(2019, 0, 1);
return Math.floor(Time * 100 + Math.random() * 100) * 100 + glEncryptInit; return Math.floor(Time * 100 + Math.random() * 100) * 100 + glEncryptInit;
}; };
function EncryptID(ArrSecret,StartEncrypt,id) function EncryptID(ArrSecret, StartEncrypt, id) {
{
var Value = $(id).value; var Value = $(id).value;
Value = Value.padEnd(Value.length + random(5), " "); Value = Value.padEnd(Value.length + random(5), " ");
return GetHexFromArr(Encrypt(ArrSecret, StartEncrypt, id, Value)); return GetHexFromArr(Encrypt(ArrSecret, StartEncrypt, id, Value));
}; };
function EncryptFields(ArrSecret,Params,ArrName) function EncryptFields(ArrSecret, Params, ArrName) {
{
if (!Params.Crypto) if (!Params.Crypto)
Params.Crypto = EncryptInit(); Params.Crypto = EncryptInit();
for(var i = 0; i < ArrName.length; i++) for (var i = 0; i < ArrName.length; i++) {
{
var Name = ArrName[i]; var Name = ArrName[i];
var Value = Params[Name]; var Value = Params[Name];
Value = Value.padEnd(Value.length + random(5), " "); Value = Value.padEnd(Value.length + random(5), " ");
@ -355,17 +306,13 @@ function EncryptFields(ArrSecret,Params,ArrName)
} }
}; };
function DecryptFields(ArrSecret,Params,ArrName) function DecryptFields(ArrSecret, Params, ArrName) {
{ for (var i = 0; i < ArrName.length; i++) {
for(var i = 0; i < ArrName.length; i++)
{
var Name = ArrName[i]; var Name = ArrName[i];
if(Params[Name]) if (Params[Name]) {
{
Params[Name] = Decrypt(ArrSecret, Params.Crypto, Name, GetArrFromHex(Params[Name])); Params[Name] = Decrypt(ArrSecret, Params.Crypto, Name, GetArrFromHex(Params[Name]));
} }
else else {
{
Params[Name] = ""; Params[Name] = "";
} }
} }

View File

@ -9,52 +9,43 @@
*/ */
function SendPay(Data) function SendPay(Data) {
{
Data.cmd = "pay"; Data.cmd = "pay";
SendData(Data); SendData(Data);
}; };
function SetStorage(Key,Value) function SetStorage(Key, Value) {
{
var Data = { cmd: "setstorage", Key: Key, Value: Value }; var Data = { cmd: "setstorage", Key: Key, Value: Value };
SendData(Data); SendData(Data);
}; };
function GetStorage(Key,F) function GetStorage(Key, F) {
{
var Data = { cmd: "getstorage", Key: Key }; var Data = { cmd: "getstorage", Key: Key };
SendData(Data, F); SendData(Data, F);
}; };
function SetCommon(Key,Value) function SetCommon(Key, Value) {
{
var Data = { cmd: "setcommon", Key: Key, Value: Value }; var Data = { cmd: "setcommon", Key: Key, Value: Value };
SendData(Data); SendData(Data);
}; };
function GetCommon(Key,F) function GetCommon(Key, F) {
{
var Data = { cmd: "getcommon", Key: Key }; var Data = { cmd: "getcommon", Key: Key };
SendData(Data, F); SendData(Data, F);
}; };
function GetInfo(F,bUseCache) function GetInfo(F, bUseCache) {
{
var Data = { cmd: "DappInfo", AllAccounts: ALL_ACCOUNTS, AllData: !bUseCache }; var Data = { cmd: "DappInfo", AllAccounts: ALL_ACCOUNTS, AllData: !bUseCache };
SendData(Data, F); SendData(Data, F);
}; };
function Call(Account,MethodName,Params,F) function Call(Account, MethodName, Params, F) {
{
var Data = { cmd: "DappCall", MethodName: MethodName, Params: Params, Account: Account }; var Data = { cmd: "DappCall", MethodName: MethodName, Params: Params, Account: Account };
SendData(Data, F); SendData(Data, F);
}; };
function SendCall(Account,MethodName,Params,FromNum) function SendCall(Account, MethodName, Params, FromNum) {
{ if (!INFO.WalletCanSign) {
if(!INFO.WalletCanSign)
{
SetError("Pls, open wallet"); SetError("Pls, open wallet");
return 0; return 0;
} }
@ -63,125 +54,100 @@ function SendCall(Account,MethodName,Params,FromNum)
return 1; return 1;
}; };
function GetWalletAccounts(F) function GetWalletAccounts(F) {
{
var Data = { cmd: "DappWalletList" }; var Data = { cmd: "DappWalletList" };
SendData(Data, F); SendData(Data, F);
}; };
function GetAccountList(Params,F) function GetAccountList(Params, F) {
{
var Data = { cmd: "DappAccountList", Params: Params }; var Data = { cmd: "DappAccountList", Params: Params };
SendData(Data, F); SendData(Data, F);
}; };
function GetSmartList(Params,F) function GetSmartList(Params, F) {
{
var Data = { cmd: "DappSmartList", Params: Params }; var Data = { cmd: "DappSmartList", Params: Params };
SendData(Data, F); SendData(Data, F);
}; };
function GetBlockList(Params,F) function GetBlockList(Params, F) {
{
var Data = { cmd: "DappBlockList", Params: Params }; var Data = { cmd: "DappBlockList", Params: Params };
SendData(Data, F); SendData(Data, F);
}; };
function GetTransactionList(Params,F) function GetTransactionList(Params, F) {
{
var Data = { cmd: "DappTransactionList", Params: Params }; var Data = { cmd: "DappTransactionList", Params: Params };
SendData(Data, F); SendData(Data, F);
}; };
function DappSmartHTMLFile(Smart,F) function DappSmartHTMLFile(Smart, F) {
{
var Data = { cmd: "DappSmartHTMLFile", Params: { Smart: Smart } }; var Data = { cmd: "DappSmartHTMLFile", Params: { Smart: Smart } };
SendData(Data, F); SendData(Data, F);
}; };
function DappBlockFile(BlockNum,TrNum,F) function DappBlockFile(BlockNum, TrNum, F) {
{
var Data = { cmd: "DappBlockFile", Params: { BlockNum: BlockNum, TrNum: TrNum } }; var Data = { cmd: "DappBlockFile", Params: { BlockNum: BlockNum, TrNum: TrNum } };
SendData(Data, F); SendData(Data, F);
}; };
function SetStatus(Str) function SetStatus(Str) {
{
SendData({ cmd: "SetStatus", Message: Str }); SendData({ cmd: "SetStatus", Message: Str });
}; };
function SetError(Str) function SetError(Str) {
{
SendData({ cmd: "SetError", Message: Str }); SendData({ cmd: "SetError", Message: Str });
}; };
function SetLocationPath(Str) function SetLocationPath(Str) {
{
SendData({ cmd: "SetLocationHash", Message: Str }); SendData({ cmd: "SetLocationHash", Message: Str });
}; };
function CreateNewAccount(Currency) function CreateNewAccount(Currency) {
{
SendData({ cmd: "CreateNewAccount", Currency: Currency }); SendData({ cmd: "CreateNewAccount", Currency: Currency });
}; };
function OpenLink(Str) function OpenLink(Str) {
{
SendData({ cmd: "OpenLink", Message: Str }); SendData({ cmd: "OpenLink", Message: Str });
}; };
function SetMobileMode() function SetMobileMode() {
{
SendData({ cmd: "SetMobileMode" }); SendData({ cmd: "SetMobileMode" });
}; };
function ComputeSecret(PubKey,F,Account) function ComputeSecret(PubKey, F, Account) {
{ if (!INFO.WalletCanSign) {
if(!INFO.WalletCanSign)
{
SetError("Pls, open wallet"); SetError("Pls, open wallet");
return 0; return 0;
} }
if (!Account && USER_ACCOUNT.length) if (!Account && USER_ACCOUNT.length)
Account = USER_ACCOUNT[0].Num; Account = USER_ACCOUNT[0].Num;
if(typeof PubKey === "number") if (typeof PubKey === "number") {
{
var AccNum = PubKey; var AccNum = PubKey;
GetAccountList({StartNum:AccNum, CountNum:1}, function (Err,Arr) GetAccountList({ StartNum: AccNum, CountNum: 1 }, function(Err, Arr) {
{ if (Err) {
if(Err)
{
SetError(Err); SetError(Err);
} }
else else {
{
SendData({ cmd: "ComputeSecret", Account: Account, PubKey: Arr[0].PubKey.data }, F); SendData({ cmd: "ComputeSecret", Account: Account, PubKey: Arr[0].PubKey.data }, F);
} }
}); });
} }
else else {
{
SendData({ cmd: "ComputeSecret", Account: Account, PubKey: PubKey }, F); SendData({ cmd: "ComputeSecret", Account: Account, PubKey: PubKey }, F);
} }
}; };
function CheckInstall() function CheckInstall() {
{
SendData({ cmd: "CheckInstall" }); SendData({ cmd: "CheckInstall" });
}; };
function SendTransaction(Body,TR,SumPow,F) function SendTransaction(Body, TR, SumPow, F) {
{
SetError("Cannt SEND TR: " + JSON.stringify(TR)); SetError("Cannt SEND TR: " + JSON.stringify(TR));
}; };
function CurrencyName(Num) function CurrencyName(Num) {
{
var Name = MapCurrency[Num]; var Name = MapCurrency[Num];
if(!Name) if (!Name) {
{ GetSmartList({ StartNum: Num, CountNum: 1, TokenGenerate: 1 }, function(Err, Arr) {
GetSmartList({StartNum:Num, CountNum:1, TokenGenerate:1}, function (Err,Arr)
{
if (Err || Arr.length === 0) if (Err || Arr.length === 0)
return; return;
var Smart = Arr[0]; var Smart = Arr[0];
@ -194,19 +160,15 @@ function CurrencyName(Num)
}; };
var SendCountUpdate = 0; var SendCountUpdate = 0;
function FindAllCurrency() function FindAllCurrency() {
{
SendCountUpdate++; SendCountUpdate++;
GetSmartList({StartNum:8, CountNum:100, TokenGenerate:1}, function (Err,Arr) GetSmartList({ StartNum: 8, CountNum: 100, TokenGenerate: 1 }, function(Err, Arr) {
{
SendCountUpdate--; SendCountUpdate--;
if (Err) if (Err)
return; return;
for(var i = 0; i < Arr.length; i++) for (var i = 0; i < Arr.length; i++) {
{
var Smart = Arr[i]; var Smart = Arr[i];
if(!MapCurrency[Smart.Num]) if (!MapCurrency[Smart.Num]) {
{
var Name = GetTokenName(Smart.Num, Smart.ShortName); var Name = GetTokenName(Smart.Num, Smart.ShortName);
MapCurrency[Smart.Num] = Name; MapCurrency[Smart.Num] = Name;
} }
@ -214,10 +176,8 @@ function FindAllCurrency()
}); });
}; };
function GetFilePath(Path) function GetFilePath(Path) {
{ if (window.PROTOCOL_SERVER_PATH && Path.indexOf("file/")) {
if(window.PROTOCOL_SERVER_PATH && Path.indexOf("file/"))
{
if (Path.substr(0, 1) !== "/") if (Path.substr(0, 1) !== "/")
Path = "/" + Path; Path = "/" + Path;
Path = window.PROTOCOL_SERVER_PATH + Path; Path = window.PROTOCOL_SERVER_PATH + Path;
@ -225,37 +185,29 @@ function GetFilePath(Path)
return Path; return Path;
}; };
function GetParamsFromPath(Name) function GetParamsFromPath(Name) {
{
if (!OPEN_PATH) if (!OPEN_PATH)
return undefined; return undefined;
var arr = OPEN_PATH.split("&"); var arr = OPEN_PATH.split("&");
for(var i = 0; i < arr.length; i++) for (var i = 0; i < arr.length; i++) {
{ if (arr[i].indexOf(Name + "=") === 0) {
if(arr[i].indexOf(Name + "=") === 0)
{
return arr[i].split("=")[1]; return arr[i].split("=")[1];
} }
} }
}; };
function GetState(AccNum,F,FErr) function GetState(AccNum, F, FErr) {
{
SendCountUpdate++; SendCountUpdate++;
GetAccountList({StartNum:AccNum, CountNum:1}, function (Err,Arr) GetAccountList({ StartNum: AccNum, CountNum: 1 }, function(Err, Arr) {
{
SendCountUpdate--; SendCountUpdate--;
if(!Err && Arr.length) if (!Err && Arr.length) {
{
var Item = Arr[0].SmartState; var Item = Arr[0].SmartState;
if(Item) if (Item) {
{
F(Item); F(Item);
return; return;
} }
} }
if(FErr) if (FErr) {
{
FErr(); FErr();
return; return;
} }
@ -264,12 +216,10 @@ function GetState(AccNum,F,FErr)
var glMapF = {}; var glMapF = {};
var glKeyF = 0; var glKeyF = 0;
function SendData(Data,F) function SendData(Data, F) {
{
if (!window.parent) if (!window.parent)
return; return;
if(F) if (F) {
{
glKeyF++; glKeyF++;
Data.CallID = glKeyF; Data.CallID = glKeyF;
glMapF[glKeyF] = F; glMapF[glKeyF] = F;
@ -277,22 +227,18 @@ function SendData(Data,F)
window.parent.postMessage(Data, "*"); window.parent.postMessage(Data, "*");
}; };
function OnMessage(event) function OnMessage(event) {
{
var Data = event.data; var Data = event.data;
if (!Data || typeof Data !== "object") if (!Data || typeof Data !== "object")
return; return;
var CallID = Data.CallID; var CallID = Data.CallID;
var cmd = Data.cmd; var cmd = Data.cmd;
if(CallID) if (CallID) {
{
var F = glMapF[CallID]; var F = glMapF[CallID];
if(F) if (F) {
{
delete Data.CallID; delete Data.CallID;
delete Data.cmd; delete Data.cmd;
switch(cmd) switch (cmd) {
{
case "getstorage": case "getstorage":
case "getcommon": case "getcommon":
F(Data.Key, Data.Value); F(Data.Key, Data.Value);
@ -323,17 +269,14 @@ function OnMessage(event)
delete glMapF[CallID]; delete glMapF[CallID];
} }
} }
else else {
{ switch (cmd) {
switch(cmd)
{
case "History": case "History":
var eventEvent = new CustomEvent("History", { detail: Data }); var eventEvent = new CustomEvent("History", { detail: Data });
window.dispatchEvent(eventEvent); window.dispatchEvent(eventEvent);
break; break;
case "OnEvent": case "OnEvent":
if(window.OnEvent) if (window.OnEvent) {
{
window.OnEvent(Data); window.OnEvent(Data);
} }
var eventEvent = new CustomEvent("Event", { detail: Data }); var eventEvent = new CustomEvent("Event", { detail: Data });
@ -342,29 +285,23 @@ function OnMessage(event)
} }
}; };
function OpenRefFile(Str) function OpenRefFile(Str) {
{
var Param = ParseFileName(Str); var Param = ParseFileName(Str);
if (Param.BlockNum) if (Param.BlockNum)
DappBlockFile(Param.BlockNum, Param.TrNum, function (Err,Body) DappBlockFile(Param.BlockNum, Param.TrNum, function(Err, Body) {
{
document.write(Body); document.write(Body);
}); });
else else {
{
OpenLink(Str); OpenLink(Str);
} }
}; };
function SaveToStorageByArr(Arr) function SaveToStorageByArr(Arr) {
{
SetStorage("VerSave", "1"); SetStorage("VerSave", "1");
for(var i = 0; i < Arr.length; i++) for (var i = 0; i < Arr.length; i++) {
{
var name = Arr[i]; var name = Arr[i];
var Item = $(name); var Item = $(name);
if(Item) if (Item) {
{
if (Item.type === "checkbox") if (Item.type === "checkbox")
SetStorage(name, 0 + Item.checked); SetStorage(name, 0 + Item.checked);
else else
@ -373,14 +310,10 @@ function SaveToStorageByArr(Arr)
} }
}; };
function LoadFromStorageByArr(Arr,F,bAll) function LoadFromStorageByArr(Arr, F, bAll) {
{ GetStorage("VerSave", function(Key, Value) {
GetStorage("VerSave", function (Key,Value) if (Value === "1") {
{ for (var i = 0; i < Arr.length; i++) {
if(Value === "1")
{
for(var i = 0; i < Arr.length; i++)
{
if (i === Arr.length - 1) if (i === Arr.length - 1)
LoadFromStorageById(Arr[i], F); LoadFromStorageById(Arr[i], F);
else else
@ -392,13 +325,10 @@ function LoadFromStorageByArr(Arr,F,bAll)
}); });
}; };
function LoadFromStorageById(Name,F) function LoadFromStorageById(Name, F) {
{ GetStorage(Name, function(Key, Value) {
GetStorage(Name, function (Key,Value)
{
var Item = document.getElementById(Name); var Item = document.getElementById(Name);
if(Item) if (Item) {
{
if (Item.type === "checkbox") if (Item.type === "checkbox")
Item.checked = parseInt(Value); Item.checked = parseInt(Value);
else else
@ -410,29 +340,22 @@ function LoadFromStorageById(Name,F)
}; };
var SendCountDappParams = 0; var SendCountDappParams = 0;
function GetDappParams(BNum,TrNum,F,bAll) function GetDappParams(BNum, TrNum, F, bAll) {
{ if (!BNum) {
if(!BNum)
{
if (bAll) if (bAll)
F(); F();
return; return;
} }
SendCountDappParams++; SendCountDappParams++;
DappBlockFile(BNum, TrNum, function (Err,Data) DappBlockFile(BNum, TrNum, function(Err, Data) {
{
SendCountDappParams--; SendCountDappParams--;
if(!Err && Data.Type === 135) if (!Err && Data.Type === 135) {
{ try {
try
{
var Params = JSON.parse(Data.Params); var Params = JSON.parse(Data.Params);
} }
catch(e) catch (e) {
{
} }
if(Params) if (Params) {
{
F(Params, Data.MethodName, Data.FromNum); F(Params, Data.MethodName, Data.FromNum);
return; return;
} }
@ -441,26 +364,20 @@ function GetDappParams(BNum,TrNum,F,bAll)
F(); F();
}); });
}; };
document.addEventListener("DOMContentLoaded", function () document.addEventListener("DOMContentLoaded", function() {
{
var refs = document.getElementsByTagName("A"); var refs = document.getElementsByTagName("A");
for(var i = 0, L = refs.length; i < L; i++) for (var i = 0, L = refs.length; i < L; i++) {
{ if (refs[i].href.indexOf("/file/") >= 0) {
if(refs[i].href.indexOf("/file/") >= 0) refs[i].onclick = function() {
{
refs[i].onclick = function ()
{
OpenRefFile(this.href); OpenRefFile(this.href);
}; };
} }
} }
}); });
if(window.addEventListener) if (window.addEventListener) {
{
window.addEventListener("message", OnMessage); window.addEventListener("message", OnMessage);
} }
else else {
{
window.attachEvent("onmessage", OnMessage); window.attachEvent("onmessage", OnMessage);
} }
var SMART = {}, BASE_ACCOUNT = {}, INFO = {}, USER_ACCOUNT = [], USER_ACCOUNT_MAP = {}, OPEN_PATH = "", ACCOUNT_OPEN_NUM = 0; var SMART = {}, BASE_ACCOUNT = {}, INFO = {}, USER_ACCOUNT = [], USER_ACCOUNT_MAP = {}, OPEN_PATH = "", ACCOUNT_OPEN_NUM = 0;
@ -468,12 +385,9 @@ var ALL_ACCOUNTS = 0;
var WasStartInit = 0, WasStartInit2 = 0; var WasStartInit = 0, WasStartInit2 = 0;
var eventInfo = new Event("UpdateInfo"); var eventInfo = new Event("UpdateInfo");
function UpdateDappInfo() function UpdateDappInfo() {
{ GetInfo(function(Err, Data) {
GetInfo(function (Err,Data) if (Err) {
{
if(Err)
{
return; return;
} }
INFO = Data; INFO = Data;
@ -486,34 +400,29 @@ function UpdateDappInfo()
USER_ACCOUNT_MAP = {}; USER_ACCOUNT_MAP = {};
for (var i = 0; i < USER_ACCOUNT.length; i++) for (var i = 0; i < USER_ACCOUNT.length; i++)
USER_ACCOUNT_MAP[USER_ACCOUNT[i].Num] = USER_ACCOUNT[i]; USER_ACCOUNT_MAP[USER_ACCOUNT[i].Num] = USER_ACCOUNT[i];
if(window.OnInit && !WasStartInit) if (window.OnInit && !WasStartInit) {
{
WasStartInit = 1; WasStartInit = 1;
window.OnInit(1); window.OnInit(1);
} }
else else
if(window.OnUpdateInfo) if (window.OnUpdateInfo) {
{
window.OnUpdateInfo(); window.OnUpdateInfo();
} }
if(!WasStartInit2) if (!WasStartInit2) {
{
WasStartInit2 = 1; WasStartInit2 = 1;
var eventInit = new Event("Init"); var eventInit = new Event("Init");
window.dispatchEvent(eventInit); window.dispatchEvent(eventInit);
} }
window.dispatchEvent(eventInfo); window.dispatchEvent(eventInfo);
if (Data.ArrEvent) if (Data.ArrEvent)
for(var i = 0; i < Data.ArrEvent.length; i++) for (var i = 0; i < Data.ArrEvent.length; i++) {
{
var Item = Data.ArrEvent[i]; var Item = Data.ArrEvent[i];
Item.cmd = "OnEvent"; Item.cmd = "OnEvent";
OnMessage({ data: Item }); OnMessage({ data: Item });
} }
}, 1); }, 1);
}; };
window.addEventListener('load', function () window.addEventListener('load', function() {
{
if (!window.sha3) if (!window.sha3)
LoadLib("./JS/sha3.js"); LoadLib("./JS/sha3.js");
UpdateDappInfo(); UpdateDappInfo();

View File

@ -12,21 +12,18 @@ var DiagramMap = {};
var DiagramMapId = {}; var DiagramMapId = {};
var LMouseOn = false; var LMouseOn = false;
if (!window.toStaticHTML) if (!window.toStaticHTML)
toStaticHTML = function (Str) toStaticHTML = function(Str) {
{
return Str; return Str;
}; };
function Rigth(Str,Count) function Rigth(Str, Count) {
{
if (Str.length < Count) if (Str.length < Count)
return Str; return Str;
else else
return Str.substr(Str.length - Count); return Str.substr(Str.length - Count);
}; };
function SetHTMLDiagramItem(Item,width) function SetHTMLDiagramItem(Item, width) {
{
Item.mouseX = width - 50; Item.mouseX = width - 50;
if (Item.Extern || Item.Delete) if (Item.Extern || Item.Delete)
return; return;
@ -35,56 +32,46 @@ function SetHTMLDiagramItem(Item,width)
Item.id = "DgrmId" + Item.num; Item.id = "DgrmId" + Item.num;
DiagramMap[Item.name] = Item; DiagramMap[Item.name] = Item;
DiagramMapId[Item.id] = Item; DiagramMapId[Item.id] = Item;
if(Item.isLine) if (Item.isLine) {
{
if (Item.text) if (Item.text)
Str = "<BR><B>" + Item.text + '</B><INPUT type="button" class="delete" onclick="DeleteDiagram(\'' + Item.id + '\')" value="X">'; Str = "<BR><B>" + Item.text + '</B><INPUT type="button" class="delete" onclick="DeleteDiagram(\'' + Item.id + '\')" value="X">';
else else
Str = "<HR>"; Str = "<HR>";
} }
else else {
{
Str = '<BR><DIV>' + Item.text + '<INPUT type="button" class="delete" onclick="DeleteDiagram(\'' + Item.id + '\')" value="X"></DIV>\ Str = '<BR><DIV>' + Item.text + '<INPUT type="button" class="delete" onclick="DeleteDiagram(\'' + Item.id + '\')" value="X"></DIV>\
<BR><canvas class="DIAGRAM" width="' + width + '" height="' + MinHeight + '" id="' + Item.id + '"></canvas>'; <BR><canvas class="DIAGRAM" width="' + width + '" height="' + MinHeight + '" id="' + Item.id + '"></canvas>';
} }
var ElBlock = document.getElementById("B" + Item.id); var ElBlock = document.getElementById("B" + Item.id);
if (ElBlock) if (ElBlock)
ElBlock.innerHTML = toStaticHTML(Str); ElBlock.innerHTML = toStaticHTML(Str);
else else {
{
var diargams = document.getElementById("diargams"); var diargams = document.getElementById("diargams");
diargams.innerHTML = toStaticHTML(diargams.innerHTML + "<DIV id='B" + Item.id + "'>" + Str + "</DIV>"); diargams.innerHTML = toStaticHTML(diargams.innerHTML + "<DIV id='B" + Item.id + "'>" + Str + "</DIV>");
} }
}; };
function SetDiagramMouseX(event,mode) function SetDiagramMouseX(event, mode) {
{ if (event.srcElement && event.srcElement.className && event.srcElement.className.indexOf && event.srcElement.className.indexOf("DIAGRAM") >= 0) {
if(event.srcElement && event.srcElement.className && event.srcElement.className.indexOf && event.srcElement.className.indexOf("DIAGRAM") >= 0)
{
if (mode === "down") if (mode === "down")
LMouseOn = true; LMouseOn = true;
else else
if (mode === "up") if (mode === "up")
LMouseOn = false; LMouseOn = false;
event.preventDefault(); event.preventDefault();
if(LMouseOn === true) if (LMouseOn === true) {
{
var obj = event.srcElement; var obj = event.srcElement;
var mouse = getMouse(obj, event); var mouse = getMouse(obj, event);
if(event.ctrlKey === true) if (event.ctrlKey === true) {
{ for (var key in DiagramMapId) {
for(var key in DiagramMapId)
{
var Item = DiagramMapId[key]; var Item = DiagramMapId[key];
Item.mouseX = mouse.x; Item.mouseX = mouse.x;
DrawDiagram(Item); DrawDiagram(Item);
} }
} }
else else {
{
var Item = DiagramMapId[obj.id]; var Item = DiagramMapId[obj.id];
if(Item) if (Item) {
{
Item.mouseX = mouse.x; Item.mouseX = mouse.x;
DrawDiagram(Item); DrawDiagram(Item);
} }
@ -93,8 +80,7 @@ function SetDiagramMouseX(event,mode)
} }
}; };
function DrawDiagram(Item) function DrawDiagram(Item) {
{
if (Item.Delete) if (Item.Delete)
return; return;
var arr = Item.arr; var arr = Item.arr;
@ -130,8 +116,7 @@ function DrawDiagram(Item)
var MaxValue = arr[0]; var MaxValue = arr[0];
var MinValue = arr[0]; var MinValue = arr[0];
var AvgValue = 0; var AvgValue = 0;
for(var i = 0; i < arr.length; i++) for (var i = 0; i < arr.length; i++) {
{
if (arr[i] > MaxValue) if (arr[i] > MaxValue)
MaxValue = arr[i]; MaxValue = arr[i];
if (arr[i] < MinValue) if (arr[i] < MinValue)
@ -160,8 +145,7 @@ function DrawDiagram(Item)
var KY = (obj.height - Top - Button) / HValue; var KY = (obj.height - Top - Button) / HValue;
var DeltaY = 0; var DeltaY = 0;
var bLine = Item.line; var bLine = Item.line;
if(Item.zero) if (Item.zero) {
{
bLine = 1; bLine = 1;
DeltaY -= Item.zero * KY; DeltaY -= Item.zero * KY;
MaxValue -= Item.zero; MaxValue -= Item.zero;
@ -181,31 +165,26 @@ function DrawDiagram(Item)
var mouseValue = undefined; var mouseValue = undefined;
var mouseColor = undefined; var mouseColor = undefined;
function DrawLines(arr,mode,color) function DrawLines(arr, mode, color) {
{
var WasMove0 = 0; var WasMove0 = 0;
ctx.beginPath(); ctx.beginPath();
ctx.moveTo(Left, obj.height - Button); ctx.moveTo(Left, obj.height - Button);
ctx.strokeStyle = color; ctx.strokeStyle = color;
var PrevX = undefined; var PrevX = undefined;
for(var i = 0; i < arr.length; i++) for (var i = 0; i < arr.length; i++) {
{
var Value = arr[i]; var Value = arr[i];
if (!Value) if (!Value)
Value = 0; Value = 0;
if(Value) if (Value) {
{
if (Pow2) if (Pow2)
Value = Math.pow(2, Value) / 1000000; Value = Math.pow(2, Value) / 1000000;
} }
if(mode === "green") if (mode === "green") {
{
if (Value > GreenValue) if (Value > GreenValue)
continue; continue;
} }
else else
if(mode === "red") if (mode === "red") {
{
if (Value <= GreenValue) if (Value <= GreenValue)
continue; continue;
} }
@ -217,29 +196,23 @@ function DrawLines(arr,mode,color)
if (VX1 === VX2) if (VX1 === VX2)
VX1 -= 2; VX1 -= 2;
var x = StartX + ctx.lineWidth / 2 + (i) * KX; var x = StartX + ctx.lineWidth / 2 + (i) * KX;
if(bLine) if (bLine) {
{ if (!WasMove0) {
if(!WasMove0)
{
WasMove0 = 1; WasMove0 = 1;
ctx.moveTo(x, StartY - VX2); ctx.moveTo(x, StartY - VX2);
} }
else else {
{
ctx.lineTo(x, StartY - VX2); ctx.lineTo(x, StartY - VX2);
} }
} }
else else {
{
ctx.moveTo(x, StartY - VX1); ctx.moveTo(x, StartY - VX1);
ctx.lineTo(x, StartY - VX2); ctx.lineTo(x, StartY - VX2);
} }
if(mouseX) if (mouseX) {
{
var deltaCur = Math.abs(x - mouseX); var deltaCur = Math.abs(x - mouseX);
var deltaWas = Math.abs(mouseValueX - mouseX); var deltaWas = Math.abs(mouseValueX - mouseX);
if(deltaCur < deltaWas) if (deltaCur < deltaWas) {
{
mouseValueX = x; mouseValueX = x;
mouseValue = Value; mouseValue = Value;
if (Item.zero) if (Item.zero)
@ -252,12 +225,10 @@ function DrawLines(arr,mode,color)
}; };
if (!Item.red) if (!Item.red)
Item.red = "#A00"; Item.red = "#A00";
if(bLine) if (bLine) {
{
DrawLines(arr, "line", Item.red); DrawLines(arr, "line", Item.red);
} }
else else {
{
DrawLines(arr, "red", Item.red); DrawLines(arr, "red", Item.red);
if (GreenValue > 0) if (GreenValue > 0)
DrawLines(arr, "green", "#0A0"); DrawLines(arr, "green", "#0A0");
@ -275,16 +246,14 @@ function DrawLines(arr,mode,color)
ctx.moveTo(StartX, StartY + DeltaY); ctx.moveTo(StartX, StartY + DeltaY);
ctx.lineTo(obj.width - 10, StartY + DeltaY); ctx.lineTo(obj.width - 10, StartY + DeltaY);
ctx.stroke(); ctx.stroke();
if(mouseX !== undefined) if (mouseX !== undefined) {
{
ctx.beginPath(); ctx.beginPath();
ctx.lineWidth = 0.5; ctx.lineWidth = 0.5;
ctx.strokeStyle = "#00F"; ctx.strokeStyle = "#00F";
ctx.moveTo(mouseX, Top); ctx.moveTo(mouseX, Top);
ctx.lineTo(mouseX, StartY); ctx.lineTo(mouseX, StartY);
ctx.stroke(); ctx.stroke();
if(mouseValue !== undefined) if (mouseValue !== undefined) {
{
ctx.fillStyle = mouseColor; ctx.fillStyle = mouseColor;
var Val = GetValueByItemProperty(mouseValue, Item); var Val = GetValueByItemProperty(mouseValue, Item);
var mouseTextX = mouseX; var mouseTextX = mouseX;
@ -298,14 +267,12 @@ function DrawLines(arr,mode,color)
ctx.fillStyle = "#000"; ctx.fillStyle = "#000";
if (!Item.NoTextMax) if (!Item.NoTextMax)
ctx.fillText(Rigth("" + MaxValueText, 8), 0, Top - 3); ctx.fillText(Rigth("" + MaxValueText, 8), 0, Top - 3);
if(MaxValue > 0 && AvgValue > 0) if (MaxValue > 0 && AvgValue > 0) {
{
var heigh = StartY - Top; var heigh = StartY - Top;
var KKY = AvgValue / MaxValue; var KKY = AvgValue / MaxValue;
var y = (heigh - Math.floor(KKY * heigh)); var y = (heigh - Math.floor(KKY * heigh));
var yT = y; var yT = y;
if(yT < 10) if (yT < 10) {
{
yT = 10; yT = 10;
} }
ctx.beginPath(); ctx.beginPath();
@ -322,18 +289,15 @@ function DrawLines(arr,mode,color)
var KDelitel = 1; var KDelitel = 1;
var Step = arr.length / CountNameX; var Step = arr.length / CountNameX;
var StartTime, bNumber; var StartTime, bNumber;
if(arrX) if (arrX) {
{
} }
else else
if(StartNumber !== undefined) if (StartNumber !== undefined) {
{
bNumber = 1; bNumber = 1;
StartTime = StartNumber; StartTime = StartNumber;
} }
else else
if(StartServer) if (StartServer) {
{
bNumber = 1; bNumber = 1;
StartTime = Math.floor(((Date.now() - StartServer) - StepTime * arr.length * 1000) / 1000); StartTime = Math.floor(((Date.now() - StartServer) - StepTime * arr.length * 1000) / 1000);
if (StartTime < 0) if (StartTime < 0)
@ -342,17 +306,14 @@ function DrawLines(arr,mode,color)
if (KDelitel == 0) if (KDelitel == 0)
KDelitel = 1; KDelitel = 1;
} }
else else {
{
bNumber = 0; bNumber = 0;
StartTime = Date.now() - StepTime * arr.length * 1000; StartTime = Date.now() - StepTime * arr.length * 1000;
StartX = StartX - 16; StartX = StartX - 16;
} }
for(i = 0; i <= CountNameX; i++) for (i = 0; i <= CountNameX; i++) {
{
var Val; var Val;
if(i === CountNameX) if (i === CountNameX) {
{
Val = arr.length * StepTime; Val = arr.length * StepTime;
KDelitel = 1; KDelitel = 1;
} }
@ -362,21 +323,18 @@ function DrawLines(arr,mode,color)
else else
Val = i * Step * StepTime; Val = i * Step * StepTime;
var Str; var Str;
if(arrX) if (arrX) {
{
Val = Math.floor(Val); Val = Math.floor(Val);
Str = arrX[Val]; Str = arrX[Val];
if (Str === undefined) if (Str === undefined)
Str = ""; Str = "";
} }
else else
if(bNumber) if (bNumber) {
{
Val = Math.floor((StartTime + Val) / KDelitel) * KDelitel; Val = Math.floor((StartTime + Val) / KDelitel) * KDelitel;
Str = Val; Str = Val;
} }
else else {
{
var Time = new Date(StartTime + Val * 1000); var Time = new Date(StartTime + Val * 1000);
Str = "" + Time.getHours(); Str = "" + Time.getHours();
Str += ":" + Rigth("0" + Time.getMinutes(), 2); Str += ":" + Rigth("0" + Time.getMinutes(), 2);
@ -386,10 +344,8 @@ function DrawLines(arr,mode,color)
} }
}; };
function GetValueByItemProperty(Value,Item) function GetValueByItemProperty(Value, Item) {
{ if (Item.MathPow && Item.MathDiv) {
if(Item.MathPow && Item.MathDiv)
{
Value = Math.pow(Item.MathPow, Value) / Item.MathDiv; Value = Math.pow(Item.MathPow, Value) / Item.MathDiv;
} }
var KPrecision = Item.KPrecision; var KPrecision = Item.KPrecision;
@ -399,29 +355,23 @@ function GetValueByItemProperty(Value,Item)
return Value; return Value;
}; };
function InitDiagramByArr(Arr,width) function InitDiagramByArr(Arr, width) {
{ for (var i = 0; i < Arr.length; i++) {
for(var i = 0; i < Arr.length; i++)
{
Arr[i].num = i + 1; Arr[i].num = i + 1;
SetHTMLDiagramItem(Arr[i], width); SetHTMLDiagramItem(Arr[i], width);
} }
window.addEventListener('mousedown', function (event) window.addEventListener('mousedown', function(event) {
{
SetDiagramMouseX(event, "down"); SetDiagramMouseX(event, "down");
}, false); }, false);
window.addEventListener('mouseup', function (event) window.addEventListener('mouseup', function(event) {
{
SetDiagramMouseX(event, "up"); SetDiagramMouseX(event, "up");
}, false); }, false);
window.addEventListener('onmousemove', function (event) window.addEventListener('onmousemove', function(event) {
{
SetDiagramMouseX(event, "move"); SetDiagramMouseX(event, "move");
}, false); }, false);
}; };
function getMouse(canvas,e) function getMouse(canvas, e) {
{
var x = e.clientX - getTrueOffsetLeft(canvas); var x = e.clientX - getTrueOffsetLeft(canvas);
if (window.pageXOffset) if (window.pageXOffset)
x = x + window.pageXOffset; x = x + window.pageXOffset;
@ -432,22 +382,18 @@ function getMouse(canvas,e)
return coord; return coord;
}; };
function getTrueOffsetLeft(ele) function getTrueOffsetLeft(ele) {
{
var n = 0; var n = 0;
while(ele) while (ele) {
{
n += ele.offsetLeft || 0; n += ele.offsetLeft || 0;
ele = ele.offsetParent; ele = ele.offsetParent;
} }
return n; return n;
}; };
function getTrueOffsetTop(ele) function getTrueOffsetTop(ele) {
{
var n = 0; var n = 0;
while(ele) while (ele) {
{
n += ele.offsetTop || 0; n += ele.offsetTop || 0;
ele = ele.offsetParent; ele = ele.offsetParent;
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -11,48 +11,39 @@
"use strict"; "use strict";
var der = require("./der"), toString = Object.prototype.toString, exports = {}, assert = exports; var der = require("./der"), toString = Object.prototype.toString, exports = {}, assert = exports;
exports.isArray = function (e,s) exports.isArray = function(e, s) {
{
if (!Array.isArray(e)) if (!Array.isArray(e))
throw TypeError(s); throw TypeError(s);
}, exports.isBoolean = function (e,s) }, exports.isBoolean = function(e, s) {
{
if ("[object Boolean]" !== toString.call(e)) if ("[object Boolean]" !== toString.call(e))
throw TypeError(s); throw TypeError(s);
}, exports.isBuffer = function (e,s) }, exports.isBuffer = function(e, s) {
{
if (!Buffer.isBuffer(e)) if (!Buffer.isBuffer(e))
throw TypeError(s); throw TypeError(s);
}, exports.isFunction = function (e,s) }, exports.isFunction = function(e, s) {
{
if ("[object Function]" !== toString.call(e)) if ("[object Function]" !== toString.call(e))
throw TypeError(s); throw TypeError(s);
}, exports.isNumber = function (e,s) }, exports.isNumber = function(e, s) {
{
if ("[object Number]" !== toString.call(e)) if ("[object Number]" !== toString.call(e))
throw TypeError(s); throw TypeError(s);
}, exports.isObject = function (e,s) }, exports.isObject = function(e, s) {
{
if ("[object Object]" !== toString.call(e)) if ("[object Object]" !== toString.call(e))
throw TypeError(s); throw TypeError(s);
}, exports.isBufferLength = function (e,s,r) }, exports.isBufferLength = function(e, s, r) {
{
if (e.length !== s) if (e.length !== s)
throw RangeError(r); throw RangeError(r);
}, exports.isBufferLength2 = function (e,s,r,_) }, exports.isBufferLength2 = function(e, s, r, _) {
{
if (e.length !== s && e.length !== r) if (e.length !== s && e.length !== r)
throw RangeError(_); throw RangeError(_);
}, exports.isLengthGTZero = function (e,s) }, exports.isLengthGTZero = function(e, s) {
{
if (0 === e.length) if (0 === e.length)
throw RangeError(s); throw RangeError(s);
}, exports.isNumberInInterval = function (e,s,r,_) }, exports.isNumberInInterval = function(e, s, r, _) {
{
if (e <= s || r <= e) if (e <= s || r <= e)
throw RangeError(_); throw RangeError(_);
}; };
var messages = {COMPRESSED_TYPE_INVALID:"compressed should be a boolean", EC_PRIVATE_KEY_TYPE_INVALID:"private key should be a Buffer", var messages = {
COMPRESSED_TYPE_INVALID: "compressed should be a boolean", EC_PRIVATE_KEY_TYPE_INVALID: "private key should be a Buffer",
EC_PRIVATE_KEY_LENGTH_INVALID: "private key length is invalid", EC_PRIVATE_KEY_RANGE_INVALID: "private key range is invalid", EC_PRIVATE_KEY_LENGTH_INVALID: "private key length is invalid", EC_PRIVATE_KEY_RANGE_INVALID: "private key range is invalid",
EC_PRIVATE_KEY_TWEAK_ADD_FAIL: "tweak out of range or resulting private key is invalid", EC_PRIVATE_KEY_TWEAK_MUL_FAIL: "tweak out of range", EC_PRIVATE_KEY_TWEAK_ADD_FAIL: "tweak out of range or resulting private key is invalid", EC_PRIVATE_KEY_TWEAK_MUL_FAIL: "tweak out of range",
EC_PRIVATE_KEY_EXPORT_DER_FAIL: "couldn't export to DER format", EC_PRIVATE_KEY_IMPORT_DER_FAIL: "couldn't import from DER format", EC_PRIVATE_KEY_EXPORT_DER_FAIL: "couldn't export to DER format", EC_PRIVATE_KEY_IMPORT_DER_FAIL: "couldn't import from DER format",
@ -66,125 +57,104 @@ var messages = {COMPRESSED_TYPE_INVALID:"compressed should be a boolean", EC_PRI
MSG32_TYPE_INVALID: "message should be a Buffer", MSG32_LENGTH_INVALID: "message length is invalid", OPTIONS_TYPE_INVALID: "options should be an Object", MSG32_TYPE_INVALID: "message should be a Buffer", MSG32_LENGTH_INVALID: "message length is invalid", OPTIONS_TYPE_INVALID: "options should be an Object",
OPTIONS_DATA_TYPE_INVALID: "options.data should be a Buffer", OPTIONS_DATA_LENGTH_INVALID: "options.data length is invalid", OPTIONS_DATA_TYPE_INVALID: "options.data should be a Buffer", OPTIONS_DATA_LENGTH_INVALID: "options.data length is invalid",
OPTIONS_NONCEFN_TYPE_INVALID: "options.noncefn should be a Function", RECOVERY_ID_TYPE_INVALID: "recovery should be a Number", OPTIONS_NONCEFN_TYPE_INVALID: "options.noncefn should be a Function", RECOVERY_ID_TYPE_INVALID: "recovery should be a Number",
RECOVERY_ID_VALUE_INVALID:"recovery should have value between -1 and 4", TWEAK_TYPE_INVALID:"tweak should be a Buffer", TWEAK_LENGTH_INVALID:"tweak length is invalid"}; RECOVERY_ID_VALUE_INVALID: "recovery should have value between -1 and 4", TWEAK_TYPE_INVALID: "tweak should be a Buffer", TWEAK_LENGTH_INVALID: "tweak length is invalid"
};
function initCompressedValue(e,s) function initCompressedValue(e, s) {
{
return void 0 === e ? s : (assert.isBoolean(e, messages.COMPRESSED_TYPE_INVALID), e); return void 0 === e ? s : (assert.isBoolean(e, messages.COMPRESSED_TYPE_INVALID), e);
}; };
module.exports = function (E) module.exports = function(E) {
{ return {
return {privateKeyVerify:function (e) privateKeyVerify: function(e) {
{
return assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), 32 === e.length && E.privateKeyVerify(e); return assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), 32 === e.length && E.privateKeyVerify(e);
}, privateKeyExport:function (e,s) }, privateKeyExport: function(e, s) {
{
assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(e, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID), assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(e, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID),
s = initCompressedValue(s, !0); s = initCompressedValue(s, !0);
var r = E.privateKeyExport(e, s); var r = E.privateKeyExport(e, s);
return der.privateKeyExport(e, r, s); return der.privateKeyExport(e, r, s);
}, privateKeyImport:function (e) }, privateKeyImport: function(e) {
{
if (assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), (e = der.privateKeyImport(e)) && 32 === e.length && E.privateKeyVerify(e)) if (assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), (e = der.privateKeyImport(e)) && 32 === e.length && E.privateKeyVerify(e))
return e; return e;
throw new Error(messages.EC_PRIVATE_KEY_IMPORT_DER_FAIL); throw new Error(messages.EC_PRIVATE_KEY_IMPORT_DER_FAIL);
}, privateKeyNegate:function (e) }, privateKeyNegate: function(e) {
{
return assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(e, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID), return assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(e, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID),
E.privateKeyNegate(e); E.privateKeyNegate(e);
}, privateKeyModInverse:function (e) }, privateKeyModInverse: function(e) {
{
return assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(e, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID), return assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(e, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID),
E.privateKeyModInverse(e); E.privateKeyModInverse(e);
}, privateKeyTweakAdd:function (e,s) }, privateKeyTweakAdd: function(e, s) {
{
return assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(e, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID), return assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(e, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID),
assert.isBuffer(s, messages.TWEAK_TYPE_INVALID), assert.isBufferLength(s, 32, messages.TWEAK_LENGTH_INVALID), E.privateKeyTweakAdd(e, assert.isBuffer(s, messages.TWEAK_TYPE_INVALID), assert.isBufferLength(s, 32, messages.TWEAK_LENGTH_INVALID), E.privateKeyTweakAdd(e,
s); s);
}, privateKeyTweakMul:function (e,s) }, privateKeyTweakMul: function(e, s) {
{
return assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(e, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID), return assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(e, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID),
assert.isBuffer(s, messages.TWEAK_TYPE_INVALID), assert.isBufferLength(s, 32, messages.TWEAK_LENGTH_INVALID), E.privateKeyTweakMul(e, assert.isBuffer(s, messages.TWEAK_TYPE_INVALID), assert.isBufferLength(s, 32, messages.TWEAK_LENGTH_INVALID), E.privateKeyTweakMul(e,
s); s);
}, publicKeyCreate:function (e,s) }, publicKeyCreate: function(e, s) {
{
return assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(e, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID), return assert.isBuffer(e, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(e, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID),
s = initCompressedValue(s, !0), E.publicKeyCreate(e, s); s = initCompressedValue(s, !0), E.publicKeyCreate(e, s);
}, publicKeyConvert:function (e,s) }, publicKeyConvert: function(e, s) {
{
return assert.isBuffer(e, messages.EC_PUBLIC_KEY_TYPE_INVALID), assert.isBufferLength2(e, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID), return assert.isBuffer(e, messages.EC_PUBLIC_KEY_TYPE_INVALID), assert.isBufferLength2(e, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID),
s = initCompressedValue(s, !0), E.publicKeyConvert(e, s); s = initCompressedValue(s, !0), E.publicKeyConvert(e, s);
}, publicKeyVerify:function (e) }, publicKeyVerify: function(e) {
{
return assert.isBuffer(e, messages.EC_PUBLIC_KEY_TYPE_INVALID), E.publicKeyVerify(e); return assert.isBuffer(e, messages.EC_PUBLIC_KEY_TYPE_INVALID), E.publicKeyVerify(e);
}, publicKeyTweakAdd:function (e,s,r) }, publicKeyTweakAdd: function(e, s, r) {
{
return assert.isBuffer(e, messages.EC_PUBLIC_KEY_TYPE_INVALID), assert.isBufferLength2(e, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID), return assert.isBuffer(e, messages.EC_PUBLIC_KEY_TYPE_INVALID), assert.isBufferLength2(e, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID),
assert.isBuffer(s, messages.TWEAK_TYPE_INVALID), assert.isBufferLength(s, 32, messages.TWEAK_LENGTH_INVALID), r = initCompressedValue(r, assert.isBuffer(s, messages.TWEAK_TYPE_INVALID), assert.isBufferLength(s, 32, messages.TWEAK_LENGTH_INVALID), r = initCompressedValue(r,
!0), E.publicKeyTweakAdd(e, s, r); !0), E.publicKeyTweakAdd(e, s, r);
}, publicKeyTweakMul:function (e,s,r) }, publicKeyTweakMul: function(e, s, r) {
{
return assert.isBuffer(e, messages.EC_PUBLIC_KEY_TYPE_INVALID), assert.isBufferLength2(e, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID), return assert.isBuffer(e, messages.EC_PUBLIC_KEY_TYPE_INVALID), assert.isBufferLength2(e, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID),
assert.isBuffer(s, messages.TWEAK_TYPE_INVALID), assert.isBufferLength(s, 32, messages.TWEAK_LENGTH_INVALID), r = initCompressedValue(r, assert.isBuffer(s, messages.TWEAK_TYPE_INVALID), assert.isBufferLength(s, 32, messages.TWEAK_LENGTH_INVALID), r = initCompressedValue(r,
!0), E.publicKeyTweakMul(e, s, r); !0), E.publicKeyTweakMul(e, s, r);
}, publicKeyCombine:function (e,s) }, publicKeyCombine: function(e, s) {
{
assert.isArray(e, messages.EC_PUBLIC_KEYS_TYPE_INVALID), assert.isLengthGTZero(e, messages.EC_PUBLIC_KEYS_LENGTH_INVALID); assert.isArray(e, messages.EC_PUBLIC_KEYS_TYPE_INVALID), assert.isLengthGTZero(e, messages.EC_PUBLIC_KEYS_LENGTH_INVALID);
for (var r = 0; r < e.length; ++r) for (var r = 0; r < e.length; ++r)
assert.isBuffer(e[r], messages.EC_PUBLIC_KEY_TYPE_INVALID), assert.isBufferLength2(e[r], 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID); assert.isBuffer(e[r], messages.EC_PUBLIC_KEY_TYPE_INVALID), assert.isBufferLength2(e[r], 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID);
return s = initCompressedValue(s, !0), E.publicKeyCombine(e, s); return s = initCompressedValue(s, !0), E.publicKeyCombine(e, s);
}, signatureNormalize:function (e) }, signatureNormalize: function(e) {
{
return assert.isBuffer(e, messages.ECDSA_SIGNATURE_TYPE_INVALID), assert.isBufferLength(e, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID), return assert.isBuffer(e, messages.ECDSA_SIGNATURE_TYPE_INVALID), assert.isBufferLength(e, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID),
E.signatureNormalize(e); E.signatureNormalize(e);
}, signatureExport:function (e) }, signatureExport: function(e) {
{
assert.isBuffer(e, messages.ECDSA_SIGNATURE_TYPE_INVALID), assert.isBufferLength(e, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID); assert.isBuffer(e, messages.ECDSA_SIGNATURE_TYPE_INVALID), assert.isBufferLength(e, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID);
var s = E.signatureExport(e); var s = E.signatureExport(e);
return der.signatureExport(s); return der.signatureExport(s);
}, signatureImport:function (e) }, signatureImport: function(e) {
{
assert.isBuffer(e, messages.ECDSA_SIGNATURE_TYPE_INVALID), assert.isLengthGTZero(e, messages.ECDSA_SIGNATURE_LENGTH_INVALID); assert.isBuffer(e, messages.ECDSA_SIGNATURE_TYPE_INVALID), assert.isLengthGTZero(e, messages.ECDSA_SIGNATURE_LENGTH_INVALID);
var s = der.signatureImport(e); var s = der.signatureImport(e);
if (s) if (s)
return E.signatureImport(s); return E.signatureImport(s);
throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL); throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL);
}, signatureImportLax:function (e) }, signatureImportLax: function(e) {
{
assert.isBuffer(e, messages.ECDSA_SIGNATURE_TYPE_INVALID), assert.isLengthGTZero(e, messages.ECDSA_SIGNATURE_LENGTH_INVALID); assert.isBuffer(e, messages.ECDSA_SIGNATURE_TYPE_INVALID), assert.isLengthGTZero(e, messages.ECDSA_SIGNATURE_LENGTH_INVALID);
var s = der.signatureImportLax(e); var s = der.signatureImportLax(e);
if (s) if (s)
return E.signatureImport(s); return E.signatureImport(s);
throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL); throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL);
}, sign:function (e,s,r) }, sign: function(e, s, r) {
{
assert.isBuffer(e, messages.MSG32_TYPE_INVALID), assert.isBufferLength(e, 32, messages.MSG32_LENGTH_INVALID), assert.isBuffer(s, assert.isBuffer(e, messages.MSG32_TYPE_INVALID), assert.isBufferLength(e, 32, messages.MSG32_LENGTH_INVALID), assert.isBuffer(s,
messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(s, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID); messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(s, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID);
var _ = null, t = null; var _ = null, t = null;
return void 0 !== r && (assert.isObject(r, messages.OPTIONS_TYPE_INVALID), void 0 !== r.data && (assert.isBuffer(r.data, messages.OPTIONS_DATA_TYPE_INVALID), return void 0 !== r && (assert.isObject(r, messages.OPTIONS_TYPE_INVALID), void 0 !== r.data && (assert.isBuffer(r.data, messages.OPTIONS_DATA_TYPE_INVALID),
assert.isBufferLength(r.data, 32, messages.OPTIONS_DATA_LENGTH_INVALID), _ = r.data), void 0 !== r.noncefn && (assert.isFunction(r.noncefn, assert.isBufferLength(r.data, 32, messages.OPTIONS_DATA_LENGTH_INVALID), _ = r.data), void 0 !== r.noncefn && (assert.isFunction(r.noncefn,
messages.OPTIONS_NONCEFN_TYPE_INVALID), t = r.noncefn)), E.sign(e, s, t, _); messages.OPTIONS_NONCEFN_TYPE_INVALID), t = r.noncefn)), E.sign(e, s, t, _);
}, verify:function (e,s,r) }, verify: function(e, s, r) {
{
return assert.isBuffer(e, messages.MSG32_TYPE_INVALID), assert.isBufferLength(e, 32, messages.MSG32_LENGTH_INVALID), assert.isBuffer(s, return assert.isBuffer(e, messages.MSG32_TYPE_INVALID), assert.isBufferLength(e, 32, messages.MSG32_LENGTH_INVALID), assert.isBuffer(s,
messages.ECDSA_SIGNATURE_TYPE_INVALID), assert.isBufferLength(s, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID), assert.isBuffer(r, messages.ECDSA_SIGNATURE_TYPE_INVALID), assert.isBufferLength(s, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID), assert.isBuffer(r,
messages.EC_PUBLIC_KEY_TYPE_INVALID), assert.isBufferLength2(r, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID), E.verify(e, messages.EC_PUBLIC_KEY_TYPE_INVALID), assert.isBufferLength2(r, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID), E.verify(e,
s, r); s, r);
}, recover:function (e,s,r,_) }, recover: function(e, s, r, _) {
{
return assert.isBuffer(e, messages.MSG32_TYPE_INVALID), assert.isBufferLength(e, 32, messages.MSG32_LENGTH_INVALID), assert.isBuffer(s, return assert.isBuffer(e, messages.MSG32_TYPE_INVALID), assert.isBufferLength(e, 32, messages.MSG32_LENGTH_INVALID), assert.isBuffer(s,
messages.ECDSA_SIGNATURE_TYPE_INVALID), assert.isBufferLength(s, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID), assert.isNumber(r, messages.ECDSA_SIGNATURE_TYPE_INVALID), assert.isBufferLength(s, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID), assert.isNumber(r,
messages.RECOVERY_ID_TYPE_INVALID), assert.isNumberInInterval(r, - 1, 4, messages.RECOVERY_ID_VALUE_INVALID), _ = initCompressedValue(_, messages.RECOVERY_ID_TYPE_INVALID), assert.isNumberInInterval(r, - 1, 4, messages.RECOVERY_ID_VALUE_INVALID), _ = initCompressedValue(_,
!0), E.recover(e, s, r, _); !0), E.recover(e, s, r, _);
}, ecdh:function (e,s) }, ecdh: function(e, s) {
{
return assert.isBuffer(e, messages.EC_PUBLIC_KEY_TYPE_INVALID), assert.isBufferLength2(e, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID), return assert.isBuffer(e, messages.EC_PUBLIC_KEY_TYPE_INVALID), assert.isBufferLength2(e, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID),
assert.isBuffer(s, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(s, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID), assert.isBuffer(s, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(s, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID),
E.ecdh(e, s); E.ecdh(e, s);
}, ecdhUnsafe:function (e,s,r) }, ecdhUnsafe: function(e, s, r) {
{
return assert.isBuffer(e, messages.EC_PUBLIC_KEY_TYPE_INVALID), assert.isBufferLength2(e, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID), return assert.isBuffer(e, messages.EC_PUBLIC_KEY_TYPE_INVALID), assert.isBufferLength2(e, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID),
assert.isBuffer(s, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(s, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID), assert.isBuffer(s, messages.EC_PRIVATE_KEY_TYPE_INVALID), assert.isBufferLength(s, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID),
r = initCompressedValue(r, !0), E.ecdhUnsafe(e, s, r); r = initCompressedValue(r, !0), E.ecdhUnsafe(e, s, r);
}}; }
};
}, global.SIGN_LIB = module.exports; }, global.SIGN_LIB = module.exports;

View File

@ -8,17 +8,14 @@
* Telegram: https://t.me/terafoundation * Telegram: https://t.me/terafoundation
*/ */
(function () (function() {
{
'use strict'; 'use strict';
var root = typeof window === 'object' ? window : {}; var root = typeof window === 'object' ? window : {};
var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node; var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;
if(NODE_JS && !root.RUN_NW_CLIENT) if (NODE_JS && !root.RUN_NW_CLIENT) {
{
root = global; root = global;
} }
if(root.RUN_CLIENT) if (root.RUN_CLIENT) {
{
root = window; root = window;
} }
var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports; var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports;
@ -37,141 +34,117 @@
var SHAKE_BITS = [128, 256]; var SHAKE_BITS = [128, 256];
var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array']; var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array'];
var CSHAKE_BYTEPAD = { '128': 168, '256': 136 }; var CSHAKE_BYTEPAD = { '128': 168, '256': 136 };
if(root.JS_SHA3_NO_NODE_JS || !Array.isArray) if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) {
{ Array.isArray = function(obj) {
Array.isArray = function (obj)
{
return Object.prototype.toString.call(obj) === '[object Array]'; return Object.prototype.toString.call(obj) === '[object Array]';
}; };
} }
var createOutputMethod = function (bits,padding,outputType) var createOutputMethod = function(bits, padding, outputType) {
{ return function(message) {
return function (message)
{
return new Keccak(bits, padding, bits).update(message)[outputType](); return new Keccak(bits, padding, bits).update(message)[outputType]();
}; };
}; };
var createShakeOutputMethod = function (bits,padding,outputType) var createShakeOutputMethod = function(bits, padding, outputType) {
{ return function(message, outputBits) {
return function (message,outputBits)
{
return new Keccak(bits, padding, outputBits).update(message)[outputType](); return new Keccak(bits, padding, outputBits).update(message)[outputType]();
}; };
}; };
var createCshakeOutputMethod = function (bits,padding,outputType) var createCshakeOutputMethod = function(bits, padding, outputType) {
{ return function(message, outputBits, n, s) {
return function (message,outputBits,n,s)
{
return methods['cshake' + bits].update(message, outputBits, n, s)[outputType](); return methods['cshake' + bits].update(message, outputBits, n, s)[outputType]();
}; };
}; };
var createKmacOutputMethod = function (bits,padding,outputType) var createKmacOutputMethod = function(bits, padding, outputType) {
{ return function(key, message, outputBits, s) {
return function (key,message,outputBits,s)
{
return methods['kmac' + bits].update(key, message, outputBits, s)[outputType](); return methods['kmac' + bits].update(key, message, outputBits, s)[outputType]();
}; };
}; };
var createOutputMethods = function (method,createMethod,bits,padding) var createOutputMethods = function(method, createMethod, bits, padding) {
{ for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
for(var i = 0; i < OUTPUT_TYPES.length; ++i)
{
var type = OUTPUT_TYPES[i]; var type = OUTPUT_TYPES[i];
method[type] = createMethod(bits, padding, type); method[type] = createMethod(bits, padding, type);
} }
return method; return method;
}; };
var createMethod = function (bits,padding,outputs) var createMethod = function(bits, padding, outputs) {
{
var method = createOutputMethod(bits, padding, outputs); var method = createOutputMethod(bits, padding, outputs);
method.create = function () method.create = function() {
{
return new Keccak(bits, padding, bits); return new Keccak(bits, padding, bits);
}; };
method.update = function (message) method.update = function(message) {
{
return method.create().update(message); return method.create().update(message);
}; };
return createOutputMethods(method, createOutputMethod, bits, padding); return createOutputMethods(method, createOutputMethod, bits, padding);
}; };
var createMethodArray = function (bits,padding) var createMethodArray = function(bits, padding) {
{
var method = createOutputMethod(bits, padding, 'array'); var method = createOutputMethod(bits, padding, 'array');
method.create = function () method.create = function() {
{
return new Keccak(bits, padding, bits); return new Keccak(bits, padding, bits);
}; };
method.update = function (message) method.update = function(message) {
{
return method.create().update(message); return method.create().update(message);
}; };
return createOutputMethods(method, createOutputMethod, bits, padding); return createOutputMethods(method, createOutputMethod, bits, padding);
}; };
var createShakeMethod = function (bits,padding) var createShakeMethod = function(bits, padding) {
{
var method = createShakeOutputMethod(bits, padding, 'hex'); var method = createShakeOutputMethod(bits, padding, 'hex');
method.create = function (outputBits) method.create = function(outputBits) {
{
return new Keccak(bits, padding, outputBits); return new Keccak(bits, padding, outputBits);
}; };
method.update = function (message,outputBits) method.update = function(message, outputBits) {
{
return method.create(outputBits).update(message); return method.create(outputBits).update(message);
}; };
return createOutputMethods(method, createShakeOutputMethod, bits, padding); return createOutputMethods(method, createShakeOutputMethod, bits, padding);
}; };
var createCshakeMethod = function (bits,padding) var createCshakeMethod = function(bits, padding) {
{
var w = CSHAKE_BYTEPAD[bits]; var w = CSHAKE_BYTEPAD[bits];
var method = createCshakeOutputMethod(bits, padding, 'hex'); var method = createCshakeOutputMethod(bits, padding, 'hex');
method.create = function (outputBits,n,s) method.create = function(outputBits, n, s) {
{ if (!n && !s) {
if(!n && !s)
{
return methods['shake' + bits].create(outputBits); return methods['shake' + bits].create(outputBits);
} }
else else {
{
return new Keccak(bits, padding, outputBits).bytepad([n, s], w); return new Keccak(bits, padding, outputBits).bytepad([n, s], w);
} }
}; };
method.update = function (message,outputBits,n,s) method.update = function(message, outputBits, n, s) {
{
return method.create(outputBits, n, s).update(message); return method.create(outputBits, n, s).update(message);
}; };
return createOutputMethods(method, createCshakeOutputMethod, bits, padding); return createOutputMethods(method, createCshakeOutputMethod, bits, padding);
}; };
var createKmacMethod = function (bits,padding) var createKmacMethod = function(bits, padding) {
{
var w = CSHAKE_BYTEPAD[bits]; var w = CSHAKE_BYTEPAD[bits];
var method = createKmacOutputMethod(bits, padding, 'hex'); var method = createKmacOutputMethod(bits, padding, 'hex');
method.create = function (key,outputBits,s) method.create = function(key, outputBits, s) {
{
return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w); return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w);
}; };
method.update = function (key,message,outputBits,s) method.update = function(key, message, outputBits, s) {
{
return method.create(key, outputBits, s).update(message); return method.create(key, outputBits, s).update(message);
}; };
return createOutputMethods(method, createKmacOutputMethod, bits, padding); return createOutputMethods(method, createKmacOutputMethod, bits, padding);
}; };
var algorithms = [{name:'keccak', padding:KECCAK_PADDING, bits:BITS, createMethod:createMethod}, {name:'sha3', padding:PADDING, var algorithms = [{ name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod }, {
bits:BITS, createMethod:createMethod, outputs:'hex'}, {name:'sha3_array', padding:PADDING, bits:BITS, createMethod:createMethod, name: 'sha3', padding: PADDING,
outputs:'array'}, {name:'sha3_buf', padding:PADDING, bits:BITS, createMethod:createMethod, outputs:'buffer'}, {name:'shake', bits: BITS, createMethod: createMethod, outputs: 'hex'
padding:SHAKE_PADDING, bits:SHAKE_BITS, createMethod:createShakeMethod}, {name:'cshake', padding:CSHAKE_PADDING, bits:SHAKE_BITS, }, {
createMethod:createCshakeMethod}, {name:'kmac', padding:CSHAKE_PADDING, bits:SHAKE_BITS, createMethod:createKmacMethod}]; name: 'sha3_array', padding: PADDING, bits: BITS, createMethod: createMethod,
outputs: 'array'
}, { name: 'sha3_buf', padding: PADDING, bits: BITS, createMethod: createMethod, outputs: 'buffer' }, {
name: 'shake',
padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod
}, {
name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS,
createMethod: createCshakeMethod
}, { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod }];
var methods = {}, methodNames = []; var methods = {}, methodNames = [];
for(var i = 0; i < algorithms.length; ++i) for (var i = 0; i < algorithms.length; ++i) {
{
var algorithm = algorithms[i]; var algorithm = algorithms[i];
var bits = algorithm.bits; var bits = algorithm.bits;
for(var j = 0; j < bits.length; ++j) for (var j = 0; j < bits.length; ++j) {
{
var methodName = algorithm.name + '_' + bits[j]; var methodName = algorithm.name + '_' + bits[j];
methodNames.push(methodName); methodNames.push(methodName);
methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding, algorithm.outputs); methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding, algorithm.outputs);
if(algorithm.name !== 'sha3') if (algorithm.name !== 'sha3') {
{
var newMethodName = algorithm.name + bits[j]; var newMethodName = algorithm.name + bits[j];
methodNames.push(newMethodName); methodNames.push(newMethodName);
methods[newMethodName] = methods[methodName]; methods[newMethodName] = methods[methodName];
@ -179,8 +152,7 @@
} }
} }
function Keccak(bits,padding,outputBits) function Keccak(bits, padding, outputBits) {
{
this.blocks = []; this.blocks = [];
this.s = []; this.s = [];
this.padding = padding; this.padding = padding;
@ -192,71 +164,55 @@ function Keccak(bits,padding,outputBits)
this.byteCount = this.blockCount << 2; this.byteCount = this.blockCount << 2;
this.outputBlocks = outputBits >> 5; this.outputBlocks = outputBits >> 5;
this.extraBytes = (outputBits & 31) >> 3; this.extraBytes = (outputBits & 31) >> 3;
for(var i = 0; i < 50; ++i) for (var i = 0; i < 50; ++i) {
{
this.s[i] = 0; this.s[i] = 0;
} }
}; };
Keccak.prototype.update = function (message) Keccak.prototype.update = function(message) {
{
var notString = typeof message !== 'string'; var notString = typeof message !== 'string';
if(notString && message.constructor === root.ArrayBuffer) if (notString && message.constructor === root.ArrayBuffer) {
{
TO_ERROR_LOG("SHA3", 10, 'ERROR: Error type ArrayBuffer, use Uint8Array instead!'); TO_ERROR_LOG("SHA3", 10, 'ERROR: Error type ArrayBuffer, use Uint8Array instead!');
return [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; return [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
} }
var length = message.length; var length = message.length;
if(notString) if (notString) {
{ if (typeof length !== 'number' || !Array.isArray(message) && !(ARRAY_BUFFER && ArrayBuffer.isView(message))) {
if(typeof length !== 'number' || !Array.isArray(message) && !(ARRAY_BUFFER && ArrayBuffer.isView(message)))
{
TO_ERROR_LOG("SHA3", 20, 'ERROR: Input is invalid type, message=' + JSON.stringify(message)); TO_ERROR_LOG("SHA3", 20, 'ERROR: Input is invalid type, message=' + JSON.stringify(message));
return [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; return [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
} }
} }
var blocks = this.blocks, byteCount = this.byteCount, blockCount = this.blockCount, index = 0, s = this.s, i, code; var blocks = this.blocks, byteCount = this.byteCount, blockCount = this.blockCount, index = 0, s = this.s, i, code;
while(index < length) while (index < length) {
{ if (this.reset) {
if(this.reset)
{
this.reset = false; this.reset = false;
blocks[0] = this.block; blocks[0] = this.block;
for(i = 1; i < blockCount + 1; ++i) for (i = 1; i < blockCount + 1; ++i) {
{
blocks[i] = 0; blocks[i] = 0;
} }
} }
if(notString) if (notString) {
{ for (i = this.start; index < length && i < byteCount; ++index) {
for(i = this.start; index < length && i < byteCount; ++index)
{
blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
} }
} }
else else {
{ for (i = this.start; index < length && i < byteCount; ++index) {
for(i = this.start; index < length && i < byteCount; ++index)
{
code = message.charCodeAt(index); code = message.charCodeAt(index);
if(code < 0x80) if (code < 0x80) {
{
blocks[i >> 2] |= code << SHIFT[i++ & 3]; blocks[i >> 2] |= code << SHIFT[i++ & 3];
} }
else else
if(code < 0x800) if (code < 0x800) {
{
blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];
blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
} }
else else
if(code < 0xd800 || code >= 0xe000) if (code < 0xd800 || code >= 0xe000) {
{
blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];
blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
} }
else else {
{
code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));
blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];
blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];
@ -266,91 +222,73 @@ function Keccak(bits,padding,outputBits)
} }
} }
this.lastByteIndex = i; this.lastByteIndex = i;
if(i >= byteCount) if (i >= byteCount) {
{
this.start = i - byteCount; this.start = i - byteCount;
this.block = blocks[blockCount]; this.block = blocks[blockCount];
for(i = 0; i < blockCount; ++i) for (i = 0; i < blockCount; ++i) {
{
s[i] ^= blocks[i]; s[i] ^= blocks[i];
} }
f(s); f(s);
this.reset = true; this.reset = true;
} }
else else {
{
this.start = i; this.start = i;
} }
} }
return this; return this;
}; };
Keccak.prototype.encode = function (x,right) Keccak.prototype.encode = function(x, right) {
{
var o = x & 255, n = 1; var o = x & 255, n = 1;
var bytes = [o]; var bytes = [o];
x = x >> 8; x = x >> 8;
o = x & 255; o = x & 255;
while(o > 0) while (o > 0) {
{
bytes.unshift(o); bytes.unshift(o);
x = x >> 8; x = x >> 8;
o = x & 255; o = x & 255;
++n; ++n;
} }
if(right) if (right) {
{
bytes.push(n); bytes.push(n);
} }
else else {
{
bytes.unshift(n); bytes.unshift(n);
} }
this.update(bytes); this.update(bytes);
return bytes.length; return bytes.length;
}; };
Keccak.prototype.encodeString = function (str) Keccak.prototype.encodeString = function(str) {
{
str = str || ''; str = str || '';
var notString = typeof str !== 'string'; var notString = typeof str !== 'string';
if(notString && str.constructor === root.ArrayBuffer) if (notString && str.constructor === root.ArrayBuffer) {
{
str = new Uint8Array(str); str = new Uint8Array(str);
} }
var length = str.length; var length = str.length;
if(notString) if (notString) {
{ if (typeof length !== 'number' || !Array.isArray(str) && !(ARRAY_BUFFER && ArrayBuffer.isView(str))) {
if(typeof length !== 'number' || !Array.isArray(str) && !(ARRAY_BUFFER && ArrayBuffer.isView(str)))
{
TO_ERROR_LOG("SHA3", 30, 'ERROR: Input is invalid type, str=' + JSON.stringify(str)); TO_ERROR_LOG("SHA3", 30, 'ERROR: Input is invalid type, str=' + JSON.stringify(str));
return [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; return [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
} }
} }
var bytes = 0; var bytes = 0;
if(notString) if (notString) {
{
bytes = length; bytes = length;
} }
else else {
{ for (var i = 0; i < str.length; ++i) {
for(var i = 0; i < str.length; ++i)
{
var code = str.charCodeAt(i); var code = str.charCodeAt(i);
if(code < 0x80) if (code < 0x80) {
{
bytes += 1; bytes += 1;
} }
else else
if(code < 0x800) if (code < 0x800) {
{
bytes += 2; bytes += 2;
} }
else else
if(code < 0xd800 || code >= 0xe000) if (code < 0xd800 || code >= 0xe000) {
{
bytes += 3; bytes += 3;
} }
else else {
{
code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff)); code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff));
bytes += 4; bytes += 4;
} }
@ -360,11 +298,9 @@ function Keccak(bits,padding,outputBits)
this.update(str); this.update(str);
return bytes; return bytes;
}; };
Keccak.prototype.bytepad = function (strs,w) Keccak.prototype.bytepad = function(strs, w) {
{
var bytes = this.encode(w); var bytes = this.encode(w);
for(var i = 0; i < strs.length; ++i) for (var i = 0; i < strs.length; ++i) {
{
bytes += this.encodeString(strs[i]); bytes += this.encodeString(strs[i]);
} }
var paddingBytes = w - bytes % w; var paddingBytes = w - bytes % w;
@ -373,104 +309,82 @@ function Keccak(bits,padding,outputBits)
this.update(zeros); this.update(zeros);
return this; return this;
}; };
Keccak.prototype.finalize = function () Keccak.prototype.finalize = function() {
{
var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s; var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;
blocks[i >> 2] |= this.padding[i & 3]; blocks[i >> 2] |= this.padding[i & 3];
if(this.lastByteIndex === this.byteCount) if (this.lastByteIndex === this.byteCount) {
{
blocks[0] = blocks[blockCount]; blocks[0] = blocks[blockCount];
for(i = 1; i < blockCount + 1; ++i) for (i = 1; i < blockCount + 1; ++i) {
{
blocks[i] = 0; blocks[i] = 0;
} }
} }
blocks[blockCount - 1] |= 0x80000000; blocks[blockCount - 1] |= 0x80000000;
for(i = 0; i < blockCount; ++i) for (i = 0; i < blockCount; ++i) {
{
s[i] ^= blocks[i]; s[i] ^= blocks[i];
} }
f(s); f(s);
}; };
Keccak.prototype.toString = Keccak.prototype.hex = function () Keccak.prototype.toString = Keccak.prototype.hex = function() {
{
this.finalize(); this.finalize();
var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0;
var hex = '', block; var hex = '', block;
while(j < outputBlocks) while (j < outputBlocks) {
{ for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
for(i = 0; i < blockCount && j < outputBlocks; ++i, ++j)
{
block = s[i]; block = s[i];
hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] + HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] + HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] + HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F]; hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] + HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] + HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] + HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];
} }
if(j % blockCount === 0) if (j % blockCount === 0) {
{
f(s); f(s);
i = 0; i = 0;
} }
} }
if(extraBytes) if (extraBytes) {
{
block = s[i]; block = s[i];
if(extraBytes > 0) if (extraBytes > 0) {
{
hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F]; hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];
} }
if(extraBytes > 1) if (extraBytes > 1) {
{
hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F]; hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];
} }
if(extraBytes > 2) if (extraBytes > 2) {
{
hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F]; hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];
} }
} }
return hex; return hex;
}; };
Keccak.prototype.arrayBuffer = function () Keccak.prototype.arrayBuffer = function() {
{
this.finalize(); this.finalize();
var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0;
var bytes = this.outputBits >> 3; var bytes = this.outputBits >> 3;
var buffer; var buffer;
if(extraBytes) if (extraBytes) {
{
buffer = new ArrayBuffer((outputBlocks + 1) << 2); buffer = new ArrayBuffer((outputBlocks + 1) << 2);
} }
else else {
{
buffer = new ArrayBuffer(bytes); buffer = new ArrayBuffer(bytes);
} }
var array = new Uint32Array(buffer); var array = new Uint32Array(buffer);
while(j < outputBlocks) while (j < outputBlocks) {
{ for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
for(i = 0; i < blockCount && j < outputBlocks; ++i, ++j)
{
array[j] = s[i]; array[j] = s[i];
} }
if(j % blockCount === 0) if (j % blockCount === 0) {
{
f(s); f(s);
} }
} }
if(extraBytes) if (extraBytes) {
{
array[i] = s[i]; array[i] = s[i];
buffer = buffer.slice(0, bytes); buffer = buffer.slice(0, bytes);
} }
return buffer; return buffer;
}; };
Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;
Keccak.prototype.digest = Keccak.prototype.array = function () Keccak.prototype.digest = Keccak.prototype.array = function() {
{
this.finalize(); this.finalize();
var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0;
var array = [], offset, block; var array = [], offset, block;
while(j < outputBlocks) while (j < outputBlocks) {
{ for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
for(i = 0; i < blockCount && j < outputBlocks; ++i, ++j)
{
offset = j << 2; offset = j << 2;
block = s[i]; block = s[i];
array[offset] = block & 0xFF; array[offset] = block & 0xFF;
@ -478,48 +392,39 @@ function Keccak(bits,padding,outputBits)
array[offset + 2] = (block >> 16) & 0xFF; array[offset + 2] = (block >> 16) & 0xFF;
array[offset + 3] = (block >> 24) & 0xFF; array[offset + 3] = (block >> 24) & 0xFF;
} }
if(j % blockCount === 0) if (j % blockCount === 0) {
{
f(s); f(s);
} }
} }
if(extraBytes) if (extraBytes) {
{
offset = j << 2; offset = j << 2;
block = s[i]; block = s[i];
if(extraBytes > 0) if (extraBytes > 0) {
{
array[offset] = block & 0xFF; array[offset] = block & 0xFF;
} }
if(extraBytes > 1) if (extraBytes > 1) {
{
array[offset + 1] = (block >> 8) & 0xFF; array[offset + 1] = (block >> 8) & 0xFF;
} }
if(extraBytes > 2) if (extraBytes > 2) {
{
array[offset + 2] = (block >> 16) & 0xFF; array[offset + 2] = (block >> 16) & 0xFF;
} }
} }
return array; return array;
}; };
function Kmac(bits,padding,outputBits) function Kmac(bits, padding, outputBits) {
{
Keccak.call(this, bits, padding, outputBits); Keccak.call(this, bits, padding, outputBits);
}; };
Kmac.prototype = new Keccak(); Kmac.prototype = new Keccak();
Kmac.prototype.finalize = function () Kmac.prototype.finalize = function() {
{
this.encode(this.outputBits, true); this.encode(this.outputBits, true);
return Keccak.prototype.finalize.call(this); return Keccak.prototype.finalize.call(this);
}; };
var f = function (s) var f = function(s) {
{
var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15,
b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40,
b41, b42, b43, b44, b45, b46, b47, b48, b49; b41, b42, b43, b44, b45, b46, b47, b48, b49;
for(n = 0; n < 48; n += 2) for (n = 0; n < 48; n += 2) {
{
c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];
c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];
c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];
@ -697,58 +602,47 @@ function Kmac(bits,padding,outputBits)
root.sha3_str = methods.sha3_256; root.sha3_str = methods.sha3_256;
root.sha3_array_256 = methods.sha3_array_256; root.sha3_array_256 = methods.sha3_array_256;
root.sha3 = methods.sha3_array_256; root.sha3 = methods.sha3_array_256;
root.sha = function (data) root.sha = function(data) {
{
return meshhash(methods.sha3_256(data)); return meshhash(methods.sha3_256(data));
}; };
root.shaarr = function (data) root.shaarr = function(data) {
{
return meshhash(methods.sha3_array_256(data)); return meshhash(methods.sha3_array_256(data));
}; };
root.shabuf = function (data) root.shabuf = function(data) {
{
return Buffer.from(shaarr(data)); return Buffer.from(shaarr(data));
}; };
root.shabuf = function (data) root.shabuf = function(data) {
{
return Buffer.from(shaarr(data)); return Buffer.from(shaarr(data));
}; };
root.SHA3BUF = function (data,num) root.SHA3BUF = function(data, num) {
{
return Buffer.from(SHA3ARR(data, num)); return Buffer.from(SHA3ARR(data, num));
}; };
root.SHA3ARR = function (data,num) root.SHA3ARR = function(data, num) {
{
if (!NEW_SIGN_TIME || !num || num >= NEW_SIGN_TIME) if (!NEW_SIGN_TIME || !num || num >= NEW_SIGN_TIME)
return sha3(data); return sha3(data);
else else
return meshhash(methods.sha3_array_256(data)); return meshhash(methods.sha3_array_256(data));
}; };
root.shaarrblock = function (data,num) root.shaarrblock = function(data, num) {
{
return meshhash(methods.sha3_array_256(data), num); return meshhash(methods.sha3_array_256(data), num);
}; };
})(); })();
function meshhash(hash,num) function meshhash(hash, num) {
{
var regs = [hash[3], hash[2], hash[1], hash[0]]; var regs = [hash[3], hash[2], hash[1], hash[0]];
var mem = []; var mem = [];
for(var i = 0; i < 16; i++) for (var i = 0; i < 16; i++) {
{
mem[i] = hash[i * 2] + (hash[i * 2 + 1] << 8); mem[i] = hash[i * 2] + (hash[i * 2 + 1] << 8);
} }
var WasGoto = 0; var WasGoto = 0;
var L = 0; var L = 0;
for(var i = 0; i < 64; i++) for (var i = 0; i < 64; i++) {
{
var c = hash[L & 31]; var c = hash[L & 31];
L++; L++;
var a = (c >> 4) & 0xF; var a = (c >> 4) & 0xF;
var b = c & 0xF; var b = c & 0xF;
var r = c & 0x3; var r = c & 0x3;
switch(a) switch (a) {
{
case 0: case 0:
regs[0] = regs[0] + regs[r]; regs[0] = regs[0] + regs[r];
break; break;
@ -768,15 +662,13 @@ function meshhash(hash,num)
regs[0] = regs[0] + regs[1] + regs[2] + regs[3]; regs[0] = regs[0] + regs[1] + regs[2] + regs[3];
break; break;
case 8: case 8:
if((regs[0] & 0xFFFF) < 32768 && !WasGoto) if ((regs[0] & 0xFFFF) < 32768 && !WasGoto) {
{
L = 32 + L - b; L = 32 + L - b;
WasGoto = 1; WasGoto = 1;
} }
break; break;
case 9: case 9:
if((regs[0] & 0xFFFF) > 32768 && !WasGoto) if ((regs[0] & 0xFFFF) > 32768 && !WasGoto) {
{
L += b; L += b;
WasGoto = 1; WasGoto = 1;
} }
@ -786,16 +678,14 @@ function meshhash(hash,num)
} }
var index1 = regs[0] & 0xF; var index1 = regs[0] & 0xF;
var index2 = (regs[0] >> 8) & 0xF; var index2 = (regs[0] >> 8) & 0xF;
if(index1 !== index2) if (index1 !== index2) {
{
var temp = mem[index1]; var temp = mem[index1];
mem[index1] = mem[index2]; mem[index1] = mem[index2];
mem[index2] = temp; mem[index2] = temp;
} }
} }
var ret = []; var ret = [];
for(var i = 0; i < 16; i++) for (var i = 0; i < 16; i++) {
{
ret[i * 2] = mem[i] & 0xFF; ret[i * 2] = mem[i] & 0xFF;
ret[i * 2 + 1] = mem[i] >> 8; ret[i * 2 + 1] = mem[i] >> 8;
} }

File diff suppressed because it is too large Load Diff

View File

@ -19,8 +19,7 @@ var MaxBlockNum = 0;
var DelList = {}; var DelList = {};
var WasAccountsDataStr; var WasAccountsDataStr;
function SetAccountsData(Data,AccountsDataStr) function SetAccountsData(Data, AccountsDataStr) {
{
if (!Data || !Data.result) if (!Data || !Data.result)
return; return;
if ($("idBtRun")) if ($("idBtRun"))
@ -30,15 +29,13 @@ function SetAccountsData(Data,AccountsDataStr)
WasAccountsDataStr = AccountsDataStr; WasAccountsDataStr = AccountsDataStr;
var arr = Data.arr; var arr = Data.arr;
var Select = $("idAccount"); var Select = $("idAccount");
if(arr.length !== Select.options.length) if (arr.length !== Select.options.length) {
{
var options = Select.options; var options = Select.options;
options.length = arr.length; options.length = arr.length;
} }
MaxBlockNum = GetCurrentBlockNumByTime(); MaxBlockNum = GetCurrentBlockNumByTime();
SetGridData(arr, "grid_accounts", "idMyTotalSum"); SetGridData(arr, "grid_accounts", "idMyTotalSum");
for(var i = 0; arr && i < arr.length; i++) for (var i = 0; arr && i < arr.length; i++) {
{
var Item = arr[i]; var Item = arr[i];
Item.MyAccount = true; Item.MyAccount = true;
var Num = ParseNum(Item.Num); var Num = ParseNum(Item.Num);
@ -53,31 +50,25 @@ function SetAccountsData(Data,AccountsDataStr)
option.text = StrText; option.text = StrText;
} }
var CurentValue = LoadMapAfter["idAccount"]; var CurentValue = LoadMapAfter["idAccount"];
if(CurentValue) if (CurentValue) {
{
Select.value = CurentValue; Select.value = CurentValue;
delete LoadMapAfter["idAccount"]; delete LoadMapAfter["idAccount"];
} }
SetCurCurencyName(); SetCurCurencyName();
}; };
function CurTransactionToForm(bForce) function CurTransactionToForm(bForce) {
{
var Item = $("idTransaction"); var Item = $("idTransaction");
if (Item && (Item.className === "" || bForce)) if (Item && (Item.className === "" || bForce))
Item.value = GetJSONFromTransaction(CurrentTR); Item.value = GetJSONFromTransaction(CurrentTR);
}; };
function CheckNameAccTo() function CheckNameAccTo() {
{
MaxBlockNum = GetCurrentBlockNumByTime(); MaxBlockNum = GetCurrentBlockNumByTime();
var ToID = ParseNum($("idTo").value); var ToID = ParseNum($("idTo").value);
if(!MapAccounts[ToID] || (MapAccounts[ToID].MustUpdate && MapAccounts[ToID].MustUpdate >= MaxBlockNum)) if (!MapAccounts[ToID] || (MapAccounts[ToID].MustUpdate && MapAccounts[ToID].MustUpdate >= MaxBlockNum)) {
{ GetData("GetAccountList", { StartNum: ToID }, function(Data) {
GetData("GetAccountList", {StartNum:ToID}, function (Data) if (Data && Data.result === 1 && Data.arr.length) {
{
if(Data && Data.result === 1 && Data.arr.length)
{
var Item = Data.arr[0]; var Item = Data.arr[0];
Item.UpdateData = Date.now(); Item.UpdateData = Date.now();
MapAccounts[Item.Num] = Item; MapAccounts[Item.Num] = Item;
@ -88,23 +79,19 @@ function CheckNameAccTo()
SetNameAccTo(); SetNameAccTo();
}; };
function SetNameAccTo() function SetNameAccTo() {
{
var Str = ""; var Str = "";
var ToID = ParseNum($("idTo").value); var ToID = ParseNum($("idTo").value);
var Item = MapAccounts[ToID]; var Item = MapAccounts[ToID];
var element = $("idNameTo"); var element = $("idNameTo");
var StrTo = GetAccountText(Item, ToID, 1); var StrTo = GetAccountText(Item, ToID, 1);
if(!element) if (!element) {
{
element = $("idNameTo2"); element = $("idNameTo2");
} }
else else {
{
StrTo = "To: " + StrTo; StrTo = "To: " + StrTo;
} }
if(element.innerText !== StrTo) if (element.innerText !== StrTo) {
{
element.innerText = StrTo; element.innerText = StrTo;
if (Item && Item.MyAccount) if (Item && Item.MyAccount)
element.className = "smallbold"; element.className = "smallbold";
@ -113,62 +100,52 @@ function SetNameAccTo()
} }
}; };
function GetAccountText(Item,Num,bGetSum) function GetAccountText(Item, Num, bGetSum) {
{ if (Item) {
if(Item)
{
var text = Item.Name; var text = Item.Name;
if (!text || text.length === 0) if (!text || text.length === 0)
text = Num; text = Num;
else else
text = "" + Num + ". " + text; text = "" + Num + ". " + text;
if(bGetSum) if (bGetSum) {
{
var StrSum = SUM_TO_STRING(Item.Value, Item.Currency); var StrSum = SUM_TO_STRING(Item.Value, Item.Currency);
text += " (" + StrSum + ")"; text += " (" + StrSum + ")";
} }
return text; return text;
} }
else else {
{
return Num; return Num;
} }
}; };
function OnEditIdTo() function OnEditIdTo() {
{
CheckNameAccTo(); CheckNameAccTo();
OnEditTransactionFields(); OnEditTransactionFields();
}; };
function OnEditTransactionFields() function OnEditTransactionFields() {
{
if (IsVisibleBlock("edit_transaction")) if (IsVisibleBlock("edit_transaction"))
CreateTransaction(); CreateTransaction();
SetCurCurencyName(); SetCurCurencyName();
SaveValues(); SaveValues();
}; };
function SetCurCurencyName() function SetCurCurencyName() {
{
var idCoin = $("idCoinName"); var idCoin = $("idCoinName");
if (!idCoin) if (!idCoin)
return; return;
var Num = ParseNum($("idAccount").value); var Num = ParseNum($("idAccount").value);
var Item = MapAccounts[Num]; var Item = MapAccounts[Num];
if(Item) if (Item) {
{
idCoin.innerText = CurrencyName(Item.Currency); idCoin.innerText = CurrencyName(Item.Currency);
} }
}; };
function CreateTransaction(F,CheckErr,Run) function CreateTransaction(F, CheckErr, Run) {
{
CheckNameAccTo(); CheckNameAccTo();
CheckSending(); CheckSending();
var FromID = ParseNum($("idAccount").value); var FromID = ParseNum($("idAccount").value);
if(CheckErr && FromID === 0) if (CheckErr && FromID === 0) {
{
SetError("Select valid 'From account'"); SetError("Select valid 'From account'");
return; return;
} }
@ -176,37 +153,31 @@ function CreateTransaction(F,CheckErr,Run)
var bFindAcc = 0; var bFindAcc = 0;
var ToPubKey = ""; var ToPubKey = "";
var ToID = ParseNum(StrTo); var ToID = ParseNum(StrTo);
if(StrTo !== "" + ToID) if (StrTo !== "" + ToID) {
{ if (StrTo.length === 66 && (StrTo.substr(0, 2) === "02" || StrTo.substr(0, 2) === "03") && IsHexStr(StrTo)) {
if(StrTo.length === 66 && (StrTo.substr(0, 2) === "02" || StrTo.substr(0, 2) === "03") && IsHexStr(StrTo))
{
ToID = 0; ToID = 0;
ToPubKey = StrTo; ToPubKey = StrTo;
if (ToPubKey === PubKeyStr) if (ToPubKey === PubKeyStr)
bFindAcc = 1; bFindAcc = 1;
} }
else else {
{
if (CheckErr) if (CheckErr)
SetError("Valid 'Pay to' - required!"); SetError("Valid 'Pay to' - required!");
return; return;
} }
} }
if(CheckErr && ToID <= 0 && ToPubKey === "" && !AttachItem) if (CheckErr && ToID <= 0 && ToPubKey === "" && !AttachItem) {
{
SetError("Valid 'Pay to' - required!"); SetError("Valid 'Pay to' - required!");
return; return;
} }
var Description = $("idDescription").value.substr(0, 200); var Description = $("idDescription").value.substr(0, 200);
var StrSum = $("idSumSend").value; var StrSum = $("idSumSend").value;
var indDot = StrSum.indexOf("."); var indDot = StrSum.indexOf(".");
if(indDot >= 0) if (indDot >= 0) {
{
var StrTER = StrSum.substr(0, indDot); var StrTER = StrSum.substr(0, indDot);
var StrCENT = StrSum.substr(indDot + 1); var StrCENT = StrSum.substr(indDot + 1);
} }
else else {
{
var StrTER = StrSum; var StrTER = StrSum;
var StrCENT = "0"; var StrCENT = "0";
} }
@ -214,13 +185,11 @@ function CreateTransaction(F,CheckErr,Run)
var Coin = { SumCOIN: ParseNum(StrTER), SumCENT: ParseNum(StrCENT.substr(0, 9)) }; var Coin = { SumCOIN: ParseNum(StrTER), SumCENT: ParseNum(StrCENT.substr(0, 9)) };
var OperationID = 0; var OperationID = 0;
var Item = MapAccounts[FromID]; var Item = MapAccounts[FromID];
if(Item) if (Item) {
{
OperationID = Item.Value.OperationID; OperationID = Item.Value.OperationID;
} }
var AttachBody = []; var AttachBody = [];
if(AttachItem) if (AttachItem) {
{
AttachBody = AttachItem.Data.Body; AttachBody = AttachItem.Data.Body;
if (!AttachBody) if (!AttachBody)
AttachBody = []; AttachBody = [];
@ -228,58 +197,54 @@ function CreateTransaction(F,CheckErr,Run)
var ToPubKeyArr = []; var ToPubKeyArr = [];
if (ToPubKey) if (ToPubKey)
ToPubKeyArr = GetArrFromHex(ToPubKey); ToPubKeyArr = GetArrFromHex(ToPubKey);
var TR = {Type:111, Version:3, Reserve:0, FromID:FromID, OperationID:OperationID, To:[{PubKey:ToPubKeyArr, ID:ToID, SumCOIN:Coin.SumCOIN, var TR = {
SumCENT:Coin.SumCENT}], Description:Description, Body:AttachBody, Sign:CurrentTR.Sign, }; Type: 111, Version: 3, Reserve: 0, FromID: FromID, OperationID: OperationID, To: [{
PubKey: ToPubKeyArr, ID: ToID, SumCOIN: Coin.SumCOIN,
SumCENT: Coin.SumCENT
}], Description: Description, Body: AttachBody, Sign: CurrentTR.Sign,
};
Object.defineProperties(TR, { bFindAcc: { configurable: true, writable: true, enumerable: false, value: bFindAcc } }); Object.defineProperties(TR, { bFindAcc: { configurable: true, writable: true, enumerable: false, value: bFindAcc } });
Object.defineProperties(TR, { Run: { configurable: true, writable: true, enumerable: false, value: Run } }); Object.defineProperties(TR, { Run: { configurable: true, writable: true, enumerable: false, value: Run } });
if(JSON.stringify(TR) === JSON.stringify(CurrentTR)) if (JSON.stringify(TR) === JSON.stringify(CurrentTR)) {
{
if (F) if (F)
F(CurrentTR); F(CurrentTR);
return; return;
} }
CurrentTR = TR; CurrentTR = TR;
GetSignTransaction(TR, "", function (TR) GetSignTransaction(TR, "", function(TR) {
{
CurTransactionToForm(true); CurTransactionToForm(true);
if (F) if (F)
F(TR); F(TR);
}); });
}; };
function SignJSON(F) function SignJSON(F) {
{
if ($("idSignJSON").disabled) if ($("idSignJSON").disabled)
return; return;
var TR = GetTransactionFromJSON(); var TR = GetTransactionFromJSON();
if (!TR) if (!TR)
return; return;
CurrentTR = TR; CurrentTR = TR;
GetSignTransaction(TR, "", function (TR) GetSignTransaction(TR, "", function(TR) {
{
CurTransactionToForm(true); CurTransactionToForm(true);
if (F) if (F)
F(); F();
}); });
}; };
function CheckSending(bToStatus) function CheckSending(bToStatus) {
{
MaxBlockNum = GetCurrentBlockNumByTime(); MaxBlockNum = GetCurrentBlockNumByTime();
var CanSend = IsPrivateMode(); var CanSend = IsPrivateMode();
var StrButton = "Send"; var StrButton = "Send";
var StrButtonSign = "Sign JSON"; var StrButtonSign = "Sign JSON";
if(!CanSend) if (!CanSend) {
{
StrButton = " "; StrButton = " ";
StrButtonSign = " "; StrButtonSign = " ";
} }
if(CanSend) if (CanSend) {
{
var FromID = ParseNum($("idAccount").value); var FromID = ParseNum($("idAccount").value);
var Item = MapAccounts[FromID]; var Item = MapAccounts[FromID];
if(Item && Item.NextSendTime && Item.NextSendTime > MaxBlockNum) if (Item && Item.NextSendTime && Item.NextSendTime > MaxBlockNum) {
{
if (bToStatus) if (bToStatus)
SetStatus("Transaction was sending. Wait... (" + Item.LastTransactionText + ")"); SetStatus("Transaction was sending. Wait... (" + Item.LastTransactionText + ")");
CanSend = false; CanSend = false;
@ -293,31 +258,26 @@ function CheckSending(bToStatus)
return CanSend; return CanSend;
}; };
function AddWhiteList() function AddWhiteList() {
{
var ToID = ParseNum($("idTo").value); var ToID = ParseNum($("idTo").value);
if (ToID && $("idWhiteOnSend").checked) if (ToID && $("idWhiteOnSend").checked)
Storage.setItem("White:" + ToID, 1); Storage.setItem("White:" + ToID, 1);
}; };
function SendMoneyBefore() function SendMoneyBefore() {
{
if ($("idSendButton").disabled) if ($("idSendButton").disabled)
return; return;
var ToID = ParseNum($("idTo").value); var ToID = ParseNum($("idTo").value);
var Item = MapAccounts[ToID]; var Item = MapAccounts[ToID];
if(Storage.getItem("White:" + ToID) || !$("idSumSend").value || Item && Item.MyAccount) if (Storage.getItem("White:" + ToID) || !$("idSumSend").value || Item && Item.MyAccount) {
{
SendMoney(); SendMoney();
} }
else else {
{
var CoinAmount = COIN_FROM_FLOAT($("idSumSend").value); var CoinAmount = COIN_FROM_FLOAT($("idSumSend").value);
var StrTo = " to " + GetAccountText(Item, ToID); var StrTo = " to " + GetAccountText(Item, ToID);
$("idWhiteOnSend").checked = 0; $("idWhiteOnSend").checked = 0;
$("idOnSendText").innerHTML = "<B style='color:#ff4534'>" + STRING_FROM_COIN(CoinAmount) + "</B> " + $("idCoinName").innerText + StrTo; $("idOnSendText").innerHTML = "<B style='color:#ff4534'>" + STRING_FROM_COIN(CoinAmount) + "</B> " + $("idCoinName").innerText + StrTo;
if($("idSumSend").value >= 100000) if ($("idSumSend").value >= 100000) {
{
$("idOnSendText").innerHTML += "<BR><DIV style='color: yellow;'>WARNING: You are about to send a very large amount!</DIV>"; $("idOnSendText").innerHTML += "<BR><DIV style='color: yellow;'>WARNING: You are about to send a very large amount!</DIV>";
} }
SetVisibleBlock("idBlockOnSend", 1); SetVisibleBlock("idBlockOnSend", 1);
@ -325,16 +285,13 @@ function SendMoneyBefore()
} }
}; };
function SendMoney2() function SendMoney2() {
{
AddWhiteList(); AddWhiteList();
SendMoney(); SendMoney();
}; };
function SendMoney() function SendMoney() {
{ if (!CanSendTransaction) {
if(!CanSendTransaction)
{
SetError("Can't Send transaction"); SetError("Can't Send transaction");
return; return;
} }
@ -345,11 +302,9 @@ function SendMoney()
CreateTransaction(SendMoneyTR, true, ClearAttach); CreateTransaction(SendMoneyTR, true, ClearAttach);
}; };
function GetJSONFromTransaction(TR) function GetJSONFromTransaction(TR) {
{
var TR2 = JSON.parse(JSON.stringify(TR)); var TR2 = JSON.parse(JSON.stringify(TR));
for(var i = 0; i < TR2.To.length; i++) for (var i = 0; i < TR2.To.length; i++) {
{
var Item = TR2.To[i]; var Item = TR2.To[i];
Item.PubKey = GetHexFromArr(Item.PubKey); Item.PubKey = GetHexFromArr(Item.PubKey);
} }
@ -359,24 +314,19 @@ function GetJSONFromTransaction(TR)
return Str; return Str;
}; };
function GetTransactionFromJSON() function GetTransactionFromJSON() {
{
var Str = $("idTransaction").value; var Str = $("idTransaction").value;
try try {
{
var TR = JSON.parse(Str); var TR = JSON.parse(Str);
} }
catch(e) catch (e) {
{
SetError(e); SetError(e);
return undefined; return undefined;
} }
for(var i = 0; i < TR.To.length; i++) for (var i = 0; i < TR.To.length; i++) {
{
var Item = TR.To[i]; var Item = TR.To[i];
Item.PubKey = GetArrFromHex(Item.PubKey); Item.PubKey = GetArrFromHex(Item.PubKey);
if(Item.SumTER && Item.SumCOIN === undefined) if (Item.SumTER && Item.SumCOIN === undefined) {
{
Item.SumCOIN = Item.SumTER; Item.SumCOIN = Item.SumTER;
delete Item.SumTER; delete Item.SumTER;
} }
@ -386,10 +336,8 @@ function GetTransactionFromJSON()
return TR; return TR;
}; };
function SendMoneyJSON() function SendMoneyJSON() {
{ if (!CanSendTransaction) {
if(!CanSendTransaction)
{
SetError("Can't Send transaction"); SetError("Can't Send transaction");
return; return;
} }
@ -399,28 +347,22 @@ function SendMoneyJSON()
SendMoneyTR(TR); SendMoneyTR(TR);
}; };
function SignAndSendFromJSON() function SignAndSendFromJSON() {
{
SignJSON(SendMoneyJSON); SignJSON(SendMoneyJSON);
}; };
function GetTransactionText(TR,key) function GetTransactionText(TR, key) {
{
var Str; var Str;
if(TR) if (TR) {
{ if (TR.Type === TYPE_TRANSACTION_CREATE) {
if(TR.Type === TYPE_TRANSACTION_CREATE)
{
Str = "New account " + TR.Name.substr(0, 20); Str = "New account " + TR.Name.substr(0, 20);
} }
else else
if(TR.Type === 111) if (TR.Type === 111) {
{
var MapItem = {}; var MapItem = {};
var ValueTotal = { SumCOIN: 0, SumCENT: 0 }; var ValueTotal = { SumCOIN: 0, SumCENT: 0 };
Str = "" + TR.FromID + "/" + TR.OperationID + " to "; Str = "" + TR.FromID + "/" + TR.OperationID + " to ";
for(var i = 0; i < TR.To.length; i++) for (var i = 0; i < TR.To.length; i++) {
{
var Item = TR.To[i]; var Item = TR.To[i];
if (Item.ID === TR.FromID || MapItem[Item.ID]) if (Item.ID === TR.FromID || MapItem[Item.ID])
continue; continue;
@ -428,8 +370,7 @@ function GetTransactionText(TR,key)
ADD(ValueTotal, Item); ADD(ValueTotal, Item);
if (i === 0) if (i === 0)
Str += "["; Str += "[";
if(Str.length < 16) if (Str.length < 16) {
{
if (i > 0) if (i > 0)
Str += ","; Str += ",";
if (Item.ID || (Item.PubKey && Item.PubKey.length !== 66)) if (Item.ID || (Item.PubKey && Item.PubKey.length !== 66))
@ -445,8 +386,7 @@ function GetTransactionText(TR,key)
Str += " " + (TR.Description.substr(0, 20)).replace(/\n/g, ""); Str += " " + (TR.Description.substr(0, 20)).replace(/\n/g, "");
} }
} }
else else {
{
if (key) if (key)
Str = key; Str = key;
else else
@ -455,18 +395,15 @@ function GetTransactionText(TR,key)
return Str; return Str;
}; };
function SendMoneyTR(TR) function SendMoneyTR(TR) {
{
var Body = GetArrFromTR(TR); var Body = GetArrFromTR(TR);
WriteArr(Body, TR.Sign, 64); WriteArr(Body, TR.Sign, 64);
Body.length += 12; Body.length += 12;
SendTransaction(Body, TR, undefined, function (Err,TR,Body) SendTransaction(Body, TR, undefined, function(Err, TR, Body) {
{
if (Err) if (Err)
return; return;
var Item = MapAccounts[TR.FromID]; var Item = MapAccounts[TR.FromID];
if(Item) if (Item) {
{
var key = GetHexFromArr(sha3(Body)); var key = GetHexFromArr(sha3(Body));
var BlockNum = GetCurrentBlockNumByTime(); var BlockNum = GetCurrentBlockNumByTime();
Item.LastTransactionText = GetTransactionText(TR); Item.LastTransactionText = GetTransactionText(TR);
@ -477,37 +414,31 @@ function SendMoneyTR(TR)
}); });
}; };
function ClearTransaction() function ClearTransaction() {
{
PayList = []; PayList = [];
ClearAttach(); ClearAttach();
CheckSendList(1); CheckSendList(1);
var arr = ["idAccount", "idTo", "idSumSend", "idDescription"]; var arr = ["idAccount", "idTo", "idSumSend", "idDescription"];
for(var i = 0; i < arr.length; i++) for (var i = 0; i < arr.length; i++) {
{
$(arr[i]).value = ""; $(arr[i]).value = "";
} }
SaveValues(); SaveValues();
CreateTransaction(); CreateTransaction();
}; };
function StartEditTransactionJSON() function StartEditTransactionJSON() {
{
var Item = $("idTransaction"); var Item = $("idTransaction");
Item.className = "smallbold"; Item.className = "smallbold";
}; };
function EditJSONTransaction() function EditJSONTransaction() {
{
var name = "edit_transaction"; var name = "edit_transaction";
var Item = $("idTransaction"); var Item = $("idTransaction");
if(IsVisibleBlock(name)) if (IsVisibleBlock(name)) {
{
SetVisibleBlock(name, false); SetVisibleBlock(name, false);
Item.className = ""; Item.className = "";
} }
else else {
{
CreateTransaction(); CreateTransaction();
SetVisibleBlock(name, true); SetVisibleBlock(name, true);
Item.className = ""; Item.className = "";
@ -515,10 +446,8 @@ function EditJSONTransaction()
}; };
var glNumPayCount = 0; var glNumPayCount = 0;
function GetInvoiceHTML(item,onclick,classstr) function GetInvoiceHTML(item, onclick, classstr) {
{ if (!item.num) {
if(!item.num)
{
glNumPayCount++; glNumPayCount++;
item.num = glNumPayCount; item.num = glNumPayCount;
} }
@ -532,53 +461,44 @@ function GetInvoiceHTML(item,onclick,classstr)
return "<button id='" + idname + "' onclick='" + onclick + "' class='" + classstr + "'>" + value + "</button>"; return "<button id='" + idname + "' onclick='" + onclick + "' class='" + classstr + "'>" + value + "</button>";
}; };
function AddSendList(item) function AddSendList(item) {
{
PayList.push({ Data: item }); PayList.push({ Data: item });
}; };
function CheckSendList(bRedraw) function CheckSendList(bRedraw) {
{
TitleWarning = PayList.length; TitleWarning = PayList.length;
if (AttachItem) if (AttachItem)
TitleWarning++; TitleWarning++;
var Str = Storage.getItem("InvoiceList"); var Str = Storage.getItem("InvoiceList");
if (!Str && !bRedraw) if (!Str && !bRedraw)
return; return;
if(!bRedraw) if (!bRedraw) {
{
SelectTab("TabSend"); SelectTab("TabSend");
} }
if(Str) if (Str) {
{
var arr = JSON.parse(Str); var arr = JSON.parse(Str);
for(var i = 0; i < arr.length; i++) for (var i = 0; i < arr.length; i++) {
{
AddSendList(arr[i]); AddSendList(arr[i]);
} }
Storage.setItem("InvoiceList", ""); Storage.setItem("InvoiceList", "");
} }
var idList = $("idSendList"); var idList = $("idSendList");
if(PayList.length) if (PayList.length) {
{
idList.innerHTML = "<DIV id='PaiListInfo'>Select the item you want to sign (pay) and send to blockchain:</DIV>"; idList.innerHTML = "<DIV id='PaiListInfo'>Select the item you want to sign (pay) and send to blockchain:</DIV>";
for(var i = 0; i < PayList.length; i++) for (var i = 0; i < PayList.length; i++) {
{
var item = PayList[i]; var item = PayList[i];
idList.innerHTML += GetInvoiceHTML(item, "UseInvoice(" + i + ")", "btinvoice"); idList.innerHTML += GetInvoiceHTML(item, "UseInvoice(" + i + ")", "btinvoice");
} }
if (AttachItem === undefined) if (AttachItem === undefined)
UseInvoice(0); UseInvoice(0);
} }
else else {
{
idList.innerHTML = ""; idList.innerHTML = "";
} }
}; };
setInterval(CheckSendList, 200); setInterval(CheckSendList, 200);
function UseInvoice(Num) function UseInvoice(Num) {
{
var item = PayList[Num]; var item = PayList[Num];
if (item.Data.From) if (item.Data.From)
$("idAccount").value = item.Data.From; $("idAccount").value = item.Data.From;
@ -591,17 +511,14 @@ function UseInvoice(Num)
CheckSendList(1); CheckSendList(1);
}; };
function ClearAttach() function ClearAttach() {
{
AttachItem = undefined; AttachItem = undefined;
if ($("idAttach")) if ($("idAttach"))
$("idAttach").innerHTML = ""; $("idAttach").innerHTML = "";
}; };
function OpenAttach() function OpenAttach() {
{ if (AttachItem) {
if(AttachItem)
{
var Data2 = JSON.parse(JSON.stringify(AttachItem.Data)); var Data2 = JSON.parse(JSON.stringify(AttachItem.Data));
if (Data2.Body) if (Data2.Body)
Data2.Body = GetHexFromArr(Data2.Body); Data2.Body = GetHexFromArr(Data2.Body);
@ -611,75 +528,61 @@ function OpenAttach()
}; };
var CURRENCY, PUBKEY, NAME, SMART; var CURRENCY, PUBKEY, NAME, SMART;
function SendTrCreateAccWait(Currency,PubKey,Name,Smart) function SendTrCreateAccWait(Currency, PubKey, Name, Smart) {
{
CURRENCY = Currency; CURRENCY = Currency;
PUBKEY = PubKey; PUBKEY = PubKey;
NAME = Name; NAME = Name;
SMART = Smart; SMART = Smart;
setTimeout(function () setTimeout(function() {
{
SendTrCreateAcc(CURRENCY, PUBKEY, NAME, 0, SMART, 0, 0); SendTrCreateAcc(CURRENCY, PUBKEY, NAME, 0, SMART, 0, 0);
}, 50); }, 50);
}; };
function SendTrCreateAcc(Currency,PubKey,Description,Adviser,Smart,bFindAcc,bAddToPay) function SendTrCreateAcc(Currency, PubKey, Description, Adviser, Smart, bFindAcc, bAddToPay) {
{
var TR = GetTrCreateAcc(Currency, PubKey, Description, Adviser, Smart); var TR = GetTrCreateAcc(Currency, PubKey, Description, Adviser, Smart);
var Body = GetBodyCreateAcc(TR); var Body = GetBodyCreateAcc(TR);
TR.bFindAcc = 1; TR.bFindAcc = 1;
if(bAddToPay) if (bAddToPay) {
{ var Item = {
var Item = {name:Description, To:0, Amount:CONFIG_DATA.PRICE_DAO.NewAccount, Description:"Create acc: " + Description, Body:Body, name: Description, To: 0, Amount: CONFIG_DATA.PRICE_DAO.NewAccount, Description: "Create acc: " + Description, Body: Body,
}; };
AddToInvoiceList(Item); AddToInvoiceList(Item);
} }
else else {
{
SendTransaction(Body, TR); SendTransaction(Body, TR);
} }
$("idAccountName").value = ""; $("idAccountName").value = "";
CancelCreateAccount(); CancelCreateAccount();
}; };
function ChangeSmart(NumAccount,WasSmart) function ChangeSmart(NumAccount, WasSmart) {
{ if (!IsPrivateMode()) {
if(!IsPrivateMode())
{
SetError("Pls, open wallet"); SetError("Pls, open wallet");
return 0; return 0;
} }
var Result = prompt("Enter smart number:", WasSmart); var Result = prompt("Enter smart number:", WasSmart);
if(Result !== null && Result != WasSmart) if (Result !== null && Result != WasSmart) {
{
var Smart = parseInt(Result); var Smart = parseInt(Result);
if(Smart) if (Smart) {
{ GetData("GetDappList", { StartNum: Smart, CountNum: 1 }, function(Data) {
GetData("GetDappList", {StartNum:Smart, CountNum:1}, function (Data) if (Data && Data.result && Data.arr.length === 1) {
{
if(Data && Data.result && Data.arr.length === 1)
{
SetSmartToAccount(NumAccount, Smart); SetSmartToAccount(NumAccount, Smart);
} }
else else {
{
SetError("Error smart number"); SetError("Error smart number");
} }
}); });
} }
else else {
{
SetSmartToAccount(NumAccount, Smart); SetSmartToAccount(NumAccount, Smart);
} }
} }
}; };
function SetSmartToAccount(NumAccount,Smart) function SetSmartToAccount(NumAccount, Smart) {
{
var OperationID = 0; var OperationID = 0;
var Item = MapAccounts[NumAccount]; var Item = MapAccounts[NumAccount];
if(Item) if (Item) {
{
OperationID = Item.Value.OperationID; OperationID = Item.Value.OperationID;
} }
OperationID++; OperationID++;
@ -694,8 +597,7 @@ function SetSmartToAccount(NumAccount,Smart)
SendTrArrayWithSign(Body, TR.Account, TR); SendTrArrayWithSign(Body, TR.Account, TR);
}; };
function CheckLengthAccDesription(name,Length) function CheckLengthAccDesription(name, Length) {
{
var Str = $(name).value.substr(0, Length + 1); var Str = $(name).value.substr(0, Length + 1);
var arr = toUTF8Array(Str); var arr = toUTF8Array(Str);
var Len = Length - arr.length; var Len = Length - arr.length;

View File

@ -18,24 +18,37 @@ var StartTimeConnecting = 0;
var ConnectedCount = 0; var ConnectedCount = 0;
var NETWORK = "TERA-MAIN"; var NETWORK = "TERA-MAIN";
var ServerMap = {}; var ServerMap = {};
var ServerMainMap = {"127.0.0.1":{"ip":"127.0.0.1", "port":80, "Name":"LOCAL"}, "terafoundation.org":{"ip":"terafoundation.org", var ServerMainMap = {
"port":443, "Name":"TERA", "System":1}, "dappsgate.com":{"ip":"dappsgate.com", "port":80, "Name":"SUPPORT2", "System":1}, "t1.teraexplorer.com":{"ip":"t1.teraexplorer.com", "127.0.0.1": { "ip": "127.0.0.1", "port": 80, "Name": "LOCAL" }, "terafoundation.org": {
"port":80, "Name":"t1.teraexplorer.com", "System":1}, "t2.teraexplorer.com":{"ip":"t2.teraexplorer.com", "port":80, "Name":"t2.teraexplorer.com", "ip": "terafoundation.org",
"System":1}, "t3.teraexplorer.com":{"ip":"t3.teraexplorer.com", "port":80, "Name":"t3.teraexplorer.com", "System":1}, "t4.teraexplorer.com":{"ip":"t4.teraexplorer.com", "port": 443, "Name": "TERA", "System": 1
"port":80, "Name":"t4.teraexplorer.com", "System":1}, "t5.teraexplorer.com":{"ip":"t5.teraexplorer.com", "port":80, "Name":"t5.teraexplorer.com", }, "dappsgate.com": { "ip": "dappsgate.com", "port": 80, "Name": "SUPPORT2", "System": 1 }, "t1.teraexplorer.com": {
"System":1}, }; "ip": "t1.teraexplorer.com",
var ServerTestMap = {"127.0.0.1":{"ip":"127.0.0.1", "port":80, "Name":"LOCAL"}, "dappsgate.com":{"ip":"dappsgate.com", "port":88, "port": 80, "Name": "t1.teraexplorer.com", "System": 1
"Name":"SUPPORT2", "System":1}, }; }, "t2.teraexplorer.com": {
"ip": "t2.teraexplorer.com", "port": 80, "Name": "t2.teraexplorer.com",
"System": 1
}, "t3.teraexplorer.com": { "ip": "t3.teraexplorer.com", "port": 80, "Name": "t3.teraexplorer.com", "System": 1 }, "t4.teraexplorer.com": {
"ip": "t4.teraexplorer.com",
"port": 80, "Name": "t4.teraexplorer.com", "System": 1
}, "t5.teraexplorer.com": {
"ip": "t5.teraexplorer.com", "port": 80, "Name": "t5.teraexplorer.com",
"System": 1
},
};
var ServerTestMap = {
"127.0.0.1": { "ip": "127.0.0.1", "port": 80, "Name": "LOCAL" }, "dappsgate.com": {
"ip": "dappsgate.com", "port": 88,
"Name": "SUPPORT2", "System": 1
},
};
function StartWebWallet() function StartWebWallet() {
{ if (NETWORK === "TERA-TEST2") {
if(NETWORK === "TERA-TEST2")
{
MIN_SUM_POWER = 0; MIN_SUM_POWER = 0;
ServerMap = ServerTestMap; ServerMap = ServerTestMap;
} }
else else {
{
MIN_SUM_POWER = COUNT_BLOCK_PROOF * 35; MIN_SUM_POWER = COUNT_BLOCK_PROOF * 35;
ServerMap = ServerMainMap; ServerMap = ServerMainMap;
} }
@ -44,14 +57,11 @@ function StartWebWallet()
ConnectWebWallet(); ConnectWebWallet();
}; };
function OnInitWebWallet() function OnInitWebWallet() {
{
var str = Storage.getItem(NETWORK + "NodesArrayList"); var str = Storage.getItem(NETWORK + "NodesArrayList");
if(str) if (str) {
{
var arr = JSON.parse(str); var arr = JSON.parse(str);
for(var i = 0; i < arr.length; i++) for (var i = 0; i < arr.length; i++) {
{
var Item = ServerMap[arr[i].ip]; var Item = ServerMap[arr[i].ip];
if (Item && Item.System) if (Item && Item.System)
continue; continue;
@ -60,46 +70,38 @@ function OnInitWebWallet()
} }
}; };
function SaveServerMap() function SaveServerMap() {
{
var arr = []; var arr = [];
for(var key in ServerMap) for (var key in ServerMap) {
{
var Item = ServerMap[key]; var Item = ServerMap[key];
if(Item.SumPower >= MIN_SUM_POWER) if (Item.SumPower >= MIN_SUM_POWER) {
{
arr.push({ ip: Item.ip, port: Item.port }); arr.push({ ip: Item.ip, port: Item.port });
} }
} }
Storage.setItem(NETWORK + "NodesArrayList", JSON.stringify(arr)); Storage.setItem(NETWORK + "NodesArrayList", JSON.stringify(arr));
}; };
function SetStatus(Str) function SetStatus(Str) {
{
var id = $("idStatus"); var id = $("idStatus");
id.innerHTML = Str; id.innerHTML = Str;
if (Str) if (Str)
console.log(id.innerText); console.log(id.innerText);
}; };
function SetError(Str,bNoSound) function SetError(Str, bNoSound) {
{
SetStatus("<DIV align='left' style='color:red'><B>" + Str + "</B></DIV>"); SetStatus("<DIV align='left' style='color:red'><B>" + Str + "</B></DIV>");
}; };
var CountConnect = 0; var CountConnect = 0;
var CountWallet = 0; var CountWallet = 0;
function ConnectWebWallet() function ConnectWebWallet() {
{
StartTimeConnecting = Date.now(); StartTimeConnecting = Date.now();
ConnectedCount = 0; ConnectedCount = 0;
for(var key in ServerMap) for (var key in ServerMap) {
{
var Item = ServerMap[key]; var Item = ServerMap[key];
Item.SendHandShake = 0; Item.SendHandShake = 0;
} }
if(window.BrowserIE && !IsLocalClient()) if (window.BrowserIE && !IsLocalClient()) {
{
MainServer = undefined; MainServer = undefined;
return; return;
} }
@ -111,12 +113,10 @@ function ConnectWebWallet()
}; };
var Stage = 0; var Stage = 0;
function LoopHandShake() function LoopHandShake() {
{
Stage++; Stage++;
SetStatus("Connecting: " + Stage + "..."); SetStatus("Connecting: " + Stage + "...");
for(var key in ServerMap) for (var key in ServerMap) {
{
var Item = ServerMap[key]; var Item = ServerMap[key];
if (Item.SendHandShake || !Item.port) if (Item.SendHandShake || !Item.port)
continue; continue;
@ -127,8 +127,7 @@ function LoopHandShake()
} }
}; };
function DoNodeList(Item) function DoNodeList(Item) {
{
console.log(GetProtocolServerPath(Item) + "/GetNodeList"); console.log(GetProtocolServerPath(Item) + "/GetNodeList");
if (window.location.protocol === "https:" && Item.port !== 443) if (window.location.protocol === "https:" && Item.port !== 443)
return; return;
@ -136,41 +135,33 @@ function DoNodeList(Item)
return; return;
SetStatus("Try: " + Item.ip + ":" + Item.port); SetStatus("Try: " + Item.ip + ":" + Item.port);
Item.SendHandShake = 1; Item.SendHandShake = 1;
GetData(GetProtocolServerPath(Item) + "/GetNodeList", {}, function (Data) GetData(GetProtocolServerPath(Item) + "/GetNodeList", {}, function(Data) {
{ if (Data && Data.result && Data.NETWORK === NETWORK && Data.VersionNum >= MIN_VERSION) {
if(Data && Data.result && Data.NETWORK === NETWORK && Data.VersionNum >= MIN_VERSION)
{
ConnectedCount++; ConnectedCount++;
Item.GetHandShake = 1; Item.GetHandShake = 1;
Item.BlockChain = Data.BlockChain; Item.BlockChain = Data.BlockChain;
SetStatus("Get: " + Item.ip + ":" + Item.port); SetStatus("Get: " + Item.ip + ":" + Item.port);
var bWas = 0; var bWas = 0;
for(var i = 0; i < Data.arr.length; i++) for (var i = 0; i < Data.arr.length; i++) {
{
var Node = Data.arr[i]; var Node = Data.arr[i];
if(!ServerMap[Node.ip] && Node.port) if (!ServerMap[Node.ip] && Node.port) {
{
ServerMap[Node.ip] = Node; ServerMap[Node.ip] = Node;
console.log("New: " + Node.ip + ":" + Node.port); console.log("New: " + Node.ip + ":" + Node.port);
bWas = 1; bWas = 1;
} }
} }
if(bWas && ConnectedCount < MaxConnectedCount && new Date() - StartTimeConnecting < MaxTimeConnecting) if (bWas && ConnectedCount < MaxConnectedCount && new Date() - StartTimeConnecting < MaxTimeConnecting) {
{
setTimeout(LoopHandShake, 100); setTimeout(LoopHandShake, 100);
} }
} }
}); });
}; };
function LoopWalletInfo() function LoopWalletInfo() {
{
SetStatus("Get wallets info..."); SetStatus("Get wallets info...");
for(var key in ServerMap) for (var key in ServerMap) {
{
var Item = ServerMap[key]; var Item = ServerMap[key];
if(Item.port) if (Item.port) {
{
CountWallet++; CountWallet++;
if (window.BrowserIE && CountWallet > 4) if (window.BrowserIE && CountWallet > 4)
break; break;
@ -180,18 +171,15 @@ function LoopWalletInfo()
setTimeout(FindLider, 500); setTimeout(FindLider, 500);
}; };
function DoWalletInfo(Item) function DoWalletInfo(Item) {
{
if (window.location.protocol === "https:" && Item.port !== 443) if (window.location.protocol === "https:" && Item.port !== 443)
return; return;
if (Item.port === 443 && IsIPAddres(Item.ip)) if (Item.port === 443 && IsIPAddres(Item.ip))
return; return;
Item.StartTime = Date.now(); Item.StartTime = Date.now();
Item.SendWalletInfo = 1; Item.SendWalletInfo = 1;
GetData(GetProtocolServerPath(Item) + "/GetCurrentInfo", {BlockChain:1}, function (Data) GetData(GetProtocolServerPath(Item) + "/GetCurrentInfo", { BlockChain: 1 }, function(Data) {
{ if (Data && Data.result && Data.BlockChain && Data.NETWORK === NETWORK) {
if(Data && Data.result && Data.BlockChain && Data.NETWORK === NETWORK)
{
Item.Name = Data.NODES_NAME; Item.Name = Data.NODES_NAME;
Item.GetWalletInfo = 1; Item.GetWalletInfo = 1;
Item.DeltaTime = new Date() - Item.StartTime; Item.DeltaTime = new Date() - Item.StartTime;
@ -202,22 +190,18 @@ function DoWalletInfo(Item)
}); });
}; };
function FindLider() function FindLider() {
{
MainServer = undefined; MainServer = undefined;
var Arr = []; var Arr = [];
var MapSumPower = {}; var MapSumPower = {};
for(var key in ServerMap) for (var key in ServerMap) {
{
var Item = ServerMap[key]; var Item = ServerMap[key];
if(Item.GetWalletInfo && Item.BlockChain) if (Item.GetWalletInfo && Item.BlockChain) {
{
var arr = Item.BlockChain; var arr = Item.BlockChain;
if (arr.data) if (arr.data)
arr = arr.data; arr = arr.data;
Item.SumPower = CalcPowFromBlockChain(arr); Item.SumPower = CalcPowFromBlockChain(arr);
if(Item.SumPower < MIN_SUM_POWER) if (Item.SumPower < MIN_SUM_POWER) {
{
console.log("Skip: " + Item.ip + ":" + Item.port + " SumPower(" + Item.SumPower + ") < MIN_SUM_POWER(" + MIN_SUM_POWER + ")"); console.log("Skip: " + Item.ip + ":" + Item.port + " SumPower(" + Item.SumPower + ") < MIN_SUM_POWER(" + MIN_SUM_POWER + ")");
continue; continue;
} }
@ -228,23 +212,18 @@ function FindLider()
} }
} }
var Max = 0, MaxKey; var Max = 0, MaxKey;
for(var key in MapSumPower) for (var key in MapSumPower) {
{ if (MapSumPower[key] >= Max) {
if(MapSumPower[key] >= Max)
{
Max = MapSumPower[key]; Max = MapSumPower[key];
MaxKey = parseInt(key); MaxKey = parseInt(key);
} }
} }
Arr.sort(function (a,b) Arr.sort(function(a, b) {
{
return a.DeltaTime - b.DeltaTime; return a.DeltaTime - b.DeltaTime;
}); });
for(var i = 0; i < Arr.length; i++) for (var i = 0; i < Arr.length; i++) {
{
var Item = Arr[i]; var Item = Arr[i];
if(Item.SumPower === MaxKey) if (Item.SumPower === MaxKey) {
{
SetStatus("Find " + Item.ip + ":" + Item.port + " with pow=" + Item.SumPower + "/" + MaxKey + " ping=" + Item.DeltaTime); SetStatus("Find " + Item.ip + ":" + Item.port + " with pow=" + Item.SumPower + "/" + MaxKey + " ping=" + Item.DeltaTime);
MainServer = Item; MainServer = Item;
SaveServerMap(); SaveServerMap();
@ -254,22 +233,18 @@ function FindLider()
OnFindServer(); OnFindServer();
}; };
function CalcPowFromBlockChain(BufRead) function CalcPowFromBlockChain(BufRead) {
{
var Sum = 0; var Sum = 0;
var Arr = GetBlockArrFromBuffer(BufRead); var Arr = GetBlockArrFromBuffer(BufRead);
if(Arr.length === COUNT_BLOCK_PROOF) if (Arr.length === COUNT_BLOCK_PROOF) {
{ for (var i = 0; i < Arr.length; i++) {
for(var i = 0; i < Arr.length; i++)
{
Sum += Arr[i].Power; Sum += Arr[i].Power;
} }
} }
return Sum; return Sum;
}; };
function SetAllSum() function SetAllSum() {
{
var Item = MapAccounts[$("idAccount").value]; var Item = MapAccounts[$("idAccount").value];
if (Item) if (Item)
$("idSumSend").value = FLOAT_FROM_COIN(Item.Value).toStringF(); $("idSumSend").value = FLOAT_FROM_COIN(Item.Value).toStringF();

View File

@ -12,7 +12,9 @@ global.HTTPCaller.CreateAccount = function(Params, response) {
if (typeof Params === "object" && Params.Name && Params.PubKey) { if (typeof Params === "object" && Params.Name && Params.PubKey) {
var TYPE_TRANSACTION_CREATE = 100; var TYPE_TRANSACTION_CREATE = 100;
var TR = { var TR = {
Type: global.TYPE_TRANSACTION_CREATE, Currency: Params.Currency, PubKey: global.GetArrFromHex(Params.PubKey), Description: Params.Name, Type: global.TYPE_TRANSACTION_CREATE,
Currency: Params.Currency,
PubKey: global.GetArrFromHex(Params.PubKey), Description: Params.Name,
Smart: Params.Smart, Adviser: 0, Smart: Params.Smart, Adviser: 0,
}; };
var Body = global.BufLib.GetBufferFromObject(TR, global.FORMAT_CREATE, 1000, {}); var Body = global.BufLib.GetBufferFromObject(TR, global.FORMAT_CREATE, 1000, {});

View File

@ -16,7 +16,7 @@ import * as crypto from 'crypto';
import * as os from 'os' import * as os from 'os'
global.glStopNode = false; global.glStopNode = false;
const MAX_TIME_NETWORK_TRANSPORT = 1 * 1000; //const MAX_TIME_NETWORK_TRANSPORT = 1 * 1000;
var GlSumUser; var GlSumUser;
var GlSumSys; var GlSumSys;
var GlSumIdle; var GlSumIdle;
@ -204,7 +204,7 @@ module.exports = class CCommon {
return crypto.randomBytes(32); return crypto.randomBytes(32);
} }
}; };
class SMemBuffer { export class SMemBuffer {
MetaMap1 MetaMap1
MetaMap2 MetaMap2
CheckName CheckName
@ -249,7 +249,7 @@ class SMemBuffer {
return; return;
if (this.CheckName) { if (this.CheckName) {
var Count = 0; var Count = 0;
for (var key in this.MetaMap2) { for (var _ in this.MetaMap2) {
Count++ Count++
} }
if (Count) { if (Count) {
@ -366,15 +366,15 @@ global.STreeBuffer = STreeBuffer;
global.TestCreateTr = TestCreateTr; global.TestCreateTr = TestCreateTr;
function TestCreateTr() { function TestCreateTr() {
const FORMAT_CREATE = "{\ // const FORMAT_CREATE = "{\
Type:byte,\ // Type:byte,\
Currency:uint,\ // Currency:uint,\
PubKey:arr33,\ // PubKey:arr33,\
Description:str40,\ // Description:str40,\
Adviser:uint,\ // Adviser:uint,\
Reserve:arr7,\ // Reserve:arr7,\
POWCreate:arr12,\ // POWCreate:arr12,\
}"; // }";
var TR = { var TR = {
Type: 100, Currency: 0, PubKey: [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Type: 100, Currency: 0, PubKey: [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0], Description: "Description", Adviser: 10, 0, 0, 0, 0, 0], Description: "Description", Adviser: 10,

View File

@ -99,7 +99,7 @@ module.exports = class CConsensus extends require("./block-loader")
Context.TrDataLen = 0 Context.TrDataLen = 0
Context.Info = "Create at:" + global.GetStrOnlyTimeUTC() Context.Info = "Create at:" + global.GetStrOnlyTimeUTC()
var Transfer; var Transfer;
var TransferM2; //var TransferM2;
var LocalLevel = 0; var LocalLevel = 0;
var Levels = this.LevelNodes; var Levels = this.LevelNodes;
for (let L = 0; L < Levels.length; L++) { for (let L = 0; L < Levels.length; L++) {
@ -180,13 +180,14 @@ module.exports = class CConsensus extends require("./block-loader")
global.ToLog("TRANSFER BlockNum:" + Block.BlockNum + " TxArray=" + Data.TxArray.length + " from " + NodeName(Node)) global.ToLog("TRANSFER BlockNum:" + Block.BlockNum + " TxArray=" + Data.TxArray.length + " from " + NodeName(Node))
this.ToMaxPOWList(Data.MaxPOW) this.ToMaxPOWList(Data.MaxPOW)
this.ToMaxSumList(this.GetMaxSumListFromID(Node, Data.MaxSumID, Data.BlockList)) this.ToMaxSumList(this.GetMaxSumListFromID(Node, Data.MaxSumID, Data.BlockList))
var WasNewAdd = 0; //var WasNewAdd = 0;
if (Data.TxArray.length) { if (Data.TxArray.length) {
for (var i = 0; i < Data.TxArray.length; i++) { for (var i = 0; i < Data.TxArray.length; i++) {
var Tr = Data.TxArray[i]; var Tr = Data.TxArray[i];
var Res = this.AddTrToBlockQuote(Block, Tr); var Res = this.AddTrToBlockQuote(Block, Tr);
if (Res === 1) if (Res === 1) {
WasNewAdd = 1 //WasNewAdd = 1
}
if (global.USE_CHECK_SENDING && Res > 0) { if (global.USE_CHECK_SENDING && Res > 0) {
var Tt = Block.PowTxTree.find(Tr); var Tt = Block.PowTxTree.find(Tr);
if (Tt) { if (Tt) {
@ -511,9 +512,8 @@ module.exports = class CConsensus extends require("./block-loader")
bSend = 1 bSend = 1
CanEnd = 0 CanEnd = 0
break; break;
} } else {
else { //var Stop = 1;
var Stop = 1;
} }
} }
} }
@ -825,7 +825,7 @@ module.exports = class CConsensus extends require("./block-loader")
var SumPow = 0; var SumPow = 0;
if (arr.length !== global.SUM_LIST_LENGTH) if (arr.length !== global.SUM_LIST_LENGTH)
return SumPow; return SumPow;
var CountLoad = 0; //var CountLoad = 0;
var BlockNumStart = CurBlockNum - arr.length + 1; var BlockNumStart = CurBlockNum - arr.length + 1;
for (var i = 0; i < arr.length; i++) { for (var i = 0; i < arr.length; i++) {
var Item = arr[i]; var Item = arr[i];
@ -1105,8 +1105,8 @@ module.exports = class CConsensus extends require("./block-loader")
if (this.LoadHistoryMode) if (this.LoadHistoryMode)
return; return;
var bWasSave = false; var bWasSave = false;
var LoadBlockNum; // var LoadBlockNum;
var LoadHash; // var LoadHash;
var start_save = CURRENTBLOCKNUM + global.TIME_START_SAVE; var start_save = CURRENTBLOCKNUM + global.TIME_START_SAVE;
for (var BlockNum = CURRENTBLOCKNUM - global.BLOCK_PROCESSING_LENGTH2; BlockNum > global.BLOCK_PROCESSING_LENGTH2 && BlockNum < CURRENTBLOCKNUM; BlockNum++) { for (var BlockNum = CURRENTBLOCKNUM - global.BLOCK_PROCESSING_LENGTH2; BlockNum > global.BLOCK_PROCESSING_LENGTH2 && BlockNum < CURRENTBLOCKNUM; BlockNum++) {
var Block = this.GetBlock(BlockNum); var Block = this.GetBlock(BlockNum);

View File

@ -9,8 +9,8 @@
*/ */
"use strict"; "use strict";
const fs = require("fs"); //const fs = require("fs");
import * as crypto from 'crypto'; //import * as crypto from 'crypto';
require('./block-loader-const'); require('./block-loader-const');
const STAT_BLOCK_LOAD_PERIOD = global.CONSENSUS_PERIOD_TIME / 5; const STAT_BLOCK_LOAD_PERIOD = global.CONSENSUS_PERIOD_TIME / 5;
module.exports = class CBlock extends require("./rest-loader") module.exports = class CBlock extends require("./rest-loader")
@ -264,7 +264,7 @@ module.exports = class CBlock extends require("./rest-loader")
if (global.LOAD_TO_BEGIN && this.BlockNumDBMin) { if (global.LOAD_TO_BEGIN && this.BlockNumDBMin) {
this.SendLoadToBegin() this.SendLoadToBegin()
} }
var CountStopSend = 0; //var CountStopSend = 0;
var min_num = this.CurrentBlockNum - global.MAX_COUNT_CHAIN_LOAD; var min_num = this.CurrentBlockNum - global.MAX_COUNT_CHAIN_LOAD;
var min_num_load = this.CurrentBlockNum; var min_num_load = this.CurrentBlockNum;
for (var i = 0; i < this.LoadedChainList.length; i++) { for (var i = 0; i < this.LoadedChainList.length; i++) {
@ -309,8 +309,9 @@ module.exports = class CBlock extends require("./rest-loader")
chain.StopSend = true chain.StopSend = true
} }
} }
if (chain && chain.StopSend) if (chain && chain.StopSend) {
CountStopSend++ //CountStopSend++
}
chain = this.LoadedChainList[i] chain = this.LoadedChainList[i]
if (chain && !chain.GetFindDB() && !chain.StopSend) { if (chain && !chain.GetFindDB() && !chain.StopSend) {
this.SendChainNext(chain, true) this.SendChainNext(chain, true)
@ -532,7 +533,7 @@ module.exports = class CBlock extends require("./rest-loader")
chain.BlockHead = Block chain.BlockHead = Block
if (!chain.BlockNumMax) if (!chain.BlockNumMax)
chain.BlockNumMax = Block.BlockNum chain.BlockNumMax = Block.BlockNum
var PrevBlock0 = PrevBlock; //var PrevBlock0 = PrevBlock;
if (BlockFind) { if (BlockFind) {
if (PrevBlock) { if (PrevBlock) {
PrevBlock.BlockDown = BlockFind PrevBlock.BlockDown = BlockFind
@ -671,9 +672,9 @@ module.exports = class CBlock extends require("./rest-loader")
for (var num = 0; num < this.LoadedChainList.length; num++) { for (var num = 0; num < this.LoadedChainList.length; num++) {
var chain = this.LoadedChainList[num]; var chain = this.LoadedChainList[num];
if (chain && chain.arr && chain.arr.length && chain.StopSend) { if (chain && chain.arr && chain.arr.length && chain.StopSend) {
var Count = 0; //var Count = 0;
for (var i = chain.CurNumArrLoad; i < chain.arr.length; i++) { for (var i = chain.CurNumArrLoad; i < chain.arr.length; i++) {
Count++ //Count++
var Block = chain.arr[i]; var Block = chain.arr[i];
if (!global.IsZeroArr(Block.TreeHash) && !Block.TreeEq && !Block.LoadDBFinaly) { if (!global.IsZeroArr(Block.TreeHash) && !Block.TreeEq && !Block.LoadDBFinaly) {
if (!Block.MapSend) { if (!Block.MapSend) {
@ -696,12 +697,12 @@ module.exports = class CBlock extends require("./rest-loader")
if (CountSend >= global.MAX_BLOCK_SEND) if (CountSend >= global.MAX_BLOCK_SEND)
return; return;
} }
} } else {
else
if (i === chain.CurNumArrLoad) { if (i === chain.CurNumArrLoad) {
chain.CurNumArrLoad++ chain.CurNumArrLoad++
Block.LoadDBFinaly = true Block.LoadDBFinaly = true
Count = 0 //Count = 0
}
} }
} }
this.CheckAndWriteLoadedChain(chain) this.CheckAndWriteLoadedChain(chain)
@ -1029,16 +1030,14 @@ module.exports = class CBlock extends require("./rest-loader")
this.SendF(Node, { "Method": "CANBLOCK", "Data": { BlockNum: Block.BlockNum } }) this.SendF(Node, { "Method": "CANBLOCK", "Data": { BlockNum: Block.BlockNum } })
} }
} }
static static CANBLOCK_F() {
CANBLOCK_F() {
return "{BlockNum:uint}"; return "{BlockNum:uint}";
} }
CANBLOCK(Info, CurTime) { CANBLOCK(Info, CurTime) {
var Data = this.DataFromF(Info); // var Data = this.DataFromF(Info);
this.SendF(Info.Node, { "Method": "RETCANBLOCK", "Data": { Result: 1 } }) this.SendF(Info.Node, { "Method": "RETCANBLOCK", "Data": { Result: 1 } })
} }
static static RETCANBLOCK_F() {
RETCANBLOCK_F() {
return "{Result:byte}"; return "{Result:byte}";
} }
RETCANBLOCK(Info, CurTime) { RETCANBLOCK(Info, CurTime) {
@ -1149,10 +1148,10 @@ module.exports = class CBlock extends require("./rest-loader")
this.FREE_MEM_BLOCKS(NumMax - global.BLOCK_COUNT_IN_MEMORY) this.FREE_MEM_BLOCKS(NumMax - global.BLOCK_COUNT_IN_MEMORY)
var maxArrMap = Math.floor(NumMax / global.BLOCK_COUNT_IN_MEMORY) - 1; var maxArrMap = Math.floor(NumMax / global.BLOCK_COUNT_IN_MEMORY) - 1;
if (maxArrMap >= 0) { if (maxArrMap >= 0) {
var nWasCount = 0; // var nWasCount = 0;
for (var key in this.MapMapLoaded) for (var key in this.MapMapLoaded)
if (key as any < maxArrMap) { if (key as any < maxArrMap) {
nWasCount++ // nWasCount++
delete this.MapMapLoaded[key] delete this.MapMapLoaded[key]
} }
} }

View File

@ -9,7 +9,7 @@
*/ */
"use strict"; "use strict";
import * as crypto from 'crypto'; // import * as crypto from 'crypto';
const CNode = require("./node"); const CNode = require("./node");
global.PERIOD_FOR_RECONNECT = 3600 * 1000; global.PERIOD_FOR_RECONNECT = 3600 * 1000;
global.CHECK_DELTA_TIME = { Num: 0, bUse: 0, StartBlockNum: 0, EndBlockNum: 0, bAddTime: 0, DeltaTime: 0, Sign: [] }; global.CHECK_DELTA_TIME = { Num: 0, bUse: 0, StartBlockNum: 0, EndBlockNum: 0, bAddTime: 0, DeltaTime: 0, Sign: [] };
@ -205,8 +205,8 @@ module.exports = class CConnect extends require("./transfer-msg")
if (Node.BlockProcessCount <= this.BusyLevel) if (Node.BlockProcessCount <= this.BusyLevel)
StopGetBlock = 1 StopGetBlock = 1
} }
var СтатДанные = []; // var СтатДанные = [];
var DirectMAccount = 0; // var DirectMAccount = 0;
var Ret = { var Ret = {
VERSIONMAX: global.DEF_VERSION, VERSIONMAX: global.DEF_VERSION,
FIRST_TIME_BLOCK: 0, FIRST_TIME_BLOCK: 0,

View File

@ -451,40 +451,42 @@ function CalcTreeHashFromArrBody(BlockNum, arrContent) {
} }
}; };
function TestMerklTree() { // function TestMerklTree() {
var h1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // var h1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var h2 = global.sha3("2"); // var h2 = global.sha3("2");
var h3 = global.sha3("3"); // var h3 = global.sha3("3");
var h4 = global.sha3("4"); // var h4 = global.sha3("4");
var h5 = global.sha3("5"); // // var h5 = global.sha3("5");
var Tree: any = { RecalcCount: 0 }; // var Tree: any = { RecalcCount: 0 };
var CalcMap = {}; // var CalcMap = {};
Tree.LevelsHash = [[h1, h2]]; // Tree.LevelsHash = [[h1, h2]];
Tree.RecalcCount = 0; // Tree.RecalcCount = 0;
CalcMap[0] = 1; // CalcMap[0] = 1;
CalcMap[1] = 1; // CalcMap[1] = 1;
UpdateMerklTree(Tree, CalcMap, 0); // UpdateMerklTree(Tree, CalcMap, 0);
CalcMap = {}; // CalcMap = {};
Tree.LevelsHash[0] = [h1, h2, h3, h4]; // Tree.LevelsHash[0] = [h1, h2, h3, h4];
Tree.RecalcCount = 0; // Tree.RecalcCount = 0;
CalcMap[2] = 1; // CalcMap[2] = 1;
CalcMap[3] = 1; // CalcMap[3] = 1;
UpdateMerklTree(Tree, CalcMap, 0); // UpdateMerklTree(Tree, CalcMap, 0);
CalcMap = {}; // CalcMap = {};
Tree.LevelsHash[0] = [h1, h2, h3]; // Tree.LevelsHash[0] = [h1, h2, h3];
Tree.RecalcCount = 0; // Tree.RecalcCount = 0;
CalcMap[Tree.LevelsHash[0].length - 1] = 1; // CalcMap[Tree.LevelsHash[0].length - 1] = 1;
UpdateMerklTree(Tree, CalcMap, 0); // UpdateMerklTree(Tree, CalcMap, 0);
global.ToLog("Root=" + global.GetHexFromArr(Tree.Root)); // global.ToLog("Root=" + global.GetHexFromArr(Tree.Root));
global.ToLog("RecalcCount=" + Tree.RecalcCount); // global.ToLog("RecalcCount=" + Tree.RecalcCount);
return Tree; // return Tree;
}; // };
if (0)
if (0) {
setTimeout(function() { setTimeout(function() {
TestMerkleProof(100); TestMerkleProof(100);
global.ToLog("=========END========="); global.ToLog("=========END=========");
process.exit(0); process.exit(0);
}); });
}
function TestMerkleProof(CountTest) { function TestMerkleProof(CountTest) {
for (var R = 0; R < CountTest; R++) { for (var R = 0; R < CountTest; R++) {
@ -841,22 +843,22 @@ function DoSecret(Arr, Arr2, SecretBuf, StartLen) {
} }
}; };
function TestEncryptDecrypt() { // function TestEncryptDecrypt() {
var ArrSecret = Buffer.from([1, 1, 1, 1, 1, 1]); // var ArrSecret = Buffer.from([1, 1, 1, 1, 1, 1]);
var Arr = GetArrFromStr(" Secret message", 64); // var Arr = GetArrFromStr(" Secret message", 64);
var Arr2 = Buffer.from(new Uint8Array(Arr.length)); // var Arr2 = Buffer.from(new Uint8Array(Arr.length));
var Arr3 = Buffer.from(new Uint8Array(Arr.length)); // var Arr3 = Buffer.from(new Uint8Array(Arr.length));
console.log("Message:"); // console.log("Message:");
console.log(Arr); // console.log(Arr);
console.log("-------------------"); // console.log("-------------------");
Encrypt(Arr, Arr2, ArrSecret); // Encrypt(Arr, Arr2, ArrSecret);
console.log("Encrypt:"); // console.log("Encrypt:");
console.log(Arr2); // console.log(Arr2);
console.log("-------------------"); // console.log("-------------------");
Decrypt(Arr2, Arr3, ArrSecret); // Decrypt(Arr2, Arr3, ArrSecret);
console.log("Decrypt:"); // console.log("Decrypt:");
console.log(Utf8ArrayToStr(Arr3.slice(9))); // console.log(Utf8ArrayToStr(Arr3.slice(9)));
}; // };
function toUTF8Array(str) { function toUTF8Array(str) {
var utf8 = []; var utf8 = [];
@ -921,9 +923,9 @@ function Utf8ArrayToStr(array) {
return out; return out;
}; };
function GetArr32FromStr(Str) { // function GetArr32FromStr(Str) {
return GetArrFromStr(Str, 32); // return GetArrFromStr(Str, 32);
}; // };
function GetArrFromStr(Str, Len) { function GetArrFromStr(Str, Len) {
var arr = toUTF8Array(Str); var arr = toUTF8Array(Str);
@ -965,8 +967,7 @@ for (var i = 0; i < DEVELOP_PUB_KEY_ARR.length; i++)
DEVELOP_PUB_KEY_ARR[i] = Buffer.from(global.GetArrFromHex(DEVELOP_PUB_KEY_ARR[i])); DEVELOP_PUB_KEY_ARR[i] = Buffer.from(global.GetArrFromHex(DEVELOP_PUB_KEY_ARR[i]));
global.DEVELOP_PUB_KEY = DEVELOP_PUB_KEY_ARR[0]; global.DEVELOP_PUB_KEY = DEVELOP_PUB_KEY_ARR[0];
global.DEVELOP_PUB_KEY0 = Buffer.from(global.GetArrFromHex("022e80aa78bc07c72781fac12488096f0bfa7b4f48fbab0f2a92e208d1ee3654df")); global.DEVELOP_PUB_KEY0 = Buffer.from(global.GetArrFromHex("022e80aa78bc07c72781fac12488096f0bfa7b4f48fbab0f2a92e208d1ee3654df"));
let LOCAL_RUN = global.LOCAL_RUN; if (global.LOCAL_RUN) {
if (LOCAL_RUN) {
global.DEVELOP_PUB_KEY0 = Buffer.from(global.GetArrFromHex("026A04AB98D9E4774AD806E302DDDEB63BEA16B5CB5F223EE77478E861BB583EB3")); global.DEVELOP_PUB_KEY0 = Buffer.from(global.GetArrFromHex("026A04AB98D9E4774AD806E302DDDEB63BEA16B5CB5F223EE77478E861BB583EB3"));
global.DEVELOP_PUB_KEY = global.DEVELOP_PUB_KEY0; global.DEVELOP_PUB_KEY = global.DEVELOP_PUB_KEY0;
} }
@ -975,8 +976,8 @@ global.ARR_PUB_KEY = ["027ae0dce92d8be1f893525b226695ddf0fe6ad756349a76777ff51f3
"0270e0c5acb8eefe7faddac45503da4885e02fb554975d12907f6c33ac6c6bdba5", "0202f2aad628f46d433faf70ba6bf12ab9ed96a46923b592a72508dc43af36cb80", "0270e0c5acb8eefe7faddac45503da4885e02fb554975d12907f6c33ac6c6bdba5", "0202f2aad628f46d433faf70ba6bf12ab9ed96a46923b592a72508dc43af36cb80",
"0254f373fc44ac4a3e80ec8cb8cc3693a856caa82e0493067bdead78ce8ec354b8", "027617f9511b0b0cdbda8f3e17907732731296321846f3fd6fd19460f7227d9482", "0254f373fc44ac4a3e80ec8cb8cc3693a856caa82e0493067bdead78ce8ec354b8", "027617f9511b0b0cdbda8f3e17907732731296321846f3fd6fd19460f7227d9482",
]; ];
let GetHexFromArr = global.GetHexFromArr; // let GetHexFromArr = global.GetHexFromArr;
if (global.TEST_NETWORK || LOCAL_RUN) { if (global.TEST_NETWORK || global.LOCAL_RUN) {
for (var i = 0; i < 100; i++) for (var i = 0; i < 100; i++)
global.ARR_PUB_KEY[i] = global.GetHexFromArr(global.DEVELOP_PUB_KEY0); global.ARR_PUB_KEY[i] = global.GetHexFromArr(global.DEVELOP_PUB_KEY0);
global.DEVELOP_PUB_KEY_ARR = [global.DEVELOP_PUB_KEY0]; global.DEVELOP_PUB_KEY_ARR = [global.DEVELOP_PUB_KEY0];

View File

@ -13,10 +13,12 @@ import './crypto-library'
import './log' import './log'
import * as crypto from 'crypto'; import * as crypto from 'crypto';
const os = require('os');
var BlockTree = new global.STreeBuffer(300 * 1000, global.CompareItemHashSimple, "number"); var BlockTree = new global.STreeBuffer(300 * 1000, global.CompareItemHashSimple, "number");
const http = require('http'), net = require('net'), url = require('url'), fs = require('fs'), querystring = require('querystring'); import http = require('http');
const url = require('url')
const fs = require('fs')
const querystring = require('querystring');
var ContenTypeMap = {}; var ContenTypeMap = {};
ContenTypeMap["js"] = "application/javascript"; ContenTypeMap["js"] = "application/javascript";
ContenTypeMap["css"] = "text/css"; ContenTypeMap["css"] = "text/css";
@ -1117,27 +1119,27 @@ HTTPCaller.GetHistoryTransactions = function(Params) {
return { result: 0 }; return { result: 0 };
}; };
function GetCopyBlock(Block) { // function GetCopyBlock(Block) {
var Result: any = { // var Result: any = {
BlockNum: Block.BlockNum, bSave: Block.bSave, TreeHash: global.GetHexFromAddres(Block.TreeHash), AddrHash: global.GetHexFromAddres(Block.AddrHash), // BlockNum: Block.BlockNum, bSave: Block.bSave, TreeHash: global.GetHexFromAddres(Block.TreeHash), AddrHash: global.GetHexFromAddres(Block.AddrHash),
PrevHash: global.GetHexFromAddres(Block.PrevHash), SumHash: global.GetHexFromAddres(Block.SumHash), SumPow: Block.SumPow, TrDataPos: Block.TrDataPos, // PrevHash: global.GetHexFromAddres(Block.PrevHash), SumHash: global.GetHexFromAddres(Block.SumHash), SumPow: Block.SumPow, TrDataPos: Block.TrDataPos,
TrDataLen: Block.TrDataLen, SeqHash: global.GetHexFromAddres(Block.SeqHash), Hash: global.GetHexFromAddres(Block.Hash), Power: global.GetPowPower(Block.PowHash), // TrDataLen: Block.TrDataLen, SeqHash: global.GetHexFromAddres(Block.SeqHash), Hash: global.GetHexFromAddres(Block.Hash), Power: global.GetPowPower(Block.PowHash),
TrCount: Block.TrCount, arrContent: Block.arrContent, // TrCount: Block.TrCount, arrContent: Block.arrContent,
}; // };
return Result; // return Result;
}; // };
var AddrLength = 16; var AddrLength = 16;
function GetHexFromAddresShort(Hash) { function GetHexFromAddresShort(Hash) {
return global.GetHexFromAddres(Hash).substr(0, AddrLength); return global.GetHexFromAddres(Hash).substr(0, AddrLength);
}; };
function GetHexFromStrShort(Str) { // function GetHexFromStrShort(Str) {
if (Str === undefined) // if (Str === undefined)
return Str; // return Str;
else // else
return Str.substr(0, AddrLength); // return Str.substr(0, AddrLength);
}; // };
var glid = 0; var glid = 0;
function GetGUID(Block) { function GetGUID(Block) {
@ -1247,7 +1249,7 @@ function AddMapList(arrLoadedBlocks, type, MapMapLoaded, MainChains?) {
} }
} }
}; };
var MapFileHTML5 = {}; // var MapFileHTML5 = {};
function SendWebFile(response, name?, StrCookie?, bParsing?) { function SendWebFile(response, name?, StrCookie?, bParsing?) {
var type = name.substr(name.length - 4, 4); var type = name.substr(name.length - 4, 4);
@ -1385,21 +1387,21 @@ global.GetFileHTMLFromMarkdown = GetFileHTMLFromMarkdown;
global.GetFileSimple = GetFileSimple; global.GetFileSimple = GetFileSimple;
global.SaveFileSimple = SaveFileSimple; global.SaveFileSimple = SaveFileSimple;
function GetStrTime(now) { // function GetStrTime(now) {
if (!now) // if (!now)
now = global.GetCurrentTime(0); // now = global.GetCurrentTime(0);
var Str = "" + now.getHours().toStringZ(2); // var Str = "" + now.getHours().toStringZ(2);
Str = Str + ":" + now.getMinutes().toStringZ(2); // Str = Str + ":" + now.getMinutes().toStringZ(2);
Str = Str + ":" + now.getSeconds().toStringZ(2); // Str = Str + ":" + now.getSeconds().toStringZ(2);
return Str; // return Str;
}; // };
function OnGetData(arg) { function OnGetData(arg) {
var response = { // var response = {
end: function() { // end: function() {
}, writeHead: function() { // }, writeHead: function() {
}, // },
}; // };
var Path = arg.path; var Path = arg.path;
var obj = arg.obj; var obj = arg.obj;
if (Path.substr(0, 1) === "/") if (Path.substr(0, 1) === "/")
@ -1573,18 +1575,18 @@ if (global.ELECTRON) {
} }
exports.SendData = OnGetData; exports.SendData = OnGetData;
function RunConsole(StrRun) { // function RunConsole(StrRun) {
var Str = fs.readFileSync("./EXPERIMENTAL/!run-console.js", { encoding: "utf8" }); // var Str = fs.readFileSync("./EXPERIMENTAL/!run-console.js", { encoding: "utf8" });
if (StrRun) // if (StrRun)
Str += "\n" + StrRun; // Str += "\n" + StrRun;
try { // try {
var ret = eval(Str); // var ret = eval(Str);
} // }
catch (e) { // catch (e) {
ret = e.message + "\n" + e.stack; // ret = e.message + "\n" + e.stack;
} // }
return ret; // return ret;
}; // };
var WebWalletUser = {}; var WebWalletUser = {};
function GetUserContext(Params) { function GetUserContext(Params) {

View File

@ -31,7 +31,7 @@ global.RBTree = require('bintrees').RBTree;
global.ntpClient = require('ntp-client'); global.ntpClient = require('ntp-client');
global.Stun = require('stun'); global.Stun = require('stun');
global.ZIP = require("zip"); global.ZIP = require("zip");
var strOS = os.platform() + "_" + os.arch(); // var strOS = os.platform() + "_" + os.arch();
if (!global.secp256k1) { if (!global.secp256k1) {
global.secp256k1 = require('secp256k1'); global.secp256k1 = require('secp256k1');
} }
@ -56,16 +56,16 @@ global.GetCurrentBlockNumByTime = function GetCurrentBlockNumByTime() {
return StartBlockNum; return StartBlockNum;
}; };
global.DelDir = function(Path) { global.DelDir = function(Path) {
if (Path.substr(Path.length - 1, 1) === "/") if (Path.substr(Path.length - 1, 1) === "/") {
Path = Path.substr(0, Path.length - 1); Path = Path.substr(0, Path.length - 1);
}
if (fs.existsSync(Path)) { if (fs.existsSync(Path)) {
var arr = fs.readdirSync(Path); var arr = fs.readdirSync(Path);
for (var i = 0; i < arr.length; i++) { for (var i = 0; i < arr.length; i++) {
var name = Path + "/" + arr[i]; var name = Path + "/" + arr[i];
if (fs.statSync(name).isDirectory()) { if (fs.statSync(name).isDirectory()) {
global.DelDir(name); global.DelDir(name);
} } else {
else {
if (name.right(9) == "const.lst") if (name.right(9) == "const.lst")
continue; continue;
if (name.right(7) == "log.log") if (name.right(7) == "log.log")
@ -82,7 +82,7 @@ global.SliceArr = function(arr, start, end) {
} }
return ret; return ret;
}; };
var nRand = Math.floor(123 + Math.random() * 1000); // var nRand = Math.floor(123 + Math.random() * 1000);
function random(max) { function random(max) {
return Math.floor(Math.random() * max); return Math.floor(Math.random() * max);

View File

@ -12,31 +12,30 @@ import * as fs from 'fs'
import './constant' import './constant'
import './log-strict' import './log-strict'
let { var file_name_info = global.GetDataPath("info.log")
START_PORT_NUMBER, var file_name_infoPrev = global.GetDataPath("info-prev.log");
CheckSizeLogFile, global.CheckSizeLogFile(file_name_info, file_name_infoPrev);
} = global var file_name_log = global.GetDataPath("log.log")
var file_name_logPrev = global.GetDataPath("log-prev.log");
var file_name_info = global.GetDataPath("info.log"), file_name_infoPrev = global.GetDataPath("info-prev.log"); global.CheckSizeLogFile(file_name_log, file_name_logPrev);
CheckSizeLogFile(file_name_info, file_name_infoPrev); var file_name_log_web = global.GetDataPath("web.log")
var file_name_log = global.GetDataPath("log.log"), file_name_logPrev = global.GetDataPath("log-prev.log"); var file_name_log_webPrev = global.GetDataPath("web-prev.log");
CheckSizeLogFile(file_name_log, file_name_logPrev); global.CheckSizeLogFile(file_name_log_web, file_name_log_webPrev);
var file_name_log_web = global.GetDataPath("web.log"), file_name_log_webPrev = global.GetDataPath("web-prev.log"); var StartStatTime, file_name_error = global.GetDataPath("err.log")
CheckSizeLogFile(file_name_log_web, file_name_log_webPrev); var file_name_errorPrev = global.GetDataPath("err-prev.log");
var StartStatTime, file_name_error = global.GetDataPath("err.log"), file_name_errorPrev = global.GetDataPath("err-prev.log");
function ToLogFile(e, t, r?) { function ToLogFile(e, t, r?) {
t instanceof Error && (t = t.message + "\n" + t.stack), global.START_SERVER || (t = global.PROCESS_NAME + ": " + t), "MAIN" !== global.PROCESS_NAME && process.send ? process.send({ t instanceof Error && (t = t.message + "\n" + t.stack), global.START_SERVER || (t = global.PROCESS_NAME + ": " + t), "MAIN" !== global.PROCESS_NAME && process.send ? process.send({
cmd: "log", cmd: "log",
message: t message: t
}) : (console.log(START_PORT_NUMBER + ": " + global.GetStrOnlyTime() + ": " + t), r || SaveToLogFileSync(e, t)); }) : (console.log(global.START_PORT_NUMBER + ": " + global.GetStrOnlyTime() + ": " + t), r || SaveToLogFileSync(e, t));
}; };
function ToLogClient(e, t, r) { function ToLogClient(e, t, r) {
let ArrLogClient = global.ArrLogClient; let ArrLogClient = global.ArrLogClient;
e && (ToLogFile(file_name_log, e), t || (t = ""), ArrLogClient.push({ text: global.GetStrOnlyTime() + " " + e, key: t, final: r }), 13 < ArrLogClient.length && ArrLogClient.shift()); e && (ToLogFile(file_name_log, e), t || (t = ""), ArrLogClient.push({ text: global.GetStrOnlyTime() + " " + e, key: t, final: r }), 13 < ArrLogClient.length && ArrLogClient.shift());
}; };
CheckSizeLogFile(file_name_error, file_name_errorPrev), global.ToLog = function(e, t) { global.CheckSizeLogFile(file_name_error, file_name_errorPrev), global.ToLog = function(e, t) {
void 0 === t && (t = 1), t && t > global.LOG_LEVEL || (global.ALL_LOG_TO_CLIENT ? ToLogClient(e, void 0, void 0) : ToLogFile(file_name_log, void 0 === t && (t = 1), t && t > global.LOG_LEVEL || (global.ALL_LOG_TO_CLIENT ? ToLogClient(e, void 0, void 0) : ToLogFile(file_name_log,
e)); e));
}, global.ToLogWeb = function(e) { }, global.ToLogWeb = function(e) {
@ -70,11 +69,11 @@ function ResizeArrAvg(e) {
return t; return t;
}; };
function ResizeArr(e) { // function ResizeArr(e) {
for (var t = [], r = Math.trunc(e.length / 2), o = 0; o < r; o++) // for (var t = [], r = Math.trunc(e.length / 2), o = 0; o < r; o++)
t[o] = e[2 * o]; // t[o] = e[2 * o];
return t; // return t;
}; // };
function GetDiagramData(e, t) { function GetDiagramData(e, t) {
var r, o = 2 * MAX_STAT_PERIOD + 2; var r, o = 2 * MAX_STAT_PERIOD + 2;
@ -115,20 +114,20 @@ function CopyStatInterval(e, t) {
r[n] = o[n], "MAX:" === n.substr(0, 4) && (o[n] = 0); r[n] = o[n], "MAX:" === n.substr(0, 4) && (o[n] = 0);
}; };
function SaveToLogFileAsync(e, o) { // function SaveToLogFileAsync(e, o) {
fs.open(e, "a", void 0, function(e, r) { // fs.open(e, "a", void 0, function(e, r) {
if (e) // if (e)
console.log("Ошибка открытия лог-файла ошибок"); // console.log("Ошибка открытия лог-файла ошибок");
else { // else {
var t = global.GetStrTime() + " : " + o + "\r\n"; // var t = global.GetStrTime() + " : " + o + "\r\n";
fs.write(r, t, null, "utf8", function(e, t) { // fs.write(r, t, null, "utf8", function(e, t) {
e ? console.log("Ошибка записи в лог-файл ошибок!") : fs.close(r, function(e) { // e ? console.log("Ошибка записи в лог-файл ошибок!") : fs.close(r, function(e) {
e && console.log(e); // e && console.log(e);
}); // });
}); // });
} // }
}); // });
}; // };
function SaveToLogFileSync(e, t) { function SaveToLogFileSync(e, t) {
try { try {
@ -143,29 +142,35 @@ global.PrepareStatEverySecond = function() {
CurStatIndex++; CurStatIndex++;
var e = GetCurrentStatIndex(); var e = GetCurrentStatIndex();
CopyStatInterval(CONTEXT_STATS, e), CopyStatInterval(CONTEXT_ERRORS, e); CopyStatInterval(CONTEXT_STATS, e), CopyStatInterval(CONTEXT_ERRORS, e);
}, global.TO_ERROR_LOG = function(e, t, r, o, n, a) { }
global.TO_ERROR_LOG = function(e, t, r, o, n, a) {
r instanceof Error && (r = r.message + "\n"), "rinfo" === o ? r += " from: " + n.address + ":" + n.port : "node" === o && (r += " from: " + n.ip + ":" + n.port); r instanceof Error && (r = r.message + "\n"), "rinfo" === o ? r += " from: " + n.address + ":" + n.port : "node" === o && (r += " from: " + n.ip + ":" + n.port);
var l = e + ":" + t; var l = e + ":" + t;
global.ToError(" ==ERROR== " + l + " " + r), AddToStatContext(CONTEXT_ERRORS, l), global.ADD_TO_STAT("ERRORS"); global.ToError(" ==ERROR== " + l + " " + r), AddToStatContext(CONTEXT_ERRORS, l), global.ADD_TO_STAT("ERRORS");
}, global.HASH_RATE = 0, global.ADD_HASH_RATE = function(e) { }
global.HASH_RATE = 0, global.ADD_HASH_RATE = function(e) {
e /= 1e6, global.HASH_RATE += e, global.ADD_TO_STAT("HASHRATE", e); e /= 1e6, global.HASH_RATE += e, global.ADD_TO_STAT("HASHRATE", e);
}, global.GET_STAT = function(e) { }
global.GET_STAT = function(e) {
var t = CONTEXT_STATS.Total[e]; var t = CONTEXT_STATS.Total[e];
return t || (t = 0), t; return t || (t = 0), t;
}, global.ADD_TO_STAT_TIME = function(e, t, r) { }
global.ADD_TO_STAT_TIME = function(e, t, r) {
if (global.STAT_MODE) { if (global.STAT_MODE) {
if (r && 2 !== global.STAT_MODE) if (r && 2 !== global.STAT_MODE)
return; return;
var o = process.hrtime(t), n = 1e3 * o[0] + o[1] / 1e6; var o = process.hrtime(t), n = 1e3 * o[0] + o[1] / 1e6;
global.ADD_TO_STAT(e, n); global.ADD_TO_STAT(e, n);
} }
}, global.ADD_TO_STAT = function(e, t, r) { }
global.ADD_TO_STAT = function(e, t, r) {
if (global.STAT_MODE) { if (global.STAT_MODE) {
if (r && 2 !== global.STAT_MODE) if (r && 2 !== global.STAT_MODE)
return; return;
AddToStatContext(CONTEXT_STATS, e, t); AddToStatContext(CONTEXT_STATS, e, t);
} }
}, global.GET_STATDIAGRAMS = function(e) { }
global.GET_STATDIAGRAMS = function(e) {
global.GetCurrentTime(); global.GetCurrentTime();
var t = GetCurrentStatIndex(); var t = GetCurrentStatIndex();
if (!e || !e.length) if (!e || !e.length)
@ -195,7 +200,8 @@ global.PrepareStatEverySecond = function() {
i.AvgValue = g, i.steptime = _, i.arr = T.slice(1); i.AvgValue = g, i.steptime = _, i.arr = T.slice(1);
} }
return r; return r;
}, global.GET_STATS = function(e) { }
global.GET_STATS = function(e) {
var t = global.GetCurrentTime(), r = GetCurrentStatIndex(); var t = global.GetCurrentTime(), r = GetCurrentStatIndex();
return { return {
stats: { stats: {
@ -206,23 +212,28 @@ global.PrepareStatEverySecond = function() {
r, 600) r, 600)
}, period: (t - StartStatTime) / 1e3, Confirmation: [] }, period: (t - StartStatTime) / 1e3, Confirmation: []
}; };
}, global.StartCommonStat = function() { }
for (var e in CONTEXT_STATS.Total) global.StartCommonStat = function() {
for (var _ in CONTEXT_STATS.Total)
return; return;
global.ClearCommonStat(); global.ClearCommonStat();
}, global.ClearCommonStat = function() { }
global.ClearCommonStat = function() {
StartStatTime = void (CurStatIndex = 0), CONTEXT_STATS = { Total: {}, Interval: [] }, CONTEXT_ERRORS = { Total: {}, Interval: [] }, StartStatTime = void (CurStatIndex = 0), CONTEXT_STATS = { Total: {}, Interval: [] }, CONTEXT_ERRORS = { Total: {}, Interval: [] },
global.HASH_RATE = 0, global.SERVER.ClearStat(); global.HASH_RATE = 0, global.SERVER.ClearStat();
}, global.ResizeArrAvg = ResizeArrAvg, global.ResizeArrMax = ResizeArrMax, global.DEBUG_MODE ? global.TO_DEBUG_LOG = function(e, t, r, o) { }
global.ResizeArrAvg = ResizeArrAvg, global.ResizeArrMax = ResizeArrMax, global.DEBUG_MODE ? global.TO_DEBUG_LOG = function(e, t, r, o) {
global.DEBUG_MODE && ("rinfo" === t && (e += " from: " + r.address + ":" + r.port + " - " + o.length), global.ToLog(e)); global.DEBUG_MODE && ("rinfo" === t && (e += " from: " + r.address + ":" + r.port + " - " + o.length), global.ToLog(e));
} : global.TO_DEBUG_LOG = function(e, t, r, o) { } : global.TO_DEBUG_LOG = function(e, t, r, o) {
}, global.GetStrOnlyTime = function(e) { }
global.GetStrOnlyTime = function(e) {
if (!global.GetCurrentTime) if (!global.GetCurrentTime)
return ":::"; return ":::";
e || (e = global.GetCurrentTime()); e || (e = global.GetCurrentTime());
var t = "" + e.getHours().toStringZ(2); var t = "" + e.getHours().toStringZ(2);
return t = (t = (t = t + ":" + e.getMinutes().toStringZ(2)) + ":" + e.getSeconds().toStringZ(2)) + "." + e.getMilliseconds().toStringZ(3); return t = (t = (t = t + ":" + e.getMinutes().toStringZ(2)) + ":" + e.getSeconds().toStringZ(2)) + "." + e.getMilliseconds().toStringZ(3);
}, global.GetStrTime = function(e) { }
global.GetStrTime = function(e) {
if (!global.GetCurrentTime) if (!global.GetCurrentTime)
return ":::"; return ":::";
e || (e = global.GetCurrentTime()); e || (e = global.GetCurrentTime());

View File

@ -10,7 +10,7 @@
"use strict"; "use strict";
import net = require("net"); import net = require("net");
import dgram = require("dgram"); // import dgram = require("dgram");
import * as crypto from 'crypto'; import * as crypto from 'crypto';
import "./library" import "./library"
import "./crypto-library" import "./crypto-library"
@ -19,7 +19,7 @@ global.BUF_TYPE = 1;
global.STR_TYPE = 2; global.STR_TYPE = 2;
global.MAX_STR_BUF_DATA = 200; global.MAX_STR_BUF_DATA = 200;
global.MAX_CONNECTION_ACTIVE = 40; global.MAX_CONNECTION_ACTIVE = 40;
var MAX_CONNECTION_ANOTHER = 40; // var MAX_CONNECTION_ANOTHER = 40;
const TRAFIC_LIMIT_NODE_1S = global.MAX_BLOCK_SIZE * 1.25; const TRAFIC_LIMIT_NODE_1S = global.MAX_BLOCK_SIZE * 1.25;
const TRAFIC_LIMIT_1S = 8 * TRAFIC_LIMIT_NODE_1S; const TRAFIC_LIMIT_1S = 8 * TRAFIC_LIMIT_NODE_1S;
global.STAT_PERIOD = global.CONSENSUS_PERIOD_TIME / 5; global.STAT_PERIOD = global.CONSENSUS_PERIOD_TIME / 5;
@ -715,13 +715,13 @@ export default class CTransport extends require("./connect")
} }
DoSendBuf() { DoSendBuf() {
this.RecalcSendStatictic() this.RecalcSendStatictic()
var CountNodeSend = 0; // var CountNodeSend = 0;
var it = this.ActualNodes.iterator(), Node; var it = this.ActualNodes.iterator(), Node;
NEXT_NODE: NEXT_NODE:
while ((Node = it.next()) !== null) while ((Node = it.next()) !== null)
if (Node.Socket && Node.ConnectStatus() === 100) if (Node.Socket && Node.ConnectStatus() === 100)
if (Node.BufWrite.length > 0) { if (Node.BufWrite.length > 0) {
CountNodeSend++ // CountNodeSend++
var CountSend = Math.min(BUF_PACKET_SIZE, Node.BufWrite.length); var CountSend = Math.min(BUF_PACKET_SIZE, Node.BufWrite.length);
var Value = CountSend / 1024; var Value = CountSend / 1024;
if (global.LIMIT_SEND_TRAFIC) { if (global.LIMIT_SEND_TRAFIC) {

View File

@ -30,7 +30,7 @@ function RunOnUpdate() {
function CreateHeadersHash100() { function CreateHeadersHash100() {
global.ToLog("CreateHeadersHash100"); global.ToLog("CreateHeadersHash100");
const DBRow = require("./db/db-row"); // const DBRow = require("./db/db-row");
global.UpdateMode = 1; global.UpdateMode = 1;
var DB = global.SERVER.DBHeader100; var DB = global.SERVER.DBHeader100;
var Num = 0; var Num = 0;

View File

@ -9,12 +9,12 @@
*/ */
"use strict"; "use strict";
const fs = require('fs'); // const fs = require('fs');
import * as crypto from 'crypto'; import * as crypto from 'crypto';
require("./library"); require("./library");
require("./crypto-library"); require("./crypto-library");
const WalletPath = "WALLET"; const WalletPath = "WALLET";
const DBRow = require("./db/db-row"); // const DBRow = require("./db/db-row");
const CONFIG_NAME = global.GetDataPath(WalletPath + "/config.lst"); const CONFIG_NAME = global.GetDataPath(WalletPath + "/config.lst");
class CApp { class CApp {
Password Password
@ -25,7 +25,7 @@ class CApp {
PubKeyArr PubKeyArr
constructor() { constructor() {
global.CheckCreateDir(global.GetDataPath(WalletPath)) global.CheckCreateDir(global.GetDataPath(WalletPath))
var bReadOnly = (global.PROCESS_NAME !== "TX"); // var bReadOnly = (global.PROCESS_NAME !== "TX");
this.Password = "" this.Password = ""
this.WalletOpen = undefined this.WalletOpen = undefined
var Params = global.LoadParams(CONFIG_NAME, undefined); var Params = global.LoadParams(CONFIG_NAME, undefined);

View File

@ -12,7 +12,7 @@ import '../core/constant'
global.PROCESS_NAME = "MAIN"; global.PROCESS_NAME = "MAIN";
import fs = require('fs'); import fs = require('fs');
import os = require('os'); import os = require('os');
import path = require('path') // import path = require('path')
import * as crypto from 'crypto'; import * as crypto from 'crypto';
global.START_SERVER = 1; global.START_SERVER = 1;
@ -366,7 +366,7 @@ var StartCheckMining = 0;
global.MiningPaused = 0; global.MiningPaused = 0;
var ProcessMemorySize = 0; var ProcessMemorySize = 0;
global.ArrMiningWrk = []; global.ArrMiningWrk = [];
var BlockMining; // var BlockMining;
if (global.ADDRLIST_MODE) { if (global.ADDRLIST_MODE) {
// @ts-ignore // @ts-ignore
return; return;
@ -503,7 +503,7 @@ function SetCalcPOW(Block, cmd) {
return; return;
if (ArrMiningWrk.length !== global.GetCountMiningCPU()) if (ArrMiningWrk.length !== global.GetCountMiningCPU())
return; return;
BlockMining = Block; // BlockMining = Block;
for (var i = 0; i < ArrMiningWrk.length; i++) { for (var i = 0; i < ArrMiningWrk.length; i++) {
var CurWorker = ArrMiningWrk[i]; var CurWorker = ArrMiningWrk[i];
if (!CurWorker.bOnline) if (!CurWorker.bOnline)
@ -654,7 +654,7 @@ function RunOnce() {
}, 10000); }, 10000);
} }
}; };
var glPortDebug = 49800; // var glPortDebug = 49800;
function Fork(Path, ArrArgs?) { function Fork(Path, ArrArgs?) {
const child_process = require('child_process'); const child_process = require('child_process');
@ -674,7 +674,7 @@ function Fork(Path, ArrArgs?) {
ArrArgs.push("NOALIVE"); ArrArgs.push("NOALIVE");
if (global.DEV_MODE) if (global.DEV_MODE)
ArrArgs.push("DEV_MODE"); ArrArgs.push("DEV_MODE");
glPortDebug++; // glPortDebug++;
var execArgv = []; var execArgv = [];
var Worker = child_process.fork(Path, ArrArgs, { execArgv: execArgv }); var Worker = child_process.fork(Path, ArrArgs, { execArgv: execArgv });
return Worker; return Worker;

View File

@ -111,7 +111,7 @@ function GETBLOCKHEADER100(msg) {
return; return;
var EndNum100 = BlockNum / 100; var EndNum100 = BlockNum / 100;
var LoadHash100 = Data.Hash; var LoadHash100 = Data.Hash;
var Hash100; // var Hash100;
var Count = Data.Count; var Count = Data.Count;
if (!Count || Count < 0 || !EndNum100) if (!Count || Count < 0 || !EndNum100)
return; return;
@ -228,8 +228,8 @@ function GETREST(msg) {
var ProofArrR = []; var ProofArrR = [];
var ArrRest = []; var ArrRest = [];
if (nResult) { if (nResult) {
var WorkStruct = {}; // var WorkStruct = {};
var WorkFormat = global.DApps.Accounts.FORMAT_ACCOUNT_ROW; // var WorkFormat = global.DApps.Accounts.FORMAT_ACCOUNT_ROW;
var WorkFormatLength = global.DApps.Accounts.SIZE_ACCOUNT_ROW; var WorkFormatLength = global.DApps.Accounts.SIZE_ACCOUNT_ROW;
var Max = global.DApps.Accounts.DBState.GetMaxNum(); var Max = global.DApps.Accounts.DBState.GetMaxNum();
var LengthAccount = Data.Count; var LengthAccount = Data.Count;

View File

@ -122,7 +122,7 @@ function DoTXProcess() {
var StartTime = Date.now(); var StartTime = Date.now();
if (global.bShowDetail) if (global.bShowDetail)
global.ToLog("BlockMin: " + BlockMin.BlockNum + " LastBlockNum=" + LastBlockNum); global.ToLog("BlockMin: " + BlockMin.BlockNum + " LastBlockNum=" + LastBlockNum);
var CountTX = 0; // var CountTX = 0;
for (var Num = BlockMin.BlockNum; Num < BlockMin.BlockNum + 200; Num++) { for (var Num = BlockMin.BlockNum; Num < BlockMin.BlockNum + 200; Num++) {
var EndTime = Date.now(); var EndTime = Date.now();
var Delta = EndTime - StartTime; var Delta = EndTime - StartTime;
@ -155,7 +155,7 @@ function DoTXProcess() {
global.SERVER.BlockProcessTX(Block); global.SERVER.BlockProcessTX(Block);
if (Num % 100000 === 0) if (Num % 100000 === 0)
global.ToLog("CALC: " + Num); global.ToLog("CALC: " + Num);
CountTX++; // CountTX++;
if (global.bShowDetail) if (global.bShowDetail)
global.ToLog(" CALC: " + Num + " SumHash: " + global.GetHexFromArr(Block.SumHash).substr(0, 12)); global.ToLog(" CALC: " + Num + " SumHash: " + global.GetHexFromArr(Block.SumHash).substr(0, 12));
BlockTree.SaveValue(Block.BlockNum, { BlockNum: Block.BlockNum, SumHash: Block.SumHash }); BlockTree.SaveValue(Block.BlockNum, { BlockNum: Block.BlockNum, SumHash: Block.SumHash });
@ -330,7 +330,8 @@ function TXWriteAccHash() {
var Item = global.DApps.Smart.DBSmart.Read(num); var Item = global.DApps.Smart.DBSmart.Read(num);
if (!Item) if (!Item)
break; break;
var Body = global.BufLib.GetBufferFromObject(Item, global.DApps.Smart.FORMAT_ROW, 20000, {}); // var Body =
global.BufLib.GetBufferFromObject(Item, global.DApps.Smart.FORMAT_ROW, 20000, {});
global.DApps.Smart.DBSmartWrite(Item); global.DApps.Smart.DBSmartWrite(Item);
} }
global.DApps.Accounts.CalcMerkleTree(1); global.DApps.Accounts.CalcMerkleTree(1);

View File

@ -9,7 +9,7 @@
*/ */
import * as crypto from 'crypto' import * as crypto from 'crypto'
import * as http from 'http' import * as http from 'http'
import * as net from 'net' // import * as net from 'net'
import * as url from 'url' import * as url from 'url'
import * as fs from 'fs' import * as fs from 'fs'
import * as querystring from 'querystring' import * as querystring from 'querystring'
@ -106,23 +106,13 @@ process.on('message', function(msg) {
var RedirectServer; var RedirectServer;
var HostingServer; var HostingServer;
let {
ToLogWeb,
CHECK_STOP_CHILD_PROCESS,
ToError,
ToLog,
TO_ERROR_LOG,
PrepareStatEverySecond,
ToLogTrace
} = global
function Exit() { function Exit() {
ToLogWeb("=Exit1="); global.ToLogWeb("=Exit1=");
if (RedirectServer) if (RedirectServer)
RedirectServer.close(); RedirectServer.close();
if (HostingServer) if (HostingServer)
HostingServer.close(); HostingServer.close();
ToLogWeb("=Exit2="); global.ToLogWeb("=Exit2=");
process.exit(0); process.exit(0);
}; };
@ -130,7 +120,7 @@ function CheckAlive() {
if (global.NOALIVE) if (global.NOALIVE)
return; return;
var Delta = Date.now() - LastAlive; var Delta = Date.now() - LastAlive;
if (Delta > CHECK_STOP_CHILD_PROCESS) { if (Delta > global.CHECK_STOP_CHILD_PROCESS) {
Exit(); Exit();
return; return;
} }
@ -138,7 +128,7 @@ function CheckAlive() {
process.on('uncaughtException', function(err) { process.on('uncaughtException', function(err) {
global.ToError(err.stack); global.ToError(err.stack);
global.ToLog(err.stack); global.ToLog(err.stack);
TO_ERROR_LOG("HOSTING", 777, err); global.TO_ERROR_LOG("HOSTING", 777, err);
global.ToLog("-----------------HOSTING EXIT------------------", 0); global.ToLog("-----------------HOSTING EXIT------------------", 0);
process.exit(); process.exit();
}); });
@ -147,7 +137,7 @@ process.on('error' as any, function(err: TeraError) {
global.ToLog(err.stack); global.ToLog(err.stack);
}); });
if (!global.HTTP_HOSTING_PORT) { if (!global.HTTP_HOSTING_PORT) {
ToLogTrace("global.HTTP_HOSTING_PORT=" + global.HTTP_HOSTING_PORT); global.ToLogTrace("global.HTTP_HOSTING_PORT=" + global.HTTP_HOSTING_PORT);
process.exit(); process.exit();
} }
var CServerDB = require("../core/db/block-db"); var CServerDB = require("../core/db/block-db");
@ -159,18 +149,12 @@ global.HTTP_PORT_NUMBER = 0;
require("../core/html-server"); require("../core/html-server");
require("../core/transaction-validator"); require("../core/transaction-validator");
global.STAT_MODE = 1; global.STAT_MODE = 1;
setInterval(PrepareStatEverySecond, 1000); setInterval(global.PrepareStatEverySecond, 1000);
var IndexName = "index.html"; var IndexName = "index.html";
let {
GetDataPath,
CheckCreateDir,
LoadParams,
SaveParams,
ADD_TO_STAT
} = global
if (global.HTTPS_HOSTING_DOMAIN) { if (global.HTTPS_HOSTING_DOMAIN) {
var file_sert = global.GetDataPath("sertif.lst"); var file_sert = global.GetDataPath("sertif.lst");
CheckCreateDir(global.GetDataPath("tmp")); global.CheckCreateDir(global.GetDataPath("tmp"));
var greenlock = require('greenlock').create({ var greenlock = require('greenlock').create({
version: 'draft-12', server: 'https://acme-v02.api.letsencrypt.org/directory', configDir: global.GetDataPath('tmp'), version: 'draft-12', server: 'https://acme-v02.api.letsencrypt.org/directory', configDir: global.GetDataPath('tmp'),
}); });
@ -182,7 +166,7 @@ if (global.HTTPS_HOSTING_DOMAIN) {
RedirectServer.listen(80); RedirectServer.listen(80);
var GetNewSert = 1; var GetNewSert = 1;
if (fs.existsSync(file_sert)) { if (fs.existsSync(file_sert)) {
var certs = LoadParams(file_sert, {}); var certs = global.LoadParams(file_sert, {});
var Delta = certs.expiresAt - Date.now(); var Delta = certs.expiresAt - Date.now();
if (Delta >= 10 * 24 * 3600 * 1000) { if (Delta >= 10 * 24 * 3600 * 1000) {
global.ToLog("USE EXIST SERT. ExpiresAt: " + new Date(certs.expiresAt)); global.ToLog("USE EXIST SERT. ExpiresAt: " + new Date(certs.expiresAt));
@ -196,7 +180,7 @@ if (global.HTTPS_HOSTING_DOMAIN) {
global.ToLog("Start get new SERT", 0); global.ToLog("Start get new SERT", 0);
var opts = { domains: [global.HTTPS_HOSTING_DOMAIN], email: 'progr76@gmail.com', agreeTos: true, communityMember: true, }; var opts = { domains: [global.HTTPS_HOSTING_DOMAIN], email: 'progr76@gmail.com', agreeTos: true, communityMember: true, };
greenlock.register(opts).then(function(certs) { greenlock.register(opts).then(function(certs) {
SaveParams(file_sert, certs); global.SaveParams(file_sert, certs);
var tlsOptions = { key: certs.privkey, cert: certs.cert + '\r\n' + certs.chain }; var tlsOptions = { key: certs.privkey, cert: certs.cert + '\r\n' + certs.chain };
HostingServer = require('https').createServer(tlsOptions, MainHTTPFunction); HostingServer = require('https').createServer(tlsOptions, MainHTTPFunction);
RunListenServer(); RunListenServer();
@ -219,7 +203,7 @@ function MainHTTPFunction(request, response) {
var DataURL = url.parse(request.url); var DataURL = url.parse(request.url);
var Params = querystring.parse(DataURL.query); var Params = querystring.parse(DataURL.query);
var Path = querystring.unescape(DataURL.pathname); var Path = querystring.unescape(DataURL.pathname);
ADD_TO_STAT("HTTP_ALL"); global.ADD_TO_STAT("HTTP_ALL");
var Type = request.method; var Type = request.method;
if (Type === "POST") { if (Type === "POST") {
let Response = response; let Response = response;
@ -354,7 +338,7 @@ function DoCommandNew(response, Type, Path, Params) {
} }
Method = ArrPath[2]; Method = ArrPath[2];
} }
ADD_TO_STAT("HTTP:" + Method); global.ADD_TO_STAT("HTTP:" + Method);
var F = Caller[Method]; var F = Caller[Method];
if (F) { if (F) {
response.writeHead(200, { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': "*" }); response.writeHead(200, { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': "*" });
@ -841,7 +825,7 @@ setInterval(function() {
if (!Count) if (!Count)
Count = 1; Count = 1;
var AvgPow = SumPow / Count; var AvgPow = SumPow / Count;
ADD_TO_STAT("MAX:HASH_RATE_B", AvgPow); global.ADD_TO_STAT("MAX:HASH_RATE_B", AvgPow);
} }
var Count = global.COUNT_BLOCK_PROOF + 16 - 1; var Count = global.COUNT_BLOCK_PROOF + 16 - 1;
if (MaxNumBlockDB > Count) { if (MaxNumBlockDB > Count) {
@ -852,8 +836,7 @@ setInterval(function() {
require("./api-exchange.js"); require("./api-exchange.js");
try { try {
require("../SITE/JS/web-addon.js"); require("../SITE/JS/web-addon.js");
} } catch (e) {
catch (e) {
} }
global.LoadBlockFromNetwork = function(Params, F) { global.LoadBlockFromNetwork = function(Params, F) {
global.ToLog("RUN: LoadBlockFromNetwork:" + Params.BlockNum, 2); global.ToLog("RUN: LoadBlockFromNetwork:" + Params.BlockNum, 2);

View File

@ -82,13 +82,6 @@ global.global.FORMAT_ACCOUNT_HASH3 = "{\
SmartHash:buffer32,\ SmartHash:buffer32,\
SmartCount:uint,\ SmartCount:uint,\
}"; }";
let {
ToLog,
shaarr,
UpdateMerklTree,
ToError,
SERVER
} = global
class MerkleDBRow extends DBRow { class MerkleDBRow extends DBRow {
private MerkleTree private MerkleTree
@ -120,7 +113,7 @@ class MerkleDBRow extends DBRow {
} }
} }
this.MerkleTree.RecalcCount = 0 this.MerkleTree.RecalcCount = 0
UpdateMerklTree(this.MerkleTree, this.MerkleCalc, 0) global.UpdateMerklTree(this.MerkleTree, this.MerkleCalc, 0)
this.MerkleCalc = {} this.MerkleCalc = {}
return this.MerkleTree.Root; return this.MerkleTree.Root;
} }
@ -590,7 +583,7 @@ class AccountApp extends require("./dapp")
power = Tr.power power = Tr.power
} }
else { else {
power = global.GetPowPower(shaarr(Body)) power = global.GetPowPower(global.shaarr(Body))
} }
if (global.TEST_NETWORK && BlockNum >= 3290000) { if (global.TEST_NETWORK && BlockNum >= 3290000) {
CheckMinPower = 0 CheckMinPower = 0
@ -1408,23 +1401,23 @@ global.DAppByType[TYPE_DEPRECATED_TRANSFER2] = App;
global.DAppByType[TYPE_TRANSACTION_TRANSFER] = App; global.DAppByType[TYPE_TRANSACTION_TRANSFER] = App;
global.DAppByType[global.TYPE_TRANSACTION_ACC_HASH] = App; global.DAppByType[global.TYPE_TRANSACTION_ACC_HASH] = App;
function TestStateFiles(Size, Format) { // function TestStateFiles(Size, Format) {
return; // return;
if (global.PROCESS_NAME !== "MAIN") // if (global.PROCESS_NAME !== "MAIN")
return; // return;
var DBState1 = new DBRow("state-ok", Size, Format, 0); // var DBState1 = new DBRow("state-ok", Size, Format, 0);
var DBState2 = new DBRow("state-no", Size, Format, 0); // var DBState2 = new DBRow("state-no", Size, Format, 0);
for (var Num = 0; 1; Num++) { // for (var Num = 0; 1; Num++) {
var Item1 = DBState1.Read(Num); // var Item1 = DBState1.Read(Num);
var Item2 = DBState2.Read(Num); // var Item2 = DBState2.Read(Num);
if (!Item1 && !Item2) // if (!Item1 && !Item2)
break; // break;
var Str1 = JSON.stringify(Item1); // var Str1 = JSON.stringify(Item1);
var Str2 = JSON.stringify(Item2); // var Str2 = JSON.stringify(Item2);
if (Str1 !== Str2) { // if (Str1 !== Str2) {
global.ToLog("Err item: " + Num); // global.ToLog("Err item: " + Num);
global.ToLog("1: " + Str1); // global.ToLog("1: " + Str1);
global.ToLog("2: " + Str2); // global.ToLog("2: " + Str2);
} // }
} // }
}; // };

View File

@ -9,7 +9,7 @@
*/ */
"use strict"; "use strict";
import * as fs from 'fs' // import * as fs from 'fs'
class DApp { class DApp {
constructor() { constructor() {
} }
@ -46,16 +46,16 @@ class DApp {
}; };
module.exports = DApp; module.exports = DApp;
function ReqDir(Path) { // function ReqDir(Path) {
if (fs.existsSync(Path)) { // if (fs.existsSync(Path)) {
var arr = fs.readdirSync(Path); // var arr = fs.readdirSync(Path);
for (var i = 0; i < arr.length; i++) { // for (var i = 0; i < arr.length; i++) {
var name = arr[i]; // var name = arr[i];
global.ToLog("Reg: " + name); // global.ToLog("Reg: " + name);
var name2 = Path + "/" + arr[i]; // var name2 = Path + "/" + arr[i];
require(name2); // require(name2);
} // }
} // }
}; // };
global.DApps = {}; global.DApps = {};
global.DAppByType = {}; global.DAppByType = {};

View File

@ -371,7 +371,7 @@ class SmartApp extends require("./dapp")
} }
if (Category) if (Category)
Category = global.global.ParseNum(Category) Category = global.global.ParseNum(Category)
var WasError = 0; // var WasError = 0;
var arr = []; var arr = [];
var Data; var Data;
for (var num = start; true; num++) { for (var num = start; true; num++) {
@ -1178,10 +1178,10 @@ var mask = 0xffffffff;
function MathRandom() { function MathRandom() {
DO(5); DO(5);
function seed(i) { // function seed(i) {
m_w = i; // m_w = i;
m_z = 987654321; // m_z = 987654321;
}; // };
function random() { function random() {
m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask; m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask;

View File

@ -3,6 +3,7 @@
"outDir": "dist", "outDir": "dist",
"allowJs": true, "allowJs": true,
"sourceMap": true, "sourceMap": true,
"noUnusedLocals": true,
"target": "es5" "target": "es5"
}, },
"include": [ "include": [