Commit 95061a25 authored by kingwang's avatar kingwang

add allow && change exec name to jsvm

parent 932ca951
<script src="runtime.js"></script>
<script src="test.js"></script>
<script>
callcode("{}", "execlocal_hello", "{}", [])
</script>
\ No newline at end of file
all:
./gen.sh
\ No newline at end of file
package executor package executor
//系统内置代码
var callcode = ` var callcode = `
var tojson = JSON.stringify var tojson = JSON.stringify
//table warp
function table(kvc, config, defaultvalue) {
var ret = table_new(config, defaultvalue)
if (ret.err) {
throw new Error(ret.err)
}
this.kvc = kvc
this.id = ret.id
this.config = config
this.defaultvalue = defaultvalue
}
function isstring(obj) {
return typeof obj === "string"
}
table.prototype.add = function(obj) {
if (!isstring(obj)) {
obj = tojson(obj)
}
var ret = table_add(this.id, obj)
return ret.err
}
table.prototype.replace = function(obj) {
if (!isstring(obj)) {
obj = tojson(obj)
}
var ret = table_replace(this.id, obj)
return ret.err
}
table.prototype.del = function(obj) {
if (!isstring(obj)) {
obj = tojson(obj)
}
var ret = table_del(this.id, obj)
return ret.err
}
table.prototype.save = function() {
var ret = table_save(this.id)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret
}
table.prototype.close = function() {
var ret = table_close(this.id)
return ret.err
}
//account warp
function account(kvc, execer, symbol) {
this.execer = execer
this.symbol = symbol
this.kvc = kvc
}
account.prototype.genesisInit = function(addr, amount) {
var ret = genesis_init(this, addr, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.execGenesisInit = function(execer, addr, amount) {
var ret = genesis_init_exec(this, execer, addr, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.getBalance = function(addr) {
return load_account(this, addr)
}
account.prototype.execGetBalance = function(execer, addr) {
return get_balance(this, execer, addr)
}
//本合约转移资产,或者转移到其他合约,或者从其他合约取回资产
account.prototype.transfer = function(from, to, amount) {
var ret = transfer(this, from, to, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.transferToExec = function(execer, from, amount) {
var ret = transfer_to_exec(this, execer, from, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.withdrawFromExec = function(execer, to, amount) {
var ret = withdraw(this, execer, to, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
//管理其他合约的资产转移到这个合约中
account.prototype.execActive = function(execer, addr, amount) {
var ret = exec_active(this, execer, addr, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.execFrozen = function(execer, addr, amount) {
var ret = exec_frozen(this, execer, addr, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.execDeposit = function(execer, addr, amount) {
var ret = exec_deposit(this, execer, addr, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.execWithdraw = function(execer, addr, amount) {
var ret = exec_withdraw(this, execer, addr, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.execTransfer = function(execer, from, to, amount) {
var ret = exec_transfer(this, execer, from, to, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
function kvcreator(dbtype) { function kvcreator(dbtype) {
this.data = {} this.data = {}
this.kvs = [] this.kvs = []
...@@ -12,30 +161,30 @@ function kvcreator(dbtype) { ...@@ -12,30 +161,30 @@ function kvcreator(dbtype) {
this.getloal = getlocaldb this.getloal = getlocaldb
this.list = listdb this.list = listdb
if (dbtype == "exec" || dbtype == "init") { if (dbtype == "exec" || dbtype == "init") {
this.get = getstatedb this.get = this.getstatedb
} else if (dbtype == "local") { } else if (dbtype == "local") {
this.get = getlocaldb this.get = this.getlocaldb
} else if (dbtype == "query") { } else if (dbtype == "query") {
this.get = getlocaldb this.get = this.getlocaldb
} else { } else {
throw new Error("chain33.js: dbtype error") throw new Error("chain33.js: dbtype error")
} }
} }
kvcreator.prototype.add = function(k, v) { kvcreator.prototype.add = function(k, v, prefix) {
if (typeof v != "string") { if (typeof v != "string") {
v = JSON.stringify(v) v = JSON.stringify(v)
} }
this.data[k] = v this.data[k] = v
this.kvs.push({key:k, value: v}) this.kvs.push({key:k, value: v, prefix: !!prefix})
} }
kvcreator.prototype.get = function(k) { kvcreator.prototype.get = function(k, prefix) {
var v var v
if (this.data[k]) { if (this.data[k]) {
v = this.data[k] v = this.data[k]
} else { } else {
var dbvalue = this.get(k) var dbvalue = this.get(k, !!prefix)
if (dbvalue.err != "") { if (dbvalue.err != "") {
return null return null
} }
...@@ -47,6 +196,21 @@ kvcreator.prototype.get = function(k) { ...@@ -47,6 +196,21 @@ kvcreator.prototype.get = function(k) {
return JSON.parse(v) return JSON.parse(v)
} }
kvcreator.prototype.save = function(receipt) {
if (Array.isArray(receipt.logs)) {
for (var i = 0; i < receipt.logs.length; i++) {
var item = receipt.logs[i]
this.addlog(item.log, item.ty, item.format)
}
}
if (Array.isArray(receipt.kvs)) {
for (var i = 0; i < receipt.kvs.length; i++) {
var item = receipt.kvs[i]
this.add(item.key, item.value, item.prefix)
}
}
}
kvcreator.prototype.listvalue = function(prefix, key, count, direction) { kvcreator.prototype.listvalue = function(prefix, key, count, direction) {
var dbvalues = this.list(prefix, key, count, direction) var dbvalues = this.list(prefix, key, count, direction)
if (dbvalues.err != "") { if (dbvalues.err != "") {
...@@ -63,14 +227,20 @@ kvcreator.prototype.listvalue = function(prefix, key, count, direction) { ...@@ -63,14 +227,20 @@ kvcreator.prototype.listvalue = function(prefix, key, count, direction) {
return objlist return objlist
} }
kvcreator.prototype.addlog = function(log) { kvcreator.prototype.addlog = function(log, ty, format) {
if (this.type != "exec") { if (this.type != "exec") {
throw new Error("local or query can't set log") throw new Error("local or query can't set log")
} }
if (typeof v != "string") { if (!isstring(log)) {
log = JSON.stringify(log) log = JSON.stringify(log)
} }
this.logs.push(log) if (!ty) {
ty = 0
}
if (!format) {
format = "json"
}
this.logs.push({log:log, ty: ty, format: format})
} }
kvcreator.prototype.receipt = function() { kvcreator.prototype.receipt = function() {
...@@ -113,3 +283,54 @@ function callcode(context, f, args, loglist) { ...@@ -113,3 +283,54 @@ function callcode(context, f, args, loglist) {
//Long //Long
!function(t,i){"object"==typeof exports&&"object"==typeof module?module.exports=i():"function"==typeof define&&define.amd?define([],i):"object"==typeof exports?exports.Long=i():t.Long=i()}("undefined"!=typeof self?self:this,function(){return function(t){function i(h){if(n[h])return n[h].exports;var e=n[h]={i:h,l:!1,exports:{}};return t[h].call(e.exports,e,e.exports,i),e.l=!0,e.exports}var n={};return i.m=t,i.c=n,i.d=function(t,n,h){i.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:h})},i.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(n,"a",n),n},i.o=function(t,i){return Object.prototype.hasOwnProperty.call(t,i)},i.p="",i(i.s=0)}([function(t,i){function n(t,i,n){this.low=0|t,this.high=0|i,this.unsigned=!!n}function h(t){return!0===(t&&t.__isLong__)}function e(t,i){var n,h,e;return i?(t>>>=0,(e=0<=t&&t<256)&&(h=l[t])?h:(n=r(t,(0|t)<0?-1:0,!0),e&&(l[t]=n),n)):(t|=0,(e=-128<=t&&t<128)&&(h=f[t])?h:(n=r(t,t<0?-1:0,!1),e&&(f[t]=n),n))}function s(t,i){if(isNaN(t))return i?p:m;if(i){if(t<0)return p;if(t>=c)return q}else{if(t<=-w)return _;if(t+1>=w)return E}return t<0?s(-t,i).neg():r(t%d|0,t/d|0,i)}function r(t,i,h){return new n(t,i,h)}function o(t,i,n){if(0===t.length)throw Error("empty string");if("NaN"===t||"Infinity"===t||"+Infinity"===t||"-Infinity"===t)return m;if("number"==typeof i?(n=i,i=!1):i=!!i,(n=n||10)<2||36<n)throw RangeError("radix");var h;if((h=t.indexOf("-"))>0)throw Error("interior hyphen");if(0===h)return o(t.substring(1),i,n).neg();for(var e=s(a(n,8)),r=m,u=0;u<t.length;u+=8){var g=Math.min(8,t.length-u),f=parseInt(t.substring(u,u+g),n);if(g<8){var l=s(a(n,g));r=r.mul(l).add(s(f))}else r=r.mul(e),r=r.add(s(f))}return r.unsigned=i,r}function u(t,i){return"number"==typeof t?s(t,i):"string"==typeof t?o(t,i):r(t.low,t.high,"boolean"==typeof i?i:t.unsigned)}t.exports=n;var g=null;try{g=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(t){}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=h;var f={},l={};n.fromInt=e,n.fromNumber=s,n.fromBits=r;var a=Math.pow;n.fromString=o,n.fromValue=u;var d=4294967296,c=d*d,w=c/2,v=e(1<<24),m=e(0);n.ZERO=m;var p=e(0,!0);n.UZERO=p;var y=e(1);n.ONE=y;var b=e(1,!0);n.UONE=b;var N=e(-1);n.NEG_ONE=N;var E=r(-1,2147483647,!1);n.MAX_VALUE=E;var q=r(-1,-1,!0);n.MAX_UNSIGNED_VALUE=q;var _=r(0,-2147483648,!1);n.MIN_VALUE=_;var B=n.prototype;B.toInt=function(){return this.unsigned?this.low>>>0:this.low},B.toNumber=function(){return this.unsigned?(this.high>>>0)*d+(this.low>>>0):this.high*d+(this.low>>>0)},B.toString=function(t){if((t=t||10)<2||36<t)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(_)){var i=s(t),n=this.div(i),h=n.mul(i).sub(this);return n.toString(t)+h.toInt().toString(t)}return"-"+this.neg().toString(t)}for(var e=s(a(t,6),this.unsigned),r=this,o="";;){var u=r.div(e),g=r.sub(u.mul(e)).toInt()>>>0,f=g.toString(t);if(r=u,r.isZero())return f+o;for(;f.length<6;)f="0"+f;o=""+f+o}},B.getHighBits=function(){return this.high},B.getHighBitsUnsigned=function(){return this.high>>>0},B.getLowBits=function(){return this.low},B.getLowBitsUnsigned=function(){return this.low>>>0},B.getNumBitsAbs=function(){if(this.isNegative())return this.eq(_)?64:this.neg().getNumBitsAbs();for(var t=0!=this.high?this.high:this.low,i=31;i>0&&0==(t&1<<i);i--);return 0!=this.high?i+33:i+1},B.isZero=function(){return 0===this.high&&0===this.low},B.eqz=B.isZero,B.isNegative=function(){return!this.unsigned&&this.high<0},B.isPositive=function(){return this.unsigned||this.high>=0},B.isOdd=function(){return 1==(1&this.low)},B.isEven=function(){return 0==(1&this.low)},B.equals=function(t){return h(t)||(t=u(t)),(this.unsigned===t.unsigned||this.high>>>31!=1||t.high>>>31!=1)&&(this.high===t.high&&this.low===t.low)},B.eq=B.equals,B.notEquals=function(t){return!this.eq(t)},B.neq=B.notEquals,B.ne=B.notEquals,B.lessThan=function(t){return this.comp(t)<0},B.lt=B.lessThan,B.lessThanOrEqual=function(t){return this.comp(t)<=0},B.lte=B.lessThanOrEqual,B.le=B.lessThanOrEqual,B.greaterThan=function(t){return this.comp(t)>0},B.gt=B.greaterThan,B.greaterThanOrEqual=function(t){return this.comp(t)>=0},B.gte=B.greaterThanOrEqual,B.ge=B.greaterThanOrEqual,B.compare=function(t){if(h(t)||(t=u(t)),this.eq(t))return 0;var i=this.isNegative(),n=t.isNegative();return i&&!n?-1:!i&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},B.comp=B.compare,B.negate=function(){return!this.unsigned&&this.eq(_)?_:this.not().add(y)},B.neg=B.negate,B.add=function(t){h(t)||(t=u(t));var i=this.high>>>16,n=65535&this.high,e=this.low>>>16,s=65535&this.low,o=t.high>>>16,g=65535&t.high,f=t.low>>>16,l=65535&t.low,a=0,d=0,c=0,w=0;return w+=s+l,c+=w>>>16,w&=65535,c+=e+f,d+=c>>>16,c&=65535,d+=n+g,a+=d>>>16,d&=65535,a+=i+o,a&=65535,r(c<<16|w,a<<16|d,this.unsigned)},B.subtract=function(t){return h(t)||(t=u(t)),this.add(t.neg())},B.sub=B.subtract,B.multiply=function(t){if(this.isZero())return m;if(h(t)||(t=u(t)),g){return r(g.mul(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}if(t.isZero())return m;if(this.eq(_))return t.isOdd()?_:m;if(t.eq(_))return this.isOdd()?_:m;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(v)&&t.lt(v))return s(this.toNumber()*t.toNumber(),this.unsigned);var i=this.high>>>16,n=65535&this.high,e=this.low>>>16,o=65535&this.low,f=t.high>>>16,l=65535&t.high,a=t.low>>>16,d=65535&t.low,c=0,w=0,p=0,y=0;return y+=o*d,p+=y>>>16,y&=65535,p+=e*d,w+=p>>>16,p&=65535,p+=o*a,w+=p>>>16,p&=65535,w+=n*d,c+=w>>>16,w&=65535,w+=e*a,c+=w>>>16,w&=65535,w+=o*l,c+=w>>>16,w&=65535,c+=i*d+n*a+e*l+o*f,c&=65535,r(p<<16|y,c<<16|w,this.unsigned)},B.mul=B.multiply,B.divide=function(t){if(h(t)||(t=u(t)),t.isZero())throw Error("division by zero");if(g){if(!this.unsigned&&-2147483648===this.high&&-1===t.low&&-1===t.high)return this;return r((this.unsigned?g.div_u:g.div_s)(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?p:m;var i,n,e;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return p;if(t.gt(this.shru(1)))return b;e=p}else{if(this.eq(_)){if(t.eq(y)||t.eq(N))return _;if(t.eq(_))return y;return i=this.shr(1).div(t).shl(1),i.eq(m)?t.isNegative()?y:N:(n=this.sub(t.mul(i)),e=i.add(n.div(t)))}if(t.eq(_))return this.unsigned?p:m;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();e=m}for(n=this;n.gte(t);){i=Math.max(1,Math.floor(n.toNumber()/t.toNumber()));for(var o=Math.ceil(Math.log(i)/Math.LN2),f=o<=48?1:a(2,o-48),l=s(i),d=l.mul(t);d.isNegative()||d.gt(n);)i-=f,l=s(i,this.unsigned),d=l.mul(t);l.isZero()&&(l=y),e=e.add(l),n=n.sub(d)}return e},B.div=B.divide,B.modulo=function(t){if(h(t)||(t=u(t)),g){return r((this.unsigned?g.rem_u:g.rem_s)(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))},B.mod=B.modulo,B.rem=B.modulo,B.not=function(){return r(~this.low,~this.high,this.unsigned)},B.and=function(t){return h(t)||(t=u(t)),r(this.low&t.low,this.high&t.high,this.unsigned)},B.or=function(t){return h(t)||(t=u(t)),r(this.low|t.low,this.high|t.high,this.unsigned)},B.xor=function(t){return h(t)||(t=u(t)),r(this.low^t.low,this.high^t.high,this.unsigned)},B.shiftLeft=function(t){return h(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?r(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned):r(0,this.low<<t-32,this.unsigned)},B.shl=B.shiftLeft,B.shiftRight=function(t){return h(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?r(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned):r(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},B.shr=B.shiftRight,B.shiftRightUnsigned=function(t){return h(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?r(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):32===t?r(this.high,0,this.unsigned):r(this.high>>>t-32,0,this.unsigned)},B.shru=B.shiftRightUnsigned,B.shr_u=B.shiftRightUnsigned,B.rotateLeft=function(t){var i;return h(t)&&(t=t.toInt()),0==(t&=63)?this:32===t?r(this.high,this.low,this.unsigned):t<32?(i=32-t,r(this.low<<t|this.high>>>i,this.high<<t|this.low>>>i,this.unsigned)):(t-=32,i=32-t,r(this.high<<t|this.low>>>i,this.low<<t|this.high>>>i,this.unsigned))},B.rotl=B.rotateLeft,B.rotateRight=function(t){var i;return h(t)&&(t=t.toInt()),0==(t&=63)?this:32===t?r(this.high,this.low,this.unsigned):t<32?(i=32-t,r(this.high<<i|this.low>>>t,this.low<<i|this.high>>>t,this.unsigned)):(t-=32,i=32-t,r(this.low<<i|this.high>>>t,this.high<<i|this.low>>>t,this.unsigned))},B.rotr=B.rotateRight,B.toSigned=function(){return this.unsigned?r(this.low,this.high,!1):this},B.toUnsigned=function(){return this.unsigned?this:r(this.low,this.high,!0)},B.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},B.toBytesLE=function(){var t=this.high,i=this.low;return[255&i,i>>>8&255,i>>>16&255,i>>>24,255&t,t>>>8&255,t>>>16&255,t>>>24]},B.toBytesBE=function(){var t=this.high,i=this.low;return[t>>>24,t>>>16&255,t>>>8&255,255&t,i>>>24,i>>>16&255,i>>>8&255,255&i]},n.fromBytes=function(t,i,h){return h?n.fromBytesLE(t,i):n.fromBytesBE(t,i)},n.fromBytesLE=function(t,i){return new n(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,i)},n.fromBytesBE=function(t,i){return new n(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],i)}}])}); !function(t,i){"object"==typeof exports&&"object"==typeof module?module.exports=i():"function"==typeof define&&define.amd?define([],i):"object"==typeof exports?exports.Long=i():t.Long=i()}("undefined"!=typeof self?self:this,function(){return function(t){function i(h){if(n[h])return n[h].exports;var e=n[h]={i:h,l:!1,exports:{}};return t[h].call(e.exports,e,e.exports,i),e.l=!0,e.exports}var n={};return i.m=t,i.c=n,i.d=function(t,n,h){i.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:h})},i.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(n,"a",n),n},i.o=function(t,i){return Object.prototype.hasOwnProperty.call(t,i)},i.p="",i(i.s=0)}([function(t,i){function n(t,i,n){this.low=0|t,this.high=0|i,this.unsigned=!!n}function h(t){return!0===(t&&t.__isLong__)}function e(t,i){var n,h,e;return i?(t>>>=0,(e=0<=t&&t<256)&&(h=l[t])?h:(n=r(t,(0|t)<0?-1:0,!0),e&&(l[t]=n),n)):(t|=0,(e=-128<=t&&t<128)&&(h=f[t])?h:(n=r(t,t<0?-1:0,!1),e&&(f[t]=n),n))}function s(t,i){if(isNaN(t))return i?p:m;if(i){if(t<0)return p;if(t>=c)return q}else{if(t<=-w)return _;if(t+1>=w)return E}return t<0?s(-t,i).neg():r(t%d|0,t/d|0,i)}function r(t,i,h){return new n(t,i,h)}function o(t,i,n){if(0===t.length)throw Error("empty string");if("NaN"===t||"Infinity"===t||"+Infinity"===t||"-Infinity"===t)return m;if("number"==typeof i?(n=i,i=!1):i=!!i,(n=n||10)<2||36<n)throw RangeError("radix");var h;if((h=t.indexOf("-"))>0)throw Error("interior hyphen");if(0===h)return o(t.substring(1),i,n).neg();for(var e=s(a(n,8)),r=m,u=0;u<t.length;u+=8){var g=Math.min(8,t.length-u),f=parseInt(t.substring(u,u+g),n);if(g<8){var l=s(a(n,g));r=r.mul(l).add(s(f))}else r=r.mul(e),r=r.add(s(f))}return r.unsigned=i,r}function u(t,i){return"number"==typeof t?s(t,i):"string"==typeof t?o(t,i):r(t.low,t.high,"boolean"==typeof i?i:t.unsigned)}t.exports=n;var g=null;try{g=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(t){}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=h;var f={},l={};n.fromInt=e,n.fromNumber=s,n.fromBits=r;var a=Math.pow;n.fromString=o,n.fromValue=u;var d=4294967296,c=d*d,w=c/2,v=e(1<<24),m=e(0);n.ZERO=m;var p=e(0,!0);n.UZERO=p;var y=e(1);n.ONE=y;var b=e(1,!0);n.UONE=b;var N=e(-1);n.NEG_ONE=N;var E=r(-1,2147483647,!1);n.MAX_VALUE=E;var q=r(-1,-1,!0);n.MAX_UNSIGNED_VALUE=q;var _=r(0,-2147483648,!1);n.MIN_VALUE=_;var B=n.prototype;B.toInt=function(){return this.unsigned?this.low>>>0:this.low},B.toNumber=function(){return this.unsigned?(this.high>>>0)*d+(this.low>>>0):this.high*d+(this.low>>>0)},B.toString=function(t){if((t=t||10)<2||36<t)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(_)){var i=s(t),n=this.div(i),h=n.mul(i).sub(this);return n.toString(t)+h.toInt().toString(t)}return"-"+this.neg().toString(t)}for(var e=s(a(t,6),this.unsigned),r=this,o="";;){var u=r.div(e),g=r.sub(u.mul(e)).toInt()>>>0,f=g.toString(t);if(r=u,r.isZero())return f+o;for(;f.length<6;)f="0"+f;o=""+f+o}},B.getHighBits=function(){return this.high},B.getHighBitsUnsigned=function(){return this.high>>>0},B.getLowBits=function(){return this.low},B.getLowBitsUnsigned=function(){return this.low>>>0},B.getNumBitsAbs=function(){if(this.isNegative())return this.eq(_)?64:this.neg().getNumBitsAbs();for(var t=0!=this.high?this.high:this.low,i=31;i>0&&0==(t&1<<i);i--);return 0!=this.high?i+33:i+1},B.isZero=function(){return 0===this.high&&0===this.low},B.eqz=B.isZero,B.isNegative=function(){return!this.unsigned&&this.high<0},B.isPositive=function(){return this.unsigned||this.high>=0},B.isOdd=function(){return 1==(1&this.low)},B.isEven=function(){return 0==(1&this.low)},B.equals=function(t){return h(t)||(t=u(t)),(this.unsigned===t.unsigned||this.high>>>31!=1||t.high>>>31!=1)&&(this.high===t.high&&this.low===t.low)},B.eq=B.equals,B.notEquals=function(t){return!this.eq(t)},B.neq=B.notEquals,B.ne=B.notEquals,B.lessThan=function(t){return this.comp(t)<0},B.lt=B.lessThan,B.lessThanOrEqual=function(t){return this.comp(t)<=0},B.lte=B.lessThanOrEqual,B.le=B.lessThanOrEqual,B.greaterThan=function(t){return this.comp(t)>0},B.gt=B.greaterThan,B.greaterThanOrEqual=function(t){return this.comp(t)>=0},B.gte=B.greaterThanOrEqual,B.ge=B.greaterThanOrEqual,B.compare=function(t){if(h(t)||(t=u(t)),this.eq(t))return 0;var i=this.isNegative(),n=t.isNegative();return i&&!n?-1:!i&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},B.comp=B.compare,B.negate=function(){return!this.unsigned&&this.eq(_)?_:this.not().add(y)},B.neg=B.negate,B.add=function(t){h(t)||(t=u(t));var i=this.high>>>16,n=65535&this.high,e=this.low>>>16,s=65535&this.low,o=t.high>>>16,g=65535&t.high,f=t.low>>>16,l=65535&t.low,a=0,d=0,c=0,w=0;return w+=s+l,c+=w>>>16,w&=65535,c+=e+f,d+=c>>>16,c&=65535,d+=n+g,a+=d>>>16,d&=65535,a+=i+o,a&=65535,r(c<<16|w,a<<16|d,this.unsigned)},B.subtract=function(t){return h(t)||(t=u(t)),this.add(t.neg())},B.sub=B.subtract,B.multiply=function(t){if(this.isZero())return m;if(h(t)||(t=u(t)),g){return r(g.mul(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}if(t.isZero())return m;if(this.eq(_))return t.isOdd()?_:m;if(t.eq(_))return this.isOdd()?_:m;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(v)&&t.lt(v))return s(this.toNumber()*t.toNumber(),this.unsigned);var i=this.high>>>16,n=65535&this.high,e=this.low>>>16,o=65535&this.low,f=t.high>>>16,l=65535&t.high,a=t.low>>>16,d=65535&t.low,c=0,w=0,p=0,y=0;return y+=o*d,p+=y>>>16,y&=65535,p+=e*d,w+=p>>>16,p&=65535,p+=o*a,w+=p>>>16,p&=65535,w+=n*d,c+=w>>>16,w&=65535,w+=e*a,c+=w>>>16,w&=65535,w+=o*l,c+=w>>>16,w&=65535,c+=i*d+n*a+e*l+o*f,c&=65535,r(p<<16|y,c<<16|w,this.unsigned)},B.mul=B.multiply,B.divide=function(t){if(h(t)||(t=u(t)),t.isZero())throw Error("division by zero");if(g){if(!this.unsigned&&-2147483648===this.high&&-1===t.low&&-1===t.high)return this;return r((this.unsigned?g.div_u:g.div_s)(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?p:m;var i,n,e;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return p;if(t.gt(this.shru(1)))return b;e=p}else{if(this.eq(_)){if(t.eq(y)||t.eq(N))return _;if(t.eq(_))return y;return i=this.shr(1).div(t).shl(1),i.eq(m)?t.isNegative()?y:N:(n=this.sub(t.mul(i)),e=i.add(n.div(t)))}if(t.eq(_))return this.unsigned?p:m;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();e=m}for(n=this;n.gte(t);){i=Math.max(1,Math.floor(n.toNumber()/t.toNumber()));for(var o=Math.ceil(Math.log(i)/Math.LN2),f=o<=48?1:a(2,o-48),l=s(i),d=l.mul(t);d.isNegative()||d.gt(n);)i-=f,l=s(i,this.unsigned),d=l.mul(t);l.isZero()&&(l=y),e=e.add(l),n=n.sub(d)}return e},B.div=B.divide,B.modulo=function(t){if(h(t)||(t=u(t)),g){return r((this.unsigned?g.rem_u:g.rem_s)(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))},B.mod=B.modulo,B.rem=B.modulo,B.not=function(){return r(~this.low,~this.high,this.unsigned)},B.and=function(t){return h(t)||(t=u(t)),r(this.low&t.low,this.high&t.high,this.unsigned)},B.or=function(t){return h(t)||(t=u(t)),r(this.low|t.low,this.high|t.high,this.unsigned)},B.xor=function(t){return h(t)||(t=u(t)),r(this.low^t.low,this.high^t.high,this.unsigned)},B.shiftLeft=function(t){return h(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?r(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned):r(0,this.low<<t-32,this.unsigned)},B.shl=B.shiftLeft,B.shiftRight=function(t){return h(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?r(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned):r(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},B.shr=B.shiftRight,B.shiftRightUnsigned=function(t){return h(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?r(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):32===t?r(this.high,0,this.unsigned):r(this.high>>>t-32,0,this.unsigned)},B.shru=B.shiftRightUnsigned,B.shr_u=B.shiftRightUnsigned,B.rotateLeft=function(t){var i;return h(t)&&(t=t.toInt()),0==(t&=63)?this:32===t?r(this.high,this.low,this.unsigned):t<32?(i=32-t,r(this.low<<t|this.high>>>i,this.high<<t|this.low>>>i,this.unsigned)):(t-=32,i=32-t,r(this.high<<t|this.low>>>i,this.low<<t|this.high>>>i,this.unsigned))},B.rotl=B.rotateLeft,B.rotateRight=function(t){var i;return h(t)&&(t=t.toInt()),0==(t&=63)?this:32===t?r(this.high,this.low,this.unsigned):t<32?(i=32-t,r(this.high<<i|this.low>>>t,this.low<<i|this.high>>>t,this.unsigned)):(t-=32,i=32-t,r(this.low<<i|this.high>>>t,this.high<<i|this.low>>>t,this.unsigned))},B.rotr=B.rotateRight,B.toSigned=function(){return this.unsigned?r(this.low,this.high,!1):this},B.toUnsigned=function(){return this.unsigned?this:r(this.low,this.high,!0)},B.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},B.toBytesLE=function(){var t=this.high,i=this.low;return[255&i,i>>>8&255,i>>>16&255,i>>>24,255&t,t>>>8&255,t>>>16&255,t>>>24]},B.toBytesBE=function(){var t=this.high,i=this.low;return[t>>>24,t>>>16&255,t>>>8&255,255&t,i>>>24,i>>>16&255,i>>>8&255,255&i]},n.fromBytes=function(t,i,h){return h?n.fromBytesLE(t,i):n.fromBytesBE(t,i)},n.fromBytesLE=function(t,i){return new n(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,i)},n.fromBytesBE=function(t,i){return new n(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],i)}}])});
` `
var jscode = `
//数据结构设计
//kvlist [{key:"key1", value:"value1"},{key:"key2", value:"value2"}]
//log 设计 {json data}
function Init(context) {
this.kvc = new kvcreator("init")
this.context = context
this.kvc.add("action", "init")
this.kvc.add("context", this.context)
return this.kvc.receipt()
}
function Exec(context) {
this.kvc = new kvcreator("exec")
this.context = context
}
function ExecLocal(context, logs) {
this.kvc = new kvcreator("local")
this.context = context
this.logs = logs
}
function Query(context) {
this.kvc = new kvcreator("query")
this.context = context
}
Exec.prototype.hello = function(args) {
this.kvc.add("args", args)
this.kvc.add("action", "exec")
this.kvc.add("context", this.context)
this.kvc.addlog({"key1": "value1"})
this.kvc.addlog({"key2": "value2"})
return this.kvc.receipt()
}
ExecLocal.prototype.hello = function(args) {
this.kvc.add("args", args)
this.kvc.add("action", "execlocal")
this.kvc.add("log", this.logs)
this.kvc.add("context", this.context)
return this.kvc.receipt()
}
//return a json string
Query.prototype.hello = function(args) {
var obj = getlocaldb("context")
return tojson(obj)
}
`
...@@ -8,7 +8,10 @@ import ( ...@@ -8,7 +8,10 @@ import (
) )
func (c *js) Exec_Create(payload *jsproto.Create, tx *types.Transaction, index int) (*types.Receipt, error) { func (c *js) Exec_Create(payload *jsproto.Create, tx *types.Transaction, index int) (*types.Receipt, error) {
execer := types.ExecName("user.js." + payload.Name) execer := types.ExecName("user." + ptypes.JsX + "." + payload.Name)
if string(tx.Execer) != execer {
return nil, types.ErrExecNameNotMatch
}
c.prefix = calcStatePrefix([]byte(execer)) c.prefix = calcStatePrefix([]byte(execer))
kvc := dapp.NewKVCreator(c.GetStateDB(), c.prefix, nil) kvc := dapp.NewKVCreator(c.GetStateDB(), c.prefix, nil)
_, err := kvc.GetNoPrefix(calcCodeKey(payload.Name)) _, err := kvc.GetNoPrefix(calcCodeKey(payload.Name))
...@@ -33,7 +36,10 @@ func (c *js) Exec_Create(payload *jsproto.Create, tx *types.Transaction, index i ...@@ -33,7 +36,10 @@ func (c *js) Exec_Create(payload *jsproto.Create, tx *types.Transaction, index i
} }
func (c *js) Exec_Call(payload *jsproto.Call, tx *types.Transaction, index int) (*types.Receipt, error) { func (c *js) Exec_Call(payload *jsproto.Call, tx *types.Transaction, index int) (*types.Receipt, error) {
execer := types.ExecName("user.js." + payload.Name) execer := types.ExecName("user." + ptypes.JsX + "." + payload.Name)
if string(tx.Execer) != execer {
return nil, types.ErrExecNameNotMatch
}
c.prefix = calcStatePrefix([]byte(execer)) c.prefix = calcStatePrefix([]byte(execer))
kvc := dapp.NewKVCreator(c.GetStateDB(), c.prefix, nil) kvc := dapp.NewKVCreator(c.GetStateDB(), c.prefix, nil)
jsvalue, err := c.callVM("exec", payload, tx, index, nil) jsvalue, err := c.callVM("exec", payload, tx, index, nil)
......
...@@ -3,6 +3,7 @@ package executor ...@@ -3,6 +3,7 @@ package executor
import ( import (
"github.com/33cn/chain33/system/dapp" "github.com/33cn/chain33/system/dapp"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
ptypes "github.com/33cn/plugin/plugin/dapp/js/types"
"github.com/33cn/plugin/plugin/dapp/js/types/jsproto" "github.com/33cn/plugin/plugin/dapp/js/types/jsproto"
) )
...@@ -12,7 +13,7 @@ func (c *js) ExecDelLocal_Create(payload *jsproto.Create, tx *types.Transaction, ...@@ -12,7 +13,7 @@ func (c *js) ExecDelLocal_Create(payload *jsproto.Create, tx *types.Transaction,
func (c *js) ExecDelLocal_Call(payload *jsproto.Call, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (c *js) ExecDelLocal_Call(payload *jsproto.Call, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
krollback := calcRollbackKey(tx.Hash()) krollback := calcRollbackKey(tx.Hash())
execer := types.ExecName("user.js." + payload.Name) execer := types.ExecName("user." + ptypes.JsX + "." + payload.Name)
c.prefix = calcLocalPrefix([]byte(execer)) c.prefix = calcLocalPrefix([]byte(execer))
kvc := dapp.NewKVCreator(c.GetLocalDB(), c.prefix, krollback) kvc := dapp.NewKVCreator(c.GetLocalDB(), c.prefix, krollback)
kvs, err := kvc.GetRollbackKVList() kvs, err := kvc.GetRollbackKVList()
......
...@@ -3,6 +3,7 @@ package executor ...@@ -3,6 +3,7 @@ package executor
import ( import (
"github.com/33cn/chain33/system/dapp" "github.com/33cn/chain33/system/dapp"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
ptypes "github.com/33cn/plugin/plugin/dapp/js/types"
"github.com/33cn/plugin/plugin/dapp/js/types/jsproto" "github.com/33cn/plugin/plugin/dapp/js/types/jsproto"
) )
...@@ -12,7 +13,7 @@ func (c *js) ExecLocal_Create(payload *jsproto.Create, tx *types.Transaction, re ...@@ -12,7 +13,7 @@ func (c *js) ExecLocal_Create(payload *jsproto.Create, tx *types.Transaction, re
func (c *js) ExecLocal_Call(payload *jsproto.Call, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (c *js) ExecLocal_Call(payload *jsproto.Call, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
k := calcRollbackKey(tx.Hash()) k := calcRollbackKey(tx.Hash())
execer := types.ExecName("user.js." + payload.Name) execer := types.ExecName("user." + ptypes.JsX + "." + payload.Name)
c.prefix = calcLocalPrefix([]byte(execer)) c.prefix = calcLocalPrefix([]byte(execer))
kvc := dapp.NewKVCreator(c.GetLocalDB(), c.prefix, k) kvc := dapp.NewKVCreator(c.GetLocalDB(), c.prefix, k)
jsvalue, err := c.callVM("execlocal", payload, tx, index, receiptData) jsvalue, err := c.callVM("execlocal", payload, tx, index, receiptData)
......
#!/bin/sh
echo "package executor\n\nvar callcode = \`" > const.go
cat runtime.js >> const.go
echo "\`" >> const.go
echo "var jscode = \`" >> const.go
cat test.js >> const.go
echo "\`" >> const.go
...@@ -106,6 +106,12 @@ func (u *js) callVM(prefix string, payload *jsproto.Call, tx *types.Transaction, ...@@ -106,6 +106,12 @@ func (u *js) callVM(prefix string, payload *jsproto.Call, tx *types.Transaction,
return jsvalue.Object(), nil return jsvalue.Object(), nil
} }
type jslogInfo struct {
Log string `json:"log"`
Ty int32 `json:"ty"`
Format string `json:"format"`
}
func jslogs(receiptData *types.ReceiptData) ([]string, error) { func jslogs(receiptData *types.ReceiptData) ([]string, error) {
data := make([]string, 0) data := make([]string, 0)
if receiptData == nil { if receiptData == nil {
...@@ -113,6 +119,7 @@ func jslogs(receiptData *types.ReceiptData) ([]string, error) { ...@@ -113,6 +119,7 @@ func jslogs(receiptData *types.ReceiptData) ([]string, error) {
} }
for i := 0; i < len(receiptData.Logs); i++ { for i := 0; i < len(receiptData.Logs); i++ {
logitem := receiptData.Logs[i] logitem := receiptData.Logs[i]
//只传递 json格式的日子,不传递 二进制的日志
if logitem.Ty != ptypes.TyLogJs { if logitem.Ty != ptypes.TyLogJs {
continue continue
} }
...@@ -121,7 +128,11 @@ func jslogs(receiptData *types.ReceiptData) ([]string, error) { ...@@ -121,7 +128,11 @@ func jslogs(receiptData *types.ReceiptData) ([]string, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
data = append(data, jslog.Data) item, err := json.Marshal(&jslogInfo{Log: jslog.Data, Ty: receiptData.Ty, Format: "json"})
if err != nil {
return nil, err
}
data = append(data, string(item))
} }
return data, nil return data, nil
} }
...@@ -143,14 +154,21 @@ func (u *js) getContext(tx *types.Transaction, index int64) *blockContext { ...@@ -143,14 +154,21 @@ func (u *js) getContext(tx *types.Transaction, index int64) *blockContext {
} }
} }
func (u *js) getstatedbFunc(vm *otto.Otto, name string) { func (u *js) statedbFunc(vm *otto.Otto, name string) {
prefix, _ := calcAllPrefix(name) prefix, _ := calcAllPrefix(name)
vm.Set("getstatedb", func(call otto.FunctionCall) otto.Value { vm.Set("getstatedb", func(call otto.FunctionCall) otto.Value {
key, err := call.Argument(0).ToString() key, err := call.Argument(0).ToString()
if err != nil { if err != nil {
return errReturn(vm, err) return errReturn(vm, err)
} }
v, err := u.getstatedb(string(prefix) + key) hasprefix, err := call.Argument(1).ToBoolean()
if err != nil {
return errReturn(vm, err)
}
if !hasprefix {
key = string(prefix) + key
}
v, err := u.getstatedb(key)
if err != nil { if err != nil {
return errReturn(vm, err) return errReturn(vm, err)
} }
...@@ -158,14 +176,21 @@ func (u *js) getstatedbFunc(vm *otto.Otto, name string) { ...@@ -158,14 +176,21 @@ func (u *js) getstatedbFunc(vm *otto.Otto, name string) {
}) })
} }
func (u *js) getlocaldbFunc(vm *otto.Otto, name string) { func (u *js) localdbFunc(vm *otto.Otto, name string) {
_, prefix := calcAllPrefix(name) _, prefix := calcAllPrefix(name)
vm.Set("getlocaldb", func(call otto.FunctionCall) otto.Value { vm.Set("getlocaldb", func(call otto.FunctionCall) otto.Value {
key, err := call.Argument(0).ToString() key, err := call.Argument(0).ToString()
if err != nil { if err != nil {
return errReturn(vm, err) return errReturn(vm, err)
} }
v, err := u.getlocaldb(string(prefix) + key) hasprefix, err := call.Argument(1).ToBoolean()
if err != nil {
return errReturn(vm, err)
}
if !hasprefix {
key = string(prefix) + key
}
v, err := u.getlocaldb(key)
if err != nil { if err != nil {
return errReturn(vm, err) return errReturn(vm, err)
} }
...@@ -227,8 +252,8 @@ func (u *js) createVM(name string, tx *types.Transaction, index int) (*otto.Otto ...@@ -227,8 +252,8 @@ func (u *js) createVM(name string, tx *types.Transaction, index int) (*otto.Otto
vm = cachevm.Copy() vm = cachevm.Copy()
} }
vm.Set("context", string(data)) vm.Set("context", string(data))
u.getstatedbFunc(vm, name) u.statedbFunc(vm, name)
u.getlocaldbFunc(vm, name) u.localdbFunc(vm, name)
u.listdbFunc(vm, name) u.listdbFunc(vm, name)
u.execnameFunc(vm, name) u.execnameFunc(vm, name)
u.registerAccountFunc(vm) u.registerAccountFunc(vm)
...@@ -295,6 +320,22 @@ func (o *object) value() otto.Value { ...@@ -295,6 +320,22 @@ func (o *object) value() otto.Value {
return v return v
} }
// Allow 允许哪些交易在本命执行器执行
func (u *js) Allow(tx *types.Transaction, index int) error {
err := u.DriverBase.Allow(tx, index)
if err == nil {
return nil
}
//增加新的规则:
//主链: user.jsvm.xxx 执行 jsvm 合约
//平行链: user.p.guodun.user.jsvm.xxx 执行 jsvm 合约
exec := types.GetParaExec(tx.Execer)
if u.AllowIsUserDot2(exec) {
return nil
}
return types.ErrNotAllow
}
func createKVObject(vm *otto.Otto, kvs []*types.KeyValue) otto.Value { func createKVObject(vm *otto.Otto, kvs []*types.KeyValue) otto.Value {
obj := newObjectString(vm, "([])") obj := newObjectString(vm, "([])")
for i := 0; i < len(kvs); i++ { for i := 0; i < len(kvs); i++ {
......
...@@ -61,13 +61,34 @@ func parseJsReturn(jsvalue *otto.Object) (kvlist []*types.KeyValue, logs []*type ...@@ -61,13 +61,34 @@ func parseJsReturn(jsvalue *otto.Object) (kvlist []*types.KeyValue, logs []*type
return nil, nil, err return nil, nil, err
} }
for i := 0; i < int(size); i++ { for i := 0; i < int(size); i++ {
data, err := getString(obj, fmt.Sprint(i)) data, err := getObject(obj, fmt.Sprint(i))
if err != nil {
return nil, nil, err
}
//
logdata, err := getString(data, "log")
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
format, err := getString(data, "format")
if err != nil {
return nil, nil, err
}
ty, err := getInt(data, "ty")
if err != nil {
return nil, nil, err
}
if format == "json" {
l := &types.ReceiptLog{ l := &types.ReceiptLog{
Ty: ptypes.TyLogJs, Log: types.Encode(&jsproto.JsLog{Data: data})} Ty: ptypes.TyLogJs, Log: types.Encode(&jsproto.JsLog{Data: logdata})}
logs = append(logs, l) logs = append(logs, l)
} else {
l := &types.ReceiptLog{
Ty: int32(ty),
Log: []byte(logdata),
}
logs = append(logs, l)
}
} }
return kvlist, logs, nil return kvlist, logs, nil
} }
......
...@@ -39,7 +39,7 @@ func createCodeTx(name, jscode string) (*jsproto.Create, *types.Transaction) { ...@@ -39,7 +39,7 @@ func createCodeTx(name, jscode string) (*jsproto.Create, *types.Transaction) {
Code: jscode, Code: jscode,
Name: name, Name: name,
} }
return data, &types.Transaction{Execer: []byte("js"), Payload: types.Encode(data)} return data, &types.Transaction{Execer: []byte("user." + ptypes.JsX + "." + name), Payload: types.Encode(data)}
} }
func callCodeTx(name, f, args string) (*jsproto.Call, *types.Transaction) { func callCodeTx(name, f, args string) (*jsproto.Call, *types.Transaction) {
...@@ -48,7 +48,7 @@ func callCodeTx(name, f, args string) (*jsproto.Call, *types.Transaction) { ...@@ -48,7 +48,7 @@ func callCodeTx(name, f, args string) (*jsproto.Call, *types.Transaction) {
Name: name, Name: name,
Args: args, Args: args,
} }
return data, &types.Transaction{Execer: []byte("js"), Payload: types.Encode(data)} return data, &types.Transaction{Execer: []byte("user." + ptypes.JsX + "." + name), Payload: types.Encode(data)}
} }
func TestCallcode(t *testing.T) { func TestCallcode(t *testing.T) {
...@@ -66,7 +66,7 @@ func TestCallcode(t *testing.T) { ...@@ -66,7 +66,7 @@ func TestCallcode(t *testing.T) {
err = json.Unmarshal(receipt.KV[2].Value, &data) err = json.Unmarshal(receipt.KV[2].Value, &data)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, uint64(1), data.Difficulty) assert.Equal(t, uint64(1), data.Difficulty)
assert.Equal(t, "js", data.DriverName) assert.Equal(t, ptypes.JsX, data.DriverName)
assert.Equal(t, int64(1), data.Height) assert.Equal(t, int64(1), data.Height)
assert.Equal(t, int64(0), data.Index) assert.Equal(t, int64(0), data.Index)
...@@ -76,12 +76,12 @@ func TestCallcode(t *testing.T) { ...@@ -76,12 +76,12 @@ func TestCallcode(t *testing.T) {
assert.Equal(t, string(kvset.KV[0].Value), `{"hello":"world"}`) assert.Equal(t, string(kvset.KV[0].Value), `{"hello":"world"}`)
assert.Equal(t, string(kvset.KV[1].Value), "execlocal") assert.Equal(t, string(kvset.KV[1].Value), "execlocal")
//test log is ok //test log is ok
assert.Equal(t, string(kvset.KV[2].Value), `[{"key1":"value1"},{"key2":"value2"}]`) assert.Equal(t, string(kvset.KV[2].Value), `[{"format":"json","log":"{\"key1\":\"value1\"}","ty":0},{"format":"json","log":"{\"key2\":\"value2\"}","ty":0}]`)
//test context //test context
err = json.Unmarshal(kvset.KV[3].Value, &data) err = json.Unmarshal(kvset.KV[3].Value, &data)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, uint64(1), data.Difficulty) assert.Equal(t, uint64(1), data.Difficulty)
assert.Equal(t, "js", data.DriverName) assert.Equal(t, "jsvm", data.DriverName)
assert.Equal(t, int64(1), data.Height) assert.Equal(t, int64(1), data.Height)
assert.Equal(t, int64(0), data.Index) assert.Equal(t, int64(0), data.Index)
...@@ -91,7 +91,7 @@ func TestCallcode(t *testing.T) { ...@@ -91,7 +91,7 @@ func TestCallcode(t *testing.T) {
err = json.Unmarshal([]byte(jsondata.(*jsproto.QueryResult).Data), &data) err = json.Unmarshal([]byte(jsondata.(*jsproto.QueryResult).Data), &data)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, uint64(1), data.Difficulty) assert.Equal(t, uint64(1), data.Difficulty)
assert.Equal(t, "js", data.DriverName) assert.Equal(t, "jsvm", data.DriverName)
assert.Equal(t, int64(1), data.Height) assert.Equal(t, int64(1), data.Height)
assert.Equal(t, int64(0), data.Index) assert.Equal(t, int64(0), data.Index)
//call rollback //call rollback
...@@ -100,7 +100,7 @@ func TestCallcode(t *testing.T) { ...@@ -100,7 +100,7 @@ func TestCallcode(t *testing.T) {
util.SaveKVList(ldb, kvset.KV) util.SaveKVList(ldb, kvset.KV)
assert.Equal(t, 5, len(kvset.KV)) assert.Equal(t, 5, len(kvset.KV))
for i := 0; i < len(kvset.KV); i++ { for i := 0; i < len(kvset.KV); i++ {
assert.Equal(t, kvset.KV[i].Value, []byte(nil)) assert.Equal(t, string(kvset.KV[i].Value), "")
} }
} }
...@@ -177,8 +177,8 @@ func TestRewriteJSON(t *testing.T) { ...@@ -177,8 +177,8 @@ func TestRewriteJSON(t *testing.T) {
func TestCalcLocalPrefix(t *testing.T) { func TestCalcLocalPrefix(t *testing.T) {
assert.Equal(t, calcLocalPrefix([]byte("a")), []byte("LODB-a-")) assert.Equal(t, calcLocalPrefix([]byte("a")), []byte("LODB-a-"))
assert.Equal(t, calcStatePrefix([]byte("a")), []byte("mavl-a-")) assert.Equal(t, calcStatePrefix([]byte("a")), []byte("mavl-a-"))
assert.Equal(t, calcCodeKey("a"), []byte("mavl-js-code-a")) assert.Equal(t, calcCodeKey("a"), []byte("mavl-jsvm-code-a"))
assert.Equal(t, calcRollbackKey([]byte("a")), []byte("LODB-js-rollback-a")) assert.Equal(t, calcRollbackKey([]byte("a")), []byte("LODB-jsvm-rollback-a"))
} }
func TestCacheMemUsage(t *testing.T) { func TestCacheMemUsage(t *testing.T) {
...@@ -206,55 +206,3 @@ func printMemUsage() { ...@@ -206,55 +206,3 @@ func printMemUsage() {
func bToMb(b uint64) uint64 { func bToMb(b uint64) uint64 {
return b / 1024 / 1024 return b / 1024 / 1024
} }
var jscode = `
//数据结构设计
//kvlist [{key:"key1", value:"value1"},{key:"key2", value:"value2"}]
//log 设计 {json data}
function Init(context) {
this.kvc = new kvcreator("init")
this.context = context
this.kvc.add("action", "init")
this.kvc.add("context", this.context)
return this.kvc.receipt()
}
function Exec(context) {
this.kvc = new kvcreator("exec")
this.context = context
}
function ExecLocal(context, logs) {
this.kvc = new kvcreator("local")
this.context = context
this.logs = logs
}
function Query(context) {
this.kvc = new kvcreator("query")
this.context = context
}
Exec.prototype.hello = function(args) {
this.kvc.add("args", args)
this.kvc.add("action", "exec")
this.kvc.add("context", this.context)
this.kvc.addlog({"key1": "value1"})
this.kvc.addlog({"key2": "value2"})
return this.kvc.receipt()
}
ExecLocal.prototype.hello = function(args) {
this.kvc.add("args", args)
this.kvc.add("action", "execlocal")
this.kvc.add("log", this.logs)
this.kvc.add("context", this.context)
return this.kvc.receipt()
}
//return a json string
Query.prototype.hello = function(args) {
var obj = getlocaldb("context")
return tojson(obj)
}
`
package executor package executor
import "github.com/33cn/chain33/types" import (
"github.com/33cn/chain33/types"
ptypes "github.com/33cn/plugin/plugin/dapp/js/types"
)
func calcLocalPrefix(execer []byte) []byte { func calcLocalPrefix(execer []byte) []byte {
s := append([]byte("LODB-"), execer...) s := append([]byte("LODB-"), execer...)
...@@ -15,16 +18,16 @@ func calcStatePrefix(execer []byte) []byte { ...@@ -15,16 +18,16 @@ func calcStatePrefix(execer []byte) []byte {
} }
func calcAllPrefix(name string) ([]byte, []byte) { func calcAllPrefix(name string) ([]byte, []byte) {
execer := types.ExecName("user.js." + name) execer := types.ExecName("user." + ptypes.JsX + "." + name)
state := calcStatePrefix([]byte(execer)) state := calcStatePrefix([]byte(execer))
local := calcLocalPrefix([]byte(execer)) local := calcLocalPrefix([]byte(execer))
return state, local return state, local
} }
func calcCodeKey(name string) []byte { func calcCodeKey(name string) []byte {
return append([]byte("mavl-js-code-"), []byte(name)...) return append([]byte("mavl-"+ptypes.JsX+"-code-"), []byte(name)...)
} }
func calcRollbackKey(hash []byte) []byte { func calcRollbackKey(hash []byte) []byte {
return append([]byte("LODB-js-rollback-"), hash...) return append([]byte("LODB-"+ptypes.JsX+"-rollback-"), hash...)
} }
var tojson = JSON.stringify
//table warp
function table(kvc, config, defaultvalue) {
var ret = table_new(config, defaultvalue)
if (ret.err) {
throw new Error(ret.err)
}
this.kvc = kvc
this.id = ret.id
this.config = config
this.defaultvalue = defaultvalue
}
function isstring(obj) {
return typeof obj === "string"
}
table.prototype.add = function(obj) {
if (!isstring(obj)) {
obj = tojson(obj)
}
var ret = table_add(this.id, obj)
return ret.err
}
table.prototype.replace = function(obj) {
if (!isstring(obj)) {
obj = tojson(obj)
}
var ret = table_replace(this.id, obj)
return ret.err
}
table.prototype.del = function(obj) {
if (!isstring(obj)) {
obj = tojson(obj)
}
var ret = table_del(this.id, obj)
return ret.err
}
table.prototype.save = function() {
var ret = table_save(this.id)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret
}
table.prototype.close = function() {
var ret = table_close(this.id)
return ret.err
}
//account warp
function account(kvc, execer, symbol) {
this.execer = execer
this.symbol = symbol
this.kvc = kvc
}
account.prototype.genesisInit = function(addr, amount) {
var ret = genesis_init(this, addr, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.execGenesisInit = function(execer, addr, amount) {
var ret = genesis_init_exec(this, execer, addr, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.getBalance = function(addr) {
return load_account(this, addr)
}
account.prototype.execGetBalance = function(execer, addr) {
return get_balance(this, execer, addr)
}
//本合约转移资产,或者转移到其他合约,或者从其他合约取回资产
account.prototype.transfer = function(from, to, amount) {
var ret = transfer(this, from, to, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.transferToExec = function(execer, from, amount) {
var ret = transfer_to_exec(this, execer, from, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.withdrawFromExec = function(execer, to, amount) {
var ret = withdraw(this, execer, to, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
//管理其他合约的资产转移到这个合约中
account.prototype.execActive = function(execer, addr, amount) {
var ret = exec_active(this, execer, addr, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.execFrozen = function(execer, addr, amount) {
var ret = exec_frozen(this, execer, addr, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.execDeposit = function(execer, addr, amount) {
var ret = exec_deposit(this, execer, addr, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.execWithdraw = function(execer, addr, amount) {
var ret = exec_withdraw(this, execer, addr, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
account.prototype.execTransfer = function(execer, from, to, amount) {
var ret = exec_transfer(this, execer, from, to, amount)
if (!this.kvc) {
this.kvc.save(ret)
}
return ret.err
}
function kvcreator(dbtype) {
this.data = {}
this.kvs = []
this.logs = []
this.type = dbtype
this.getstate = getstatedb
this.getloal = getlocaldb
this.list = listdb
if (dbtype == "exec" || dbtype == "init") {
this.get = this.getstatedb
} else if (dbtype == "local") {
this.get = this.getlocaldb
} else if (dbtype == "query") {
this.get = this.getlocaldb
} else {
throw new Error("chain33.js: dbtype error")
}
}
kvcreator.prototype.add = function(k, v, prefix) {
if (typeof v != "string") {
v = JSON.stringify(v)
}
this.data[k] = v
this.kvs.push({key:k, value: v, prefix: !!prefix})
}
kvcreator.prototype.get = function(k, prefix) {
var v
if (this.data[k]) {
v = this.data[k]
} else {
var dbvalue = this.get(k, !!prefix)
if (dbvalue.err != "") {
return null
}
v = dbvalue.value
}
if (!v) {
return null
}
return JSON.parse(v)
}
kvcreator.prototype.save = function(receipt) {
if (Array.isArray(receipt.logs)) {
for (var i = 0; i < receipt.logs.length; i++) {
var item = receipt.logs[i]
this.addlog(item.log, item.ty, item.format)
}
}
if (Array.isArray(receipt.kvs)) {
for (var i = 0; i < receipt.kvs.length; i++) {
var item = receipt.kvs[i]
this.add(item.key, item.value, item.prefix)
}
}
}
kvcreator.prototype.listvalue = function(prefix, key, count, direction) {
var dbvalues = this.list(prefix, key, count, direction)
if (dbvalues.err != "") {
return []
}
var values = dbvalues.value
if (!values || values.length == 0) {
return []
}
var objlist = []
for (var i = 0; i < values.length; i++) {
objlist.push(JSON.parse(values[i]))
}
return objlist
}
kvcreator.prototype.addlog = function(log, ty, format) {
if (this.type != "exec") {
throw new Error("local or query can't set log")
}
if (!isstring(log)) {
log = JSON.stringify(log)
}
if (!ty) {
ty = 0
}
if (!format) {
format = "json"
}
this.logs.push({log:log, ty: ty, format: format})
}
kvcreator.prototype.receipt = function() {
return {kvs: this.kvs, logs: this.logs}
}
function callcode(context, f, args, loglist) {
if (f == "init") {
return Init(JSON.parse(context))
}
var farr = f.split("_", 2)
if (farr.length != 2) {
throw new Error("chain33.js: invalid function name format")
}
var prefix = farr[0]
var funcname = farr[1]
var runobj = {}
var logs = []
if (!Array.isArray(loglist)) {
throw new Error("chain33.js: loglist must be array")
}
for (var i = 0; i < loglist.length; i++) {
logs.push(JSON.parse(loglist[i]))
}
if (prefix == "exec") {
runobj = new Exec(JSON.parse(context))
} else if (prefix == "execlocal") {
runobj = new ExecLocal(JSON.parse(context), logs)
} else if (prefix == "query") {
runobj = new Query(JSON.parse(context))
} else {
throw new Error("chain33.js: invalid function prefix format")
}
var arg = JSON.parse(args)
if (typeof runobj[funcname] != "function") {
throw new Error("chain33.js: invalid function name not found")
}
return runobj[funcname](arg)
}
//Long
!function(t,i){"object"==typeof exports&&"object"==typeof module?module.exports=i():"function"==typeof define&&define.amd?define([],i):"object"==typeof exports?exports.Long=i():t.Long=i()}("undefined"!=typeof self?self:this,function(){return function(t){function i(h){if(n[h])return n[h].exports;var e=n[h]={i:h,l:!1,exports:{}};return t[h].call(e.exports,e,e.exports,i),e.l=!0,e.exports}var n={};return i.m=t,i.c=n,i.d=function(t,n,h){i.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:h})},i.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(n,"a",n),n},i.o=function(t,i){return Object.prototype.hasOwnProperty.call(t,i)},i.p="",i(i.s=0)}([function(t,i){function n(t,i,n){this.low=0|t,this.high=0|i,this.unsigned=!!n}function h(t){return!0===(t&&t.__isLong__)}function e(t,i){var n,h,e;return i?(t>>>=0,(e=0<=t&&t<256)&&(h=l[t])?h:(n=r(t,(0|t)<0?-1:0,!0),e&&(l[t]=n),n)):(t|=0,(e=-128<=t&&t<128)&&(h=f[t])?h:(n=r(t,t<0?-1:0,!1),e&&(f[t]=n),n))}function s(t,i){if(isNaN(t))return i?p:m;if(i){if(t<0)return p;if(t>=c)return q}else{if(t<=-w)return _;if(t+1>=w)return E}return t<0?s(-t,i).neg():r(t%d|0,t/d|0,i)}function r(t,i,h){return new n(t,i,h)}function o(t,i,n){if(0===t.length)throw Error("empty string");if("NaN"===t||"Infinity"===t||"+Infinity"===t||"-Infinity"===t)return m;if("number"==typeof i?(n=i,i=!1):i=!!i,(n=n||10)<2||36<n)throw RangeError("radix");var h;if((h=t.indexOf("-"))>0)throw Error("interior hyphen");if(0===h)return o(t.substring(1),i,n).neg();for(var e=s(a(n,8)),r=m,u=0;u<t.length;u+=8){var g=Math.min(8,t.length-u),f=parseInt(t.substring(u,u+g),n);if(g<8){var l=s(a(n,g));r=r.mul(l).add(s(f))}else r=r.mul(e),r=r.add(s(f))}return r.unsigned=i,r}function u(t,i){return"number"==typeof t?s(t,i):"string"==typeof t?o(t,i):r(t.low,t.high,"boolean"==typeof i?i:t.unsigned)}t.exports=n;var g=null;try{g=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(t){}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=h;var f={},l={};n.fromInt=e,n.fromNumber=s,n.fromBits=r;var a=Math.pow;n.fromString=o,n.fromValue=u;var d=4294967296,c=d*d,w=c/2,v=e(1<<24),m=e(0);n.ZERO=m;var p=e(0,!0);n.UZERO=p;var y=e(1);n.ONE=y;var b=e(1,!0);n.UONE=b;var N=e(-1);n.NEG_ONE=N;var E=r(-1,2147483647,!1);n.MAX_VALUE=E;var q=r(-1,-1,!0);n.MAX_UNSIGNED_VALUE=q;var _=r(0,-2147483648,!1);n.MIN_VALUE=_;var B=n.prototype;B.toInt=function(){return this.unsigned?this.low>>>0:this.low},B.toNumber=function(){return this.unsigned?(this.high>>>0)*d+(this.low>>>0):this.high*d+(this.low>>>0)},B.toString=function(t){if((t=t||10)<2||36<t)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(_)){var i=s(t),n=this.div(i),h=n.mul(i).sub(this);return n.toString(t)+h.toInt().toString(t)}return"-"+this.neg().toString(t)}for(var e=s(a(t,6),this.unsigned),r=this,o="";;){var u=r.div(e),g=r.sub(u.mul(e)).toInt()>>>0,f=g.toString(t);if(r=u,r.isZero())return f+o;for(;f.length<6;)f="0"+f;o=""+f+o}},B.getHighBits=function(){return this.high},B.getHighBitsUnsigned=function(){return this.high>>>0},B.getLowBits=function(){return this.low},B.getLowBitsUnsigned=function(){return this.low>>>0},B.getNumBitsAbs=function(){if(this.isNegative())return this.eq(_)?64:this.neg().getNumBitsAbs();for(var t=0!=this.high?this.high:this.low,i=31;i>0&&0==(t&1<<i);i--);return 0!=this.high?i+33:i+1},B.isZero=function(){return 0===this.high&&0===this.low},B.eqz=B.isZero,B.isNegative=function(){return!this.unsigned&&this.high<0},B.isPositive=function(){return this.unsigned||this.high>=0},B.isOdd=function(){return 1==(1&this.low)},B.isEven=function(){return 0==(1&this.low)},B.equals=function(t){return h(t)||(t=u(t)),(this.unsigned===t.unsigned||this.high>>>31!=1||t.high>>>31!=1)&&(this.high===t.high&&this.low===t.low)},B.eq=B.equals,B.notEquals=function(t){return!this.eq(t)},B.neq=B.notEquals,B.ne=B.notEquals,B.lessThan=function(t){return this.comp(t)<0},B.lt=B.lessThan,B.lessThanOrEqual=function(t){return this.comp(t)<=0},B.lte=B.lessThanOrEqual,B.le=B.lessThanOrEqual,B.greaterThan=function(t){return this.comp(t)>0},B.gt=B.greaterThan,B.greaterThanOrEqual=function(t){return this.comp(t)>=0},B.gte=B.greaterThanOrEqual,B.ge=B.greaterThanOrEqual,B.compare=function(t){if(h(t)||(t=u(t)),this.eq(t))return 0;var i=this.isNegative(),n=t.isNegative();return i&&!n?-1:!i&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},B.comp=B.compare,B.negate=function(){return!this.unsigned&&this.eq(_)?_:this.not().add(y)},B.neg=B.negate,B.add=function(t){h(t)||(t=u(t));var i=this.high>>>16,n=65535&this.high,e=this.low>>>16,s=65535&this.low,o=t.high>>>16,g=65535&t.high,f=t.low>>>16,l=65535&t.low,a=0,d=0,c=0,w=0;return w+=s+l,c+=w>>>16,w&=65535,c+=e+f,d+=c>>>16,c&=65535,d+=n+g,a+=d>>>16,d&=65535,a+=i+o,a&=65535,r(c<<16|w,a<<16|d,this.unsigned)},B.subtract=function(t){return h(t)||(t=u(t)),this.add(t.neg())},B.sub=B.subtract,B.multiply=function(t){if(this.isZero())return m;if(h(t)||(t=u(t)),g){return r(g.mul(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}if(t.isZero())return m;if(this.eq(_))return t.isOdd()?_:m;if(t.eq(_))return this.isOdd()?_:m;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(v)&&t.lt(v))return s(this.toNumber()*t.toNumber(),this.unsigned);var i=this.high>>>16,n=65535&this.high,e=this.low>>>16,o=65535&this.low,f=t.high>>>16,l=65535&t.high,a=t.low>>>16,d=65535&t.low,c=0,w=0,p=0,y=0;return y+=o*d,p+=y>>>16,y&=65535,p+=e*d,w+=p>>>16,p&=65535,p+=o*a,w+=p>>>16,p&=65535,w+=n*d,c+=w>>>16,w&=65535,w+=e*a,c+=w>>>16,w&=65535,w+=o*l,c+=w>>>16,w&=65535,c+=i*d+n*a+e*l+o*f,c&=65535,r(p<<16|y,c<<16|w,this.unsigned)},B.mul=B.multiply,B.divide=function(t){if(h(t)||(t=u(t)),t.isZero())throw Error("division by zero");if(g){if(!this.unsigned&&-2147483648===this.high&&-1===t.low&&-1===t.high)return this;return r((this.unsigned?g.div_u:g.div_s)(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?p:m;var i,n,e;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return p;if(t.gt(this.shru(1)))return b;e=p}else{if(this.eq(_)){if(t.eq(y)||t.eq(N))return _;if(t.eq(_))return y;return i=this.shr(1).div(t).shl(1),i.eq(m)?t.isNegative()?y:N:(n=this.sub(t.mul(i)),e=i.add(n.div(t)))}if(t.eq(_))return this.unsigned?p:m;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();e=m}for(n=this;n.gte(t);){i=Math.max(1,Math.floor(n.toNumber()/t.toNumber()));for(var o=Math.ceil(Math.log(i)/Math.LN2),f=o<=48?1:a(2,o-48),l=s(i),d=l.mul(t);d.isNegative()||d.gt(n);)i-=f,l=s(i,this.unsigned),d=l.mul(t);l.isZero()&&(l=y),e=e.add(l),n=n.sub(d)}return e},B.div=B.divide,B.modulo=function(t){if(h(t)||(t=u(t)),g){return r((this.unsigned?g.rem_u:g.rem_s)(this.low,this.high,t.low,t.high),g.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))},B.mod=B.modulo,B.rem=B.modulo,B.not=function(){return r(~this.low,~this.high,this.unsigned)},B.and=function(t){return h(t)||(t=u(t)),r(this.low&t.low,this.high&t.high,this.unsigned)},B.or=function(t){return h(t)||(t=u(t)),r(this.low|t.low,this.high|t.high,this.unsigned)},B.xor=function(t){return h(t)||(t=u(t)),r(this.low^t.low,this.high^t.high,this.unsigned)},B.shiftLeft=function(t){return h(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?r(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned):r(0,this.low<<t-32,this.unsigned)},B.shl=B.shiftLeft,B.shiftRight=function(t){return h(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?r(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned):r(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},B.shr=B.shiftRight,B.shiftRightUnsigned=function(t){return h(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?r(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):32===t?r(this.high,0,this.unsigned):r(this.high>>>t-32,0,this.unsigned)},B.shru=B.shiftRightUnsigned,B.shr_u=B.shiftRightUnsigned,B.rotateLeft=function(t){var i;return h(t)&&(t=t.toInt()),0==(t&=63)?this:32===t?r(this.high,this.low,this.unsigned):t<32?(i=32-t,r(this.low<<t|this.high>>>i,this.high<<t|this.low>>>i,this.unsigned)):(t-=32,i=32-t,r(this.high<<t|this.low>>>i,this.low<<t|this.high>>>i,this.unsigned))},B.rotl=B.rotateLeft,B.rotateRight=function(t){var i;return h(t)&&(t=t.toInt()),0==(t&=63)?this:32===t?r(this.high,this.low,this.unsigned):t<32?(i=32-t,r(this.high<<i|this.low>>>t,this.low<<i|this.high>>>t,this.unsigned)):(t-=32,i=32-t,r(this.low<<i|this.high>>>t,this.high<<i|this.low>>>t,this.unsigned))},B.rotr=B.rotateRight,B.toSigned=function(){return this.unsigned?r(this.low,this.high,!1):this},B.toUnsigned=function(){return this.unsigned?this:r(this.low,this.high,!0)},B.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},B.toBytesLE=function(){var t=this.high,i=this.low;return[255&i,i>>>8&255,i>>>16&255,i>>>24,255&t,t>>>8&255,t>>>16&255,t>>>24]},B.toBytesBE=function(){var t=this.high,i=this.low;return[t>>>24,t>>>16&255,t>>>8&255,255&t,i>>>24,i>>>16&255,i>>>8&255,255&i]},n.fromBytes=function(t,i,h){return h?n.fromBytesLE(t,i):n.fromBytesBE(t,i)},n.fromBytesLE=function(t,i){return new n(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,i)},n.fromBytesBE=function(t,i){return new n(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],i)}}])});
...@@ -186,8 +186,7 @@ func tableDelFunc(vm *otto.Otto) { ...@@ -186,8 +186,7 @@ func tableDelFunc(vm *otto.Otto) {
if err != nil { if err != nil {
return errReturn(vm, err) return errReturn(vm, err)
} }
err = tab.DelRow(&jsproto.JsLog{Data: row})
err = tab.DelRow(&jsproto.JsLog{Data: json})
if err != nil { if err != nil {
return errReturn(vm, err) return errReturn(vm, err)
} }
......
//数据结构设计
//kvlist [{key:"key1", value:"value1"},{key:"key2", value:"value2"}]
//log 设计 {json data}
function Init(context) {
this.kvc = new kvcreator("init")
this.context = context
this.kvc.add("action", "init")
this.kvc.add("context", this.context)
return this.kvc.receipt()
}
function Exec(context) {
this.kvc = new kvcreator("exec")
this.context = context
}
function ExecLocal(context, logs) {
this.kvc = new kvcreator("local")
this.context = context
this.logs = logs
}
function Query(context) {
this.kvc = new kvcreator("query")
this.context = context
}
Exec.prototype.hello = function(args) {
this.kvc.add("args", args)
this.kvc.add("action", "exec")
this.kvc.add("context", this.context)
this.kvc.addlog({"key1": "value1"})
this.kvc.addlog({"key2": "value2"})
return this.kvc.receipt()
}
ExecLocal.prototype.hello = function(args) {
this.kvc.add("args", args)
this.kvc.add("action", "execlocal")
this.kvc.add("log", this.logs)
this.kvc.add("context", this.context)
return this.kvc.receipt()
}
//return a json string
Query.prototype.hello = function(args) {
var obj = getlocaldb("context")
return tojson(obj)
}
...@@ -30,7 +30,7 @@ var ( ...@@ -30,7 +30,7 @@ var (
) )
//JsX 插件名字 //JsX 插件名字
var JsX = "js" var JsX = "jsvm"
//错误常量 //错误常量
var ( var (
......
...@@ -9,31 +9,44 @@ import ( ...@@ -9,31 +9,44 @@ import (
"github.com/golang/protobuf/proto" "github.com/golang/protobuf/proto"
) )
func safeAdd(balance, amount int64) (int64, error) {
if balance+amount < amount || balance+amount > types.MaxTokenBalance {
return balance, types.ErrAmount
}
return balance + amount, nil
}
// GenesisInit 生成创世地址账户收据 // GenesisInit 生成创世地址账户收据
func (acc *DB) GenesisInit(addr string, amount int64) (*types.Receipt, error) { func (acc *DB) GenesisInit(addr string, amount int64) (receipt *types.Receipt, err error) {
accTo := acc.LoadAccount(addr) accTo := acc.LoadAccount(addr)
copyto := *accTo copyto := *accTo
accTo.Balance = accTo.GetBalance() + amount accTo.Balance, err = safeAdd(accTo.GetBalance(), amount)
if err != nil {
return nil, err
}
receiptBalanceTo := &types.ReceiptAccountTransfer{ receiptBalanceTo := &types.ReceiptAccountTransfer{
Prev: &copyto, Prev: &copyto,
Current: accTo, Current: accTo,
} }
acc.SaveAccount(accTo) acc.SaveAccount(accTo)
receipt := acc.genesisReceipt(accTo, receiptBalanceTo) receipt = acc.genesisReceipt(accTo, receiptBalanceTo)
return receipt, nil return receipt, nil
} }
// GenesisInitExec 生成创世地址执行器账户收据 // GenesisInitExec 生成创世地址执行器账户收据
func (acc *DB) GenesisInitExec(addr string, amount int64, execaddr string) (*types.Receipt, error) { func (acc *DB) GenesisInitExec(addr string, amount int64, execaddr string) (receipt *types.Receipt, err error) {
accTo := acc.LoadAccount(execaddr) accTo := acc.LoadAccount(execaddr)
copyto := *accTo copyto := *accTo
accTo.Balance = accTo.GetBalance() + amount accTo.Balance, err = safeAdd(accTo.GetBalance(), amount)
if err != nil {
return nil, err
}
receiptBalanceTo := &types.ReceiptAccountTransfer{ receiptBalanceTo := &types.ReceiptAccountTransfer{
Prev: &copyto, Prev: &copyto,
Current: accTo, Current: accTo,
} }
acc.SaveAccount(accTo) acc.SaveAccount(accTo)
receipt := acc.genesisReceipt(accTo, receiptBalanceTo) receipt = acc.genesisReceipt(accTo, receiptBalanceTo)
receipt2, err := acc.ExecDeposit(addr, execaddr, amount) receipt2, err := acc.ExecDeposit(addr, execaddr, amount)
if err != nil { if err != nil {
panic(err) panic(err)
......
...@@ -395,8 +395,9 @@ func (table *Table) Del(primaryKey []byte) error { ...@@ -395,8 +395,9 @@ func (table *Table) Del(primaryKey []byte) error {
return err return err
} }
if incache { if incache {
rowty := row.Ty
table.delRowCache(row) table.delRowCache(row)
if row.Ty == Add { if rowty == Add {
return nil return nil
} }
} }
...@@ -407,6 +408,15 @@ func (table *Table) Del(primaryKey []byte) error { ...@@ -407,6 +408,15 @@ func (table *Table) Del(primaryKey []byte) error {
return nil return nil
} }
//DelRow 删除一行
func (table *Table) DelRow(data types.Message) error {
primaryKey, err := table.primaryKey(data)
if err != nil {
return err
}
return table.Del(primaryKey)
}
//getDataKey data key 构造 //getDataKey data key 构造
func (table *Table) getDataKey(primaryKey []byte) []byte { func (table *Table) getDataKey(primaryKey []byte) []byte {
return append([]byte(table.dataprefix), primaryKey...) return append([]byte(table.dataprefix), primaryKey...)
......
...@@ -300,7 +300,7 @@ func TestDel(t *testing.T) { ...@@ -300,7 +300,7 @@ func TestDel(t *testing.T) {
//save 然后从列表中读取 //save 然后从列表中读取
kvs, err := table.Save() kvs, err := table.Save()
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, len(kvs), 6) assert.Equal(t, 3, len(kvs))
//save to database //save to database
util.SaveKVList(ldb, kvs) util.SaveKVList(ldb, kvs)
//printKV(kvs) //printKV(kvs)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment