github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/eth/tracers/tracer.go (about)

     1  
     2  //<developer>
     3  //    <name>linapex 曹一峰</name>
     4  //    <email>linapex@163.com</email>
     5  //    <wx>superexc</wx>
     6  //    <qqgroup>128148617</qqgroup>
     7  //    <url>https://jsq.ink</url>
     8  //    <role>pku engineer</role>
     9  //    <date>2019-03-16 19:16:37</date>
    10  //</624450089842118656>
    11  
    12  
    13  package tracers
    14  
    15  import (
    16  	"encoding/json"
    17  	"errors"
    18  	"fmt"
    19  	"math/big"
    20  	"sync/atomic"
    21  	"time"
    22  	"unsafe"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/common/hexutil"
    26  	"github.com/ethereum/go-ethereum/core/vm"
    27  	"github.com/ethereum/go-ethereum/crypto"
    28  	"github.com/ethereum/go-ethereum/log"
    29  	duktape "gopkg.in/olebedev/go-duktape.v3"
    30  )
    31  
    32  //biginegerjs是https://github.com/peterrolson/bigineger.js的小型版本。
    33  const bigIntegerJS = `var bigInt=function(undefined){"use strict";var BASE=1e7,LOG_BASE=7,MAX_INT=9007199254740992,MAX_INT_ARR=smallToArray(MAX_INT),LOG_MAX_INT=Math.log(MAX_INT);function Integer(v,radix){if(typeof v==="undefined")return Integer[0];if(typeof radix!=="undefined")return+radix===10?parseValue(v):parseBase(v,radix);return parseValue(v)}function BigInteger(value,sign){this.value=value;this.sign=sign;this.isSmall=false}BigInteger.prototype=Object.create(Integer.prototype);function SmallInteger(value){this.value=value;this.sign=value<0;this.isSmall=true}SmallInteger.prototype=Object.create(Integer.prototype);function isPrecise(n){return-MAX_INT<n&&n<MAX_INT}function smallToArray(n){if(n<1e7)return[n];if(n<1e14)return[n%1e7,Math.floor(n/1e7)];return[n%1e7,Math.floor(n/1e7)%1e7,Math.floor(n/1e14)]}function arrayToSmall(arr){trim(arr);var length=arr.length;if(length<4&&compareAbs(arr,MAX_INT_ARR)<0){switch(length){case 0:return 0;case 1:return arr[0];case 2:return arr[0]+arr[1]*BASE;default:return arr[0]+(arr[1]+arr[2]*BASE)*BASE}}return arr}function trim(v){var i=v.length;while(v[--i]===0);v.length=i+1}function createArray(length){var x=new Array(length);var i=-1;while(++i<length){x[i]=0}return x}function truncate(n){if(n>0)return Math.floor(n);return Math.ceil(n)}function add(a,b){var l_a=a.length,l_b=b.length,r=new Array(l_a),carry=0,base=BASE,sum,i;for(i=0;i<l_b;i++){sum=a[i]+b[i]+carry;carry=sum>=base?1:0;r[i]=sum-carry*base}while(i<l_a){sum=a[i]+carry;carry=sum===base?1:0;r[i++]=sum-carry*base}if(carry>0)r.push(carry);return r}function addAny(a,b){if(a.length>=b.length)return add(a,b);return add(b,a)}function addSmall(a,carry){var l=a.length,r=new Array(l),base=BASE,sum,i;for(i=0;i<l;i++){sum=a[i]-base+carry;carry=Math.floor(sum/base);r[i]=sum-carry*base;carry+=1}while(carry>0){r[i++]=carry%base;carry=Math.floor(carry/base)}return r}BigInteger.prototype.add=function(v){var n=parseValue(v);if(this.sign!==n.sign){return this.subtract(n.negate())}var a=this.value,b=n.value;if(n.isSmall){return new BigInteger(addSmall(a,Math.abs(b)),this.sign)}return new BigInteger(addAny(a,b),this.sign)};BigInteger.prototype.plus=BigInteger.prototype.add;SmallInteger.prototype.add=function(v){var n=parseValue(v);var a=this.value;if(a<0!==n.sign){return this.subtract(n.negate())}var b=n.value;if(n.isSmall){if(isPrecise(a+b))return new SmallInteger(a+b);b=smallToArray(Math.abs(b))}return new BigInteger(addSmall(b,Math.abs(a)),a<0)};SmallInteger.prototype.plus=SmallInteger.prototype.add;function subtract(a,b){var a_l=a.length,b_l=b.length,r=new Array(a_l),borrow=0,base=BASE,i,difference;for(i=0;i<b_l;i++){difference=a[i]-borrow-b[i];if(difference<0){difference+=base;borrow=1}else borrow=0;r[i]=difference}for(i=b_l;i<a_l;i++){difference=a[i]-borrow;if(difference<0)difference+=base;else{r[i++]=difference;break}r[i]=difference}for(;i<a_l;i++){r[i]=a[i]}trim(r);return r}function subtractAny(a,b,sign){var value;if(compareAbs(a,b)>=0){value=subtract(a,b)}else{value=subtract(b,a);sign=!sign}value=arrayToSmall(value);if(typeof value==="number"){if(sign)value=-value;return new SmallInteger(value)}return new BigInteger(value,sign)}function subtractSmall(a,b,sign){var l=a.length,r=new Array(l),carry=-b,base=BASE,i,difference;for(i=0;i<l;i++){difference=a[i]+carry;carry=Math.floor(difference/base);difference%=base;r[i]=difference<0?difference+base:difference}r=arrayToSmall(r);if(typeof r==="number"){if(sign)r=-r;return new SmallInteger(r)}return new BigInteger(r,sign)}BigInteger.prototype.subtract=function(v){var n=parseValue(v);if(this.sign!==n.sign){return this.add(n.negate())}var a=this.value,b=n.value;if(n.isSmall)return subtractSmall(a,Math.abs(b),this.sign);return subtractAny(a,b,this.sign)};BigInteger.prototype.minus=BigInteger.prototype.subtract;SmallInteger.prototype.subtract=function(v){var n=parseValue(v);var a=this.value;if(a<0!==n.sign){return this.add(n.negate())}var b=n.value;if(n.isSmall){return new SmallInteger(a-b)}return subtractSmall(b,Math.abs(a),a>=0)};SmallInteger.prototype.minus=SmallInteger.prototype.subtract;BigInteger.prototype.negate=function(){return new BigInteger(this.value,!this.sign)};SmallInteger.prototype.negate=function(){var sign=this.sign;var small=new SmallInteger(-this.value);small.sign=!sign;return small};BigInteger.prototype.abs=function(){return new BigInteger(this.value,false)};SmallInteger.prototype.abs=function(){return new SmallInteger(Math.abs(this.value))};function multiplyLong(a,b){var a_l=a.length,b_l=b.length,l=a_l+b_l,r=createArray(l),base=BASE,product,carry,i,a_i,b_j;for(i=0;i<a_l;++i){a_i=a[i];for(var j=0;j<b_l;++j){b_j=b[j];product=a_i*b_j+r[i+j];carry=Math.floor(product/base);r[i+j]=product-carry*base;r[i+j+1]+=carry}}trim(r);return r}function multiplySmall(a,b){var l=a.length,r=new Array(l),base=BASE,carry=0,product,i;for(i=0;i<l;i++){product=a[i]*b+carry;carry=Math.floor(product/base);r[i]=product-carry*base}while(carry>0){r[i++]=carry%base;carry=Math.floor(carry/base)}return r}function shiftLeft(x,n){var r=[];while(n-- >0)r.push(0);return r.concat(x)}function multiplyKaratsuba(x,y){var n=Math.max(x.length,y.length);if(n<=30)return multiplyLong(x,y);n=Math.ceil(n/2);var b=x.slice(n),a=x.slice(0,n),d=y.slice(n),c=y.slice(0,n);var ac=multiplyKaratsuba(a,c),bd=multiplyKaratsuba(b,d),abcd=multiplyKaratsuba(addAny(a,b),addAny(c,d));var product=addAny(addAny(ac,shiftLeft(subtract(subtract(abcd,ac),bd),n)),shiftLeft(bd,2*n));trim(product);return product}function useKaratsuba(l1,l2){return-.012*l1-.012*l2+15e-6*l1*l2>0}BigInteger.prototype.multiply=function(v){var n=parseValue(v),a=this.value,b=n.value,sign=this.sign!==n.sign,abs;if(n.isSmall){if(b===0)return Integer[0];if(b===1)return this;if(b===-1)return this.negate();abs=Math.abs(b);if(abs<BASE){return new BigInteger(multiplySmall(a,abs),sign)}b=smallToArray(abs)}if(useKaratsuba(a.length,b.length))return new BigInteger(multiplyKaratsuba(a,b),sign);return new BigInteger(multiplyLong(a,b),sign)};BigInteger.prototype.times=BigInteger.prototype.multiply;function multiplySmallAndArray(a,b,sign){if(a<BASE){return new BigInteger(multiplySmall(b,a),sign)}return new BigInteger(multiplyLong(b,smallToArray(a)),sign)}SmallInteger.prototype._multiplyBySmall=function(a){if(isPrecise(a.value*this.value)){return new SmallInteger(a.value*this.value)}return multiplySmallAndArray(Math.abs(a.value),smallToArray(Math.abs(this.value)),this.sign!==a.sign)};BigInteger.prototype._multiplyBySmall=function(a){if(a.value===0)return Integer[0];if(a.value===1)return this;if(a.value===-1)return this.negate();return multiplySmallAndArray(Math.abs(a.value),this.value,this.sign!==a.sign)};SmallInteger.prototype.multiply=function(v){return parseValue(v)._multiplyBySmall(this)};SmallInteger.prototype.times=SmallInteger.prototype.multiply;function square(a){var l=a.length,r=createArray(l+l),base=BASE,product,carry,i,a_i,a_j;for(i=0;i<l;i++){a_i=a[i];for(var j=0;j<l;j++){a_j=a[j];product=a_i*a_j+r[i+j];carry=Math.floor(product/base);r[i+j]=product-carry*base;r[i+j+1]+=carry}}trim(r);return r}BigInteger.prototype.square=function(){return new BigInteger(square(this.value),false)};SmallInteger.prototype.square=function(){var value=this.value*this.value;if(isPrecise(value))return new SmallInteger(value);return new BigInteger(square(smallToArray(Math.abs(this.value))),false)};function divMod1(a,b){var a_l=a.length,b_l=b.length,base=BASE,result=createArray(b.length),divisorMostSignificantDigit=b[b_l-1],lambda=Math.ceil(base/(2*divisorMostSignificantDigit)),remainder=multiplySmall(a,lambda),divisor=multiplySmall(b,lambda),quotientDigit,shift,carry,borrow,i,l,q;if(remainder.length<=a_l)remainder.push(0);divisor.push(0);divisorMostSignificantDigit=divisor[b_l-1];for(shift=a_l-b_l;shift>=0;shift--){quotientDigit=base-1;if(remainder[shift+b_l]!==divisorMostSignificantDigit){quotientDigit=Math.floor((remainder[shift+b_l]*base+remainder[shift+b_l-1])/divisorMostSignificantDigit)}carry=0;borrow=0;l=divisor.length;for(i=0;i<l;i++){carry+=quotientDigit*divisor[i];q=Math.floor(carry/base);borrow+=remainder[shift+i]-(carry-q*base);carry=q;if(borrow<0){remainder[shift+i]=borrow+base;borrow=-1}else{remainder[shift+i]=borrow;borrow=0}}while(borrow!==0){quotientDigit-=1;carry=0;for(i=0;i<l;i++){carry+=remainder[shift+i]-base+divisor[i];if(carry<0){remainder[shift+i]=carry+base;carry=0}else{remainder[shift+i]=carry;carry=1}}borrow+=carry}result[shift]=quotientDigit}remainder=divModSmall(remainder,lambda)[0];return[arrayToSmall(result),arrayToSmall(remainder)]}function divMod2(a,b){var a_l=a.length,b_l=b.length,result=[],part=[],base=BASE,guess,xlen,highx,highy,check;while(a_l){part.unshift(a[--a_l]);trim(part);if(compareAbs(part,b)<0){result.push(0);continue}xlen=part.length;highx=part[xlen-1]*base+part[xlen-2];highy=b[b_l-1]*base+b[b_l-2];if(xlen>b_l){highx=(highx+1)*base}guess=Math.ceil(highx/highy);do{check=multiplySmall(b,guess);if(compareAbs(check,part)<=0)break;guess--}while(guess);result.push(guess);part=subtract(part,check)}result.reverse();return[arrayToSmall(result),arrayToSmall(part)]}function divModSmall(value,lambda){var length=value.length,quotient=createArray(length),base=BASE,i,q,remainder,divisor;remainder=0;for(i=length-1;i>=0;--i){divisor=remainder*base+value[i];q=truncate(divisor/lambda);remainder=divisor-q*lambda;quotient[i]=q|0}return[quotient,remainder|0]}function divModAny(self,v){var value,n=parseValue(v);var a=self.value,b=n.value;var quotient;if(b===0)throw new Error("Cannot divide by zero");if(self.isSmall){if(n.isSmall){return[new SmallInteger(truncate(a/b)),new SmallInteger(a%b)]}return[Integer[0],self]}if(n.isSmall){if(b===1)return[self,Integer[0]];if(b==-1)return[self.negate(),Integer[0]];var abs=Math.abs(b);if(abs<BASE){value=divModSmall(a,abs);quotient=arrayToSmall(value[0]);var remainder=value[1];if(self.sign)remainder=-remainder;if(typeof quotient==="number"){if(self.sign!==n.sign)quotient=-quotient;return[new SmallInteger(quotient),new SmallInteger(remainder)]}return[new BigInteger(quotient,self.sign!==n.sign),new SmallInteger(remainder)]}b=smallToArray(abs)}var comparison=compareAbs(a,b);if(comparison===-1)return[Integer[0],self];if(comparison===0)return[Integer[self.sign===n.sign?1:-1],Integer[0]];if(a.length+b.length<=200)value=divMod1(a,b);else value=divMod2(a,b);quotient=value[0];var qSign=self.sign!==n.sign,mod=value[1],mSign=self.sign;if(typeof quotient==="number"){if(qSign)quotient=-quotient;quotient=new SmallInteger(quotient)}else quotient=new BigInteger(quotient,qSign);if(typeof mod==="number"){if(mSign)mod=-mod;mod=new SmallInteger(mod)}else mod=new BigInteger(mod,mSign);return[quotient,mod]}BigInteger.prototype.divmod=function(v){var result=divModAny(this,v);return{quotient:result[0],remainder:result[1]}};SmallInteger.prototype.divmod=BigInteger.prototype.divmod;BigInteger.prototype.divide=function(v){return divModAny(this,v)[0]};SmallInteger.prototype.over=SmallInteger.prototype.divide=BigInteger.prototype.over=BigInteger.prototype.divide;BigInteger.prototype.mod=function(v){return divModAny(this,v)[1]};SmallInteger.prototype.remainder=SmallInteger.prototype.mod=BigInteger.prototype.remainder=BigInteger.prototype.mod;BigInteger.prototype.pow=function(v){var n=parseValue(v),a=this.value,b=n.value,value,x,y;if(b===0)return Integer[1];if(a===0)return Integer[0];if(a===1)return Integer[1];if(a===-1)return n.isEven()?Integer[1]:Integer[-1];if(n.sign){return Integer[0]}if(!n.isSmall)throw new Error("The exponent "+n.toString()+" is too large.");if(this.isSmall){if(isPrecise(value=Math.pow(a,b)))return new SmallInteger(truncate(value))}x=this;y=Integer[1];while(true){if(b&1===1){y=y.times(x);--b}if(b===0)break;b/=2;x=x.square()}return y};SmallInteger.prototype.pow=BigInteger.prototype.pow;BigInteger.prototype.modPow=function(exp,mod){exp=parseValue(exp);mod=parseValue(mod);if(mod.isZero())throw new Error("Cannot take modPow with modulus 0");var r=Integer[1],base=this.mod(mod);while(exp.isPositive()){if(base.isZero())return Integer[0];if(exp.isOdd())r=r.multiply(base).mod(mod);exp=exp.divide(2);base=base.square().mod(mod)}return r};SmallInteger.prototype.modPow=BigInteger.prototype.modPow;function compareAbs(a,b){if(a.length!==b.length){return a.length>b.length?1:-1}for(var i=a.length-1;i>=0;i--){if(a[i]!==b[i])return a[i]>b[i]?1:-1}return 0}BigInteger.prototype.compareAbs=function(v){var n=parseValue(v),a=this.value,b=n.value;if(n.isSmall)return 1;return compareAbs(a,b)};SmallInteger.prototype.compareAbs=function(v){var n=parseValue(v),a=Math.abs(this.value),b=n.value;if(n.isSmall){b=Math.abs(b);return a===b?0:a>b?1:-1}return-1};BigInteger.prototype.compare=function(v){if(v===Infinity){return-1}if(v===-Infinity){return 1}var n=parseValue(v),a=this.value,b=n.value;if(this.sign!==n.sign){return n.sign?1:-1}if(n.isSmall){return this.sign?-1:1}return compareAbs(a,b)*(this.sign?-1:1)};BigInteger.prototype.compareTo=BigInteger.prototype.compare;SmallInteger.prototype.compare=function(v){if(v===Infinity){return-1}if(v===-Infinity){return 1}var n=parseValue(v),a=this.value,b=n.value;if(n.isSmall){return a==b?0:a>b?1:-1}if(a<0!==n.sign){return a<0?-1:1}return a<0?1:-1};SmallInteger.prototype.compareTo=SmallInteger.prototype.compare;BigInteger.prototype.equals=function(v){return this.compare(v)===0};SmallInteger.prototype.eq=SmallInteger.prototype.equals=BigInteger.prototype.eq=BigInteger.prototype.equals;BigInteger.prototype.notEquals=function(v){return this.compare(v)!==0};SmallInteger.prototype.neq=SmallInteger.prototype.notEquals=BigInteger.prototype.neq=BigInteger.prototype.notEquals;BigInteger.prototype.greater=function(v){return this.compare(v)>0};SmallInteger.prototype.gt=SmallInteger.prototype.greater=BigInteger.prototype.gt=BigInteger.prototype.greater;BigInteger.prototype.lesser=function(v){return this.compare(v)<0};SmallInteger.prototype.lt=SmallInteger.prototype.lesser=BigInteger.prototype.lt=BigInteger.prototype.lesser;BigInteger.prototype.greaterOrEquals=function(v){return this.compare(v)>=0};SmallInteger.prototype.geq=SmallInteger.prototype.greaterOrEquals=BigInteger.prototype.geq=BigInteger.prototype.greaterOrEquals;BigInteger.prototype.lesserOrEquals=function(v){return this.compare(v)<=0};SmallInteger.prototype.leq=SmallInteger.prototype.lesserOrEquals=BigInteger.prototype.leq=BigInteger.prototype.lesserOrEquals;BigInteger.prototype.isEven=function(){return(this.value[0]&1)===0};SmallInteger.prototype.isEven=function(){return(this.value&1)===0};BigInteger.prototype.isOdd=function(){return(this.value[0]&1)===1};SmallInteger.prototype.isOdd=function(){return(this.value&1)===1};BigInteger.prototype.isPositive=function(){return!this.sign};SmallInteger.prototype.isPositive=function(){return this.value>0};BigInteger.prototype.isNegative=function(){return this.sign};SmallInteger.prototype.isNegative=function(){return this.value<0};BigInteger.prototype.isUnit=function(){return false};SmallInteger.prototype.isUnit=function(){return Math.abs(this.value)===1};BigInteger.prototype.isZero=function(){return false};SmallInteger.prototype.isZero=function(){return this.value===0};BigInteger.prototype.isDivisibleBy=function(v){var n=parseValue(v);var value=n.value;if(value===0)return false;if(value===1)return true;if(value===2)return this.isEven();return this.mod(n).equals(Integer[0])};SmallInteger.prototype.isDivisibleBy=BigInteger.prototype.isDivisibleBy;function isBasicPrime(v){var n=v.abs();if(n.isUnit())return false;if(n.equals(2)||n.equals(3)||n.equals(5))return true;if(n.isEven()||n.isDivisibleBy(3)||n.isDivisibleBy(5))return false;if(n.lesser(25))return true}BigInteger.prototype.isPrime=function(){var isPrime=isBasicPrime(this);if(isPrime!==undefined)return isPrime;var n=this.abs(),nPrev=n.prev();var a=[2,3,5,7,11,13,17,19],b=nPrev,d,t,i,x;while(b.isEven())b=b.divide(2);for(i=0;i<a.length;i++){x=bigInt(a[i]).modPow(b,n);if(x.equals(Integer[1])||x.equals(nPrev))continue;for(t=true,d=b;t&&d.lesser(nPrev);d=d.multiply(2)){x=x.square().mod(n);if(x.equals(nPrev))t=false}if(t)return false}return true};SmallInteger.prototype.isPrime=BigInteger.prototype.isPrime;BigInteger.prototype.isProbablePrime=function(iterations){var isPrime=isBasicPrime(this);if(isPrime!==undefined)return isPrime;var n=this.abs();var t=iterations===undefined?5:iterations;for(var i=0;i<t;i++){var a=bigInt.randBetween(2,n.minus(2));if(!a.modPow(n.prev(),n).isUnit())return false}return true};SmallInteger.prototype.isProbablePrime=BigInteger.prototype.isProbablePrime;BigInteger.prototype.modInv=function(n){var t=bigInt.zero,newT=bigInt.one,r=parseValue(n),newR=this.abs(),q,lastT,lastR;while(!newR.equals(bigInt.zero)){q=r.divide(newR);lastT=t;lastR=r;t=newT;r=newR;newT=lastT.subtract(q.multiply(newT));newR=lastR.subtract(q.multiply(newR))}if(!r.equals(1))throw new Error(this.toString()+" and "+n.toString()+" are not co-prime");if(t.compare(0)===-1){t=t.add(n)}if(this.isNegative()){return t.negate()}return t};SmallInteger.prototype.modInv=BigInteger.prototype.modInv;BigInteger.prototype.next=function(){var value=this.value;if(this.sign){return subtractSmall(value,1,this.sign)}return new BigInteger(addSmall(value,1),this.sign)};SmallInteger.prototype.next=function(){var value=this.value;if(value+1<MAX_INT)return new SmallInteger(value+1);return new BigInteger(MAX_INT_ARR,false)};BigInteger.prototype.prev=function(){var value=this.value;if(this.sign){return new BigInteger(addSmall(value,1),true)}return subtractSmall(value,1,this.sign)};SmallInteger.prototype.prev=function(){var value=this.value;if(value-1>-MAX_INT)return new SmallInteger(value-1);return new BigInteger(MAX_INT_ARR,true)};var powersOfTwo=[1];while(2*powersOfTwo[powersOfTwo.length-1]<=BASE)powersOfTwo.push(2*powersOfTwo[powersOfTwo.length-1]);var powers2Length=powersOfTwo.length,highestPower2=powersOfTwo[powers2Length-1];function shift_isSmall(n){return(typeof n==="number"||typeof n==="string")&&+Math.abs(n)<=BASE||n instanceof BigInteger&&n.value.length<=1}BigInteger.prototype.shiftLeft=function(n){if(!shift_isSmall(n)){throw new Error(String(n)+" is too large for shifting.")}n=+n;if(n<0)return this.shiftRight(-n);var result=this;while(n>=powers2Length){result=result.multiply(highestPower2);n-=powers2Length-1}return result.multiply(powersOfTwo[n])};SmallInteger.prototype.shiftLeft=BigInteger.prototype.shiftLeft;BigInteger.prototype.shiftRight=function(n){var remQuo;if(!shift_isSmall(n)){throw new Error(String(n)+" is too large for shifting.")}n=+n;if(n<0)return this.shiftLeft(-n);var result=this;while(n>=powers2Length){if(result.isZero())return result;remQuo=divModAny(result,highestPower2);result=remQuo[1].isNegative()?remQuo[0].prev():remQuo[0];n-=powers2Length-1}remQuo=divModAny(result,powersOfTwo[n]);return remQuo[1].isNegative()?remQuo[0].prev():remQuo[0]};SmallInteger.prototype.shiftRight=BigInteger.prototype.shiftRight;function bitwise(x,y,fn){y=parseValue(y);var xSign=x.isNegative(),ySign=y.isNegative();var xRem=xSign?x.not():x,yRem=ySign?y.not():y;var xDigit=0,yDigit=0;var xDivMod=null,yDivMod=null;var result=[];while(!xRem.isZero()||!yRem.isZero()){xDivMod=divModAny(xRem,highestPower2);xDigit=xDivMod[1].toJSNumber();if(xSign){xDigit=highestPower2-1-xDigit}yDivMod=divModAny(yRem,highestPower2);yDigit=yDivMod[1].toJSNumber();if(ySign){yDigit=highestPower2-1-yDigit}xRem=xDivMod[0];yRem=yDivMod[0];result.push(fn(xDigit,yDigit))}var sum=fn(xSign?1:0,ySign?1:0)!==0?bigInt(-1):bigInt(0);for(var i=result.length-1;i>=0;i-=1){sum=sum.multiply(highestPower2).add(bigInt(result[i]))}return sum}BigInteger.prototype.not=function(){return this.negate().prev()};SmallInteger.prototype.not=BigInteger.prototype.not;BigInteger.prototype.and=function(n){return bitwise(this,n,function(a,b){return a&b})};SmallInteger.prototype.and=BigInteger.prototype.and;BigInteger.prototype.or=function(n){return bitwise(this,n,function(a,b){return a|b})};SmallInteger.prototype.or=BigInteger.prototype.or;BigInteger.prototype.xor=function(n){return bitwise(this,n,function(a,b){return a^b})};SmallInteger.prototype.xor=BigInteger.prototype.xor;var LOBMASK_I=1<<30,LOBMASK_BI=(BASE&-BASE)*(BASE&-BASE)|LOBMASK_I;function roughLOB(n){var v=n.value,x=typeof v==="number"?v|LOBMASK_I:v[0]+v[1]*BASE|LOBMASK_BI;return x&-x}function max(a,b){a=parseValue(a);b=parseValue(b);return a.greater(b)?a:b}function min(a,b){a=parseValue(a);b=parseValue(b);return a.lesser(b)?a:b}function gcd(a,b){a=parseValue(a).abs();b=parseValue(b).abs();if(a.equals(b))return a;if(a.isZero())return b;if(b.isZero())return a;var c=Integer[1],d,t;while(a.isEven()&&b.isEven()){d=Math.min(roughLOB(a),roughLOB(b));a=a.divide(d);b=b.divide(d);c=c.multiply(d)}while(a.isEven()){a=a.divide(roughLOB(a))}do{while(b.isEven()){b=b.divide(roughLOB(b))}if(a.greater(b)){t=b;b=a;a=t}b=b.subtract(a)}while(!b.isZero());return c.isUnit()?a:a.multiply(c)}function lcm(a,b){a=parseValue(a).abs();b=parseValue(b).abs();return a.divide(gcd(a,b)).multiply(b)}function randBetween(a,b){a=parseValue(a);b=parseValue(b);var low=min(a,b),high=max(a,b);var range=high.subtract(low).add(1);if(range.isSmall)return low.add(Math.floor(Math.random()*range));var length=range.value.length-1;var result=[],restricted=true;for(var i=length;i>=0;i--){var top=restricted?range.value[i]:BASE;var digit=truncate(Math.random()*top);result.unshift(digit);if(digit<top)restricted=false}result=arrayToSmall(result);return low.add(typeof result==="number"?new SmallInteger(result):new BigInteger(result,false))}var parseBase=function(text,base){var length=text.length;var i;var absBase=Math.abs(base);for(var i=0;i<length;i++){var c=text[i].toLowerCase();if(c==="-")continue;if(/[a-z0-9]/.test(c)){if(/[0-9]/.test(c)&&+c>=absBase){if(c==="1"&&absBase===1)continue;throw new Error(c+" is not a valid digit in base "+base+".")}else if(c.charCodeAt(0)-87>=absBase){throw new Error(c+" is not a valid digit in base "+base+".")}}}if(2<=base&&base<=36){if(length<=LOG_MAX_INT/Math.log(base)){var result=parseInt(text,base);if(isNaN(result)){throw new Error(c+" is not a valid digit in base "+base+".")}return new SmallInteger(parseInt(text,base))}}base=parseValue(base);var digits=[];var isNegative=text[0]==="-";for(i=isNegative?1:0;i<text.length;i++){var c=text[i].toLowerCase(),charCode=c.charCodeAt(0);if(48<=charCode&&charCode<=57)digits.push(parseValue(c));else if(97<=charCode&&charCode<=122)digits.push(parseValue(c.charCodeAt(0)-87));else if(c==="<"){var start=i;do{i++}while(text[i]!==">");digits.push(parseValue(text.slice(start+1,i)))}else throw new Error(c+" is not a valid character")}return parseBaseFromArray(digits,base,isNegative)};function parseBaseFromArray(digits,base,isNegative){var val=Integer[0],pow=Integer[1],i;for(i=digits.length-1;i>=0;i--){val=val.add(digits[i].times(pow));pow=pow.times(base)}return isNegative?val.negate():val}function stringify(digit){var v=digit.value;if(typeof v==="number")v=[v];if(v.length===1&&v[0]<=35){return"0123456789abcdefghijklmnopqrstuvwxyz".charAt(v[0])}return"<"+v+">"}function toBase(n,base){base=bigInt(base);if(base.isZero()){if(n.isZero())return"0";throw new Error("Cannot convert nonzero numbers to base 0.")}if(base.equals(-1)){if(n.isZero())return"0";if(n.isNegative())return new Array(1-n).join("10");return"1"+new Array(+n).join("01")}var minusSign="";if(n.isNegative()&&base.isPositive()){minusSign="-";n=n.abs()}if(base.equals(1)){if(n.isZero())return"0";return minusSign+new Array(+n+1).join(1)}var out=[];var left=n,divmod;while(left.isNegative()||left.compareAbs(base)>=0){divmod=left.divmod(base);left=divmod.quotient;var digit=divmod.remainder;if(digit.isNegative()){digit=base.minus(digit).abs();left=left.next()}out.push(stringify(digit))}out.push(stringify(left));return minusSign+out.reverse().join("")}BigInteger.prototype.toString=function(radix){if(radix===undefined)radix=10;if(radix!==10)return toBase(this,radix);var v=this.value,l=v.length,str=String(v[--l]),zeros="0000000",digit;while(--l>=0){digit=String(v[l]);str+=zeros.slice(digit.length)+digit}var sign=this.sign?"-":"";return sign+str};SmallInteger.prototype.toString=function(radix){if(radix===undefined)radix=10;if(radix!=10)return toBase(this,radix);return String(this.value)};BigInteger.prototype.toJSON=SmallInteger.prototype.toJSON=function(){return this.toString()};BigInteger.prototype.valueOf=function(){return+this.toString()};BigInteger.prototype.toJSNumber=BigInteger.prototype.valueOf;SmallInteger.prototype.valueOf=function(){return this.value};SmallInteger.prototype.toJSNumber=SmallInteger.prototype.valueOf;function parseStringValue(v){if(isPrecise(+v)){var x=+v;if(x===truncate(x))return new SmallInteger(x);throw"Invalid integer: "+v}var sign=v[0]==="-";if(sign)v=v.slice(1);var split=v.split(/e/i);if(split.length>2)throw new Error("Invalid integer: "+split.join("e"));if(split.length===2){var exp=split[1];if(exp[0]==="+")exp=exp.slice(1);exp=+exp;if(exp!==truncate(exp)||!isPrecise(exp))throw new Error("Invalid integer: "+exp+" is not a valid exponent.");var text=split[0];var decimalPlace=text.indexOf(".");if(decimalPlace>=0){exp-=text.length-decimalPlace-1;text=text.slice(0,decimalPlace)+text.slice(decimalPlace+1)}if(exp<0)throw new Error("Cannot include negative exponent part for integers");text+=new Array(exp+1).join("0");v=text}var isValid=/^([0-9][0-9]*)$/.test(v);if(!isValid)throw new Error("Invalid integer: "+v);var r=[],max=v.length,l=LOG_BASE,min=max-l;while(max>0){r.push(+v.slice(min,max));min-=l;if(min<0)min=0;max-=l}trim(r);return new BigInteger(r,sign)}function parseNumberValue(v){if(isPrecise(v)){if(v!==truncate(v))throw new Error(v+" is not an integer.");return new SmallInteger(v)}return parseStringValue(v.toString())}function parseValue(v){if(typeof v==="number"){return parseNumberValue(v)}if(typeof v==="string"){return parseStringValue(v)}return v}for(var i=0;i<1e3;i++){Integer[i]=new SmallInteger(i);if(i>0)Integer[-i]=new SmallInteger(-i)}Integer.one=Integer[1];Integer.zero=Integer[0];Integer.minusOne=Integer[-1];Integer.max=max;Integer.min=min;Integer.gcd=gcd;Integer.lcm=lcm;Integer.isInstance=function(x){return x instanceof BigInteger||x instanceof SmallInteger};Integer.randBetween=randBetween;Integer.fromArray=function(digits,base,isNegative){return parseBaseFromArray(digits.map(parseValue),parseValue(base||10),isNegative)};return Integer}();if(typeof module!=="undefined"&&module.hasOwnProperty("exports")){module.exports=bigInt}if(typeof define==="function"&&define.amd){define("big-integer",[],function(){return bigInt})}; bigInt`
    34  
    35  //makeslice将具有给定类型的不安全内存指针转换为go字节
    36  //切片。
    37  //
    38  //注意,返回的切片使用与输入参数相同的内存区域。
    39  //如果这些是Duktape堆栈项,则弹出它们**将**成为切片
    40  //内容更改。
    41  func makeSlice(ptr unsafe.Pointer, size uint) []byte {
    42  	var sl = struct {
    43  		addr uintptr
    44  		len  int
    45  		cap  int
    46  	}{uintptr(ptr), int(size), int(size)}
    47  
    48  	return *(*[]byte)(unsafe.Pointer(&sl))
    49  }
    50  
    51  //popsicle从javascript堆栈中弹出一个缓冲区,并将其作为一个切片返回。
    52  func popSlice(ctx *duktape.Context) []byte {
    53  	blob := common.CopyBytes(makeSlice(ctx.GetBuffer(-1)))
    54  	ctx.Pop()
    55  	return blob
    56  }
    57  
    58  //pushbigint在虚拟机中创建一个javascript biginger。
    59  func pushBigInt(n *big.Int, ctx *duktape.Context) {
    60  	ctx.GetGlobalString("bigInt")
    61  	ctx.PushString(n.String())
    62  	ctx.Call(1)
    63  }
    64  
    65  //opwrapper提供了一个围绕操作码的javascript包装器。
    66  type opWrapper struct {
    67  	op vm.OpCode
    68  }
    69  
    70  //PushObject组装包装可交换操作码的JSVM对象并将其推送
    71  //到VM堆栈。
    72  func (ow *opWrapper) pushObject(vm *duktape.Context) {
    73  	obj := vm.PushObject()
    74  
    75  	vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushInt(int(ow.op)); return 1 })
    76  	vm.PutPropString(obj, "toNumber")
    77  
    78  	vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushString(ow.op.String()); return 1 })
    79  	vm.PutPropString(obj, "toString")
    80  
    81  	vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushBoolean(ow.op.IsPush()); return 1 })
    82  	vm.PutPropString(obj, "isPush")
    83  }
    84  
    85  //memory wrapper提供了一个围绕vm.memory的javascript包装器。
    86  type memoryWrapper struct {
    87  	memory *vm.Memory
    88  }
    89  
    90  //slice以字节片的形式返回请求的内存范围。
    91  func (mw *memoryWrapper) slice(begin, end int64) []byte {
    92  	if mw.memory.Len() < int(end) {
    93  //托多(卡拉拉比):我们不能把球从内往外扔。围棋
    94  //运行时崩溃https://github.com/golang/go/issues/15639。
    95  		log.Warn("Tracer accessed out of bound memory", "available", mw.memory.Len(), "offset", begin, "size", end-begin)
    96  		return nil
    97  	}
    98  	return mw.memory.Get(begin, end-begin)
    99  }
   100  
   101  //getuint返回被解释为uint的指定地址处的32个字节。
   102  func (mw *memoryWrapper) getUint(addr int64) *big.Int {
   103  	if mw.memory.Len() < int(addr)+32 {
   104  //托多(卡拉拉比):我们不能把球从内往外扔。围棋
   105  //运行时崩溃https://github.com/golang/go/issues/15639。
   106  		log.Warn("Tracer accessed out of bound memory", "available", mw.memory.Len(), "offset", addr, "size", 32)
   107  		return new(big.Int)
   108  	}
   109  	return new(big.Int).SetBytes(mw.memory.GetPtr(addr, 32))
   110  }
   111  
   112  //pushobject组装包装可交换内存的JSVM对象并将其推送
   113  //到VM堆栈。
   114  func (mw *memoryWrapper) pushObject(vm *duktape.Context) {
   115  	obj := vm.PushObject()
   116  
   117  //生成接受两个整数并返回缓冲区的“slice”方法
   118  	vm.PushGoFunction(func(ctx *duktape.Context) int {
   119  		blob := mw.slice(int64(ctx.GetInt(-2)), int64(ctx.GetInt(-1)))
   120  		ctx.Pop2()
   121  
   122  		ptr := ctx.PushFixedBuffer(len(blob))
   123  		copy(makeSlice(ptr, uint(len(blob))), blob)
   124  		return 1
   125  	})
   126  	vm.PutPropString(obj, "slice")
   127  
   128  //生成“getuint”方法,该方法接受int并返回bigint
   129  	vm.PushGoFunction(func(ctx *duktape.Context) int {
   130  		offset := int64(ctx.GetInt(-1))
   131  		ctx.Pop()
   132  
   133  		pushBigInt(mw.getUint(offset), ctx)
   134  		return 1
   135  	})
   136  	vm.PutPropString(obj, "getUint")
   137  }
   138  
   139  //stack wrapper提供了一个围绕vm.stack的javascript包装器。
   140  type stackWrapper struct {
   141  	stack *vm.Stack
   142  }
   143  
   144  //Peek返回堆栈顶部元素的第n个。
   145  func (sw *stackWrapper) peek(idx int) *big.Int {
   146  	if len(sw.stack.Data()) <= idx {
   147  //托多(卡拉拉比):我们不能把球从内往外扔。围棋
   148  //运行时崩溃https://github.com/golang/go/issues/15639。
   149  		log.Warn("Tracer accessed out of bound stack", "size", len(sw.stack.Data()), "index", idx)
   150  		return new(big.Int)
   151  	}
   152  	return sw.stack.Data()[len(sw.stack.Data())-idx-1]
   153  }
   154  
   155  //PushObject组装包装可交换堆栈的JSVM对象并将其推送
   156  //到VM堆栈。
   157  func (sw *stackWrapper) pushObject(vm *duktape.Context) {
   158  	obj := vm.PushObject()
   159  
   160  	vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushInt(len(sw.stack.Data())); return 1 })
   161  	vm.PutPropString(obj, "length")
   162  
   163  //生成接受int并返回bigint的“peek”方法
   164  	vm.PushGoFunction(func(ctx *duktape.Context) int {
   165  		offset := ctx.GetInt(-1)
   166  		ctx.Pop()
   167  
   168  		pushBigInt(sw.peek(offset), ctx)
   169  		return 1
   170  	})
   171  	vm.PutPropString(obj, "peek")
   172  }
   173  
   174  //dbwrapper提供了一个围绕vm.database的javascript包装器。
   175  type dbWrapper struct {
   176  	db vm.StateDB
   177  }
   178  
   179  //pushobject组装包装可交换数据库的JSVM对象并将其推送
   180  //到VM堆栈。
   181  func (dw *dbWrapper) pushObject(vm *duktape.Context) {
   182  	obj := vm.PushObject()
   183  
   184  //推送statedb.getbalance的包装
   185  	vm.PushGoFunction(func(ctx *duktape.Context) int {
   186  		pushBigInt(dw.db.GetBalance(common.BytesToAddress(popSlice(ctx))), ctx)
   187  		return 1
   188  	})
   189  	vm.PutPropString(obj, "getBalance")
   190  
   191  //推送statedb.getnonce的包装
   192  	vm.PushGoFunction(func(ctx *duktape.Context) int {
   193  		ctx.PushInt(int(dw.db.GetNonce(common.BytesToAddress(popSlice(ctx)))))
   194  		return 1
   195  	})
   196  	vm.PutPropString(obj, "getNonce")
   197  
   198  //推送statedb.getcode的包装器
   199  	vm.PushGoFunction(func(ctx *duktape.Context) int {
   200  		code := dw.db.GetCode(common.BytesToAddress(popSlice(ctx)))
   201  
   202  		ptr := ctx.PushFixedBuffer(len(code))
   203  		copy(makeSlice(ptr, uint(len(code))), code)
   204  		return 1
   205  	})
   206  	vm.PutPropString(obj, "getCode")
   207  
   208  //推送statedb.getstate的包装
   209  	vm.PushGoFunction(func(ctx *duktape.Context) int {
   210  		hash := popSlice(ctx)
   211  		addr := popSlice(ctx)
   212  
   213  		state := dw.db.GetState(common.BytesToAddress(addr), common.BytesToHash(hash))
   214  
   215  		ptr := ctx.PushFixedBuffer(len(state))
   216  		copy(makeSlice(ptr, uint(len(state))), state[:])
   217  		return 1
   218  	})
   219  	vm.PutPropString(obj, "getState")
   220  
   221  //推送statedb.exists的包装
   222  	vm.PushGoFunction(func(ctx *duktape.Context) int {
   223  		ctx.PushBoolean(dw.db.Exist(common.BytesToAddress(popSlice(ctx))))
   224  		return 1
   225  	})
   226  	vm.PutPropString(obj, "exists")
   227  }
   228  
   229  //contractWrapper provides a JavaScript wrapper around vm.Contract
   230  type contractWrapper struct {
   231  	contract *vm.Contract
   232  }
   233  
   234  //PushObject组装包装可交换协定的JSVM对象并将其推送
   235  //到VM堆栈。
   236  func (cw *contractWrapper) pushObject(vm *duktape.Context) {
   237  	obj := vm.PushObject()
   238  
   239  //为contract.caller推送包装
   240  	vm.PushGoFunction(func(ctx *duktape.Context) int {
   241  		ptr := ctx.PushFixedBuffer(20)
   242  		copy(makeSlice(ptr, 20), cw.contract.Caller().Bytes())
   243  		return 1
   244  	})
   245  	vm.PutPropString(obj, "getCaller")
   246  
   247  //按合同包装。地址
   248  	vm.PushGoFunction(func(ctx *duktape.Context) int {
   249  		ptr := ctx.PushFixedBuffer(20)
   250  		copy(makeSlice(ptr, 20), cw.contract.Address().Bytes())
   251  		return 1
   252  	})
   253  	vm.PutPropString(obj, "getAddress")
   254  
   255  //为contract.value推送包装器
   256  	vm.PushGoFunction(func(ctx *duktape.Context) int {
   257  		pushBigInt(cw.contract.Value(), ctx)
   258  		return 1
   259  	})
   260  	vm.PutPropString(obj, "getValue")
   261  
   262  //为contract.input推送包装器
   263  	vm.PushGoFunction(func(ctx *duktape.Context) int {
   264  		blob := cw.contract.Input
   265  
   266  		ptr := ctx.PushFixedBuffer(len(blob))
   267  		copy(makeSlice(ptr, uint(len(blob))), blob)
   268  		return 1
   269  	})
   270  	vm.PutPropString(obj, "getInput")
   271  }
   272  
   273  //跟踪程序提供跟踪程序的实现,该跟踪程序评估JavaScript
   274  //每个VM执行步骤的函数。
   275  type Tracer struct {
   276  inited bool //标记上下文是否已从EVM初始化
   277  
   278  vm *duktape.Context //javascript虚拟机实例
   279  
   280  tracerObject int //跟踪程序javascript对象的堆栈索引
   281  stateObject  int //Stack index of the global state to pull arguments from
   282  
   283  opWrapper       *opWrapper       //围绕VM操作码的包装器
   284  stackWrapper    *stackWrapper    //围绕VM堆栈包装
   285  memoryWrapper   *memoryWrapper   //包装虚拟机内存
   286  contractWrapper *contractWrapper //包装合同对象
   287  dbWrapper       *dbWrapper       //包装虚拟机环境
   288  
   289  pcValue     *uint   //由日志访问器包装的可交换PC值
   290  gasValue    *uint   //由日志访问器包装的可交换气体值
   291  costValue   *uint   //日志访问器包装的可交换成本值
   292  depthValue  *uint   //日志访问器包装的可交换深度值
   293  errorValue  *string //日志访问器包装的可交换错误值
   294  refundValue *uint   //日志访问器包装的可交换退款值
   295  
   296  ctx map[string]interface{} //在执行过程中收集的事务上下文
   297  err error                  //如果发生错误
   298  
   299  interrupt uint32 //信号执行中断的原子标志
   300  reason    error  //中断的文字原因
   301  }
   302  
   303  //New实例化新的跟踪程序实例。代码指定了一个javascript代码段,
   304  //它必须计算为返回带有“step”、“fault”的对象的表达式
   305  //和“result”函数。
   306  func New(code string) (*Tracer, error) {
   307  //按名称解析任何跟踪程序并组装跟踪程序对象
   308  	if tracer, ok := tracer(code); ok {
   309  		code = tracer
   310  	}
   311  	tracer := &Tracer{
   312  		vm:              duktape.New(),
   313  		ctx:             make(map[string]interface{}),
   314  		opWrapper:       new(opWrapper),
   315  		stackWrapper:    new(stackWrapper),
   316  		memoryWrapper:   new(memoryWrapper),
   317  		contractWrapper: new(contractWrapper),
   318  		dbWrapper:       new(dbWrapper),
   319  		pcValue:         new(uint),
   320  		gasValue:        new(uint),
   321  		costValue:       new(uint),
   322  		depthValue:      new(uint),
   323  		refundValue:     new(uint),
   324  	}
   325  //为此环境设置内置项
   326  	tracer.vm.PushGlobalGoFunction("toHex", func(ctx *duktape.Context) int {
   327  		ctx.PushString(hexutil.Encode(popSlice(ctx)))
   328  		return 1
   329  	})
   330  	tracer.vm.PushGlobalGoFunction("toWord", func(ctx *duktape.Context) int {
   331  		var word common.Hash
   332  		if ptr, size := ctx.GetBuffer(-1); ptr != nil {
   333  			word = common.BytesToHash(makeSlice(ptr, size))
   334  		} else {
   335  			word = common.HexToHash(ctx.GetString(-1))
   336  		}
   337  		ctx.Pop()
   338  		copy(makeSlice(ctx.PushFixedBuffer(32), 32), word[:])
   339  		return 1
   340  	})
   341  	tracer.vm.PushGlobalGoFunction("toAddress", func(ctx *duktape.Context) int {
   342  		var addr common.Address
   343  		if ptr, size := ctx.GetBuffer(-1); ptr != nil {
   344  			addr = common.BytesToAddress(makeSlice(ptr, size))
   345  		} else {
   346  			addr = common.HexToAddress(ctx.GetString(-1))
   347  		}
   348  		ctx.Pop()
   349  		copy(makeSlice(ctx.PushFixedBuffer(20), 20), addr[:])
   350  		return 1
   351  	})
   352  	tracer.vm.PushGlobalGoFunction("toContract", func(ctx *duktape.Context) int {
   353  		var from common.Address
   354  		if ptr, size := ctx.GetBuffer(-2); ptr != nil {
   355  			from = common.BytesToAddress(makeSlice(ptr, size))
   356  		} else {
   357  			from = common.HexToAddress(ctx.GetString(-2))
   358  		}
   359  		nonce := uint64(ctx.GetInt(-1))
   360  		ctx.Pop2()
   361  
   362  		contract := crypto.CreateAddress(from, nonce)
   363  		copy(makeSlice(ctx.PushFixedBuffer(20), 20), contract[:])
   364  		return 1
   365  	})
   366  	tracer.vm.PushGlobalGoFunction("toContract2", func(ctx *duktape.Context) int {
   367  		var from common.Address
   368  		if ptr, size := ctx.GetBuffer(-3); ptr != nil {
   369  			from = common.BytesToAddress(makeSlice(ptr, size))
   370  		} else {
   371  			from = common.HexToAddress(ctx.GetString(-3))
   372  		}
   373  //从JS堆栈中检索salt十六进制字符串
   374  		salt := common.HexToHash(ctx.GetString(-2))
   375  //从JS堆栈中检索代码切片
   376  		var code []byte
   377  		if ptr, size := ctx.GetBuffer(-1); ptr != nil {
   378  			code = common.CopyBytes(makeSlice(ptr, size))
   379  		} else {
   380  			code = common.FromHex(ctx.GetString(-1))
   381  		}
   382  		codeHash := crypto.Keccak256(code)
   383  		ctx.Pop3()
   384  		contract := crypto.CreateAddress2(from, salt, codeHash)
   385  		copy(makeSlice(ctx.PushFixedBuffer(20), 20), contract[:])
   386  		return 1
   387  	})
   388  	tracer.vm.PushGlobalGoFunction("isPrecompiled", func(ctx *duktape.Context) int {
   389  		_, ok := vm.PrecompiledContractsByzantium[common.BytesToAddress(popSlice(ctx))]
   390  		ctx.PushBoolean(ok)
   391  		return 1
   392  	})
   393  	tracer.vm.PushGlobalGoFunction("slice", func(ctx *duktape.Context) int {
   394  		start, end := ctx.GetInt(-2), ctx.GetInt(-1)
   395  		ctx.Pop2()
   396  
   397  		blob := popSlice(ctx)
   398  		size := end - start
   399  
   400  		if start < 0 || start > end || end > len(blob) {
   401  //托多(卡拉拉比):我们不能把球从内往外扔。围棋
   402  //运行时崩溃https://github.com/golang/go/issues/15639。
   403  			log.Warn("Tracer accessed out of bound memory", "available", len(blob), "offset", start, "size", size)
   404  			ctx.PushFixedBuffer(0)
   405  			return 1
   406  		}
   407  		copy(makeSlice(ctx.PushFixedBuffer(size), uint(size)), blob[start:end])
   408  		return 1
   409  	})
   410  //将javascript跟踪程序作为对象0推送到JSVM堆栈上,并对其进行验证
   411  	if err := tracer.vm.PevalString("(" + code + ")"); err != nil {
   412  		log.Warn("Failed to compile tracer", "err", err)
   413  		return nil, err
   414  	}
   415  tracer.tracerObject = 0 //是的,很好,Eval不能返回索引本身
   416  
   417  	if !tracer.vm.GetPropString(tracer.tracerObject, "step") {
   418  		return nil, fmt.Errorf("Trace object must expose a function step()")
   419  	}
   420  	tracer.vm.Pop()
   421  
   422  	if !tracer.vm.GetPropString(tracer.tracerObject, "fault") {
   423  		return nil, fmt.Errorf("Trace object must expose a function fault()")
   424  	}
   425  	tracer.vm.Pop()
   426  
   427  	if !tracer.vm.GetPropString(tracer.tracerObject, "result") {
   428  		return nil, fmt.Errorf("Trace object must expose a function result()")
   429  	}
   430  	tracer.vm.Pop()
   431  
   432  //tracer有效,注入big int库以访问大量
   433  	tracer.vm.EvalString(bigIntegerJS)
   434  	tracer.vm.PutGlobalString("bigInt")
   435  
   436  //将全局环境状态作为对象1推送到JSVM堆栈中
   437  	tracer.stateObject = tracer.vm.PushObject()
   438  
   439  	logObject := tracer.vm.PushObject()
   440  
   441  	tracer.opWrapper.pushObject(tracer.vm)
   442  	tracer.vm.PutPropString(logObject, "op")
   443  
   444  	tracer.stackWrapper.pushObject(tracer.vm)
   445  	tracer.vm.PutPropString(logObject, "stack")
   446  
   447  	tracer.memoryWrapper.pushObject(tracer.vm)
   448  	tracer.vm.PutPropString(logObject, "memory")
   449  
   450  	tracer.contractWrapper.pushObject(tracer.vm)
   451  	tracer.vm.PutPropString(logObject, "contract")
   452  
   453  	tracer.vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushUint(*tracer.pcValue); return 1 })
   454  	tracer.vm.PutPropString(logObject, "getPC")
   455  
   456  	tracer.vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushUint(*tracer.gasValue); return 1 })
   457  	tracer.vm.PutPropString(logObject, "getGas")
   458  
   459  	tracer.vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushUint(*tracer.costValue); return 1 })
   460  	tracer.vm.PutPropString(logObject, "getCost")
   461  
   462  	tracer.vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushUint(*tracer.depthValue); return 1 })
   463  	tracer.vm.PutPropString(logObject, "getDepth")
   464  
   465  	tracer.vm.PushGoFunction(func(ctx *duktape.Context) int { ctx.PushUint(*tracer.refundValue); return 1 })
   466  	tracer.vm.PutPropString(logObject, "getRefund")
   467  
   468  	tracer.vm.PushGoFunction(func(ctx *duktape.Context) int {
   469  		if tracer.errorValue != nil {
   470  			ctx.PushString(*tracer.errorValue)
   471  		} else {
   472  			ctx.PushUndefined()
   473  		}
   474  		return 1
   475  	})
   476  	tracer.vm.PutPropString(logObject, "getError")
   477  
   478  	tracer.vm.PutPropString(tracer.stateObject, "log")
   479  
   480  	tracer.dbWrapper.pushObject(tracer.vm)
   481  	tracer.vm.PutPropString(tracer.stateObject, "db")
   482  
   483  	return tracer, nil
   484  }
   485  
   486  //stop在第一个适当的时刻终止跟踪程序的执行。
   487  func (jst *Tracer) Stop(err error) {
   488  	jst.reason = err
   489  	atomic.StoreUint32(&jst.interrupt, 1)
   490  }
   491  
   492  //调用对JS对象执行方法,捕获任何错误、格式和
   493  //将它们作为错误对象返回。
   494  func (jst *Tracer) call(method string, args ...string) (json.RawMessage, error) {
   495  //执行javascript调用并返回任何错误
   496  	jst.vm.PushString(method)
   497  	for _, arg := range args {
   498  		jst.vm.GetPropString(jst.stateObject, arg)
   499  	}
   500  	code := jst.vm.PcallProp(jst.tracerObject, len(args))
   501  	defer jst.vm.Pop()
   502  
   503  	if code != 0 {
   504  		err := jst.vm.SafeToString(-1)
   505  		return nil, errors.New(err)
   506  	}
   507  //未发生错误,提取返回值并返回
   508  	return json.RawMessage(jst.vm.JsonEncode(-1)), nil
   509  }
   510  
   511  func wrapError(context string, err error) error {
   512  	return fmt.Errorf("%v    in server-side tracer function '%v'", err, context)
   513  }
   514  
   515  //CaptureStart实现跟踪程序接口以初始化跟踪操作。
   516  func (jst *Tracer) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error {
   517  	jst.ctx["type"] = "CALL"
   518  	if create {
   519  		jst.ctx["type"] = "CREATE"
   520  	}
   521  	jst.ctx["from"] = from
   522  	jst.ctx["to"] = to
   523  	jst.ctx["input"] = input
   524  	jst.ctx["gas"] = gas
   525  	jst.ctx["value"] = value
   526  
   527  	return nil
   528  }
   529  
   530  //CaptureState实现跟踪接口来跟踪VM执行的单个步骤。
   531  func (jst *Tracer) CaptureState(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, depth int, err error) error {
   532  	if jst.err == nil {
   533  //初始化上下文(如果尚未完成)
   534  		if !jst.inited {
   535  			jst.ctx["block"] = env.BlockNumber.Uint64()
   536  			jst.inited = true
   537  		}
   538  //如果跟踪被中断,设置错误并停止
   539  		if atomic.LoadUint32(&jst.interrupt) > 0 {
   540  			jst.err = jst.reason
   541  			return nil
   542  		}
   543  		jst.opWrapper.op = op
   544  		jst.stackWrapper.stack = stack
   545  		jst.memoryWrapper.memory = memory
   546  		jst.contractWrapper.contract = contract
   547  		jst.dbWrapper.db = env.StateDB
   548  
   549  		*jst.pcValue = uint(pc)
   550  		*jst.gasValue = uint(gas)
   551  		*jst.costValue = uint(cost)
   552  		*jst.depthValue = uint(depth)
   553  		*jst.refundValue = uint(env.StateDB.GetRefund())
   554  
   555  		jst.errorValue = nil
   556  		if err != nil {
   557  			jst.errorValue = new(string)
   558  			*jst.errorValue = err.Error()
   559  		}
   560  		_, err := jst.call("step", "log", "db")
   561  		if err != nil {
   562  			jst.err = wrapError("step", err)
   563  		}
   564  	}
   565  	return nil
   566  }
   567  
   568  //CaptureFault实现跟踪程序接口来跟踪执行错误
   569  //运行操作码时。
   570  func (jst *Tracer) CaptureFault(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, contract *vm.Contract, depth int, err error) error {
   571  	if jst.err == nil {
   572  //除了错误,所有内容都与上一次调用匹配
   573  		jst.errorValue = new(string)
   574  		*jst.errorValue = err.Error()
   575  
   576  		_, err := jst.call("fault", "log", "db")
   577  		if err != nil {
   578  			jst.err = wrapError("fault", err)
   579  		}
   580  	}
   581  	return nil
   582  }
   583  
   584  //在调用完成后调用CaptureEnd以完成跟踪。
   585  func (jst *Tracer) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error {
   586  	jst.ctx["output"] = output
   587  	jst.ctx["gasUsed"] = gasUsed
   588  	jst.ctx["time"] = t.String()
   589  
   590  	if err != nil {
   591  		jst.ctx["error"] = err.Error()
   592  	}
   593  	return nil
   594  }
   595  
   596  //getresult调用javascript“result”函数并返回其值或任何累积错误
   597  func (jst *Tracer) GetResult() (json.RawMessage, error) {
   598  //将上下文转换为javascript对象并注入状态
   599  	obj := jst.vm.PushObject()
   600  
   601  	for key, val := range jst.ctx {
   602  		switch val := val.(type) {
   603  		case uint64:
   604  			jst.vm.PushUint(uint(val))
   605  
   606  		case string:
   607  			jst.vm.PushString(val)
   608  
   609  		case []byte:
   610  			ptr := jst.vm.PushFixedBuffer(len(val))
   611  			copy(makeSlice(ptr, uint(len(val))), val)
   612  
   613  		case common.Address:
   614  			ptr := jst.vm.PushFixedBuffer(20)
   615  			copy(makeSlice(ptr, 20), val[:])
   616  
   617  		case *big.Int:
   618  			pushBigInt(val, jst.vm)
   619  
   620  		default:
   621  			panic(fmt.Sprintf("unsupported type: %T", val))
   622  		}
   623  		jst.vm.PutPropString(obj, key)
   624  	}
   625  	jst.vm.PutPropString(jst.stateObject, "ctx")
   626  
   627  //完成跟踪并返回结果
   628  	result, err := jst.call("result", "ctx", "db")
   629  	if err != nil {
   630  		jst.err = wrapError("result", err)
   631  	}
   632  //清理javascript环境
   633  	jst.vm.DestroyHeap()
   634  	jst.vm.Destroy()
   635  
   636  	return result, jst.err
   637  }
   638