diff options
author | zelig <viktor.tron@gmail.com> | 2015-03-15 14:13:39 +0800 |
---|---|---|
committer | zelig <viktor.tron@gmail.com> | 2015-03-15 14:13:39 +0800 |
commit | da44097800caf2e20ec8e067f8700e59a43a5e06 (patch) | |
tree | 59caea58032056fbc42395cf3a1eb53f5f75e46c /jsre | |
parent | 2a5fbced7fb1fe976367f3f9f334c6ca657e7917 (diff) | |
download | dexon-da44097800caf2e20ec8e067f8700e59a43a5e06.tar.gz dexon-da44097800caf2e20ec8e067f8700e59a43a5e06.tar.zst dexon-da44097800caf2e20ec8e067f8700e59a43a5e06.zip |
jsre:
- require became loadScript(), no require is supplied
- bignumber_js.go: heredoc v2.0.3 minified fixed for otto Regexp incompatibility https://github.com/robertkrimen/otto#regular-expression-incompatibility
- bignumber.min.js also updated in mist/assets/ext
- ethereum_js.go: latest master minified
- assetPath in constructor
- Eval/Exec/Handle/ToVal nice API
- jsre tests
Diffstat (limited to 'jsre')
-rw-r--r-- | jsre/bignumber_js.go | 6 | ||||
-rw-r--r-- | jsre/ethereum_js.go | 3 | ||||
-rw-r--r-- | jsre/jsre.go | 115 | ||||
-rw-r--r-- | jsre/jsre_test.go | 85 | ||||
-rw-r--r-- | jsre/pp_js.go | 55 |
5 files changed, 264 insertions, 0 deletions
diff --git a/jsre/bignumber_js.go b/jsre/bignumber_js.go new file mode 100644 index 000000000..7902018be --- /dev/null +++ b/jsre/bignumber_js.go @@ -0,0 +1,6 @@ +package jsre + +const BigNumber_JS = `/* bignumber.js v2.0.3 https://github.com/MikeMcl/bignumber.js/LICENCE */ +/* modified by zelig to fix https://github.com/robertkrimen/otto#regular-expression-incompatibility */ +!function(e){"use strict";function n(e){function a(e,n){var t,r,i,o,u,s,f=this;if(!(f instanceof a))return j&&L(26,"constructor call without new",e),new a(e,n);if(null!=n&&H(n,2,64,M,"base")){if(n=0|n,s=e+"",10==n)return f=new a(e instanceof a?e:s),U(f,P+f.e+1,k);if((o="number"==typeof e)&&0*e!=0||!new RegExp("^-?"+(t="["+O.slice(0,n)+"]+")+"(?:\\."+t+")?$",37>n?"i":"").test(s))return g(f,s,o,n);o?(f.s=0>1/e?(s=s.slice(1),-1):1,j&&s.replace(/^0\.0*|\./,"").length>15&&L(M,b,e),o=!1):f.s=45===s.charCodeAt(0)?(s=s.slice(1),-1):1,s=D(s,10,n,f.s)}else{if(e instanceof a)return f.s=e.s,f.e=e.e,f.c=(e=e.c)?e.slice():e,void(M=0);if((o="number"==typeof e)&&0*e==0){if(f.s=0>1/e?(e=-e,-1):1,e===~~e){for(r=0,i=e;i>=10;i/=10,r++);return f.e=r,f.c=[e],void(M=0)}s=e+""}else{if(!p.test(s=e+""))return g(f,s,o);f.s=45===s.charCodeAt(0)?(s=s.slice(1),-1):1}}for((r=s.indexOf("."))>-1&&(s=s.replace(".","")),(i=s.search(/e/i))>0?(0>r&&(r=i),r+=+s.slice(i+1),s=s.substring(0,i)):0>r&&(r=s.length),i=0;48===s.charCodeAt(i);i++);for(u=s.length;48===s.charCodeAt(--u););if(s=s.slice(i,u+1))if(u=s.length,o&&j&&u>15&&L(M,b,f.s*e),r=r-i-1,r>z)f.c=f.e=null;else if(G>r)f.c=[f.e=0];else{if(f.e=r,f.c=[],i=(r+1)%y,0>r&&(i+=y),u>i){for(i&&f.c.push(+s.slice(0,i)),u-=y;u>i;)f.c.push(+s.slice(i,i+=y));s=s.slice(i),i=y-s.length}else i-=u;for(;i--;s+="0");f.c.push(+s)}else f.c=[f.e=0];M=0}function D(e,n,t,i){var o,u,f,c,h,g,p,d=e.indexOf("."),m=P,w=k;for(37>t&&(e=e.toLowerCase()),d>=0&&(f=J,J=0,e=e.replace(".",""),p=new a(t),h=p.pow(e.length-d),J=f,p.c=s(l(r(h.c),h.e),10,n),p.e=p.c.length),g=s(e,t,n),u=f=g.length;0==g[--f];g.pop());if(!g[0])return"0";if(0>d?--u:(h.c=g,h.e=u,h.s=i,h=C(h,p,m,w,n),g=h.c,c=h.r,u=h.e),o=u+m+1,d=g[o],f=n/2,c=c||0>o||null!=g[o+1],c=4>w?(null!=d||c)&&(0==w||w==(h.s<0?3:2)):d>f||d==f&&(4==w||c||6==w&&1&g[o-1]||w==(h.s<0?8:7)),1>o||!g[0])e=c?l("1",-m):"0";else{if(g.length=o,c)for(--n;++g[--o]>n;)g[o]=0,o||(++u,g.unshift(1));for(f=g.length;!g[--f];);for(d=0,e="";f>=d;e+=O.charAt(g[d++]));e=l(e,u)}return e}function _(e,n,t,i){var o,u,s,c,h;if(t=null!=t&&H(t,0,8,i,v)?0|t:k,!e.c)return e.toString();if(o=e.c[0],s=e.e,null==n)h=r(e.c),h=19==i||24==i&&B>=s?f(h,s):l(h,s);else if(e=U(new a(e),n,t),u=e.e,h=r(e.c),c=h.length,19==i||24==i&&(u>=n||B>=u)){for(;n>c;h+="0",c++);h=f(h,u)}else if(n-=s,h=l(h,u),u+1>c){if(--n>0)for(h+=".";n--;h+="0");}else if(n+=u-c,n>0)for(u+1==c&&(h+=".");n--;h+="0");return e.s<0&&o?"-"+h:h}function x(e,n){var t,r,i=0;for(u(e[0])&&(e=e[0]),t=new a(e[0]);++i<e.length;){if(r=new a(e[i]),!r.s){t=r;break}n.call(t,r)&&(t=r)}return t}function F(e,n,t,r,i){return(n>e||e>t||e!=c(e))&&L(r,(i||"decimal places")+(n>e||e>t?" out of range":" not an integer"),e),!0}function I(e,n,t){for(var r=1,i=n.length;!n[--i];n.pop());for(i=n[0];i>=10;i/=10,r++);return(t=r+t*y-1)>z?e.c=e.e=null:G>t?e.c=[e.e=0]:(e.e=t,e.c=n),e}function L(e,n,t){var r=new Error(["new BigNumber","cmp","config","div","divToInt","eq","gt","gte","lt","lte","minus","mod","plus","precision","random","round","shift","times","toDigits","toExponential","toFixed","toFormat","toFraction","pow","toPrecision","toString","BigNumber"][e]+"() "+n+": "+t);throw r.name="BigNumber Error",M=0,r}function U(e,n,t,r){var i,o,u,s,f,l,c,a=e.c,h=R;if(a){e:{for(i=1,s=a[0];s>=10;s/=10,i++);if(o=n-i,0>o)o+=y,u=n,f=a[l=0],c=f/h[i-u-1]%10|0;else if(l=d((o+1)/y),l>=a.length){if(!r)break e;for(;a.length<=l;a.push(0));f=c=0,i=1,o%=y,u=o-y+1}else{for(f=s=a[l],i=1;s>=10;s/=10,i++);o%=y,u=o-y+i,c=0>u?0:f/h[i-u-1]%10|0}if(r=r||0>n||null!=a[l+1]||(0>u?f:f%h[i-u-1]),r=4>t?(c||r)&&(0==t||t==(e.s<0?3:2)):c>5||5==c&&(4==t||r||6==t&&(o>0?u>0?f/h[i-u]:0:a[l-1])%10&1||t==(e.s<0?8:7)),1>n||!a[0])return a.length=0,r?(n-=e.e+1,a[0]=h[n%y],e.e=-n||0):a[0]=e.e=0,e;if(0==o?(a.length=l,s=1,l--):(a.length=l+1,s=h[y-o],a[l]=u>0?m(f/h[i-u]%h[u])*s:0),r)for(;;){if(0==l){for(o=1,u=a[0];u>=10;u/=10,o++);for(u=a[0]+=s,s=1;u>=10;u/=10,s++);o!=s&&(e.e++,a[0]==N&&(a[0]=1));break}if(a[l]+=s,a[l]!=N)break;a[l--]=0,s=1}for(o=a.length;0===a[--o];a.pop());}e.e>z?e.c=e.e=null:e.e<G&&(e.c=[e.e=0])}return e}var C,M=0,T=a.prototype,q=new a(1),P=20,k=4,B=-7,$=21,G=-1e7,z=1e7,j=!0,H=F,V=!1,W=1,J=100,X={decimalSeparator:".",groupSeparator:",",groupSize:3,secondaryGroupSize:0,fractionGroupSeparator:" ",fractionGroupSize:0};return a.another=n,a.ROUND_UP=0,a.ROUND_DOWN=1,a.ROUND_CEIL=2,a.ROUND_FLOOR=3,a.ROUND_HALF_UP=4,a.ROUND_HALF_DOWN=5,a.ROUND_HALF_EVEN=6,a.ROUND_HALF_CEIL=7,a.ROUND_HALF_FLOOR=8,a.EUCLID=9,a.config=function(){var e,n,t=0,r={},i=arguments,s=i[0],f=s&&"object"==typeof s?function(){return s.hasOwnProperty(n)?null!=(e=s[n]):void 0}:function(){return i.length>t?null!=(e=i[t++]):void 0};return f(n="DECIMAL_PLACES")&&H(e,0,E,2,n)&&(P=0|e),r[n]=P,f(n="ROUNDING_MODE")&&H(e,0,8,2,n)&&(k=0|e),r[n]=k,f(n="EXPONENTIAL_AT")&&(u(e)?H(e[0],-E,0,2,n)&&H(e[1],0,E,2,n)&&(B=0|e[0],$=0|e[1]):H(e,-E,E,2,n)&&(B=-($=0|(0>e?-e:e)))),r[n]=[B,$],f(n="RANGE")&&(u(e)?H(e[0],-E,-1,2,n)&&H(e[1],1,E,2,n)&&(G=0|e[0],z=0|e[1]):H(e,-E,E,2,n)&&(0|e?G=-(z=0|(0>e?-e:e)):j&&L(2,n+" cannot be zero",e))),r[n]=[G,z],f(n="ERRORS")&&(e===!!e||1===e||0===e?(M=0,H=(j=!!e)?F:o):j&&L(2,n+w,e)),r[n]=j,f(n="CRYPTO")&&(e===!!e||1===e||0===e?(V=!(!e||!h||"object"!=typeof h),e&&!V&&j&&L(2,"crypto unavailable",h)):j&&L(2,n+w,e)),r[n]=V,f(n="MODULO_MODE")&&H(e,0,9,2,n)&&(W=0|e),r[n]=W,f(n="POW_PRECISION")&&H(e,0,E,2,n)&&(J=0|e),r[n]=J,f(n="FORMAT")&&("object"==typeof e?X=e:j&&L(2,n+" not an object",e)),r[n]=X,r},a.max=function(){return x(arguments,T.lt)},a.min=function(){return x(arguments,T.gt)},a.random=function(){var e=9007199254740992,n=Math.random()*e&2097151?function(){return m(Math.random()*e)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)};return function(e){var t,r,i,o,u,s=0,f=[],l=new a(q);if(e=null!=e&&H(e,0,E,14)?0|e:P,o=d(e/y),V)if(h&&h.getRandomValues){for(t=h.getRandomValues(new Uint32Array(o*=2));o>s;)u=131072*t[s]+(t[s+1]>>>11),u>=9e15?(r=h.getRandomValues(new Uint32Array(2)),t[s]=r[0],t[s+1]=r[1]):(f.push(u%1e14),s+=2);s=o/2}else if(h&&h.randomBytes){for(t=h.randomBytes(o*=7);o>s;)u=281474976710656*(31&t[s])+1099511627776*t[s+1]+4294967296*t[s+2]+16777216*t[s+3]+(t[s+4]<<16)+(t[s+5]<<8)+t[s+6],u>=9e15?h.randomBytes(7).copy(t,s):(f.push(u%1e14),s+=7);s=o/7}else j&&L(14,"crypto unavailable",h);if(!s)for(;o>s;)u=n(),9e15>u&&(f[s++]=u%1e14);for(o=f[--s],e%=y,o&&e&&(u=R[y-e],f[s]=m(o/u)*u);0===f[s];f.pop(),s--);if(0>s)f=[i=0];else{for(i=-1;0===f[0];f.shift(),i-=y);for(s=1,u=f[0];u>=10;u/=10,s++);y>s&&(i-=y-s)}return l.e=i,l.c=f,l}}(),C=function(){function e(e,n,t){var r,i,o,u,s=0,f=e.length,l=n%A,c=n/A|0;for(e=e.slice();f--;)o=e[f]%A,u=e[f]/A|0,r=c*o+u*l,i=l*o+r%A*A+s,s=(i/t|0)+(r/A|0)+c*u,e[f]=i%t;return s&&e.unshift(s),e}function n(e,n,t,r){var i,o;if(t!=r)o=t>r?1:-1;else for(i=o=0;t>i;i++)if(e[i]!=n[i]){o=e[i]>n[i]?1:-1;break}return o}function r(e,n,t,r){for(var i=0;t--;)e[t]-=i,i=e[t]<n[t]?1:0,e[t]=i*r+e[t]-n[t];for(;!e[0]&&e.length>1;e.shift());}return function(i,o,u,s,f){var l,c,h,g,p,d,w,v,b,O,S,R,A,E,D,_,x,F=i.s==o.s?1:-1,I=i.c,L=o.c;if(!(I&&I[0]&&L&&L[0]))return new a(i.s&&o.s&&(I?!L||I[0]!=L[0]:L)?I&&0==I[0]||!L?0*F:F/0:0/0);for(v=new a(F),b=v.c=[],c=i.e-o.e,F=u+c+1,f||(f=N,c=t(i.e/y)-t(o.e/y),F=F/y|0),h=0;L[h]==(I[h]||0);h++);if(L[h]>(I[h]||0)&&c--,0>F)b.push(1),g=!0;else{for(E=I.length,_=L.length,h=0,F+=2,p=m(f/(L[0]+1)),p>1&&(L=e(L,p,f),I=e(I,p,f),_=L.length,E=I.length),A=_,O=I.slice(0,_),S=O.length;_>S;O[S++]=0);x=L.slice(),x.unshift(0),D=L[0],L[1]>=f/2&&D++;do p=0,l=n(L,O,_,S),0>l?(R=O[0],_!=S&&(R=R*f+(O[1]||0)),p=m(R/D),p>1?(p>=f&&(p=f-1),d=e(L,p,f),w=d.length,S=O.length,l=n(d,O,w,S),1==l&&(p--,r(d,w>_?x:L,w,f))):(0==p&&(l=p=1),d=L.slice()),w=d.length,S>w&&d.unshift(0),r(O,d,S,f),-1==l&&(S=O.length,l=n(L,O,_,S),1>l&&(p++,r(O,S>_?x:L,S,f))),S=O.length):0===l&&(p++,O=[0]),b[h++]=p,l&&O[0]?O[S++]=I[A]||0:(O=[I[A]],S=1);while((A++<E||null!=O[0])&&F--);g=null!=O[0],b[0]||b.shift()}if(f==N){for(h=1,F=b[0];F>=10;F/=10,h++);U(v,u+(v.e=h+c*y-1)+1,s,g)}else v.e=c,v.r=+g;return v}}(),g=function(){var e=/^(-?)0([xbo])(\w[\w.]*$)/i,n=/^([^.]+)\.$/,t=/^\.([^.]+)$/,r=/^-?(Infinity|NaN)$/,i=/^\s*\+([\w.])|^\s+|\s+$/g;return function(o,u,s,f){var l,c=s?u:u.replace(i,"$1");if(r.test(c))o.s=isNaN(c)?null:0>c?-1:1;else{if(!s&&(c=c.replace(e,function(e,n,t){return l="x"==(t=t.toLowerCase())?16:"b"==t?2:8,f&&f!=l?e:n}),f&&(l=f,c=c.replace(n,"$1").replace(t,"0.$1")),u!=c))return new a(c,l);j&&L(M,"not a"+(f?" base "+f:"")+" number",u),o.s=null}o.c=o.e=null,M=0}}(),T.absoluteValue=T.abs=function(){var e=new a(this);return e.s<0&&(e.s=1),e},T.ceil=function(){return U(new a(this),this.e+1,2)},T.comparedTo=T.cmp=function(e,n){return M=1,i(this,new a(e,n))},T.decimalPlaces=T.dp=function(){var e,n,r=this.c;if(!r)return null;if(e=((n=r.length-1)-t(this.e/y))*y,n=r[n])for(;n%10==0;n/=10,e--);return 0>e&&(e=0),e},T.dividedBy=T.div=function(e,n){return M=3,C(this,new a(e,n),P,k)},T.dividedToIntegerBy=T.divToInt=function(e,n){return M=4,C(this,new a(e,n),0,1)},T.equals=T.eq=function(e,n){return M=5,0===i(this,new a(e,n))},T.floor=function(){return U(new a(this),this.e+1,3)},T.greaterThan=T.gt=function(e,n){return M=6,i(this,new a(e,n))>0},T.greaterThanOrEqualTo=T.gte=function(e,n){return M=7,1===(n=i(this,new a(e,n)))||0===n},T.isFinite=function(){return!!this.c},T.isInteger=T.isInt=function(){return!!this.c&&t(this.e/y)>this.c.length-2},T.isNaN=function(){return!this.s},T.isNegative=T.isNeg=function(){return this.s<0},T.isZero=function(){return!!this.c&&0==this.c[0]},T.lessThan=T.lt=function(e,n){return M=8,i(this,new a(e,n))<0},T.lessThanOrEqualTo=T.lte=function(e,n){return M=9,-1===(n=i(this,new a(e,n)))||0===n},T.minus=T.sub=function(e,n){var r,i,o,u,s=this,f=s.s;if(M=10,e=new a(e,n),n=e.s,!f||!n)return new a(0/0);if(f!=n)return e.s=-n,s.plus(e);var l=s.e/y,c=e.e/y,h=s.c,g=e.c;if(!l||!c){if(!h||!g)return h?(e.s=-n,e):new a(g?s:0/0);if(!h[0]||!g[0])return g[0]?(e.s=-n,e):new a(h[0]?s:3==k?-0:0)}if(l=t(l),c=t(c),h=h.slice(),f=l-c){for((u=0>f)?(f=-f,o=h):(c=l,o=g),o.reverse(),n=f;n--;o.push(0));o.reverse()}else for(i=(u=(f=h.length)<(n=g.length))?f:n,f=n=0;i>n;n++)if(h[n]!=g[n]){u=h[n]<g[n];break}if(u&&(o=h,h=g,g=o,e.s=-e.s),n=(i=g.length)-(r=h.length),n>0)for(;n--;h[r++]=0);for(n=N-1;i>f;){if(h[--i]<g[i]){for(r=i;r&&!h[--r];h[r]=n);--h[r],h[i]+=N}h[i]-=g[i]}for(;0==h[0];h.shift(),--c);return h[0]?I(e,h,c):(e.s=3==k?-1:1,e.c=[e.e=0],e)},T.modulo=T.mod=function(e,n){var t,r,i=this;return M=11,e=new a(e,n),!i.c||!e.s||e.c&&!e.c[0]?new a(0/0):!e.c||i.c&&!i.c[0]?new a(i):(9==W?(r=e.s,e.s=1,t=C(i,e,0,3),e.s=r,t.s*=r):t=C(i,e,0,W),i.minus(t.times(e)))},T.negated=T.neg=function(){var e=new a(this);return e.s=-e.s||null,e},T.plus=T.add=function(e,n){var r,i=this,o=i.s;if(M=12,e=new a(e,n),n=e.s,!o||!n)return new a(0/0);if(o!=n)return e.s=-n,i.minus(e);var u=i.e/y,s=e.e/y,f=i.c,l=e.c;if(!u||!s){if(!f||!l)return new a(o/0);if(!f[0]||!l[0])return l[0]?e:new a(f[0]?i:0*o)}if(u=t(u),s=t(s),f=f.slice(),o=u-s){for(o>0?(s=u,r=l):(o=-o,r=f),r.reverse();o--;r.push(0));r.reverse()}for(o=f.length,n=l.length,0>o-n&&(r=l,l=f,f=r,n=o),o=0;n;)o=(f[--n]=f[n]+l[n]+o)/N|0,f[n]%=N;return o&&(f.unshift(o),++s),I(e,f,s)},T.precision=T.sd=function(e){var n,t,r=this,i=r.c;if(null!=e&&e!==!!e&&1!==e&&0!==e&&(j&&L(13,"argument"+w,e),e!=!!e&&(e=null)),!i)return null;if(t=i.length-1,n=t*y+1,t=i[t]){for(;t%10==0;t/=10,n--);for(t=i[0];t>=10;t/=10,n++);}return e&&r.e+1>n&&(n=r.e+1),n},T.round=function(e,n){var t=new a(this);return(null==e||H(e,0,E,15))&&U(t,~~e+this.e+1,null!=n&&H(n,0,8,15,v)?0|n:k),t},T.shift=function(e){var n=this;return H(e,-S,S,16,"argument")?n.times("1e"+c(e)):new a(n.c&&n.c[0]&&(-S>e||e>S)?n.s*(0>e?0:1/0):n)},T.squareRoot=T.sqrt=function(){var e,n,i,o,u,s=this,f=s.c,l=s.s,c=s.e,h=P+4,g=new a("0.5");if(1!==l||!f||!f[0])return new a(!l||0>l&&(!f||f[0])?0/0:f?s:1/0);if(l=Math.sqrt(+s),0==l||l==1/0?(n=r(f),(n.length+c)%2==0&&(n+="0"),l=Math.sqrt(n),c=t((c+1)/2)-(0>c||c%2),l==1/0?n="1e"+c:(n=l.toExponential(),n=n.slice(0,n.indexOf("e")+1)+c),i=new a(n)):i=new a(l+""),i.c[0])for(c=i.e,l=c+h,3>l&&(l=0);;)if(u=i,i=g.times(u.plus(C(s,u,h,1))),r(u.c).slice(0,l)===(n=r(i.c)).slice(0,l)){if(i.e<c&&--l,n=n.slice(l-3,l+1),"9999"!=n&&(o||"4999"!=n)){(!+n||!+n.slice(1)&&"5"==n.charAt(0))&&(U(i,i.e+P+2,1),e=!i.times(i).eq(s));break}if(!o&&(U(u,u.e+P+2,0),u.times(u).eq(s))){i=u;break}h+=4,l+=4,o=1}return U(i,i.e+P+1,k,e)},T.times=T.mul=function(e,n){var r,i,o,u,s,f,l,c,h,g,p,d,m,w,v,b=this,O=b.c,S=(M=17,e=new a(e,n)).c;if(!(O&&S&&O[0]&&S[0]))return!b.s||!e.s||O&&!O[0]&&!S||S&&!S[0]&&!O?e.c=e.e=e.s=null:(e.s*=b.s,O&&S?(e.c=[0],e.e=0):e.c=e.e=null),e;for(i=t(b.e/y)+t(e.e/y),e.s*=b.s,l=O.length,g=S.length,g>l&&(m=O,O=S,S=m,o=l,l=g,g=o),o=l+g,m=[];o--;m.push(0));for(w=N,v=A,o=g;--o>=0;){for(r=0,p=S[o]%v,d=S[o]/v|0,s=l,u=o+s;u>o;)c=O[--s]%v,h=O[s]/v|0,f=d*c+h*p,c=p*c+f%v*v+m[u]+r,r=(c/w|0)+(f/v|0)+d*h,m[u--]=c%w;m[u]=r}return r?++i:m.shift(),I(e,m,i)},T.toDigits=function(e,n){var t=new a(this);return e=null!=e&&H(e,1,E,18,"precision")?0|e:null,n=null!=n&&H(n,0,8,18,v)?0|n:k,e?U(t,e,n):t},T.toExponential=function(e,n){return _(this,null!=e&&H(e,0,E,19)?~~e+1:null,n,19)},T.toFixed=function(e,n){return _(this,null!=e&&H(e,0,E,20)?~~e+this.e+1:null,n,20)},T.toFormat=function(e,n){var t=_(this,null!=e&&H(e,0,E,21)?~~e+this.e+1:null,n,21);if(this.c){var r,i=t.split("."),o=+X.groupSize,u=+X.secondaryGroupSize,s=X.groupSeparator,f=i[0],l=i[1],c=this.s<0,a=c?f.slice(1):f,h=a.length;if(u&&(r=o,o=u,u=r,h-=r),o>0&&h>0){for(r=h%o||o,f=a.substr(0,r);h>r;r+=o)f+=s+a.substr(r,o);u>0&&(f+=s+a.slice(r)),c&&(f="-"+f)}t=l?f+X.decimalSeparator+((u=+X.fractionGroupSize)?l.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+X.fractionGroupSeparator):l):f}return t},T.toFraction=function(e){var n,t,i,o,u,s,f,l,c,h=j,g=this,p=g.c,d=new a(q),m=t=new a(q),w=f=new a(q);if(null!=e&&(j=!1,s=new a(e),j=h,(!(h=s.isInt())||s.lt(q))&&(j&&L(22,"max denominator "+(h?"out of range":"not an integer"),e),e=!h&&s.c&&U(s,s.e+1,1).gte(q)?s:null)),!p)return g.toString();for(c=r(p),o=d.e=c.length-g.e-1,d.c[0]=R[(u=o%y)<0?y+u:u],e=!e||s.cmp(d)>0?o>0?d:m:s,u=z,z=1/0,s=new a(c),f.c[0]=0;l=C(s,d,0,1),i=t.plus(l.times(w)),1!=i.cmp(e);)t=w,w=i,m=f.plus(l.times(i=m)),f=i,d=s.minus(l.times(i=d)),s=i;return i=C(e.minus(t),w,0,1),f=f.plus(i.times(m)),t=t.plus(i.times(w)),f.s=m.s=g.s,o*=2,n=C(m,w,o,k).minus(g).abs().cmp(C(f,t,o,k).minus(g).abs())<1?[m.toString(),w.toString()]:[f.toString(),t.toString()],z=u,n},T.toNumber=function(){var e=this;return+e||(e.s?0*e.s:0/0)},T.toPower=T.pow=function(e){var n,t,r=m(0>e?-e:+e),i=this;if(!H(e,-S,S,23,"exponent")&&(!isFinite(e)||r>S&&(e/=0)||parseFloat(e)!=e&&!(e=0/0)))return new a(Math.pow(+i,e));for(n=J?d(J/y+2):0,t=new a(q);;){if(r%2){if(t=t.times(i),!t.c)break;n&&t.c.length>n&&(t.c.length=n)}if(r=m(r/2),!r)break;i=i.times(i),n&&i.c&&i.c.length>n&&(i.c.length=n)}return 0>e&&(t=q.div(t)),n?U(t,J,k):t},T.toPrecision=function(e,n){return _(this,null!=e&&H(e,1,E,24,"precision")?0|e:null,n,24)},T.toString=function(e){var n,t=this,i=t.s,o=t.e;return null===o?i?(n="Infinity",0>i&&(n="-"+n)):n="NaN":(n=r(t.c),n=null!=e&&H(e,2,64,25,"base")?D(l(n,o),0|e,10,i):B>=o||o>=$?f(n,o):l(n,o),0>i&&t.c[0]&&(n="-"+n)),n},T.truncated=T.trunc=function(){return U(new a(this),this.e+1,1)},T.valueOf=T.toJSON=function(){return this.toString()},null!=e&&a.config(e),a}function t(e){var n=0|e;return e>0||e===n?n:n-1}function r(e){for(var n,t,r=1,i=e.length,o=e[0]+"";i>r;){for(n=e[r++]+"",t=y-n.length;t--;n="0"+n);o+=n}for(i=o.length;48===o.charCodeAt(--i););return o.slice(0,i+1||1)}function i(e,n){var t,r,i=e.c,o=n.c,u=e.s,s=n.s,f=e.e,l=n.e;if(!u||!s)return null;if(t=i&&!i[0],r=o&&!o[0],t||r)return t?r?0:-s:u;if(u!=s)return u;if(t=0>u,r=f==l,!i||!o)return r?0:!i^t?1:-1;if(!r)return f>l^t?1:-1;for(s=(f=i.length)<(l=o.length)?f:l,u=0;s>u;u++)if(i[u]!=o[u])return i[u]>o[u]^t?1:-1;return f==l?0:f>l^t?1:-1}function o(e,n,t){return(e=c(e))>=n&&t>=e}function u(e){return"[object Array]"==Object.prototype.toString.call(e)}function s(e,n,t){for(var r,i,o=[0],u=0,s=e.length;s>u;){for(i=o.length;i--;o[i]*=n);for(o[r=0]+=O.indexOf(e.charAt(u++));r<o.length;r++)o[r]>t-1&&(null==o[r+1]&&(o[r+1]=0),o[r+1]+=o[r]/t|0,o[r]%=t)}return o.reverse()}function f(e,n){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(0>n?"e":"e+")+n}function l(e,n){var t,r;if(0>n){for(r="0.";++n;r+="0");e=r+e}else if(t=e.length,++n>t){for(r="0",n-=t;--n;r+="0");e+=r}else t>n&&(e=e.slice(0,n)+"."+e.slice(n));return e}function c(e){return e=parseFloat(e),0>e?d(e):m(e)}var a,h,g,p=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,d=Math.ceil,m=Math.floor,w=" not a boolean or binary digit",v="rounding mode",b="number type has more than 15 significant digits",O="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_",N=1e14,y=14,S=9007199254740991,R=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],A=1e7,E=1e9;if(a=n(),"function"==typeof define&&define.amd)define(function(){return a});else if("undefined"!=typeof module&&module.exports){if(module.exports=a,!h)try{h=require("crypto")}catch(D){}}else e.BigNumber=a}(this); +//# sourceMappingURL=doc/bignumber.js.map` diff --git a/jsre/ethereum_js.go b/jsre/ethereum_js.go new file mode 100644 index 000000000..8b2f6e9dd --- /dev/null +++ b/jsre/ethereum_js.go @@ -0,0 +1,3 @@ +package jsre + +const Ethereum_JS = `require=function t(e,n,r){function o(i,u){if(!n[i]){if(!e[i]){var s="function"==typeof require&&require;if(!u&&s)return s(i,!0);if(a)return a(i,!0);var c=new Error("Cannot find module '"+i+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[i]={exports:{}};e[i][0].call(l.exports,function(t){var n=e[i][1][t];return o(n?n:t)},l,l.exports,t,e,n,r)}return n[i].exports}for(var a="function"==typeof require&&require,i=0;i<r.length;i++)o(r[i]);return o}({1:[function(t,e){var n=t("../utils/utils"),r=t("../utils/config"),o=t("./types"),a=t("./formatters"),i=function(t){throw new Error("parser does not support type: "+t)},u=function(t){return"[]"===t.slice(-2)},s=function(t,e){return u(t)||"string"===t?a.formatInputInt(e.length):""},c=o.inputTypes(),l=function(t,e){var n="",r="",o="";return t.forEach(function(t,r){n+=s(t.type,e[r])}),t.forEach(function(n,a){for(var s=!1,l=0;l<c.length&&!s;l++)s=c[l].type(t[a].type,e[a]);s||i(t[a].type);var f=c[l-1].format;u(t[a].type)?o+=e[a].reduce(function(t,e){return t+f(e)},""):"string"===t[a].type?o+=f(e[a]):r+=f(e[a])}),n+=r+o},f=function(t){return u(t)||"string"===t?2*r.ETH_PADDING:0},p=o.outputTypes(),m=function(t,e){e=e.slice(2);var n=[],s=2*r.ETH_PADDING,c=t.reduce(function(t,e){return t+f(e.type)},0),l=e.slice(0,c);return e=e.slice(c),t.forEach(function(r,c){for(var f=!1,m=0;m<p.length&&!f;m++)f=p[m].type(t[c].type);f||i(t[c].type);var d=p[m-1].format;if(u(t[c].type)){var h=a.formatOutputUInt(l.slice(0,s));l=l.slice(s);for(var g=[],y=0;h>y;y++)g.push(d(e.slice(0,s))),e=e.slice(s);n.push(g)}else o.prefixedType("string")(t[c].type)?(l=l.slice(s),n.push(d(e.slice(0,s))),e=e.slice(s)):(n.push(d(e.slice(0,s))),e=e.slice(s))}),n},d=function(t){var e={};return t.forEach(function(t){var r=n.extractDisplayName(t.name),o=n.extractTypeName(t.name),a=function(){var e=Array.prototype.slice.call(arguments);return l(t.inputs,e)};void 0===e[r]&&(e[r]=a),e[r][o]=a}),e},h=function(t){var e={};return t.forEach(function(t){var r=n.extractDisplayName(t.name),o=n.extractTypeName(t.name),a=function(e){return m(t.outputs,e)};void 0===e[r]&&(e[r]=a),e[r][o]=a}),e};e.exports={inputParser:d,outputParser:h,formatInput:l,formatOutput:m}},{"../utils/config":4,"../utils/utils":5,"./formatters":2,"./types":3}],2:[function(t,e){var n=t("../utils/utils"),r=t("../utils/config"),o=function(t,e,n){return new Array(e-t.length+1).join(n?n:"0")+t},a=function(t){var e=2*r.ETH_PADDING;return BigNumber.config(r.ETH_BIGNUMBER_ROUNDING_MODE),o(n.toTwosComplement(t).round().toString(16),e)},i=function(t){return n.fromAscii(t,r.ETH_PADDING).substr(2)},u=function(t){return"000000000000000000000000000000000000000000000000000000000000000"+(t?"1":"0")},s=function(t){return a(new BigNumber(t).times(new BigNumber(2).pow(128)))},c=function(t){return"1"===new BigNumber(t.substr(0,1),16).toString(2).substr(0,1)},l=function(t){return t=t||"0",c(t)?new BigNumber(t,16).minus(new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16)).minus(1):new BigNumber(t,16)},f=function(t){return t=t||"0",new BigNumber(t,16)},p=function(t){return l(t).dividedBy(new BigNumber(2).pow(128))},m=function(t){return f(t).dividedBy(new BigNumber(2).pow(128))},d=function(t){return"0x"+t},h=function(t){return"0000000000000000000000000000000000000000000000000000000000000001"===t?!0:!1},g=function(t){return n.toAscii(t)},y=function(t){return"0x"+t.slice(t.length-40,t.length)};e.exports={formatInputInt:a,formatInputString:i,formatInputBool:u,formatInputReal:s,formatOutputInt:l,formatOutputUInt:f,formatOutputReal:p,formatOutputUReal:m,formatOutputHash:d,formatOutputBool:h,formatOutputString:g,formatOutputAddress:y}},{"../utils/config":4,"../utils/utils":5}],3:[function(t,e){var n=t("./formatters"),r=function(t){return function(e){return 0===e.indexOf(t)}},o=function(t){return function(e){return t===e}},a=function(){return[{type:r("uint"),format:n.formatInputInt},{type:r("int"),format:n.formatInputInt},{type:r("hash"),format:n.formatInputInt},{type:r("string"),format:n.formatInputString},{type:r("real"),format:n.formatInputReal},{type:r("ureal"),format:n.formatInputReal},{type:o("address"),format:n.formatInputInt},{type:o("bool"),format:n.formatInputBool}]},i=function(){return[{type:r("uint"),format:n.formatOutputUInt},{type:r("int"),format:n.formatOutputInt},{type:r("hash"),format:n.formatOutputHash},{type:r("string"),format:n.formatOutputString},{type:r("real"),format:n.formatOutputReal},{type:r("ureal"),format:n.formatOutputUReal},{type:o("address"),format:n.formatOutputAddress},{type:o("bool"),format:n.formatOutputBool}]};e.exports={prefixedType:r,namedType:o,inputTypes:a,outputTypes:i}},{"./formatters":2}],4:[function(t,e){var n=["wei","Kwei","Mwei","Gwei","szabo","finney","ether","grand","Mether","Gether","Tether","Pether","Eether","Zether","Yether","Nether","Dether","Vether","Uether"];e.exports={ETH_PADDING:32,ETH_SIGNATURE_LENGTH:4,ETH_UNITS:n,ETH_BIGNUMBER_ROUNDING_MODE:{ROUNDING_MODE:BigNumber.ROUND_DOWN},ETH_POLLING_TIMEOUT:1e3,ETH_DEFAULTBLOCK:"latest"}},{}],5:[function(t,e){var n={wei:"1",kwei:"1000",ada:"1000",mwei:"1000000",babbage:"1000000",gwei:"1000000000",shannon:"1000000000",szabo:"1000000000000",finney:"1000000000000000",ether:"1000000000000000000",kether:"1000000000000000000000",grand:"1000000000000000000000",einstein:"1000000000000000000000",mether:"1000000000000000000000000",gether:"1000000000000000000000000000",tether:"1000000000000000000000000000000"},r=function(t,e){for(var n=!1,r=0;r<t.length&&!n;r++)n=e(t[r]);return n?r-1:-1},o=function(t){var e="",n=0,r=t.length;for("0x"===t.substring(0,2)&&(n=2);r>n;n+=2){var o=parseInt(t.substr(n,2),16);if(0===o)break;e+=String.fromCharCode(o)}return e},a=function(t){for(var e="",n=0;n<t.length;n++){var r=t.charCodeAt(n).toString(16);e+=r.length<2?"0"+r:r}return e},i=function(t,e){e=void 0===e?0:e;for(var n=a(t);n.length<2*e;)n+="00";return"0x"+n},u=function(t){var e=t.indexOf("(");return-1!==e?t.substr(0,e):t},s=function(t){var e=t.indexOf("(");return-1!==e?t.substr(e+1,t.length-1-(e+1)).replace(" ",""):""},c=function(t){return t.filter(function(t){return"function"===t.type})},l=function(t){return t.filter(function(t){return"event"===t.type})},f=function(t){return y(t).toNumber()},p=function(t){var e=y(t),n=e.toString(16);return e.lessThan(0)?"-0x"+n.substr(1):"0x"+n},m=function(t){if(B(t))return t;if(w(t))return p(t);if(T(t))return i(JSON.stringify(t));if(_(t)){if(0===t.indexOf("-0x"))return p(t);if(!isFinite(t))return i(t)}return p(t)},d=function(t){t=t?t.toLowerCase():"ether";var e=n[t];if(void 0===e)throw new Error("This unit doesn't exists, please use the one of the following units"+JSON.stringify(n,null,2));return new BigNumber(e,10)},h=function(t,e){var n=y(t).dividedBy(d(e));return w(t)?n:n.toString(10)},g=function(t,e){var n=y(t).times(d(e));return w(t)?n:n.toString(10)},y=function(t){return t=t||0,w(t)?t:!_(t)||0!==t.indexOf("0x")&&0!==t.indexOf("-0x")?new BigNumber(t.toString(10),10):new BigNumber(t.replace("0x",""),16)},b=function(t){var e=y(t);return e.lessThan(0)?new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16).plus(e).plus(1):e},v=function(t){return _(t)?0===t.indexOf("0x")&&42===t.length||-1===t.indexOf("0x")&&40===t.length:!1},w=function(t){return t instanceof BigNumber||t&&t.constructor&&"BigNumber"===t.constructor.name},_=function(t){return"string"==typeof t||t&&t.constructor&&"String"===t.constructor.name},x=function(t){return"function"==typeof t},T=function(t){return"object"==typeof t},B=function(t){return"boolean"==typeof t},F=function(t){return t instanceof Array};e.exports={findIndex:r,toHex:m,toDecimal:f,fromDecimal:p,toAscii:o,fromAscii:i,extractDisplayName:u,extractTypeName:s,filterFunctions:c,filterEvents:l,toWei:g,fromWei:h,toBigNumber:y,toTwosComplement:b,isBigNumber:w,isAddress:v,isFunction:x,isString:_,isObject:T,isBoolean:B,isArray:F}},{}],6:[function(t,e){var n=t("./web3/net"),r=t("./web3/eth"),o=t("./web3/db"),a=t("./web3/shh"),i=t("./web3/watches"),u=t("./web3/filter"),s=t("./utils/utils"),c=t("./solidity/formatters"),l=t("./web3/requestmanager"),f=t("./utils/config"),p=function(){return[{name:"sha3",call:"web3_sha3"}]},m=function(t,e){e.forEach(function(e){var n=e.name.split("."),r=function(){var t=null,n=Array.prototype.slice.call(arguments),r="function"==typeof e.call?e.call(n):e.call;return"function"==typeof n[n.length-1]&&(t=n[n.length-1],Array.prototype.pop.call(n)),e.addDefaultblock&&(n.length!==e.addDefaultblock?Array.prototype.push.call(n,isFinite(f.ETH_DEFAULTBLOCK)?s.fromDecimal(f.ETH_DEFAULTBLOCK):f.ETH_DEFAULTBLOCK):n[n.length-1]=isFinite(n[n.length-1])?s.fromDecimal(n[n.length-1]):n[n.length-1]),e.newMethod&&console.warn("This method is deprecated please use web3."+e.newMethod+"() instead."),v.manager.send({method:r,params:n,outputFormatter:e.outputFormatter,inputFormatter:e.inputFormatter,addDefaultblock:e.addDefaultblock},t)};n.length>1?(t[n[0]]||(t[n[0]]={}),t[n[0]][n[1]]=r):t[n[0]]=r})},d=function(t,e){e.forEach(function(e){var n={};n.get=function(){return e.newProperty&&console.warn("This property is deprecated please use web3."+e.newProperty+" instead."),v.manager.send({method:e.getter,outputFormatter:e.outputFormatter})},e.setter&&(n.set=function(t){return e.newProperty&&console.warn("This property is deprecated please use web3."+e.newProperty+" instead."),v.manager.send({method:e.setter,params:[t],inputFormatter:e.inputFormatter})}),n.enumerable=!e.newProperty,Object.defineProperty(t,e.name,n)})},h=function(t,e,n,r){v.manager.startPolling({method:t,params:[e]},e,n,r)},g=function(t){v.manager.stopPolling(t)},y={startPolling:h.bind(null,"eth_getFilterChanges"),stopPolling:g},b={startPolling:h.bind(null,"shh_getFilterChanges"),stopPolling:g},v={manager:l(),providers:{},setProvider:function(t){v.manager.setProvider(t)},reset:function(){v.manager.reset()},toHex:s.toHex,toAscii:s.toAscii,fromAscii:s.fromAscii,toDecimal:s.toDecimal,fromDecimal:s.fromDecimal,toBigNumber:s.toBigNumber,toWei:s.toWei,fromWei:s.fromWei,isAddress:s.isAddress,net:{},eth:{contractFromAbi:function(t){return console.warn("Initiating a contract like this is deprecated please use var MyContract = eth.contract(abi); new MyContract(address); instead."),function(e){e=e||"0xc6d9d2cd449a754c494264e1809c50e34d64562b";var n=v.eth.contract(e,t);return n.address=e,n}},filter:function(t,e,n){return t._isEvent?t(e,n):u(t,y,c.outputLogFormatter)},watch:function(t,e,n){return console.warn("eth.watch() is deprecated please use eth.filter() instead."),this.filter(t,e,n)}},db:{},shh:{filter:function(t){return u(t,b,c.outputPostFormatter)},watch:function(t){return console.warn("shh.watch() is deprecated please use shh.filter() instead."),this.filter(t)}}};Object.defineProperty(v.eth,"defaultBlock",{get:function(){return f.ETH_DEFAULTBLOCK},set:function(t){return f.ETH_DEFAULTBLOCK=t,f.ETH_DEFAULTBLOCK}}),m(v,p()),m(v.net,n.methods),d(v.net,n.properties),m(v.eth,r.methods),d(v.eth,r.properties),m(v.db,o.methods()),m(v.shh,a.methods()),m(y,i.eth()),m(b,i.shh()),e.exports=v},{"./solidity/formatters":2,"./utils/config":4,"./utils/utils":5,"./web3/db":8,"./web3/eth":9,"./web3/filter":11,"./web3/net":15,"./web3/requestmanager":17,"./web3/shh":18,"./web3/watches":20}],7:[function(t,e){function n(t,e){t.forEach(function(t){if(-1===t.name.indexOf("(")){var e=t.name,n=t.inputs.map(function(t){return t.type}).join();t.name=e+"("+n+")"}});var n={};return c(n),l(n,t,e),f(n,t,e),p(n,t,e),n}var r=t("../web3"),o=t("../solidity/abi"),a=t("../utils/utils"),i=t("./event"),u=t("./signature"),s=function(t){r._currentContractAbi=t.abi,r._currentContractAddress=t.address,r._currentContractMethodName=t.method,r._currentContractMethodParams=t.params},c=function(t){t.call=function(e){return t._isTransaction=!1,t._options=e,t},t.sendTransaction=function(e){return t._isTransaction=!0,t._options=e,t},t.transact=function(e){return console.warn("myContract.transact() is deprecated please use myContract.sendTransaction() instead."),t.sendTransaction(e)},t._options={},["gas","gasPrice","value","from"].forEach(function(e){t[e]=function(n){return t._options[e]=n,t}})},l=function(t,e,n){var i=o.inputParser(e),c=o.outputParser(e);a.filterFunctions(e).forEach(function(o){var l=a.extractDisplayName(o.name),f=a.extractTypeName(o.name),p=function(){var a=Array.prototype.slice.call(arguments),p=u.functionSignatureFromAscii(o.name),m=i[l][f].apply(null,a),d=t._options||{};d.to=n,d.data=p+m;var h=t._isTransaction===!0||t._isTransaction!==!1&&!o.constant,g=d.collapse!==!1;if(t._options={},t._isTransaction=null,h)return s({abi:e,address:n,method:o.name,params:a}),void r.eth.sendTransaction(d);var y=r.eth.call(d),b=c[l][f](y);return g&&(1===b.length?b=b[0]:0===b.length&&(b=null)),b};void 0===t[l]&&(t[l]=p),t[l][f]=p})},f=function(t,e,n){t.address=n,t._onWatchEventResult=function(t){var n=event.getMatchingEvent(a.filterEvents(e)),r=i.outputParser(n);return r(t)},Object.defineProperty(t,"topics",{get:function(){return a.filterEvents(e).map(function(t){return u.eventSignatureFromAscii(t.name)})}})},p=function(t,e,n){a.filterEvents(e).forEach(function(e){var o=function(){var t=Array.prototype.slice.call(arguments),o=u.eventSignatureFromAscii(e.name),a=i.inputParser(n,o,e),s=a.apply(null,t),c=function(t){var n=i.outputParser(e);return n(t)};return r.eth.filter(s,void 0,void 0,c)};o._isEvent=!0;var s=a.extractDisplayName(e.name),c=a.extractTypeName(e.name);void 0===t[s]&&(t[s]=o),t[s][c]=o})},m=function(t){return t instanceof Array&&1===arguments.length?n.bind(null,t):(console.warn("Initiating a contract like this is deprecated please use var MyContract = eth.contract(abi); new MyContract(address); instead."),new n(arguments[1],arguments[0]))};e.exports=m},{"../solidity/abi":1,"../utils/utils":5,"../web3":6,"./event":10,"./signature":19}],8:[function(t,e){var n=function(){return[{name:"put",call:"db_put"},{name:"get",call:"db_get"},{name:"putString",call:"db_putString"},{name:"getString",call:"db_getString"}]};e.exports={methods:n}},{}],9:[function(t,e){var n=t("./formatters"),r=t("../utils/utils"),o=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getBlockByHash":"eth_getBlockByNumber"},a=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getTransactionByBlockHashAndIndex":"eth_getTransactionByBlockNumberAndIndex"},i=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getUncleByBlockHashAndIndex":"eth_getUncleByBlockNumberAndIndex"},u=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getBlockTransactionCountByHash":"eth_getBlockTransactionCountByNumber"},s=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getUncleCountByBlockHash":"eth_getUncleCountByBlockNumber"},c=[{name:"getBalance",call:"eth_getBalance",addDefaultblock:2,outputFormatter:n.convertToBigNumber},{name:"getStorage",call:"eth_getStorage",addDefaultblock:2},{name:"getStorageAt",call:"eth_getStorageAt",addDefaultblock:3,inputFormatter:r.toHex},{name:"getData",call:"eth_getData",addDefaultblock:2},{name:"getBlock",call:o,outputFormatter:n.outputBlockFormatter,inputFormatter:[r.toHex,function(t){return t?!0:!1}]},{name:"getUncle",call:i,outputFormatter:n.outputBlockFormatter,inputFormatter:[r.toHex,r.toHex,function(t){return t?!0:!1}]},{name:"getCompilers",call:"eth_getCompilers"},{name:"getBlockTransactionCount",call:u,outputFormatter:r.toDecimal,inputFormatter:r.toHex},{name:"getBlockUncleCount",call:s,outputFormatter:r.toDecimal,inputFormatter:r.toHex},{name:"getTransaction",call:"eth_getTransactionByHash",outputFormatter:n.outputTransactionFormatter},{name:"getTransactionFromBlock",call:a,outputFormatter:n.outputTransactionFormatter,inputFormatter:r.toHex},{name:"getTransactionCount",call:"eth_getTransactionCount",addDefaultblock:2,outputFormatter:r.toDecimal},{name:"sendTransaction",call:"eth_sendTransaction",inputFormatter:n.inputTransactionFormatter},{name:"call",call:"eth_call",addDefaultblock:2,inputFormatter:n.inputCallFormatter},{name:"compile.solidity",call:"eth_compileSolidity",inputFormatter:r.toHex},{name:"compile.lll",call:"eth_compileLLL",inputFormatter:r.toHex},{name:"compile.serpent",call:"eth_compileSerpent",inputFormatter:r.toHex},{name:"flush",call:"eth_flush"},{name:"balanceAt",call:"eth_balanceAt",newMethod:"eth.getBalance"},{name:"stateAt",call:"eth_stateAt",newMethod:"eth.getStorageAt"},{name:"storageAt",call:"eth_storageAt",newMethod:"eth.getStorage"},{name:"countAt",call:"eth_countAt",newMethod:"eth.getTransactionCount"},{name:"codeAt",call:"eth_codeAt",newMethod:"eth.getData"},{name:"transact",call:"eth_transact",newMethod:"eth.sendTransaction"},{name:"block",call:o,newMethod:"eth.getBlock"},{name:"transaction",call:a,newMethod:"eth.getTransaction"},{name:"uncle",call:i,newMethod:"eth.getUncle"},{name:"compilers",call:"eth_compilers",newMethod:"eth.getCompilers"},{name:"solidity",call:"eth_solidity",newMethod:"eth.compile.solidity"},{name:"lll",call:"eth_lll",newMethod:"eth.compile.lll"},{name:"serpent",call:"eth_serpent",newMethod:"eth.compile.serpent"},{name:"transactionCount",call:u,newMethod:"eth.getBlockTransactionCount"},{name:"uncleCount",call:s,newMethod:"eth.getBlockUncleCount"},{name:"logs",call:"eth_logs"}],l=[{name:"coinbase",getter:"eth_coinbase"},{name:"mining",getter:"eth_mining"},{name:"gasPrice",getter:"eth_gasPrice",outputFormatter:n.convertToBigNumber},{name:"accounts",getter:"eth_accounts"},{name:"blockNumber",getter:"eth_blockNumber",outputFormatter:r.toDecimal},{name:"listening",getter:"net_listening",setter:"eth_setListening",newProperty:"net.listening"},{name:"peerCount",getter:"net_peerCount",newProperty:"net.peerCount"},{name:"number",getter:"eth_number",newProperty:"eth.blockNumber"}];e.exports={methods:c,properties:l}},{"../utils/utils":5,"./formatters":12}],10:[function(t,e){var n=t("../solidity/abi"),r=t("../utils/utils"),o=t("./signature"),a=function(t,e){return t.filter(function(t){return t.indexed===e})},i=function(t,e){var n=r.findIndex(t,function(t){return t.name===e});return-1===n?void console.error("indexed param with name "+e+" not found"):t[n]},u=function(t,e){return Object.keys(e).map(function(r){var o=[i(a(t.inputs,!0),r)],u=e[r];return u instanceof Array?u.map(function(t){return n.formatInput(o,[t])}):n.formatInput(o,[u])})},s=function(t,e,n){return function(r,o){var a=o||{};return a.address=t,a.topics=[],a.topics.push(e),r&&(a.topics=a.topics.concat(u(n,r))),a}},c=function(t,e,n){var r=e.slice(),o=n.slice();return t.reduce(function(t,e){var n;return n=e.indexed?r.splice(0,1)[0]:o.splice(0,1)[0],t[e.name]=n,t},{})},l=function(t){return function(e){var o={event:r.extractDisplayName(t.name),number:e.number,hash:e.hash,args:{}};if(e.topics=e.topic,!e.topics)return o;var i=a(t.inputs,!0),u="0x"+e.topics.slice(1,e.topics.length).map(function(t){return t.slice(2)}).join(""),s=n.formatOutput(i,u),l=a(t.inputs,!1),f=n.formatOutput(l,e.data);return o.args=c(t.inputs,s,f),o}},f=function(t,e){for(var n=0;n<t.length;n++){var r=o.eventSignatureFromAscii(t[n].name);if(r===e.topics[0])return t[n]}return void 0};e.exports={inputParser:s,outputParser:l,getMatchingEvent:f}},{"../solidity/abi":1,"../utils/utils":5,"./signature":19}],11:[function(t,e){var n=t("../utils/utils"),r=function(t){return!!t&&"function"==typeof t.newFilter&&"function"==typeof t.getLogs&&"function"==typeof t.uninstallFilter&&"function"==typeof t.startPolling&&"function"==typeof t.stopPolling},o=function(t){return"string"==typeof t?t:(t=t||{},t.topic&&(console.warn('"topic" is deprecated, is "topics" instead'),t.topics=t.topic),t.earliest&&(console.warn('"earliest" is deprecated, is "fromBlock" instead'),t.fromBlock=t.earliest),t.latest&&(console.warn('"latest" is deprecated, is "toBlock" instead'),t.toBlock=t.latest),t.skip&&(console.warn('"skip" is deprecated, is "offset" instead'),t.offset=t.skip),t.max&&(console.warn('"max" is deprecated, is "limit" instead'),t.limit=t.max),t.topics instanceof Array&&(t.topics=t.topics.map(function(t){return n.toHex(t)})),{fromBlock:n.toHex(t.fromBlock),toBlock:n.toHex(t.toBlock),limit:n.toHex(t.limit),offset:n.toHex(t.offset),to:t.to,address:t.address,topics:t.topics})},a=function(t,e,a){if(!r(e))return void console.error("filter implemenation is invalid");t=o(t);var i=[],u=e.newFilter(t),s=function(t){t.forEach(function(t){t=a?a(t):t,i.forEach(function(e){e(t)})})};e.startPolling(u,s,e.uninstallFilter);var c=function(t){i.push(t)},l=function(){e.stopPolling(u),e.uninstallFilter(u),i=[]},f=function(){var t=e.getLogs(u);return n.isArray(t)?t.map(function(t){return a?a(t):t}):t};return{watch:c,stopWatching:l,get:f,changed:function(){return console.warn("watch().changed() is deprecated please use filter().watch() instead."),c.apply(this,arguments)},arrived:function(){return console.warn("watch().arrived() is deprecated please use filter().watch() instead."),c.apply(this,arguments)},happened:function(){return console.warn("watch().happened() is deprecated please use filter().watch() instead."),c.apply(this,arguments)},uninstall:function(){return console.warn("watch().uninstall() is deprecated please use filter().stopWatching() instead."),l.apply(this,arguments)},messages:function(){return console.warn("watch().messages() is deprecated please use filter().get() instead."),f.apply(this,arguments)},logs:function(){return console.warn("watch().logs() is deprecated please use filter().get() instead."),f.apply(this,arguments)}}};e.exports=a},{"../utils/utils":5}],12:[function(t,e){var n=t("../utils/utils"),r=function(t){return n.toBigNumber(t)},o=function(t){return t.code&&(t.data=t.code,delete t.code),["gasPrice","gas","value"].forEach(function(e){t[e]=n.fromDecimal(t[e])}),t},a=function(t){return t.gas=n.toDecimal(t.gas),t.gasPrice=n.toBigNumber(t.gasPrice),t.value=n.toBigNumber(t.value),t},i=function(t){return t.code&&(t.data=t.code,delete t.code),t},u=function(t){return t.gasLimit=n.toDecimal(t.gasLimit),t.gasUsed=n.toDecimal(t.gasUsed),t.size=n.toDecimal(t.size),t.timestamp=n.toDecimal(t.timestamp),t.number=n.toDecimal(t.number),t.minGasPrice=n.toBigNumber(t.minGasPrice),t.difficulty=n.toBigNumber(t.difficulty),t.totalDifficulty=n.toBigNumber(t.totalDifficulty),t.transactions instanceof Array&&t.transactions.forEach(function(t){return n.isString(t)?void 0:a(t)}),t},s=function(t){return t.blockNumber=n.toDecimal(t.blockNumber),t.transactionIndex=n.toDecimal(t.transactionIndex),t.logIndex=n.toDecimal(t.logIndex),t},c=function(t){return t.payload=n.toHex(t.payload),t.ttl=n.fromDecimal(t.ttl),t.priority=n.fromDecimal(t.priority),t.topics instanceof Array||(t.topics=[t.topics]),t.topics=t.topics.map(function(t){return n.fromAscii(t)}),t},l=function(t){if(t.expiry=n.toDecimal(t.expiry),t.sent=n.toDecimal(t.sent),t.ttl=n.toDecimal(t.ttl),t.workProved=n.toDecimal(t.workProved),t.payloadRaw=t.payload,t.payload=n.toAscii(t.payload),0===t.payload.indexOf("{")||0===t.payload.indexOf("["))try{t.payload=JSON.parse(t.payload)}catch(e){}return t.topics=t.topics.map(function(t){return n.toAscii(t)}),t};e.exports={convertToBigNumber:r,inputTransactionFormatter:o,outputTransactionFormatter:a,inputCallFormatter:i,outputBlockFormatter:u,outputLogFormatter:s,inputPostFormatter:c,outputPostFormatter:l}},{"../utils/utils":5}],13:[function(t,e){var n=function(t){this.name="HTTP",this.handlers=[],this.host=t||"http://localhost:8080"};n.prototype.send=function(t,e){var n=new XMLHttpRequest;if(n.open("POST",this.host,!1),"function"!=typeof e){if(n.open("POST",this.host,!1),n.send(JSON.stringify(t)),200!==n.status)return;return JSON.parse(n.responseText)}n.onreadystatechange=function(){if(4===n.readyState){var t="";try{t=JSON.parse(n.responseText)}catch(r){t=r}e(t,n.status)}},n.open("POST",this.host,!0),n.send(JSON.stringify(t))},e.exports=n},{}],14:[function(t,e){var n=1,r=function(t,e){return t||console.error("jsonrpc method should be specified!"),{jsonrpc:"2.0",method:t,params:e||[],id:n++}},o=function(t){return!!t&&!t.error&&"2.0"===t.jsonrpc&&"number"==typeof t.id&&void 0!==t.result},a=function(t){return t.map(function(t){return r(t.method,t.params)})};e.exports={toPayload:r,isValidResponse:o,toBatchPayload:a}},{}],15:[function(t,e){var n=t("../utils/utils"),r=[],o=[{name:"listening",getter:"net_listening"},{name:"peerCount",getter:"net_peerCount",outputFormatter:n.toDecimal}];e.exports={methods:r,properties:o}},{"../utils/utils":5}],16:[function(t,e){var n=function(){};n.prototype.send=function(t){var e=navigator.qt.callMethod(JSON.stringify(t));return JSON.parse(e)},e.exports=n},{}],17:[function(t,e){var n=t("./jsonrpc"),r=t("../utils/config"),o=function(){var t,e=[],o=null,a=function(e,r){"function"==typeof e.inputFormatter?e.params=Array.prototype.map.call(e.params,function(t,n){return!e.addDefaultblock||n+1<e.addDefaultblock?e.inputFormatter(t):t}):e.inputFormatter instanceof Array&&(e.params=Array.prototype.map.call(e.inputFormatter,function(t,n){return!e.addDefaultblock||n+1<e.addDefaultblock?t(e.params[n]):e.params[n]}));var o=n.toPayload(e.method,e.params);if(!t)return console.error("provider is not set"),null;if("function"!=typeof r||"HTTP"!==t.name){var a=t.send(o);return n.isValidResponse(a)?"function"==typeof e.outputFormatter?e.outputFormatter(a.result):a.result:(console.log(a),"object"==typeof a&&a.error&&a.error.message&&console.error(a.error.message),null)}t.send(o,function(t,o){return n.isValidResponse(t)?void r(null,"function"==typeof e.outputFormatter?e.outputFormatter(t.result):t.result):("object"==typeof t&&t.error&&t.error.message?(console.error(t.error.message),r(t.error)):r(new Error({status:o,error:t,message:"Bad Request"})),null)})},i=function(e){t=e},u=function(t,n,r,o){e.push({data:t,id:n,callback:r,uninstall:o})},s=function(t){for(var n=e.length;n--;){var r=e[n];r.id===t&&e.splice(n,1)}},c=function(){e.forEach(function(t){t.uninstall(t.id)}),e=[],o&&(clearTimeout(o),o=null),l()},l=function(){e.forEach(function(t){a(t.data,function(e,n){n instanceof Array&&0!==n.length&&t.callback(n)})}),o=setTimeout(l,r.ETH_POLLING_TIMEOUT)};return l(),{send:a,setProvider:i,startPolling:u,stopPolling:s,reset:c}};e.exports=o},{"../utils/config":4,"./jsonrpc":14}],18:[function(t,e){var n=t("./formatters"),r=function(){return[{name:"post",call:"shh_post",inputFormatter:n.inputPostFormatter},{name:"newIdentity",call:"shh_newIdentity"},{name:"hasIdentity",call:"shh_hasIdentity"},{name:"newGroup",call:"shh_newGroup"},{name:"addToGroup",call:"shh_addToGroup"},{name:"haveIdentity",call:"shh_haveIdentity",newMethod:"shh.hasIdentity"}]};e.exports={methods:r}},{"./formatters":12}],19:[function(t,e){var n=t("../web3"),r=t("../utils/config"),o=function(t){return n.sha3(n.fromAscii(t)).slice(0,2+2*r.ETH_SIGNATURE_LENGTH)},a=function(t){return n.sha3(n.fromAscii(t))};e.exports={functionSignatureFromAscii:o,eventSignatureFromAscii:a}},{"../utils/config":4,"../web3":6}],20:[function(t,e){var n=function(){var t=function(t){return"string"==typeof t[0]?"eth_newBlockFilter":"eth_newFilter"};return[{name:"newFilter",call:t},{name:"uninstallFilter",call:"eth_uninstallFilter"},{name:"getLogs",call:"eth_getFilterLogs"}]},r=function(){return[{name:"newFilter",call:"shh_newFilter"},{name:"uninstallFilter",call:"shh_uninstallFilter"},{name:"getLogs",call:"shh_getMessages"}]};e.exports={eth:n,shh:r}},{}],web3:[function(t,e){var n=t("./lib/web3");n.providers.HttpProvider=t("./lib/web3/httpprovider"),n.providers.QtSyncProvider=t("./lib/web3/qtsync"),n.eth.contract=t("./lib/web3/contract"),n.abi=t("./lib/solidity/abi"),e.exports=n},{"./lib/solidity/abi":1,"./lib/web3":6,"./lib/web3/contract":7,"./lib/web3/httpprovider":13,"./lib/web3/qtsync":16}]},{},["web3"]);` diff --git a/jsre/jsre.go b/jsre/jsre.go new file mode 100644 index 000000000..7ae5be742 --- /dev/null +++ b/jsre/jsre.go @@ -0,0 +1,115 @@ +package jsre + +import ( + "fmt" + "github.com/obscuren/otto" + "io/ioutil" + + "github.com/ethereum/go-ethereum/ethutil" +) + +/* +JSRE is a generic JS runtime environment embedding the otto JS interpreter. +It provides some helper functions to +- load code from files +- run code snippets +- require libraries +- bind native go objects +*/ +type JSRE struct { + assetPath string + vm *otto.Otto +} + +func New(assetPath string) *JSRE { + re := &JSRE{ + assetPath, + otto.New(), + } + + // load prettyprint func definition + re.vm.Run(pp_js) + re.vm.Set("loadScript", re.loadScript) + + return re +} + +// Exec(file) loads and runs the contents of a file +// if a relative path is given, the jsre's assetPath is used +func (self *JSRE) Exec(file string) error { + return self.exec(ethutil.AbsolutePath(self.assetPath, file)) +} + +func (self *JSRE) exec(path string) error { + code, err := ioutil.ReadFile(path) + if err != nil { + return err + } + _, err = self.vm.Run(code) + return err +} + +func (self *JSRE) Bind(name string, v interface{}) (err error) { + self.vm.Set(name, v) + return +} + +func (self *JSRE) Run(code string) (otto.Value, error) { + return self.vm.Run(code) +} + +func (self *JSRE) Get(ns string) (otto.Value, error) { + return self.vm.Get(ns) +} + +func (self *JSRE) Set(ns string, v interface{}) error { + return self.vm.Set(ns, v) +} + +func (self *JSRE) loadScript(call otto.FunctionCall) otto.Value { + file, err := call.Argument(0).ToString() + if err != nil { + return otto.FalseValue() + } + if err := self.Exec(file); err != nil { + fmt.Println("err:", err) + return otto.FalseValue() + } + + return otto.TrueValue() +} + +func (self *JSRE) PrettyPrint(v interface{}) (val otto.Value, err error) { + var method otto.Value + v, err = self.vm.ToValue(v) + if err != nil { + return + } + method, err = self.vm.Get("prettyPrint") + if err != nil { + return + } + return method.Call(method, v) +} + +func (self *JSRE) ToVal(v interface{}) otto.Value { + result, err := self.vm.ToValue(v) + if err != nil { + fmt.Println("Value unknown:", err) + return otto.UndefinedValue() + } + return result +} + +func (self *JSRE) Eval(code string) (s string, err error) { + var val otto.Value + val, err = self.Run(code) + if err != nil { + return + } + val, err = self.PrettyPrint(val) + if err != nil { + return + } + return fmt.Sprintf("%v", val), nil +} diff --git a/jsre/jsre_test.go b/jsre/jsre_test.go new file mode 100644 index 000000000..67b5ea906 --- /dev/null +++ b/jsre/jsre_test.go @@ -0,0 +1,85 @@ +package jsre + +import ( + "github.com/obscuren/otto" + "os" + "path" + "testing" + + "github.com/ethereum/go-ethereum/ethutil" +) + +var defaultAssetPath = path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist", "assets", "ext") + +type testNativeObjectBinding struct { + toVal func(interface{}) otto.Value +} + +type msg struct { + Msg string +} + +func (no *testNativeObjectBinding) TestMethod(call otto.FunctionCall) otto.Value { + m, err := call.Argument(0).ToString() + if err != nil { + return otto.UndefinedValue() + } + return no.toVal(&msg{m}) +} + +func TestExec(t *testing.T) { + jsre := New("/tmp") + + ethutil.WriteFile("/tmp/test.js", []byte(`msg = "testMsg"`)) + err := jsre.Exec("test.js") + if err != nil { + t.Errorf("expected no error, got %v", err) + } + val, err := jsre.Run("msg") + if err != nil { + t.Errorf("expected no error, got %v", err) + } + if !val.IsString() { + t.Errorf("expected string value, got %v", val) + } + + // this errors + err = jsre.Exec(path.Join(defaultAssetPath, "bignumber.min.js")) + if err != nil { + t.Errorf("expected no error, got %v", err) + } + _, err = jsre.Run("x = new BigNumber(123.4567);") + if err != nil { + t.Errorf("expected no error, got %v", err) + } +} + +func TestBind(t *testing.T) { + jsre := New(defaultAssetPath) + + jsre.Bind("no", &testNativeObjectBinding{jsre.ToVal}) + + val, err := jsre.Run(`no.testMethod("testMsg")`) + if err != nil { + t.Errorf("expected no error, got %v", err) + } + pp, err := jsre.PrettyPrint(val) + if err != nil { + t.Errorf("expected no error, got %v", err) + } + t.Logf("no: %v", pp) +} + +func TestRequire(t *testing.T) { + jsre := New(defaultAssetPath) + + _, err := jsre.Run("x = new BigNumber(123.4567);") + if err == nil { + t.Errorf("expected error, got nothing") + } + _, err = jsre.Run(`loadScript("bignumber.min.js"); x = new BigNumber(123.4567)`) + if err != nil { + t.Errorf("expected no error, got %v", err) + } + +} diff --git a/jsre/pp_js.go b/jsre/pp_js.go new file mode 100644 index 000000000..fd80ae68b --- /dev/null +++ b/jsre/pp_js.go @@ -0,0 +1,55 @@ +package jsre + +const pp_js = ` +function pp(object) { + var str = ""; + + if(object instanceof Array) { + str += "[ "; + for(var i = 0, l = object.length; i < l; i++) { + str += pp(object[i]); + + if(i < l-1) { + str += ", "; + } + } + str += " ]"; + } else if(typeof(object) === "object") { + str += "{ "; + var last = Object.keys(object).pop() + for(var k in object) { + str += k + ": " + pp(object[k]); + + if(k !== last) { + str += ", "; + } + } + str += " }"; + } else if(typeof(object) === "string") { + str += "\033[32m'" + object + "'"; + } else if(typeof(object) === "undefined") { + str += "\033[1m\033[30m" + object; + } else if(typeof(object) === "number") { + str += "\033[31m" + object; + } else if(typeof(object) === "function") { + str += "\033[35m[Function]"; + } else { + str += object; + } + + str += "\033[0m"; + + return str; +} + +function prettyPrint(/* */) { + var args = arguments; + var ret = ""; + for(var i = 0, l = args.length; i < l; i++) { + ret += pp(args[i]) + "\n"; + } + return ret; +} + +var print = prettyPrint; +` |