Commit 8b3cd529 authored by harrylee's avatar harrylee

add test cases

parent bd668bac
...@@ -11,13 +11,13 @@ import ( ...@@ -11,13 +11,13 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"github.com/golang/protobuf/proto"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/golang/protobuf/proto"
sdk "gitlab.33.cn/link33/chain33-sdk-go" sdk "gitlab.33.cn/link33/chain33-sdk-go"
"gitlab.33.cn/link33/chain33-sdk-go/crypto" "gitlab.33.cn/link33/chain33-sdk-go/crypto"
"gitlab.33.cn/link33/chain33-sdk-go/dapp/broker" "gitlab.33.cn/link33/chain33-sdk-go/dapp/broker"
...@@ -301,15 +301,26 @@ func (client *JSONClient) QueryBlockInfo(start, end int64, isDetail bool) (*Bloc ...@@ -301,15 +301,26 @@ func (client *JSONClient) QueryBlockInfo(start, end int64, isDetail bool) (*Bloc
return &res, nil return &res, nil
} }
// 发布跨链事件 // k V明文存证
func (client *JSONClient) EmitDataSwapInterchainEvent(dstServiceID, args, argscb, argsrb string, privateKey string) (*Response, error) { func (client *JSONClient) KVStore(key, value, privateKey string) (*Response, error) {
// FIXME 这里需完善 funcName="interchainGet,interchainSet," txType=0 表示是存在类数据交换 tx, err := storage.CreateContentStorageTx("", storage.OpCreate, key, nil, value)
tx, err := broker.EmitInterchainEvent("", dstServiceID, "interchainGet,interchainSet,", args, argsrb, argsrb, 0)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return client.SendTransactionSync(privateKey, tx) return client.SendTransactionSync(privateKey, tx)
} }
// 初始化broker
func (client *JSONClient) InitBroker(bxhId, appChainId, privateKey string) (*Response, error) {
tx := broker.InitBroker(bxhId, appChainId)
return client.SendTransactionSync(privateKey, tx)
}
// 发布跨链事件
func (client *JSONClient) EmitDataSwapInterchainEvent(dstServiceID, args, argscb, argsrb string, privateKey string) (*Response, error) {
// FIXME 这里需完善 funcName="interchainGet,interchainSet," txType=0 表示是存在类数据交换
tx := broker.EmitInterchainEvent("", dstServiceID, "interchainGet,interchainSet,", args, argsrb, argsrb, 0)
return client.SendTransactionSync(privateKey, tx)
}
// TODO 执行请求 // TODO 执行请求
func (client *JSONClient) Execute(requst *Request, privateKey string) (*Response, error) { func (client *JSONClient) Execute(requst *Request, privateKey string) (*Response, error) {
...@@ -327,45 +338,62 @@ func (client *JSONClient) Execute(requst *Request, privateKey string) (*Response ...@@ -327,45 +338,62 @@ func (client *JSONClient) Execute(requst *Request, privateKey string) (*Response
return nil, fmt.Errorf("cannot parse %s to uint64", string(requst.Args[3])) return nil, fmt.Errorf("cannot parse %s to uint64", string(requst.Args[3]))
} }
if tx, err := broker.UpdateIndex("", srcChainServiceID, targetCID, sequenceNum, reqType, nil); err == nil { // reqType==0 表示跨入交易, reqType==1 表示跨出交易,响应更新
if reqType != 0 {
tx := broker.UpdateIndex("", srcChainServiceID, targetCID, sequenceNum, reqType, 0)
resp, err := client.SendTransactionSync(privateKey, tx) resp, err := client.SendTransactionSync(privateKey, tx)
if err != nil { if err != nil {
return resp, err return resp, err
} }
//splitedCID[1]就是合约名称 }
splitedCID := strings.Split(targetCID, "&")
if len(splitedCID) != 2 {
return nil, fmt.Errorf("Target chaincode id %s is not valid", targetCID)
}
callFunc := &CallFunc{} //splitedCID[1]就是合约名称
if err := json.Unmarshal(requst.Args[4], callFunc); err != nil { splitedCID := strings.Split(targetCID, "&")
return nil, fmt.Errorf("unmarshal call func failed for %s", requst.Args[4]) if len(splitedCID) != 2 {
} return nil, fmt.Errorf("Target chaincode id %s is not valid", targetCID)
// 调用相应链码, (链码名称,参数,通道名称) }
if splitedCID[1] == storage.StorageX {
//interchainGet方法是在sdk封装的,用于支持跨链之前数据的查询 callFunc := &CallFunc{}
switch callFunc.Func { if err := json.Unmarshal(requst.Args[4], callFunc); err != nil {
case "interchainGet": return nil, fmt.Errorf("unmarshal call func failed for %s", requst.Args[4])
response, err := client.InterChainGet(string(callFunc.Args[0])) }
// 调用相应链码, (链码名称,参数,通道名称)
if splitedCID[1] == storage.StorageX {
//interchainGet方法是在sdk封装的,用于支持跨链之前数据的查询
switch callFunc.Func {
case "interchainGet":
response, err := client.InterChainGet(string(callFunc.Args[0]))
if err != nil {
return response, err
}
//携带TXhash
//response.Message = resp.Message
return response, err
case "interchainSet":
//跨链set kv
status := 1
response, err := client.InterChainSet(string(callFunc.Args[0]), string(callFunc.Args[1]), privateKey)
if err != nil {
status = 0
}
//TODO 这里的处理不是事务机制
if reqType != 0 {
tx := broker.UpdateIndex("", srcChainServiceID, targetCID, sequenceNum, reqType, int32(status))
resp, err := client.SendTransactionSync(privateKey, tx)
if err != nil { if err != nil {
return resp, err return resp, err
} }
//携带TXhash
response.Message = resp.Message
return response, err
case "interchainSet":
//跨链set kv
return client.InterChainSet(string(callFunc.Args[0]), string(callFunc.Args[1]), privateKey)
} }
} else { return response,nil
return nil, fmt.Errorf("can't support exec %s", splitedCID[1])
} }
} else {
return nil, fmt.Errorf("can't support exec %s", splitedCID[1])
} }
} }
} }
return nil, fmt.Errorf("not matching execution or method!") return nil, fmt.Errorf("not matching execution or method!")
} }
...@@ -489,12 +517,17 @@ func (client *JSONClient) QueryInnerMeta() (*types.Meta, error) { ...@@ -489,12 +517,17 @@ func (client *JSONClient) QueryInnerMeta() (*types.Meta, error) {
FuncName: broker.FuncNameQueryInnerMeta, FuncName: broker.FuncNameQueryInnerMeta,
Payload: jsonraw, Payload: jsonraw,
} }
var meta types.Meta //var meta types.Meta
err = client.Call("Chain33.Query", query, &meta) //err = client.Call("Chain33.Query", query, &meta)
//if err != nil {
// return nil, err
//}
//return &meta, nil
data,err:=client.CallBack("Chain33.Query", query,ParseMeta)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &meta, nil return data.(*types.Meta),nil
} }
func (client *JSONClient) QueryOutterMeta() (*types.Meta, error) { func (client *JSONClient) QueryOutterMeta() (*types.Meta, error) {
...@@ -507,12 +540,17 @@ func (client *JSONClient) QueryOutterMeta() (*types.Meta, error) { ...@@ -507,12 +540,17 @@ func (client *JSONClient) QueryOutterMeta() (*types.Meta, error) {
FuncName: broker.FuncNameQueryOutterMeta, FuncName: broker.FuncNameQueryOutterMeta,
Payload: jsonraw, Payload: jsonraw,
} }
var meta types.Meta //var meta types.Meta
err = client.Call("Chain33.Query", query, &meta) //err = client.Call("Chain33.Query", query, &meta)
//if err != nil {
// return nil, err
//}
//return &meta, nil
data,err:=client.CallBack("Chain33.Query", query,ParseMeta)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &meta, nil return data.(*types.Meta),nil
} }
func (client *JSONClient) QueryCallBackMeta() (*types.Meta, error) { func (client *JSONClient) QueryCallBackMeta() (*types.Meta, error) {
...@@ -533,7 +571,7 @@ func (client *JSONClient) QueryCallBackMeta() (*types.Meta, error) { ...@@ -533,7 +571,7 @@ func (client *JSONClient) QueryCallBackMeta() (*types.Meta, error) {
return &meta, nil return &meta, nil
} }
func (client *JSONClient) QueryOutMessage(inServicePair string, index uint64) (*types.Response, error) { func (client *JSONClient) QueryOutMessage(inServicePair string, index uint64) (*types.InterchainEvent, error) {
jsonraw, err := json.Marshal(&types.QueryOutMessage{InServicePair: inServicePair, SequenceNum: index}) jsonraw, err := json.Marshal(&types.QueryOutMessage{InServicePair: inServicePair, SequenceNum: index})
if err != nil { if err != nil {
return nil, err return nil, err
...@@ -543,12 +581,17 @@ func (client *JSONClient) QueryOutMessage(inServicePair string, index uint64) (* ...@@ -543,12 +581,17 @@ func (client *JSONClient) QueryOutMessage(inServicePair string, index uint64) (*
FuncName: broker.FuncNameQueryOutMessage, FuncName: broker.FuncNameQueryOutMessage,
Payload: jsonraw, Payload: jsonraw,
} }
var resp types.Response //var event types.InterchainEvent
err = client.Call("Chain33.Query", query, &resp) //err = client.Call("Chain33.Query", query, &event)
//if err != nil {
// return nil, err
//}
//return &event, nil
data,err:=client.CallBack("Chain33.Query", query, ParseInterChainEvent)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &resp, nil return data.(*types.InterchainEvent),nil
} }
func (client *JSONClient) QueryInMessage(inServicePair string, index uint64) (*types.Response, error) { func (client *JSONClient) QueryInMessage(inServicePair string, index uint64) (*types.Response, error) {
......
package client
import (
"gitlab.33.cn/link33/chain33-sdk-go/dapp/broker"
//"gitlab.33.cn/link33/chain33-sdk-go/dapp/broker"
"testing"
"time"
)
var (
GenesisPriv = "cc38546e9e659d15e6b4893f0ab32a06d103931a8230b0bde71459d2b27d6944"
)
func Test_InitBroker(t *testing.T){
client, err := NewJSONClient("", "http://localhost:8901")
if err != nil {
t.Error(err)
}
resp, err :=client.InitBroker("bxhv1","chain33",GenesisPriv)
if err != nil {
t.Error(err)
}
t.Log(resp.Message)
}
func Test_EmitDataSwapInterchainEvent(t *testing.T) {
client, err := NewJSONClient("", "http://localhost:8901")
if err != nil {
t.Error(err)
}
// 第一次存储
resp, err := client.KVStore("test", "hello", GenesisPriv)
if err != nil {
t.Error(err)
}
time.Sleep(time.Second)
resp, err = client.EmitDataSwapInterchainEvent("fabric&broker", "test", "test", "", GenesisPriv)
if err != nil {
t.Error(err)
}
t.Log(resp.Data)
}
func Test_InterChainGet(t *testing.T){
client, err := NewJSONClient("", "http://localhost:8901")
if err != nil {
t.Error(err)
}
resp,err:=client.InterChainGet("test")
if err != nil {
t.Error(err)
}
t.Log(string(resp.Data))
}
func Test_QueryBrokerInfo(t *testing.T){
client, err := NewJSONClient("", "http://localhost:8901")
if err != nil {
t.Error(err)
}
info,err:=client.QueryBrokerInfo()
if err != nil {
t.Error(err)
}
t.Logf("appid:%s,version:%s",info.GetAppChainId(),info.GetBxhId())
meta,err:=client.QueryOutterMeta()
if err != nil {
t.Error(err)
}
t.Log(meta.Meta)
}
func Test_PollEvent(t *testing.T){
client, err := NewJSONClient("", "http://localhost:8901")
if err != nil {
t.Error(err)
}
registerCh,eventCh,errCh:=client.RegisterTxEvent(0,"broker","EmitInterchainEvent")
go func() {
select {
case event:=<-eventCh:
t.Log(event)
case err:=<-errCh:
t.Error(err)
}
}()
time.Sleep(5*time.Second)
registerCh<- struct {}{}
}
func Test_UpdateIndex(t *testing.T){
client, err := NewJSONClient("", "http://localhost:8901")
if err != nil {
t.Error(err)
}
event,err:=client.QueryOutMessage("bxhv1:chain33:local&broker-fabric&broker",1)
if err !=nil {
t.Error(err)
}
tx := broker.UpdateIndex("", event.SrcServiceID, event.GetDstServiceID(), event.GetIndex(), 0, 1)
resp, err := client.SendTransactionSync(GenesisPriv, tx)
if err != nil {
t.Error(err)
}
t.Log(resp.Message)
}
func Test_QueryMeta(t *testing.T){
client, err := NewJSONClient("", "http://localhost:8901")
if err != nil {
t.Error(err)
}
resp,err:=client.QueryOutMessage("bxhv1:chain33:local&broker-fabric&broker",1)
if err !=nil {
t.Error(err)
}
t.Log(resp)
respon,err:=client.QueryInMessage("bxhv1:chain33:local&broker-fabric&broker",1)
if err !=nil {
t.Error(err)
}
t.Logf("status:%d",respon.Status)
meta,err:=client.QueryOutterMeta()
if err !=nil {
t.Error(err)
}
t.Log(meta.Meta)
}
...@@ -3,9 +3,10 @@ package client ...@@ -3,9 +3,10 @@ package client
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
. "github.com/bitly/go-simplejson"
"gitlab.33.cn/link33/chain33-sdk-go/dapp/storage" "gitlab.33.cn/link33/chain33-sdk-go/dapp/storage"
"gitlab.33.cn/link33/chain33-sdk-go/types" "gitlab.33.cn/link33/chain33-sdk-go/types"
. "github.com/bitly/go-simplejson" "strconv"
) )
// 回调解析函数 // 回调解析函数
...@@ -106,3 +107,45 @@ func ParseStorage(raw json.RawMessage) (interface{}, error) { ...@@ -106,3 +107,45 @@ func ParseStorage(raw json.RawMessage) (interface{}, error) {
} }
return nil, fmt.Errorf("unknow type!") return nil, fmt.Errorf("unknow type!")
} }
//FIXME 解析跨链事件,系统json序列化有问题,非string字段全部转化为string字段了
func ParseInterChainEvent(raw json.RawMessage)(interface{}, error){
js, err := NewJson(raw)
if err != nil {
return nil, err
}
index,err:= strconv.ParseUint(js.Get("index").MustString(),10,64)
if err != nil {
return nil, err
}
ty,err:=strconv.ParseUint(js.Get("type").MustString(),10,64)
if err != nil {
return nil, err
}
event:=&types.InterchainEvent{
Index:index,
DstServiceID:js.Get("dstServiceID").MustString(),
SrcServiceID:js.Get("srcServiceID").MustString(),
Type:ty,
Func:js.Get("func").MustString(),
Args:js.Get("args").MustString(),
Argsrb:js.Get("argsrb").MustString(),
Argscb:js.Get("argscb").MustString(),
}
return event,nil
}
func ParseMeta(raw json.RawMessage)(interface{}, error){
js, err := NewJson(raw)
if err != nil {
return nil, err
}
m :=js.Get("meta").MustMap()
mk :=make(map[string]uint64)
for k,v :=range m{
value,_:=strconv.ParseUint(v.(string),10,64)
mk[k]=value
}
//移除broker键值
delete(mk,"broker")
return &types.Meta{Meta:mk},nil
}
...@@ -9,26 +9,34 @@ import ( ...@@ -9,26 +9,34 @@ import (
) )
// 构造发布跨链交易事件交易 // 构造发布跨链交易事件交易
func EmitInterchainEvent(paraName, dstServiceID, funcName string, args,argscb,argsrb string, txType uint64) (*types.Transaction, error) { func EmitInterchainEvent(paraName, dstServiceID, funcName string, args, argscb, argsrb string, txType uint64) *types.Transaction {
payload := &types.BrokerAction{Ty: TyEmitInterchainEventAction, Value: &types.BrokerAction_EmitInterchainEvent{EmitInterchainEvent: &types.InterchainEvent{DstServiceID: dstServiceID, Type: txType, Func: funcName, Args: args,Argscb:argscb,Argsrb:argsrb}}} payload := &types.BrokerAction{Ty: TyEmitInterchainEventAction, Value: &types.BrokerAction_EmitInterchainEvent{EmitInterchainEvent: &types.InterchainEvent{DstServiceID: dstServiceID, Type: txType, Func: funcName, Args: args, Argscb: argscb, Argsrb: argsrb}}}
if paraName == "" { if paraName == "" {
tx := &types.Transaction{Execer: []byte(BrokerX), Payload: types.Encode(payload), Fee: 1e5, Nonce: rand.Int63n(time.Now().UnixNano()), To: Addr} tx := &types.Transaction{Execer: []byte(BrokerX), Payload: types.Encode(payload), Fee: 1e5, Nonce: rand.Int63n(time.Now().UnixNano()), To: Addr}
return tx, nil return tx
} else { } else {
tx := &types.Transaction{Execer: []byte(paraName + BrokerX), Payload: types.Encode(payload), Fee: 1e5, Nonce: rand.Int63n(time.Now().UnixNano()), To: crypto.GetExecAddress(paraName + BrokerX)} tx := &types.Transaction{Execer: []byte(paraName + BrokerX), Payload: types.Encode(payload), Fee: 1e5, Nonce: rand.Int63n(time.Now().UnixNano()), To: crypto.GetExecAddress(paraName + BrokerX)}
return tx, nil return tx
} }
} }
// 构造更新Index交易 // 构造更新Index交易
func UpdateIndex(paraName, srcServiceID, dstServiceID string, sequenceNum, reqType uint64, response *types.Response) (*types.Transaction, error) { func UpdateIndex(paraName, srcServiceID, dstServiceID string, sequenceNum, reqType uint64, status int32) *types.Transaction {
payload := &types.BrokerAction{Ty: TyUpdateIndexAction, Value: &types.BrokerAction_UpdateIndex{UpdateIndex: &types.UpdateIndex{DstServiceID: dstServiceID, SrcServiceID: srcServiceID, ReqType: reqType, SequenceNum: sequenceNum, Response: response}}} payload := &types.BrokerAction{Ty: TyUpdateIndexAction, Value: &types.BrokerAction_UpdateIndex{UpdateIndex: &types.UpdateIndex{DstServiceID: dstServiceID, SrcServiceID: srcServiceID, ReqType: reqType, SequenceNum: sequenceNum, Response: &types.Response{Status:status}}}}
if paraName == "" { if paraName == "" {
tx := &types.Transaction{Execer: []byte(BrokerX), Payload: types.Encode(payload), Fee: 1e5, Nonce: rand.Int63n(time.Now().UnixNano()), To: Addr} tx := &types.Transaction{Execer: []byte(BrokerX), Payload: types.Encode(payload), Fee: 1e5, Nonce: rand.Int63n(time.Now().UnixNano()), To: Addr}
return tx, nil return tx
} else { } else {
tx := &types.Transaction{Execer: []byte(paraName + BrokerX), Payload: types.Encode(payload), Fee: 1e5, Nonce: rand.Int63n(time.Now().UnixNano()), To: crypto.GetExecAddress(paraName + BrokerX)} tx := &types.Transaction{Execer: []byte(paraName + BrokerX), Payload: types.Encode(payload), Fee: 1e5, Nonce: rand.Int63n(time.Now().UnixNano()), To: crypto.GetExecAddress(paraName + BrokerX)}
return tx, nil return tx
} }
} }
func InitBroker(bxhId, appChainId string) *types.Transaction {
payload := &types.BrokerAction{Ty: TyInitAction, Value: &types.BrokerAction_Init{Init: &types.Init{
BxhId: bxhId,
AppChainId: appChainId,
}}}
tx := &types.Transaction{Execer: []byte(BrokerX), Payload: types.Encode(payload), Fee: 1e5, Nonce: rand.Int63n(time.Now().UnixNano()), To: Addr}
return tx
}
...@@ -19,7 +19,7 @@ var ( ...@@ -19,7 +19,7 @@ var (
func TestCreateContentStorageTx(t *testing.T) { func TestCreateContentStorageTx(t *testing.T) {
// 第一次存储 // 第一次存储
tx, err := CreateContentStorageTx("", OpCreate, "", []byte("hello"), "") tx, err := CreateContentStorageTx("", OpCreate, "test", nil,"hello")
assert.Nil(t, err) assert.Nil(t, err)
hexbytes, _ := types.FromHex(privkey) hexbytes, _ := types.FromHex(privkey)
sdk.Sign(tx, hexbytes, crypto.SECP256K1, nil) sdk.Sign(tx, hexbytes, crypto.SECP256K1, nil)
...@@ -35,9 +35,9 @@ func TestCreateContentStorageTx(t *testing.T) { ...@@ -35,9 +35,9 @@ func TestCreateContentStorageTx(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, types.ExecOk, int(detail.Receipt.Ty)) assert.Equal(t, types.ExecOk, int(detail.Receipt.Ty))
// 查询 // 查询
storage, err := QueryStorageByKey("", url, txhash) storage, err := QueryStorageByKey("", url, "test")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, []byte("hello"), storage.GetContentStorage().Content) assert.Equal(t, "hello", storage.GetContentStorage().Value)
//第二次追加 老版本不支持 //第二次追加 老版本不支持
//tx,err=CreateContentStorageTx("",OpAdd,txhash,[]byte("world"),"") //tx,err=CreateContentStorageTx("",OpAdd,txhash,[]byte("world"),"")
//assert.Nil(t,err) //assert.Nil(t,err)
...@@ -52,6 +52,8 @@ func TestCreateContentStorageTx(t *testing.T) { ...@@ -52,6 +52,8 @@ func TestCreateContentStorageTx(t *testing.T) {
//assert.Equal(t,[]byte("hello,world"),storage.GetContentStorage().Content) //assert.Equal(t,[]byte("hello,world"),storage.GetContentStorage().Content)
} }
// hash,or link 存证 // hash,or link 存证
func TestCreateHashStorageTx(t *testing.T) { func TestCreateHashStorageTx(t *testing.T) {
tx, err := CreateHashStorageTx("", "", []byte("123456harrylee"), "") tx, err := CreateHashStorageTx("", "", []byte("123456harrylee"), "")
......
...@@ -49,7 +49,7 @@ message UpdateIndex { ...@@ -49,7 +49,7 @@ message UpdateIndex {
string srcServiceID = 3; string srcServiceID = 3;
//请求类型 0表示信息流入 1表示信息流出 2表示回滚 //请求类型 0表示信息流入 1表示信息流出 2表示回滚
uint64 reqType =4; uint64 reqType =4;
//响应信息 //跨入交易执行结果
Response response = 5; Response response = 5;
} }
// 跨链事件 // 跨链事件
...@@ -150,10 +150,6 @@ message Meta { ...@@ -150,10 +150,6 @@ message Meta {
message Response{ message Response{
// A status code that should follow the HTTP status codes. //状态 0表示开始处理 1表示跨链成功 2表示跨链失败
int32 status = 1; int32 status = 1;
// A message associated with the response code.
string message = 2;
// A payload that can be used to include metadata with this response.
bytes payload = 3;
} }
This diff is collapsed.
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