From 9119f526fec67a5a50b85c5e0e6e319723904bfc Mon Sep 17 00:00:00 2001 From: AbigailDeng Date: Wed, 21 Aug 2024 07:53:30 +0000 Subject: [PATCH] deploy: e5398c2c3ff74e02c831cfe72ac69ffc7e9efd3a --- badges.svg | 8 +- base.css | 224 ++++ block-navigation.js | 87 ++ favicon.png | Bin 0 -> 445 bytes index.html | 176 ++++ prettify.css | 1 + prettify.js | 2 + sort-arrow-sprite.png | Bin 0 -> 138 bytes sorter.js | 196 ++++ src/chain/chainMethod.js.html | 364 +++++++ src/chain/index.html | 131 +++ src/chain/index.js.html | 454 ++++++++ src/contract/contractMethod.js.html | 1006 ++++++++++++++++++ src/contract/index.html | 131 +++ src/contract/index.js.html | 259 +++++ src/index.html | 116 +++ src/index.js.html | 307 ++++++ src/util/bloom.js.html | 379 +++++++ src/util/errors.js.html | 166 +++ src/util/formatters.js.html | 226 ++++ src/util/httpProvider.js.html | 880 ++++++++++++++++ src/util/index.html | 296 ++++++ src/util/keccak.js.html | 148 +++ src/util/keyStore.js.html | 1084 ++++++++++++++++++++ src/util/merkleTree.js.html | 304 ++++++ src/util/proto.js.html | 859 ++++++++++++++++ src/util/requestManage.js.html | 205 ++++ src/util/settings.js.html | 115 +++ src/util/sha256.js.html | 142 +++ src/util/transform.js.html | 838 +++++++++++++++ src/util/utils.js.html | 1483 +++++++++++++++++++++++++++ src/wallet/index.html | 116 +++ src/wallet/index.js.html | 961 +++++++++++++++++ 33 files changed, 11660 insertions(+), 4 deletions(-) create mode 100644 base.css create mode 100644 block-navigation.js create mode 100644 favicon.png create mode 100644 index.html create mode 100644 prettify.css create mode 100644 prettify.js create mode 100644 sort-arrow-sprite.png create mode 100644 sorter.js create mode 100644 src/chain/chainMethod.js.html create mode 100644 src/chain/index.html create mode 100644 src/chain/index.js.html create mode 100644 src/contract/contractMethod.js.html create mode 100644 src/contract/index.html create mode 100644 src/contract/index.js.html create mode 100644 src/index.html create mode 100644 src/index.js.html create mode 100644 src/util/bloom.js.html create mode 100644 src/util/errors.js.html create mode 100644 src/util/formatters.js.html create mode 100644 src/util/httpProvider.js.html create mode 100644 src/util/index.html create mode 100644 src/util/keccak.js.html create mode 100644 src/util/keyStore.js.html create mode 100644 src/util/merkleTree.js.html create mode 100644 src/util/proto.js.html create mode 100644 src/util/requestManage.js.html create mode 100644 src/util/settings.js.html create mode 100644 src/util/sha256.js.html create mode 100644 src/util/transform.js.html create mode 100644 src/util/utils.js.html create mode 100644 src/wallet/index.html create mode 100644 src/wallet/index.js.html diff --git a/badges.svg b/badges.svg index bc800e05..03acca57 100644 --- a/badges.svg +++ b/badges.svg @@ -1,14 +1,14 @@ coverage: 99.04% - + - - + + - + + Code coverage report for All files + + + + + + + + + +
+
+

All files

+
+ +
+ 99.08% + Statements + 974/983 +
+ + +
+ 97.54% + Branches + 477/489 +
+ + +
+ 99.07% + Functions + 214/216 +
+ + +
+ 99.04% + Lines + 933/942 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
src +
+
100%12/12100%2/2100%3/3100%12/12
src/chain +
+
100%98/98100%52/52100%23/23100%96/96
src/contract +
+
99.42%174/17595.83%69/72100%39/3999.41%169/170
src/util +
+
98.72%617/62597.94%334/34198.56%137/13998.65%587/595
src/wallet +
+
100%73/7390.9%20/22100%12/12100%69/69
+
+
+
+ + + + + + + + \ No newline at end of file diff --git a/prettify.css b/prettify.css new file mode 100644 index 00000000..b317a7cd --- /dev/null +++ b/prettify.css @@ -0,0 +1 @@ +.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} diff --git a/prettify.js b/prettify.js new file mode 100644 index 00000000..b3225238 --- /dev/null +++ b/prettify.js @@ -0,0 +1,2 @@ +/* eslint-disable */ +window.PR_SHOULD_USE_CONTINUATION=true;(function(){var h=["break,continue,do,else,for,if,return,while"];var u=[h,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];var p=[u,"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"];var l=[p,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"];var x=[p,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"];var R=[x,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];var r="all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes";var w=[p,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"];var s="caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END";var I=[h,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"];var f=[h,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"];var H=[h,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"];var A=[l,R,w,s+I,f,H];var e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;var C="str";var z="kwd";var j="com";var O="typ";var G="lit";var L="pun";var F="pln";var m="tag";var E="dec";var J="src";var P="atn";var n="atv";var N="nocode";var M="(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*";function k(Z){var ad=0;var S=false;var ac=false;for(var V=0,U=Z.length;V122)){if(!(al<65||ag>90)){af.push([Math.max(65,ag)|32,Math.min(al,90)|32])}if(!(al<97||ag>122)){af.push([Math.max(97,ag)&~32,Math.min(al,122)&~32])}}}}af.sort(function(av,au){return(av[0]-au[0])||(au[1]-av[1])});var ai=[];var ap=[NaN,NaN];for(var ar=0;arat[0]){if(at[1]+1>at[0]){an.push("-")}an.push(T(at[1]))}}an.push("]");return an.join("")}function W(al){var aj=al.source.match(new RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g"));var ah=aj.length;var an=[];for(var ak=0,am=0;ak=2&&ai==="["){aj[ak]=X(ag)}else{if(ai!=="\\"){aj[ak]=ag.replace(/[a-zA-Z]/g,function(ao){var ap=ao.charCodeAt(0);return"["+String.fromCharCode(ap&~32,ap|32)+"]"})}}}}return aj.join("")}var aa=[];for(var V=0,U=Z.length;V=0;){S[ac.charAt(ae)]=Y}}var af=Y[1];var aa=""+af;if(!ag.hasOwnProperty(aa)){ah.push(af);ag[aa]=null}}ah.push(/[\0-\uffff]/);V=k(ah)})();var X=T.length;var W=function(ah){var Z=ah.sourceCode,Y=ah.basePos;var ad=[Y,F];var af=0;var an=Z.match(V)||[];var aj={};for(var ae=0,aq=an.length;ae=5&&"lang-"===ap.substring(0,5);if(am&&!(ai&&typeof ai[1]==="string")){am=false;ap=J}if(!am){aj[ag]=ap}}var ab=af;af+=ag.length;if(!am){ad.push(Y+ab,ap)}else{var al=ai[1];var ak=ag.indexOf(al);var ac=ak+al.length;if(ai[2]){ac=ag.length-ai[2].length;ak=ac-al.length}var ar=ap.substring(5);B(Y+ab,ag.substring(0,ak),W,ad);B(Y+ab+ak,al,q(ar,al),ad);B(Y+ab+ac,ag.substring(ac),W,ad)}}ah.decorations=ad};return W}function i(T){var W=[],S=[];if(T.tripleQuotedStrings){W.push([C,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""])}else{if(T.multiLineStrings){W.push([C,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"])}else{W.push([C,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"])}}if(T.verbatimStrings){S.push([C,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null])}var Y=T.hashComments;if(Y){if(T.cStyleComments){if(Y>1){W.push([j,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,"#"])}else{W.push([j,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"])}S.push([C,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,null])}else{W.push([j,/^#[^\r\n]*/,null,"#"])}}if(T.cStyleComments){S.push([j,/^\/\/[^\r\n]*/,null]);S.push([j,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(T.regexLiterals){var X=("/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/");S.push(["lang-regex",new RegExp("^"+M+"("+X+")")])}var V=T.types;if(V){S.push([O,V])}var U=(""+T.keywords).replace(/^ | $/g,"");if(U.length){S.push([z,new RegExp("^(?:"+U.replace(/[\s,]+/g,"|")+")\\b"),null])}W.push([F,/^\s+/,null," \r\n\t\xA0"]);S.push([G,/^@[a-z_$][a-z_$@0-9]*/i,null],[O,/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],[F,/^[a-z_$][a-z_$@0-9]*/i,null],[G,new RegExp("^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*","i"),null,"0123456789"],[F,/^\\[\s\S]?/,null],[L,/^.[^\s\w\.$@\'\"\`\/\#\\]*/,null]);return g(W,S)}var K=i({keywords:A,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function Q(V,ag){var U=/(?:^|\s)nocode(?:\s|$)/;var ab=/\r\n?|\n/;var ac=V.ownerDocument;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=ac.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Z=S&&"pre"===S.substring(0,3);var af=ac.createElement("LI");while(V.firstChild){af.appendChild(V.firstChild)}var W=[af];function ae(al){switch(al.nodeType){case 1:if(U.test(al.className)){break}if("BR"===al.nodeName){ad(al);if(al.parentNode){al.parentNode.removeChild(al)}}else{for(var an=al.firstChild;an;an=an.nextSibling){ae(an)}}break;case 3:case 4:if(Z){var am=al.nodeValue;var aj=am.match(ab);if(aj){var ai=am.substring(0,aj.index);al.nodeValue=ai;var ah=am.substring(aj.index+aj[0].length);if(ah){var ak=al.parentNode;ak.insertBefore(ac.createTextNode(ah),al.nextSibling)}ad(al);if(!ai){al.parentNode.removeChild(al)}}}break}}function ad(ak){while(!ak.nextSibling){ak=ak.parentNode;if(!ak){return}}function ai(al,ar){var aq=ar?al.cloneNode(false):al;var ao=al.parentNode;if(ao){var ap=ai(ao,1);var an=al.nextSibling;ap.appendChild(aq);for(var am=an;am;am=an){an=am.nextSibling;ap.appendChild(am)}}return aq}var ah=ai(ak.nextSibling,0);for(var aj;(aj=ah.parentNode)&&aj.nodeType===1;){ah=aj}W.push(ah)}for(var Y=0;Y=S){ah+=2}if(V>=ap){Z+=2}}}var t={};function c(U,V){for(var S=V.length;--S>=0;){var T=V[S];if(!t.hasOwnProperty(T)){t[T]=U}else{if(window.console){console.warn("cannot override language handler %s",T)}}}}function q(T,S){if(!(T&&t.hasOwnProperty(T))){T=/^\s*]*(?:>|$)/],[j,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[L,/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);c(g([[F,/^[\s]+/,null," \t\r\n"],[n,/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[[m,/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],[P,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[L,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);c(g([],[[n,/^[\s\S]+/]]),["uq.val"]);c(i({keywords:l,hashComments:true,cStyleComments:true,types:e}),["c","cc","cpp","cxx","cyc","m"]);c(i({keywords:"null,true,false"}),["json"]);c(i({keywords:R,hashComments:true,cStyleComments:true,verbatimStrings:true,types:e}),["cs"]);c(i({keywords:x,cStyleComments:true}),["java"]);c(i({keywords:H,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);c(i({keywords:I,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);c(i({keywords:s,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);c(i({keywords:f,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);c(i({keywords:w,cStyleComments:true,regexLiterals:true}),["js"]);c(i({keywords:r,hashComments:3,cStyleComments:true,multilineStrings:true,tripleQuotedStrings:true,regexLiterals:true}),["coffee"]);c(g([],[[C,/^[\s\S]+/]]),["regex"]);function d(V){var U=V.langExtension;try{var S=a(V.sourceNode);var T=S.sourceCode;V.sourceCode=T;V.spans=S.spans;V.basePos=0;q(U,T)(V);D(V)}catch(W){if("console" in window){console.log(W&&W.stack?W.stack:W)}}}function y(W,V,U){var S=document.createElement("PRE");S.innerHTML=W;if(U){Q(S,U)}var T={langExtension:V,numberLines:U,sourceNode:S};d(T);return S.innerHTML}function b(ad){function Y(af){return document.getElementsByTagName(af)}var ac=[Y("pre"),Y("code"),Y("xmp")];var T=[];for(var aa=0;aa=0){var ah=ai.match(ab);var am;if(!ah&&(am=o(aj))&&"CODE"===am.tagName){ah=am.className.match(ab)}if(ah){ah=ah[1]}var al=false;for(var ak=aj.parentNode;ak;ak=ak.parentNode){if((ak.tagName==="pre"||ak.tagName==="code"||ak.tagName==="xmp")&&ak.className&&ak.className.indexOf("prettyprint")>=0){al=true;break}}if(!al){var af=aj.className.match(/\blinenums\b(?::(\d+))?/);af=af?af[1]&&af[1].length?+af[1]:true:false;if(af){Q(aj,af)}S={langExtension:ah,sourceNode:aj,numberLines:af};d(S)}}}if(X]*(?:>|$)/],[PR.PR_COMMENT,/^<\!--[\s\S]*?(?:-\->|$)/],[PR.PR_PUNCTUATION,/^(?:<[%?]|[%?]>)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-handlebars",/^]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i],[PR.PR_DECLARATION,/^{{[#^>/]?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{&?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{{>?\s*[\w.][^}]*}}}/],[PR.PR_COMMENT,/^{{![^}]*}}/]]),["handlebars","hbs"]);PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[ \t\r\n\f]+/,null," \t\r\n\f"]],[[PR.PR_STRING,/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],[PR.PR_STRING,/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],[PR.PR_KEYWORD,/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],[PR.PR_COMMENT,/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],[PR.PR_COMMENT,/^(?:)/],[PR.PR_LITERAL,/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],[PR.PR_LITERAL,/^#(?:[0-9a-f]{3}){1,2}/i],[PR.PR_PLAIN,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i],[PR.PR_PUNCTUATION,/^[^\s\w\'\"]+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_KEYWORD,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_STRING,/^[^\)\"\']+/]]),["css-str"]); diff --git a/sort-arrow-sprite.png b/sort-arrow-sprite.png new file mode 100644 index 0000000000000000000000000000000000000000..6ed68316eb3f65dec9063332d2f69bf3093bbfab GIT binary patch literal 138 zcmeAS@N?(olHy`uVBq!ia0vp^>_9Bd!3HEZxJ@+%Qh}Z>jv*C{$p!i!8j}?a+@3A= zIAGwzjijN=FBi!|L1t?LM;Q;gkwn>2cAy-KV{dn nf0J1DIvEHQu*n~6U}x}qyky7vi4|9XhBJ7&`njxgN@xNA8m%nc literal 0 HcmV?d00001 diff --git a/sorter.js b/sorter.js new file mode 100644 index 00000000..2bb296a8 --- /dev/null +++ b/sorter.js @@ -0,0 +1,196 @@ +/* eslint-disable */ +var addSorting = (function() { + 'use strict'; + var cols, + currentSort = { + index: 0, + desc: false + }; + + // returns the summary table element + function getTable() { + return document.querySelector('.coverage-summary'); + } + // returns the thead element of the summary table + function getTableHeader() { + return getTable().querySelector('thead tr'); + } + // returns the tbody element of the summary table + function getTableBody() { + return getTable().querySelector('tbody'); + } + // returns the th element for nth column + function getNthColumn(n) { + return getTableHeader().querySelectorAll('th')[n]; + } + + function onFilterInput() { + const searchValue = document.getElementById('fileSearch').value; + const rows = document.getElementsByTagName('tbody')[0].children; + for (let i = 0; i < rows.length; i++) { + const row = rows[i]; + if ( + row.textContent + .toLowerCase() + .includes(searchValue.toLowerCase()) + ) { + row.style.display = ''; + } else { + row.style.display = 'none'; + } + } + } + + // loads the search box + function addSearchBox() { + var template = document.getElementById('filterTemplate'); + var templateClone = template.content.cloneNode(true); + templateClone.getElementById('fileSearch').oninput = onFilterInput; + template.parentElement.appendChild(templateClone); + } + + // loads all columns + function loadColumns() { + var colNodes = getTableHeader().querySelectorAll('th'), + colNode, + cols = [], + col, + i; + + for (i = 0; i < colNodes.length; i += 1) { + colNode = colNodes[i]; + col = { + key: colNode.getAttribute('data-col'), + sortable: !colNode.getAttribute('data-nosort'), + type: colNode.getAttribute('data-type') || 'string' + }; + cols.push(col); + if (col.sortable) { + col.defaultDescSort = col.type === 'number'; + colNode.innerHTML = + colNode.innerHTML + ''; + } + } + return cols; + } + // attaches a data attribute to every tr element with an object + // of data values keyed by column name + function loadRowData(tableRow) { + var tableCols = tableRow.querySelectorAll('td'), + colNode, + col, + data = {}, + i, + val; + for (i = 0; i < tableCols.length; i += 1) { + colNode = tableCols[i]; + col = cols[i]; + val = colNode.getAttribute('data-value'); + if (col.type === 'number') { + val = Number(val); + } + data[col.key] = val; + } + return data; + } + // loads all row data + function loadData() { + var rows = getTableBody().querySelectorAll('tr'), + i; + + for (i = 0; i < rows.length; i += 1) { + rows[i].data = loadRowData(rows[i]); + } + } + // sorts the table using the data for the ith column + function sortByIndex(index, desc) { + var key = cols[index].key, + sorter = function(a, b) { + a = a.data[key]; + b = b.data[key]; + return a < b ? -1 : a > b ? 1 : 0; + }, + finalSorter = sorter, + tableBody = document.querySelector('.coverage-summary tbody'), + rowNodes = tableBody.querySelectorAll('tr'), + rows = [], + i; + + if (desc) { + finalSorter = function(a, b) { + return -1 * sorter(a, b); + }; + } + + for (i = 0; i < rowNodes.length; i += 1) { + rows.push(rowNodes[i]); + tableBody.removeChild(rowNodes[i]); + } + + rows.sort(finalSorter); + + for (i = 0; i < rows.length; i += 1) { + tableBody.appendChild(rows[i]); + } + } + // removes sort indicators for current column being sorted + function removeSortIndicators() { + var col = getNthColumn(currentSort.index), + cls = col.className; + + cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, ''); + col.className = cls; + } + // adds sort indicators for current column being sorted + function addSortIndicators() { + getNthColumn(currentSort.index).className += currentSort.desc + ? ' sorted-desc' + : ' sorted'; + } + // adds event listeners for all sorter widgets + function enableUI() { + var i, + el, + ithSorter = function ithSorter(i) { + var col = cols[i]; + + return function() { + var desc = col.defaultDescSort; + + if (currentSort.index === i) { + desc = !currentSort.desc; + } + sortByIndex(i, desc); + removeSortIndicators(); + currentSort.index = i; + currentSort.desc = desc; + addSortIndicators(); + }; + }; + for (i = 0; i < cols.length; i += 1) { + if (cols[i].sortable) { + // add the click event handler on the th so users + // dont have to click on those tiny arrows + el = getNthColumn(i).querySelector('.sorter').parentElement; + if (el.addEventListener) { + el.addEventListener('click', ithSorter(i)); + } else { + el.attachEvent('onclick', ithSorter(i)); + } + } + } + } + // adds sorting functionality to the UI + return function() { + if (!getTable()) { + return; + } + cols = loadColumns(); + loadData(); + addSearchBox(); + addSortIndicators(); + enableUI(); + }; +})(); + +window.addEventListener('load', addSorting); diff --git a/src/chain/chainMethod.js.html b/src/chain/chainMethod.js.html new file mode 100644 index 00000000..38bef927 --- /dev/null +++ b/src/chain/chainMethod.js.html @@ -0,0 +1,364 @@ + + + + + + Code coverage report for src/chain/chainMethod.js + + + + + + + + + +
+
+

All files / src/chain chainMethod.js

+
+ +
+ 100% + Statements + 35/35 +
+ + +
+ 100% + Branches + 24/24 +
+ + +
+ 100% + Functions + 10/10 +
+ + +
+ 100% + Lines + 35/35 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +506x +506x +506x +506x +506x +506x +506x +506x +  +  +  +47x +38x +  +  +9x +16x +16x +  +  +  +  +498x +  +  +  +65x +  +  +  +  +  +46x +1x +  +45x +  +  +  +  +  +  +45x +66x +  +25x +  +5x +5x +  +25x +20x +  +  +  +41x +  +  +45x +  +  +  +42x +42x +19x +  +23x +  +  +22x +22x +  +  +1x +1x +  +  +  + 
/**
+ * @file method on chain
+ * @author atom-yang
+ */
+import { isFunction, noop, isBoolean } from '../util/utils';
+ 
+export default class ChainMethod {
+  constructor({
+    name,
+    call,
+    method = 'GET',
+    params = [],
+    inputFormatter = [],
+    outputFormatter = null,
+  }) {
+    this.name = name;
+    this.call = call;
+    this.requestMethod = method;
+    this.params = params;
+    this.inputFormatter = inputFormatter;
+    this.outputFormatter = outputFormatter;
+    this.requestManager = null;
+    this.run = this.run.bind(this);
+  }
+ 
+  formatInput(args) {
+    if (!this.inputFormatter || this.inputFormatter.length === 0) {
+      return args;
+    }
+ 
+    return args.map((arg, index) => {
+      const formatter = this.inputFormatter[index];
+      return formatter ? formatter(arg) : arg;
+    });
+  }
+ 
+  setRequestManager(manager) {
+    this.requestManager = manager;
+  }
+ 
+  formatOutput(result) {
+    return this.outputFormatter && result
+      ? this.outputFormatter(result)
+      : result;
+  }
+ 
+  extractArgumentsIntoObject(args) {
+    if (args.length < this.params.length) {
+      throw new Error(`should supply enough parameters for ${this.call}`);
+    }
+    const result = {
+      method: this.call,
+      requestMethod: this.requestMethod,
+      isSync: false,
+      callback: noop,
+      params: {},
+    };
+    this.formatInput(args).forEach((arg, index) => {
+      if (index > this.params.length - 1) {
+        // if index is greater than params.length, that means arg is an extra argument
+        if (isFunction(arg)) {
+          // if there is a callback, user want to be in async mode, set isSync to false
+          result.callback = arg;
+          result.isSync = false;
+        }
+        if (isBoolean(arg?.sync)) {
+          result.isSync = arg.sync;
+        }
+      } else {
+        // if index is less than or equal to params.length, that means arg is one of the params
+        result.params[this.params[index]] = arg;
+      }
+    });
+    return result;
+  }
+ 
+  run(...args) {
+    const argsObj = this.extractArgumentsIntoObject(args);
+    if (argsObj.isSync) {
+      return this.formatOutput(this.requestManager.send(argsObj));
+    }
+    return this.requestManager
+      .sendAsync(argsObj)
+      .then(result => {
+        argsObj.callback(null, this.formatOutput(result));
+        return this.formatOutput(result);
+      })
+      .catch(err => {
+        argsObj.callback(err);
+        throw err;
+      });
+  }
+}
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/chain/index.html b/src/chain/index.html new file mode 100644 index 00000000..8fc92109 --- /dev/null +++ b/src/chain/index.html @@ -0,0 +1,131 @@ + + + + + + Code coverage report for src/chain + + + + + + + + + +
+
+

All files src/chain

+
+ +
+ 100% + Statements + 98/98 +
+ + +
+ 100% + Branches + 52/52 +
+ + +
+ 100% + Functions + 23/23 +
+ + +
+ 100% + Lines + 96/96 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
chainMethod.js +
+
100%35/35100%24/24100%10/10100%35/35
index.js +
+
100%63/63100%28/28100%13/13100%61/61
+
+
+
+ + + + + + + + \ No newline at end of file diff --git a/src/chain/index.js.html b/src/chain/index.js.html new file mode 100644 index 00000000..a9f8e950 --- /dev/null +++ b/src/chain/index.js.html @@ -0,0 +1,454 @@ + + + + + + Code coverage report for src/chain/index.js + + + + + + + + + +
+
+

All files / src/chain index.js

+
+ +
+ 100% + Statements + 63/63 +
+ + +
+ 100% + Branches + 28/28 +
+ + +
+ 100% + Functions + 13/13 +
+ + +
+ 100% + Lines + 61/61 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124  +  +  +  +  +  +  +  +  +  +  +  +  +26x +494x +494x +494x +494x +494x +  +  +  +  +12x +  +  +  +  +12x +  +4x +  +8x +1x +  +8x +8x +5x +  +8x +1x +  +  +8x +  +  +  +  +  +  +  +  +  +  +5x +5x +2x +  +  +2x +1x +1x +  +1x +  +  +3x +3x +1x +1x +1x +1x +  +2x +  +2x +1x +  +  +  +  +  +4x +4x +2x +  +  +2x +2x +3x +2x +1x +  +1x +  +  +1x +11x +11x +11x +11x +  +1x +  +2x +2x +2x +3x +2x +1x +  +1x +1x +11x +11x +11x +11x +  +1x +  +  +  +  + 
/**
+ * @file chain
+ * @author atom-yang
+ */
+import { isBoolean, isFunction, noop, setPath } from '../util/utils';
+import { CHAIN_METHODS } from '../common/constants';
+import ChainMethod from './chainMethod';
+import * as merkleTree from '../util/merkleTree';
+ 
+import ContractFactory from '../contract';
+ 
+export default class Chain {
+  constructor(requestManager) {
+    Object.keys(CHAIN_METHODS).forEach(key => {
+      const methodConfig = CHAIN_METHODS[key];
+      const { name } = methodConfig;
+      const method = new ChainMethod(methodConfig);
+      method.setRequestManager(requestManager);
+      setPath(this, name, method.run);
+    });
+  }
+ 
+  extractArgumentsIntoObject(args) {
+    const result = {
+      callback: noop,
+      isSync: false,
+      refBlockNumberStrategy: 0
+    };
+    if (args.length === 0) {
+      // has no callback, default to be async mode
+      return result;
+    }
+    if (isFunction(args[args.length - 1])) {
+      result.callback = args[args.length - 1];
+    }
+    args.forEach(arg => {
+      if (isBoolean(arg?.sync)) {
+        result.isSync = arg.sync;
+      }
+      if (typeof arg?.refBlockNumberStrategy === 'number') {
+        result.refBlockNumberStrategy = arg.refBlockNumberStrategy;
+      }
+    });
+    return result;
+  }
+ 
+  /**
+   * @param {string} address - Contract address
+   * @param {IBlockchainWallet} wallet - aelf wallet
+   * @param {object} options - {sync: boolean, refBlockNumberStrategy: number}
+   * @param  {...any} args
+   * @returns
+   */
+  contractAt(address, wallet, ...args) {
+    const { callback, isSync, refBlockNumberStrategy } = this.extractArgumentsIntoObject(args);
+    if (isSync) {
+      const fds = this.getContractFileDescriptorSet(address, {
+        sync: true
+      });
+      if (fds && fds.file && fds.file.length > 0) {
+        const factory = new ContractFactory(this, fds, wallet, { refBlockNumberStrategy });
+        return factory.at(address);
+      }
+      throw new Error('no such contract');
+    }
+    // eslint-disable-next-line consistent-return
+    return this.getContractFileDescriptorSet(address).then(fds => {
+      if (fds && fds.file && fds.file.length > 0) {
+        const factory = new ContractFactory(this, fds, wallet, { refBlockNumberStrategy });
+        const result = factory.at(address);
+        callback(null, result);
+        return result;
+      }
+      callback(new Error('no such contract'));
+      // if callback is noop, throw error
+      if (callback.length === 0) {
+        throw new Error('no such contract');
+      }
+    });
+  }
+ 
+  getMerklePath(txId, height, ...args) {
+    const { isSync } = this.extractArgumentsIntoObject(args);
+    if (isSync) {
+      const block = this.getBlockByHeight(height, true, {
+        sync: true
+      });
+      const { BlockHash, Body } = block;
+      const txIds = Body.Transactions;
+      const txIndex = txIds.findIndex(id => id === txId);
+      if (txIndex === -1) {
+        throw new Error(`txId ${txId} has no correspond transaction in the block with height ${height}`);
+      }
+      const txResults = this.getTxResults(BlockHash, 0, txIds.length, {
+        sync: true
+      });
+      const nodes = txResults.map((result, index) => {
+        const id = txIds[index];
+        const status = result.Status;
+        const buffer = Buffer.concat([Buffer.from(id.replace('0x', ''), 'hex'), Buffer.from(status, 'utf8')]);
+        return merkleTree.node(buffer);
+      });
+      return merkleTree.getMerklePath(txIndex, nodes);
+    }
+    return this.getBlockByHeight(height, true).then(block => {
+      const { BlockHash, Body } = block;
+      const txIds = Body.Transactions;
+      const txIndex = txIds.findIndex(id => id === txId);
+      if (txIndex === -1) {
+        throw new Error(`txId ${txId} has no correspond transaction in the block with height ${height}`);
+      }
+      return this.getTxResults(BlockHash, 0, txIds.length).then(results => {
+        const nodes = results.map((result, index) => {
+          const id = txIds[index];
+          const status = result.Status;
+          const buffer = Buffer.concat([Buffer.from(id.replace('0x', ''), 'hex'), Buffer.from(status, 'utf8')]);
+          return merkleTree.node(buffer);
+        });
+        return merkleTree.getMerklePath(txIndex, nodes);
+      });
+    });
+  }
+}
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/contract/contractMethod.js.html b/src/contract/contractMethod.js.html new file mode 100644 index 00000000..a5763abd --- /dev/null +++ b/src/contract/contractMethod.js.html @@ -0,0 +1,1006 @@ + + + + + + Code coverage report for src/contract/contractMethod.js + + + + + + + + + +
+
+

All files / src/contract contractMethod.js

+
+ +
+ 99.33% + Statements + 149/150 +
+ + +
+ 95.45% + Branches + 63/66 +
+ + +
+ 100% + Functions + 28/28 +
+ + +
+ 99.31% + Lines + 145/146 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254 +255 +256 +257 +258 +259 +260 +261 +262 +263 +264 +265 +266 +267 +268 +269 +270 +271 +272 +273 +274 +275 +276 +277 +278 +279 +280 +281 +282 +283 +284 +285 +286 +287 +288 +289 +290 +291 +292 +293 +294 +295 +296 +297 +298 +299 +300 +301 +302 +303 +304 +305 +306 +307 +308  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +126x +126x +126x +126x +126x +126x +126x +126x +126x +  +126x +126x +126x +126x +126x +126x +126x +126x +126x +126x +  +  +  +21x +1x +  +20x +20x +20x +20x +  +  +  +2x +1x +  +1x +  +  +  +1x +1x +1x +  +  +  +5x +1x +  +4x +  +  +  +4x +4x +4x +  +  +  +2x +1x +  +1x +  +1x +  +1x +1x +  +  +  +16x +  +16x +  +16x +  +  +16x +16x +  +  +  +  +  +8x +8x +  +8x +1x +  +7x +7x +  +7x +  +7x +7x +  +3x +1x +  +2x +1x +  +1x +  +  +  +5x +1x +1x +  +  +1x +  +  +5x +  +  +  +  +  +  +  +  +  +12x +9x +  +9x +1x +  +  +8x +  +8x +10x +  +3x +1x +  +2x +1x +  +1x +  +  +  +6x +  +  +  +6x +  +6x +1x +1x +  +  +1x +  +  +6x +  +  +  +4x +2x +  +2x +  +2x +  +  +  +3x +3x +1x +1x +  +  +  +  +2x +2x +  +  +  +  +2x +2x +1x +1x +  +  +  +  +  +  +1x +1x +  +1x +  +  +  +  +  +  +8x +  +  +  +8x +  +1x +  +7x +2x +  +7x +11x +2x +  +  +7x +  +  +  +  +5x +  +3x +2x +2x +1x +  +1x +  +  +1x +  +  +  +18x +18x +16x +  +18x +16x +16x +  +18x +  +  +  +1x +1x +1x +  +  +  +  +  +  +  +  +1x +  +  +  +125x +125x +125x +125x +125x +125x +125x +125x +125x +125x +125x +125x +125x +125x +  +125x +  +  + 
/**
+ * @file contract method
+ * @author atom-yang
+ */
+import { getTransaction, Transaction } from '../util/proto';
+import {
+  transformArrayToMap,
+  transformMapToArray,
+  transform,
+  INPUT_TRANSFORMERS,
+  OUTPUT_TRANSFORMERS
+} from '../util/transform';
+import { isBoolean, isFunction, isNumber, noop, uint8ArrayToHex, unpackSpecifiedTypeData } from '../util/utils';
+import wallet from '../wallet';
+ 
+export default class ContractMethod {
+  constructor(chain, method, contractAddress, walletInstance, option) {
+    this._chain = chain;
+    this._method = method;
+    this._option = option || {};
+    const { resolvedRequestType, resolvedResponseType } = method;
+    this._inputType = resolvedRequestType;
+    this._outputType = resolvedResponseType;
+    this._name = method.name;
+    this._contractAddress = contractAddress;
+    this._wallet = walletInstance;
+ 
+    this.sendTransaction = this.sendTransaction.bind(this);
+    this.unpackPackedInput = this.unpackPackedInput.bind(this);
+    this.packInput = this.packInput.bind(this);
+    this.unpackOutput = this.unpackOutput.bind(this);
+    this.bindMethodToContract = this.bindMethodToContract.bind(this);
+    this.run = this.run.bind(this);
+    this.request = this.request.bind(this);
+    this.callReadOnly = this.callReadOnly.bind(this);
+    this.getSignedTx = this.getSignedTx.bind(this);
+    this.getRawTx = this.getRawTx.bind(this);
+  }
+ 
+  packInput(input) {
+    if (!input) {
+      return null;
+    }
+    let params = transformMapToArray(this._inputType, input);
+    params = transform(this._inputType, params, INPUT_TRANSFORMERS);
+    const message = this._inputType.fromObject(params);
+    return this._inputType.encode(message).finish();
+  }
+ 
+  unpackPackedInput(inputPacked) {
+    if (!inputPacked) {
+      return null;
+    }
+    const result = unpackSpecifiedTypeData({
+      data: inputPacked,
+      dataType: this._inputType
+    });
+    let params = transform(this._inputType, result, OUTPUT_TRANSFORMERS);
+    params = transformArrayToMap(this._inputType, params);
+    return params;
+  }
+ 
+  unpackOutput(output) {
+    if (!output) {
+      return null;
+    }
+    let result = unpackSpecifiedTypeData({
+      data: isNumber(output) ? String(output) : output,
+      dataType: this._outputType
+    });
+    result = transform(this._outputType, result, OUTPUT_TRANSFORMERS);
+    result = transformArrayToMap(this._outputType, result);
+    return result;
+  }
+ 
+  packOutput(result) {
+    if (!result) {
+      return null;
+    }
+    let params = transformMapToArray(this._outputType, result);
+ 
+    params = transform(this._outputType, params, INPUT_TRANSFORMERS);
+ 
+    const message = this._outputType.fromObject(params);
+    return this._outputType.encode(message).finish();
+  }
+ 
+  handleTransaction(height, hash, encoded) {
+    const rawTx = this.getRawTx(height, hash, encoded);
+ 
+    let tx = wallet.signTransaction(rawTx, this._wallet.keyPair);
+ 
+    tx = Transaction.encode(tx).finish();
+    // jest environment just go into Buffer branch
+    // we have test in browser example handly
+    Eif (tx instanceof Buffer) {
+      return tx.toString('hex');
+    }
+    return uint8ArrayToHex(tx);
+  }
+ 
+  prepareParametersAsync(args, isView) {
+    const filterArgs = args.filter(arg => !isFunction(arg) && !isBoolean(arg.sync));
+    const encoded = this.packInput(filterArgs[0]);
+ 
+    if (isView) {
+      return Promise.resolve(this.handleTransaction('', '', encoded));
+    }
+    return this._chain.getChainStatus().then(status => {
+      let { BestChainHeight, BestChainHash } = status;
+ 
+      let { refBlockNumberStrategy } = this._option || {};
+ 
+      args.forEach(arg => {
+        if (arg.refBlockNumberStrategy) {
+          // eslint-disable-next-line max-len
+          if (typeof arg.refBlockNumberStrategy !== 'number') {
+            throw new Error('Invalid type, refBlockNumberStrategy must be number');
+          }
+          if (arg.refBlockNumberStrategy > 0) {
+            throw new Error('refBlockNumberStrategy must be less than 0');
+          }
+          refBlockNumberStrategy = arg.refBlockNumberStrategy;
+        }
+      });
+ 
+      if (refBlockNumberStrategy) {
+        BestChainHeight += refBlockNumberStrategy;
+        const block = this._chain.getBlockByHeight(BestChainHeight, true, {
+          sync: true
+        });
+        BestChainHash = block.BlockHash;
+      }
+ 
+      return this.handleTransaction(BestChainHeight, BestChainHash, encoded);
+    });
+  }
+ 
+  /**
+   * @param {Array} args - argument
+   * @param {boolean} isView - view method
+   * @returns any
+   */
+  prepareParameters(args, isView) {
+    const filterArgs = args.filter(arg => !isFunction(arg) && !isBoolean(arg.sync));
+    const encoded = this.packInput(filterArgs[0]);
+ 
+    if (isView) {
+      return this.handleTransaction('', '', encoded);
+    }
+ 
+    let { refBlockNumberStrategy } = this._option;
+ 
+    args.forEach(arg => {
+      if (arg.refBlockNumberStrategy) {
+        // eslint-disable-next-line max-len
+        if (typeof arg.refBlockNumberStrategy !== 'number') {
+          throw new Error('Invalid type, refBlockNumberStrategy must be number');
+        }
+        if (arg.refBlockNumberStrategy > 0) {
+          throw new Error('refBlockNumberStrategy must be less than 0');
+        }
+        refBlockNumberStrategy = arg.refBlockNumberStrategy;
+      }
+    });
+ 
+    const statusRes = this._chain.getChainStatus({
+      sync: true
+    });
+ 
+    let { BestChainHeight, BestChainHash } = statusRes;
+ 
+    if (refBlockNumberStrategy) {
+      BestChainHeight += refBlockNumberStrategy;
+      const block = this._chain.getBlockByHeight(BestChainHeight, true, {
+        sync: true
+      });
+      BestChainHash = block.BlockHash;
+    }
+ 
+    return this.handleTransaction(BestChainHeight, BestChainHash, encoded);
+  }
+ 
+  prepareParametersWithBlockInfo(args) {
+    const filterArgs = args.filter(arg => !isFunction(arg) && !isBoolean(arg.sync));
+    const encoded = this.packInput(filterArgs[0]);
+ 
+    const { height, hash } = filterArgs[1]; // blockInfo
+ 
+    return this.handleTransaction(height, hash, encoded);
+  }
+ 
+  sendTransaction(...args) {
+    const argsObject = this.extractArgumentsIntoObject(args);
+    if (argsObject.isSync) {
+      const parameters = this.prepareParameters(args);
+      return this._chain.sendTransaction(parameters, {
+        sync: true
+      });
+    }
+    // eslint-disable-next-line arrow-body-style
+    return this.prepareParametersAsync(args).then(parameters => {
+      return this._chain.sendTransaction(parameters, argsObject.callback);
+    });
+  }
+ 
+  callReadOnly(...args) {
+    const argsObject = this.extractArgumentsIntoObject(args);
+    if (argsObject.isSync) {
+      const parameters = this.prepareParameters(args, true);
+      return this.unpackOutput(
+        this._chain.callReadOnly(parameters, {
+          sync: true
+        })
+      );
+    }
+    // eslint-disable-next-line arrow-body-style
+    return this.prepareParametersAsync(args, true).then(parameters => {
+      return this._chain
+        .callReadOnly(parameters, (error, result) => {
+          argsObject.callback(error, this.unpackOutput(result));
+        })
+        .then(this.unpackOutput);
+    });
+  }
+ 
+  extractArgumentsIntoObject(args) {
+    const result = {
+      callback: noop,
+      isSync: false
+    };
+    if (args.length === 0) {
+      // has no callback, default to be async mode
+      return result;
+    }
+    if (isFunction(args[args.length - 1])) {
+      result.callback = args[args.length - 1];
+    }
+    args.forEach(arg => {
+      if (isBoolean(arg.sync)) {
+        result.isSync = arg.sync;
+      }
+    });
+    return result;
+  }
+ 
+  // getData(...args) {
+  getSignedTx(...args) {
+    const filterArgs = args.filter(arg => !isFunction(arg) && !isBoolean(arg.sync));
+ 
+    if (filterArgs[1]) {
+      const { height, hash } = filterArgs[1]; // blockInfo
+      if (hash && height) {
+        return this.prepareParametersWithBlockInfo(args);
+      }
+      throw Error('The second param is the height & hash of a block');
+    }
+ 
+    return this.prepareParameters(args);
+  }
+ 
+  getRawTx(blockHeightInput, blockHashInput, packedInput) {
+    const rawTx = getTransaction(this._wallet.address, this._contractAddress, this._name, packedInput);
+    if (blockHeightInput) {
+      rawTx.refBlockNumber = blockHeightInput;
+    }
+    if (blockHashInput) {
+      const blockHash = blockHashInput.match(/^0x/) ? blockHashInput.substring(2) : blockHashInput;
+      rawTx.refBlockPrefix = Buffer.from(blockHash, 'hex').slice(0, 4);
+    }
+    return rawTx;
+  }
+ 
+  request(...args) {
+    const { callback } = this.extractArgumentsIntoObject(args);
+    const params = this.prepareParameters(args);
+    return {
+      method: 'broadcast_tx',
+      callback,
+      params,
+      format: this.unpackOutput
+    };
+  }
+ 
+  run(...args) {
+    return this.sendTransaction(...args);
+  }
+ 
+  bindMethodToContract(contract) {
+    const { run } = this;
+    run.request = this.request;
+    run.call = this.callReadOnly;
+    run.inputTypeInfo = this._inputType.toJSON();
+    run.inputType = this._inputType;
+    run.outputTypeInfo = this._outputType.toJSON();
+    run.outputType = this._outputType;
+    run.unpackPackedInput = this.unpackPackedInput;
+    run.packInput = this.packInput;
+    run.packOutput = this.packOutput.bind(this);
+    run.sendTransaction = this.sendTransaction;
+    run.getSignedTx = this.getSignedTx;
+    run.getRawTx = this.getRawTx;
+    run.unpackOutput = this.unpackOutput;
+    // eslint-disable-next-line no-param-reassign
+    contract[this._name] = run;
+  }
+}
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/contract/index.html b/src/contract/index.html new file mode 100644 index 00000000..7591c6b8 --- /dev/null +++ b/src/contract/index.html @@ -0,0 +1,131 @@ + + + + + + Code coverage report for src/contract + + + + + + + + + +
+
+

All files src/contract

+
+ +
+ 99.42% + Statements + 174/175 +
+ + +
+ 95.83% + Branches + 69/72 +
+ + +
+ 100% + Functions + 39/39 +
+ + +
+ 99.41% + Lines + 169/170 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
contractMethod.js +
+
99.33%149/15095.45%63/66100%28/2899.31%145/146
index.js +
+
100%25/25100%6/6100%11/11100%24/24
+
+
+
+ + + + + + + + \ No newline at end of file diff --git a/src/contract/index.js.html b/src/contract/index.js.html new file mode 100644 index 00000000..99587e94 --- /dev/null +++ b/src/contract/index.js.html @@ -0,0 +1,259 @@ + + + + + + Code coverage report for src/contract/index.js + + + + + + + + + +
+
+

All files / src/contract index.js

+
+ +
+ 100% + Statements + 25/25 +
+ + +
+ 100% + Branches + 6/6 +
+ + +
+ 100% + Functions + 11/11 +
+ + +
+ 100% + Lines + 24/24 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59  +  +  +  +  +  +  +  +  +  +7x +6x +6x +58x +  +20x +20x +20x +  +  +  +  +  +9x +9x +9x +  +  +  +7x +7x +  +  +  +  +  +6x +6x +6x +  +  +  +9x +15x +124x +124x +124x +  +  +  +  +  +9x +9x +9x +9x +  +  + 
/**
+ * @file contract
+ * @author atom-yang
+ */
+// eslint-disable-next-line max-classes-per-file
+import * as protobuf from '@aelfqueen/protobufjs';
+import ContractMethod from './contractMethod';
+import { noop } from '../util/utils';
+import { deserializeLog } from '../util/proto';
+ 
+const getServicesFromFileDescriptors = descriptors => {
+  const root = protobuf.Root.fromDescriptor(descriptors, 'proto3').resolveAll();
+  return descriptors.file
+    .filter(f => f.service.length > 0)
+    .map(f => {
+      const sn = f.service[0].name;
+      const fullName = f.package ? `${f.package}.${sn}` : sn;
+      return root.lookupService(fullName);
+    });
+};
+ 
+class Contract {
+  constructor(chain, services, address) {
+    this._chain = chain;
+    this.address = address;
+    this.services = services;
+  }
+ 
+  deserializeLog(logs = [], logName) {
+    const logInThisAddress = logs.filter(v => v.Address === this.address && v.Name === logName);
+    return deserializeLog(logInThisAddress, this.services);
+  }
+}
+ 
+export default class ContractFactory {
+  constructor(chain, fileDescriptorSet, wallet) {
+    this.chain = chain;
+    this.services = getServicesFromFileDescriptors(fileDescriptorSet);
+    this.wallet = wallet;
+  }
+ 
+  static bindMethodsToContract(contract, wallet) {
+    contract.services.forEach(service => {
+      Object.keys(service.methods).forEach(key => {
+        const method = service.methods[key].resolve();
+        const contractMethod = new ContractMethod(contract._chain, method, contract.address, wallet);
+        contractMethod.bindMethodToContract(contract);
+      });
+    });
+  }
+ 
+  at(address, callback = noop) {
+    const contractInstance = new Contract(this.chain, this.services, address);
+    ContractFactory.bindMethodsToContract(contractInstance, this.wallet);
+    callback(null, contractInstance);
+    return contractInstance;
+  }
+}
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/index.html b/src/index.html new file mode 100644 index 00000000..7c5f940e --- /dev/null +++ b/src/index.html @@ -0,0 +1,116 @@ + + + + + + Code coverage report for src + + + + + + + + + +
+
+

All files src

+
+ +
+ 100% + Statements + 12/12 +
+ + +
+ 100% + Branches + 2/2 +
+ + +
+ 100% + Functions + 3/3 +
+ + +
+ 100% + Lines + 12/12 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
index.js +
+
100%12/12100%2/2100%3/3100%12/12
+
+
+
+ + + + + + + + \ No newline at end of file diff --git a/src/index.js.html b/src/index.js.html new file mode 100644 index 00000000..9191def1 --- /dev/null +++ b/src/index.js.html @@ -0,0 +1,307 @@ + + + + + + Code coverage report for src/index.js + + + + + + + + + +
+
+

All files / src index.js

+
+ +
+ 100% + Statements + 12/12 +
+ + +
+ 100% + Branches + 2/2 +
+ + +
+ 100% + Functions + 3/3 +
+ + +
+ 100% + Lines + 12/12 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +12x +12x +12x +  +  +7x +  +7x +  +  +  +  +  +  +  +  +  +  +  +  +7x +  +  +  +  +  +  +12x +  +  +  +12x +  +  +  +  +  +12x +  +  +  +  +  +  +  +  +1x +  +  +  +1x +1x +  +  +  + 
/**
+ * @file AElf-sdk index export
+ * @author atom-yang
+ */
+import * as protobuf from '@aelfqueen/protobufjs/light';
+import * as bloom from './util/bloom';
+import Chain from './chain';
+import RequestManager from './util/requestManage';
+import HttpProvider from './util/httpProvider';
+import wallet from './wallet';
+import * as utils from './util/utils';
+import * as proto from './util/proto';
+import * as transform from './util/transform';
+import Settings from './util/settings';
+import sha256 from './util/sha256';
+ 
+/* eslint-disable no-underscore-dangle */
+export default class AElf {
+  constructor(provider) {
+    this._requestManager = new RequestManager(provider);
+    this.currentProvider = provider;
+    this.chain = new Chain(this._requestManager);
+  }
+ 
+  static version = process.env.SDK_VERSION;
+ 
+  static providers = {
+    HttpProvider
+  };
+ 
+  /**
+   * @type {protobuf} export protobufjs for developers
+   */
+  static pbjs = protobuf;
+ 
+  static pbUtils = proto;
+ 
+  static wallet = wallet;
+ 
+  static utils = {
+    ...utils,
+    ...bloom,
+    sha256,
+    transform
+  };
+ 
+  providers = {
+    HttpProvider
+  };
+ 
+  settings = new Settings();
+ 
+  /**
+   * AElf-sdk version
+   * @type {{api: string}}
+   */
+  version = {
+    api: process.env.SDK_VERSION
+  };
+ 
+  /**
+   * check the rpc node is work or not.
+   * @returns {boolean} whether can connect to the rpc.
+   */
+  isConnected() {
+    return this.currentProvider && this.currentProvider.isConnected();
+  }
+ 
+  setProvider(provider) {
+    this._requestManager.setProvider(provider);
+    this.currentProvider = provider;
+  }
+}
+/* eslint-enable */
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/util/bloom.js.html b/src/util/bloom.js.html new file mode 100644 index 00000000..0b055c59 --- /dev/null +++ b/src/util/bloom.js.html @@ -0,0 +1,379 @@ + + + + + + Code coverage report for src/util/bloom.js + + + + + + + + + +
+
+

All files / src/util bloom.js

+
+ +
+ 100% + Statements + 26/26 +
+ + +
+ 100% + Branches + 24/24 +
+ + +
+ 100% + Functions + 6/6 +
+ + +
+ 100% + Lines + 25/25 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99  +  +  +  +  +  +  +  +  +  +  +  +  +  +19x +1x +  +  +  +  +  +18x +  +  +  +15x +  +3x +  +  +  +  +  +  +  +38x +  +35x +  +  +3x +  +1x +  +  +2x +  +1x +  +  +1x +  +  +  +  +  +  +  +  +19x +4x +  +15x +  +37x +  +  +  +  +37x +  +  +37x +  +37x +4x +  +  +11x +  +  +  +  +  +  +  +  +4x +  +  +  +3x +  +  +  +3x +3x +  + 
/**
+ * @file bloom
+ * @author joshstevens19
+ * @link https://github.com/joshstevens19/ethereum-bloom-filters
+ */
+import sha256 from './sha256';
+import {
+  Address,
+  getAddressObjectFromRep
+} from './proto';
+/**
+ * @deprecated Use the new Bloom instead
+ */
+function isBloom(bloom) {
+  if (bloom instanceof Buffer || bloom instanceof Uint8Array) {
+    return bloom.length === 256;
+  }
+  // if (!/^(0x)?[0-9a-f]{512}$/i.test(bloom)) {
+  //   return false;
+  // }
+ 
+  if (
+    /^(0x)?[0-9a-f]{512}$/.test(bloom)
+    || /^(0x)?[0-9A-F]{512}$/.test(bloom)
+  ) {
+    return true;
+  }
+  return false;
+}
+ 
+/**
+ * @param codePoint
+ * @return {number}
+ */
+function codePointToInt(codePoint) {
+  if (codePoint >= 48 && codePoint <= 57) {
+    /* ['0'..'9'] -> [0..9] */
+    return codePoint - 48;
+  }
+ 
+  if (codePoint >= 65 && codePoint <= 70) {
+    /* ['A'..'F'] -> [10..15] */
+    return codePoint - 55;
+  }
+ 
+  if (codePoint >= 97 && codePoint <= 102) {
+    /* ['a'..'f'] -> [10..15] */
+    return codePoint - 87;
+  }
+ 
+  throw new Error('invalid bloom');
+}
+ 
+/**
+ * @param {string} bloom hex string
+ * @param {string} hash hex string
+ * @return {boolean}
+ */
+export function isInBloom(bloom, hash) {
+  if (!isBloom(bloom)) {
+    throw new Error('Invalid Bloom');
+  }
+  for (let i = 0; i < 12; i += 4) {
+    // calculate bit position in bloom filter that must be active
+    const bitpos = ((parseInt(hash.substr(i, 2), 16) << 8)
+      + parseInt(hash.substr(i + 2, 2), 16))
+      & 2047;
+ 
+    // test if bitpos in bloom is active
+    const code = codePointToInt(
+      bloom.charCodeAt(bloom.length - 1 - Math.floor(bitpos / 4)),
+    );
+    const offset = 1 << bitpos % 4;
+ 
+    if ((code & offset) !== offset) {
+      return false;
+    }
+  }
+  return true;
+}
+ 
+/**
+ * @param {string} bloom base64 string
+ * @param {string} eventName utf-8 string, such as `Transferred`
+ * @return {boolean}
+ */
+export function isEventInBloom(bloom, eventName) {
+  return isInBloom(Buffer.from(bloom, 'base64').toString('hex'), sha256(eventName));
+}
+ 
+export function isIndexedInBloom(bloom, indexed) {
+  return isInBloom(Buffer.from(bloom, 'base64').toString('hex'), sha256(Buffer.from(indexed, 'base64')));
+}
+ 
+export function isAddressInBloom(bloom, address) {
+  const encodedAddress = Address.encode(getAddressObjectFromRep(address)).finish();
+  return isInBloom(Buffer.from(bloom, 'base64').toString('hex'), sha256(encodedAddress));
+}
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/util/errors.js.html b/src/util/errors.js.html new file mode 100644 index 00000000..6c0ae325 --- /dev/null +++ b/src/util/errors.js.html @@ -0,0 +1,166 @@ + + + + + + Code coverage report for src/util/errors.js + + + + + + + + + +
+
+

All files / src/util errors.js

+
+ +
+ 100% + Statements + 8/8 +
+ + +
+ 100% + Branches + 0/0 +
+ + +
+ 100% + Functions + 5/5 +
+ + +
+ 100% + Lines + 8/8 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28  +  +  +  +  +  +  +  +1x +  +1x +  +  +1x +  +  +1x +  +  +1x +1x +1x +  +  +1x +  +  + 
/**
+ * @file throw exact errors
+ * @author atom-yang
+ */
+ 
+/**
+ * errors related to requests
+ */
+export const RequestError = {
+  InvalidNumberOfRPCParams() {
+    return new Error('Invalid number of input parameters to RPC method');
+  },
+  InvalidConnection(host) {
+    return new Error(`CONNECTION ERROR: Couldn\'t connect to node ${host}.`);
+  },
+  InvalidProvider() {
+    return new Error('Provider not set or invalid');
+  },
+  InvalidResponse(error, result) {
+    const message = `Invalid JSON RPC response: ${JSON.stringify(result)}`;
+    console.error(`error ${error.toString()} \n ${message}`);
+    return new Error(message);
+  },
+  ConnectionTimeout(ms) {
+    return new Error(`CONNECTION TIMEOUT: timeout of ${ms} ms archived`);
+  }
+};
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/util/formatters.js.html b/src/util/formatters.js.html new file mode 100644 index 00000000..4f5da67c --- /dev/null +++ b/src/util/formatters.js.html @@ -0,0 +1,226 @@ + + + + + + Code coverage report for src/util/formatters.js + + + + + + + + + +
+
+

All files / src/util formatters.js

+
+ +
+ 100% + Statements + 20/20 +
+ + +
+ 100% + Branches + 8/8 +
+ + +
+ 100% + Functions + 3/3 +
+ + +
+ 100% + Lines + 20/20 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48  +  +  +  +  +  +  +  +  +  +14x +  +40x +  +39x +  +39x +  +  +14x +40x +40x +1x +  +40x +40x +10x +10x +  +40x +2x +  +37x +  +3x +  +37x +  +  +  +  +  +  +14x +9x +9x +  + 
/**
+ * @file formatters.js
+ * @author Marek Kotewicz <marek@ethdev.com>
+ * @author Fabian Vogelsteller <fabian@ethdev.com>
+ * @date 2015
+ */
+import descriptor from '@aelfqueen/protobufjs/ext/descriptor';
+import bs58 from 'bs58';
+import { base58 } from './utils';
+ 
+const getByteCountByAddress = base58Str => {
+  // convert a Base58 string to a binary array and get its byte count
+  const buffer = bs58.decode(base58Str);
+  // get byte
+  const byteCount = buffer.length;
+  // last four digits are the checksum
+  return byteCount;
+};
+ 
+export const inputAddressFormatter = address => {
+  let realAddress = address;
+  if (address && address.value) {
+    realAddress = address.value;
+  }
+  try {
+    if (realAddress.indexOf('_') > 0) {
+      const parts = realAddress.split('_');
+      realAddress = parts?.[1];
+    }
+    if (getByteCountByAddress(realAddress) !== 36) {
+      throw new Error('Invalid address');
+    }
+    base58.decode(realAddress, 'hex');
+  } catch (e) {
+    throw new Error('Invalid address');
+  }
+  return realAddress;
+};
+ 
+/**
+ * @param {String} result base64 representation of serialized FileDescriptorSet
+ * @returns {FileDescriptorSet} decoded FileDescriptorSet message
+ */
+export const outputFileDescriptorSetFormatter = result => {
+  const buffer = Buffer.from(result, 'base64');
+  return descriptor.FileDescriptorSet.decode(buffer);
+};
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/util/httpProvider.js.html b/src/util/httpProvider.js.html new file mode 100644 index 00000000..90dea25c --- /dev/null +++ b/src/util/httpProvider.js.html @@ -0,0 +1,880 @@ + + + + + + Code coverage report for src/util/httpProvider.js + + + + + + + + + +
+
+

All files / src/util httpProvider.js

+
+ +
+ 93.27% + Statements + 111/119 +
+ + +
+ 89.85% + Branches + 62/69 +
+ + +
+ 92% + Functions + 23/25 +
+ + +
+ 93.16% + Lines + 109/117 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254 +255 +256 +257 +258 +259 +260 +261 +262 +263 +264 +265 +266  +  +  +  +  +  +22x +  +  +  +  +22x +22x +22x +  +22x +  +  +  +22x +22x +22x +11x +11x +11x +11x +11x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +59x +59x +59x +59x +59x +1x +1x +  +1x +  +  +  +  +58x +  +  +  +  +  +  +  +  +58x +58x +  +8x +  +58x +  +  +  +  +4x +4x +4x +  +  +  +  +  +  +  +  +1x +  +4x +  +  +  +11x +11x +1x +  +1x +  +  +  +  +  +13x +13x +13x +13x +13x +13x +11x +11x +  +13x +26x +  +13x +  +  +  +  +  +  +  +  +  +  +11x +11x +11x +  +11x +  +10x +  +  +10x +10x +  +2x +2x +  +8x +  +  +6x +6x +3x +3x +  +3x +  +1x +  +  +1x +  +  +  +  +  +  +  +53x +53x +53x +53x +44x +  +53x +53x +106x +  +53x +44x +  +9x +  +  +  +  +  +26x +1x +  +1x +  +  +  +  +25x +  +25x +25x +24x +  +24x +24x +1x +  +23x +  +  +  +25x +24x +  +  +  +26x +26x +26x +26x +26x +26x +852x +26x +26x +26x +26x +1x +  +25x +  +  +  +  +  +  +  +  +26x +  +  +26x +  +  +  +  +  +  +  +3x +3x +  +  +  +2x +  +1x +  +  +  +  +2x +2x +  +  +  +  +1x +  +  +  + 
/**
+ * @file rpc connection built with http
+ * @author atom-yang
+ */
+import { stringify } from 'query-string';
+ 
+const defaultHeaders = {
+  Accept: 'text/plain;v=1.0',
+  'Content-Type': 'application/json'
+};
+ 
+let RequestLibrary = {};
+let RequestLibraryXMLOnly = null;
+let isFetch = false;
+let NodeHeaders;
+if (process.env.RUNTIME_ENV === 'browser') {
+  // For browsers use DOM Api XMLHttpRequest
+  // serviceworker without window and document, only with self
+  // eslint-disable-next-line no-restricted-globals
+  const _self = typeof self === 'object' ? self : {};
+  const _window = typeof window === 'object' ? window : _self;
+  if (typeof _window.XMLHttpRequest !== 'undefined') {
+    RequestLibrary = _window.XMLHttpRequest;
+    isFetch = false;
+  } else Eif (typeof _window.fetch !== 'undefined') {
+    RequestLibrary = _window.fetch;
+    isFetch = true;
+  }
+} else E{
+  // For node use xmlhttprequest
+  // eslint-disable-next-line global-require
+  RequestLibraryXMLOnly = require('xmlhttprequest').XMLHttpRequest;
+  // eslint-disable-next-line global-require
+  RequestLibrary = require('node-fetch').default;
+  NodeHeaders = RequestLibrary.Headers;
+  isFetch = true;
+}
+ 
+export default class HttpProvider {
+  constructor(
+    host = 'http://localhost:8545',
+    timeout = 8000,
+    headers = defaultHeaders,
+    // support node-fetch options
+    options = {}
+  ) {
+    this.host = host.replace(/\/$/, '');
+    this.timeout = timeout;
+    this.headers = {};
+    this.options = options;
+    if (Array.isArray(headers)) {
+      headers.forEach(({ name, value }) => {
+        this.headers[name] = value;
+      });
+      this.headers = {
+        ...defaultHeaders,
+        ...this.headers
+      };
+    } else {
+      this.headers = {
+        ...defaultHeaders,
+        ...headers
+      };
+    }
+  }
+ 
+  static formatResponse(response) {
+    let result;
+    try {
+      result = JSON.parse(response);
+    } catch (e) {
+      result = response;
+    }
+    return result;
+  }
+ 
+  static formatResponseText(request) {
+    let result;
+    try {
+      const parseRequest = request;
+      result = {
+        status: parseRequest.status,
+        error: parseRequest.status === 200 ? 0 : parseRequest.status,
+        Error: {
+          message: request.statusText
+        },
+        statusText: request.statusText
+      };
+    } catch (e) {
+      result = request;
+    }
+    return result;
+  }
+ 
+  static timeoutPromise(delay) {
+    return new Promise(_resolve => {
+      const ids = setTimeout(() => {
+        clearTimeout(ids);
+        // eslint-disable-next-line prefer-promise-reject-errors
+        _resolve({ type: 'timeout' });
+      }, delay);
+    });
+  }
+ 
+  requestSendByFetch(requestConfig, request) {
+    const { url, method = 'POST', params = {}, signal } = requestConfig;
+    const path = `/api/${url}`.replace(/\/\//g, '/');
+    let uri = `${this.host}${path}`.replace();
+    const myHeaders = process.env.RUNTIME_ENV === 'browser' ? new Headers() : new NodeHeaders();
+    let body = JSON.stringify(params);
+    if (method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') {
+      uri = Object.keys(params).length > 0 ? `${uri}?${stringify(params)}` : uri;
+      body = undefined;
+    }
+    Object.keys(this.headers).forEach(header => {
+      myHeaders.append(header, this.headers[header]);
+    });
+    return request(uri, {
+      ...this.options,
+      method: method.toUpperCase(),
+      headers: myHeaders,
+      body,
+      signal
+    });
+  }
+ 
+  sendAsyncByFetch(requestConfig) {
+    const request = RequestLibrary;
+    const { timeout } = this;
+    const control = typeof AbortController === 'function' ? new AbortController() : {};
+    const config = { ...requestConfig, signal: control.signal, credentials: 'omit' };
+    // Simulation timeout
+    return Promise.race([this.requestSendByFetch(config, request), HttpProvider.timeoutPromise(timeout)]).then(
+      result =>
+        new Promise((resolve, reject) => {
+          // @deprecated unuse timeout=1
+          // if (timeout !== 1) {
+          try {
+            if (result.type === 'timeout') {
+              // Cancel timeout request
+              if (control.abort) control.abort();
+              reject(result);
+            } else {
+              result
+                .text()
+                .then(text => {
+                  const res = HttpProvider.formatResponse(text);
+                  if (result.status !== 200 || !result.ok) {
+                    reject(res);
+                    return;
+                  }
+                  resolve(res);
+                })
+                .catch(err => reject(err));
+            }
+          } catch (e) {
+            reject(e);
+          }
+          // }
+        })
+    );
+  }
+ 
+  requestSend(requestConfig, request, isAsync = false) {
+    const { url, method = 'POST', params = {} } = requestConfig;
+    const path = `/api/${url}`.replace(/\/\//g, '/');
+    let uri = `${this.host}${path}`.replace();
+    if (method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') {
+      uri = Object.keys(params).length > 0 ? `${uri}?${stringify(params)}` : uri;
+    }
+    request.open(method.toUpperCase(), uri, isAsync);
+    Object.keys(this.headers).forEach(header => {
+      request.setRequestHeader(header, this.headers[header]);
+    });
+    if (method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') {
+      request.send();
+    } else {
+      request.send(JSON.stringify(params));
+    }
+  }
+ 
+  send(requestConfig) {
+    let request;
+    if (isFetch) {
+      if (!RequestLibraryXMLOnly) {
+        // browser case, Chrome extension v3.
+        throw new Error("Can not get XMLHttpRequest, invalid parameter: 'sync'");
+      } else E{
+        request = new RequestLibraryXMLOnly();
+      }
+    } else {
+      request = new RequestLibrary();
+    }
+    request.withCredentials = false;
+    this.requestSend(requestConfig, request);
+    let result = request.responseText;
+ 
+    result = HttpProvider.formatResponse(result);
+    if (result.Error) {
+      throw result;
+    }
+    return result;
+  }
+ 
+  sendAsync(requestConfig) {
+    if (isFetch) return this.sendAsyncByFetch(requestConfig);
+    return this.sendAsyncByXMLHttp(requestConfig);
+  }
+ 
+  sendAsyncByXMLHttp(requestConfig) {
+    const request = RequestLibraryXMLOnly ? new RequestLibraryXMLOnly() : new RequestLibrary();
+    request.withCredentials = false;
+    request.timeout = this.timeout;
+    this.requestSend(requestConfig, request, true);
+    return new Promise((resolve, reject) => {
+      request.onreadystatechange = () => {
+        if (request.readyState === 4 && request.timeout !== 1) {
+          let result = request.responseText;
+          try {
+            result = HttpProvider.formatResponse(result);
+            if (request.status !== 200 || result.Error) {
+              reject(result);
+            } else {
+              resolve(result);
+            }
+          } catch (e) {
+            // todo: error handle
+            reject(e);
+          }
+        }
+      };
+ 
+      request.onerror = err => {
+        reject(err);
+      };
+      request.ontimeout = err => {
+        // todo: timeout error
+        reject(err);
+      };
+    });
+  }
+ 
+  isConnected() {
+    try {
+      this.send({
+        method: 'GET',
+        url: 'blockChain/chainStatus'
+      });
+      return true;
+    } catch (e) {
+      return false;
+    }
+  }
+ 
+  async isConnectedAsync() {
+    try {
+      return await this.sendAsyncByFetch({
+        method: 'GET',
+        url: 'blockChain/chainStatus'
+      });
+    } catch (e) {
+      return false;
+    }
+  }
+}
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/util/index.html b/src/util/index.html new file mode 100644 index 00000000..75b94fb2 --- /dev/null +++ b/src/util/index.html @@ -0,0 +1,296 @@ + + + + + + Code coverage report for src/util + + + + + + + + + +
+
+

All files src/util

+
+ +
+ 98.72% + Statements + 617/625 +
+ + +
+ 97.94% + Branches + 334/341 +
+ + +
+ 98.56% + Functions + 137/139 +
+ + +
+ 98.65% + Lines + 587/595 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
bloom.js +
+
100%26/26100%24/24100%6/6100%25/25
errors.js +
+
100%8/8100%0/0100%5/5100%8/8
formatters.js +
+
100%20/20100%8/8100%3/3100%20/20
httpProvider.js +
+
93.27%111/11989.85%62/6992%23/2593.16%109/117
keccak.js +
+
100%17/17100%2/2100%2/2100%14/14
keyStore.js +
+
100%38/38100%20/20100%3/3100%38/38
merkleTree.js +
+
100%53/53100%22/22100%6/6100%49/49
proto.js +
+
100%91/91100%33/33100%23/23100%85/85
requestManage.js +
+
100%11/11100%5/5100%5/5100%11/11
settings.js +
+
100%1/1100%0/0100%1/1100%1/1
sha256.js +
+
100%13/13100%0/0100%2/2100%13/13
transform.js +
+
100%103/103100%102/102100%25/25100%94/94
utils.js +
+
100%125/125100%56/56100%33/33100%120/120
+
+
+
+ + + + + + + + \ No newline at end of file diff --git a/src/util/keccak.js.html b/src/util/keccak.js.html new file mode 100644 index 00000000..e3726e9b --- /dev/null +++ b/src/util/keccak.js.html @@ -0,0 +1,148 @@ + + + + + + Code coverage report for src/util/keccak.js + + + + + + + + + +
+
+

All files / src/util keccak.js

+
+ +
+ 100% + Statements + 17/17 +
+ + +
+ 100% + Branches + 2/2 +
+ + +
+ 100% + Functions + 2/2 +
+ + +
+ 100% + Lines + 14/14 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +2212x +  +48x +  +43x +3x +3x +22x +  +3x +  +40x +  +43x +43x +  +  +12x +12x +12x +12x + 
const createKeccakHash = require('keccak');
+ 
+const keccak = bits => str => {
+  let msg;
+  if (str.slice(0, 2) === '0x') {
+    msg = [];
+    for (let i = 2, l = str.length; i < l; i += 2) {
+      msg.push(parseInt(str.slice(i, i + 2), 16));
+    }
+    msg = Buffer.from(msg);
+  } else {
+    msg = str;
+  }
+  const instance = createKeccakHash(`keccak${bits}`);
+  return `0x${instance.update(msg).digest('hex')}`;
+};
+ 
+export const keccak256 = keccak(256);
+export const keccak512 = keccak(512);
+export const keccak256s = keccak(256);
+export const keccak512s = keccak(512);
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/util/keyStore.js.html b/src/util/keyStore.js.html new file mode 100644 index 00000000..5e7603c2 --- /dev/null +++ b/src/util/keyStore.js.html @@ -0,0 +1,1084 @@ + + + + + + Code coverage report for src/util/keyStore.js + + + + + + + + + +
+
+

All files / src/util keyStore.js

+
+ +
+ 100% + Statements + 38/38 +
+ + +
+ 100% + Branches + 20/20 +
+ + +
+ 100% + Functions + 3/3 +
+ + +
+ 100% + Lines + 38/38 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254 +255 +256 +257 +258 +259 +260 +261 +262 +263 +264 +265 +266 +267 +268 +269 +270 +271 +272 +273 +274 +275 +276 +277 +278 +279 +280 +281 +282 +283 +284 +285 +286 +287 +288 +289 +290 +291 +292 +293 +294 +295 +296 +297 +298 +299 +300 +301 +302 +303 +304 +305 +306 +307 +308 +309 +310 +311 +312 +313 +314 +315 +316 +317 +318 +319 +320 +321 +322 +323 +324 +325 +326 +327 +328 +329 +330 +331 +332 +333 +334  +  +  +  +  +  +  +  +  +  +9x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +9x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +5x +  +  +  +5x +5x +5x +5x +5x +5x +5x +4x +  +  +  +4x +4x +  +  +  +4x +4x +4x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +5x +5x +5x +5x +5x +5x +  +  +  +  +  +  +  +5x +5x +5x +4x +4x +  +  +  +  +4x +4x +  +  +  +4x +  +  +  +  +  +  +1x +1x +  +  +4x +  +  +  +  +  +  +  +  +  +  +9x +2x +2x +1x +  +1x +  +  + 
/**
+ * @file AElf keyStore tools
+ * @author atom-yang
+ */
+import scrypt from 'scryptsy';
+import { createCipheriv, createDecipheriv } from 'browserify-cipher';
+import randomBytes from 'randombytes';
+import { keccak256 } from './keccak';
+import { KEY_STORE_ERRORS } from '../common/constants';
+ 
+const AES_MODES = {
+  'aes-128-ecb': {
+    cipher: 'AES',
+    key: 128,
+    iv: 0,
+    mode: 'ECB',
+    type: 'block'
+  },
+  'aes-192-ecb': {
+    cipher: 'AES',
+    key: 192,
+    iv: 0,
+    mode: 'ECB',
+    type: 'block'
+  },
+  'aes-256-ecb': {
+    cipher: 'AES',
+    key: 256,
+    iv: 0,
+    mode: 'ECB',
+    type: 'block'
+  },
+  'aes-128-cbc': {
+    cipher: 'AES',
+    key: 128,
+    iv: 16,
+    mode: 'CBC',
+    type: 'block'
+  },
+  'aes-192-cbc': {
+    cipher: 'AES',
+    key: 192,
+    iv: 16,
+    mode: 'CBC',
+    type: 'block'
+  },
+  'aes-256-cbc': {
+    cipher: 'AES',
+    key: 256,
+    iv: 16,
+    mode: 'CBC',
+    type: 'block'
+  },
+  aes128: {
+    cipher: 'AES',
+    key: 128,
+    iv: 16,
+    mode: 'CBC',
+    type: 'block'
+  },
+  aes192: {
+    cipher: 'AES',
+    key: 192,
+    iv: 16,
+    mode: 'CBC',
+    type: 'block'
+  },
+  aes256: {
+    cipher: 'AES',
+    key: 256,
+    iv: 16,
+    mode: 'CBC',
+    type: 'block'
+  },
+  'aes-128-cfb': {
+    cipher: 'AES',
+    key: 128,
+    iv: 16,
+    mode: 'CFB',
+    type: 'stream'
+  },
+  'aes-192-cfb': {
+    cipher: 'AES',
+    key: 192,
+    iv: 16,
+    mode: 'CFB',
+    type: 'stream'
+  },
+  'aes-256-cfb': {
+    cipher: 'AES',
+    key: 256,
+    iv: 16,
+    mode: 'CFB',
+    type: 'stream'
+  },
+  'aes-128-cfb8': {
+    cipher: 'AES',
+    key: 128,
+    iv: 16,
+    mode: 'CFB8',
+    type: 'stream'
+  },
+  'aes-192-cfb8': {
+    cipher: 'AES',
+    key: 192,
+    iv: 16,
+    mode: 'CFB8',
+    type: 'stream'
+  },
+  'aes-256-cfb8': {
+    cipher: 'AES',
+    key: 256,
+    iv: 16,
+    mode: 'CFB8',
+    type: 'stream'
+  },
+  'aes-128-cfb1': {
+    cipher: 'AES',
+    key: 128,
+    iv: 16,
+    mode: 'CFB1',
+    type: 'stream'
+  },
+  'aes-192-cfb1': {
+    cipher: 'AES',
+    key: 192,
+    iv: 16,
+    mode: 'CFB1',
+    type: 'stream'
+  },
+  'aes-256-cfb1': {
+    cipher: 'AES',
+    key: 256,
+    iv: 16,
+    mode: 'CFB1',
+    type: 'stream'
+  },
+  'aes-128-ofb': {
+    cipher: 'AES',
+    key: 128,
+    iv: 16,
+    mode: 'OFB',
+    type: 'stream'
+  },
+  'aes-192-ofb': {
+    cipher: 'AES',
+    key: 192,
+    iv: 16,
+    mode: 'OFB',
+    type: 'stream'
+  },
+  'aes-256-ofb': {
+    cipher: 'AES',
+    key: 256,
+    iv: 16,
+    mode: 'OFB',
+    type: 'stream'
+  },
+  'aes-128-ctr': {
+    cipher: 'AES',
+    key: 128,
+    iv: 16,
+    mode: 'CTR',
+    type: 'stream'
+  },
+  'aes-192-ctr': {
+    cipher: 'AES',
+    key: 192,
+    iv: 16,
+    mode: 'CTR',
+    type: 'stream'
+  },
+  'aes-256-ctr': {
+    cipher: 'AES',
+    key: 256,
+    iv: 16,
+    mode: 'CTR',
+    type: 'stream'
+  },
+  'aes-128-gcm': {
+    cipher: 'AES',
+    key: 128,
+    iv: 12,
+    mode: 'GCM',
+    type: 'auth'
+  },
+  'aes-192-gcm': {
+    cipher: 'AES',
+    key: 192,
+    iv: 12,
+    mode: 'GCM',
+    type: 'auth'
+  },
+  'aes-256-gcm': {
+    cipher: 'AES',
+    key: 256,
+    iv: 12,
+    mode: 'GCM',
+    type: 'auth'
+  }
+};
+ 
+const defaultOptions = {
+  dklen: 32,
+  n: 8192, // 2048 4096 8192 16384
+  r: 8,
+  p: 1,
+  cipher: 'aes-128-ctr'
+};
+ 
+/**
+ * getKeyStore
+ *
+ * @method getKeyStore
+ * @param {Object} walletInfoInput  walletInfo
+ * @param {string} password password
+ * @param {Object} option option
+ * @return {Object} keyStore
+ */
+export function getKeystore({ mnemonic, privateKey, nickName = '', address = '' }, password, option = defaultOptions) {
+  const opt = {
+    ...defaultOptions,
+    ...option
+  };
+  const { cipher = 'aes-128-ctr' } = opt;
+  const sliceLength = /128/.test(cipher) ? 16 : 32;
+  const salt = randomBytes(32); // instance of Buffer
+  const ivLength = (AES_MODES[cipher.toLowerCase()] || {}).iv;
+  const iv = randomBytes(ivLength === undefined ? 16 : ivLength); // instance of Buffer
+  const derivedKey = scrypt(Buffer.from(password, 'utf8'), salt, opt.n, opt.r, opt.p, opt.dklen); // instance of Buffer
+  const privateKeyCipher = createCipheriv(cipher, derivedKey.slice(0, sliceLength), iv);
+  const privateKeyEncrypted = Buffer.concat([
+    privateKeyCipher.update(Buffer.from(privateKey, 'hex')),
+    privateKeyCipher.final()
+  ]);
+  const mnemonicCipher = createCipheriv(cipher, derivedKey.slice(0, sliceLength), iv);
+  const mnemonicEncrypted = Buffer.concat([
+    mnemonicCipher.update(Buffer.from(mnemonic, 'utf8')),
+    mnemonicCipher.final()
+  ]);
+  const rawMac = Buffer.concat([derivedKey.slice(16), privateKeyEncrypted]);
+  const mac = keccak256(rawMac).replace('0x', '');
+  return {
+    version: 1,
+    type: 'aelf',
+    nickName,
+    address,
+    crypto: {
+      cipher,
+      ciphertext: privateKeyEncrypted.toString('hex'),
+      cipherparams: {
+        iv: iv.toString('hex')
+      },
+      mnemonicEncrypted: mnemonicEncrypted.toString('hex'),
+      kdf: 'scrypt',
+      kdfparams: {
+        r: opt.r,
+        n: opt.n,
+        p: opt.p,
+        dklen: opt.dklen,
+        salt: salt.toString('hex')
+      },
+      mac
+    }
+  };
+}
+ 
+/**
+ * unlock AElf key store
+ *
+ * @method unlockKeystore
+ * @param {Object} keyStoreInput  key store input
+ * @param {string} password password
+ * @return {Object} walletInfo
+ */
+export function unlockKeystore({ crypto, nickName = '', address = '' }, password) {
+  let error = null;
+  let result = null;
+  const { kdfparams, mac, cipherparams, mnemonicEncrypted = '', ciphertext, cipher = 'aes-128-ctr' } = crypto;
+  const sliceLength = /128/.test(cipher) ? 16 : 32;
+  const iv = Buffer.from(cipherparams.iv, 'hex');
+  const derivedKey = scrypt(
+    Buffer.from(password),
+    Buffer.from(kdfparams.salt, 'hex'),
+    kdfparams.n,
+    kdfparams.r,
+    kdfparams.p,
+    kdfparams.dklen || kdfparams.dkLen
+  );
+  const rawMac = Buffer.concat([derivedKey.slice(16), Buffer.from(ciphertext, 'hex')]);
+  const currentMac = keccak256(rawMac).replace('0x', '');
+  if (currentMac === mac) {
+    const privateKeyDeCipher = createDecipheriv(cipher, derivedKey.slice(0, sliceLength), iv);
+    const privateKey = Buffer.concat([
+      privateKeyDeCipher.update(Buffer.from(ciphertext, 'hex')),
+      privateKeyDeCipher.final()
+    ]).toString('hex');
+ 
+    const mnemonicDeCipher = createDecipheriv(cipher, derivedKey.slice(0, sliceLength), iv);
+    const mnemonic = Buffer.concat([
+      mnemonicDeCipher.update(Buffer.from(mnemonicEncrypted, 'hex')),
+      mnemonicDeCipher.final()
+    ]).toString('utf8');
+    result = {
+      nickName,
+      address,
+      mnemonic,
+      privateKey
+    };
+  } else {
+    error = { ...KEY_STORE_ERRORS.INVALID_PASSWORD };
+    throw error;
+  }
+ 
+  return result;
+}
+ 
+/**
+ * checkPassword
+ *
+ * @method checkPassword
+ * @param {Object} keyStoreInput  keyStoreInput
+ * @param {string} password password
+ * @return {boolean} true or false
+ */
+export const checkPassword = (keyStoreInput, password) => {
+  try {
+    const result = unlockKeystore(keyStoreInput, password);
+    return !!result.privateKey;
+  } catch (e) {
+    return false;
+  }
+};
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/util/merkleTree.js.html b/src/util/merkleTree.js.html new file mode 100644 index 00000000..1c11ebfb --- /dev/null +++ b/src/util/merkleTree.js.html @@ -0,0 +1,304 @@ + + + + + + Code coverage report for src/util/merkleTree.js + + + + + + + + + +
+
+

All files / src/util merkleTree.js

+
+ +
+ 100% + Statements + 53/53 +
+ + +
+ 100% + Branches + 22/22 +
+ + +
+ 100% + Functions + 6/6 +
+ + +
+ 100% + Lines + 49/49 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74  +  +8x +43x +  +42x +42x +15x +  +  +42x +42x +42x +  +  +8x +8x +1x +  +  +7x +7x +7x +7x +7x +42x +42x +42x +42x +  +19x +3x +3x +  +  +19x +19x +  +  +7x +  +  +8x +6x +6x +  +5x +5x +5x +5x +15x +15x +15x +15x +15x +15x +15x +  +5x +  +  +8x +1x +1x +  +  +8x +6x +6x +6x +  +  +24x + 
import sha256 from './sha256';
+ 
+const fromTwoBuffers = data => {
+  if (data.length !== 2) throw new TypeError('Wrong data size.');
+ 
+  const compared = Buffer.compare(data[0], data[1]);
+  if (compared > 0) {
+    data.reverse();
+  }
+ 
+  let buffer = Buffer.concat(data);
+  buffer = Buffer.from(sha256(buffer), 'hex');
+  return buffer;
+};
+ 
+const generateMerkleTree = data => {
+  if (data.length === 0) {
+    return null;
+  }
+ 
+  if (data.length % 2 === 1) { data.push(data[data.length - 1]); }
+  let nodeToAdd = data.length / 2;
+  let newAdded = 0;
+  let i = 0;
+  while (i < data.length - 1) {
+    const left = data[i++];
+    const right = data[i++];
+    data.push(fromTwoBuffers([left, right]));
+    if (++newAdded === nodeToAdd) {
+      // complete this row
+      if (nodeToAdd % 2 === 1 && nodeToAdd !== 1) {
+        nodeToAdd++;
+        data.push(data[data.length - 1]);
+      }
+      // start a new row
+      nodeToAdd /= 2;
+      newAdded = 0;
+    }
+  }
+  return data;
+};
+ 
+const generateMerklePath = (indexArg, leafCount, tree) => {
+  let index = indexArg;
+  if (tree.length === 0 || index >= leafCount) return null;
+ 
+  let firstInRow = 0;
+  let rowcount = leafCount;
+  const path = [];
+  while (index < tree.length - 1) {
+    const neighbor = index % 2 === 0 ? index + 1 : index - 1;
+    path.push(tree[neighbor]);
+    rowcount = rowcount % 2 === 0 ? rowcount : rowcount + 1;
+    const shift = Math.floor((index - firstInRow) / 2);
+    firstInRow += rowcount;
+    index = firstInRow + shift;
+    rowcount /= 2;
+  }
+  return path;
+};
+ 
+export const computeRoot = data => {
+  const merkleTree = generateMerkleTree(data);
+  return merkleTree[merkleTree.length - 1];
+};
+ 
+export const getMerklePath = (index, data) => {
+  const leafCount = data.length;
+  const merkleTree = generateMerkleTree(data);
+  return generateMerklePath(index, leafCount, merkleTree);
+};
+ 
+export const node = buffer => Buffer.from(sha256(buffer), 'hex');
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/util/proto.js.html b/src/util/proto.js.html new file mode 100644 index 00000000..05eaffc5 --- /dev/null +++ b/src/util/proto.js.html @@ -0,0 +1,859 @@ + + + + + + Code coverage report for src/util/proto.js + + + + + + + + + +
+
+

All files / src/util proto.js

+
+ +
+ 100% + Statements + 91/91 +
+ + +
+ 100% + Branches + 33/33 +
+ + +
+ 100% + Functions + 23/23 +
+ + +
+ 100% + Lines + 85/85 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254 +255 +256 +257 +258 +259  +  +  +  +  +  +  +  +  +  +  +  +14x +  +  +14x +11x +2x +  +9x +9x +9x +  +  +  +  +  +  +  +  +  +9x +9x +9x +  +  +14x +9x +9x +9x +8x +  +9x +  +  +14x +4x +1x +  +3x +1x +  +  +14x +6x +1x +  +5x +4x +  +  +  +  +  +  +  +  +  +14x +36x +  +  +  +  +  +  +  +  +14x +2x +2x +2x +1x +  +  +1x +  +2x +  +  +  +  +  +  +  +  +  +14x +47x +47x +  +  +  +  +  +  +  +  +  +  +  +14x +  +  +  +  +  +  +  +  +14x +2x +2x +2x +1x +  +  +1x +  +2x +  +  +  +  +  +  +  +  +  +14x +2x +  +  +  +  +  +  +  +  +  +  +14x +  +  +  +  +  +  +  +  +14x +  +  +  +  +  +  +  +  +  +  +  +14x +21x +  +  +  +  +  +21x +  +  +14x +5x +11x +9x +  +  +  +  +  +  +  +  +9x +  +  +  +  +  +3x +3x +3x +  +14x +  +9x +4x +  +5x +5x +  +  +5x +5x +5x +2x +  +  +5x +5x +4x +  +5x +  +2x +2x +2x +  +  +1x +  +  +  +3x +1x +  +  +  +  +2x +  +  +4x +  +  +  +  +  +  +  +  +  +14x +9x +9x +  +  + 
/**
+ * @file proto utils
+ * @author atom-yang
+ */
+import * as protobuf from '@aelfqueen/protobufjs';
+import * as utils from './utils';
+import { transform, OUTPUT_TRANSFORMERS, transformArrayToMap } from './transform';
+import coreDescriptor from '../../proto/transaction_fee.proto.json';
+import VirtualTransactionDescriptor from '../../proto/virtual_transaction.proto.json';
+ 
+// We cannot use loadSync because it's not supoort browsers
+// https://github.com/protobufjs/protobuf.js/issues/1648
+export const coreRootProto = protobuf.Root.fromJSON(coreDescriptor).nested.aelf;
+export const { Transaction, Hash, Address, TransactionFeeCharged, ResourceTokenCharged } = coreRootProto;
+ 
+export const getFee = (base64Str, type = 'TransactionFeeCharged') => {
+  if (['ResourceTokenCharged', 'TransactionFeeCharged'].indexOf(type) === -1) {
+    throw new Error('type needs to be one of ResourceTokenCharged and TransactionFeeCharged');
+  }
+  const dataType = coreRootProto[type];
+  let deserialize = dataType.decode(Buffer.from(base64Str, 'base64'));
+  deserialize = dataType.toObject(deserialize, {
+    enums: String, // enums as string names
+    longs: String, // longs as strings (requires long.js)
+    bytes: String, // bytes as base64 encoded strings
+    defaults: true, // includes default values
+    arrays: true, // populates empty arrays (repeated fields) even if defaults=false
+    objects: true, // populates empty objects (map fields) even if defaults=false
+    oneofs: true // includes virtual oneof fields set to the present field's name
+  });
+  // eslint-disable-next-line max-len
+  let deserializeLogResult = transform(dataType, deserialize, OUTPUT_TRANSFORMERS);
+  deserializeLogResult = transformArrayToMap(dataType, deserializeLogResult);
+  return deserializeLogResult;
+};
+ 
+export const getSerializedDataFromLog = log => {
+  const { NonIndexed, Indexed = [] } = log;
+  const serializedData = [...(Indexed || [])];
+  if (NonIndexed) {
+    serializedData.push(NonIndexed);
+  }
+  return serializedData.join('');
+};
+ 
+export const getResourceFee = (Logs = []) => {
+  if (!Array.isArray(Logs) || Logs.length === 0) {
+    return [];
+  }
+  return Logs.filter(log => log.Name === 'ResourceTokenCharged').map(v =>
+    getFee(getSerializedDataFromLog(v), 'ResourceTokenCharged'));
+};
+ 
+export const getTransactionFee = (Logs = []) => {
+  if (!Array.isArray(Logs) || Logs.length === 0) {
+    return [];
+  }
+  return Logs.filter(log => log.Name === 'TransactionFeeCharged').map(v =>
+    getFee(getSerializedDataFromLog(v), 'TransactionFeeCharged'));
+};
+ 
+/**
+ * arrayBuffer To Hex
+ *
+ * @alias module:AElf/pbUtils
+ * @param {Buffer} arrayBuffer arrayBuffer
+ * @return {string} hex string
+ */
+export const arrayBufferToHex = arrayBuffer =>
+  Array.prototype.map.call(new Uint8Array(arrayBuffer), n => `0${n.toString(16)}`.slice(-2)).join('');
+ 
+/**
+ * get hex rep From Address
+ *
+ * @alias module:AElf/pbUtils
+ * @param {protobuf} address kernel.Address
+ * @return {string} hex rep of address
+ */
+export const getRepForAddress = address => {
+  const message = Address.fromObject(address);
+  let hex = '';
+  if (message.value instanceof Buffer) {
+    hex = message.value.toString('hex');
+  } else {
+    // Uint8Array
+    hex = arrayBufferToHex(message.value);
+  }
+  return utils.encodeAddressRep(hex);
+};
+ 
+/**
+ * get address From hex rep
+ *
+ * @alias module:AElf/pbUtils
+ * @param {string} rep address
+ * @return {protobuf} address kernel.Address
+ */
+export const getAddressFromRep = rep => {
+  const hex = utils.decodeAddressRep(rep);
+  return Address.create({
+    value: Buffer.from(hex.replace('0x', ''), 'hex')
+  });
+};
+ 
+/**
+ * get address From hex rep
+ *
+ * @alias module:AElf/pbUtils
+ * @param {string} rep address
+ * @return {protobuf} address kernel.Address
+ */
+export const getAddressObjectFromRep = rep => Address.toObject(getAddressFromRep(rep));
+ 
+/**
+ * get hex rep From hash
+ *
+ * @alias module:AElf/pbUtils
+ * @param {protobuf} hash kernel.Hash
+ * @return {string} hex rep
+ */
+export const getRepForHash = hash => {
+  const message = Address.fromObject(hash);
+  let hex = '';
+  if (message.value instanceof Buffer) {
+    hex = message.value.toString('hex');
+  } else {
+    // Uint8Array
+    hex = arrayBufferToHex(message.value);
+  }
+  return hex;
+};
+ 
+/**
+ * get Hash From Hex
+ *
+ * @alias module:AElf/pbUtils
+ * @param {string} hex string
+ * @return {protobuf} kernel.Hash
+ */
+export const getHashFromHex = hex =>
+  Hash.create({
+    value: Buffer.from(hex.replace('0x', ''), 'hex')
+  });
+ 
+/**
+ * get Hash Object From Hex
+ *
+ * @alias module:AElf/pbUtils
+ * @param {string} hex string
+ * @return {Object} kernel.Hash Hash ot Object
+ */
+export const getHashObjectFromHex = hex => Hash.toObject(getHashFromHex(hex));
+ 
+/**
+ * encode Transaction to protobuf type
+ *
+ * @alias module:AElf/pbUtils
+ * @param {Object} tx object
+ * @return {protobuf} kernel.Transaction
+ */
+export const encodeTransaction = tx => Transaction.encode(tx).finish();
+ 
+/**
+ * get Transaction
+ *
+ * @alias module:AElf/pbUtils
+ * @param {string} from
+ * @param {string} to
+ * @param {string} methodName
+ * @param {string} params
+ * @return {protobuf} kernel.Transaction
+ */
+export const getTransaction = (from, to, methodName, params) => {
+  const txn = {
+    from: getAddressFromRep(from),
+    to: getAddressFromRep(to),
+    methodName,
+    params
+  };
+  return Transaction.create(txn);
+};
+ 
+const deserializeIndexedAndNonIndexed = (serializedData, dataType) => {
+  let deserializeLogResult = serializedData.reduce((acc, v) => {
+    let deserialize = dataType.decode(Buffer.from(v, 'base64'));
+    deserialize = dataType.toObject(deserialize, {
+      enums: String, // enums as string names
+      longs: String, // longs as strings (requires long.js)
+      bytes: String, // bytes as base64 encoded strings
+      defaults: false, // includes default values
+      arrays: true, // populates empty arrays (repeated fields) even if defaults=false
+      objects: true, // populates empty objects (map fields) even if defaults=false
+      oneofs: true // includes virtual oneof fields set to the present field's name
+    });
+    return {
+      ...acc,
+      ...deserialize
+    };
+  }, {});
+  // eslint-disable-next-line max-len
+  deserializeLogResult = transform(dataType, deserializeLogResult, OUTPUT_TRANSFORMERS);
+  deserializeLogResult = transformArrayToMap(dataType, deserializeLogResult);
+  return deserializeLogResult;
+};
+const deserializeWithServicesAndRoot = (logs, services, Root) => {
+  // filter by address and name
+  if (logs.length === 0) {
+    return [];
+  }
+  const results = logs.map(item => {
+    const { Name, NonIndexed, Indexed } = item;
+    let dataType;
+    // eslint-disable-next-line no-restricted-syntax
+    for (const service of services) {
+      try {
+        dataType = service.lookupType(Name);
+        break;
+      } catch (e) {}
+    }
+    const serializedData = [...(Indexed || [])];
+    if (NonIndexed) {
+      serializedData.push(NonIndexed);
+    }
+    if (Name === 'VirtualTransactionCreated') {
+      // VirtualTransactionCreated is system-default
+      try {
+        dataType = Root.VirtualTransactionCreated;
+        return deserializeIndexedAndNonIndexed(serializedData, dataType);
+      } catch (e) {
+        // if normal contract has a method called VirtualTransactionCreated
+        return deserializeIndexedAndNonIndexed(serializedData, dataType);
+      }
+    } else {
+      // if dataType cannot be found and also is not VirtualTransactionCreated
+      if (!dataType) {
+        return {
+          message: 'This log is not supported.'
+        };
+      }
+      // other method
+      return deserializeIndexedAndNonIndexed(serializedData, dataType);
+    }
+  });
+  return results;
+};
+/**
+ * deserialize logs
+ *
+ * @alias module:AElf/pbUtils
+ * @param {array} logs array of log which enclude Address,Name,Indexed and NonIndexed.
+ * @param {array} services array of service which got from getContractFileDescriptorSet
+ * @return {array} deserializeLogResult
+ */
+export const deserializeLog = (logs = [], services) => {
+  const Root = protobuf.Root.fromJSON(VirtualTransactionDescriptor);
+  return deserializeWithServicesAndRoot(logs, services, Root);
+};
+/* eslint-enable */
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/util/requestManage.js.html b/src/util/requestManage.js.html new file mode 100644 index 00000000..36546df9 --- /dev/null +++ b/src/util/requestManage.js.html @@ -0,0 +1,205 @@ + + + + + + Code coverage report for src/util/requestManage.js + + + + + + + + + +
+
+

All files / src/util requestManage.js

+
+ +
+ 100% + Statements + 11/11 +
+ + +
+ 100% + Branches + 5/5 +
+ + +
+ 100% + Functions + 5/5 +
+ + +
+ 100% + Lines + 11/11 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41  +  +  +  +  +  +  +35x +  +  +  +45x +  +  +  +  +  +  +  +2x +  +  +  +21x +1x +  +  +20x +20x +  +  +  +24x +1x +  +  +23x +23x +  +  + 
/**
+ * @file request methods, connected to rpc node
+ * @author atom-yang
+ */
+ 
+export default class RequestManager {
+  constructor(provider) {
+    this.provider = provider;
+  }
+ 
+  static prepareRequest({ requestMethod, method, params = {} }) {
+    return {
+      method: requestMethod.toUpperCase(),
+      url: method,
+      params
+    };
+  }
+ 
+  setProvider(provider) {
+    this.provider = provider;
+  }
+ 
+  send(requestBody) {
+    if (!this.provider) {
+      return null;
+    }
+ 
+    const payload = RequestManager.prepareRequest(requestBody);
+    return this.provider.send(payload);
+  }
+ 
+  sendAsync(requestBody) {
+    if (!this.provider) {
+      return null;
+    }
+ 
+    const payload = RequestManager.prepareRequest(requestBody);
+    return this.provider.sendAsync(payload);
+  }
+}
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/util/settings.js.html b/src/util/settings.js.html new file mode 100644 index 00000000..a7c86d63 --- /dev/null +++ b/src/util/settings.js.html @@ -0,0 +1,115 @@ + + + + + + Code coverage report for src/util/settings.js + + + + + + + + + +
+
+

All files / src/util settings.js

+
+ +
+ 100% + Statements + 1/1 +
+ + +
+ 100% + Branches + 0/0 +
+ + +
+ 100% + Functions + 1/1 +
+ + +
+ 100% + Lines + 1/1 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11  +  +  +  +  +  +  +13x +  +  + 
/**
+ * @file settings
+ * @author atom-yang
+ */
+ 
+export default class Settings {
+  constructor() {
+    this.defaultAccount = undefined;
+  }
+}
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/util/sha256.js.html b/src/util/sha256.js.html new file mode 100644 index 00000000..42692824 --- /dev/null +++ b/src/util/sha256.js.html @@ -0,0 +1,142 @@ + + + + + + Code coverage report for src/util/sha256.js + + + + + + + + + +
+
+

All files / src/util sha256.js

+
+ +
+ 100% + Statements + 13/13 +
+ + +
+ 100% + Branches + 0/0 +
+ + +
+ 100% + Functions + 2/2 +
+ + +
+ 100% + Lines + 13/13 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20  +  +15x +419x +419x +419x +419x +419x +  +15x +1x +1x +1x +1x +1x +  +15x +  +  + 
import { Sha256 } from '@aws-crypto/sha256-js';
+ 
+const sha256 = value => {
+  const hexStr = value;
+  const hash = new Sha256();
+  hash.update(hexStr);
+  const hashUint8Array = hash.digestSync();
+  return Buffer.from(hashUint8Array).toString('hex');
+};
+sha256.digest = value => {
+  const hexStr = value;
+  const hash = new Sha256();
+  hash.update(hexStr);
+  const hashUint8Array = hash.digestSync();
+  return hashUint8Array;
+};
+sha256.array = sha256.digest;
+ 
+export default sha256;
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/util/transform.js.html b/src/util/transform.js.html new file mode 100644 index 00000000..a81aa254 --- /dev/null +++ b/src/util/transform.js.html @@ -0,0 +1,838 @@ + + + + + + Code coverage report for src/util/transform.js + + + + + + + + + +
+
+

All files / src/util transform.js

+
+ +
+ 100% + Statements + 103/103 +
+ + +
+ 100% + Branches + 102/102 +
+ + +
+ 100% + Functions + 25/25 +
+ + +
+ 100% + Lines + 94/94 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252  +  +  +  +  +  +  +14x +128x +91x +  +37x +1x +  +36x +  +  +80x +  +48x +  +  +81x +81x +81x +2x +  +  +79x +127x +35x +  +  +  +44x +  +  +  +  +115x +115x +46x +2x +2x +1x +1x +1x +  +2x +  +  +  +  +44x +  +  +  +  +  +  +  +44x +  +  +  +51x +51x +51x +3x +  +48x +23x +  +  +  +  +  +  +  +  +25x +25x +2x +  +  +24x +  +  +  +52x +52x +24x +1x +1x +1x +  +  +  +  +23x +  +  +  +  +  +  +24x +  +  +  +50x +50x +50x +  +  +  +28x +  +  +  +  +  +22x +22x +  +  +  +  +  +1x +2x +  +  +  +  +  +  +  +21x +62x +62x +24x +  +  +  +  +3x +  +3x +  +  +  +  +  +1x +  +  +2x +  +  +  +  +  +  +  +2x +3x +2x +  +  +  +  +  +21x +  +  +  +  +  +  +21x +  +  +14x +  +  +  +24x +24x +23x +  +  +  +24x +1x +  +  +  +24x +  +  +  +  +  +3x +3x +2x +  +  +  +3x +1x +  +  +  +3x +  +  +  +  +  +14x +14x +  +  +14x +  +  +  +12x +12x +1x +11x +10x +  +12x +  +  +  +  +  +6x +6x +1x +5x +4x +  +6x +  +  +  + 
/**
+ * @file transform protobuf
+ * @author atom-yang
+ */
+import { base58, decodeAddressRep } from './utils';
+import { inputAddressFormatter } from './formatters';
+ 
+const isWrappedBytes = (resolvedType, name) => {
+  if (!resolvedType.name || resolvedType.name !== name) {
+    return false;
+  }
+  if (!resolvedType.fieldsArray || resolvedType.fieldsArray.length !== 1) {
+    return false;
+  }
+  return resolvedType.fieldsArray[0].type === 'bytes';
+};
+ 
+const isAddress = resolvedType => isWrappedBytes(resolvedType, 'Address');
+ 
+const isHash = resolvedType => isWrappedBytes(resolvedType, 'Hash');
+ 
+export function transform(inputType, origin, transformers = []) {
+  const fieldsLength = (inputType.fieldsArray || []).length;
+  let result = origin;
+  if (fieldsLength === 0) {
+    return origin;
+  }
+  // eslint-disable-next-line no-restricted-syntax
+  for (const { filter, transformer } of transformers) {
+    if (filter(inputType) && origin) {
+      return transformer(origin);
+    }
+  }
+  // eslint-disable-next-line no-restricted-syntax
+  Object.keys(inputType.fields).forEach(field => {
+    const {
+      rule,
+      name,
+      resolvedType
+    } = inputType.fields[field];
+    if (resolvedType) {
+      if (rule && rule === 'repeated') {
+        let value = origin[name];
+        if (value && Array.isArray(value)) {
+          value = value
+            .filter(v => v !== null && v !== undefined)
+            .map(item => transform(resolvedType, item, transformers));
+        }
+        result = {
+          ...result,
+          [name]: value
+        };
+      } else {
+        result = {
+          ...result,
+          [name]: origin[name] !== null && origin[name] !== undefined
+            ? transform(resolvedType, origin[name], transformers) : origin[name]
+        };
+      }
+    }
+  });
+  return result;
+}
+ 
+export function transformMapToArray(inputType, origin) {
+  const fieldsLength = inputType.fieldsArray ? inputType.fieldsArray.length : 0;
+  let result = origin;
+  if (!origin) {
+    return origin;
+  }
+  if (fieldsLength === 0 || (fieldsLength === 1 && !inputType.fieldsArray[0].resolvedType)) {
+    return origin;
+  }
+  // Params which satisfy address or hash format satisfy above first.
+  // if (isAddress(inputType) || isHash(inputType)) {
+  //   return origin;
+  // }
+  const {
+    fields,
+    options = {}
+  } = inputType;
+  if (fieldsLength === 2 && fields.value && fields.key && options.map_entry === true) {
+    return Object.keys(origin).map(key => ({ key, value: origin[key] }));
+  }
+  // eslint-disable-next-line no-restricted-syntax
+  Object.keys(inputType.fields).forEach(field => {
+    const {
+      name,
+      resolvedType
+    } = inputType.fields[field];
+    if (resolvedType) {
+      if (origin[name] && Array.isArray(origin[name])) {
+        let value = origin[name];
+        value = value.map(item => transformMapToArray(resolvedType, item));
+        result = {
+          ...result,
+          [name]: value
+        };
+      } else {
+        result = {
+          ...result,
+          [name]: transformMapToArray(resolvedType, origin[name])
+        };
+      }
+    }
+  });
+  return result;
+}
+ 
+export function transformArrayToMap(inputType, origin) {
+  const fieldsLength = (inputType.fieldsArray || []).length;
+  let result = origin;
+  if (
+    fieldsLength === 0
+    || (fieldsLength === 1 && !inputType.fieldsArray[0].resolvedType)
+  ) {
+    return origin;
+  }
+  // Params which satisfy address or hash format satisfy above first.
+  // if (isAddress(inputType) || isHash(inputType)) {
+  //   return origin;
+  // }
+  const { fields, options = {} } = inputType;
+  if (
+    fieldsLength === 2
+    && fields.value
+    && fields.key
+    && options.map_entry === true
+  ) {
+    return origin.reduce(
+      (acc, v) => ({
+        ...acc,
+        [v.key]: v.value,
+      }),
+      {}
+    );
+  }
+  // eslint-disable-next-line no-restricted-syntax
+  Object.keys(fields).forEach(field => {
+    const { name, resolvedType } = fields[field];
+    if (resolvedType && origin !== null && origin !== undefined) {
+      if (origin[name] && Array.isArray(origin[name])) {
+        const {
+          fieldsArray = [],
+          fields: resolvedFields,
+          options: resolvedOptions = {},
+        } = resolvedType;
+        // eslint-disable-next-line max-len
+        if (
+          fieldsArray.length === 2
+          && resolvedFields.value
+          && resolvedFields.key
+          && resolvedOptions.map_entry === true
+        ) {
+          result = {
+            ...result,
+            [name]: origin[name].reduce(
+              (acc, v) => ({
+                ...acc,
+                [v.key]: v.value,
+              }),
+              {}
+            ),
+          };
+        } else {
+          let value = origin[name];
+          value = value.map(item => transformArrayToMap(resolvedType, item));
+          result = {
+            ...result,
+            [name]: value,
+          };
+        }
+      } else {
+        result = {
+          ...result,
+          [name]: transformArrayToMap(resolvedType, origin[name]),
+        };
+      }
+    }
+  });
+  return result;
+}
+ 
+export const INPUT_TRANSFORMERS = [
+  {
+    filter: isAddress,
+    transformer: origin => {
+      let result = origin;
+      if (typeof origin === 'string') {
+        result = {
+          value: Buffer.from(decodeAddressRep(inputAddressFormatter(origin)), 'hex')
+        };
+      }
+      if (Array.isArray(origin)) {
+        result = origin.map(h => ({
+          value: Buffer.from(decodeAddressRep(inputAddressFormatter(h)), 'hex')
+        }));
+      }
+      return result;
+    }
+  },
+  {
+    filter: isHash,
+    transformer: origin => {
+      let result = origin;
+      if (typeof origin === 'string') {
+        result = {
+          value: Buffer.from(origin.replace('0x', ''), 'hex')
+        };
+      }
+      if (Array.isArray(origin)) {
+        result = origin.map(h => ({
+          value: Buffer.from(h.replace('0x', ''), 'hex')
+        }));
+      }
+      return result;
+    }
+  },
+];
+ 
+export function encodeAddress(str) {
+  const buf = Buffer.from(str, 'base64');
+  return base58.encode(buf);
+}
+ 
+export const OUTPUT_TRANSFORMERS = [
+  {
+    filter: isAddress,
+    transformer: origin => {
+      let result = origin;
+      if (Array.isArray(result)) {
+        result = result.map(h => encodeAddress(h.value));
+      } else if (typeof result !== 'string') {
+        result = encodeAddress(result.value);
+      }
+      return result;
+    }
+  },
+  {
+    filter: isHash,
+    transformer: origin => {
+      let result = origin;
+      if (Array.isArray(result)) {
+        result = result.map(h => Buffer.from(h.value, 'base64').toString('hex'));
+      } else if (typeof result !== 'string') {
+        result = Buffer.from(result.value, 'base64').toString('hex');
+      }
+      return result;
+    }
+  },
+];
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/util/utils.js.html b/src/util/utils.js.html new file mode 100644 index 00000000..f911e037 --- /dev/null +++ b/src/util/utils.js.html @@ -0,0 +1,1483 @@ + + + + + + Code coverage report for src/util/utils.js + + + + + + + + + +
+
+

All files / src/util utils.js

+
+ +
+ 100% + Statements + 125/125 +
+ + +
+ 100% + Branches + 56/56 +
+ + +
+ 100% + Functions + 33/33 +
+ + +
+ 100% + Lines + 120/120 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254 +255 +256 +257 +258 +259 +260 +261 +262 +263 +264 +265 +266 +267 +268 +269 +270 +271 +272 +273 +274 +275 +276 +277 +278 +279 +280 +281 +282 +283 +284 +285 +286 +287 +288 +289 +290 +291 +292 +293 +294 +295 +296 +297 +298 +299 +300 +301 +302 +303 +304 +305 +306 +307 +308 +309 +310 +311 +312 +313 +314 +315 +316 +317 +318 +319 +320 +321 +322 +323 +324 +325 +326 +327 +328 +329 +330 +331 +332 +333 +334 +335 +336 +337 +338 +339 +340 +341 +342 +343 +344 +345 +346 +347 +348 +349 +350 +351 +352 +353 +354 +355 +356 +357 +358 +359 +360 +361 +362 +363 +364 +365 +366 +367 +368 +369 +370 +371 +372 +373 +374 +375 +376 +377 +378 +379 +380 +381 +382 +383 +384 +385 +386 +387 +388 +389 +390 +391 +392 +393 +394 +395 +396 +397 +398 +399 +400 +401 +402 +403 +404 +405 +406 +407 +408 +409 +410 +411 +412 +413 +414 +415 +416 +417 +418 +419 +420 +421 +422 +423 +424 +425 +426 +427 +428 +429 +430 +431 +432 +433 +434 +435 +436 +437 +438 +439 +440 +441 +442 +443 +444 +445 +446 +447 +448 +449 +450 +451 +452 +453 +454 +455 +456 +457 +458 +459 +460 +461 +462 +463 +464 +465 +466 +467  +  +  +  +  +  +  +  +  +  +  +  +14x +  +34x +34x +2x +  +34x +1x +  +33x +33x +33x +33x +33x +  +  +115x +115x +115x +115x +115x +115x +460x +1x +  +  +114x +111x +  +114x +  +  +  +14x +  +  +1x +1x +1x +1x +  +  +1x +  +  +  +14x +4x +  +14x +2x +2x +1x +  +  +1x +  +2x +  +  +  +  +  +  +  +  +  +  +  +14x +11x +11x +  +  +  +  +  +  +  +  +  +  +  +14x +3x +3x +  +  +  +  +  +  +  +  +  +14x +72x +4x +4x +4x +  +68x +  +  +  +  +  +  +  +  +  +14x +17x +17x +  +  +  +  +  +  +  +  +  +14x +20x +  +  +  +  +  +  +  +  +14x +14x +  +  +  +  +  +  +  +  +73x +  +  +  +  +  +  +  +  +14x +  +  +  +  +  +  +  +  +77x +  +  +  +  +  +  +  +  +14x +5x +5x +  +3x +  +  +  +  +  +  +  +  +  +  +14x +  +  +  +  +  +  +  +  +14x +12x +12x +4x +  +  +8x +2x +  +  +6x +  +  +  +  +  +  +  +  +  +  +14x +7x +7x +  +1x +  +  +  +6x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +14x +2x +  +2x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +14x +2x +  +2x +  +  +  +  +  +  +  +  +  +  +14x +4x +4x +3x +  +1x +  +  +  +  +  +  +  +  +  +14x +2x +2x +6x +6x +3x +  +6x +  +2x +  +  +  +  +  +14x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +14x +496x +496x +500x +496x +496x +  +4x +4x +  +  +  +14x +8x +8x +8x +  +  +  +  +  +  +  +  +8x +  +  +  +1x +  +  +  +1x +  +  +  +  +1x +1x +  +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +1x +  +  +  +  +  +  +  +  +  +  +  +  +1x +1x +1x +1x +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  + 
/**
+ * @file common utils
+ * @author atom-yang
+ */
+ 
+import BigNumber from 'bignumber.js';
+import bs58 from 'bs58';
+import { UNIT_MAP, UNSIGNED_256_INT } from '../common/constants';
+import { Transaction } from './proto';
+import { OUTPUT_TRANSFORMERS, encodeAddress, transform, transformArrayToMap } from './transform';
+import sha256 from './sha256';
+ 
+export const base58 = {
+  encode(data, encoding = 'hex') {
+    let result = data;
+    if (typeof data === 'string') {
+      result = Buffer.from(data, encoding);
+    }
+    if (!(result instanceof Buffer)) {
+      throw new TypeError('"data" argument must be an Array of Buffers');
+    }
+    let hash = result;
+    hash = Buffer.from(sha256(result), 'hex');
+    hash = Buffer.from(sha256(hash), 'hex');
+    hash = Buffer.from(result.toString('hex') + hash.slice(0, 4).toString('hex'), 'hex');
+    return bs58.encode(hash);
+  },
+  decode(str, encoding) {
+    const buffer = Buffer.from(bs58.decode(str));
+    let data = buffer.slice(0, -4);
+    let hash = data;
+    hash = Buffer.from(sha256(hash), 'hex');
+    hash = Buffer.from(sha256(hash), 'hex');
+    buffer.slice(-4).forEach((check, index) => {
+      if (check !== hash[index]) {
+        throw new Error('Invalid checksum');
+      }
+    });
+    if (encoding) {
+      data = data.toString(encoding);
+    }
+    return data;
+  }
+};
+ 
+export const chainIdConvertor = {
+  // chainIdToBase58 (int32 chainId)
+  chainIdToBase58(chainId) {
+    const bufferTemp = Buffer.alloc(4);
+    bufferTemp.writeInt32LE(`0x${chainId.toString('16')}`, 0);
+    const bytes = Buffer.concat([bufferTemp], 3);
+    return bs58.encode(bytes);
+  },
+  base58ToChainId(base58String) {
+    return Buffer.concat([bs58.decode(base58String)], 4).readInt32LE(0);
+  }
+};
+ 
+const arrayBufferToHex = arrayBuffer =>
+  Array.prototype.map.call(new Uint8Array(arrayBuffer), n => `0${n.toString(16)}`.slice(-2)).join('');
+ 
+export const arrayToHex = value => {
+  let hex = '';
+  if (value instanceof Buffer) {
+    hex = value.toString('hex');
+  } else {
+    // Uint8Array
+    hex = arrayBufferToHex(value);
+  }
+  return hex;
+};
+ 
+/**
+ * Should be called to pad string to expected length
+ *
+ * @method padLeft
+ * @param {String} string to be padded
+ * @param {Number} charLen that result string should have
+ * @param {String} sign, by default 0
+ * @returns {String} right aligned string
+ */
+export const padLeft = (string, charLen, sign) => {
+  const length = charLen - string.length + 1;
+  return new Array(length < 0 ? 0 : length).join(sign || '0') + string;
+};
+ 
+/**
+ * Should be called to pad string to expected length
+ *
+ * @method padRight
+ * @param {String} string to be padded
+ * @param {Number} charLen that result string should have
+ * @param {String} sign, by default 0
+ * @returns {String} right aligned string
+ */
+export const padRight = (string, charLen, sign) => {
+  const length = charLen - string.length + 1;
+  return string + new Array(length < 0 ? 0 : length).join(sign || '0');
+};
+ 
+/**
+ * Returns a hex rep from the encoded address
+ *
+ * @method decodeAddressRep
+ * @param {String} address
+ * @return {String}
+ */
+export const decodeAddressRep = address => {
+  if (address.indexOf('_') > -1) {
+    const parts = address.split('_');
+    const b58rep = parts[1];
+    return base58.decode(b58rep, 'hex');
+  }
+  return base58.decode(address, 'hex');
+};
+ 
+/**
+ * Returns a encoded address from the hex rep
+ *
+ * @method encodeAddressRep
+ * @param {String} hex
+ * @return {String}
+ */
+export const encodeAddressRep = hex => {
+  const buf = Buffer.from(hex.replace('0x', ''), 'hex');
+  return base58.encode(buf, 'hex');
+};
+ 
+/**
+ * Returns true if object is BigNumber, otherwise false
+ *
+ * @method isBigNumber
+ * @param {Object} object
+ * @return {Boolean}
+ */
+export const isBigNumber = object =>
+  object instanceof BigNumber || (object && object.constructor && object.constructor.name === 'BigNumber');
+ 
+/**
+ * Returns true if object is string, otherwise false
+ *
+ * @method isString
+ * @param {Object} object
+ * @return {Boolean}
+ */
+export const isString = object =>
+  typeof object === 'string' || (object && object.constructor && object.constructor.name === 'String');
+ 
+/**
+ * Returns true if object is function, otherwise false
+ *
+ * @method isFunction
+ * @param {Object} object
+ * @return {Boolean}
+ */
+export const isFunction = object => typeof object === 'function';
+ 
+/**
+ * Returns true if object is Object, otherwise false
+ *
+ * @method isObject
+ * @param {Object} object
+ * @return {Boolean}
+ */
+export const isObject = object => object !== null && !Array.isArray(object) && typeof object === 'object';
+ 
+/**
+ * Returns true if object is boolean, otherwise false
+ *
+ * @method isBoolean
+ * @param {Object} object
+ * @return {Boolean}
+ */
+export const isBoolean = object => typeof object === 'boolean';
+ 
+/**
+ * Returns true if given string is valid json object
+ *
+ * @method isJson
+ * @param {String} str
+ * @return {Boolean}
+ */
+export const isJson = str => {
+  try {
+    return !!JSON.parse(str);
+  } catch (e) {
+    return false;
+  }
+};
+ 
+/**
+ * Returns true if given number is valid number
+ *
+ * @method isNumber
+ * @param {Number} number
+ * @return {Boolean}
+ */
+export const isNumber = number => number === +number;
+ 
+/**
+ * Takes an input and transforms it into an bignumber
+ *
+ * @method toBigNumber
+ * @param {Number|String|BigNumber} number, a number, string, HEX string or BigNumber
+ * @return {BigNumber} BigNumber
+ */
+export const toBigNumber = number => {
+  const num = number || 0;
+  if (isBigNumber(num)) {
+    return num;
+  }
+ 
+  if (isString(num) && (num.indexOf('0x') === 0 || num.indexOf('-0x') === 0)) {
+    return new BigNumber(num.replace('0x', ''), 16);
+  }
+ 
+  return new BigNumber(num.toString(10), 10);
+};
+ 
+/**
+ * Returns value of unit in Wei
+ *
+ * @method getValueOfUnit
+ * @param {String} unit the unit to convert to, default ether
+ * @returns {BigNumber} value of the unit (in Wei)
+ * @throws error if the unit is not correct:w
+ */
+export const getValueOfUnit = unit => {
+  const unitValue = UNIT_MAP[unit ? unit.toLowerCase() : 'ether'];
+  if (unitValue === undefined) {
+    // eslint-disable-next-line max-len
+    throw new Error(
+      `This unit doesn\'t exists, please use the one of the following units ${JSON.stringify(UNIT_MAP, null, 2)}`
+    );
+  }
+  return new BigNumber(unitValue, 10);
+};
+ 
+/**
+ * Takes a number of wei and converts it to any other ether unit.
+ *
+ * Possible units are:
+ *   SI Short   SI Full        Effigy       Other
+ * - kwei       femtoether     babbage
+ * - mwei       picoether      lovelace
+ * - gwei       nanoether      shannon      nano
+ * - --         microether     szabo        micro
+ * - --         milliether     finney       milli
+ * - ether      --             --
+ * - kether                    --           grand
+ * - mether
+ * - gether
+ * - tether
+ *
+ * @method fromWei
+ * @param {Number|String} number can be a number, number string or a HEX of a decimal
+ * @param {String} unit the unit to convert to, default ether
+ * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number
+ */
+export const fromWei = (number, unit) => {
+  const returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit));
+ 
+  return isBigNumber(number) ? returnValue : returnValue.toString(10);
+};
+ 
+/**
+ * Takes a number of a unit and converts it to wei.
+ *
+ * Possible units are:
+ *   SI Short   SI Full        Effigy       Other
+ * - kwei       femtoether     babbage
+ * - mwei       picoether      lovelace
+ * - gwei       nanoether      shannon      nano
+ * - --         microether     szabo        micro
+ * - --         milliether     finney       milli
+ * - ether      --             --
+ * - kether                    --           grand
+ * - mether
+ * - gether
+ * - tether
+ *
+ * @method toWei
+ * @param {Number|String|BigNumber} number can be a number, number string or a HEX of a decimal
+ * @param {String} unit the unit to convert from, default ether
+ * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number
+ */
+export const toWei = (number, unit) => {
+  const returnValue = toBigNumber(number).times(getValueOfUnit(unit));
+ 
+  return isBigNumber(number) ? returnValue : returnValue.toString(10);
+};
+ 
+/**
+ * Takes and input transforms it into bignumber and if it is negative value, into two's complement
+ * bignumber.js get rid of round + floor in 6.0 https://github.com/MikeMcl/bignumber.js/issues/139
+ * the method lessThan was named isLessThan after 6.0 https://github.com/MikeMcl/bignumber.js/issues/152
+ * @method toTwosComplement
+ * @param {Number|String|BigNumber} number
+ * @return {BigNumber}
+ */
+export const toTwosComplement = number => {
+  const bigNumber = toBigNumber(number).integerValue();
+  if (bigNumber.isLessThan(0)) {
+    return new BigNumber(UNSIGNED_256_INT, 16).plus(bigNumber).plus(1);
+  }
+  return bigNumber;
+};
+ 
+/**
+ * Returns hex
+ *
+ * @method uint8ArrayToHex
+ * @param {Array} uint8Array
+ * @return {String}
+ */
+export const uint8ArrayToHex = uint8Array => {
+  let string = '';
+  uint8Array.forEach(item => {
+    let hex = item.toString(16);
+    if (hex.length <= 1) {
+      hex = `0${hex}`;
+    }
+    string += hex;
+  });
+  return string;
+};
+ 
+/**
+ * empty function
+ */
+export const noop = () => {};
+ 
+/**
+ *
+ * @param {object} obj The object to modify
+ * @param {string} path The path of the property to set
+ * @param {*} value The value to set
+ * @example
+ *
+ * const object = { 'a': [{ 'b': { 'c': 3 } }] }
+ *
+ * set(object, 'test.b.c', 4)
+ * console.log(object.test.b.c)
+ * // => 4
+ */
+export const setPath = (obj, path, value) => {
+  const paths = path.split('.');
+  paths.reduce((acc, p, index) => {
+    if (index === paths.length - 1) {
+      acc[p] = value;
+      return acc;
+    }
+    acc[p] = {};
+    return acc[p];
+  }, obj);
+};
+ 
+export const unpackSpecifiedTypeData = ({ data, dataType, encoding = 'hex' }) => {
+  const buffer = Buffer.from(data, encoding);
+  const decoded = dataType.decode(buffer);
+  const result = dataType.toObject(decoded, {
+    enums: String, // enums as string names
+    longs: String, // longs as strings (requires long.js)
+    bytes: String, // bytes as base64 encoded strings
+    defaults: true, // includes default values
+    arrays: true, // populates empty arrays (repeated fields) even if defaults=false
+    objects: true, // populates empty objects (map fields) even if defaults=false
+    oneofs: true // includes virtual oneof fields set to the present field's name
+  });
+  return result;
+};
+ 
+export function deserializeTransaction(rawTx, paramsDataType) {
+  const { from, to, params, refBlockPrefix, signature, ...rest } = unpackSpecifiedTypeData({
+    data: rawTx,
+    dataType: Transaction
+  });
+  let methodParameters = unpackSpecifiedTypeData({
+    data: params,
+    encoding: 'base64',
+    dataType: paramsDataType
+  });
+  methodParameters = transform(paramsDataType, methodParameters, OUTPUT_TRANSFORMERS);
+  methodParameters = transformArrayToMap(paramsDataType, methodParameters);
+ 
+  return {
+    from: encodeAddress(from.value),
+    to: encodeAddress(to.value),
+    params: methodParameters,
+    refBlockPrefix: Buffer.from(refBlockPrefix, 'base64').toString('hex'),
+    signature: Buffer.from(signature, 'base64').toString('hex'),
+    ...rest
+  };
+}
+/**
+ *
+ * @param {String} userName Username
+ * @param {String} password Password
+ * @return {any} Authorization information
+ *
+ * const authorization = getAuthorization('test','pass')
+ * console.log(authorization)
+ * // => Basic dGVzdDpwYXNz
+ */
+export function getAuthorization(userName, password) {
+  const base = Buffer.from(`${userName}:${password}`).toString('base64');
+  return `Basic ${base}`;
+}
+/**
+ *
+ * Use rawTransaction to get transaction id
+ * @param {String} rawTx rawTransaction
+ * @return {String} string
+ *
+ * const txId = getTransactionId('0a220a2071a4dc8cdf109bd72913c90c3fc666c78d080cdda0da7f3abbc7105c6b651fd512220a2089ac786c8ad3b56f63a6f2767369a5273f801de2415b613c783cad3d148ce3ab18d5d3bb35220491cf6ba12a18537761704578616374546f6b656e73466f72546f6b656e73325008c0f7f27110bbe5947c1a09534752544553542d311a03454c4622220a2071a4dc8cdf109bd72913c90c3fc666c78d080cdda0da7f3abbc7105c6b651fd52a08088996ceb0061000320631323334353682f10441ec6ad50c4b210976ba0ba5c287ab6fabd0c444839e2505ecb1b5f52838095b290cb245ec1c97dade3bde6ac14c6892e526569e9b71240d3c120b1a6c8e41afba00');
+ * console.log(txId);
+ * // => cf564f3169012cb173efcf5543b2a71b030b16fad3ddefe3e04a5c1e1bc0047d
+ */
+export function getTransactionId(rawTx) {
+  const hash = Buffer.from(rawTx.replace('0x', ''), 'hex');
+  const decode = Transaction.decode(hash);
+  decode.signature = null;
+  const encode = Transaction.encode(decode).finish();
+  return sha256(encode);
+}
+ 
+// /**
+//  * Converts value to it's hex representation
+//  *
+//  * @method fromDecimal
+//  * @param {String|Number|BigNumber}
+//  * @return {String}
+//  */
+// export const fromDecimal = value => {
+//   const number = toBigNumber(value);
+//   const result = number.toString(16);
+//
+//   return number.lessThan(0) ? `-0x${result.substr(1)}` : `0x${result}`;
+// };
+//
+// /**
+//  * Should be called to get hex representation (prefixed by 0x) of utf8 string
+//  *
+//  * @method fromUtf8
+//  * @param {String} string
+//  * @param {Boolean} allowZero to convert code point zero to 00 instead of end of string
+//  * @returns {String} hex representation of input string
+//  */
+// export const fromUtf8 = (str, allowZero) => {
+//   const encodeStr = utf8.encode(str);
+//   let hex = '';
+//   for (let i = 0; i < encodeStr.length; i++) {
+//     const code = encodeStr.charCodeAt(i);
+//     if (code === 0) {
+//       if (allowZero) {
+//         hex += '00';
+//       } else {
+//         break;
+//       }
+//     } else {
+//       const n = code.toString(16);
+//       hex += n.length < 2 ? `0${n}` : n;
+//     }
+//   }
+//   return `0x${hex}`;
+// };
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/src/wallet/index.html b/src/wallet/index.html new file mode 100644 index 00000000..b66844ac --- /dev/null +++ b/src/wallet/index.html @@ -0,0 +1,116 @@ + + + + + + Code coverage report for src/wallet + + + + + + + + + +
+
+

All files src/wallet

+
+ +
+ 100% + Statements + 73/73 +
+ + +
+ 90.9% + Branches + 20/22 +
+ + +
+ 100% + Functions + 12/12 +
+ + +
+ 100% + Lines + 69/69 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
index.js +
+
100%73/7390.9%20/22100%12/12100%69/69
+
+
+
+ + + + + + + + \ No newline at end of file diff --git a/src/wallet/index.js.html b/src/wallet/index.js.html new file mode 100644 index 00000000..f6481544 --- /dev/null +++ b/src/wallet/index.js.html @@ -0,0 +1,961 @@ + + + + + + Code coverage report for src/wallet/index.js + + + + + + + + + +
+
+

All files / src/wallet index.js

+
+ +
+ 100% + Statements + 73/73 +
+ + +
+ 90.9% + Branches + 20/22 +
+ + +
+ 100% + Functions + 12/12 +
+ + +
+ 100% + Lines + 69/69 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254 +255 +256 +257 +258 +259 +260 +261 +262 +263 +264 +265 +266 +267 +268 +269 +270 +271 +272 +273 +274 +275 +276 +277 +278 +279 +280 +281 +282 +283 +284 +285 +286 +287 +288 +289 +290 +291 +292 +293  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +9x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +9x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +9x +  +  +  +  +  +  +  +  +  +  +  +  +9x +13x +13x +13x +13x +  +  +9x +  +  +  +13x +13x +13x +13x +  +13x +  +1x +1x +1x +1x +1x +1x +  +2x +2x +2x +2x +2x +2x +  +9x +8x +  +1x +  +9x +  +1x +  +  +  +  +  +  +  +12x +12x +12x +12x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +9x +19x +19x +19x +  +  +19x +  +  +19x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +9x +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +9x +3x +2x +  +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +9x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +9x +18x +18x +1x +  +  +  +  +  +18x +18x +18x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +9x +1x +1x +  +  +9x +  +  +  +  +  +  +9x +2x +2x +2x +2x +  +  +  +  +  +2x +1x +1x +  +1x +  +2x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  + 
/**
+ * @file wallet
+ * @author atom-yang
+ */
+import elliptic from 'elliptic';
+import * as bip39 from 'bip39';
+import hdkey from 'hdkey';
+import AES from 'crypto-js/aes';
+import encUTF8 from 'crypto-js/enc-utf8';
+import BN from 'bn.js';
+import sha256 from '../util/sha256';
+import * as keyStore from '../util/keyStore';
+import { encodeAddressRep, padLeft } from '../util/utils';
+import { Transaction } from '../util/proto';
+ 
+// eslint-disable-next-line new-cap
+const ellipticEc = new elliptic.ec('secp256k1');
+ 
+/**
+ * Advanced Encryption Standard need crypto-js
+ *
+ * @alias module:AElf/wallet
+ * @param {string} input anything you want to encrypt
+ * @param {string} password password
+ * @return {string} using base64 encoding way
+ *
+ * @Example
+ * const AESEncryptPrivateKey = aelf.wallet.AESEncrypt('123', '123');
+ * // AESEncryptPrivateKey = "U2FsdGVkX1+RYovrVJVEEl8eiIUA3vx4GrNR+3sqOow="
+ * const AESEncryptMnemonic = alef.wallet.AESEncrypt('hello world', '123');
+ * // AESEncryptMnemonic = U2FsdGVkX19gCjHzYmoY5FGZA1ArXG+eGZIR77dK2GE=
+ *
+ */
+const AESEncrypt = (input, password) => AES.encrypt(input, password).toString();
+ 
+/**
+ * Decrypt any encrypted information you want to decrypt
+ *
+ * @alias module:AElf/wallet
+ * @param {string} input anything you want to decrypt
+ * @param {string} password password
+ * @return {string} decrypted input, using utf8 decoding way
+ *
+ * @Example
+ * const AESDecryptPrivateKey = aelf.wallet.AESDecrypt('U2FsdGVkX18+tvF7t4rhGOi5cbUvdTH2U5a6Tbu4Ojg=', '123');
+ * // AESDecryptPrivateKey = "123"
+ * const AESDecryptMnemonic = aelf.wallet.AESDecrypt('U2FsdGVkX19gCjHzYmoY5FGZA1ArXG+eGZIR77dK2GE=', '123');
+ * // AESDecryptMnemonic = "hello world"
+ */
+const AESDecrypt = (input, password) => AES.decrypt(input, password).toString(encUTF8);
+ 
+/**
+ * the same as in C#
+ *
+ * @alias module:AElf/wallet
+ * @param {Object} pubKey get the pubKey you want through keyPair
+ * @return {string} address encoded address
+ *
+ * @Example
+ * const pubKey = wallet.keyPair.getPublic();
+ * const address = aelf.wallet.getAddressFromPubKey(pubKey);
+ */
+const getAddressFromPubKey = pubKey => {
+  const pubKeyEncoded = pubKey.encode();
+  const onceSHAResult = Buffer.from(sha256(pubKeyEncoded), 'hex');
+  const hash = sha256(onceSHAResult).slice(0, 64);
+  return encodeAddressRep(hash);
+};
+ 
+const _getWallet = (type, value, BIP44Path = "m/44'/1616'/0'/0/0", seedWithBuffer = true) => {
+  // m/purpose'/coin_type'/account'/change/address_index
+  // "m/44'/1616'/0'/0/0"
+ 
+  let mnemonic = '';
+  let rootSeed = '';
+  let childWallet = '';
+  let keyPair = '';
+  let hdWallet;
+  switch (type) {
+    case 'createNewWallet':
+      mnemonic = bip39.generateMnemonic();
+      rootSeed = bip39.mnemonicToSeedSync(mnemonic).toString('hex');
+      hdWallet = hdkey.fromMasterSeed(seedWithBuffer ? Buffer.from(rootSeed, 'hex') : rootSeed);
+      childWallet = hdWallet.derive(BIP44Path);
+      keyPair = ellipticEc.keyFromPrivate(childWallet.privateKey);
+      break;
+    case 'getWalletByMnemonic':
+      mnemonic = value;
+      rootSeed = bip39.mnemonicToSeedSync(mnemonic).toString('hex');
+      hdWallet = hdkey.fromMasterSeed(seedWithBuffer ? Buffer.from(rootSeed, 'hex') : rootSeed);
+      childWallet = hdWallet.derive(BIP44Path);
+      keyPair = ellipticEc.keyFromPrivate(childWallet.privateKey);
+      break;
+    case 'getWalletByPrivateKey':
+      if (typeof value === 'string') {
+        keyPair = ellipticEc.keyFromPrivate(padLeft(value, 64, '0'));
+      } else {
+        keyPair = ellipticEc.keyFromPrivate(value);
+      }
+      break;
+    default:
+      throw new Error('not a valid method');
+  }
+  // let mnemonic = bip39.generateMnemonic();
+  // let rootSeed = bip39.mnemonicToSeedHex(mnemonic);
+  // let hdWallet = hdkey.fromMasterSeed(Buffer.from(rootSeed, 'hex'));
+  // let keyPair = ec.keyFromPrivate(xPrivateKey);
+  // TODO 1.将私钥加密保存,用密码解密才能使用。
+  // TODO 2.将助记词机密保存,用密码解密才能获取。
+  const privateKey = keyPair.getPrivate().toString(16, 64);
+  const publicKey = keyPair.getPublic();
+  const address = getAddressFromPubKey(publicKey);
+  return {
+    mnemonic,
+    BIP44Path,
+    childWallet,
+    keyPair,
+    privateKey,
+    address
+  };
+};
+ 
+/**
+ * get signature
+ * @param bytesToBeSign
+ * @param keyPair
+ * @returns {Buffer}
+ */
+const getSignature = (bytesToBeSign, keyPair) => {
+  const privateKey = keyPair.getPrivate('hex');
+  const msgHash = sha256(bytesToBeSign);
+  const sigObj = ellipticEc.sign(Buffer.from(msgHash, 'hex'), privateKey, 'hex', {
+    canonical: true
+  });
+  const hex = [sigObj.r.toString('hex', 32), sigObj.s.toString('hex', 32), `0${sigObj.recoveryParam.toString()}`].join(
+    ''
+  );
+  return Buffer.from(hex, 'hex');
+};
+ 
+/**
+ * create a wallet
+ *
+ * @alias module:AElf/wallet
+ * @param {string} BIP44Path
+ * @return {Object} wallet
+ *
+ * @Example
+ * const wallet = aelf.wallet.createNewWallet();
+ * // The format returned is similar to this
+ * // wallet = {
+ * //     mnemonic: "hello world",
+ * //     BIP44Path: 'm/44\'/1616\'/0\'/0/0',
+ * //     childWallet: {},
+ * //     keyPair: KeyPair {ec: EC, priv: BN, pub: Point}
+ * //     privateKey: "123f7c123"
+ * //     address: "5uhk3434242424"
+ * // }
+ */
+const createNewWallet = (BIP44Path = "m/44'/1616'/0'/0/0", seedWithBuffer = true) =>
+  _getWallet('createNewWallet', '', BIP44Path, seedWithBuffer);
+ 
+/**
+ * create a wallet by mnemonic
+ *
+ * @alias module:AElf/wallet
+ * @param {string} mnemonic base on bip39
+ * @param {string} BIP44Path
+ * @return {Object} wallet
+ *
+ * @Example
+ *
+ * const mnemonicWallet = aelf.wallet.getWalletByMnemonic('hello world');
+ */
+const getWalletByMnemonic = (mnemonic, BIP44Path = "m/44'/1616'/0'/0/0", seedWithBuffer = true) => {
+  if (bip39.validateMnemonic(mnemonic)) {
+    return _getWallet('getWalletByMnemonic', mnemonic, BIP44Path, seedWithBuffer);
+  }
+  return false;
+};
+ 
+/**
+ * create a wallet by private key
+ *
+ * @alias module:AElf/wallet
+ * @param {string} privateKey privateKey
+ * @return {Object} wallet
+ *
+ * @Example
+ * const privateKeyWallet = aelf.wallet.getWalletByPrivateKey('123');
+ *
+ */
+const getWalletByPrivateKey = privateKey => _getWallet('getWalletByPrivateKey', privateKey);
+ 
+/**
+ * sign a transaction
+ *
+ * @alias module:AElf/wallet
+ * @param {Object} rawTxn rawTxn
+ * @param {Object} keyPair Any standard key pair
+ * @return {Object} wallet
+ *
+ * @Example
+ * const rawTxn = proto.getTransaction(
+ *    'ELF_65dDNxzcd35jESiidFXN5JV8Z7pCwaFnepuYQToNefSgqk9',
+ *    'ELF_65dDNxzcd35jESiidFXN5JV8Z7pCwaFnepuYQToNefSgqk9',
+ *    'test',
+ *    []
+ * );
+ * const signWallet = aelf.wallet.signTransaction(rawTxn, wallet.keyPair);
+ */
+const signTransaction = (rawTxn, keyPair) => {
+  let { params } = rawTxn;
+  if (params.length === 0) {
+    params = null;
+  }
+  // proto in proto.Transaction use proto2, but C# use proto3
+  // proto3 will remove the default value key.
+  // The differences between proto2 and proto3:
+  // https://blog.csdn.net/huanggang982/article/details/77944174
+  const ser = Transaction.encode(rawTxn).finish();
+  const sig = getSignature(ser, keyPair);
+  return {
+    ...rawTxn,
+    params,
+    signature: sig
+  };
+};
+ 
+/**
+ * Encryption Using Elliptic Curve Algorithms(Use ECDSA)
+ * Please see https://www.npmjs.com/package/elliptic#incentive
+ *
+ * @alias module:AElf/wallet
+ * @param {string} hexString hex string
+ * @param {Object} keyPair Any standard key pair
+ * @return {Buffer} Buffer.from(hex, 'hex')
+ *
+ * @Example
+ * const buffer = aelf.wallet.sign('68656c6c6f20776f726c64', wallet.keyPair);
+ * buffer = [65, 246, 49, 108, 122, 252, 66, 187, 240, 7, 14, 48, 89,
+ * 38, 103, 42, 58, 0, 46, 182, 180, 194, 200, 208, 141, 15, 95, 67,
+ * 234, 248, 31, 199, 73, 151, 2, 133, 233, 84, 180, 216, 116, 9, 153,
+ * 208, 254, 175, 96, 123, 76, 184, 224, 87, 69, 220, 172, 170, 239, 232,
+ * 188, 123, 168, 163, 244, 151, 1]
+ */
+const sign = (hexString, keyPair) => {
+  const bytesToBeSign = Buffer.from(hexString.replace('0x', ''), 'hex');
+  return getSignature(bytesToBeSign, keyPair);
+};
+ 
+const hexToDecimal = x => ellipticEc.keyFromPrivate(x, 'hex').getPrivate().toString(10);
+ 
+/**
+ * @param {string} signature Signature
+ * @param {string} msgHash Message for signing
+ * @param {string} pubKey deprecatedParam - This parameter is deprecated.
+ */
+const verify = (signature, msgHash, pubKey) => {
+  const rHex = signature.substring(0, 64);
+  const sHex = signature.substring(64, 128);
+  const recoveryParamHex = signature.substring(128, 130);
+  const sigObj = {
+    r: new BN(rHex, 16),
+    s: new BN(sHex, 16),
+    recoveryParam: recoveryParamHex.slice(1)
+  };
+  let publicKey;
+  if (!pubKey) {
+    const key = ellipticEc.recoverPubKey(hexToDecimal(msgHash), sigObj, +sigObj.recoveryParam, 'hex');
+    publicKey = ellipticEc.keyFromPublic(key).getPublic('hex');
+  } else {
+    publicKey = pubKey;
+  }
+  return ellipticEc.verify(msgHash, sigObj, Buffer.from(publicKey, 'hex'));
+};
+ 
+export default {
+  hdkey,
+  bip39,
+  sign,
+  verify,
+  signTransaction,
+  createNewWallet,
+  getWalletByMnemonic,
+  getWalletByPrivateKey,
+  getAddressFromPubKey,
+  ellipticEc,
+  AESEncrypt,
+  AESDecrypt,
+  keyStore
+};
+ 
+ +
+
+ + + + + + + + \ No newline at end of file