Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add addresstobase58,base58toaddress API support #658

Merged
merged 7 commits into from Oct 12, 2018
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 3 additions & 2 deletions common/address.go
Expand Up @@ -89,7 +89,7 @@ func AddressFromHexString(s string) (Address, error) {
// AddressFromBase58 returns Address from encoded base58 string
func AddressFromBase58(encoded string) (Address, error) {
if encoded == "" {
return ADDRESS_EMPTY, fmt.Errorf("invalid address")
return ADDRESS_EMPTY, errors.New("invalid address")
}
decoded, err := base58.BitcoinEncoding.Decode([]byte(encoded))
if err != nil {
Expand All @@ -98,13 +98,14 @@ func AddressFromBase58(encoded string) (Address, error) {

x, ok := new(big.Int).SetString(string(decoded), 10)
if !ok {
return ADDRESS_EMPTY, fmt.Errorf("invalid address")
return ADDRESS_EMPTY, errors.New("invalid address")
}

buf := x.Bytes()
if len(buf) != 1+ADDR_LEN+4 || buf[0] != byte(23) {
return ADDRESS_EMPTY, errors.New("wrong encoded address")
}

ph, err := AddressParseFromBytes(buf[1:21])
if err != nil {
return ADDRESS_EMPTY, err
Expand Down
9 changes: 4 additions & 5 deletions core/genesis/genesis.go
Expand Up @@ -231,11 +231,10 @@ func newParamInit() *types.Transaction {
s = append(s, k)
}

neovm.GAS_TABLE.Range(func(key, value interface{}) bool {
INIT_PARAM[key.(string)] = strconv.FormatUint(value.(uint64), 10)
s = append(s, key.(string))
return true
})
for k, v := range neovm.INIT_GAS_TABLE {
INIT_PARAM[k] = strconv.FormatUint(v, 10)
s = append(s, k)
}

sort.Strings(s)
for _, v := range s {
Expand Down
13 changes: 9 additions & 4 deletions core/store/ledgerstore/ledger_store.go
Expand Up @@ -52,7 +52,6 @@ import (
"github.com/ontio/ontology/smartcontract/service/neovm"
sstate "github.com/ontio/ontology/smartcontract/states"
"github.com/ontio/ontology/smartcontract/storage"
"time"
)

const (
Expand Down Expand Up @@ -845,12 +844,18 @@ func (this *LedgerStoreImp) GetEventNotifyByBlock(height uint32) ([]*event.Execu

//PreExecuteContract return the result of smart contract execution without commit to store
func (this *LedgerStoreImp) PreExecuteContract(tx *types.Transaction) (*sstate.PreExecResult, error) {
height := this.GetCurrentBlockHeight()
stf := &sstate.PreExecResult{State: event.CONTRACT_STATE_FAIL, Gas: neovm.MIN_TRANSACTION_GAS, Result: nil}
header, err := this.GetHeaderByHeight(height)
if err != nil {
return stf, err
}

config := &smartcontract.Config{
Time: uint32(time.Now().Unix()),
Height: this.GetCurrentBlockHeight() + 1,
Tx: tx,
Time: header.Timestamp,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why revert this back?

Height: header.Height,
Tx: tx,
RandomHash: this.GetBlockHash(height),
}

cache := storage.NewCloneCache(this.stateStore.NewStateBatch())
Expand Down
14 changes: 8 additions & 6 deletions core/store/ledgerstore/tx_handler.go
Expand Up @@ -59,9 +59,10 @@ func (self *StateStore) HandleDeployTransaction(store store.LedgerStore, stateBa
if tx.GasPrice != 0 {
// init smart contract configuration info
config := &smartcontract.Config{
Time: block.Header.Timestamp,
Height: block.Header.Height,
Tx: tx,
Time: block.Header.Timestamp,
Height: block.Header.Height,
Tx: tx,
RandomHash: block.Hash(),
}
cache := storage.NewCloneCache(stateBatch)
createGasPrice, ok := neovm.GAS_TABLE.Load(neovm.CONTRACT_CREATE_NAME)
Expand Down Expand Up @@ -122,9 +123,10 @@ func (self *StateStore) HandleInvokeTransaction(store store.LedgerStore, stateBa

// init smart contract configuration info
config := &smartcontract.Config{
Time: block.Header.Timestamp,
Height: block.Header.Height,
Tx: tx,
Time: block.Header.Timestamp,
Height: block.Header.Height,
Tx: tx,
RandomHash: block.Hash(),
}

var (
Expand Down
1 change: 1 addition & 0 deletions smartcontract/service/native/native_service.go
Expand Up @@ -51,6 +51,7 @@ type NativeService struct {
Tx *types.Transaction
Height uint32
Time uint32
RandomHash common.Uint256
ContextRef context.ContextRef
}

Expand Down
44 changes: 37 additions & 7 deletions smartcontract/service/neovm/config.go
Expand Up @@ -36,6 +36,8 @@ var (
STORAGE_PUT_GAS uint64 = 4000
STORAGE_DELETE_GAS uint64 = 100
RUNTIME_CHECKWITNESS_GAS uint64 = 200
RUNTIME_ADDRESSTOBASE58_GAS uint64 = 40
RUNTIME_BASE58TOADDRESS_GAS uint64 = 30
APPCALL_GAS uint64 = 10
TAILCALL_GAS uint64 = 10
SHA1_GAS uint64 = 10
Expand Down Expand Up @@ -90,13 +92,16 @@ var (

STORAGECONTEXT_ASREADONLY_NAME = "System.StorageContext.AsReadOnly"

RUNTIME_GETTIME_NAME = "System.Runtime.GetTime"
RUNTIME_CHECKWITNESS_NAME = "System.Runtime.CheckWitness"
RUNTIME_NOTIFY_NAME = "System.Runtime.Notify"
RUNTIME_LOG_NAME = "System.Runtime.Log"
RUNTIME_GETTRIGGER_NAME = "System.Runtime.GetTrigger"
RUNTIME_SERIALIZE_NAME = "System.Runtime.Serialize"
RUNTIME_DESERIALIZE_NAME = "System.Runtime.Deserialize"
RUNTIME_GETTIME_NAME = "System.Runtime.GetTime"
RUNTIME_CHECKWITNESS_NAME = "System.Runtime.CheckWitness"
RUNTIME_NOTIFY_NAME = "System.Runtime.Notify"
RUNTIME_LOG_NAME = "System.Runtime.Log"
RUNTIME_GETTRIGGER_NAME = "System.Runtime.GetTrigger"
RUNTIME_SERIALIZE_NAME = "System.Runtime.Serialize"
RUNTIME_DESERIALIZE_NAME = "System.Runtime.Deserialize"
RUNTIME_BASE58TOADDRESS_NAME = "Ontology.Runtime.Base58ToAddress"
RUNTIME_ADDRESSTOBASE58_NAME = "Ontology.Runtime.AddressToBase58"
RUNTIME_GETRANDOMHASH_NAME = "Ontology.Runtime.GetRandomHash"

NATIVE_INVOKE_NAME = "Ontology.Native.Invoke"

Expand Down Expand Up @@ -137,6 +142,28 @@ var (
UINT_DEPLOY_CODE_LEN_NAME,
UINT_INVOKE_CODE_LEN_NAME,
}

INIT_GAS_TABLE = map[string]uint64{
BLOCKCHAIN_GETHEADER_NAME: BLOCKCHAIN_GETHEADER_GAS,
BLOCKCHAIN_GETBLOCK_NAME: BLOCKCHAIN_GETBLOCK_GAS,
BLOCKCHAIN_GETTRANSACTION_NAME: BLOCKCHAIN_GETTRANSACTION_GAS,
BLOCKCHAIN_GETCONTRACT_NAME: BLOCKCHAIN_GETCONTRACT_GAS,
CONTRACT_CREATE_NAME: CONTRACT_CREATE_GAS,
CONTRACT_MIGRATE_NAME: CONTRACT_MIGRATE_GAS,
STORAGE_GET_NAME: STORAGE_GET_GAS,
STORAGE_PUT_NAME: STORAGE_PUT_GAS,
STORAGE_DELETE_NAME: STORAGE_DELETE_GAS,
RUNTIME_CHECKWITNESS_NAME: RUNTIME_CHECKWITNESS_GAS,
NATIVE_INVOKE_NAME: NATIVE_INVOKE_GAS,
APPCALL_NAME: APPCALL_GAS,
TAILCALL_NAME: TAILCALL_GAS,
SHA1_NAME: SHA1_GAS,
SHA256_NAME: SHA256_GAS,
HASH160_NAME: HASH160_GAS,
HASH256_NAME: HASH256_GAS,
UINT_DEPLOY_CODE_LEN_NAME: UINT_DEPLOY_CODE_LEN_GAS,
UINT_INVOKE_CODE_LEN_NAME: UINT_INVOKE_CODE_LEN_GAS,
}
)

func initGAS_TABLE() *sync.Map {
Expand All @@ -161,5 +188,8 @@ func initGAS_TABLE() *sync.Map {
m.Store(UINT_DEPLOY_CODE_LEN_NAME, UINT_DEPLOY_CODE_LEN_GAS)
m.Store(UINT_INVOKE_CODE_LEN_NAME, UINT_INVOKE_CODE_LEN_GAS)

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

return &m
}
5 changes: 5 additions & 0 deletions smartcontract/service/neovm/neovm_service.go
Expand Up @@ -86,6 +86,10 @@ var (
GETEXECUTINGSCRIPTHASH_NAME: {Execute: GetExecutingAddress},
GETCALLINGSCRIPTHASH_NAME: {Execute: GetCallingAddress},
GETENTRYSCRIPTHASH_NAME: {Execute: GetEntryAddress},

RUNTIME_BASE58TOADDRESS_NAME: {Execute: RuntimeBase58ToAddress},
RUNTIME_ADDRESSTOBASE58_NAME: {Execute: RuntimeAddressToBase58},
RUNTIME_GETRANDOMHASH_NAME: {Execute: RuntimeGetRandomHash},
}
)

Expand Down Expand Up @@ -123,6 +127,7 @@ type NeoVmService struct {
Tx *types.Transaction
Time uint32
Height uint32
RandomHash scommon.Uint256
Engine *vm.ExecutionEngine
}

Expand Down
39 changes: 37 additions & 2 deletions smartcontract/service/neovm/runtime.go
Expand Up @@ -126,17 +126,52 @@ func RuntimeGetTrigger(service *NeoVmService, engine *vm.ExecutionEngine) error
return nil
}

func RuntimeBase58ToAddress(service *NeoVmService, engine *vm.ExecutionEngine) error {
if vm.EvaluationStackCount(engine) < 1 {
return errors.NewErr("[RuntimeBase58ToAddress] Too few input parameters")
}
item, err := vm.PopByteArray(engine)
if err != nil {
return err
}
address, err := common.AddressFromBase58(string(item))
if err != nil {
return err
}
vm.PushData(engine, address[:])
return nil
}

func RuntimeAddressToBase58(service *NeoVmService, engine *vm.ExecutionEngine) error {
if vm.EvaluationStackCount(engine) < 1 {
return errors.NewErr("[RuntimeAddressToBase58] Too few input parameters")
}
item, err := vm.PopByteArray(engine)
if err != nil {
return err
}
address, err := common.AddressParseFromBytes(item)
if err != nil {
return err
}
vm.PushData(engine, []byte(address.ToBase58()))
return nil
}

func RuntimeGetRandomHash(service *NeoVmService, engine *vm.ExecutionEngine) error {
vm.PushData(engine, service.RandomHash.ToArray())
return nil
}

func SerializeStackItem(item vmtypes.StackItems) ([]byte, error) {
if CircularRefAndDepthDetection(item) {
return nil, errors.NewErr("runtime serialize: can not serialize circular reference data")
}

bf := new(bytes.Buffer)
err := serializeStackItem(item, common.NewLimitedWriter(bf, uint64(vm.MAX_BYTEARRAY_SIZE)))
if err != nil {
return nil, err
}

return bf.Bytes(), nil
}

Expand Down
52 changes: 52 additions & 0 deletions smartcontract/service/neovm/runtime_test.go
Expand Up @@ -21,6 +21,9 @@ package neovm
import (
"testing"

"errors"
"github.com/ontio/ontology/account"
"github.com/ontio/ontology/vm/neovm"
"github.com/ontio/ontology/vm/neovm/types"
"github.com/stretchr/testify/assert"
)
Expand Down Expand Up @@ -104,3 +107,52 @@ func TestStructRef(t *testing.T) {

assert.False(t, CircularRefAndDepthDetection(map8))
}

func TestRuntimeBase58ToAddress(t *testing.T) {
vm := neovm.NewExecutionEngine()

acc := account.NewAccount("")
addr := acc.Address
base58 := acc.Address.ToBase58()

err := RuntimeBase58ToAddress(nil, vm)

if assert.Error(t, err) {
assert.Equal(t, errors.New("[RuntimeBase58ToAddress] Too few input parameters"), err)
}

vm.EvaluationStack.Push(types.NewByteArray([]byte(base58)))

err = RuntimeBase58ToAddress(nil, vm)

assert.NoError(t, err)

result, err := vm.EvaluationStack.Pop().GetByteArray()
assert.NoError(t, err)
assert.Equal(t, addr[:], result)
}

func TestRuntimeAddressToBase58(t *testing.T) {
vm := neovm.NewExecutionEngine()

acc := account.NewAccount("")
addr := acc.Address
base58 := acc.Address.ToBase58()

err := RuntimeAddressToBase58(nil, vm)

if assert.Error(t, err) {
assert.Equal(t, errors.New("[RuntimeAddressToBase58] Too few input parameters"), err)
}

vm.EvaluationStack.Push(types.NewByteArray(addr[:]))

err = RuntimeAddressToBase58(nil, vm)

assert.NoError(t, err)

result, err := vm.EvaluationStack.Pop().GetByteArray()

assert.NoError(t, err)
assert.Equal(t, base58, string(result))
}
9 changes: 6 additions & 3 deletions smartcontract/smart_contract.go
Expand Up @@ -49,9 +49,10 @@ type SmartContract struct {

// Config describe smart contract need parameters configuration
type Config struct {
Time uint32 // current block timestamp
Height uint32 // current block height
Tx *ctypes.Transaction // current transaction
Time uint32 // current block timestamp
Height uint32 // current block height
RandomHash common.Uint256 // current block hash
Tx *ctypes.Transaction // current transaction
}

// PushContext push current context to smart contract
Expand Down Expand Up @@ -132,6 +133,7 @@ func (this *SmartContract) NewExecuteEngine(code []byte) (context.Engine, error)
Tx: this.Config.Tx,
Time: this.Config.Time,
Height: this.Config.Height,
RandomHash: this.Config.RandomHash,
Engine: vm.NewExecutionEngine(),
}
return service, nil
Expand All @@ -147,6 +149,7 @@ func (this *SmartContract) NewNativeService() (*native.NativeService, error) {
Tx: this.Config.Tx,
Time: this.Config.Time,
Height: this.Config.Height,
RandomHash: this.Config.RandomHash,
ServiceMap: make(map[string]native.Handler),
}
return service, nil
Expand Down