Commit 973b4e61 authored by Litian's avatar Litian

Merge branch 'master' into evm_abi

parents 781721f6 83795d85
......@@ -11,6 +11,7 @@ APP := build/chain33
CHAIN33=github.com/33cn/chain33
CHAIN33_PATH=vendor/${CHAIN33}
LDFLAGS := -ldflags "-w -s"
PKG_LIST_VET := `go list ./... | grep -v "vendor" | grep -v plugin/dapp/evm/executor/vm/common/crypto/bn256`
PKG_LIST := `go list ./... | grep -v "vendor" | grep -v "chain33/test" | grep -v "mocks" | grep -v "pbft"`
PKG_LIST_Q := `go list ./... | grep -v "vendor" | grep -v "chain33/test" | grep -v "mocks" | grep -v "blockchain" | grep -v "pbft"`
BUILD_FLAGS = -ldflags "-X github.com/33cn/chain33/common/version.GitCommit=`git rev-parse --short=8 HEAD`"
......@@ -35,6 +36,8 @@ build_ci: depends ## Build the binary file for CI
para:
@go build -v -o build/$(NAME) -ldflags "-X $(SRC_CLI)/buildflags.ParaName=user.p.$(NAME). -X $(SRC_CLI)/buildflags.RPCAddr=http://localhost:8901" $(SRC_CLI)
vet:
@go vet ${PKG_LIST_VET}
autotest: ## build autotest binary
@cd build/autotest && bash ./build.sh && cd ../../
......@@ -55,7 +58,7 @@ autotest_tick: autotest ## run with ticket mining
update:
rm -rf ${CHAIN33_PATH}
git clone --depth 1 -b master https://${CHAIN33}.git ${CHAIN33_PATH}
git clone --depth 1 -b ${b} https://${CHAIN33}.git ${CHAIN33_PATH}
rm -rf vendor/${CHAIN33}/.git
rm -rf vendor/${CHAIN33}/vendor/github.com/apache/thrift/tutorial/erl/
cp -Rf vendor/${CHAIN33}/vendor/* vendor/
......@@ -71,30 +74,12 @@ updatevendor:
dep:
dep init -v
linter: vet ## Use gometalinter check code, ignore some unserious warning
@./golinter.sh "filter"
@find . -name '*.sh' -not -path "./vendor/*" | xargs shellcheck
linter: ## Use gometalinter check code, ignore some unserious warning
@res=$$(gometalinter.v2 -t --sort=linter --enable-gc --deadline=2m --disable-all \
--enable=gofmt \
--enable=gosimple \
--enable=deadcode \
--enable=unconvert \
--enable=interfacer \
--enable=varcheck \
--enable=structcheck \
--enable=goimports \
--vendor ./...) \
# --enable=vet \
# --enable=staticcheck \
# --enable=gocyclo \
# --enable=staticcheck \
# --enable=golint \
# --enable=unused \
# --enable=gotype \
# --enable=gotypex \
if [ -n "$$res" ]; then \
echo "$${res}"; \
exit 1; \
fi;
linter_test: ## Use gometalinter check code, for local test
@./golinter.sh "test" "${p}"
@find . -name '*.sh' -not -path "./vendor/*" | xargs shellcheck
race: ## Run data race detector
......@@ -260,4 +245,23 @@ push:
make sync
git checkout ${b}
git merge master
git push origin ${b}
\ No newline at end of file
git push origin ${b}
pull:
@remotelist=$$(git remote | grep ${name});if [ -z $$remotelist ]; then \
echo ${remotelist}; \
git remote add ${name} https://github.com/${name}/plugin.git ; \
fi;
git fetch ${name}
git checkout ${name}/${b}
git checkout -b ${name}-${b}
pullsync:
git fetch ${name}
git checkout ${name}-${b}
git merge ${name}/${b}
pullpush:
@if [ -n "$$m" ]; then \
git commit -a -m "${m}" ; \
fi;
make pullsync
git push ${name} ${name}-${b}:${b}
......@@ -4,5 +4,8 @@
package buildflags
// ParaName para name
var ParaName string
// RPCAddr rpc address
var RPCAddr string
#!/bin/bash
# shellcheck disable=SC2207
set +e
OP="${1}"
path="${2}"
function filterLinter() {
res=$(gometalinter.v2 -t --sort=linter --enable-gc --deadline=2m --disable-all \
--enable=gofmt \
--enable=gosimple \
--enable=deadcode \
--enable=unconvert \
--enable=interfacer \
--enable=varcheck \
--enable=structcheck \
--enable=goimports \
--vendor ./...)
# --enable=staticcheck \
# --enable=gocyclo \
# --enable=staticcheck \
# --enable=golint \
# --enable=unused \
# --enable=gotype \
# --enable=gotypex \
if [[ ${#res} -gt "0" ]]; then
resNoSpace=$(echo "${res}" | tr ' ' '@')
array=($(echo "${resNoSpace}" | tr '\n' '\n'))
str=""
for var in ${array[*]}; do
if ! [[ $var =~ "underscores" ]]; then
str="${str}""${var}""\\n"
fi
done
res=""
res=$(echo "${str}" | tr '@' ' ')
fi
if [[ ${#res} -gt "0" ]]; then
echo -e "${res}"
exit 1
fi
}
function testLinter() {
cd "${path}" >/dev/null || exit
gometalinter.v2 -t --sort=linter --enable-gc --deadline=2m --disable-all \
--enable=gofmt \
--enable=gosimple \
--enable=deadcode \
--enable=unconvert \
--enable=interfacer \
--enable=varcheck \
--enable=structcheck \
--enable=goimports \
--enable=vet \
--enable=golint \
--enable=ineffassign \
--vendor ./...
cd - >/dev/null || exit
}
function main() {
if [ "${OP}" == "filter" ]; then
filterLinter
elif [ "${OP}" == "test" ]; then
testLinter
fi
}
# run script
main
......@@ -2,13 +2,13 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build go1.9
/*
每个系统的功能通过插件完成,插件分成4类:
共识 加密 dapp 存储
这个go 包提供了 官方提供的 插件。
*/
// +build go1.8
package main
import (
......
// 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.
package init
import (
......
......@@ -43,6 +43,7 @@ type envelope struct {
Data *json.RawMessage `json:"data"`
}
// EvidenceInfo struct
type EvidenceInfo struct {
Committed bool `json:"committed"`
Priority int64 `json:"priority"`
......@@ -77,8 +78,8 @@ func keyPending(evidence ttypes.Evidence) []byte {
return _key("%s/%s/%X", baseKeyPending, bE(evidence.Height()), evidence.Hash())
}
func _key(fmt_ string, o ...interface{}) []byte {
return []byte(fmt.Sprintf(fmt_, o...))
func _key(s string, o ...interface{}) []byte {
return []byte(fmt.Sprintf(s, o...))
}
// EvidenceStore is a store of all the evidence we've seen, including
......@@ -88,6 +89,7 @@ type EvidenceStore struct {
db dbm.DB
}
// NewEvidenceStore method
func NewEvidenceStore(db dbm.DB) *EvidenceStore {
if len(ttypes.EvidenceType2Type) == 0 {
ttypes.EvidenceType2Type = map[string]reflect.Type{
......@@ -160,8 +162,8 @@ func (store *EvidenceStore) GetEvidence(height int64, hash []byte) *EvidenceInfo
// It returns false if the evidence is already stored.
func (store *EvidenceStore) AddNewEvidence(evidence ttypes.Evidence, priority int64) bool {
// check if we already have seen it
ei_ := store.GetEvidence(evidence.Height(), evidence.Hash())
if ei_ != nil && len(ei_.Evidence.Kind) == 0 {
ei := store.GetEvidence(evidence.Height(), evidence.Hash())
if ei != nil && len(ei.Evidence.Kind) == 0 {
return false
}
......@@ -191,7 +193,7 @@ func (store *EvidenceStore) MarkEvidenceAsBroadcasted(evidence ttypes.Evidence)
store.db.Delete(key)
}
// MarkEvidenceAsPending removes evidence from pending and outqueue and sets the state to committed.
// MarkEvidenceAsCommitted removes evidence from pending and outqueue and sets the state to committed.
func (store *EvidenceStore) MarkEvidenceAsCommitted(evidence ttypes.Evidence) {
// if its committed, its been broadcast
store.MarkEvidenceAsBroadcasted(evidence)
......@@ -227,6 +229,7 @@ func (store *EvidenceStore) getEvidenceInfo(evidence ttypes.Evidence) EvidenceIn
return ei
}
// EvidenceToInfoBytes method
func EvidenceToInfoBytes(evidence ttypes.Evidence, priority int64) ([]byte, error) {
evi, err := json.Marshal(evidence)
if err != nil {
......@@ -250,6 +253,7 @@ func EvidenceToInfoBytes(evidence ttypes.Evidence, priority int64) ([]byte, erro
return eiBytes, nil
}
// EvidenceFromInfoBytes method
func (store *EvidenceStore) EvidenceFromInfoBytes(data []byte) (ttypes.Evidence, error) {
vote2 := EvidenceInfo{}
err := json.Unmarshal(data, &vote2)
......@@ -268,7 +272,6 @@ func (store *EvidenceStore) EvidenceFromInfoBytes(data []byte) (ttypes.Evidence,
}
//-------------------------evidence pool----------------------------
// EvidencePool maintains a pool of valid evidence
// in an EvidenceStore.
type EvidencePool struct {
......@@ -285,6 +288,7 @@ type EvidencePool struct {
evidenceChan chan ttypes.Evidence
}
// NewEvidencePool method
func NewEvidencePool(stateDB *CSStateDB, state State, evidenceStore *EvidenceStore) *EvidencePool {
evpool := &EvidencePool{
stateDB: stateDB,
......
......@@ -22,14 +22,15 @@ import (
)
const (
numBufferedConnections = 10
MaxNumPeers = 50
tryListenSeconds = 5
HandshakeTimeout = 20 // * time.Second,
maxSendQueueSize = 1024
defaultSendTimeout = 60 * time.Second
numBufferedConnections = 10
maxNumPeers = 50
tryListenSeconds = 5
handshakeTimeout = 20 // * time.Second,
maxSendQueueSize = 1024
defaultSendTimeout = 60 * time.Second
//MaxMsgPacketPayloadSize define
MaxMsgPacketPayloadSize = 10 * 1024 * 1024
DefaultDialTimeout = 3 * time.Second
defaultDialTimeout = 3 * time.Second
dialRandomizerIntervalMilliseconds = 3000
// repeatedly try to reconnect for a few minutes
// ie. 5 * 20 = 100s
......@@ -47,6 +48,7 @@ const (
broadcastEvidenceIntervalS = 60 // broadcast uncommitted evidence this often
)
// Parallel method
func Parallel(tasks ...func()) {
var wg sync.WaitGroup
wg.Add(len(tasks))
......@@ -59,23 +61,27 @@ func Parallel(tasks ...func()) {
wg.Wait()
}
// GenAddressByPubKey method
func GenAddressByPubKey(pubkey crypto.PubKey) []byte {
//must add 3 bytes ahead to make compatibly
typeAddr := append([]byte{byte(0x01), byte(0x01), byte(0x20)}, pubkey.Bytes()...)
return crypto.Ripemd160(typeAddr)
}
// IP2IPPort struct
type IP2IPPort struct {
mutex sync.RWMutex
mapList map[string]string
}
// NewMutexMap method
func NewMutexMap() *IP2IPPort {
return &IP2IPPort{
mapList: make(map[string]string),
}
}
// Has method
func (ipp *IP2IPPort) Has(ip string) bool {
ipp.mutex.RLock()
defer ipp.mutex.RUnlock()
......@@ -83,18 +89,21 @@ func (ipp *IP2IPPort) Has(ip string) bool {
return ok
}
// Set method
func (ipp *IP2IPPort) Set(ip string, ipport string) {
ipp.mutex.Lock()
defer ipp.mutex.Unlock()
ipp.mapList[ip] = ipport
}
// Delete method
func (ipp *IP2IPPort) Delete(ip string) {
ipp.mutex.Lock()
defer ipp.mutex.Unlock()
delete(ipp.mapList, ip)
}
// NodeInfo struct
type NodeInfo struct {
ID ID `json:"id"`
Network string `json:"network"`
......@@ -102,6 +111,7 @@ type NodeInfo struct {
IP string `json:"ip,omitempty"`
}
// Node struct
type Node struct {
listener net.Listener
connections chan net.Conn
......@@ -129,6 +139,7 @@ type Node struct {
quit chan struct{}
}
// NewNode method
func NewNode(seeds []string, protocol string, lAddr string, privKey crypto.PrivKey, network string, version string, state *ConsensusState, evpool *EvidencePool) *Node {
address := GenAddressByPubKey(privKey.PubKey())
......@@ -163,6 +174,7 @@ func NewNode(seeds []string, protocol string, lAddr string, privKey crypto.PrivK
return node
}
// Start node
func (node *Node) Start() {
if atomic.CompareAndSwapUint32(&node.started, 0, 1) {
// Create listener
......@@ -211,6 +223,7 @@ func (node *Node) Start() {
}
}
// DialPeerWithAddress ...
func (node *Node) DialPeerWithAddress(addr string) error {
ip, _ := splitHostPort(addr)
node.dialing.Set(ip, addr)
......@@ -234,6 +247,7 @@ func (node *Node) addOutboundPeerWithConfig(addr string) error {
return nil
}
// Stop ...
func (node *Node) Stop() {
atomic.CompareAndSwapUint32(&node.stopped, 0, 1)
node.listener.Close()
......@@ -245,10 +259,11 @@ func (node *Node) Stop() {
peer.Stop()
node.peerSet.Remove(peer)
}
// Stop reactors
tendermintlog.Debug("Switch: Stopping reactors")
//stop consensus
node.state.Stop()
}
// IsRunning ...
func (node *Node) IsRunning() bool {
return atomic.LoadUint32(&node.started) == 1 && atomic.LoadUint32(&node.stopped) == 0
}
......@@ -277,8 +292,10 @@ func (node *Node) listenRoutine() {
}
}
// StartConsensusRoutine if peers reached the threshold start consensus routine
func (node *Node) StartConsensusRoutine() {
for {
//TODO:the peer count need be optimized
if node.peerSet.Size() >= 0 {
node.state.Start()
break
......@@ -347,6 +364,7 @@ func (node *Node) evidenceBroadcastRoutine() {
}
}
// BroadcastRoutine receive to broadcast
func (node *Node) BroadcastRoutine() {
for {
msg, ok := <-node.broadcastChannel
......@@ -359,7 +377,7 @@ func (node *Node) BroadcastRoutine() {
}
func (node *Node) connectComming(inConn net.Conn) {
maxPeers := MaxNumPeers
maxPeers := maxNumPeers
if maxPeers <= node.peerSet.Size() {
tendermintlog.Debug("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", node.peerSet.Size(), "max", maxPeers)
return
......@@ -378,6 +396,7 @@ func (node *Node) stopAndRemovePeer(peer Peer, reason interface{}) {
peer.Stop()
}
// StopPeerForError called if error occured
func (node *Node) StopPeerForError(peer Peer, reason interface{}) {
tendermintlog.Error("Stopping peer for error", "peer", peer, "err", reason)
addr, err := peer.RemoteAddr()
......@@ -408,7 +427,7 @@ func (node *Node) addInboundPeer(conn net.Conn) error {
// peer to the switch and to all registered reactors.
// NOTE: This performs a blocking handshake before the peer is added.
// NOTE: If error is returned, caller is responsible for calling peer.CloseConn()
func (node *Node) addPeer(pc peerConn) error {
func (node *Node) addPeer(pc *peerConn) error {
addr := pc.conn.RemoteAddr()
if err := node.FilterConnByAddr(addr); err != nil {
return err
......@@ -422,7 +441,7 @@ func (node *Node) addPeer(pc peerConn) error {
Version: node.Version,
}
// Exchange NodeInfo on the conn
peerNodeInfo, err := pc.HandshakeTimeout(nodeinfo, HandshakeTimeout*time.Second)
peerNodeInfo, err := pc.HandshakeTimeout(nodeinfo, handshakeTimeout*time.Second)
if err != nil {
return err
}
......@@ -472,7 +491,7 @@ func (node *Node) addPeer(pc peerConn) error {
// All good. Start peer
if node.IsRunning() {
pc.SetTransferChannel(node.state.peerMsgQueue)
if err = node.startInitPeer(&pc); err != nil {
if err = node.startInitPeer(pc); err != nil {
return err
}
}
......@@ -480,7 +499,7 @@ func (node *Node) addPeer(pc peerConn) error {
// Add the peer to .peers.
// We start it first so that a peer in the list is safe to Stop.
// It should not err since we already checked peers.Has().
if err := node.peerSet.Add(&pc); err != nil {
if err := node.peerSet.Add(pc); err != nil {
return err
}
//node.metrics.Peers.Add(float64(1))
......@@ -489,6 +508,7 @@ func (node *Node) addPeer(pc peerConn) error {
return nil
}
// Broadcast to peers in set
func (node *Node) Broadcast(msg MsgInfo) chan bool {
successChan := make(chan bool, len(node.peerSet.List()))
tendermintlog.Debug("Broadcast", "msgtype", msg.TypeID)
......@@ -519,13 +539,12 @@ func (node *Node) startInitPeer(peer *peerConn) error {
return nil
}
// FilterConnByAddr TODO:can make fileter by addr
func (node *Node) FilterConnByAddr(addr net.Addr) error {
//if node.filterConnByAddr != nil {
// return node.filterConnByAddr(addr)
//}
return nil
}
// CompatibleWith one node by nodeInfo
func (node *Node) CompatibleWith(other NodeInfo) error {
iMajor, iMinor, _, iErr := splitVersion(node.Version)
oMajor, oMinor, _, oErr := splitVersion(other.Version)
......@@ -679,25 +698,25 @@ func splitHostPort(addr string) (host string, port int) {
}
func dial(addr string) (net.Conn, error) {
conn, err := net.DialTimeout("tcp", addr, DefaultDialTimeout)
conn, err := net.DialTimeout("tcp", addr, defaultDialTimeout)
if err != nil {
return nil, err
}
return conn, nil
}
func newOutboundPeerConn(addr string, ourNodePrivKey crypto.PrivKey, onPeerError func(Peer, interface{}), state *ConsensusState, evpool *EvidencePool) (peerConn, error) {
func newOutboundPeerConn(addr string, ourNodePrivKey crypto.PrivKey, onPeerError func(Peer, interface{}), state *ConsensusState, evpool *EvidencePool) (*peerConn, error) {
conn, err := dial(addr)
if err != nil {
return peerConn{}, fmt.Errorf("Error creating peer:%v", err)
return &peerConn{}, fmt.Errorf("Error creating peer:%v", err)
}
pc, err := newPeerConn(conn, true, true, ourNodePrivKey, onPeerError, state, evpool)
if err != nil {
if cerr := conn.Close(); cerr != nil {
return peerConn{}, fmt.Errorf("newPeerConn failed:%v, connection close failed:%v", err, cerr)
return &peerConn{}, fmt.Errorf("newPeerConn failed:%v, connection close failed:%v", err, cerr)
}
return peerConn{}, err
return &peerConn{}, err
}
return pc, nil
......@@ -709,7 +728,7 @@ func newInboundPeerConn(
onPeerError func(Peer, interface{}),
state *ConsensusState,
evpool *EvidencePool,
) (peerConn, error) {
) (*peerConn, error) {
// TODO: issue PoW challenge
......@@ -723,11 +742,11 @@ func newPeerConn(
onPeerError func(Peer, interface{}),
state *ConsensusState,
evpool *EvidencePool,
) (pc peerConn, err error) {
) (pc *peerConn, err error) {
conn := rawConn
// Set deadline for secret handshake
dl := time.Now().Add(HandshakeTimeout * time.Second)
dl := time.Now().Add(handshakeTimeout * time.Second)
if err := conn.SetDeadline(dl); err != nil {
return pc, fmt.Errorf("Error setting deadline while encrypting connection:%v", err)
}
......@@ -739,7 +758,7 @@ func newPeerConn(
}
// Only the information we already have
return peerConn{
return &peerConn{
outbound: outbound,
persistent: persistent,
conn: conn,
......
......@@ -33,6 +33,7 @@ type msgPacket struct {
Bytes []byte
}
// MsgInfo struct
type MsgInfo struct {
TypeID byte
Msg proto.Message
......@@ -40,6 +41,7 @@ type MsgInfo struct {
PeerIP string
}
// Peer interface
type Peer interface {
ID() ID
RemoteIP() (net.IP, error) // remote IP of the connection
......@@ -57,6 +59,7 @@ type Peer interface {
//Get(string) interface{}
}
// PeerConnState struct
type PeerConnState struct {
mtx sync.Mutex
ip net.IP
......@@ -98,6 +101,7 @@ type peerConn struct {
heartbeatQueue chan proto.Message
}
// PeerSet struct
type PeerSet struct {
mtx sync.Mutex
lookup map[ID]*peerSetItem
......@@ -109,6 +113,7 @@ type peerSetItem struct {
index int
}
// NewPeerSet method
func NewPeerSet() *PeerSet {
return &PeerSet{
lookup: make(map[ID]*peerSetItem),
......@@ -164,6 +169,7 @@ func (ps *PeerSet) hasIP(peerIP net.IP) bool {
return false
}
// Size of list
func (ps *PeerSet) Size() int {
ps.mtx.Lock()
defer ps.mtx.Unlock()
......@@ -277,36 +283,41 @@ func (pc *peerConn) HandshakeTimeout(
func() {
info, err1 := json.Marshal(ourNodeInfo)
if err1 != nil {
tendermintlog.Error("Peer handshake peerNodeInfo failed", "err", err1)
tendermintlog.Error("Peer handshake Marshal ourNodeInfo failed", "err", err1)
return
}
frame := make([]byte, 4)
binary.BigEndian.PutUint32(frame, uint32(len(info)))
_, err1 = pc.conn.Write(frame)
if err1 != nil {
tendermintlog.Error("Peer handshake write info size failed", "err", err1)
return
}
_, err1 = pc.conn.Write(info[:])
if err1 != nil {
tendermintlog.Error("Peer handshake write info failed", "err", err1)
return
} else {
frame := make([]byte, 4)
binary.BigEndian.PutUint32(frame, uint32(len(info)))
_, err1 = pc.conn.Write(frame)
_, err1 = pc.conn.Write(info[:])
}
//var n int
//wire.WriteBinary(ourNodeInfo, p.conn, &n, &err1)
},
func() {
readBuffer := make([]byte, 4)
_, err2 = io.ReadFull(pc.conn, readBuffer[:])
if err2 != nil {
tendermintlog.Error("Peer handshake read info size failed", "err", err1)
return
}
len := binary.BigEndian.Uint32(readBuffer)
readBuffer = make([]byte, len)
_, err2 = io.ReadFull(pc.conn, readBuffer[:])
if err2 != nil {
tendermintlog.Error("Peer handshake read info failed", "err", err1)
return
}
err2 = json.Unmarshal(readBuffer, &peerNodeInfo)
if err2 != nil {
tendermintlog.Error("Peer handshake Unmarshal failed", "err", err1)
return
}
//var n int
//wire.ReadBinary(peerNodeInfo, p.conn, maxNodeInfoSize, &n, &err2)
tendermintlog.Info("Peer handshake", "peerNodeInfo", peerNodeInfo)
},
)
......@@ -537,7 +548,7 @@ FOR_LOOP:
tendermintlog.Debug("Receiving vote", "vote-height", vote.Height, "peerip", pc.ip.String())
pc.state.SetHasVote(vote)
} else if pkt.TypeID == ttypes.ProposalBlockID {
block := &ttypes.TendermintBlock{realMsg.(*tmtypes.TendermintBlock)}
block := &ttypes.TendermintBlock{TendermintBlock: realMsg.(*tmtypes.TendermintBlock)}
tendermintlog.Debug("Receiving proposal block", "block-height", block.Header.Height, "peerip", pc.ip.String())
pc.state.SetHasProposalBlock(block)
}
......@@ -956,6 +967,7 @@ OUTER_LOOP:
}
}
// StackError struct
type StackError struct {
Err interface{}
Stack []byte
......@@ -969,7 +981,6 @@ func (se StackError) Error() string {
return se.String()
}
//-----------------------------------------------------------------
// GetRoundState returns an atomic snapshot of the PeerRoundState.
// There's no point in mutating it since it won't change PeerState.
func (ps *PeerConnState) GetRoundState() *ttypes.PeerRoundState {
......@@ -1034,7 +1045,7 @@ func (ps *PeerConnState) PickVoteToSend(votes ttypes.VoteSetReader) (vote *ttype
return nil, false
}
height, round, type_, size := votes.Height(), votes.Round(), votes.Type(), votes.Size()
height, round, voteType, size := votes.Height(), votes.Round(), votes.Type(), votes.Size()
// Lazily set data using 'votes'.
if votes.IsCommit() {
......@@ -1042,28 +1053,28 @@ func (ps *PeerConnState) PickVoteToSend(votes ttypes.VoteSetReader) (vote *ttype
}
ps.ensureVoteBitArrays(height, size)
psVotes := ps.getVoteBitArray(height, round, type_)
psVotes := ps.getVoteBitArray(height, round, voteType)
if psVotes == nil {
return nil, false // Not something worth sending
}
if index, ok := votes.BitArray().Sub(psVotes).PickRandom(); ok {
tendermintlog.Debug("PickVoteToSend", "height", height, "index", index, "type", type_, "selfVotes", votes.BitArray().String(),
tendermintlog.Debug("PickVoteToSend", "height", height, "index", index, "type", voteType, "selfVotes", votes.BitArray().String(),
"peerVotes", psVotes.String(), "peerip", ps.ip.String())
ps.setHasVote(height, round, type_, index)
ps.setHasVote(height, round, voteType, index)
return votes.GetByIndex(index), true
}
return nil, false
}
func (ps *PeerConnState) getVoteBitArray(height int64, round int, type_ byte) *ttypes.BitArray {
if !ttypes.IsVoteTypeValid(type_) {
func (ps *PeerConnState) getVoteBitArray(height int64, round int, voteType byte) *ttypes.BitArray {
if !ttypes.IsVoteTypeValid(voteType) {
return nil
}
if ps.Height == height {
if ps.Round == round {
switch type_ {
switch voteType {
case ttypes.VoteTypePrevote:
return ps.Prevotes
case ttypes.VoteTypePrecommit:
......@@ -1071,7 +1082,7 @@ func (ps *PeerConnState) getVoteBitArray(height int64, round int, type_ byte) *t
}
}
if ps.CatchupCommitRound == round {
switch type_ {
switch voteType {
case ttypes.VoteTypePrevote:
return nil
case ttypes.VoteTypePrecommit:
......@@ -1079,7 +1090,7 @@ func (ps *PeerConnState) getVoteBitArray(height int64, round int, type_ byte) *t
}
}
if ps.ProposalPOLRound == round {
switch type_ {
switch voteType {
case ttypes.VoteTypePrevote:
return ps.ProposalPOL
case ttypes.VoteTypePrecommit:
......@@ -1090,7 +1101,7 @@ func (ps *PeerConnState) getVoteBitArray(height int64, round int, type_ byte) *t
}
if ps.Height == height+1 {
if ps.LastCommitRound == round {
switch type_ {
switch voteType {
case ttypes.VoteTypePrevote:
return nil
case ttypes.VoteTypePrecommit:
......@@ -1127,7 +1138,7 @@ func (ps *PeerConnState) ensureCatchupCommitRound(height int64, round int, numVa
}
}
// EnsureVoteVitArrays ensures the bit-arrays have been allocated for tracking
// EnsureVoteBitArrays ensures the bit-arrays have been allocated for tracking
// what votes this peer has received.
// NOTE: It's important to make sure that numValidators actually matches
// what the node sees as the number of validators for height.
......@@ -1166,14 +1177,14 @@ func (ps *PeerConnState) SetHasVote(vote *ttypes.Vote) {
ps.setHasVote(vote.Height, int(vote.Round), byte(vote.Type), int(vote.ValidatorIndex))
}
func (ps *PeerConnState) setHasVote(height int64, round int, type_ byte, index int) {
func (ps *PeerConnState) setHasVote(height int64, round int, voteType byte, index int) {
// NOTE: some may be nil BitArrays -> no side effects.
psVotes := ps.getVoteBitArray(height, round, type_)
psVotes := ps.getVoteBitArray(height, round, voteType)
tendermintlog.Debug("setHasVote before", "height", height, "psVotes", psVotes.String(), "peerip", ps.ip.String())
if psVotes != nil {
psVotes.SetIndex(index, true)
}
tendermintlog.Debug("setHasVote after", "height", height, "index", index, "type", type_, "peerVotes", psVotes.String(), "peerip", ps.ip.String())
tendermintlog.Debug("setHasVote after", "height", height, "index", index, "type", voteType, "peerVotes", psVotes.String(), "peerip", ps.ip.String())
}
// ApplyNewRoundStepMessage updates the peer state for the new round.
......
......@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Uses nacl's secret_box to encrypt a net.Conn.
// Package tendermint Uses nacl's secret_box to encrypt a net.Conn.
// It is (meant to be) an implementation of the STS protocol.
// Note we do not (yet) assume that a remote peer's pubkey
// is known ahead of time, and thus we are technically
......@@ -36,7 +36,7 @@ const (
authSigMsgSize = (32) + (64)
) // fixed size (length prefixed) byte arrays
// Implements net.Conn
// SecretConnection Implements net.Conn
type SecretConnection struct {
conn io.ReadWriteCloser
recvBuffer []byte
......@@ -46,7 +46,7 @@ type SecretConnection struct {
shrSecret *[32]byte // shared secret
}
// Performs handshake and returns a new authenticated SecretConnection.
// MakeSecretConnection Performs handshake and returns a new authenticated SecretConnection.
// Returns nil if error in handshake.
// Caller should call conn.Close()
// See docs/sts-final.pdf for more information.
......@@ -108,7 +108,7 @@ func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKey) (*
return sc, nil
}
// Returns authenticated remote pubkey
// RemotePubKey Returns authenticated remote pubkey
func (sc *SecretConnection) RemotePubKey() crypto.PubKey {
return sc.remPubKey
}
......@@ -140,9 +140,8 @@ func (sc *SecretConnection) Write(data []byte) (n int, err error) {
_, err := sc.conn.Write(sealedFrame)
if err != nil {
return n, err
} else {
n += len(chunk)
}
n += len(chunk)
}
return
}
......@@ -150,8 +149,8 @@ func (sc *SecretConnection) Write(data []byte) (n int, err error) {
// CONTRACT: data smaller than dataMaxSize is read atomically.
func (sc *SecretConnection) Read(data []byte) (n int, err error) {
if 0 < len(sc.recvBuffer) {
n_ := copy(data, sc.recvBuffer)
sc.recvBuffer = sc.recvBuffer[n_:]
count := copy(data, sc.recvBuffer)
sc.recvBuffer = sc.recvBuffer[count:]
return
}
......@@ -182,14 +181,24 @@ func (sc *SecretConnection) Read(data []byte) (n int, err error) {
return
}
// Implements net.Conn
func (sc *SecretConnection) Close() error { return sc.conn.Close() }
func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() }
func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() }
// Close Implements net.Conn
func (sc *SecretConnection) Close() error { return sc.conn.Close() }
// LocalAddr ...
func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() }
// RemoteAddr ...
func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() }
// SetDeadline ...
func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) }
// SetReadDeadline ...
func (sc *SecretConnection) SetReadDeadline(t time.Time) error {
return sc.conn.(net.Conn).SetReadDeadline(t)
}
// SetWriteDeadline ...
func (sc *SecretConnection) SetWriteDeadline(t time.Time) error {
return sc.conn.(net.Conn).SetWriteDeadline(t)
}
......@@ -343,7 +352,7 @@ func incr2Nonce(nonce *[24]byte) {
// increment nonce big-endian by 1 with wraparound.
func incrNonce(nonce *[24]byte) {
for i := 23; 0 <= i; i-- {
nonce[i] += 1
nonce[i]++
if nonce[i] != 0 {
return
}
......
......@@ -174,7 +174,7 @@ func MakeGenesisState(genDoc *ttypes.GenesisDoc) (State, error) {
for i, val := range genDoc.Validators {
pubKey, err := ttypes.PubKeyFromString(val.PubKey.Data)
if err != nil {
return State{}, fmt.Errorf("Error validate[i] in genesis file: %v", i, err)
return State{}, fmt.Errorf("Error validate[%v] in genesis file: %v", i, err)
}
// Make validator
......@@ -204,14 +204,15 @@ func MakeGenesisState(genDoc *ttypes.GenesisDoc) (State, error) {
}, nil
}
//-------------------stateDB------------------------
// CSStateDB just for EvidencePool and BlockExecutor
type CSStateDB struct {
client *TendermintClient
client *Client
state State
mtx sync.Mutex
}
func NewStateDB(client *TendermintClient, state State) *CSStateDB {
// NewStateDB make a new one
func NewStateDB(client *Client, state State) *CSStateDB {
r = rand.New(rand.NewSource(time.Now().UnixNano()))
return &CSStateDB{
client: client,
......@@ -219,6 +220,7 @@ func NewStateDB(client *TendermintClient, state State) *CSStateDB {
}
}
// LoadState convert external state to internal state
func LoadState(state *tmtypes.State) State {
stateTmp := State{
ChainID: state.GetChainID(),
......@@ -286,18 +288,21 @@ func LoadState(state *tmtypes.State) State {
return stateTmp
}
// SaveState to state cache
func (csdb *CSStateDB) SaveState(state State) {
csdb.mtx.Lock()
defer csdb.mtx.Unlock()
csdb.state = state.Copy()
}
// LoadState from state cache
func (csdb *CSStateDB) LoadState() State {
csdb.mtx.Lock()
defer csdb.mtx.Unlock()
return csdb.state
}
// LoadValidators by height
func (csdb *CSStateDB) LoadValidators(height int64) (*ttypes.ValidatorSet, error) {
if height == 0 {
return nil, nil
......@@ -363,6 +368,7 @@ func saveProposer(dest *tmtypes.Validator, source *ttypes.Validator) {
}
}
// SaveState convert internal state to external state
func SaveState(state State) *tmtypes.State {
newState := tmtypes.State{
ChainID: state.ChainID,
......@@ -405,6 +411,7 @@ func getprivkey(key string) crypto.PrivKey {
return priv
}
// LoadValidators convert all external validators to internal validators
func LoadValidators(des []*ttypes.Validator, source []*tmtypes.Validator) {
for i, item := range source {
if item.GetAddress() == nil || len(item.GetAddress()) == 0 {
......@@ -427,6 +434,7 @@ func LoadValidators(des []*ttypes.Validator, source []*tmtypes.Validator) {
}
}
// LoadProposer convert external proposer to internal proposer
func LoadProposer(source *tmtypes.Validator) (*ttypes.Validator, error) {
if source.GetAddress() == nil || len(source.GetAddress()) == 0 {
tendermintlog.Warn("LoadProposer get address is nil or empty")
......@@ -449,6 +457,7 @@ func LoadProposer(source *tmtypes.Validator) (*ttypes.Validator, error) {
return des, nil
}
// CreateBlockInfoTx make blockInfo to the first transaction of the block and execer is valnode
func CreateBlockInfoTx(pubkey string, lastCommit *tmtypes.TendermintCommit, seenCommit *tmtypes.TendermintCommit, state *tmtypes.State, proposal *tmtypes.Proposal, block *tmtypes.TendermintBlock) *types.Transaction {
blockNoTxs := *block
blockNoTxs.Txs = make([]*types.Transaction, 0)
......
This diff is collapsed.
......@@ -36,7 +36,7 @@ import (
var (
random *rand.Rand
loopCount int = 10
loopCount = 10
conn *grpc.ClientConn
c types.Chain33Client
)
......@@ -147,7 +147,7 @@ func prepareTxList() *types.Transaction {
key = generateKey(i, 32)
value = generateValue(i, 180)
nput := &pty.NormAction_Nput{&pty.NormPut{Key: key, Value: []byte(value)}}
nput := &pty.NormAction_Nput{Nput: &pty.NormPut{Key: key, Value: []byte(value)}}
action := &pty.NormAction{Value: nput, Ty: pty.NormActionPut}
tx := &types.Transaction{Execer: []byte("norm"), Payload: types.Encode(action), Fee: fee}
tx.To = address.ExecAddress("norm")
......
......@@ -29,7 +29,9 @@ const fee = 1e6
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var r *rand.Rand
var TxHeightOffset int64 = 0
// TxHeightOffset needed
var TxHeightOffset int64
func main() {
if len(os.Args) == 1 || os.Args[1] == "-h" {
......@@ -69,6 +71,7 @@ func main() {
}
}
// LoadHelp ...
func LoadHelp() {
fmt.Println("Available Commands:")
fmt.Println("perf [ip, size, num, interval, duration] {offset} : 写数据性能测试")
......@@ -77,6 +80,7 @@ func LoadHelp() {
fmt.Println("valnode [ip, pubkey, power] : 增加/删除/修改tendermint节点")
}
// Perf ...
func Perf(ip, size, num, interval, duration string) {
var numThread int
numInt, err := strconv.Atoi(num)
......@@ -128,6 +132,7 @@ func Perf(ip, size, num, interval, duration string) {
}
}
// Put ...
func Put(ip string, size string, privkey string) {
sizeInt, err := strconv.Atoi(size)
if err != nil {
......@@ -164,6 +169,7 @@ func Put(ip string, size string, privkey string) {
fmt.Printf("returned JSON: %s\n", string(b))
}
// Get ...
func Get(ip string, hash string) {
url := "http://" + ip + ":8801"
fmt.Println("transaction hash:", hash)
......@@ -209,8 +215,9 @@ func setTxHeight(ip string) {
fmt.Println("TxHeightOffset:", TxHeightOffset)
}
// RespMsg ...
type RespMsg struct {
Id int64 `json:"id"`
ID int64 `json:"id"`
Result rpctypes.Header `json:"result"`
Err string `json:"error"`
}
......@@ -245,6 +252,7 @@ func genaddress() (string, crypto.PrivKey) {
return addrto.String(), privto
}
// RandStringBytes ...
func RandStringBytes(n int) string {
b := make([]byte, n)
rand.Seed(time.Now().UnixNano())
......@@ -254,6 +262,7 @@ func RandStringBytes(n int) string {
return string(b)
}
// ValNode ...
func ValNode(ip, pubkey, power string) {
url := "http://" + ip + ":8801"
......
......@@ -21,12 +21,12 @@ import (
)
var (
blocklog = log15.New("module", "tendermint-block")
blocklog = log15.New("module", "tendermint-block")
// ConsensusCrypto define
ConsensusCrypto crypto.Crypto
)
//-----------------------------------------------------------------------------
//BlockID
// BlockID struct
type BlockID struct {
tmtypes.BlockID
}
......@@ -51,8 +51,7 @@ func (blockID BlockID) String() string {
return Fmt(`%v`, blockID.Hash)
}
//-----------------------------------------------------------------------------
//TendermintBlock
//TendermintBlock struct
type TendermintBlock struct {
*tmtypes.TendermintBlock
}
......@@ -186,12 +185,10 @@ func (b *TendermintBlock) StringIndented(indent string) string {
func (b *TendermintBlock) StringShort() string {
if b == nil {
return "nil-Block"
} else {
return Fmt("Block#%v", b.Hash())
}
return Fmt("Block#%v", b.Hash())
}
//-----------------------------------------------------------------------------
// Header defines the structure of a Tendermint block header
// TODO: limit header size
// NOTE: changes to the Header should be duplicated in the abci Header
......@@ -247,8 +244,7 @@ func (h *Header) StringIndented(indent string) string {
indent, h.Hash())
}
//-----------------------------------------------------------------------------
//Commit
// Commit struct
type Commit struct {
*tmtypes.TendermintCommit
......@@ -393,21 +389,21 @@ func (commit *Commit) StringIndented(indent string) string {
indent, commit.hash)
}
//-----------------------------------------------------------------------------
// SignedHeader is a header along with the commits that prove it
type SignedHeader struct {
Header *Header `json:"header"`
Commit *Commit `json:"commit"`
}
//-----------------------------------------------------------------------------
// EvidenceEnvelope ...
type EvidenceEnvelope struct {
*tmtypes.EvidenceEnvelope
}
// EvidenceData contains any evidence of malicious wrong-doing by validators
// EvidenceEnvelopeList contains any evidence of malicious wrong-doing by validators
type EvidenceEnvelopeList []EvidenceEnvelope
// Hash ...
func (env EvidenceEnvelope) Hash() []byte {
penv := env.EvidenceEnvelope
evidence := EvidenceEnvelope2Evidence(penv)
......@@ -464,6 +460,7 @@ func (evl EvidenceEnvelopeList) Has(evidence Evidence) bool {
return false
}
// EvidenceData ...
type EvidenceData struct {
*tmtypes.EvidenceData
hash []byte
......@@ -505,5 +502,4 @@ func (data *EvidenceData) StringIndented(indent string) string {
%s}#%v`,
indent, strings.Join(evStrings, "\n"+indent+" "),
indent, data.hash)
return ""
}
......@@ -23,6 +23,7 @@ type ErrEvidenceInvalid struct {
ErrorValue error
}
// NewEvidenceInvalidErr ...
func NewEvidenceInvalidErr(ev Evidence, err error) *ErrEvidenceInvalid {
return &ErrEvidenceInvalid{ev, err}
}
......@@ -39,8 +40,11 @@ const (
MockBad = "MockBad"
)
var EvidenceType2Type map[string]reflect.Type
var EvidenceType2Obj map[string]Evidence
// EvidenceType map define
var (
EvidenceType2Type map[string]reflect.Type
EvidenceType2Obj map[string]Evidence
)
// Evidence represents any provable malicious activity by a validator
type Evidence interface {
......@@ -205,22 +209,27 @@ func (dve *DuplicateVoteEvidence) Equal(ev Evidence) bool {
return bytes.Equal(SimpleHashFromBinary(dve), SimpleHashFromBinary(ev.(*DuplicateVoteEvidence)))
}
// TypeName ...
func (dve *DuplicateVoteEvidence) TypeName() string {
return DuplicateVote
}
// Copy ...
func (dve *DuplicateVoteEvidence) Copy() Evidence {
return &DuplicateVoteEvidence{}
}
// SetChild ...
func (dve *DuplicateVoteEvidence) SetChild(child proto.Message) {
dve.DuplicateVoteEvidence = child.(*tmtypes.DuplicateVoteEvidence)
}
// Child ...
func (dve *DuplicateVoteEvidence) Child() proto.Message {
return dve.DuplicateVoteEvidence
}
// SimpleHashFromBinary ...
func SimpleHashFromBinary(item *DuplicateVoteEvidence) []byte {
bytes, e := json.Marshal(item)
if e != nil {
......@@ -231,6 +240,7 @@ func SimpleHashFromBinary(item *DuplicateVoteEvidence) []byte {
}
// EvidenceEnvelope2Evidence ...
func EvidenceEnvelope2Evidence(envelope *tmtypes.EvidenceEnvelope) Evidence {
if v, ok := EvidenceType2Type[envelope.TypeName]; ok {
realMsg2 := reflect.New(v).Interface()
......@@ -247,69 +257,98 @@ func EvidenceEnvelope2Evidence(envelope *tmtypes.EvidenceEnvelope) Evidence {
return nil
}
//-----------------------------------------------------------------
// UNSTABLE
// MockGoodEvidence UNSTABLE
type MockGoodEvidence struct {
Height_ int64
Address_ []byte
Index_ int
MGHeight int64
MGAddress []byte
MGIndex int
}
// UNSTABLE
// NewMockGoodEvidence UNSTABLE
func NewMockGoodEvidence(height int64, index int, address []byte) MockGoodEvidence {
return MockGoodEvidence{height, address, index}
}
func (e MockGoodEvidence) Height() int64 { return e.Height_ }
func (e MockGoodEvidence) Address() []byte { return e.Address_ }
func (e MockGoodEvidence) Index() int { return e.Index_ }
// Height ...
func (e MockGoodEvidence) Height() int64 { return e.MGHeight }
// Address ...
func (e MockGoodEvidence) Address() []byte { return e.MGAddress }
// Index ...
func (e MockGoodEvidence) Index() int { return e.MGIndex }
// Hash ...
func (e MockGoodEvidence) Hash() []byte {
return []byte(Fmt("%d-%d", e.Height_, e.Index_))
return []byte(Fmt("%d-%d", e.MGHeight, e.MGIndex))
}
// Verify ...
func (e MockGoodEvidence) Verify(chainID string) error { return nil }
// Equal ...
func (e MockGoodEvidence) Equal(ev Evidence) bool {
e2 := ev.(MockGoodEvidence)
return e.Height_ == e2.Height_ &&
bytes.Equal(e.Address_, e2.Address_) &&
e.Index_ == e2.Index_
return e.MGHeight == e2.MGHeight &&
bytes.Equal(e.MGAddress, e2.MGAddress) &&
e.MGIndex == e2.MGIndex
}
func (e MockGoodEvidence) String() string {
return Fmt("GoodEvidence: %d/%s/%d", e.Height_, e.Address_, e.Index_)
return Fmt("GoodEvidence: %d/%s/%d", e.MGHeight, e.MGAddress, e.MGIndex)
}
// TypeName ...
func (e MockGoodEvidence) TypeName() string {
return MockGood
}
// Copy ...
func (e MockGoodEvidence) Copy() Evidence {
return &MockGoodEvidence{}
}
// SetChild ...
func (e MockGoodEvidence) SetChild(proto.Message) {}
// Child ...
func (e MockGoodEvidence) Child() proto.Message {
return nil
}
// UNSTABLE
// MockBadEvidence UNSTABLE
type MockBadEvidence struct {
MockGoodEvidence
}
// Verify ...
func (e MockBadEvidence) Verify(chainID string) error { return fmt.Errorf("MockBadEvidence") }
// Equal ...
func (e MockBadEvidence) Equal(ev Evidence) bool {
e2 := ev.(MockBadEvidence)
return e.Height_ == e2.Height_ &&
bytes.Equal(e.Address_, e2.Address_) &&
e.Index_ == e2.Index_
return e.MGHeight == e2.MGHeight &&
bytes.Equal(e.MGAddress, e2.MGAddress) &&
e.MGIndex == e2.MGIndex
}
func (e MockBadEvidence) String() string {
return Fmt("BadEvidence: %d/%s/%d", e.Height_, e.Address_, e.Index_)
return Fmt("BadEvidence: %d/%s/%d", e.MGHeight, e.MGAddress, e.MGIndex)
}
// TypeName ...
func (e MockBadEvidence) TypeName() string {
return MockBad
}
// Copy ...
func (e MockBadEvidence) Copy() Evidence {
return &MockBadEvidence{}
}
// SetChild ...
func (e MockBadEvidence) SetChild(proto.Message) {}
// Child ...
func (e MockBadEvidence) Child() proto.Message {
return nil
}
......@@ -325,11 +364,16 @@ type EvidencePool interface {
Update(*TendermintBlock)
}
// MockMempool is an empty implementation of a Mempool, useful for testing.
// MockEvidencePool is an empty implementation of a Mempool, useful for testing.
// UNSTABLE
type MockEvidencePool struct {
}
// PendingEvidence ...
func (m MockEvidencePool) PendingEvidence() []Evidence { return nil }
func (m MockEvidencePool) AddEvidence(Evidence) error { return nil }
func (m MockEvidencePool) Update(*TendermintBlock) {}
// AddEvidence ...
func (m MockEvidencePool) AddEvidence(Evidence) error { return nil }
// Update ...
func (m MockEvidencePool) Update(*TendermintBlock) {}
......@@ -12,6 +12,7 @@ import (
tmtypes "github.com/33cn/plugin/plugin/dapp/valnode/types"
)
// RoundVoteSet ...
type RoundVoteSet struct {
Prevotes *VoteSet
Precommits *VoteSet
......@@ -31,6 +32,8 @@ peer to prevent abuse.
We let each peer provide us with up to 2 unexpected "catchup" rounds.
One for their LastCommit round, and another for the official commit round.
*/
// HeightVoteSet ...
type HeightVoteSet struct {
chainID string
height int64
......@@ -42,6 +45,7 @@ type HeightVoteSet struct {
peerCatchupRounds map[string][]int // keys: peer.Key; values: at most 2 rounds
}
// NewHeightVoteSet ...
func NewHeightVoteSet(chainID string, height int64, valSet *ValidatorSet) *HeightVoteSet {
hvs := &HeightVoteSet{
chainID: chainID,
......@@ -50,6 +54,7 @@ func NewHeightVoteSet(chainID string, height int64, valSet *ValidatorSet) *Heigh
return hvs
}
// Reset ...
func (hvs *HeightVoteSet) Reset(height int64, valSet *ValidatorSet) {
hvs.mtx.Lock()
defer hvs.mtx.Unlock()
......@@ -63,19 +68,21 @@ func (hvs *HeightVoteSet) Reset(height int64, valSet *ValidatorSet) {
hvs.round = 0
}
// Height ...
func (hvs *HeightVoteSet) Height() int64 {
hvs.mtx.Lock()
defer hvs.mtx.Unlock()
return hvs.height
}
// Round ...
func (hvs *HeightVoteSet) Round() int {
hvs.mtx.Lock()
defer hvs.mtx.Unlock()
return hvs.round
}
// Create more RoundVoteSets up to round.
// SetRound Create more RoundVoteSets up to round.
func (hvs *HeightVoteSet) SetRound(round int) {
hvs.mtx.Lock()
defer hvs.mtx.Unlock()
......@@ -104,7 +111,7 @@ func (hvs *HeightVoteSet) addRound(round int) {
}
}
// Duplicate votes return added=false, err=nil.
// AddVote Duplicate votes return added=false, err=nil.
// By convention, peerKey is "" if origin is self.
func (hvs *HeightVoteSet) AddVote(vote *Vote, peerID string) (added bool, err error) {
hvs.mtx.Lock()
......@@ -132,19 +139,21 @@ func (hvs *HeightVoteSet) AddVote(vote *Vote, peerID string) (added bool, err er
return
}
// Prevotes ...
func (hvs *HeightVoteSet) Prevotes(round int) *VoteSet {
hvs.mtx.Lock()
defer hvs.mtx.Unlock()
return hvs.getVoteSet(round, VoteTypePrevote)
}
// Precommits ...
func (hvs *HeightVoteSet) Precommits(round int) *VoteSet {
hvs.mtx.Lock()
defer hvs.mtx.Unlock()
return hvs.getVoteSet(round, VoteTypePrecommit)
}
// Last round and blockID that has +2/3 prevotes for a particular block or nil.
// POLInfo Last round and blockID that has +2/3 prevotes for a particular block or nil.
// Returns -1 if no such round exists.
func (hvs *HeightVoteSet) POLInfo() (polRound int, polBlockID BlockID) {
hvs.mtx.Lock()
......@@ -159,19 +168,18 @@ func (hvs *HeightVoteSet) POLInfo() (polRound int, polBlockID BlockID) {
return -1, BlockID{}
}
func (hvs *HeightVoteSet) getVoteSet(round int, type_ byte) *VoteSet {
func (hvs *HeightVoteSet) getVoteSet(round int, voteType byte) *VoteSet {
rvs, ok := hvs.roundVoteSets[round]
if !ok {
return nil
}
switch type_ {
switch voteType {
case VoteTypePrevote:
return rvs.Prevotes
case VoteTypePrecommit:
return rvs.Precommits
default:
panic(Fmt("Panicked on a Sanity Check: %v", Fmt("Unexpected vote type %X", type_)))
return nil
panic(Fmt("Panicked on a Sanity Check: %v", Fmt("Unexpected vote type %X", voteType)))
}
}
......@@ -179,6 +187,7 @@ func (hvs *HeightVoteSet) String() string {
return hvs.StringIndented("")
}
// StringIndented ...
func (hvs *HeightVoteSet) StringIndented(indent string) string {
hvs.mtx.Lock()
defer hvs.mtx.Unlock()
......@@ -208,17 +217,17 @@ func (hvs *HeightVoteSet) StringIndented(indent string) string {
indent)
}
// If a peer claims that it has 2/3 majority for given blockKey, call this.
// SetPeerMaj23 If a peer claims that it has 2/3 majority for given blockKey, call this.
// NOTE: if there are too many peers, or too much peer churn,
// this can cause memory issues.
// TODO: implement ability to remove peers too
func (hvs *HeightVoteSet) SetPeerMaj23(round int, type_ byte, peerID string, blockID *tmtypes.BlockID) {
func (hvs *HeightVoteSet) SetPeerMaj23(round int, voteType byte, peerID string, blockID *tmtypes.BlockID) {
hvs.mtx.Lock()
defer hvs.mtx.Unlock()
if !IsVoteTypeValid(type_) {
if !IsVoteTypeValid(voteType) {
return
}
voteSet := hvs.getVoteSet(round, type_)
voteSet := hvs.getVoteSet(round, voteType)
if voteSet == nil {
return
}
......
......@@ -82,7 +82,7 @@ func DefaultBlockGossip() BlockGossip {
}
}
// DefaultEvidence Params returns a default EvidenceParams.
// DefaultEvidenceParams returns a default EvidenceParams.
func DefaultEvidenceParams() EvidenceParams {
return EvidenceParams{
MaxAge: 100000, // 27.8 hrs at 1block/s
......
......@@ -22,6 +22,7 @@ var (
pvFile = "priv_validator_"
)
// KeyFileCmd ...
func KeyFileCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "keyfile",
......@@ -34,6 +35,7 @@ func KeyFileCmd() *cobra.Command {
return cmd
}
// CreateCmd ...
func CreateCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "create",
......@@ -49,6 +51,7 @@ func addCreateCmdFlags(cmd *cobra.Command) {
cmd.MarkFlagRequired("num")
}
// RandStr ...
func RandStr(length int) string {
chars := []byte{}
MAIN_LOOP:
......
......@@ -12,16 +12,15 @@ import (
tmtypes "github.com/33cn/plugin/plugin/dapp/valnode/types"
)
//-----------------------------------------------------------------------------
// RoundStepType enum type
// RoundStepType enumerates the state of the consensus state machine
type RoundStepType uint8 // These must be numeric, ordered.
var (
// MsgMap define
MsgMap map[byte]reflect.Type
)
// step and message id define
const (
RoundStepNewHeight = RoundStepType(0x01) // Wait til CommitTime + timeoutCommit
RoundStepNewRound = RoundStepType(0x02) // Setup new round and go to RoundStepPropose
......@@ -49,6 +48,7 @@ const (
PacketTypePong = byte(0xfe)
)
// InitMessageMap ...
func InitMessageMap() {
MsgMap = map[byte]reflect.Type{
EvidenceListID: reflect.TypeOf(tmtypes.EvidenceData{}),
......@@ -114,6 +114,7 @@ type RoundState struct {
LastValidators *ValidatorSet
}
// RoundStateMessage ...
func (rs *RoundState) RoundStateMessage() *tmtypes.NewRoundStepMsg {
return &tmtypes.NewRoundStepMsg{
Height: rs.Height,
......@@ -164,7 +165,7 @@ func (rs *RoundState) StringShort() string {
rs.Height, rs.Round, rs.Step, rs.StartTime)
}
//---------------------PeerRoundState----------------------------
// PeerRoundState ...
type PeerRoundState struct {
Height int64 // Height peer is at
Round int // Round peer is at, -1 if unknown.
......@@ -211,16 +212,20 @@ func (prs PeerRoundState) StringIndented(indent string) string {
}
//---------------------Canonical json-----------------------------------
// CanonicalJSONBlockID ...
type CanonicalJSONBlockID struct {
Hash []byte `json:"hash,omitempty"`
PartsHeader CanonicalJSONPartSetHeader `json:"parts,omitempty"`
}
// CanonicalJSONPartSetHeader ...
type CanonicalJSONPartSetHeader struct {
Hash []byte `json:"hash"`
Total int `json:"total"`
}
// CanonicalJSONProposal ...
type CanonicalJSONProposal struct {
BlockBytes []byte `json:"block_parts_header"`
Height int64 `json:"height"`
......@@ -230,6 +235,7 @@ type CanonicalJSONProposal struct {
Timestamp string `json:"timestamp"`
}
// CanonicalJSONVote ...
type CanonicalJSONVote struct {
BlockID CanonicalJSONBlockID `json:"block_id"`
Height int64 `json:"height"`
......@@ -238,6 +244,7 @@ type CanonicalJSONVote struct {
Type byte `json:"type"`
}
// CanonicalJSONHeartbeat ...
type CanonicalJSONHeartbeat struct {
Height int64 `json:"height"`
Round int `json:"round"`
......@@ -246,33 +253,36 @@ type CanonicalJSONHeartbeat struct {
ValidatorIndex int `json:"validator_index"`
}
//------------------------------------
// Messages including a "chain id" can only be applied to one chain, hence "Once"
// CanonicalJSONOnceProposal ...
type CanonicalJSONOnceProposal struct {
ChainID string `json:"chain_id"`
Proposal CanonicalJSONProposal `json:"proposal"`
}
// CanonicalJSONOnceVote ...
type CanonicalJSONOnceVote struct {
ChainID string `json:"chain_id"`
Vote CanonicalJSONVote `json:"vote"`
}
// CanonicalJSONOnceHeartbeat ...
type CanonicalJSONOnceHeartbeat struct {
ChainID string `json:"chain_id"`
Heartbeat CanonicalJSONHeartbeat `json:"heartbeat"`
}
//-----------------------------------
// Canonicalize the structs
// CanonicalBlockID ...
func CanonicalBlockID(blockID BlockID) CanonicalJSONBlockID {
return CanonicalJSONBlockID{
Hash: blockID.Hash,
}
}
// CanonicalProposal ...
func CanonicalProposal(proposal *Proposal) CanonicalJSONProposal {
return CanonicalJSONProposal{
//BlockBytes: proposal.BlockBytes,
......@@ -286,6 +296,7 @@ func CanonicalProposal(proposal *Proposal) CanonicalJSONProposal {
}
}
// CanonicalVote ...
func CanonicalVote(vote *Vote) CanonicalJSONVote {
return CanonicalJSONVote{
BlockID: CanonicalJSONBlockID{Hash: vote.BlockID.Hash},
......@@ -296,6 +307,7 @@ func CanonicalVote(vote *Vote) CanonicalJSONVote {
}
}
// CanonicalHeartbeat ...
func CanonicalHeartbeat(heartbeat *Heartbeat) CanonicalJSONHeartbeat {
return CanonicalJSONHeartbeat{
heartbeat.Height,
......@@ -306,6 +318,7 @@ func CanonicalHeartbeat(heartbeat *Heartbeat) CanonicalJSONHeartbeat {
}
}
// CanonicalTime ...
func CanonicalTime(t time.Time) string {
// note that sending time over go-wire resets it to
// local time, we need to force UTC here, so the
......
......@@ -17,6 +17,7 @@ import (
tmtypes "github.com/33cn/plugin/plugin/dapp/valnode/types"
)
// error defines
var (
ErrVoteUnexpectedStep = errors.New("Unexpected step")
ErrVoteInvalidValidatorIndex = errors.New("Invalid validator index")
......@@ -44,7 +45,6 @@ func SignBytes(chainID string, o Signable) []byte {
return buf.Bytes()
}
//----------------------Proposal----------------------
// Proposal defines a block proposal for the consensus.
// It refers to the block only by its PartSetHeader.
// It must be signed by the correct proposer for the given Height/Round
......@@ -89,12 +89,12 @@ func (p *Proposal) WriteSignBytes(chainID string, w io.Writer, n *int, err *erro
*err = e
return
}
n_, err_ := w.Write(byteOnceProposal)
*n = n_
*err = err_
number, writeErr := w.Write(byteOnceProposal)
*n = number
*err = writeErr
}
//-------------------heartbeat-------------------------
// Heartbeat ...
type Heartbeat struct {
*tmtypes.Heartbeat
}
......@@ -114,12 +114,12 @@ func (heartbeat *Heartbeat) WriteSignBytes(chainID string, w io.Writer, n *int,
*err = e
return
}
n_, err_ := w.Write(byteHeartbeat)
*n = n_
*err = err_
number, writeErr := w.Write(byteHeartbeat)
*n = number
*err = writeErr
}
//----------------------vote-----------------------------
// ErrVoteConflictingVotes ...
type ErrVoteConflictingVotes struct {
*DuplicateVoteEvidence
}
......@@ -133,6 +133,7 @@ func (err *ErrVoteConflictingVotes) Error() string {
return fmt.Sprintf("Conflicting votes from validator %v", addr)
}
// NewConflictingVoteError ...
func NewConflictingVoteError(val *Validator, voteA, voteB *tmtypes.Vote) *ErrVoteConflictingVotes {
keyString := fmt.Sprintf("%X", val.PubKey)
return &ErrVoteConflictingVotes{
......@@ -153,8 +154,9 @@ const (
VoteTypePrecommit = byte(0x02)
)
func IsVoteTypeValid(type_ byte) bool {
switch type_ {
// IsVoteTypeValid ...
func IsVoteTypeValid(voteType byte) bool {
switch voteType {
case VoteTypePrevote:
return true
case VoteTypePrecommit:
......@@ -164,11 +166,12 @@ func IsVoteTypeValid(type_ byte) bool {
}
}
// Represents a prevote, precommit, or commit vote from validators for consensus.
// Vote Represents a prevote, precommit, or commit vote from validators for consensus.
type Vote struct {
*tmtypes.Vote
}
// WriteSignBytes ...
func (vote *Vote) WriteSignBytes(chainID string, w io.Writer, n *int, err *error) {
if *err != nil {
return
......@@ -183,11 +186,12 @@ func (vote *Vote) WriteSignBytes(chainID string, w io.Writer, n *int, err *error
votelog.Error("vote WriteSignBytes marshal failed", "err", e)
return
}
n_, err_ := w.Write(byteVote)
*n = n_
*err = err_
number, writeErr := w.Write(byteVote)
*n = number
*err = writeErr
}
// Copy ...
func (vote *Vote) Copy() *Vote {
voteCopy := *vote
return &voteCopy
......@@ -214,6 +218,7 @@ func (vote *Vote) String() string {
CanonicalTime(time.Unix(0, vote.Timestamp)))
}
// Verify ...
func (vote *Vote) Verify(chainID string, pubKey crypto.PubKey) error {
addr := GenAddressByPubKey(pubKey)
if !bytes.Equal(addr, vote.ValidatorAddress) {
......@@ -232,6 +237,7 @@ func (vote *Vote) Verify(chainID string, pubKey crypto.PubKey) error {
return nil
}
// Hash ...
func (vote *Vote) Hash() []byte {
if vote == nil {
//votelog.Error("vote hash is nil")
......
......@@ -22,6 +22,7 @@ import (
)
const (
// RFC3339Millis ...
RFC3339Millis = "2006-01-02T15:04:05.000Z" // forced microseconds
timeFormat = RFC3339Millis
)
......@@ -29,9 +30,11 @@ const (
var (
randgen *rand.Rand
randMux sync.Mutex
Fmt = fmt.Sprintf
// Fmt ...
Fmt = fmt.Sprintf
)
// Init ...
func Init() {
if randgen == nil {
randMux.Lock()
......@@ -40,10 +43,12 @@ func Init() {
}
}
// WriteFile ...
func WriteFile(filePath string, contents []byte, mode os.FileMode) error {
return ioutil.WriteFile(filePath, contents, mode)
}
// WriteFileAtomic ...
func WriteFileAtomic(filePath string, newBytes []byte, mode os.FileMode) error {
dir := filepath.Dir(filePath)
f, err := ioutil.TempFile(dir, "")
......@@ -70,7 +75,7 @@ func WriteFileAtomic(filePath string, newBytes []byte, mode os.FileMode) error {
return err
}
//----------------------------------------------------------
// Tempfile ...
func Tempfile(prefix string) (*os.File, string) {
file, err := ioutil.TempFile("", prefix)
if err != nil {
......@@ -79,12 +84,14 @@ func Tempfile(prefix string) (*os.File, string) {
return file, file.Name()
}
// Fingerprint ...
func Fingerprint(slice []byte) []byte {
fingerprint := make([]byte, 6)
copy(fingerprint, slice)
return fingerprint
}
// Kill ...
func Kill() error {
p, err := os.FindProcess(os.Getpid())
if err != nil {
......@@ -93,12 +100,13 @@ func Kill() error {
return p.Signal(syscall.SIGTERM)
}
// Exit ...
func Exit(s string) {
fmt.Printf(s + "\n")
os.Exit(1)
}
//-----------------------------------------------------------
// Parallel ...
func Parallel(tasks ...func()) {
var wg sync.WaitGroup
wg.Add(len(tasks))
......@@ -114,6 +122,7 @@ func Parallel(tasks ...func()) {
// Percent represents a percentage in increments of 1/1000th of a percent.
type Percent uint32
// Float ...
func (p Percent) Float() float64 {
return float64(p) * 1e-3
}
......@@ -127,7 +136,7 @@ func (p Percent) String() string {
return string(append(b, '%'))
}
//-------------------------------------------------------------------
// MinInt ...
func MinInt(a, b int) int {
if a < b {
return a
......@@ -135,6 +144,7 @@ func MinInt(a, b int) int {
return b
}
// MaxInt ...
func MaxInt(a, b int) int {
if a > b {
return a
......@@ -142,7 +152,7 @@ func MaxInt(a, b int) int {
return b
}
//--------------------------------------------------------------
// RandIntn ...
func RandIntn(n int) int {
if n <= 0 {
panic("invalid argument to Intn")
......@@ -159,6 +169,7 @@ func RandIntn(n int) int {
return int(i64)
}
// RandUint32 ...
func RandUint32() uint32 {
randMux.Lock()
u32 := randgen.Uint32()
......@@ -166,6 +177,7 @@ func RandUint32() uint32 {
return u32
}
// RandInt63n ...
func RandInt63n(n int64) int64 {
randMux.Lock()
i64 := randgen.Int63n(n)
......@@ -173,26 +185,28 @@ func RandInt63n(n int64) int64 {
return i64
}
//-------------------------------------------------------------
// PanicSanity ...
func PanicSanity(v interface{}) {
panic(Fmt("Panicked on a Sanity Check: %v", v))
}
// PanicCrisis ...
func PanicCrisis(v interface{}) {
panic(Fmt("Panicked on a Crisis: %v", v))
}
// PanicQ ...
func PanicQ(v interface{}) {
panic(Fmt("Panicked questionably: %v", v))
}
//--------------------BitArray------------------------
// BitArray ...
type BitArray struct {
*tmtypes.TendermintBitArray
mtx sync.Mutex `json:"-"`
mtx sync.Mutex
}
// There is no BitArray whose Size is 0. Use nil instead.
// NewBitArray There is no BitArray whose Size is 0. Use nil instead.
func NewBitArray(bits int) *BitArray {
if bits <= 0 {
return nil
......@@ -205,6 +219,7 @@ func NewBitArray(bits int) *BitArray {
}
}
// Size ...
func (bA *BitArray) Size() int {
if bA == nil {
return 0
......@@ -212,7 +227,7 @@ func (bA *BitArray) Size() int {
return int(bA.Bits)
}
// NOTE: behavior is undefined if i >= bA.Bits
// GetIndex NOTE: behavior is undefined if i >= bA.Bits
func (bA *BitArray) GetIndex(i int) bool {
if bA == nil {
return false
......@@ -229,7 +244,7 @@ func (bA *BitArray) getIndex(i int) bool {
return bA.Elems[i/64]&(uint64(1)<<uint(i%64)) > 0
}
// NOTE: behavior is undefined if i >= bA.Bits
// SetIndex NOTE: behavior is undefined if i >= bA.Bits
func (bA *BitArray) SetIndex(i int, v bool) bool {
if bA == nil {
return false
......@@ -251,6 +266,7 @@ func (bA *BitArray) setIndex(i int, v bool) bool {
return true
}
// Copy ...
func (bA *BitArray) Copy() *BitArray {
if bA == nil {
return nil
......@@ -280,7 +296,7 @@ func (bA *BitArray) copyBits(bits int) *BitArray {
}
}
// Returns a BitArray of larger bits size.
// Or Returns a BitArray of larger bits size.
func (bA *BitArray) Or(o *BitArray) *BitArray {
if bA == nil && o.TendermintBitArray == nil {
return nil
......@@ -300,7 +316,7 @@ func (bA *BitArray) Or(o *BitArray) *BitArray {
return c
}
// Returns a BitArray of smaller bit size.
// And Returns a BitArray of smaller bit size.
func (bA *BitArray) And(o *BitArray) *BitArray {
if bA == nil || o.TendermintBitArray == nil {
return nil
......@@ -318,6 +334,7 @@ func (bA *BitArray) and(o *BitArray) *BitArray {
return c
}
// Not ...
func (bA *BitArray) Not() *BitArray {
if bA == nil {
return nil // Degenerate
......@@ -331,6 +348,7 @@ func (bA *BitArray) Not() *BitArray {
return c
}
// Sub ...
func (bA *BitArray) Sub(o *BitArray) *BitArray {
if bA == nil || o.TendermintBitArray == nil {
return nil
......@@ -354,6 +372,7 @@ func (bA *BitArray) Sub(o *BitArray) *BitArray {
return bA.and(o.Not()) // Note degenerate case where o == nil
}
// IsEmpty ...
func (bA *BitArray) IsEmpty() bool {
if bA == nil {
return true // should this be opposite?
......@@ -368,6 +387,7 @@ func (bA *BitArray) IsEmpty() bool {
return true
}
// IsFull ...
func (bA *BitArray) IsFull() bool {
if bA == nil {
return true
......@@ -388,6 +408,7 @@ func (bA *BitArray) IsFull() bool {
return (lastElem+1)&((uint64(1)<<uint(lastElemBits))-1) == 0
}
// PickRandom ...
func (bA *BitArray) PickRandom() (int, bool) {
if bA == nil {
return 0, false
......@@ -440,6 +461,7 @@ func (bA *BitArray) String() string {
return bA.stringIndented("")
}
// StringIndented ...
func (bA *BitArray) StringIndented(indent string) string {
if bA == nil {
return "nil-BitArray"
......@@ -476,6 +498,7 @@ func (bA *BitArray) stringIndented(indent string) string {
return fmt.Sprintf("BA{%v:%v}", bA.Bits, strings.Join(lines, indent))
}
// Bytes ...
func (bA *BitArray) Bytes() []byte {
bA.mtx.Lock()
defer bA.mtx.Unlock()
......@@ -490,7 +513,7 @@ func (bA *BitArray) Bytes() []byte {
return bytes
}
// NOTE: other bitarray o is not locked when reading,
// Update NOTE: other bitarray o is not locked when reading,
// so if necessary, caller must copy or lock o prior to calling Update.
// If bA is nil, does nothing.
func (bA *BitArray) Update(o *BitArray) {
......@@ -503,12 +526,12 @@ func (bA *BitArray) Update(o *BitArray) {
}
//------------------Heap----------------------
// Comparable ...
type Comparable interface {
Less(o interface{}) bool
}
//-----------------------------------------------------------------------------
/*
Example usage:
h := NewHeap()
......@@ -522,22 +545,27 @@ Example usage:
fmt.Println(h.Pop())
*/
// Heap ...
type Heap struct {
pq priorityQueue
}
// NewHeap ...
func NewHeap() *Heap {
return &Heap{pq: make([]*pqItem, 0)}
}
// Len ...
func (h *Heap) Len() int64 {
return int64(len(h.pq))
}
// Push ...
func (h *Heap) Push(value interface{}, priority Comparable) {
heap.Push(&h.pq, &pqItem{value: value, priority: priority})
}
// Peek ...
func (h *Heap) Peek() interface{} {
if len(h.pq) == 0 {
return nil
......@@ -545,10 +573,12 @@ func (h *Heap) Peek() interface{} {
return h.pq[0].value
}
// Update ...
func (h *Heap) Update(value interface{}, priority Comparable) {
h.pq.Update(h.pq[0], value, priority)
}
// Pop ...
func (h *Heap) Pop() interface{} {
item := heap.Pop(&h.pq).(*pqItem)
return item.value
......
......@@ -19,6 +19,7 @@ import (
var validatorsetlog = log15.New("module", "tendermint-val")
// Validator ...
type Validator struct {
Address []byte `json:"address"`
PubKey []byte `json:"pub_key"`
......@@ -27,6 +28,7 @@ type Validator struct {
Accum int64 `json:"accum"`
}
// NewValidator ...
func NewValidator(pubKey crypto.PubKey, votingPower int64) *Validator {
return &Validator{
Address: GenAddressByPubKey(pubKey),
......@@ -36,14 +38,14 @@ func NewValidator(pubKey crypto.PubKey, votingPower int64) *Validator {
}
}
// Creates a new copy of the validator so we can mutate accum.
// Copy Creates a new copy of the validator so we can mutate accum.
// Panics if the validator is nil.
func (v *Validator) Copy() *Validator {
vCopy := *v
return &vCopy
}
// Returns the one with higher Accum.
// CompareAccum Returns the one with higher Accum.
func (v *Validator) CompareAccum(other *Validator) *Validator {
if v == nil {
return other
......@@ -105,6 +107,7 @@ type ValidatorSet struct {
totalVotingPower int64
}
// NewValidatorSet ...
func NewValidatorSet(vals []*Validator) *ValidatorSet {
validators := make([]*Validator, len(vals))
for i, val := range vals {
......@@ -122,7 +125,7 @@ func NewValidatorSet(vals []*Validator) *ValidatorSet {
return vs
}
// incrementAccum and update the proposer
// IncrementAccum incrementAccum and update the proposer
// TODO: mind the overflow when times and votingPower shares too large.
func (valSet *ValidatorSet) IncrementAccum(times int) {
// Add VotingPower * times to each validator and order into heap.
......@@ -143,6 +146,7 @@ func (valSet *ValidatorSet) IncrementAccum(times int) {
}
}
// Copy ...
func (valSet *ValidatorSet) Copy() *ValidatorSet {
validators := make([]*Validator, len(valSet.Validators))
for i, val := range valSet.Validators {
......@@ -156,6 +160,7 @@ func (valSet *ValidatorSet) Copy() *ValidatorSet {
}
}
// HasAddress ...
func (valSet *ValidatorSet) HasAddress(address []byte) bool {
idx := sort.Search(len(valSet.Validators), func(i int) bool {
return bytes.Compare(address, valSet.Validators[i].Address) <= 0
......@@ -163,15 +168,15 @@ func (valSet *ValidatorSet) HasAddress(address []byte) bool {
return idx != len(valSet.Validators) && bytes.Equal(valSet.Validators[idx].Address, address)
}
// GetByAddress ...
func (valSet *ValidatorSet) GetByAddress(address []byte) (index int, val *Validator) {
idx := sort.Search(len(valSet.Validators), func(i int) bool {
return bytes.Compare(address, valSet.Validators[i].Address) <= 0
})
if idx != len(valSet.Validators) && bytes.Equal(valSet.Validators[idx].Address, address) {
return idx, valSet.Validators[idx].Copy()
} else {
return -1, nil
}
return -1, nil
}
// GetByIndex returns the validator by index.
......@@ -185,10 +190,12 @@ func (valSet *ValidatorSet) GetByIndex(index int) (address []byte, val *Validato
return val.Address, val.Copy()
}
// Size ...
func (valSet *ValidatorSet) Size() int {
return len(valSet.Validators)
}
// TotalVotingPower ...
func (valSet *ValidatorSet) TotalVotingPower() int64 {
if valSet.totalVotingPower == 0 {
for _, val := range valSet.Validators {
......@@ -198,6 +205,7 @@ func (valSet *ValidatorSet) TotalVotingPower() int64 {
return valSet.totalVotingPower
}
// GetProposer ...
func (valSet *ValidatorSet) GetProposer() (proposer *Validator) {
if len(valSet.Validators) == 0 {
return nil
......@@ -218,6 +226,7 @@ func (valSet *ValidatorSet) findProposer() *Validator {
return proposer
}
// Hash ...
func (valSet *ValidatorSet) Hash() []byte {
if len(valSet.Validators) == 0 {
return nil
......@@ -229,6 +238,7 @@ func (valSet *ValidatorSet) Hash() []byte {
return merkle.GetMerkleRoot(hashables)
}
// Add ...
func (valSet *ValidatorSet) Add(val *Validator) (added bool) {
val = val.Copy()
idx := sort.Search(len(valSet.Validators), func(i int) bool {
......@@ -255,39 +265,40 @@ func (valSet *ValidatorSet) Add(val *Validator) (added bool) {
}
}
// Update ...
func (valSet *ValidatorSet) Update(val *Validator) (updated bool) {
index, sameVal := valSet.GetByAddress(val.Address)
if sameVal == nil {
return false
} else {
valSet.Validators[index] = val.Copy()
// Invalidate cache
valSet.Proposer = nil
valSet.totalVotingPower = 0
return true
}
valSet.Validators[index] = val.Copy()
// Invalidate cache
valSet.Proposer = nil
valSet.totalVotingPower = 0
return true
}
// Remove ...
func (valSet *ValidatorSet) Remove(address []byte) (val *Validator, removed bool) {
idx := sort.Search(len(valSet.Validators), func(i int) bool {
return bytes.Compare(address, valSet.Validators[i].Address) <= 0
})
if idx == len(valSet.Validators) || !bytes.Equal(valSet.Validators[idx].Address, address) {
return nil, false
} else {
removedVal := valSet.Validators[idx]
newValidators := valSet.Validators[:idx]
if idx+1 < len(valSet.Validators) {
newValidators = append(newValidators, valSet.Validators[idx+1:]...)
}
valSet.Validators = newValidators
// Invalidate cache
valSet.Proposer = nil
valSet.totalVotingPower = 0
return removedVal, true
}
removedVal := valSet.Validators[idx]
newValidators := valSet.Validators[:idx]
if idx+1 < len(valSet.Validators) {
newValidators = append(newValidators, valSet.Validators[idx+1:]...)
}
valSet.Validators = newValidators
// Invalidate cache
valSet.Proposer = nil
valSet.totalVotingPower = 0
return removedVal, true
}
// Iterate ...
func (valSet *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) {
for i, val := range valSet.Validators {
stop := fn(i, val.Copy())
......@@ -297,7 +308,7 @@ func (valSet *ValidatorSet) Iterate(fn func(index int, val *Validator) bool) {
}
}
// Verify that +2/3 of the set had signed the given signBytes
// VerifyCommit Verify that +2/3 of the set had signed the given signBytes
func (valSet *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, height int64, commit *Commit) error {
if valSet.Size() != len(commit.Precommits) {
return fmt.Errorf("Invalid commit -- wrong set size: %v vs %v", valSet.Size(), len(commit.Precommits))
......@@ -350,10 +361,9 @@ func (valSet *ValidatorSet) VerifyCommit(chainID string, blockID BlockID, height
if talliedVotingPower > valSet.TotalVotingPower()*2/3 {
return nil
} else {
return fmt.Errorf("Invalid commit -- insufficient voting power: got %v, needed %v",
talliedVotingPower, (valSet.TotalVotingPower()*2/3 + 1))
}
return fmt.Errorf("Invalid commit -- insufficient voting power: got %v, needed %v",
talliedVotingPower, (valSet.TotalVotingPower()*2/3 + 1))
}
// VerifyCommitAny will check to see if the set would
......@@ -453,6 +463,7 @@ func (valSet *ValidatorSet) String() string {
return valSet.StringIndented("")
}
// StringIndented ...
func (valSet *ValidatorSet) StringIndented(indent string) string {
if valSet == nil {
return "nil-ValidatorSet"
......@@ -474,9 +485,9 @@ func (valSet *ValidatorSet) StringIndented(indent string) string {
}
//-------------------------------------
// Implements sort for sorting validators by address.
// ValidatorsByAddress ...
type ValidatorsByAddress []*Validator
func (vs ValidatorsByAddress) Len() int {
......
......@@ -7,11 +7,14 @@ package ticket
import (
"testing"
"github.com/33cn/plugin/plugin/dapp/ticket/types"
"github.com/33cn/chain33/types"
"github.com/33cn/chain33/common/crypto"
"github.com/33cn/chain33/queue"
_ "github.com/33cn/chain33/system"
"github.com/33cn/chain33/util/testnode"
_ "github.com/33cn/plugin/plugin/dapp/init"
ty "github.com/33cn/plugin/plugin/dapp/ticket/types"
_ "github.com/33cn/plugin/plugin/store/init"
"github.com/stretchr/testify/assert"
)
......@@ -28,8 +31,8 @@ func TestTicket(t *testing.T) {
func TestTicketMap(t *testing.T) {
c := Client{}
ticketList := &types.ReplyTicketList{}
ticketList.Tickets = []*types.Ticket{
ticketList := &ty.ReplyTicketList{}
ticketList.Tickets = []*ty.Ticket{
{TicketId: "1111"},
{TicketId: "2222"},
{TicketId: "3333"},
......@@ -40,5 +43,34 @@ func TestTicketMap(t *testing.T) {
assert.Equal(t, c.getTicketCount(), int64(4))
c.delTicket("3333")
assert.Equal(t, c.getTicketCount(), int64(3))
}
func TestProcEvent(t *testing.T) {
c := Client{}
ret := c.ProcEvent(queue.Message{})
assert.Equal(t, ret, true)
}
func Test_genPrivHash(t *testing.T) {
c, err := crypto.New(types.GetSignName("", types.SECP256K1))
assert.NoError(t, err)
priv, _ := c.GenKey()
bt, err := genPrivHash(priv, "AA:BB:CC:DD")
assert.NotNil(t, err)
assert.Equal(t, 0, len(bt))
bt, err = genPrivHash(priv, "111:222:333:444")
assert.NoError(t, err)
assert.Equal(t, 32, len(bt))
}
func Test_getNextRequiredDifficulty(t *testing.T) {
c := &Client{}
bits, bt, err := c.getNextRequiredDifficulty(nil, 1)
assert.NoError(t, err)
assert.Equal(t, bt, defaultModify)
assert.Equal(t, bits, types.GetP(0).PowLimitBits)
}
// 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.
package init
import (
......
......@@ -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 = 750
TyLogBlackwhitePlay = 751
TyLogBlackwhiteShow = 752
TyLogBlackwhiteTimeout = 753
TyLogBlackwhiteDone = 754
// 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 = "GetBlackwhiteRoundInfo"
// GetBlackwhiteRoundInfo 用于在cmd里面的区分不同的查询
GetBlackwhiteRoundInfo = "GetBlackwhiteRoundInfo"
// GetBlackwhiteByStatusAndAddr 用于在cmd里面的区分不同的查询
GetBlackwhiteByStatusAndAddr = "GetBlackwhiteByStatusAndAddr"
GetBlackwhiteloopResult = "GetBlackwhiteloopResult"
// GetBlackwhiteloopResult 用于在cmd里面的区分不同的查询
GetBlackwhiteloopResult = "GetBlackwhiteloopResult"
)
var (
// BlackwhiteX 执行器名字
BlackwhiteX = "blackwhite"
glog = log15.New("module", BlackwhiteX)
//GRPCName = "chain33.blackwhite"
JRPCName = "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 = errors.New("ErrIncorrectStatus")
// ErrIncorrectStatus 所处游戏状态不正确
ErrIncorrectStatus = errors.New("ErrIncorrectStatus")
// ErrRepeatPlayerAddr 重复玩家
ErrRepeatPlayerAddr = errors.New("ErrRepeatPlayerAddress")
ErrNoTimeoutDone = errors.New("ErrNoTimeoutDone")
ErrNoExistAddr = errors.New("ErrNoExistAddress")
ErrNoLoopSeq = errors.New("ErrBlackwhiteFinalloopLessThanSeq")
// 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
}
......@@ -22,6 +22,9 @@ func (c *Cert) ExecLocal_New(payload *ct.CertNew, tx *types.Transaction, receipt
clog.Error("Authority is not available. Please check the authority config or authority initialize error logs.")
return nil, ct.ErrInitializeAuthority
}
if receiptData.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
var set types.LocalDBSet
historityCertdata := &types.HistoryCertStore{}
......@@ -51,6 +54,9 @@ func (c *Cert) ExecLocal_Update(payload *ct.CertUpdate, tx *types.Transaction, r
clog.Error("Authority is not available. Please check the authority config or authority initialize error logs.")
return nil, ct.ErrInitializeAuthority
}
if receiptData.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
var set types.LocalDBSet
// 写入上一纪录的next-height
......@@ -81,6 +87,9 @@ func (c *Cert) ExecLocal_Normal(payload *ct.CertNormal, tx *types.Transaction, r
clog.Error("Authority is not available. Please check the authority config or authority initialize error logs.")
return nil, ct.ErrInitializeAuthority
}
if receiptData.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
var set types.LocalDBSet
return &set, nil
......
......@@ -117,7 +117,7 @@ func (action *Action) GetIndex(game *gt.Game) int64 {
//GetKVSet get kv set
func (action *Action) GetKVSet(game *gt.Game) (kvset []*types.KeyValue) {
value := types.Encode(game)
kvset = append(kvset, &types.KeyValue{Key(game.GameId), value})
kvset = append(kvset, &types.KeyValue{Key: Key(game.GameId), Value: value})
return kvset
}
......@@ -126,7 +126,7 @@ func (action *Action) updateCount(status int32, addr string) (kvset []*types.Key
if err != nil {
glog.Error("updateCount", "Query count have err:", err.Error())
}
kvset = append(kvset, &types.KeyValue{calcCountKey(status, addr), []byte(strconv.FormatInt(count+1, 10))})
kvset = append(kvset, &types.KeyValue{Key: calcCountKey(status, addr), Value: []byte(strconv.FormatInt(count+1, 10))})
return kvset
}
......@@ -231,7 +231,7 @@ func (action *Action) GameCreate(create *gt.GameCreate) (*types.Receipt, error)
kv = append(kv, receipt.KV...)
kv = append(kv, action.updateCount(game.GetStatus(), "")...)
kv = append(kv, action.updateCount(game.GetStatus(), game.GetCreateAddress())...)
receipt = &types.Receipt{types.ExecOk, kv, logs}
receipt = &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}
return receipt, nil
}
......@@ -286,7 +286,7 @@ func (action *Action) GameMatch(match *gt.GameMatch) (*types.Receipt, error) {
kvs = append(kvs, action.updateCount(game.GetStatus(), "")...)
kvs = append(kvs, action.updateCount(game.GetStatus(), game.GetCreateAddress())...)
kvs = append(kvs, action.updateCount(game.GetStatus(), game.GetMatchAddress())...)
receipts := &types.Receipt{types.ExecOk, kvs, logs}
receipts := &types.Receipt{Ty: types.ExecOk, KV: kvs, Logs: logs}
return receipts, nil
}
......@@ -338,7 +338,7 @@ func (action *Action) GameCancel(cancel *gt.GameCancel) (*types.Receipt, error)
kv = append(kv, action.updateCount(game.GetStatus(), "")...)
kv = append(kv, action.updateCount(game.GetStatus(), game.GetCreateAddress())...)
return &types.Receipt{types.ExecOk, kv, logs}, nil
return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
}
// GameClose close game
......@@ -480,7 +480,7 @@ func (action *Action) GameClose(close *gt.GameClose) (*types.Receipt, error) {
kv = append(kv, action.updateCount(game.GetStatus(), "")...)
kv = append(kv, action.updateCount(game.GetStatus(), game.GetCreateAddress())...)
kv = append(kv, action.updateCount(game.GetStatus(), game.GetMatchAddress())...)
return &types.Receipt{types.ExecOk, kv, logs}, nil
return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
}
// 检查开奖是否超时,若超过一天,则不让庄家开奖,但其他人可以开奖,
......@@ -602,7 +602,7 @@ func queryGameListByStatusAndAddr(db dbm.Lister, stateDB dbm.KV, param *gt.Query
}
gameIds = append(gameIds, record.GetGameId())
}
return &gt.ReplyGameList{GetGameList(stateDB, gameIds)}, nil
return &gt.ReplyGameList{Games: GetGameList(stateDB, gameIds)}, nil
}
// QueryGameListCount count数查询
......@@ -610,7 +610,7 @@ func QueryGameListCount(stateDB dbm.KV, param *gt.QueryGameListCount) (types.Mes
if param.Status < 1 || param.Status > 4 {
return nil, fmt.Errorf("%s", "the status only fill in 1,2,3,4!")
}
return &gt.ReplyGameListCount{QueryCountByStatusAndAddr(stateDB, param.GetStatus(), param.GetAddress())}, nil
return &gt.ReplyGameListCount{Count: QueryCountByStatusAndAddr(stateDB, param.GetStatus(), param.GetAddress())}, nil
}
// QueryCountByStatusAndAddr query game count by status and addr
......
......@@ -30,5 +30,5 @@ func (g *Game) Query_QueryGameById(in *gt.QueryGameInfo) (types.Message, error)
if err != nil {
return nil, err
}
return &gt.ReplyGame{game}, nil
return &gt.ReplyGame{Game: game}, nil
}
......@@ -45,7 +45,7 @@ type GameType struct {
// GetLogMap get log
func (gt *GameType) GetLogMap() map[int64]*types.LogInfo {
return map[int64]*types.LogInfo{
TyLogCreateGame: {reflect.TypeOf(ReceiptGame{}), "LogLotteryCreate"},
TyLogCreateGame: {reflect.TypeOf(ReceiptGame{}), "LogCreateGame"},
TyLogCancleGame: {reflect.TypeOf(ReceiptGame{}), "LogCancleGame"},
TyLogMatchGame: {reflect.TypeOf(ReceiptGame{}), "LogMatchGame"},
TyLogCloseGame: {reflect.TypeOf(ReceiptGame{}), "LogCloseGame"},
......
......@@ -12,6 +12,9 @@ import (
// ExecDelLocal_Hlock Action
func (h *Hashlock) ExecDelLocal_Hlock(hlock *pty.HashlockLock, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if receipt.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
info := pty.Hashlockquery{Time: hlock.Time, Status: hashlockLocked, Amount: hlock.Amount, CreateTime: h.GetBlockTime(), CurrentTime: 0}
kv, err := UpdateHashReciver(h.GetLocalDB(), hlock.Hash, info)
if err != nil {
......@@ -22,6 +25,9 @@ func (h *Hashlock) ExecDelLocal_Hlock(hlock *pty.HashlockLock, tx *types.Transac
// ExecDelLocal_Hsend Action
func (h *Hashlock) ExecDelLocal_Hsend(hsend *pty.HashlockSend, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if receipt.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
info := pty.Hashlockquery{Time: 0, Status: hashlockSent, Amount: 0, CreateTime: 0, CurrentTime: 0}
kv, err := UpdateHashReciver(h.GetLocalDB(), common.Sha256(hsend.Secret), info)
if err != nil {
......@@ -32,6 +38,9 @@ func (h *Hashlock) ExecDelLocal_Hsend(hsend *pty.HashlockSend, tx *types.Transac
// ExecDelLocal_Hunlock Action
func (h *Hashlock) ExecDelLocal_Hunlock(hunlock *pty.HashlockUnlock, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if receipt.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
info := pty.Hashlockquery{Time: 0, Status: hashlockUnlocked, Amount: 0, CreateTime: 0, CurrentTime: 0}
kv, err := UpdateHashReciver(h.GetLocalDB(), common.Sha256(hunlock.Secret), info)
if err != nil {
......
......@@ -12,6 +12,9 @@ import (
// ExecLocal_Hlock Action
func (h *Hashlock) ExecLocal_Hlock(hlock *pty.HashlockLock, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if receipt.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
info := pty.Hashlockquery{Time: hlock.Time, Status: hashlockLocked, Amount: hlock.Amount, CreateTime: h.GetBlockTime(), CurrentTime: 0}
clog.Error("ExecLocal", "info", info)
kv, err := UpdateHashReciver(h.GetLocalDB(), hlock.Hash, info)
......@@ -23,6 +26,9 @@ func (h *Hashlock) ExecLocal_Hlock(hlock *pty.HashlockLock, tx *types.Transactio
// ExecLocal_Hsend Action
func (h *Hashlock) ExecLocal_Hsend(hsend *pty.HashlockSend, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if receipt.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
info := pty.Hashlockquery{Time: 0, Status: hashlockSent, Amount: 0, CreateTime: 0, CurrentTime: 0}
clog.Error("ExecLocal", "info", info)
kv, err := UpdateHashReciver(h.GetLocalDB(), common.Sha256(hsend.Secret), info)
......@@ -34,6 +40,9 @@ func (h *Hashlock) ExecLocal_Hsend(hsend *pty.HashlockSend, tx *types.Transactio
// ExecLocal_Hunlock Action
func (h *Hashlock) ExecLocal_Hunlock(hunlock *pty.HashlockUnlock, tx *types.Transaction, receipt *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if receipt.GetTy() != types.ExecOk {
return &types.LocalDBSet{}, nil
}
info := pty.Hashlockquery{Time: 0, Status: hashlockUnlocked, Amount: 0, CreateTime: 0, CurrentTime: 0}
clog.Error("ExecLocal", "info", info)
kv, err := UpdateHashReciver(h.GetLocalDB(), common.Sha256(hunlock.Secret), info)
......
// 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.
package init
import (
......
......@@ -43,20 +43,20 @@ func (l *Lottery) execDelLocal(tx *types.Transaction, receiptData *types.Receipt
// ExecDelLocal_Create Action
func (l *Lottery) ExecDelLocal_Create(payload *pty.LotteryCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil
return l.execDelLocal(tx, receiptData)
}
// ExecDelLocal_Buy Action
func (l *Lottery) ExecDelLocal_Buy(payload *pty.LotteryBuy, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil
return l.execDelLocal(tx, receiptData)
}
// ExecDelLocal_Draw Action
func (l *Lottery) ExecDelLocal_Draw(payload *pty.LotteryDraw, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil
return l.execDelLocal(tx, receiptData)
}
// ExecDelLocal_Close Action
func (l *Lottery) ExecDelLocal_Close(payload *pty.LotteryClose, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil
return l.execDelLocal(tx, receiptData)
}
......@@ -16,6 +16,7 @@ import (
"github.com/spf13/cobra"
)
//ParcCmd paracross cmd register
func ParcCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "para",
......@@ -32,7 +33,7 @@ func ParcCmd() *cobra.Command {
return cmd
}
// create raw asset transfer tx
// CreateRawAssetTransferCmd create raw asset transfer tx
func CreateRawAssetTransferCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "asset_transfer",
......@@ -67,7 +68,7 @@ func createAssetTransfer(cmd *cobra.Command, args []string) {
fmt.Println(txHex)
}
// create raw asset withdraw tx
// CreateRawAssetWithdrawCmd create raw asset withdraw tx
func CreateRawAssetWithdrawCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "asset_withdraw",
......@@ -139,7 +140,7 @@ func createAssetTx(cmd *cobra.Command, isWithdraw bool) (string, error) {
return hex.EncodeToString(txHex), nil
}
// create raw transfer tx
//CreateRawTransferCmd create raw transfer tx
func CreateRawTransferCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "transfer",
......@@ -174,7 +175,7 @@ func createTransfer(cmd *cobra.Command, args []string) {
fmt.Println(txHex)
}
// create raw transfer to exec tx
//CreateRawTransferToExecCmd create raw transfer to exec tx
func CreateRawTransferToExecCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "transfer_exec",
......@@ -209,7 +210,7 @@ func createTransferToExec(cmd *cobra.Command, args []string) {
fmt.Println(txHex)
}
// create raw withdraw tx
//CreateRawWithdrawCmd create raw withdraw tx
func CreateRawWithdrawCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "withdraw",
......
......@@ -13,6 +13,7 @@ import (
// 注: 在计算帐号地址时, 平行链paracross合约地址需要带上title前缀,才能表现出和主链一致, 但是现在不带,
//NewParaAccount create new paracross account
// 其中带{}, 都表示变量, 用需要用真实的地址, 符号代替
// 构建主链资产在平行链paracross帐号
// execName: user.p.{guodun}.paracross
......@@ -28,6 +29,7 @@ func NewParaAccount(paraTitle, mainExecName, mainSymbol string, db db.KV) (*acco
return account.NewAccountDB(paraExec, paraSymbol, db)
}
//NewMainAccount create new Main account
// 以后如果支持从平行链资产转移到主链, 构建平行链资产在主链的paracross帐号
// execName: paracross
// symbol: user.p.{guodun}.coins.{guodun} user.p.{guodun}.token.{TEST}
......
......@@ -448,7 +448,7 @@ func (a *action) Miner(miner *pt.ParacrossMinerAction) (*types.Receipt, error) {
log.Log = types.Encode(receipt)
logs = append(logs, log)
return &types.Receipt{types.ExecOk, nil, logs}, nil
return &types.Receipt{Ty: types.ExecOk, KV: nil, Logs: logs}, nil
}
......
......@@ -30,24 +30,24 @@ func (a *action) assetTransfer(transfer *types.AssetsTransfer) (*types.Receipt,
clog.Debug("paracross.AssetTransfer not isPara", "execer", string(a.tx.Execer),
"txHash", common.Bytes2Hex(a.tx.Hash()))
return accDB.ExecTransfer(a.fromaddr, toAddr, execAddr, transfer.Amount)
}
paraTitle, err := getTitleFrom(a.tx.Execer)
if err != nil {
return nil, errors.Wrap(err, "assetTransferCoins call getTitleFrom failed")
}
var paraAcc *account.DB
if transfer.Cointoken == "" {
paraAcc, err = NewParaAccount(string(paraTitle), "coins", "bty", a.db)
} else {
paraTitle, err := getTitleFrom(a.tx.Execer)
if err != nil {
return nil, errors.Wrap(err, "assetTransferCoins call getTitleFrom failed")
}
var paraAcc *account.DB
if transfer.Cointoken == "" {
paraAcc, err = NewParaAccount(string(paraTitle), "coins", "bty", a.db)
} else {
paraAcc, err = NewParaAccount(string(paraTitle), "token", transfer.Cointoken, a.db)
}
if err != nil {
return nil, errors.Wrap(err, "assetTransferCoins call NewParaAccount failed")
}
clog.Debug("paracross.AssetTransfer isPara", "execer", string(a.tx.Execer),
"txHash", common.Bytes2Hex(a.tx.Hash()))
return assetDepositBalance(paraAcc, transfer.To, transfer.Amount)
paraAcc, err = NewParaAccount(string(paraTitle), "token", transfer.Cointoken, a.db)
}
if err != nil {
return nil, errors.Wrap(err, "assetTransferCoins call NewParaAccount failed")
}
clog.Debug("paracross.AssetTransfer isPara", "execer", string(a.tx.Execer),
"txHash", common.Bytes2Hex(a.tx.Hash()))
return assetDepositBalance(paraAcc, transfer.To, transfer.Amount)
}
func (a *action) assetWithdraw(withdraw *types.AssetsWithdraw, withdrawTx *types.Transaction) (*types.Receipt, error) {
......@@ -62,24 +62,24 @@ func (a *action) assetWithdraw(withdraw *types.AssetsWithdraw, withdrawTx *types
clog.Debug("Paracross.Exec", "AssettWithdraw", withdraw.Amount, "from", fromAddr,
"to", withdraw.To, "exec", execAddr, "withdrawTx execor", string(withdrawTx.Execer))
return accDB.ExecTransfer(fromAddr, withdraw.To, execAddr, withdraw.Amount)
}
paraTitle, err := getTitleFrom(a.tx.Execer)
if err != nil {
return nil, errors.Wrap(err, "assetWithdrawCoins call getTitleFrom failed")
}
var paraAcc *account.DB
if withdraw.Cointoken == "" {
paraAcc, err = NewParaAccount(string(paraTitle), "coins", "bty", a.db)
} else {
paraTitle, err := getTitleFrom(a.tx.Execer)
if err != nil {
return nil, errors.Wrap(err, "assetWithdrawCoins call getTitleFrom failed")
}
var paraAcc *account.DB
if withdraw.Cointoken == "" {
paraAcc, err = NewParaAccount(string(paraTitle), "coins", "bty", a.db)
} else {
paraAcc, err = NewParaAccount(string(paraTitle), "token", withdraw.Cointoken, a.db)
}
if err != nil {
return nil, errors.Wrap(err, "assetWithdrawCoins call NewParaAccount failed")
}
clog.Debug("paracross.assetWithdrawCoins isPara", "execer", string(a.tx.Execer),
"txHash", common.Bytes2Hex(a.tx.Hash()))
return assetWithdrawBalance(paraAcc, a.fromaddr, withdraw.Amount)
paraAcc, err = NewParaAccount(string(paraTitle), "token", withdraw.Cointoken, a.db)
}
if err != nil {
return nil, errors.Wrap(err, "assetWithdrawCoins call NewParaAccount failed")
}
clog.Debug("paracross.assetWithdrawCoins isPara", "execer", string(a.tx.Execer),
"txHash", common.Bytes2Hex(a.tx.Hash()))
return assetWithdrawBalance(paraAcc, a.fromaddr, withdraw.Amount)
}
func createAccount(db db.KV, symbol string) (*account.DB, error) {
......
......@@ -83,13 +83,13 @@ func (suite *AssetTransferTestSuite) SetupTest() {
saveTitle(suite.stateDB, calcTitleKey(Title), &titleStatus)
// setup api
hashes := &types.ReqHashes{[][]byte{MainBlockHash10}}
hashes := &types.ReqHashes{Hashes: [][]byte{MainBlockHash10}}
suite.api.On("GetBlockByHashes", hashes).Return(
&types.BlockDetails{
Items: []*types.BlockDetail{blockDetail},
}, nil)
suite.api.On("GetBlockHash", &types.ReqInt{MainBlockHeight}).Return(
&types.ReplyHash{MainBlockHash10}, nil)
suite.api.On("GetBlockHash", &types.ReqInt{Height: MainBlockHeight}).Return(
&types.ReplyHash{Hash: MainBlockHash10}, nil)
}
func (suite *AssetTransferTestSuite) TestExecTransferNobalance() {
......
......@@ -78,13 +78,13 @@ func (suite *AssetWithdrawTestSuite) SetupTest() {
saveTitle(suite.stateDB, calcTitleKey(Title), &titleStatus)
// setup api
hashes := &types.ReqHashes{[][]byte{MainBlockHash10}}
hashes := &types.ReqHashes{Hashes: [][]byte{MainBlockHash10}}
suite.api.On("GetBlockByHashes", hashes).Return(
&types.BlockDetails{
Items: []*types.BlockDetail{blockDetail},
}, nil)
suite.api.On("GetBlockHash", &types.ReqInt{MainBlockHeight}).Return(
&types.ReplyHash{MainBlockHash10}, nil)
suite.api.On("GetBlockHash", &types.ReqInt{Height: MainBlockHeight}).Return(
&types.ReplyHash{Hash: MainBlockHash10}, nil)
}
// 主链先不执行
......
......@@ -53,8 +53,9 @@ func saveTitleHeight(db dbm.KV, key []byte, heightStatus types.Message /* height
return db.Set(key, val)
}
//GetBlock get block detail by block hash
func GetBlock(api client.QueueProtocolAPI, blockHash []byte) (*types.BlockDetail, error) {
blockDetails, err := api.GetBlockByHashes(&types.ReqHashes{[][]byte{blockHash}})
blockDetails, err := api.GetBlockByHashes(&types.ReqHashes{Hashes: [][]byte{blockHash}})
if err != nil {
clog.Error("paracross.Commit getBlockHeader", "db", err,
"commit tx hash", common.Bytes2Hex(blockHash))
......@@ -88,8 +89,9 @@ func isNotFound(err error) bool {
return false
}
//GetTx get tx by tx hash
func GetTx(api client.QueueProtocolAPI, txHash []byte) (*types.TransactionDetail, error) {
txs, err := api.GetTransactionByHash(&types.ReqHashes{[][]byte{txHash}})
txs, err := api.GetTransactionByHash(&types.ReqHashes{Hashes: [][]byte{txHash}})
if err != nil {
clog.Error("paracross.Commit GetTx", "db", err,
"commit tx hash", common.Bytes2Hex(txHash))
......
......@@ -11,6 +11,7 @@ import (
"github.com/pkg/errors"
)
//Exec_Commit consensus commit tx exec process
func (e *Paracross) Exec_Commit(payload *pt.ParacrossCommitAction, tx *types.Transaction, index int) (*types.Receipt, error) {
a := newAction(e, tx)
receipt, err := a.Commit(payload)
......@@ -21,6 +22,7 @@ func (e *Paracross) Exec_Commit(payload *pt.ParacrossCommitAction, tx *types.Tra
return receipt, nil
}
//Exec_AssetTransfer asset transfer exec process
func (e *Paracross) Exec_AssetTransfer(payload *types.AssetsTransfer, tx *types.Transaction, index int) (*types.Receipt, error) {
clog.Debug("Paracross.Exec", "transfer", "")
_, err := e.checkTxGroup(tx, index)
......@@ -37,6 +39,7 @@ func (e *Paracross) Exec_AssetTransfer(payload *types.AssetsTransfer, tx *types.
return receipt, nil
}
//Exec_AssetWithdraw asset withdraw exec process
func (e *Paracross) Exec_AssetWithdraw(payload *types.AssetsWithdraw, tx *types.Transaction, index int) (*types.Receipt, error) {
clog.Debug("Paracross.Exec", "withdraw", "")
_, err := e.checkTxGroup(tx, index)
......@@ -53,6 +56,7 @@ func (e *Paracross) Exec_AssetWithdraw(payload *types.AssetsWithdraw, tx *types.
return receipt, nil
}
//Exec_Miner miner tx exec process
func (e *Paracross) Exec_Miner(payload *pt.ParacrossMinerAction, tx *types.Transaction, index int) (*types.Receipt, error) {
if index != 0 {
return nil, pt.ErrParaMinerBaseIndex
......@@ -64,16 +68,19 @@ func (e *Paracross) Exec_Miner(payload *pt.ParacrossMinerAction, tx *types.Trans
return a.Miner(payload)
}
//Exec_Transfer exec asset transfer process
func (e *Paracross) Exec_Transfer(payload *types.AssetsTransfer, tx *types.Transaction, index int) (*types.Receipt, error) {
a := newAction(e, tx)
return a.Transfer(payload, tx, index)
}
//Exec_Withdraw exec asset withdraw
func (e *Paracross) Exec_Withdraw(payload *types.AssetsWithdraw, tx *types.Transaction, index int) (*types.Receipt, error) {
a := newAction(e, tx)
return a.Withdraw(payload, tx, index)
}
//Exec_TransferToExec exec transfer asset
func (e *Paracross) Exec_TransferToExec(payload *types.AssetsTransferToExec, tx *types.Transaction, index int) (*types.Receipt, error) {
a := newAction(e, tx)
return a.TransferToExec(payload, tx, index)
......
......@@ -9,6 +9,7 @@ import (
pt "github.com/33cn/plugin/plugin/dapp/paracross/types"
)
//ExecDelLocal_Commit consensus commit tx del local db process
func (e *Paracross) ExecDelLocal_Commit(payload *pt.ParacrossCommitAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
var set types.LocalDBSet
for _, log := range receiptData.Logs {
......@@ -18,17 +19,17 @@ func (e *Paracross) ExecDelLocal_Commit(payload *pt.ParacrossCommitAction, tx *t
var r pt.ParacrossTx
r.TxHash = string(tx.Hash())
set.KV = append(set.KV, &types.KeyValue{calcLocalTxKey(g.Status.Title, g.Status.Height, tx.From()), nil})
set.KV = append(set.KV, &types.KeyValue{Key: calcLocalTxKey(g.Status.Title, g.Status.Height, tx.From()), Value: nil})
} else if log.Ty == pt.TyLogParacrossCommitDone {
var g pt.ReceiptParacrossDone
types.Decode(log.Log, &g)
g.Height = g.Height - 1
key := calcLocalTitleKey(g.Title)
set.KV = append(set.KV, &types.KeyValue{key, types.Encode(&g)})
set.KV = append(set.KV, &types.KeyValue{Key: key, Value: types.Encode(&g)})
key = calcLocalHeightKey(g.Title, g.Height)
set.KV = append(set.KV, &types.KeyValue{key, nil})
set.KV = append(set.KV, &types.KeyValue{Key: key, Value: nil})
r, err := e.saveLocalParaTxs(tx, true)
if err != nil {
......@@ -41,12 +42,13 @@ func (e *Paracross) ExecDelLocal_Commit(payload *pt.ParacrossCommitAction, tx *t
var r pt.ParacrossTx
r.TxHash = string(tx.Hash())
set.KV = append(set.KV, &types.KeyValue{calcLocalTxKey(g.Status.Title, g.Status.Height, tx.From()), nil})
set.KV = append(set.KV, &types.KeyValue{Key: calcLocalTxKey(g.Status.Title, g.Status.Height, tx.From()), Value: nil})
}
}
return &set, nil
}
//ExecDelLocal_AssetTransfer asset transfer del local db process
func (e *Paracross) ExecDelLocal_AssetTransfer(payload *types.AssetsTransfer, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
var set types.LocalDBSet
......@@ -61,29 +63,34 @@ func (e *Paracross) ExecDelLocal_AssetTransfer(payload *types.AssetsTransfer, tx
return &set, nil
}
//ExecDelLocal_AssetWithdraw asset withdraw local db process
func (e *Paracross) ExecDelLocal_AssetWithdraw(payload *types.AssetsWithdraw, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil
}
//ExecDelLocal_Miner miner tx del local db process
func (e *Paracross) ExecDelLocal_Miner(payload *pt.ParacrossMinerAction, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
if index != 0 {
return nil, pt.ErrParaMinerBaseIndex
}
var set types.LocalDBSet
set.KV = append(set.KV, &types.KeyValue{pt.CalcMinerHeightKey(payload.Status.Title, payload.Status.Height), nil})
set.KV = append(set.KV, &types.KeyValue{Key: pt.CalcMinerHeightKey(payload.Status.Title, payload.Status.Height), Value: nil})
return &set, nil
}
//ExecDelLocal_Transfer asset transfer del local process
func (e *Paracross) ExecDelLocal_Transfer(payload *types.AssetsTransfer, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil
}
//ExecDelLocal_Withdraw asset withdraw del local db process
func (e *Paracross) ExecDelLocal_Withdraw(payload *types.AssetsWithdraw, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil
}
//ExecDelLocal_TransferToExec asset transfer to exec del local db process
func (e *Paracross) ExecDelLocal_TransferToExec(payload *types.AssetsTransferToExec, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return nil, nil
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment