Unverified Commit 5d10cc15 authored by vipwzw's avatar vipwzw Committed by GitHub

Merge pull request #57 from lyh169/modify_pl_linter_warning

Modify pl linter warning
parents f125f764 c829ea34
......@@ -4,5 +4,8 @@
package buildflags
// ParaName para name
var ParaName string
// RPCAddr rpc address
var RPCAddr string
......@@ -15,6 +15,7 @@ import (
"github.com/spf13/cobra"
)
// BlackwhiteCmd 黑白配游戏命令行
func BlackwhiteCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "blackwhite",
......@@ -33,6 +34,7 @@ func BlackwhiteCmd() *cobra.Command {
return cmd
}
// BlackwhiteCreateRawTxCmd 创建黑白配游戏交易命令
func BlackwhiteCreateRawTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "create",
......@@ -83,6 +85,7 @@ func blackwhiteCreate(cmd *cobra.Command, args []string) {
ctx.RunWithoutMarshal()
}
// BlackwhitePlayRawTxCmd 参与玩黑白配游戏
func BlackwhitePlayRawTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "play",
......@@ -142,6 +145,7 @@ func blackwhitePlay(cmd *cobra.Command, args []string) {
ctx.RunWithoutMarshal()
}
// BlackwhiteShowRawTxCmd 出示密钥
func BlackwhiteShowRawTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "show",
......@@ -180,6 +184,7 @@ func blackwhiteShow(cmd *cobra.Command, args []string) {
ctx.RunWithoutMarshal()
}
// BlackwhiteTimeoutDoneTxCmd 触发游戏超时,由外部触发
func BlackwhiteTimeoutDoneTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "timeoutDone",
......@@ -212,6 +217,7 @@ func blackwhiteTimeoutDone(cmd *cobra.Command, args []string) {
ctx.RunWithoutMarshal()
}
// ShowBlackwhiteInfoCmd 显示黑白配游戏查询信息
func ShowBlackwhiteInfoCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "showInfo",
......
......@@ -19,14 +19,14 @@ import (
)
const (
MaxAmount int64 = 100 * types.Coin
MinAmount int64 = 1 * types.Coin
MinPlayerCount int32 = 3
MaxPlayerCount int32 = 100000
maxAmount int64 = 100 * types.Coin
minAmount int64 = 1 * types.Coin
minPlayerCount int32 = 3
maxPlayerCount int32 = 100000
lockAmount int64 = types.Coin / 100 //创建者锁定金额
showTimeout int64 = 60 * 5 // 公布密钥超时时间
MaxPlayTimeout int64 = 60 * 60 * 24 // 创建交易之后最大超时时间
MinPlayTimeout int64 = 60 * 10 // 创建交易之后最小超时时间
maxPlayTimeout int64 = 60 * 60 * 24 // 创建交易之后最大超时时间
minPlayTimeout int64 = 60 * 10 // 创建交易之后最小超时时间
white = "0"
black = "1"
......@@ -63,13 +63,13 @@ func newAction(t *Blackwhite, tx *types.Transaction, index int32) *action {
}
func (a *action) Create(create *gt.BlackwhiteCreate) (*types.Receipt, error) {
if create.PlayAmount < MinAmount || create.PlayAmount > MaxAmount {
if create.PlayAmount < minAmount || create.PlayAmount > maxAmount {
return nil, types.ErrAmount
}
if create.PlayerCount < MinPlayerCount || create.PlayerCount > MaxPlayerCount {
if create.PlayerCount < minPlayerCount || create.PlayerCount > maxPlayerCount {
return nil, types.ErrInvalidParam
}
if create.Timeout < MinPlayTimeout || create.Timeout > MaxPlayTimeout {
if create.Timeout < minPlayTimeout || create.Timeout > maxPlayTimeout {
return nil, types.ErrInvalidParam
}
......@@ -92,12 +92,12 @@ func (a *action) Create(create *gt.BlackwhiteCreate) (*types.Receipt, error) {
key := calcMavlRoundKey(round.GameID)
value := types.Encode(round)
kv = append(kv, &types.KeyValue{key, value})
kv = append(kv, &types.KeyValue{Key: key, Value: value})
receiptLog := a.GetReceiptLog(round, round.GetCreateAddr())
logs = append(logs, receiptLog)
return &types.Receipt{types.ExecOk, kv, logs}, nil
return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
}
func (a *action) Play(play *gt.BlackwhitePlay) (*types.Receipt, error) {
......@@ -184,9 +184,9 @@ func (a *action) Play(play *gt.BlackwhitePlay) (*types.Receipt, error) {
//将当前游戏状态保存,便于同一区块中游戏参数的累加
a.db.Set(key1, value1)
}
kv = append(kv, &types.KeyValue{key1, value1})
kv = append(kv, &types.KeyValue{Key: key1, Value: value1})
return &types.Receipt{types.ExecOk, kv, logs}, nil
return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
}
func (a *action) Show(show *gt.BlackwhiteShow) (*types.Receipt, error) {
......@@ -268,9 +268,9 @@ func (a *action) Show(show *gt.BlackwhiteShow) (*types.Receipt, error) {
//将当前游戏状态保存,便于同一区块中游戏参数的累加
a.db.Set(key1, value1)
}
kv = append(kv, &types.KeyValue{key1, value1})
kv = append(kv, &types.KeyValue{Key: key1, Value: value1})
return &types.Receipt{types.ExecOk, kv, logs}, nil
return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
}
func (a *action) TimeoutDone(done *gt.BlackwhiteTimeoutDone) (*types.Receipt, error) {
......@@ -364,7 +364,7 @@ func (a *action) TimeoutDone(done *gt.BlackwhiteTimeoutDone) (*types.Receipt, er
//将当前游戏状态保存,便于同一区块中游戏参数的累加
a.db.Set(key1, value1)
}
kv = append(kv, &types.KeyValue{key1, value1})
kv = append(kv, &types.KeyValue{Key: key1, Value: value1})
// 需要更新全部地址状态
for _, addr := range round.AddrResult {
......@@ -376,7 +376,7 @@ func (a *action) TimeoutDone(done *gt.BlackwhiteTimeoutDone) (*types.Receipt, er
receiptLog := a.GetReceiptLog(&round, round.CreateAddr)
logs = append(logs, receiptLog)
return &types.Receipt{types.ExecOk, kv, logs}, nil
return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
}
......@@ -514,9 +514,9 @@ func (a *action) StatTransfer(round *gt.BlackwhiteRound) (*types.Receipt, error)
kv = append(kv, receipt.KV...)
// 将每一轮次的结果保存
logs = append(logs, &types.ReceiptLog{gt.TyLogBlackwhiteLoopInfo, types.Encode(loopResults)})
logs = append(logs, &types.ReceiptLog{Ty: gt.TyLogBlackwhiteLoopInfo, Log: types.Encode(loopResults)})
return &types.Receipt{types.ExecOk, kv, logs}, nil
return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
}
......@@ -646,14 +646,14 @@ func (a *action) getLoser(round *gt.BlackwhiteRound) []*addrResult {
return results
}
//状态变化:
// GetReceiptLog 根据游戏信息获取log
// 状态变化:
// staus == BlackwhiteStatusCreate (创建,开始游戏)
// status == BlackwhiteStatusPlay (参与)
// status == BlackwhiteStatusShow (展示密钥)
// status == BlackwhiteStatusTime (超时退出情况)
// status == BlackwhiteStatusDone (结束情况)
func (action *action) GetReceiptLog(round *gt.BlackwhiteRound, addr string) *types.ReceiptLog {
func (a *action) GetReceiptLog(round *gt.BlackwhiteRound, addr string) *types.ReceiptLog {
log := &types.ReceiptLog{}
r := &gt.ReceiptBlackwhiteStatus{}
if round.Status == gt.BlackwhiteStatusCreate {
......
......@@ -25,7 +25,7 @@ func init() {
ety.InitFuncList(types.ListMethod(&Blackwhite{}))
}
//黑白配可以被重命名执行器名称
// Init 重命名执行器名称
func Init(name string, sub []byte) {
driverName = name
gt.BlackwhiteX = driverName
......@@ -33,6 +33,7 @@ func Init(name string, sub []byte) {
drivers.Register(name, newBlackwhite, types.GetDappFork(driverName, "Enable"))
}
// Blackwhite 几类执行器结构体
type Blackwhite struct {
drivers.DriverBase
}
......@@ -44,10 +45,12 @@ func newBlackwhite() drivers.Driver {
return c
}
// GetName 获取执行器别名
func GetName() string {
return newBlackwhite().GetName()
}
// GetDriverName 获取执行器名字
func (c *Blackwhite) GetDriverName() string {
return driverName
}
......@@ -118,9 +121,10 @@ func (c *Blackwhite) delHeightIndex(res *gt.ReceiptBlackwhiteStatus) (kvs []*typ
return kvs
}
// GetBlackwhiteRoundInfo 获取当前游戏信息
func (c *Blackwhite) GetBlackwhiteRoundInfo(req *gt.ReqBlackwhiteRoundInfo) (types.Message, error) {
gameId := req.GameID
key := calcMavlRoundKey(gameId)
gameID := req.GameID
key := calcMavlRoundKey(gameID)
values, err := c.GetStateDB().Get(key)
if err != nil {
return nil, err
......@@ -157,6 +161,7 @@ func (c *Blackwhite) GetBlackwhiteRoundInfo(req *gt.ReqBlackwhiteRoundInfo) (typ
return &rep, nil
}
// GetBwRoundListInfo 根据要求获取游戏信息,包括游戏所处状态,或者参与者地址
func (c *Blackwhite) GetBwRoundListInfo(req *gt.ReqBlackwhiteRoundList) (types.Message, error) {
var key []byte
var values [][]byte
......@@ -234,6 +239,7 @@ func (c *Blackwhite) GetBwRoundListInfo(req *gt.ReqBlackwhiteRoundList) (types.M
return &rep, nil
}
// GetBwRoundLoopResult 获取游戏中每轮的胜负结果
func (c *Blackwhite) GetBwRoundLoopResult(req *gt.ReqLoopResult) (types.Message, error) {
localDb := c.GetLocalDB()
values, err := localDb.Get(calcRoundKey4LoopResult(req.GameID))
......@@ -275,6 +281,7 @@ func heightIndexToIndex(height int64, index int32) int64 {
return height*types.MaxTxsPerBlock + int64(index)
}
// GetPayloadValue 获取执行器action结构体
func (c *Blackwhite) GetPayloadValue() types.Message {
return &gt.BlackwhiteAction{}
}
......@@ -9,21 +9,25 @@ import (
gt "github.com/33cn/plugin/plugin/dapp/blackwhite/types"
)
// Exec_Create 创建游戏
func (c *Blackwhite) Exec_Create(payload *gt.BlackwhiteCreate, tx *types.Transaction, index int) (*types.Receipt, error) {
action := newAction(c, tx, int32(index))
return action.Create(payload)
}
// Exec_Play 参与游戏
func (c *Blackwhite) Exec_Play(payload *gt.BlackwhitePlay, tx *types.Transaction, index int) (*types.Receipt, error) {
action := newAction(c, tx, int32(index))
return action.Play(payload)
}
// Exec_Show 出示密钥
func (c *Blackwhite) Exec_Show(payload *gt.BlackwhiteShow, tx *types.Transaction, index int) (*types.Receipt, error) {
action := newAction(c, tx, int32(index))
return action.Show(payload)
}
// Exec_TimeoutDone 超时处理
func (c *Blackwhite) Exec_TimeoutDone(payload *gt.BlackwhiteTimeoutDone, tx *types.Transaction, index int) (*types.Receipt, error) {
action := newAction(c, tx, int32(index))
return action.TimeoutDone(payload)
......
......@@ -59,6 +59,7 @@ func (c *Blackwhite) execDelLocal(receiptData *types.ReceiptData) ([]*types.KeyV
return retKV, nil
}
// ExecDelLocal_Create 执行删除创建游戏产生的本地数据库
func (c *Blackwhite) ExecDelLocal_Create(payload *gt.BlackwhiteCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execDelLocal(receiptData)
if err != nil {
......@@ -67,6 +68,7 @@ func (c *Blackwhite) ExecDelLocal_Create(payload *gt.BlackwhiteCreate, tx *types
return &types.LocalDBSet{KV: kv}, nil
}
// ExecDelLocal_Play 执行删除参与游戏产生的本地数据库
func (c *Blackwhite) ExecDelLocal_Play(payload *gt.BlackwhitePlay, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execDelLocal(receiptData)
if err != nil {
......@@ -75,6 +77,7 @@ func (c *Blackwhite) ExecDelLocal_Play(payload *gt.BlackwhitePlay, tx *types.Tra
return &types.LocalDBSet{KV: kv}, nil
}
// ExecDelLocal_Show 执行删除出示密钥产生的本地数据库
func (c *Blackwhite) ExecDelLocal_Show(payload *gt.BlackwhiteShow, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execDelLocal(receiptData)
if err != nil {
......@@ -83,6 +86,7 @@ func (c *Blackwhite) ExecDelLocal_Show(payload *gt.BlackwhiteShow, tx *types.Tra
return &types.LocalDBSet{KV: kv}, nil
}
// ExecDelLocal_TimeoutDone 执行删除超时产生的本地数据库
func (c *Blackwhite) ExecDelLocal_TimeoutDone(payload *gt.BlackwhiteTimeoutDone, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execDelLocal(receiptData)
if err != nil {
......
......@@ -44,6 +44,7 @@ func (c *Blackwhite) execLocal(receiptData *types.ReceiptData) ([]*types.KeyValu
return set, nil
}
// ExecLocal_Create 执行生成创建游戏产生的本地数据库
func (c *Blackwhite) ExecLocal_Create(payload *gt.BlackwhiteCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execLocal(receiptData)
if err != nil {
......@@ -52,6 +53,7 @@ func (c *Blackwhite) ExecLocal_Create(payload *gt.BlackwhiteCreate, tx *types.Tr
return &types.LocalDBSet{KV: kv}, nil
}
// ExecLocal_Play 执行生成参与游戏产生的本地数据库
func (c *Blackwhite) ExecLocal_Play(payload *gt.BlackwhitePlay, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execLocal(receiptData)
if err != nil {
......@@ -60,6 +62,7 @@ func (c *Blackwhite) ExecLocal_Play(payload *gt.BlackwhitePlay, tx *types.Transa
return &types.LocalDBSet{KV: kv}, nil
}
// ExecLocal_Show 执行生成出示密钥产生的本地数据库
func (c *Blackwhite) ExecLocal_Show(payload *gt.BlackwhiteShow, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execLocal(receiptData)
if err != nil {
......@@ -68,6 +71,7 @@ func (c *Blackwhite) ExecLocal_Show(payload *gt.BlackwhiteShow, tx *types.Transa
return &types.LocalDBSet{KV: kv}, nil
}
// ExecLocal_TimeoutDone 执行生成超时产生的本地数据库
func (c *Blackwhite) ExecLocal_TimeoutDone(payload *gt.BlackwhiteTimeoutDone, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
kv, err := c.execLocal(receiptData)
if err != nil {
......
......@@ -9,6 +9,7 @@ import (
gt "github.com/33cn/plugin/plugin/dapp/blackwhite/types"
)
// Query_GetBlackwhiteRoundInfo 查询游戏信息
func (c *Blackwhite) Query_GetBlackwhiteRoundInfo(in *gt.ReqBlackwhiteRoundInfo) (types.Message, error) {
if in == nil {
return nil, types.ErrInvalidParam
......@@ -16,6 +17,7 @@ func (c *Blackwhite) Query_GetBlackwhiteRoundInfo(in *gt.ReqBlackwhiteRoundInfo)
return c.GetBlackwhiteRoundInfo(in)
}
// Query_GetBlackwhiteByStatusAndAddr 查询符合状态以及地址的游戏信息
func (c *Blackwhite) Query_GetBlackwhiteByStatusAndAddr(in *gt.ReqBlackwhiteRoundList) (types.Message, error) {
if in == nil {
return nil, types.ErrInvalidParam
......@@ -23,6 +25,7 @@ func (c *Blackwhite) Query_GetBlackwhiteByStatusAndAddr(in *gt.ReqBlackwhiteRoun
return c.GetBwRoundListInfo(in)
}
// Query_GetBlackwhiteloopResult 查询游戏中每轮次的比赛结果
func (c *Blackwhite) Query_GetBlackwhiteloopResult(in *gt.ReqLoopResult) (types.Message, error) {
if in == nil {
return nil, types.ErrInvalidParam
......
......@@ -4,6 +4,7 @@
package executor
// BlackwhiteCreateTxReq 创建游戏结构体
type BlackwhiteCreateTxReq struct {
PlayAmount int64 `json:"amount"`
PlayerCount int32 `json:"playerCount"`
......@@ -12,6 +13,7 @@ type BlackwhiteCreateTxReq struct {
Fee int64 `json:"fee"`
}
// BlackwhitePlayTx 参与游戏结构体
type BlackwhitePlayTx struct {
GameID string `json:"gameID"`
Amount int64 `json:"amount"`
......@@ -19,12 +21,14 @@ type BlackwhitePlayTx struct {
Fee int64 `json:"fee"`
}
// BlackwhiteShowTx 出示密钥结构体
type BlackwhiteShowTx struct {
GameID string `json:"gameID"`
Secret string `json:"secret"`
Fee int64 `json:"fee"`
}
// BlackwhiteTimeoutDoneTx 游戏超时结构体
type BlackwhiteTimeoutDoneTx struct {
GameID string `json:"GameID"`
Fee int64 `json:"fee"`
......
......@@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package blackwhite 黑白配游戏插件
package blackwhite
import (
......
......@@ -12,6 +12,7 @@ import (
bw "github.com/33cn/plugin/plugin/dapp/blackwhite/types"
)
// BlackwhiteCreateTx 创建游戏RPC接口
func (c *Jrpc) BlackwhiteCreateTx(parm *bw.BlackwhiteCreateTxReq, result *interface{}) error {
if parm == nil {
return types.ErrInvalidParam
......@@ -30,6 +31,7 @@ func (c *Jrpc) BlackwhiteCreateTx(parm *bw.BlackwhiteCreateTxReq, result *interf
return nil
}
// BlackwhiteShowTx 出示游戏密钥的RPC接口
func (c *Jrpc) BlackwhiteShowTx(parm *BlackwhiteShowTx, result *interface{}) error {
if parm == nil {
return types.ErrInvalidParam
......@@ -46,6 +48,7 @@ func (c *Jrpc) BlackwhiteShowTx(parm *BlackwhiteShowTx, result *interface{}) err
return nil
}
// BlackwhitePlayTx 参与游戏的RPC接口
func (c *Jrpc) BlackwhitePlayTx(parm *BlackwhitePlayTx, result *interface{}) error {
if parm == nil {
return types.ErrInvalidParam
......@@ -65,6 +68,7 @@ func (c *Jrpc) BlackwhitePlayTx(parm *BlackwhitePlayTx, result *interface{}) err
return nil
}
// BlackwhiteTimeoutDoneTx 游戏超时RPC接口
func (c *Jrpc) BlackwhiteTimeoutDoneTx(parm *BlackwhiteTimeoutDoneTx, result *interface{}) error {
if parm == nil {
return types.ErrInvalidParam
......
......@@ -14,7 +14,7 @@ import (
func (c *channelClient) Create(ctx context.Context, head *bw.BlackwhiteCreate) (*types.UnsignTx, error) {
val := &bw.BlackwhiteAction{
Ty: bw.BlackwhiteActionCreate,
Value: &bw.BlackwhiteAction_Create{head},
Value: &bw.BlackwhiteAction_Create{Create: head},
}
tx := &types.Transaction{
Payload: types.Encode(val),
......@@ -29,7 +29,7 @@ func (c *channelClient) Create(ctx context.Context, head *bw.BlackwhiteCreate) (
func (c *channelClient) Show(ctx context.Context, head *bw.BlackwhiteShow) (*types.UnsignTx, error) {
val := &bw.BlackwhiteAction{
Ty: bw.BlackwhiteActionShow,
Value: &bw.BlackwhiteAction_Show{head},
Value: &bw.BlackwhiteAction_Show{Show: head},
}
tx := &types.Transaction{
Payload: types.Encode(val),
......@@ -44,7 +44,7 @@ func (c *channelClient) Show(ctx context.Context, head *bw.BlackwhiteShow) (*typ
func (c *channelClient) Play(ctx context.Context, head *bw.BlackwhitePlay) (*types.UnsignTx, error) {
val := &bw.BlackwhiteAction{
Ty: bw.BlackwhiteActionPlay,
Value: &bw.BlackwhiteAction_Play{head},
Value: &bw.BlackwhiteAction_Play{Play: head},
}
tx := &types.Transaction{
Payload: types.Encode(val),
......@@ -59,7 +59,7 @@ func (c *channelClient) Play(ctx context.Context, head *bw.BlackwhitePlay) (*typ
func (c *channelClient) TimeoutDone(ctx context.Context, head *bw.BlackwhiteTimeoutDone) (*types.UnsignTx, error) {
val := &bw.BlackwhiteAction{
Ty: bw.BlackwhiteActionTimeoutDone,
Value: &bw.BlackwhiteAction_TimeoutDone{head},
Value: &bw.BlackwhiteAction_TimeoutDone{TimeoutDone: head},
}
tx := &types.Transaction{
Payload: types.Encode(val),
......
......@@ -4,6 +4,7 @@
package rpc
// BlackwhiteCreateTx 创建游戏结构体
type BlackwhiteCreateTx struct {
PlayAmount int64 `json:"amount"`
PlayerCount int32 `json:"playerCount"`
......@@ -12,6 +13,7 @@ type BlackwhiteCreateTx struct {
Fee int64 `json:"fee"`
}
// BlackwhitePlayTx 参与游戏结构体
type BlackwhitePlayTx struct {
GameID string `json:"gameID"`
Amount int64 `json:"amount"`
......@@ -19,12 +21,14 @@ type BlackwhitePlayTx struct {
Fee int64 `json:"fee"`
}
// BlackwhiteShowTx 出示密钥结构体
type BlackwhiteShowTx struct {
GameID string `json:"gameID"`
Secret string `json:"secret"`
Fee int64 `json:"fee"`
}
// BlackwhiteTimeoutDoneTx 游戏超时结构体
type BlackwhiteTimeoutDoneTx struct {
GameID string `json:"GameID"`
Fee int64 `json:"fee"`
......
......@@ -13,10 +13,12 @@ import (
bw "github.com/33cn/plugin/plugin/dapp/blackwhite/types"
)
// Jrpc json rpc struct
type Jrpc struct {
cli *channelClient
}
// Grpc grpc struct
type Grpc struct {
*channelClient
}
......@@ -25,6 +27,7 @@ type channelClient struct {
rpctypes.ChannelClient
}
// Init init grpc param
func Init(name string, s rpctypes.RPCServer) {
cli := &channelClient{}
grpc := &Grpc{channelClient: cli}
......@@ -32,8 +35,10 @@ func Init(name string, s rpctypes.RPCServer) {
bw.RegisterBlackwhiteServer(s.GRPC(), grpc)
}
// BlackwhiteCreateTxRPC ...
type BlackwhiteCreateTxRPC struct{}
// Input for convert struct
func (t *BlackwhiteCreateTxRPC) Input(message json.RawMessage) ([]byte, error) {
var req bw.BlackwhiteCreateTxReq
err := json.Unmarshal(message, &req)
......@@ -43,6 +48,7 @@ func (t *BlackwhiteCreateTxRPC) Input(message json.RawMessage) ([]byte, error) {
return types.Encode(&req), nil
}
// Output for convert struct
func (t *BlackwhiteCreateTxRPC) Output(reply interface{}) (interface{}, error) {
if replyData, ok := reply.(*types.Message); ok {
if tx, ok := (*replyData).(*types.Transaction); ok {
......@@ -53,9 +59,11 @@ func (t *BlackwhiteCreateTxRPC) Output(reply interface{}) (interface{}, error) {
return nil, types.ErrTypeAsset
}
// BlackwhitePlayTxRPC ...
type BlackwhitePlayTxRPC struct {
}
// Input for convert struct
func (t *BlackwhitePlayTxRPC) Input(message json.RawMessage) ([]byte, error) {
var req bw.BlackwhitePlayTxReq
err := json.Unmarshal(message, &req)
......@@ -65,6 +73,7 @@ func (t *BlackwhitePlayTxRPC) Input(message json.RawMessage) ([]byte, error) {
return types.Encode(&req), nil
}
// Output for convert struct
func (t *BlackwhitePlayTxRPC) Output(reply interface{}) (interface{}, error) {
if replyData, ok := reply.(*types.Message); ok {
if tx, ok := (*replyData).(*types.Transaction); ok {
......@@ -75,9 +84,11 @@ func (t *BlackwhitePlayTxRPC) Output(reply interface{}) (interface{}, error) {
return nil, types.ErrTypeAsset
}
// BlackwhiteShowTxRPC ...
type BlackwhiteShowTxRPC struct {
}
// Input for convert struct
func (t *BlackwhiteShowTxRPC) Input(message json.RawMessage) ([]byte, error) {
var req bw.BlackwhiteShowTxReq
err := json.Unmarshal(message, &req)
......@@ -87,6 +98,7 @@ func (t *BlackwhiteShowTxRPC) Input(message json.RawMessage) ([]byte, error) {
return types.Encode(&req), nil
}
// Output for convert struct
func (t *BlackwhiteShowTxRPC) Output(reply interface{}) (interface{}, error) {
if replyData, ok := reply.(*types.Message); ok {
if tx, ok := (*replyData).(*types.Transaction); ok {
......@@ -97,9 +109,11 @@ func (t *BlackwhiteShowTxRPC) Output(reply interface{}) (interface{}, error) {
return nil, types.ErrTypeAsset
}
// BlackwhiteTimeoutDoneTxRPC ...
type BlackwhiteTimeoutDoneTxRPC struct {
}
// Input for convert struct
func (t *BlackwhiteTimeoutDoneTxRPC) Input(message json.RawMessage) ([]byte, error) {
var req bw.BlackwhiteTimeoutDoneTxReq
err := json.Unmarshal(message, &req)
......@@ -109,6 +123,7 @@ func (t *BlackwhiteTimeoutDoneTxRPC) Input(message json.RawMessage) ([]byte, err
return types.Encode(&req), nil
}
// Output for convert struct
func (t *BlackwhiteTimeoutDoneTxRPC) Output(reply interface{}) (interface{}, error) {
if replyData, ok := reply.(*types.Message); ok {
if tx, ok := (*replyData).(*types.Transaction); ok {
......
......@@ -21,26 +21,36 @@ const (
)
const (
// log for blackwhite game
// TyLogBlackwhiteCreate log for blackwhite create game
TyLogBlackwhiteCreate = 750
// TyLogBlackwhitePlay log for blackwhite play game
TyLogBlackwhitePlay = 751
// TyLogBlackwhiteShow log for blackwhite show game
TyLogBlackwhiteShow = 752
// TyLogBlackwhiteTimeout log for blackwhite timeout game
TyLogBlackwhiteTimeout = 753
// TyLogBlackwhiteDone log for blackwhite down game
TyLogBlackwhiteDone = 754
// TyLogBlackwhiteLoopInfo log for blackwhite LoopInfo game
TyLogBlackwhiteLoopInfo = 755
)
const (
// GetBlackwhiteRoundInfo 用于在cmd里面的区分不同的查询
GetBlackwhiteRoundInfo = "GetBlackwhiteRoundInfo"
// GetBlackwhiteByStatusAndAddr 用于在cmd里面的区分不同的查询
GetBlackwhiteByStatusAndAddr = "GetBlackwhiteByStatusAndAddr"
// GetBlackwhiteloopResult 用于在cmd里面的区分不同的查询
GetBlackwhiteloopResult = "GetBlackwhiteloopResult"
)
var (
// BlackwhiteX 执行器名字
BlackwhiteX = "blackwhite"
glog = log15.New("module", BlackwhiteX)
//GRPCName = "chain33.blackwhite"
// JRPCName json RPC name
JRPCName = "Blackwhite"
// ExecerBlackwhite 执行器名字byte形式
ExecerBlackwhite = []byte(BlackwhiteX)
actionName = map[string]int32{
"Create": BlackwhiteActionCreate,
......
......@@ -7,9 +7,14 @@ package types
import "errors"
var (
// ErrIncorrectStatus 所处游戏状态不正确
ErrIncorrectStatus = errors.New("ErrIncorrectStatus")
// ErrRepeatPlayerAddr 重复玩家
ErrRepeatPlayerAddr = errors.New("ErrRepeatPlayerAddress")
// ErrNoTimeoutDone 还未超时
ErrNoTimeoutDone = errors.New("ErrNoTimeoutDone")
// ErrNoExistAddr 不存在地址,未参与游戏
ErrNoExistAddr = errors.New("ErrNoExistAddress")
// ErrNoLoopSeq 查询的轮次大于决出胜负的轮次
ErrNoLoopSeq = errors.New("ErrBlackwhiteFinalloopLessThanSeq")
)
......@@ -12,9 +12,13 @@ import (
// blackwhite action type
const (
// BlackwhiteActionCreate blackwhite create action
BlackwhiteActionCreate = iota
// BlackwhiteActionPlay blackwhite play action
BlackwhiteActionPlay
// BlackwhiteActionShow blackwhite show action
BlackwhiteActionShow
// BlackwhiteActionTimeoutDone blackwhite timeout action
BlackwhiteActionTimeoutDone
)
......@@ -26,33 +30,40 @@ func init() {
types.RegisterDappFork(BlackwhiteX, "Enable", 850000)
}
// BlackwhiteType 执行器基类结构体
type BlackwhiteType struct {
types.ExecTypeBase
}
// NewType 创建执行器类型
func NewType() *BlackwhiteType {
c := &BlackwhiteType{}
c.SetChild(c)
return c
}
// GetPayload 获取blackwhite action
func (b *BlackwhiteType) GetPayload() types.Message {
return &BlackwhiteAction{}
}
// GetName 获取执行器名称
func (b *BlackwhiteType) GetName() string {
return BlackwhiteX
}
// GetLogMap 获取log的映射对应关系
func (b *BlackwhiteType) GetLogMap() map[int64]*types.LogInfo {
return logInfo
}
// GetTypeMap 根据action的name获取type
func (b *BlackwhiteType) GetTypeMap() map[string]int32 {
return actionName
}
func (m BlackwhiteType) ActionName(tx *types.Transaction) string {
// ActionName 根据交易的payLoad获取blackwhite的action的name
func (b BlackwhiteType) ActionName(tx *types.Transaction) string {
var g BlackwhiteAction
err := types.Decode(tx.Payload, &g)
if err != nil {
......@@ -70,20 +81,24 @@ func (m BlackwhiteType) ActionName(tx *types.Transaction) string {
return "unkown"
}
func (m BlackwhiteType) Amount(tx *types.Transaction) (int64, error) {
// Amount ...
func (b BlackwhiteType) Amount(tx *types.Transaction) (int64, error) {
return 0, nil
}
// CreateTx ...
// TODO 暂时不修改实现, 先完成结构的重构
func (m BlackwhiteType) CreateTx(action string, message json.RawMessage) (*types.Transaction, error) {
func (b BlackwhiteType) CreateTx(action string, message json.RawMessage) (*types.Transaction, error) {
glog.Debug("Blackwhite.CreateTx", "action", action)
var tx *types.Transaction
return tx, nil
}
// BlackwhiteRoundInfo ...
type BlackwhiteRoundInfo struct {
}
// Input for convert struct
func (t *BlackwhiteRoundInfo) Input(message json.RawMessage) ([]byte, error) {
var req ReqBlackwhiteRoundInfo
err := json.Unmarshal(message, &req)
......@@ -93,13 +108,16 @@ func (t *BlackwhiteRoundInfo) Input(message json.RawMessage) ([]byte, error) {
return types.Encode(&req), nil
}
// Output for convert struct
func (t *BlackwhiteRoundInfo) Output(reply interface{}) (interface{}, error) {
return reply, nil
}
// BlackwhiteByStatusAndAddr ...
type BlackwhiteByStatusAndAddr struct {
}
// Input for convert struct
func (t *BlackwhiteByStatusAndAddr) Input(message json.RawMessage) ([]byte, error) {
var req ReqBlackwhiteRoundList
err := json.Unmarshal(message, &req)
......@@ -109,13 +127,16 @@ func (t *BlackwhiteByStatusAndAddr) Input(message json.RawMessage) ([]byte, erro
return types.Encode(&req), nil
}
// Output for convert struct
func (t *BlackwhiteByStatusAndAddr) Output(reply interface{}) (interface{}, error) {
return reply, nil
}
// BlackwhiteloopResult ...
type BlackwhiteloopResult struct {
}
// Input for convert struct
func (t *BlackwhiteloopResult) Input(message json.RawMessage) ([]byte, error) {
var req ReqLoopResult
err := json.Unmarshal(message, &req)
......@@ -125,6 +146,7 @@ func (t *BlackwhiteloopResult) Input(message json.RawMessage) ([]byte, error) {
return types.Encode(&req), nil
}
// Output for convert struct
func (t *BlackwhiteloopResult) Output(reply interface{}) (interface{}, error) {
return reply, nil
}
......@@ -47,14 +47,15 @@ var (
// |
// V
// tcp
type HTTPConn struct {
type httpConn struct {
in io.Reader
out io.Writer
}
func (c *HTTPConn) Read(p []byte) (n int, err error) { return c.in.Read(p) }
func (c *HTTPConn) Write(d []byte) (n int, err error) { return c.out.Write(d) }
func (c *HTTPConn) Close() error { return nil }
func (c *httpConn) Read(p []byte) (n int, err error) { return c.in.Read(p) }
func (c *httpConn) Write(d []byte) (n int, err error) { return c.out.Write(d) }
func (c *httpConn) Close() error { return nil }
func main() {
d, _ := os.Getwd()
......@@ -87,7 +88,7 @@ func main() {
}
if r.URL.Path == "/" {
serverCodec := jsonrpc.NewServerCodec(&HTTPConn{in: r.Body, out: w})
serverCodec := jsonrpc.NewServerCodec(&httpConn{in: r.Body, out: w})
w.Header().Set("Content-type", "application/json")
w.WriteHeader(200)
......@@ -112,6 +113,7 @@ func main() {
}
// InitCfg 初始化配置
func InitCfg(path string) *signatory.Config {
var cfg signatory.Config
if _, err := tml.DecodeFile(path, &cfg); err != nil {
......@@ -122,6 +124,7 @@ func InitCfg(path string) *signatory.Config {
return &cfg
}
// InitWhiteList 初始化白名单
func InitWhiteList(cfg *signatory.Config) map[string]bool {
whitelist := map[string]bool{}
if len(cfg.Whitelist) == 1 && cfg.Whitelist[0] == "*" {
......
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: config.proto
......@@ -31,6 +27,7 @@ var _ = math.Inf
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// Config token相关cmd配置
type Config struct {
Whitelist []string `protobuf:"bytes,1,rep,name=whitelist" json:"whitelist,omitempty"`
JrpcBindAddr string `protobuf:"bytes,2,opt,name=jrpcBindAddr" json:"jrpcBindAddr,omitempty"`
......
......@@ -2,6 +2,7 @@ syntax = "proto3";
package signatory;
// Config token相关cmd配置
message Config {
repeated string whitelist = 1;
string jrpcBindAddr = 2;
......
......@@ -20,10 +20,12 @@ import (
var log = l.New("module", "signatory")
// Signatory 签名密钥
type Signatory struct {
Privkey string
}
// Echo echo
func (*Signatory) Echo(in *string, out *interface{}) error {
if in == nil {
return types.ErrInvalidParam
......@@ -32,12 +34,14 @@ func (*Signatory) Echo(in *string, out *interface{}) error {
return nil
}
// TokenFinish token创建完成
type TokenFinish struct {
OwnerAddr string `json:"ownerAddr"`
Symbol string `json:"symbol"`
// Fee int64 `json:"fee"`
}
// SignApprove 完成签名
func (signatory *Signatory) SignApprove(in *TokenFinish, out *interface{}) error {
if in == nil {
return types.ErrInvalidParam
......@@ -48,7 +52,7 @@ func (signatory *Signatory) SignApprove(in *TokenFinish, out *interface{}) error
v := &tokenty.TokenFinishCreate{Symbol: in.Symbol, Owner: in.OwnerAddr}
finish := &tokenty.TokenAction{
Ty: tokenty.TokenActionFinishCreate,
Value: &tokenty.TokenAction_TokenFinishCreate{v},
Value: &tokenty.TokenAction_TokenFinishCreate{TokenFinishCreate: v},
}
tx := &types.Transaction{
......@@ -73,6 +77,7 @@ func (signatory *Signatory) SignApprove(in *TokenFinish, out *interface{}) error
return nil
}
// SignTransfer 签名交易,in 输入要数据 签名out 签名之后数据
func (signatory *Signatory) SignTransfer(in *string, out *interface{}) error {
if in == nil {
return types.ErrInvalidParam
......@@ -88,7 +93,7 @@ func (signatory *Signatory) SignTransfer(in *string, out *interface{}) error {
}
transfer := &cty.CoinsAction{
Ty: cty.CoinsActionTransfer,
Value: &cty.CoinsAction_Transfer{v},
Value: &cty.CoinsAction_Transfer{Transfer: v},
}
tx := &types.Transaction{
......@@ -116,7 +121,7 @@ func (signatory *Signatory) SignTransfer(in *string, out *interface{}) error {
}
func signTx(tx *types.Transaction, hexPrivKey string) error {
c, err := crypto.New(types.GetSignName("", types.SECP256K1))
c, _ := crypto.New(types.GetSignName("", types.SECP256K1))
bytes, err := common.FromHex(hexPrivKey)
if err != nil {
......
......@@ -22,6 +22,7 @@ var (
tokenSymbol string
)
// TokenCmd token 命令行
func TokenCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "token",
......@@ -44,7 +45,7 @@ func TokenCmd() *cobra.Command {
return cmd
}
// create raw transfer tx
// CreateTokenTransferCmd create raw transfer tx
func CreateTokenTransferCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "transfer",
......@@ -81,7 +82,7 @@ func createTokenTransfer(cmd *cobra.Command, args []string) {
fmt.Println(txHex)
}
// create raw withdraw tx
// CreateTokenWithdrawCmd create raw withdraw tx
func CreateTokenWithdrawCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "withdraw",
......@@ -125,7 +126,7 @@ func createTokenWithdraw(cmd *cobra.Command, args []string) {
fmt.Println(txHex)
}
// get precreated tokens
// GetTokensPreCreatedCmd get precreated tokens
func GetTokensPreCreatedCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "get_precreated",
......@@ -171,7 +172,7 @@ func getPreCreatedTokens(cmd *cobra.Command, args []string) {
}
}
// get finish created tokens
// GetTokensFinishCreatedCmd get finish created tokens
func GetTokensFinishCreatedCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "get_finish_created",
......@@ -218,7 +219,7 @@ func getFinishCreatedTokens(cmd *cobra.Command, args []string) {
}
}
// get token assets
// GetTokenAssetsCmd get token assets
func GetTokenAssetsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "token_assets",
......@@ -277,7 +278,7 @@ func parseTokenAssetsRes(arg interface{}) (interface{}, error) {
return result, nil
}
// get token balance
// GetTokenBalanceCmd get token balance
func GetTokenBalanceCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "token_balance",
......@@ -336,7 +337,7 @@ func parseTokenBalanceRes(arg interface{}) (interface{}, error) {
return result, nil
}
// create raw token precreate transaction
// CreateRawTokenPreCreateTxCmd create raw token precreate transaction
func CreateRawTokenPreCreateTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "precreate",
......@@ -391,7 +392,7 @@ func tokenPrecreated(cmd *cobra.Command, args []string) {
ctx.RunWithoutMarshal()
}
// create raw token finish create transaction
// CreateRawTokenFinishTxCmd create raw token finish create transaction
func CreateRawTokenFinishTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "finish",
......@@ -425,7 +426,7 @@ func tokenFinish(cmd *cobra.Command, args []string) {
ctx.RunWithoutMarshal()
}
// create raw token revoke transaction
// CreateRawTokenRevokeTxCmd create raw token revoke transaction
func CreateRawTokenRevokeTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "revoke",
......
......@@ -16,6 +16,7 @@ import (
"github.com/spf13/cobra"
)
// CreateRawTx 创建交易
func CreateRawTx(cmd *cobra.Command, to string, amount float64, note string, isWithdraw bool, tokenSymbol, execName string) (string, error) {
if amount < 0 {
return "", types.ErrAmount
......@@ -51,6 +52,7 @@ func CreateRawTx(cmd *cobra.Command, to string, amount float64, note string, isW
return hex.EncodeToString(txHex), nil
}
// GetExecAddr 获取执行器地址
func GetExecAddr(exec string) (string, error) {
if ok := types.IsAllowExecName([]byte(exec), []byte(exec)); !ok {
return "", types.ErrExecNameNotAllow
......
......@@ -2,22 +2,19 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Package token
主要包含两方面功能
1. token 的创建
1. token 的转账
//Package token
//主要包含两方面功能
// 1. token 的创建
// 1. token 的转账
//
//token的创建
// 1. prepare create
// 1. finish create
// 1. revoke create
//
//token的转账
// 1. transfer
// 1. withdraw
// 1. transfer to exec
token的创建
1. prepare create
1. finish create
1. revoke create
token的转账
1. transfer
1. withdraw
1. transfer to exec
*/
package token
......@@ -19,7 +19,7 @@ func (t *token) Exec_Transfer(payload *types.AssetsTransfer, tx *types.Transacti
tokenAction := tokenty.TokenAction{
Ty: tokenty.ActionTransfer,
Value: &tokenty.TokenAction_Transfer{
payload,
Transfer: payload,
},
}
return t.ExecTransWithdraw(db, tx, &tokenAction, index)
......@@ -34,7 +34,7 @@ func (t *token) Exec_Withdraw(payload *types.AssetsWithdraw, tx *types.Transacti
tokenAction := tokenty.TokenAction{
Ty: tokenty.ActionWithdraw,
Value: &tokenty.TokenAction_Withdraw{
payload,
Withdraw: payload,
},
}
return t.ExecTransWithdraw(db, tx, &tokenAction, index)
......@@ -64,7 +64,7 @@ func (t *token) Exec_TransferToExec(payload *types.AssetsTransferToExec, tx *typ
tokenAction := tokenty.TokenAction{
Ty: tokenty.TokenActionTransferToExec,
Value: &tokenty.TokenAction_TransferToExec{
payload,
TransferToExec: payload,
},
}
return t.ExecTransWithdraw(db, tx, &tokenAction, index)
......
......@@ -35,7 +35,7 @@ func (t *token) ExecDelLocal_Transfer(payload *types.AssetsTransfer, tx *types.T
tokenAction := tokenty.TokenAction{
Ty: tokenty.ActionTransfer,
Value: &tokenty.TokenAction_Transfer{
payload,
Transfer: payload,
},
}
kvs, err := t.makeTokenTxKvs(tx, &tokenAction, receiptData, index, true)
......@@ -56,7 +56,7 @@ func (t *token) ExecDelLocal_Withdraw(payload *types.AssetsWithdraw, tx *types.T
tokenAction := tokenty.TokenAction{
Ty: tokenty.ActionWithdraw,
Value: &tokenty.TokenAction_Withdraw{
payload,
Withdraw: payload,
},
}
kvs, err := t.makeTokenTxKvs(tx, &tokenAction, receiptData, index, true)
......@@ -77,7 +77,7 @@ func (t *token) ExecDelLocal_TransferToExec(payload *types.AssetsTransferToExec,
tokenAction := tokenty.TokenAction{
Ty: tokenty.TokenActionTransferToExec,
Value: &tokenty.TokenAction_TransferToExec{
payload,
TransferToExec: payload,
},
}
kvs, err := t.makeTokenTxKvs(tx, &tokenAction, receiptData, index, true)
......
......@@ -25,7 +25,7 @@ func (t *token) ExecLocal_Transfer(payload *types.AssetsTransfer, tx *types.Tran
tokenAction := tokenty.TokenAction{
Ty: tokenty.ActionTransfer,
Value: &tokenty.TokenAction_Transfer{
payload,
Transfer: payload,
},
}
kvs, err := t.makeTokenTxKvs(tx, &tokenAction, receiptData, index, false)
......@@ -51,7 +51,7 @@ func (t *token) ExecLocal_Withdraw(payload *types.AssetsWithdraw, tx *types.Tran
tokenAction := tokenty.TokenAction{
Ty: tokenty.ActionWithdraw,
Value: &tokenty.TokenAction_Withdraw{
payload,
Withdraw: payload,
},
}
kvs, err := t.makeTokenTxKvs(tx, &tokenAction, receiptData, index, false)
......@@ -72,7 +72,7 @@ func (t *token) ExecLocal_TransferToExec(payload *types.AssetsTransferToExec, tx
tokenAction := tokenty.TokenAction{
Ty: tokenty.TokenActionTransferToExec,
Value: &tokenty.TokenAction_TransferToExec{
payload,
TransferToExec: payload,
},
}
kvs, err := t.makeTokenTxKvs(tx, &tokenAction, receiptData, index, false)
......
......@@ -9,25 +9,28 @@ import (
tokenty "github.com/33cn/plugin/plugin/dapp/token/types"
)
// Query_GetTokens 获取token
func (t *token) Query_GetTokens(in *tokenty.ReqTokens) (types.Message, error) {
if in == nil {
return nil, types.ErrInvalidParam
}
return t.GetTokens(in)
return t.getTokens(in)
}
// Query_GetTokenInfo 获取token信息
func (t *token) Query_GetTokenInfo(in *types.ReqString) (types.Message, error) {
if in == nil {
return nil, types.ErrInvalidParam
}
return t.GetTokenInfo(in.GetData())
return t.getTokenInfo(in.GetData())
}
// Query_GetTotalAmount 获取token总量
func (t *token) Query_GetTotalAmount(in *types.ReqString) (types.Message, error) {
if in == nil {
return nil, types.ErrInvalidParam
}
ret, err := t.GetTokenInfo(in.GetData())
ret, err := t.getTokenInfo(in.GetData())
if err != nil {
return nil, err
}
......@@ -40,20 +43,23 @@ func (t *token) Query_GetTotalAmount(in *types.ReqString) (types.Message, error)
}, nil
}
// Query_GetAddrReceiverforTokens 获取token接受人数据
func (t *token) Query_GetAddrReceiverforTokens(in *tokenty.ReqAddrTokens) (types.Message, error) {
if in == nil {
return nil, types.ErrInvalidParam
}
return t.GetAddrReceiverforTokens(in)
return t.getAddrReceiverforTokens(in)
}
// Query_GetAccountTokenAssets 获取账户的token资产
func (t *token) Query_GetAccountTokenAssets(in *tokenty.ReqAccountTokenAssets) (types.Message, error) {
if in == nil {
return nil, types.ErrInvalidParam
}
return t.GetAccountTokenAssets(in)
return t.getAccountTokenAssets(in)
}
// Query_GetTxByToken 获取token相关交易
func (t *token) Query_GetTxByToken(in *tokenty.ReqTokenTx) (types.Message, error) {
if in == nil {
return nil, types.ErrInvalidParam
......@@ -61,5 +67,5 @@ func (t *token) Query_GetTxByToken(in *tokenty.ReqTokenTx) (types.Message, error
if !cfg.SaveTokenTxList {
return nil, types.ErrActionNotSupport
}
return t.GetTxByToken(in)
return t.getTxByToken(in)
}
......@@ -46,6 +46,7 @@ type subConfig struct {
var cfg subConfig
// Init 重命名执行器名称
func Init(name string, sub []byte) {
if sub != nil {
types.MustDecode(sub, &cfg)
......@@ -53,6 +54,7 @@ func Init(name string, sub []byte) {
drivers.Register(GetName(), newToken, types.GetDappFork(driverName, "Enable"))
}
// GetName 获取执行器别名
func GetName() string {
return newToken().GetName()
}
......@@ -68,16 +70,18 @@ func newToken() drivers.Driver {
return t
}
// GetDriverName 获取执行器名字
func (t *token) GetDriverName() string {
return driverName
}
func (c *token) CheckTx(tx *types.Transaction, index int) error {
// CheckTx ...
func (t *token) CheckTx(tx *types.Transaction, index int) error {
return nil
}
func (t *token) QueryTokenAssetsKey(addr string) (*types.ReplyStrings, error) {
key := CalcTokenAssetsKey(addr)
func (t *token) queryTokenAssetsKey(addr string) (*types.ReplyStrings, error) {
key := calcTokenAssetsKey(addr)
value, err := t.GetLocalDB().Get(key)
if value == nil || err != nil {
tokenlog.Error("tokendb", "GetTokenAssetsKey", types.ErrNotFound)
......@@ -92,9 +96,9 @@ func (t *token) QueryTokenAssetsKey(addr string) (*types.ReplyStrings, error) {
return &assets, nil
}
func (t *token) GetAccountTokenAssets(req *tokenty.ReqAccountTokenAssets) (types.Message, error) {
func (t *token) getAccountTokenAssets(req *tokenty.ReqAccountTokenAssets) (types.Message, error) {
var reply = &tokenty.ReplyAccountTokenAssets{}
assets, err := t.QueryTokenAssetsKey(req.Address)
assets, err := t.queryTokenAssetsKey(req.Address)
if err != nil {
return nil, err
}
......@@ -113,13 +117,13 @@ func (t *token) GetAccountTokenAssets(req *tokenty.ReqAccountTokenAssets) (types
if acc1 == nil {
continue
}
tokenAsset := &tokenty.TokenAsset{asset, acc1}
tokenAsset := &tokenty.TokenAsset{Symbol: asset, Account: acc1}
reply.TokenAssets = append(reply.TokenAssets, tokenAsset)
}
return reply, nil
}
func (t *token) GetAddrReceiverforTokens(addrTokens *tokenty.ReqAddrTokens) (types.Message, error) {
func (t *token) getAddrReceiverforTokens(addrTokens *tokenty.ReqAddrTokens) (types.Message, error) {
var reply = &tokenty.ReplyAddrRecvForTokens{}
db := t.GetLocalDB()
reciver := types.Int64{}
......@@ -133,14 +137,14 @@ func (t *token) GetAddrReceiverforTokens(addrTokens *tokenty.ReqAddrTokens) (typ
continue
}
recv := &tokenty.TokenRecv{token, reciver.Data}
recv := &tokenty.TokenRecv{Token: token, Recv: reciver.Data}
reply.TokenRecvs = append(reply.TokenRecvs, recv)
}
return reply, nil
}
func (t *token) GetTokenInfo(symbol string) (types.Message, error) {
func (t *token) getTokenInfo(symbol string) (types.Message, error) {
if symbol == "" {
return nil, types.ErrInvalidParam
}
......@@ -160,7 +164,7 @@ func (t *token) GetTokenInfo(symbol string) (types.Message, error) {
return &tokenInfo, nil
}
func (t *token) GetTokens(reqTokens *tokenty.ReqTokens) (types.Message, error) {
func (t *token) getTokens(reqTokens *tokenty.ReqTokens) (types.Message, error) {
replyTokens := &tokenty.ReplyTokens{}
tokens, err := t.listTokenKeys(reqTokens)
if err != nil {
......@@ -212,7 +216,7 @@ func (t *token) listTokenKeys(reqTokens *tokenty.ReqTokens) ([][]byte, error) {
}
tokenlog.Debug("token Query GetTokens", "get count", len(keys))
return keys, nil
} else {
}
var keys [][]byte
for _, token := range reqTokens.Tokens {
keys1, err := querydb.List(calcTokenStatusTokenKeyPrefixLocal(reqTokens.Status, token), nil, 0, 0)
......@@ -227,7 +231,6 @@ func (t *token) listTokenKeys(reqTokens *tokenty.ReqTokens) ([][]byte, error) {
return nil, types.ErrNotFound
}
return keys, nil
}
}
// value 对应 statedb 的key
......@@ -241,11 +244,11 @@ func (t *token) saveLogs(receipt *tokenty.ReceiptToken) []*types.KeyValue {
} else {
value = calcTokenAddrKeyS(receipt.Symbol, receipt.Owner)
}
kv = append(kv, &types.KeyValue{key, value})
kv = append(kv, &types.KeyValue{Key: key, Value: value})
//如果当前需要被更新的状态不是Status_PreCreated,则认为之前的状态是precreate,且其对应的key需要被删除
if receipt.Status != tokenty.TokenStatusPreCreated {
key = calcTokenStatusKeyLocal(receipt.Symbol, receipt.Owner, tokenty.TokenStatusPreCreated)
kv = append(kv, &types.KeyValue{key, nil})
kv = append(kv, &types.KeyValue{Key: key, Value: nil})
}
return kv
}
......@@ -254,7 +257,7 @@ func (t *token) deleteLogs(receipt *tokenty.ReceiptToken) []*types.KeyValue {
var kv []*types.KeyValue
key := calcTokenStatusKeyLocal(receipt.Symbol, receipt.Owner, receipt.Status)
kv = append(kv, &types.KeyValue{key, nil})
kv = append(kv, &types.KeyValue{Key: key, Value: nil})
//如果当前需要被更新的状态不是Status_PreCreated,则认为之前的状态是precreate,且其对应的key需要被恢复
if receipt.Status != tokenty.TokenStatusPreCreated {
key = calcTokenStatusKeyLocal(receipt.Symbol, receipt.Owner, tokenty.TokenStatusPreCreated)
......@@ -264,7 +267,7 @@ func (t *token) deleteLogs(receipt *tokenty.ReceiptToken) []*types.KeyValue {
} else {
value = calcTokenAddrKeyS(receipt.Symbol, receipt.Owner)
}
kv = append(kv, &types.KeyValue{key, value})
kv = append(kv, &types.KeyValue{Key: key, Value: value})
}
return kv
}
......@@ -282,7 +285,7 @@ func (t *token) makeTokenTxKvs(tx *types.Transaction, action *tokenty.TokenActio
return kvs, nil
}
kvs, err := TokenTxKvs(tx, symbol, t.GetHeight(), int64(index), isDel)
kvs, err := tokenTxKvs(tx, symbol, t.GetHeight(), int64(index), isDel)
return kvs, err
}
......@@ -290,15 +293,15 @@ func findTokenTxListUtil(req *tokenty.ReqTokenTx) ([]byte, []byte) {
var key, prefix []byte
if len(req.Addr) > 0 {
if req.Flag == 0 {
prefix = CalcTokenAddrTxKey(req.Symbol, req.Addr, -1, 0)
key = CalcTokenAddrTxKey(req.Symbol, req.Addr, req.Height, req.Index)
prefix = calcTokenAddrTxKey(req.Symbol, req.Addr, -1, 0)
key = calcTokenAddrTxKey(req.Symbol, req.Addr, req.Height, req.Index)
} else {
prefix = CalcTokenAddrTxDirKey(req.Symbol, req.Addr, req.Flag, -1, 0)
key = CalcTokenAddrTxDirKey(req.Symbol, req.Addr, req.Flag, req.Height, req.Index)
prefix = calcTokenAddrTxDirKey(req.Symbol, req.Addr, req.Flag, -1, 0)
key = calcTokenAddrTxDirKey(req.Symbol, req.Addr, req.Flag, req.Height, req.Index)
}
} else {
prefix = CalcTokenTxKey(req.Symbol, -1, 0)
key = CalcTokenTxKey(req.Symbol, req.Height, req.Index)
prefix = calcTokenTxKey(req.Symbol, -1, 0)
key = calcTokenTxKey(req.Symbol, req.Height, req.Index)
}
if req.Height == -1 {
key = nil
......@@ -306,7 +309,7 @@ func findTokenTxListUtil(req *tokenty.ReqTokenTx) ([]byte, []byte) {
return key, prefix
}
func (t *token) GetTxByToken(req *tokenty.ReqTokenTx) (types.Message, error) {
func (t *token) getTxByToken(req *tokenty.ReqTokenTx) (types.Message, error) {
if req.Flag != 0 && req.Flag != dapp.TxIndexFrom && req.Flag != dapp.TxIndexTo {
err := types.ErrInvalidParam
return nil, errors.Wrap(err, "flag unknown")
......
......@@ -28,8 +28,8 @@ import (
)
var (
isMainNetTest bool = false
isParaNetTest bool = false
isMainNetTest bool
isParaNetTest bool
)
var (
......@@ -58,7 +58,7 @@ var (
tokenName = "NEW"
tokenSym = "NEW"
tokenIntro = "newtoken"
tokenPrice int64 = 0
tokenPrice int64
tokenAmount int64 = 1000 * 1e4 * 1e4
execName = "user.p.guodun.token"
feeForToken int64 = 1e6
......@@ -164,7 +164,7 @@ func TestPrecreate(t *testing.T) {
}
precreate := &tokenty.TokenAction{
Ty: tokenty.TokenActionPreCreate,
Value: &tokenty.TokenAction_TokenPreCreate{v},
Value: &tokenty.TokenAction_TokenPreCreate{TokenPreCreate: v},
}
tx := &types.Transaction{
Execer: []byte(execName),
......@@ -205,7 +205,7 @@ func TestFinish(t *testing.T) {
v := &tokenty.TokenFinishCreate{Symbol: tokenSym, Owner: addr}
finish := &tokenty.TokenAction{
Ty: tokenty.TokenActionFinishCreate,
Value: &tokenty.TokenAction_TokenFinishCreate{v},
Value: &tokenty.TokenAction_TokenFinishCreate{TokenFinishCreate: v},
}
tx := &types.Transaction{
Execer: []byte(execName),
......@@ -320,7 +320,7 @@ func TestQueryAsset(t *testing.T) {
//**************common actions for Test**************
//***************************************************
func sendtoaddress(c types.Chain33Client, priv crypto.PrivKey, to string, amount int64) ([]byte, error) {
v := &cty.CoinsAction_Transfer{&types.AssetsTransfer{Amount: amount}}
v := &cty.CoinsAction_Transfer{Transfer: &types.AssetsTransfer{Amount: amount}}
transfer := &cty.CoinsAction{Value: v, Ty: cty.CoinsActionTransfer}
tx := &types.Transaction{Execer: []byte("coins"), Payload: types.Encode(transfer), Fee: fee, To: to}
tx.Nonce = r.Int63()
......
......@@ -43,8 +43,8 @@ func (t *tokenDB) save(db dbm.KV, key []byte) {
func (t *tokenDB) getLogs(ty int32, status int32) []*types.ReceiptLog {
var log []*types.ReceiptLog
value := types.Encode(&pty.ReceiptToken{t.token.Symbol, t.token.Owner, t.token.Status})
log = append(log, &types.ReceiptLog{ty, value})
value := types.Encode(&pty.ReceiptToken{Symbol: t.token.Symbol, Owner: t.token.Owner, Status: t.token.Status})
log = append(log, &types.ReceiptLog{Ty: ty, Log: value})
return log
}
......@@ -52,7 +52,7 @@ func (t *tokenDB) getLogs(ty int32, status int32) []*types.ReceiptLog {
//key:mavl-create-token-addr-xxx or mavl-token-xxx <-----> value:token
func (t *tokenDB) getKVSet(key []byte) (kvset []*types.KeyValue) {
value := types.Encode(&t.token)
kvset = append(kvset, &types.KeyValue{key, value})
kvset = append(kvset, &types.KeyValue{Key: key, Value: value})
return kvset
}
......@@ -109,12 +109,12 @@ func (action *tokenAction) preCreate(token *pty.TokenPreCreate) (*types.Receipt,
return nil, pty.ErrTokenTotalOverflow
}
if !ValidSymbolWithHeight([]byte(token.GetSymbol()), action.height) {
if !validSymbolWithHeight([]byte(token.GetSymbol()), action.height) {
tokenlog.Error("token precreate ", "symbol need be upper", token.GetSymbol())
return nil, pty.ErrTokenSymbolUpper
}
if CheckTokenExist(token.GetSymbol(), action.db) {
if checkTokenExist(token.GetSymbol(), action.db) {
return nil, pty.ErrTokenExist
}
......@@ -167,7 +167,7 @@ func (action *tokenAction) preCreate(token *pty.TokenPreCreate) (*types.Receipt,
//tokenlog.Info("func token preCreate", "token:", tokendb.token.Symbol, "owner:", tokendb.token.Owner,
// "key:", key, "key string", string(key), "value:", tokendb.getKVSet(key)[0].Value)
receipt := &types.Receipt{types.ExecOk, kv, logs}
receipt := &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}
return receipt, nil
}
......@@ -242,7 +242,7 @@ func (action *tokenAction) finishCreate(tokenFinish *pty.TokenFinishCreate) (*ty
//因为该token已经被创建,需要保存一个全局的token,防止其他用户再次创建
tokendb.save(action.db, key)
kv = append(kv, tokendb.getKVSet(key)...)
receipt := &types.Receipt{types.ExecOk, kv, logs}
receipt := &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}
return receipt, nil
}
......@@ -297,11 +297,11 @@ func (action *tokenAction) revokeCreate(tokenRevoke *pty.TokenRevokeCreate) (*ty
logs = append(logs, tokendb.getLogs(pty.TyLogRevokeCreateToken, pty.TokenStatusCreateRevoked)...)
kv = append(kv, tokendb.getKVSet(key)...)
receipt := &types.Receipt{types.ExecOk, kv, logs}
receipt := &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}
return receipt, nil
}
func CheckTokenExist(token string, db dbm.KV) bool {
func checkTokenExist(token string, db dbm.KV) bool {
_, err := db.Get(calcTokenKey(token))
return err == nil
}
......@@ -366,12 +366,12 @@ func validOperator(addr, key string, db dbm.KV) (bool, error) {
return false, nil
}
func CalcTokenAssetsKey(addr string) []byte {
func calcTokenAssetsKey(addr string) []byte {
return []byte(fmt.Sprintf(tokenAssetsPrefix+"%s", addr))
}
func GetTokenAssetsKey(addr string, db dbm.KVDB) (*types.ReplyStrings, error) {
key := CalcTokenAssetsKey(addr)
func getTokenAssetsKey(addr string, db dbm.KVDB) (*types.ReplyStrings, error) {
key := calcTokenAssetsKey(addr)
value, err := db.Get(key)
if err != nil && err != types.ErrNotFound {
tokenlog.Error("tokendb", "GetTokenAssetsKey", err)
......@@ -389,8 +389,9 @@ func GetTokenAssetsKey(addr string, db dbm.KVDB) (*types.ReplyStrings, error) {
return &assets, nil
}
// AddTokenToAssets 添加个人资产列表
func AddTokenToAssets(addr string, db dbm.KVDB, symbol string) []*types.KeyValue {
tokenAssets, err := GetTokenAssetsKey(addr, db)
tokenAssets, err := getTokenAssetsKey(addr, db)
if err != nil {
return nil
}
......@@ -409,7 +410,7 @@ func AddTokenToAssets(addr string, db dbm.KVDB, symbol string) []*types.KeyValue
tokenAssets.Datas = append(tokenAssets.Datas, symbol)
}
var kv []*types.KeyValue
kv = append(kv, &types.KeyValue{CalcTokenAssetsKey(addr), types.Encode(tokenAssets)})
kv = append(kv, &types.KeyValue{Key: calcTokenAssetsKey(addr), Value: types.Encode(tokenAssets)})
return kv
}
......@@ -418,25 +419,25 @@ func inBlacklist(symbol, key string, db dbm.KV) (bool, error) {
return found, err
}
func IsUpperChar(a byte) bool {
func isUpperChar(a byte) bool {
res := (a <= 'Z' && a >= 'A')
return res
}
func ValidSymbol(cs []byte) bool {
func validSymbol(cs []byte) bool {
for _, c := range cs {
if !IsUpperChar(c) {
if !isUpperChar(c) {
return false
}
}
return true
}
func ValidSymbolWithHeight(cs []byte, height int64) bool {
func validSymbolWithHeight(cs []byte, height int64) bool {
if !types.IsDappFork(height, pty.TokenX, "ForkBadTokenSymbol") {
symbol := string(cs)
upSymbol := strings.ToUpper(symbol)
return upSymbol == symbol
}
return ValidSymbol(cs)
return validSymbol(cs)
}
......@@ -19,7 +19,7 @@ const (
tokenTxAddrDirPrefix = "LODB-token-txAddrDirHash:"
)
func TokenTxKvs(tx *types.Transaction, symbol string, height, index int64, isDel bool) ([]*types.KeyValue, error) {
func tokenTxKvs(tx *types.Transaction, symbol string, height, index int64, isDel bool) ([]*types.KeyValue, error) {
var kv []*types.KeyValue
from := address.PubKeyToAddress(tx.GetSignature().GetPubkey()).String()
......@@ -31,45 +31,45 @@ func TokenTxKvs(tx *types.Transaction, symbol string, height, index int64, isDel
txInfo = makeReplyTxInfo(tx, height, index, symbol)
}
for _, k := range keys {
kv = append(kv, &types.KeyValue{k, txInfo})
kv = append(kv, &types.KeyValue{Key: k, Value: txInfo})
}
return kv, nil
}
func tokenTxkeys(symbol, from, to string, height, index int64) (result [][]byte) {
key := CalcTokenTxKey(symbol, height, index)
key := calcTokenTxKey(symbol, height, index)
result = append(result, key)
if len(from) > 0 {
fromKey1 := CalcTokenAddrTxKey(symbol, from, height, index)
fromKey2 := CalcTokenAddrTxDirKey(symbol, from, dapp.TxIndexFrom, height, index)
fromKey1 := calcTokenAddrTxKey(symbol, from, height, index)
fromKey2 := calcTokenAddrTxDirKey(symbol, from, dapp.TxIndexFrom, height, index)
result = append(result, fromKey1)
result = append(result, fromKey2)
}
if len(to) > 0 {
toKey1 := CalcTokenAddrTxKey(symbol, to, height, index)
toKey2 := CalcTokenAddrTxDirKey(symbol, to, dapp.TxIndexTo, height, index)
toKey1 := calcTokenAddrTxKey(symbol, to, height, index)
toKey2 := calcTokenAddrTxDirKey(symbol, to, dapp.TxIndexTo, height, index)
result = append(result, toKey1)
result = append(result, toKey2)
}
return
}
// token transaction entities in local DB
func CalcTokenTxKey(symbol string, height, index int64) []byte {
// calcTokenTxKey token transaction entities in local DB
func calcTokenTxKey(symbol string, height, index int64) []byte {
if height == -1 {
return []byte(fmt.Sprintf(tokenTxPrefix+"%s:%s", symbol, ""))
}
return []byte(fmt.Sprintf(tokenTxPrefix+"%s:%s", symbol, dapp.HeightIndexStr(height, index)))
}
func CalcTokenAddrTxKey(symbol, addr string, height, index int64) []byte {
func calcTokenAddrTxKey(symbol, addr string, height, index int64) []byte {
if height == -1 {
return []byte(fmt.Sprintf(tokenTxAddrPrefix+"%s:%s:%s", symbol, addr, ""))
}
return []byte(fmt.Sprintf(tokenTxAddrPrefix+"%s:%s:%s", symbol, addr, dapp.HeightIndexStr(height, index)))
}
func CalcTokenAddrTxDirKey(symbol, addr string, flag int32, height, index int64) []byte {
func calcTokenAddrTxDirKey(symbol, addr string, flag int32, height, index int64) []byte {
if height == -1 {
return []byte(fmt.Sprintf(tokenTxAddrDirPrefix+"%s:%s:%d:%s", symbol, addr, flag, ""))
}
......
......@@ -40,9 +40,8 @@ func (t *token) ExecTransWithdraw(accountDB *account.DB, tx *types.Transaction,
return accountDB.GenesisInitExec(genesis.ReturnAddress, genesis.Amount, tx.GetRealToAddr())
}
return accountDB.GenesisInit(tx.GetRealToAddr(), genesis.Amount)
} else {
return nil, types.ErrReRunGenesis
}
return nil, types.ErrReRunGenesis
} else if action.Ty == tokenty.TokenActionTransferToExec && action.GetTransferToExec() != nil {
if !types.IsFork(t.GetHeight(), "ForkTransferExec") {
return nil, types.ErrActionNotSupport
......@@ -136,9 +135,9 @@ func (t *token) ExecDelLocalLocalTransWithdraw(tx *types.Transaction, receipt *t
}
func getAddrReciverKV(token string, addr string, reciverAmount int64) *types.KeyValue {
reciver := &types.Int64{reciverAmount}
reciver := &types.Int64{Data: reciverAmount}
amountbytes := types.Encode(reciver)
kv := &types.KeyValue{calcAddrKey(token, addr), amountbytes}
kv := &types.KeyValue{Key: calcAddrKey(token, addr), Value: amountbytes}
return kv
}
......
......@@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package token 创建token
package token
import (
......
......@@ -57,6 +57,7 @@ func (c *channelClient) getTokenBalance(in *tokenty.ReqTokenBalance) ([]*types.A
}
}
// GetTokenBalance 获取token金额(channelClient)
func (c *channelClient) GetTokenBalance(ctx context.Context, in *tokenty.ReqTokenBalance) (*types.Accounts, error) {
reply, err := c.getTokenBalance(in)
if err != nil {
......@@ -65,6 +66,7 @@ func (c *channelClient) GetTokenBalance(ctx context.Context, in *tokenty.ReqToke
return &types.Accounts{Acc: reply}, nil
}
// GetTokenBalance 获取token金额 (Jrpc)
func (c *Jrpc) GetTokenBalance(in tokenty.ReqTokenBalance, result *interface{}) error {
balances, err := c.cli.GetTokenBalance(context.Background(), &in)
if err != nil {
......@@ -81,6 +83,7 @@ func (c *Jrpc) GetTokenBalance(in tokenty.ReqTokenBalance, result *interface{})
return nil
}
// CreateRawTokenPreCreateTx 创建未签名的创建Token交易
func (c *Jrpc) CreateRawTokenPreCreateTx(param *tokenty.TokenPreCreate, result *interface{}) error {
if param == nil || param.Symbol == "" {
return types.ErrInvalidParam
......@@ -93,6 +96,7 @@ func (c *Jrpc) CreateRawTokenPreCreateTx(param *tokenty.TokenPreCreate, result *
return nil
}
// CreateRawTokenFinishTx 创建未签名的结束Token交易
func (c *Jrpc) CreateRawTokenFinishTx(param *tokenty.TokenFinishCreate, result *interface{}) error {
if param == nil || param.Symbol == "" {
return types.ErrInvalidParam
......@@ -105,6 +109,7 @@ func (c *Jrpc) CreateRawTokenFinishTx(param *tokenty.TokenFinishCreate, result *
return nil
}
// CreateRawTokenRevokeTx 创建未签名的撤销Token交易
func (c *Jrpc) CreateRawTokenRevokeTx(param *tokenty.TokenRevokeCreate, result *interface{}) error {
if param == nil || param.Symbol == "" {
return types.ErrInvalidParam
......
......@@ -27,7 +27,7 @@ func newTestJrpcClient() *Jrpc {
return &Jrpc{cli: newTestChannelClient()}
}
func testChannelClient_GetTokenBalanceToken(t *testing.T) {
func testChannelClientGetTokenBalanceToken(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := &channelClient{
......@@ -57,7 +57,7 @@ func testChannelClient_GetTokenBalanceToken(t *testing.T) {
}
func testChannelClient_GetTokenBalanceOther(t *testing.T) {
func testChannelClientGetTokenBalanceOther(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := &channelClient{
ChannelClient: rpctypes.ChannelClient{QueueProtocolAPI: api},
......@@ -86,13 +86,13 @@ func testChannelClient_GetTokenBalanceOther(t *testing.T) {
}
func TestChannelClient_GetTokenBalance(t *testing.T) {
testChannelClient_GetTokenBalanceToken(t)
testChannelClient_GetTokenBalanceOther(t)
func TestChannelClientGetTokenBalance(t *testing.T) {
testChannelClientGetTokenBalanceToken(t)
testChannelClientGetTokenBalanceOther(t)
}
func TestChannelClient_CreateRawTokenPreCreateTx(t *testing.T) {
func TestChannelClientCreateRawTokenPreCreateTx(t *testing.T) {
client := newTestJrpcClient()
var data interface{}
err := client.CreateRawTokenPreCreateTx(nil, &data)
......@@ -108,7 +108,7 @@ func TestChannelClient_CreateRawTokenPreCreateTx(t *testing.T) {
assert.Nil(t, err)
}
func TestChannelClient_CreateRawTokenRevokeTx(t *testing.T) {
func TestChannelClientCreateRawTokenRevokeTx(t *testing.T) {
client := newTestJrpcClient()
var data interface{}
err := client.CreateRawTokenRevokeTx(nil, &data)
......@@ -124,7 +124,7 @@ func TestChannelClient_CreateRawTokenRevokeTx(t *testing.T) {
assert.Nil(t, err)
}
func TestChannelClient_CreateRawTokenFinishTx(t *testing.T) {
func TestChannelClientCreateRawTokenFinishTx(t *testing.T) {
client := newTestJrpcClient()
var data interface{}
err := client.CreateRawTokenFinishTx(nil, &data)
......
......@@ -11,10 +11,12 @@ import (
var log = log15.New("module", "token.rpc")
// Jrpc json rpc struct
type Jrpc struct {
cli *channelClient
}
// Grpc grpc struct
type Grpc struct {
*channelClient
}
......@@ -23,6 +25,7 @@ type channelClient struct {
types.ChannelClient
}
// Init init grpc param
func Init(name string, s types.RPCServer) {
cli := &channelClient{}
grpc := &Grpc{channelClient: cli}
......
......@@ -5,45 +5,71 @@
package types
const (
//action for token
// ActionTransfer for transfer
ActionTransfer = 4
// ActionGenesis for genesis
ActionGenesis = 5
// ActionWithdraw for Withdraw
ActionWithdraw = 6
// TokenActionPreCreate for token pre create
TokenActionPreCreate = 7
// TokenActionFinishCreate for token finish create
TokenActionFinishCreate = 8
// TokenActionRevokeCreate for token revoke create
TokenActionRevokeCreate = 9
// TokenActionTransferToExec for token transfer to exec
TokenActionTransferToExec = 11
)
// token status
const (
// TokenStatusPreCreated token pre create status
TokenStatusPreCreated = iota
// TokenStatusCreated token create status
TokenStatusCreated
// TokenStatusCreateRevoked token revoke status
TokenStatusCreateRevoked
)
var (
// TokenX token name
TokenX = "token"
)
const (
// TyLogPreCreateToken log for pre create token
TyLogPreCreateToken = 211
// TyLogFinishCreateToken log for finish create token
TyLogFinishCreateToken = 212
// TyLogRevokeCreateToken log for revoke create token
TyLogRevokeCreateToken = 213
// TyLogTokenTransfer log for token tranfer
TyLogTokenTransfer = 313
// TyLogTokenGenesis log for token genesis
TyLogTokenGenesis = 314
// TyLogTokenDeposit log for token deposit
TyLogTokenDeposit = 315
// TyLogTokenExecTransfer log for token exec transfer
TyLogTokenExecTransfer = 316
// TyLogTokenExecWithdraw log for token exec withdraw
TyLogTokenExecWithdraw = 317
// TyLogTokenExecDeposit log for token exec deposit
TyLogTokenExecDeposit = 318
// TyLogTokenExecFrozen log for token exec frozen
TyLogTokenExecFrozen = 319
// TyLogTokenExecActive log for token exec active
TyLogTokenExecActive = 320
// TyLogTokenGenesisTransfer log for token genesis rransfer
TyLogTokenGenesisTransfer = 321
// TyLogTokenGenesisDeposit log for token genesis deposit
TyLogTokenGenesisDeposit = 322
)
const (
// TokenNameLenLimit token name length limit
TokenNameLenLimit = 128
// TokenSymbolLenLimit token symbol length limit
TokenSymbolLenLimit = 16
// TokenIntroLenLimit token introduction length limit
TokenIntroLenLimit = 1024
)
......@@ -7,18 +7,32 @@ package types
import "errors"
var (
// ErrTokenNameLen error token name length
ErrTokenNameLen = errors.New("ErrTokenNameLength")
// ErrTokenSymbolLen error token symbol length
ErrTokenSymbolLen = errors.New("ErrTokenSymbolLength")
// ErrTokenTotalOverflow error token total Overflow
ErrTokenTotalOverflow = errors.New("ErrTokenTotalOverflow")
// ErrTokenSymbolUpper error token total Overflow
ErrTokenSymbolUpper = errors.New("ErrTokenSymbolUpper")
// ErrTokenIntroLen error token introduction length
ErrTokenIntroLen = errors.New("ErrTokenIntroductionLen")
// ErrTokenExist error token symbol exist already
ErrTokenExist = errors.New("ErrTokenSymbolExistAlready")
// ErrTokenNotPrecreated error token not pre created
ErrTokenNotPrecreated = errors.New("ErrTokenNotPrecreated")
// ErrTokenCreatedApprover error token created approver
ErrTokenCreatedApprover = errors.New("ErrTokenCreatedApprover")
// ErrTokenRevoker error token revoker
ErrTokenRevoker = errors.New("ErrTokenRevoker")
// ErrTokenCanotRevoked error token canot revoked with wrong status
ErrTokenCanotRevoked = errors.New("ErrTokenCanotRevokedWithWrongStatus")
// ErrTokenOwner error token symbol owner not match
ErrTokenOwner = errors.New("ErrTokenSymbolOwnerNotMatch")
// ErrTokenHavePrecreated error owner have token pre create yet
ErrTokenHavePrecreated = errors.New("ErrOwnerHaveTokenPrecreateYet")
// ErrTokenBlacklist error token blacklist
ErrTokenBlacklist = errors.New("ErrTokenBlacklist")
// ErrTokenNotExist error token symbol not exist
ErrTokenNotExist = errors.New("ErrTokenSymbolNotExist")
)
......@@ -4,6 +4,7 @@
package types
// TokenAccountResult about token account result
type TokenAccountResult struct {
Token string `json:"Token,omitempty"`
Currency int32 `json:"currency,omitempty"`
......
......@@ -19,21 +19,24 @@ func init() {
types.RegisterDappFork(TokenX, "ForkTokenPrice", 560000)
}
// exec
// TokenType 执行器基类结构体
type TokenType struct {
types.ExecTypeBase
}
// NewType 创建执行器类型
func NewType() *TokenType {
c := &TokenType{}
c.SetChild(c)
return c
}
// GetPayload 获取token action
func (t *TokenType) GetPayload() types.Message {
return &TokenAction{}
}
// GetTypeMap 根据action的name获取type
func (t *TokenType) GetTypeMap() map[string]int32 {
return map[string]int32{
"Transfer": ActionTransfer,
......@@ -46,6 +49,7 @@ func (t *TokenType) GetTypeMap() map[string]int32 {
}
}
// GetLogMap 获取log的映射对应关系
func (t *TokenType) GetLogMap() map[int64]*types.LogInfo {
return map[int64]*types.LogInfo{
TyLogTokenTransfer: {reflect.TypeOf(types.ReceiptAccountTransfer{}), "LogTokenTransfer"},
......@@ -63,6 +67,7 @@ func (t *TokenType) GetLogMap() map[int64]*types.LogInfo {
}
}
// RPC_Default_Process rpc 默认处理
func (t *TokenType) RPC_Default_Process(action string, msg interface{}) (*types.Transaction, error) {
var create *types.CreateTx
if _, ok := msg.(*types.CreateTx); !ok {
......
......@@ -36,10 +36,6 @@ var secureKeyPrefix = []byte("secure-key-")
// secureKeyLength is the length of the above prefix + 32byte hash.
const secureKeyLength = 11 + 32
// Code using batches should try to add this much data to the batch.
// The value was determined empirically.
const IdealBatchSize = 100 * 1024
// rawNode is a simple binary blob used to differentiate between collapsed trie
// nodes and already encoded RLP binary blobs (while at the same time store them
// in the same cache fields).
......
......@@ -39,9 +39,13 @@ type node interface {
}
const (
// TyFullNode 全节点类型
TyFullNode = 1
// TyShortNode 扩展节点类型
TyShortNode = 2
// TyHashNode hash节点类型
TyHashNode = 3
// TyValueNode value节点类型
TyValueNode = 4
)
......
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Code generated by protoc-gen-go.
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: node.proto
// DO NOT EDIT!
/*
Package mpt is a generated protocol buffer package.
......@@ -36,6 +31,7 @@ var _ = math.Inf
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
// Node mpt涉及到的node类型由四种基本类型
type Node struct {
// Types that are valid to be assigned to Value:
// *Node_Full
......@@ -235,6 +231,7 @@ func _Node_OneofSizer(msg proto.Message) (n int) {
return n
}
// FullNode 分支节点
type FullNode struct {
Nodes []*Node `protobuf:"bytes,1,rep,name=nodes" json:"nodes,omitempty"`
}
......@@ -251,6 +248,7 @@ func (m *FullNode) GetNodes() []*Node {
return nil
}
// ShortNode 扩展/叶子节点
type ShortNode struct {
Key []byte `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
Val *Node `protobuf:"bytes,2,opt,name=val" json:"val,omitempty"`
......@@ -275,6 +273,7 @@ func (m *ShortNode) GetVal() *Node {
return nil
}
// HashNode hash节点
type HashNode struct {
Hash []byte `protobuf:"bytes,1,opt,name=hash,proto3" json:"hash,omitempty"`
}
......@@ -291,6 +290,7 @@ func (m *HashNode) GetHash() []byte {
return nil
}
// ValueNode value节点
type ValueNode struct {
Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
}
......@@ -319,7 +319,7 @@ func init() { proto.RegisterFile("node.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 264 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x4c, 0x51, 0xc1, 0x4a, 0xc3, 0x40,
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x51, 0xc1, 0x4a, 0xc3, 0x40,
0x10, 0x75, 0xb3, 0xd9, 0xda, 0x4c, 0xb5, 0xc8, 0xe0, 0x61, 0x41, 0xd0, 0xb8, 0x82, 0x04, 0x84,
0x1c, 0xea, 0xcd, 0xa3, 0x07, 0xe9, 0xc9, 0x43, 0x2c, 0xde, 0x23, 0x59, 0x89, 0xb8, 0xed, 0x86,
0x26, 0x29, 0xf6, 0x1b, 0xfd, 0xa9, 0x32, 0xbb, 0x9b, 0x90, 0xdb, 0xce, 0x7b, 0x6f, 0xde, 0xbc,
......
......@@ -2,6 +2,7 @@ syntax = "proto3";
package mpt;
// Node mpt涉及到的node类型由四种基本类型
message Node {
oneof value {
FullNode full = 2;
......@@ -13,19 +14,23 @@ message Node {
int32 index = 6;
}
// FullNode 分支节点
message FullNode {
repeated Node nodes = 1;
}
// ShortNode 扩展/叶子节点
message ShortNode {
bytes key = 1;
Node val = 2;
}
// HashNode hash节点
message HashNode {
bytes hash = 1;
}
// ValueNode value节点
message ValueNode {
bytes value = 1;
}
......@@ -27,6 +27,7 @@ import (
)
const (
// HashLength hash长度32字节
HashLength = 32
)
......
......@@ -18,7 +18,7 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// Package trie implements Merkle Patricia Tries.
// Package mpt implements Merkle Patricia Tries.
package mpt
import (
......@@ -468,6 +468,7 @@ func (t *Trie) hashRoot(db *Database, onleaf LeafCallback) (node, node, error) {
return h.hash(t.root, db, true)
}
// Commit2Db 保存tire数据到db
func (t *Trie) Commit2Db(node common.Hash, report bool) error {
err := t.db.Commit(node, report)
if nil != err {
......@@ -477,10 +478,12 @@ func (t *Trie) Commit2Db(node common.Hash, report bool) error {
return nil
}
// TrieEx Trie扩展,可以相应enableSecure
type TrieEx struct {
*Trie
}
// NewEx creates a trie
func NewEx(root common.Hash, db *Database) (*TrieEx, error) {
trie, err := New(root, db)
if nil == err {
......@@ -492,6 +495,7 @@ func NewEx(root common.Hash, db *Database) (*TrieEx, error) {
return trieEx, err
}
// Get returns the value for key stored in the trie
func (t *TrieEx) Get(key []byte) []byte {
res, err := t.TryGet(key)
if err != nil {
......@@ -500,6 +504,7 @@ func (t *TrieEx) Get(key []byte) []byte {
return res
}
// TryGet returns the value for key stored in the trie.
func (t *TrieEx) TryGet(key []byte) ([]byte, error) {
if enableSecure {
key = common.ShaKeccak256(key)
......@@ -507,12 +512,14 @@ func (t *TrieEx) TryGet(key []byte) ([]byte, error) {
return t.Trie.TryGet(key)
}
// Update set key with value in the trie
func (t *TrieEx) Update(key, value []byte) {
if err := t.TryUpdate(key, value); err != nil {
mptlog.Error(fmt.Sprintf("Unhandled trie error: %v", err))
}
}
// TryUpdate set key with value in the trie
func (t *TrieEx) TryUpdate(key, value []byte) error {
if enableSecure {
key = common.ShaKeccak256(key)
......@@ -520,12 +527,14 @@ func (t *TrieEx) TryUpdate(key, value []byte) error {
return t.Trie.TryUpdate(key, value)
}
// Delete removes any existing value for key from the trie.
func (t *TrieEx) Delete(key []byte) {
if err := t.TryDelete(key); err != nil {
mptlog.Error(fmt.Sprintf("Unhandled trie error: %v", err))
}
}
// TryDelete removes any existing value for key from the trie.
func (t *TrieEx) TryDelete(key []byte) error {
if enableSecure {
key = common.ShaKeccak256(key)
......@@ -533,15 +542,17 @@ func (t *TrieEx) TryDelete(key []byte) error {
return t.Trie.TryDelete(key)
}
// Commit writes all nodes to the trie's memory database
func (t *TrieEx) Commit(onleaf LeafCallback) (root common.Hash, err error) {
return t.Trie.Commit(onleaf)
}
// Commit2Db writes all nodes to the trie's database
func (t *TrieEx) Commit2Db(node common.Hash, report bool) error {
return t.Trie.Commit2Db(node, report)
}
//对外接口
// SetKVPair set key value 的对外接口
func SetKVPair(db dbm.DB, storeSet *types.StoreSet, sync bool) ([]byte, error) {
var err error
var trie *TrieEx
......@@ -567,6 +578,7 @@ func SetKVPair(db dbm.DB, storeSet *types.StoreSet, sync bool) ([]byte, error) {
return hashByte, nil
}
// GetKVPair get values by keys, return values and error
func GetKVPair(db dbm.DB, storeGet *types.StoreGet) ([][]byte, error) {
var err error
var trie *TrieEx
......@@ -585,6 +597,7 @@ func GetKVPair(db dbm.DB, storeGet *types.StoreGet) ([][]byte, error) {
return values, nil
}
// GetKVPairProof 获取指定k:v pair的proof证明
func GetKVPairProof(db dbm.DB, roothash []byte, key []byte) []byte {
if enableSecure {
key = common.ShaKeccak256(key)
......@@ -596,7 +609,7 @@ func GetKVPairProof(db dbm.DB, roothash []byte, key []byte) []byte {
return value
}
//剔除key对应的节点在本次tree中,返回新的roothash和key对应的value
// DelKVPair 剔除key对应的节点在本次tree中,返回新的roothash和key对应的value
func DelKVPair(db dbm.DB, storeDel *types.StoreGet) ([]byte, [][]byte, error) {
var err error
var trie *TrieEx
......@@ -626,6 +639,7 @@ func DelKVPair(db dbm.DB, storeDel *types.StoreGet) ([]byte, [][]byte, error) {
return hashByte, values, nil
}
// VerifyKVPairProof 验证KVPair 的证明
func VerifyKVPairProof(db dbm.DB, roothash []byte, keyvalue types.KeyValue, proof []byte) bool {
if enableSecure {
keyvalue.Key = common.ShaKeccak256(keyvalue.Key)
......@@ -634,6 +648,7 @@ func VerifyKVPairProof(db dbm.DB, roothash []byte, keyvalue types.KeyValue, proo
return nil == err
}
// IterateRangeByStateHash 迭代实现功能; statehash:当前状态hash, start:开始查找的key, end: 结束的key, ascending:升序,降序, fn 迭代回调函数
func IterateRangeByStateHash(db dbm.DB, statehash, start, end []byte, ascending bool, fn func([]byte, []byte) bool) {
var err error
var trie *TrieEx
......
......@@ -37,7 +37,7 @@ var secureKeyPrefix = []byte("secure-key-")
// secureKeyLength is the length of the above prefix + 32byte hash.
const secureKeyLength = 11 + 32
// Code using batches should try to add this much data to the batch.
// IdealBatchSize Code using batches should try to add this much data to the batch.
// The value was determined empirically.
const IdealBatchSize = 100 * 1024
......
......@@ -33,17 +33,23 @@ import (
)
var (
// EOL is returned when the end of the current list
// ErrFoo is returned when the end of the current list
// has been reached during streaming.
EOL = errors.New("rlp: end of list")
ErrFoo = errors.New("rlp: end of list")
// Actual Errors
// ErrExpectedString expected String or Byte
ErrExpectedString = errors.New("rlp: expected String or Byte")
// ErrExpectedList expected List
ErrExpectedList = errors.New("rlp: expected List")
// ErrCanonInt non-canonical integer format
ErrCanonInt = errors.New("rlp: non-canonical integer format")
// ErrCanonSize non-canonical size information
ErrCanonSize = errors.New("rlp: non-canonical size information")
// ErrElemTooLarge element is larger than containing list
ErrElemTooLarge = errors.New("rlp: element is larger than containing list")
// ErrValueTooLarge value size exceeds available input length
ErrValueTooLarge = errors.New("rlp: value size exceeds available input length")
// ErrMoreThanOneValue input contains more than one value
ErrMoreThanOneValue = errors.New("rlp: input contains more than one value")
// internal errors
......@@ -356,7 +362,7 @@ func decodeSliceElems(s *Stream, val reflect.Value, elemdec decoder) error {
val.SetLen(i + 1)
}
// decode into element
if err := elemdec(s, val.Index(i)); err == EOL {
if err := elemdec(s, val.Index(i)); err == ErrFoo {
break
} else if err != nil {
return addErrorContext(err, fmt.Sprint("[", i, "]"))
......@@ -375,7 +381,7 @@ func decodeListArray(s *Stream, val reflect.Value, elemdec decoder) error {
vlen := val.Len()
i := 0
for ; i < vlen; i++ {
if err := elemdec(s, val.Index(i)); err == EOL {
if err := elemdec(s, val.Index(i)); err == ErrFoo {
break
} else if err != nil {
return addErrorContext(err, fmt.Sprint("[", i, "]"))
......@@ -444,7 +450,7 @@ func makeStructDecoder(typ reflect.Type) (decoder, error) {
}
for _, f := range fields {
err := f.info.decoder(s, val.Field(f.index))
if err == EOL {
if err == ErrFoo {
return &decodeError{msg: "too few elements", typ: typ}
} else if err != nil {
return addErrorContext(err, "."+typ.Field(f.index).Name)
......@@ -557,8 +563,11 @@ func decodeDecoder(s *Stream, val reflect.Value) error {
type Kind int
const (
// Byte RLP 编码类型 byte
Byte Kind = iota
// String RLP 编码类型 string
String
// List RLP 编码类型 list
List
)
......@@ -880,7 +889,7 @@ func (s *Stream) Kind() (kind Kind, size uint64, err error) {
// Don't read further if we're at the end of the
// innermost list.
if tos != nil && tos.pos == tos.size {
return 0, 0, EOL
return 0, 0, ErrFoo
}
s.kind, s.size, s.kinderr = s.readKind()
if s.kinderr == nil {
......
......@@ -109,9 +109,9 @@ func TestStreamErrors(t *testing.T) {
{"89000000000000000001", calls{"Uint"}, nil, errUintOverflow},
{"00", calls{"List"}, nil, ErrExpectedList},
{"80", calls{"List"}, nil, ErrExpectedList},
{"C0", calls{"List", "Uint"}, nil, EOL},
{"C0", calls{"List", "Uint"}, nil, ErrFoo},
{"C8C9010101010101010101", calls{"List", "Kind"}, nil, ErrElemTooLarge},
{"C3C2010201", calls{"List", "List", "Uint", "Uint", "ListEnd", "Uint"}, nil, EOL},
{"C3C2010201", calls{"List", "List", "Uint", "Uint", "ListEnd", "Uint"}, nil, ErrFoo},
{"00", calls{"ListEnd"}, nil, errNotInList},
{"C401020304", calls{"List", "Uint", "ListEnd"}, nil, errNotAtEOL},
......@@ -194,7 +194,7 @@ func TestStreamErrors(t *testing.T) {
"Bytes", // past final element
"Bytes", // this one should fail
}, nil, EOL},
}, nil, ErrFoo},
}
testfor:
......@@ -251,8 +251,8 @@ func TestStreamList(t *testing.T) {
}
}
if _, err := s.Uint(); err != EOL {
t.Errorf("Uint error mismatch, got %v, want %v", err, EOL)
if _, err := s.Uint(); err != ErrFoo {
t.Errorf("Uint error mismatch, got %v, want %v", err, ErrFoo)
}
if err = s.ListEnd(); err != nil {
t.Fatalf("ListEnd error: %v", err)
......
......@@ -29,9 +29,11 @@ import (
)
var (
// EmptyString rlp definition
// Common encoded values.
// These are useful when implementing EncodeRLP.
EmptyString = []byte{0x80}
// EmptyList rlp definition
EmptyList = []byte{0xC0}
)
......
......@@ -27,6 +27,7 @@ import (
)
const (
// HashLength hash长度32字节
HashLength = 32
)
......
......@@ -18,7 +18,7 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// Package trie implements Merkle Patricia Tries.
// Package mpt implements Merkle Patricia Tries.
package mpt
import (
......@@ -468,6 +468,7 @@ func (t *Trie) hashRoot(db *Database, onleaf LeafCallback) (node, node, error) {
return h.hash(t.root, db, true)
}
// Commit2Db 保存tire数据到db
func (t *Trie) Commit2Db(node common.Hash, report bool) error {
err := t.db.Commit(node, report)
if nil != err {
......@@ -477,10 +478,12 @@ func (t *Trie) Commit2Db(node common.Hash, report bool) error {
return nil
}
// TrieEx Trie扩展,可以相应enableSecure
type TrieEx struct {
*Trie
}
// NewEx creates a trie
func NewEx(root common.Hash, db *Database) (*TrieEx, error) {
trie, err := New(root, db)
if nil == err {
......@@ -492,6 +495,7 @@ func NewEx(root common.Hash, db *Database) (*TrieEx, error) {
return trieEx, err
}
// Get returns the value for key stored in the trie
func (t *TrieEx) Get(key []byte) []byte {
res, err := t.TryGet(key)
if err != nil {
......@@ -500,6 +504,7 @@ func (t *TrieEx) Get(key []byte) []byte {
return res
}
// TryGet returns the value for key stored in the trie.
func (t *TrieEx) TryGet(key []byte) ([]byte, error) {
if enableSecure {
key = common.ShaKeccak256(key)
......@@ -507,12 +512,14 @@ func (t *TrieEx) TryGet(key []byte) ([]byte, error) {
return t.Trie.TryGet(key)
}
// Update set key with value in the trie
func (t *TrieEx) Update(key, value []byte) {
if err := t.TryUpdate(key, value); err != nil {
mptlog.Error(fmt.Sprintf("Unhandled trie error: %v", err))
}
}
// TryUpdate set key with value in the trie
func (t *TrieEx) TryUpdate(key, value []byte) error {
if enableSecure {
key = common.ShaKeccak256(key)
......@@ -520,12 +527,14 @@ func (t *TrieEx) TryUpdate(key, value []byte) error {
return t.Trie.TryUpdate(key, value)
}
// Delete removes any existing value for key from the trie.
func (t *TrieEx) Delete(key []byte) {
if err := t.TryDelete(key); err != nil {
mptlog.Error(fmt.Sprintf("Unhandled trie error: %v", err))
}
}
// TryDelete removes any existing value for key from the trie.
func (t *TrieEx) TryDelete(key []byte) error {
if enableSecure {
key = common.ShaKeccak256(key)
......@@ -533,15 +542,17 @@ func (t *TrieEx) TryDelete(key []byte) error {
return t.Trie.TryDelete(key)
}
// Commit writes all nodes to the trie's memory database
func (t *TrieEx) Commit(onleaf LeafCallback) (root common.Hash, err error) {
return t.Trie.Commit(onleaf)
}
// Commit2Db writes all nodes to the trie's database
func (t *TrieEx) Commit2Db(node common.Hash, report bool) error {
return t.Trie.Commit2Db(node, report)
}
//对外接口
// SetKVPair set key value 的对外接口
func SetKVPair(db dbm.DB, storeSet *types.StoreSet, sync bool) ([]byte, error) {
var err error
var trie *TrieEx
......@@ -567,6 +578,7 @@ func SetKVPair(db dbm.DB, storeSet *types.StoreSet, sync bool) ([]byte, error) {
return hashByte, nil
}
// GetKVPair get values by keys, return values and error
func GetKVPair(db dbm.DB, storeGet *types.StoreGet) ([][]byte, error) {
var err error
var trie *TrieEx
......@@ -585,6 +597,7 @@ func GetKVPair(db dbm.DB, storeGet *types.StoreGet) ([][]byte, error) {
return values, nil
}
// GetKVPairProof 获取指定k:v pair的proof证明
func GetKVPairProof(db dbm.DB, roothash []byte, key []byte) []byte {
if enableSecure {
key = common.ShaKeccak256(key)
......@@ -596,7 +609,7 @@ func GetKVPairProof(db dbm.DB, roothash []byte, key []byte) []byte {
return value
}
//剔除key对应的节点在本次tree中,返回新的roothash和key对应的value
// DelKVPair 剔除key对应的节点在本次tree中,返回新的roothash和key对应的value
func DelKVPair(db dbm.DB, storeDel *types.StoreGet) ([]byte, [][]byte, error) {
var err error
var trie *TrieEx
......@@ -626,6 +639,7 @@ func DelKVPair(db dbm.DB, storeDel *types.StoreGet) ([]byte, [][]byte, error) {
return hashByte, values, nil
}
// VerifyKVPairProof 验证KVPair 的证明
func VerifyKVPairProof(db dbm.DB, roothash []byte, keyvalue types.KeyValue, proof []byte) bool {
if enableSecure {
keyvalue.Key = common.ShaKeccak256(keyvalue.Key)
......@@ -634,6 +648,7 @@ func VerifyKVPairProof(db dbm.DB, roothash []byte, keyvalue types.KeyValue, proo
return nil == err
}
// IterateRangeByStateHash 迭代实现功能; statehash:当前状态hash, start:开始查找的key, end: 结束的key, ascending:升序,降序, fn 迭代回调函数
func IterateRangeByStateHash(db dbm.DB, statehash, start, end []byte, ascending bool, fn func([]byte, []byte) bool) {
var err error
var trie *TrieEx
......
......@@ -17,14 +17,17 @@ import (
var mlog = log.New("module", "mpt")
// SetLogLevel set log level
func SetLogLevel(level string) {
clog.SetLogLevel(level)
}
// DisableLog disable log
func DisableLog() {
mlog.SetHandler(log.DiscardHandler())
}
// Store mpt store struct
type Store struct {
*drivers.BaseStore
trees map[string]*mpt.TrieEx
......@@ -35,6 +38,7 @@ func init() {
drivers.Reg("mpt", New)
}
// New new mpt store module
func New(cfg *types.Store, sub []byte) queue.Module {
bs := drivers.NewBaseStore(cfg)
mpts := &Store{bs, make(map[string]*mpt.TrieEx), nil}
......@@ -43,11 +47,13 @@ func New(cfg *types.Store, sub []byte) queue.Module {
return mpts
}
// Close close mpt store
func (mpts *Store) Close() {
mpts.BaseStore.Close()
mlog.Info("store mavl closed")
}
// Set set k v to mpt store db; sync is true represent write sync
func (mpts *Store) Set(datas *types.StoreSet, sync bool) ([]byte, error) {
hash, err := mpt.SetKVPair(mpts.GetDB(), datas, sync)
if err != nil {
......@@ -57,6 +63,7 @@ func (mpts *Store) Set(datas *types.StoreSet, sync bool) ([]byte, error) {
return hash, nil
}
// Get get values by keys
func (mpts *Store) Get(datas *types.StoreGet) [][]byte {
var tree *mpt.TrieEx
var err error
......@@ -87,6 +94,7 @@ func (mpts *Store) Get(datas *types.StoreGet) [][]byte {
return values
}
// MemSet set keys values to memcory mpt, return root hash and error
func (mpts *Store) MemSet(datas *types.StoreSet, sync bool) ([]byte, error) {
var err error
var tree *mpt.TrieEx
......@@ -111,6 +119,7 @@ func (mpts *Store) MemSet(datas *types.StoreSet, sync bool) ([]byte, error) {
return hash, nil
}
// Commit convert memcory mpt to storage db
func (mpts *Store) Commit(req *types.ReqHash) ([]byte, error) {
tree, ok := mpts.trees[string(req.Hash)]
if !ok {
......@@ -126,6 +135,7 @@ func (mpts *Store) Commit(req *types.ReqHash) ([]byte, error) {
return req.Hash, nil
}
// Rollback 回退将缓存的mpt树删除掉
func (mpts *Store) Rollback(req *types.ReqHash) ([]byte, error) {
_, ok := mpts.trees[string(req.Hash)]
if !ok {
......@@ -136,15 +146,18 @@ func (mpts *Store) Rollback(req *types.ReqHash) ([]byte, error) {
return req.Hash, nil
}
// Del ...
func (mpts *Store) Del(req *types.StoreDel) ([]byte, error) {
//not support
return nil, nil
}
// IterateRangeByStateHash 迭代实现功能; statehash:当前状态hash, start:开始查找的key, end: 结束的key, ascending:升序,降序, fn 迭代回调函数
func (mpts *Store) IterateRangeByStateHash(statehash []byte, start []byte, end []byte, ascending bool, fn func(key, value []byte) bool) {
mpt.IterateRangeByStateHash(mpts.GetDB(), statehash, start, end, ascending, fn)
}
// ProcEvent not support message
func (mpts *Store) ProcEvent(msg queue.Message) {
msg.ReplyErr("Store", types.ErrActionNotSupport)
}
......@@ -29,8 +29,8 @@ func TestKvdbNewClose(t *testing.T) {
assert.Nil(t, err)
defer os.RemoveAll(dir) // clean up
os.RemoveAll(dir) //删除已存在目录
var store_cfg = newStoreCfg(dir)
store := New(store_cfg, nil)
var storeCfg = newStoreCfg(dir)
store := New(storeCfg, nil)
assert.NotNil(t, store)
store.Close()
......@@ -41,12 +41,12 @@ func TestKvddbSetGet(t *testing.T) {
assert.Nil(t, err)
defer os.RemoveAll(dir) // clean up
os.RemoveAll(dir) //删除已存在目录
var store_cfg = newStoreCfg(dir)
store := New(store_cfg, nil).(*Store)
var storeCfg = newStoreCfg(dir)
store := New(storeCfg, nil).(*Store)
assert.NotNil(t, store)
keys0 := [][]byte{[]byte("mk1"), []byte("mk2")}
get0 := &types.StoreGet{drivers.EmptyRoot[:], keys0}
get0 := &types.StoreGet{StateHash: drivers.EmptyRoot[:], Keys: keys0}
values0 := store.Get(get0)
mlog.Info("info", "info", values0)
// Get exist key, result nil
......@@ -55,16 +55,16 @@ func TestKvddbSetGet(t *testing.T) {
assert.Equal(t, []byte(nil), values0[1])
var kv []*types.KeyValue
kv = append(kv, &types.KeyValue{[]byte("k1"), []byte("v1")})
kv = append(kv, &types.KeyValue{[]byte("k2"), []byte("v2")})
kv = append(kv, &types.KeyValue{Key: []byte("k1"), Value: []byte("v1")})
kv = append(kv, &types.KeyValue{Key: []byte("k2"), Value: []byte("v2")})
datas := &types.StoreSet{
drivers.EmptyRoot[:],
kv,
0}
StateHash: drivers.EmptyRoot[:],
KV: kv,
Height: 0}
hash, err := store.Set(datas, true)
assert.Nil(t, err)
keys := [][]byte{[]byte("k1"), []byte("k2")}
get1 := &types.StoreGet{hash, keys}
get1 := &types.StoreGet{StateHash: hash, Keys: keys}
values := store.Get(get1)
assert.Len(t, values, 2)
......@@ -72,12 +72,12 @@ func TestKvddbSetGet(t *testing.T) {
assert.Equal(t, []byte("v2"), values[1])
keys = [][]byte{[]byte("k1")}
get2 := &types.StoreGet{hash, keys}
get2 := &types.StoreGet{StateHash: hash, Keys: keys}
values2 := store.Get(get2)
assert.Len(t, values2, 1)
assert.Equal(t, []byte("v1"), values2[0])
get3 := &types.StoreGet{drivers.EmptyRoot[:], keys}
get3 := &types.StoreGet{StateHash: drivers.EmptyRoot[:], Keys: keys}
values3 := store.Get(get3)
assert.Len(t, values3, 1)
assert.Equal(t, []byte(nil), values3[0])
......@@ -88,29 +88,29 @@ func TestKvdbMemSet(t *testing.T) {
assert.Nil(t, err)
defer os.RemoveAll(dir) // clean up
os.RemoveAll(dir) //删除已存在目录
var store_cfg = newStoreCfg(dir)
store := New(store_cfg, nil).(*Store)
var storeCfg = newStoreCfg(dir)
store := New(storeCfg, nil).(*Store)
assert.NotNil(t, store)
var kv []*types.KeyValue
kv = append(kv, &types.KeyValue{[]byte("mk1"), []byte("v1")})
kv = append(kv, &types.KeyValue{[]byte("mk2"), []byte("v2")})
kv = append(kv, &types.KeyValue{Key: []byte("mk1"), Value: []byte("v1")})
kv = append(kv, &types.KeyValue{Key: []byte("mk2"), Value: []byte("v2")})
datas := &types.StoreSet{
drivers.EmptyRoot[:],
kv,
0}
StateHash: drivers.EmptyRoot[:],
KV: kv,
Height: 0}
hash, err := store.MemSet(datas, true)
assert.Nil(t, err)
keys := [][]byte{[]byte("mk1"), []byte("mk2")}
get1 := &types.StoreGet{hash, keys}
get1 := &types.StoreGet{StateHash: hash, Keys: keys}
values := store.Get(get1)
assert.Len(t, values, 2)
actHash, _ := store.Commit(&types.ReqHash{hash})
actHash, _ := store.Commit(&types.ReqHash{Hash: hash})
assert.Equal(t, hash, actHash)
notExistHash, _ := store.Commit(&types.ReqHash{drivers.EmptyRoot[:]})
notExistHash, _ := store.Commit(&types.ReqHash{Hash: drivers.EmptyRoot[:]})
assert.Nil(t, notExistHash)
}
......@@ -119,28 +119,28 @@ func TestKvdbRollback(t *testing.T) {
assert.Nil(t, err)
defer os.RemoveAll(dir) // clean up
os.RemoveAll(dir) //删除已存在目录
var store_cfg = newStoreCfg(dir)
store := New(store_cfg, nil).(*Store)
var storeCfg = newStoreCfg(dir)
store := New(storeCfg, nil).(*Store)
assert.NotNil(t, store)
var kv []*types.KeyValue
kv = append(kv, &types.KeyValue{[]byte("mk1"), []byte("v1")})
kv = append(kv, &types.KeyValue{[]byte("mk2"), []byte("v2")})
kv = append(kv, &types.KeyValue{Key: []byte("mk1"), Value: []byte("v1")})
kv = append(kv, &types.KeyValue{Key: []byte("mk2"), Value: []byte("v2")})
datas := &types.StoreSet{
drivers.EmptyRoot[:],
kv,
0}
StateHash: drivers.EmptyRoot[:],
KV: kv,
Height: 0}
hash, err := store.MemSet(datas, true)
assert.Nil(t, err)
keys := [][]byte{[]byte("mk1"), []byte("mk2")}
get1 := &types.StoreGet{hash, keys}
get1 := &types.StoreGet{StateHash: hash, Keys: keys}
values := store.Get(get1)
assert.Len(t, values, 2)
actHash, _ := store.Rollback(&types.ReqHash{hash})
actHash, _ := store.Rollback(&types.ReqHash{Hash: hash})
assert.Equal(t, hash, actHash)
notExistHash, _ := store.Rollback(&types.ReqHash{drivers.EmptyRoot[:]})
notExistHash, _ := store.Rollback(&types.ReqHash{Hash: drivers.EmptyRoot[:]})
assert.Nil(t, notExistHash)
}
......@@ -148,7 +148,7 @@ var checkKVResult []*types.KeyValue
func checkKV(k, v []byte) bool {
checkKVResult = append(checkKVResult,
&types.KeyValue{k, v})
&types.KeyValue{Key: k, Value: v})
//mlog.Debug("checkKV", "key", string(k), "value", string(v))
return false
}
......@@ -163,8 +163,8 @@ func BenchmarkGet(b *testing.B) {
assert.Nil(b, err)
defer os.RemoveAll(dir) // clean up
os.RemoveAll(dir) //删除已存在目录
var store_cfg = newStoreCfg(dir)
store := New(store_cfg, nil).(*Store)
var storeCfg = newStoreCfg(dir)
store := New(storeCfg, nil).(*Store)
assert.NotNil(b, store)
var kv []*types.KeyValue
......@@ -174,26 +174,25 @@ func BenchmarkGet(b *testing.B) {
key := GetRandomString(MaxKeylenth)
value := fmt.Sprintf("%s%d", key, i)
keys = append(keys, []byte(string(key)))
kv = append(kv, &types.KeyValue{[]byte(string(key)), []byte(string(value))})
kv = append(kv, &types.KeyValue{Key: []byte(string(key)), Value: []byte(string(value))})
if i%10000 == 0 {
datas := &types.StoreSet{hash, kv, 0}
datas := &types.StoreSet{StateHash: hash, KV: kv, Height: 0}
hash, err = store.Set(datas, true)
assert.Nil(b, err)
kv = nil
}
}
if kv != nil {
datas := &types.StoreSet{hash, kv, 0}
datas := &types.StoreSet{StateHash: hash, KV: kv, Height: 0}
hash, err = store.Set(datas, true)
assert.Nil(b, err)
//kv = nil
}
start := time.Now()
b.ResetTimer()
for _, key := range keys {
getData := &types.StoreGet{
hash,
[][]byte{key}}
StateHash: hash,
Keys: [][]byte{key}}
store.Get(getData)
}
end := time.Now()
......@@ -205,8 +204,8 @@ func BenchmarkSet(b *testing.B) {
assert.Nil(b, err)
defer os.RemoveAll(dir) // clean up
os.RemoveAll(dir) //删除已存在目录
var store_cfg = newStoreCfg(dir)
store := New(store_cfg, nil).(*Store)
var storeCfg = newStoreCfg(dir)
store := New(storeCfg, nil).(*Store)
assert.NotNil(b, store)
var kv []*types.KeyValue
......@@ -217,19 +216,18 @@ func BenchmarkSet(b *testing.B) {
key := GetRandomString(MaxKeylenth)
value := fmt.Sprintf("%s%d", key, i)
keys = append(keys, []byte(string(key)))
kv = append(kv, &types.KeyValue{[]byte(string(key)), []byte(string(value))})
kv = append(kv, &types.KeyValue{Key: []byte(string(key)), Value: []byte(string(value))})
if i%10000 == 0 {
datas := &types.StoreSet{hash, kv, 0}
datas := &types.StoreSet{StateHash: hash, KV: kv, Height: 0}
hash, err = store.Set(datas, true)
assert.Nil(b, err)
kv = nil
}
}
if kv != nil {
datas := &types.StoreSet{hash, kv, 0}
datas := &types.StoreSet{StateHash: hash, KV: kv, Height: 0}
_, err = store.Set(datas, true)
assert.Nil(b, err)
//kv = nil
}
end := time.Now()
fmt.Println("mpt BenchmarkSet cost time is", end.Sub(start), "num is", b.N)
......@@ -240,8 +238,8 @@ func BenchmarkMemSet(b *testing.B) {
assert.Nil(b, err)
defer os.RemoveAll(dir) // clean up
os.RemoveAll(dir) //删除已存在目录
var store_cfg = newStoreCfg(dir)
store := New(store_cfg, nil).(*Store)
var storeCfg = newStoreCfg(dir)
store := New(storeCfg, nil).(*Store)
assert.NotNil(b, store)
var kv []*types.KeyValue
......@@ -253,12 +251,12 @@ func BenchmarkMemSet(b *testing.B) {
key = GetRandomString(MaxKeylenth)
value = fmt.Sprintf("v%d", i)
keys = append(keys, []byte(string(key)))
kv = append(kv, &types.KeyValue{[]byte(string(key)), []byte(string(value))})
kv = append(kv, &types.KeyValue{Key: []byte(string(key)), Value: []byte(string(value))})
}
datas := &types.StoreSet{
drivers.EmptyRoot[:],
kv,
0}
StateHash: drivers.EmptyRoot[:],
KV: kv,
Height: 0}
start := time.Now()
b.ResetTimer()
hash, err := store.MemSet(datas, true)
......@@ -273,8 +271,8 @@ func BenchmarkCommit(b *testing.B) {
assert.Nil(b, err)
defer os.RemoveAll(dir) // clean up
os.RemoveAll(dir) //删除已存在目录
var store_cfg = newStoreCfg(dir)
store := New(store_cfg, nil).(*Store)
var storeCfg = newStoreCfg(dir)
store := New(storeCfg, nil).(*Store)
assert.NotNil(b, store)
var kv []*types.KeyValue
......@@ -286,12 +284,12 @@ func BenchmarkCommit(b *testing.B) {
key = GetRandomString(MaxKeylenth)
value = fmt.Sprintf("v%d", i)
keys = append(keys, []byte(string(key)))
kv = append(kv, &types.KeyValue{[]byte(string(key)), []byte(string(value))})
kv = append(kv, &types.KeyValue{Key: []byte(string(key)), Value: []byte(string(value))})
}
datas := &types.StoreSet{
drivers.EmptyRoot[:],
kv,
0}
StateHash: drivers.EmptyRoot[:],
KV: kv,
Height: 0}
hash, err := store.MemSet(datas, true)
assert.Nil(b, err)
req := &types.ReqHash{
......
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