Skip to content

Commit

Permalink
add get gas info chain api
Browse files Browse the repository at this point in the history
  • Loading branch information
laizy committed Jan 7, 2021
1 parent b5ad5f3 commit 0644958
Show file tree
Hide file tree
Showing 14 changed files with 59 additions and 5 deletions.
1 change: 1 addition & 0 deletions smartcontract/context/context.go
Expand Up @@ -40,6 +40,7 @@ type ContextRef interface {
PushNotifications(notifications []*event.NotifyEventInfo)
NewExecuteEngine(code []byte, txtype types.TransactionType) (Engine, error)
CheckUseGas(gas uint64) bool
GetGasInfo() (gasLeft uint64, gasPrice uint64)
CheckExecStep() bool
GetCallerAddress() []common.Address
SetInternalErr()
Expand Down
3 changes: 3 additions & 0 deletions smartcontract/service/neovm/config.go
Expand Up @@ -41,6 +41,7 @@ var (
STORAGE_DELETE_GAS uint64 = 100
RUNTIME_CHECKWITNESS_GAS uint64 = 200
RUNTIME_VERIFYMUTISIG_GAS uint64 = 400
RUNTIME_GETGASINFO_GAS uint64 = 10
RUNTIME_ADDRESSTOBASE58_GAS uint64 = 40
RUNTIME_BASE58TOADDRESS_GAS uint64 = 30
APPCALL_GAS uint64 = 10
Expand Down Expand Up @@ -108,6 +109,7 @@ var (
RUNTIME_ADDRESSTOBASE58_NAME = "Ontology.Runtime.AddressToBase58"
RUNTIME_GETCURRENTBLOCKHASH_NAME = "Ontology.Runtime.GetCurrentBlockHash"
RUNTIME_VERIFYMUTISIG_NAME = "Ontology.Runtime.VerifyMutiSig"
RUNTIME_GETGASINFO = "Ontology.Runtime.GetGasInfo"

NATIVE_INVOKE_NAME = "Ontology.Native.Invoke"
WASM_INVOKE_NAME = "Ontology.Wasm.InvokeWasm"
Expand Down Expand Up @@ -199,6 +201,7 @@ func initGAS_TABLE() *sync.Map {

m.Store(RUNTIME_BASE58TOADDRESS_NAME, RUNTIME_BASE58TOADDRESS_GAS)
m.Store(RUNTIME_ADDRESSTOBASE58_NAME, RUNTIME_ADDRESSTOBASE58_GAS)
m.Store(RUNTIME_GETGASINFO, RUNTIME_GETGASINFO_GAS)

m.Store(RUNTIME_VERIFYMUTISIG_NAME, RUNTIME_VERIFYMUTISIG_GAS)
m.Store(WASM_INVOKE_NAME, APPCALL_GAS)
Expand Down
1 change: 1 addition & 0 deletions smartcontract/service/neovm/neovm_service.go
Expand Up @@ -106,6 +106,7 @@ var (
RUNTIME_BASE58TOADDRESS_NAME: RuntimeBase58ToAddress,
RUNTIME_ADDRESSTOBASE58_NAME: RuntimeAddressToBase58,
RUNTIME_GETCURRENTBLOCKHASH_NAME: RuntimeGetCurrentBlockHash,
RUNTIME_GETGASINFO: RuntimeGetGasInfo,
}
)

Expand Down
10 changes: 10 additions & 0 deletions smartcontract/service/neovm/runtime.go
Expand Up @@ -187,6 +187,16 @@ func RuntimeBase58ToAddress(service *NeoVmService, engine *vm.Executor) error {
return engine.EvalStack.PushBytes(address[:])
}

func RuntimeGetGasInfo(service *NeoVmService, engine *vm.Executor) error {
left, price := service.ContextRef.GetGasInfo()
err := engine.EvalStack.PushUint64(left)
if err != nil {
return err
}

return engine.EvalStack.PushUint64(price)
}

func RuntimeAddressToBase58(service *NeoVmService, engine *vm.Executor) error {
item, err := engine.EvalStack.PopAsBytes()
if err != nil {
Expand Down
1 change: 1 addition & 0 deletions smartcontract/service/wasmvm/config.go
Expand Up @@ -21,6 +21,7 @@ var (
TIMESTAMP_GAS uint64 = 1
BLOCK_HEGHT_GAS uint64 = 1
SELF_ADDRESS_GAS uint64 = 1
GET_GAS_INFO_GAS uint64 = 1
CALLER_ADDRESS_GAS uint64 = 1
ENTRY_ADDRESS_GAS uint64 = 1
CHECKWITNESS_GAS uint64 = 200
Expand Down
Binary file modified smartcontract/service/wasmvm/libwasmjit_onto_interface.a
Binary file not shown.
Binary file modified smartcontract/service/wasmvm/libwasmjit_onto_interface_darwin.a
Binary file not shown.
22 changes: 22 additions & 0 deletions smartcontract/service/wasmvm/runtime.go
Expand Up @@ -78,6 +78,18 @@ func SelfAddress(proc *exec.Process, dst uint32) {
}
}

func GetGasInfo(proc *exec.Process, dst uint32) {
self := proc.HostData().(*Runtime)
self.checkGas(GET_GAS_INFO_GAS)
sink := common.NewZeroCopySink(nil)
sink.WriteUint64(*self.Service.vm.ExecMetrics.GasLimit)
sink.WriteUint64(self.Service.GasPrice)
_, err := proc.WriteAt(sink.Bytes(), int64(dst))
if err != nil {
panic(err)
}
}

func Sha256(proc *exec.Process, src uint32, slen uint32, dst uint32) {
self := proc.HostData().(*Runtime)
cost := uint64((slen/1024)+1) * SHA256_GAS
Expand Down Expand Up @@ -463,6 +475,11 @@ func NewHostModule() *wasm.Module {
Host: reflect.ValueOf(Sha256),
Body: &wasm.FunctionBody{}, // create a dummy wasm body (the actual value will be taken from Host.)
},
{ //24
Sig: &m.Types.Entries[2],
Host: reflect.ValueOf(GetGasInfo),
Body: &wasm.FunctionBody{}, // create a dummy wasm body (the actual value will be taken from Host.)
},
}

m.Export = &wasm.SectionExports{
Expand Down Expand Up @@ -587,6 +604,11 @@ func NewHostModule() *wasm.Module {
Kind: wasm.ExternalFunction,
Index: 23,
},
"ontio_gas_info": {
FieldStr: "ontio_gas_info",
Kind: wasm.ExternalFunction,
Index: 24,
},
},
}

Expand Down
1 change: 1 addition & 0 deletions smartcontract/service/wasmvm/wasmjit.h
Expand Up @@ -56,6 +56,7 @@ wasmjit_chain_context_t *wasmjit_chain_context_create(uint32_t height,
wasmjit_slice_t callers_raw,
wasmjit_slice_t witness_raw,
wasmjit_slice_t input_raw,
uint64_t gas_price,
uint64_t exec_step,
uint64_t gas_factor,
uint64_t gas_left,
Expand Down
5 changes: 3 additions & 2 deletions smartcontract/service/wasmvm/wasmjit_runtime.go
Expand Up @@ -256,7 +256,7 @@ func ontio_call_contract_cgo(vmctx *C.wasmjit_vmctx_t, contractAddr *C.address_t
*service.ExecStep = uint64(exec_step)
*service.GasLimit = uint64(gas_left)

buff := jitSliceToBytes(C.wasmjit_slice_t{data: ((*C.uint8_t)((unsafe.Pointer)(contractAddr))), len: 20})
buff := jitSliceToBytes(C.wasmjit_slice_t{data: (*C.uint8_t)((unsafe.Pointer)(contractAddr)), len: 20})

copy(contractAddress[:], buff[:])

Expand Down Expand Up @@ -324,13 +324,14 @@ func invokeJit(this *WasmVmService, contract *states.WasmContractParam, wasmCode
witness_raw := C.wasmjit_slice_t{data: witnessPtr, len: C.uint32_t(witness_len)}
input_raw := C.wasmjit_slice_t{data: inputPtr, len: C.uint32_t(input_len)}
service_index := C.uint64_t(this.ServiceIndex)
gas_price := C.uint64_t(this.GasPrice)
exec_step := C.uint64_t(*this.ExecStep)
gas_factor := C.uint64_t(this.GasFactor)
gas_left := C.uint64_t(*this.GasLimit)
depth_left := C.uint64_t(WASM_CALLSTACK_LIMIT)
codeSlice := C.wasmjit_slice_t{data: (*C.uint8_t)((unsafe.Pointer)(&wasmCode[0])), len: C.uint32_t(len(wasmCode))}

ctx := C.wasmjit_chain_context_create(height, block_hash, timestamp, tx_hash, caller_raw, witness_raw, input_raw, exec_step, gas_factor, gas_left, depth_left, service_index)
ctx := C.wasmjit_chain_context_create(height, block_hash, timestamp, tx_hash, caller_raw, witness_raw, input_raw, gas_price, exec_step, gas_factor, gas_left, depth_left, service_index)
jit_ret := C.wasmjit_invoke(codeSlice, ctx)
*this.ExecStep = uint64(jit_ret.exec_step)
*this.GasLimit = uint64(jit_ret.gas_left)
Expand Down
6 changes: 6 additions & 0 deletions smartcontract/smart_contract.go
Expand Up @@ -112,6 +112,12 @@ func (this *SmartContract) CheckExecStep() bool {
return true
}

func (this *SmartContract) GetGasInfo() (gasLeft uint64, gasPrice uint64) {
gasLeft = this.Gas
gasPrice = this.Config.Tx.GasPrice
return
}

func (this *SmartContract) CheckUseGas(gas uint64) bool {
if this.Gas < gas {
return false
Expand Down
2 changes: 1 addition & 1 deletion wasmtest/contracts-rust/helloworld/Cargo.toml
Expand Up @@ -12,7 +12,7 @@ path = "src/lib.rs"

[dependencies.ontio-std]
git="https://github.com/ontio/ontology-wasm-cdt-rust"
rev="d78390613ce1c1fd3b34d9e00b47b83a65cfcdf4"
#rev="d78390613ce1c1fd3b34d9e00b47b83a65cfcdf4"

[features]
mock = ["ontio-std/mock"]
10 changes: 9 additions & 1 deletion wasmtest/contracts-rust/helloworld/src/lib.rs
Expand Up @@ -25,6 +25,14 @@ pub fn invoke() {
b"block_height" => sink.write(runtime::block_height()),
b"self_address" => sink.write(runtime::address()),
b"caller_address" => sink.write(runtime::caller()),
b"gas_info" => {
let (left1, price) = runtime::gas_info();
let (left2, _) = runtime::gas_info();
assert_eq!(price, 0);
assert!(left1 > left2);
assert!(left1 < left2 + 100);
sink.write(true)
},
b"entry_address" => sink.write(runtime::entry_address()),
b"check_witness" => {
let addr: Address = source.read().unwrap();
Expand Down Expand Up @@ -65,7 +73,7 @@ fn testcase() -> String {
[
[{"env":{"witness":[]}, "method":"add", "param":"int:1, int:2", "expected":"int:3"},
{"method":"timestamp"}, {"method":"block_height"}, {"method":"self_address"},
{"method":"caller_address"}, {"method":"entry_address"},
{"method":"caller_address"}, {"method":"entry_address"}, {"method":"gas_info"},
{"method":"current_txhash"}, {"method":"current_blockhash"},
{"method":"storage_write", "param":"string:abc, string:123"},
{"method":"storage_read", "param":"string:abc", "expected":"string:123"},
Expand Down
2 changes: 1 addition & 1 deletion wasmtest/contracts-rust/travis.build.sh
Expand Up @@ -5,7 +5,7 @@ set -x
rm -rf js-vm && git clone --depth=1 https://github.com/laizy/ontio-js-vm js-vm
cd js-vm
RUSTFLAGS="-C link-arg=-zstack-size=32768" cargo build --lib --release --target=wasm32-unknown-unknown
cd ..
cd .. && rm -rf js-vm
mv ./target/wasm32-unknown-unknown/release/boa.wasm ../testwasmdata/jsvm.wasm

for dir in $(ls)
Expand Down

0 comments on commit 0644958

Please sign in to comment.