diff --git a/circle.yml b/circle.yml index 994cf8048ccde6d74fbcb97bd4806fdd03534e7e..1d6b6830fe959fe27fa8728d28284477364fcfc9 100644 --- a/circle.yml +++ b/circle.yml @@ -24,21 +24,21 @@ dependencies: # - sudo rm -rf /usr/local/go # - sudo cp -r ~/cache/go /usr/local/go # Override host docker - - sudo cp ~/cache/docker /usr/bin/dockeu + - sudo cp ~/cache/docker /usr/bin/docker - sudo chmod +x /usr/bin/docker # Override host go - sudo service docker start - - docker login -e $DOCKER_EMAIL -u $DOCKER_USER -p $DOCKER_PASS quay.io - "sudo apt-get update && sudo apt-get install -y libgmp3-dev" - # Install erisdb cmd for tests - - cd $GOPATH_REPO && go install ./cmd/erisdb cache_directories: - ~/cache - + test: pre: - go get github.com/stretchr/testify - go get github.com/Masterminds/glide + - cd $GOPATH_REPO && glide install + # Install erisdb cmd for tests + - cd $GOPATH_REPO && go install ./cmd/erisdb override: # We only wish to test our packages not vendored ones - cd $GOPATH_REPO && glide novendor | xargs go test -v @@ -48,6 +48,7 @@ deployment: branch: master commands: - DOCKER/build.sh + - docker login -e $DOCKER_EMAIL -u $DOCKER_USER -p $DOCKER_PASS quay.io - docker push quay.io/eris/erisdb develop: branch: develop diff --git a/cmd/erisdb/main.go b/cmd/erisdb/main.go index 0237ca425d8d64f87729ec35b9a6fa78bac4b1ab..a3ef77a82c44cc4c1b463f25a92875cfac9067e8 100644 --- a/cmd/erisdb/main.go +++ b/cmd/erisdb/main.go @@ -4,9 +4,6 @@ import ( "fmt" edb "github.com/eris-ltd/eris-db/erisdb" "os" - - _ "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/Sirupsen/logrus" // hack cuz godeps :( - _ "github.com/eris-ltd/eris-db/Godeps/_workspace/src/github.com/tendermint/go-clist" // godeps ... ) // TODO the input stuff. diff --git a/config/config.go b/config/config.go index 84fff16a9e058dc4db73af3181e845fe33b5ab7d..7c14d3c8950289fe99acf6cfdc8f649efc73104e 100644 --- a/config/config.go +++ b/config/config.go @@ -141,3 +141,12 @@ func WriteErisDBConfig(filePath string, cfg *ErisDBConfig) error { } return files.WriteAndBackup(filePath, bts) } + +// Write a server configuration file. +func WriteServerConfig(filePath string, cfg *ServerConfig) error { + bts, err := toml.Marshal(*cfg) + if err != nil { + return err + } + return files.WriteAndBackup(filePath, bts) +} diff --git a/erisdb/erisdbss/http.go b/erisdb/erisdbss/http.go index 7ea8b390dccf442e62b1353295120955da387e0c..d01865ea8965e10f182e5c42756cc8f433a97c76 100644 --- a/erisdb/erisdbss/http.go +++ b/erisdb/erisdbss/http.go @@ -3,14 +3,15 @@ package erisdbss import ( "bytes" "encoding/json" - "github.com/eris-ltd/eris-db/server" + "net/http" + "os" + + "github.com/eris-ltd/eris-db/config" stypes "github.com/eris-ltd/eris-db/state/types" "github.com/gin-gonic/gin" . "github.com/tendermint/go-common" "github.com/tendermint/go-wire" tmtypes "github.com/tendermint/tendermint/types" - "net/http" - "os" ) const TendermintConfigDefault = `# This is a TOML config file. @@ -68,7 +69,7 @@ func NewServerServer(baseDir string) *ServerServer { } // Start the server. -func (this *ServerServer) Start(config *server.ServerConfig, router *gin.Engine) { +func (this *ServerServer) Start(config *config.ServerConfig, router *gin.Engine) { router.POST("/server", this.handleFunc) this.running = true } diff --git a/erisdb/erisdbss/server_manager.go b/erisdb/erisdbss/server_manager.go index 6cb8c44fe79001dcfdae730819c6e6b7c6733918..34faeb71905b7ab8cc734803e5035e1e0d0153d5 100644 --- a/erisdb/erisdbss/server_manager.go +++ b/erisdb/erisdbss/server_manager.go @@ -3,16 +3,18 @@ package erisdbss import ( "bufio" "fmt" - "github.com/eris-ltd/eris-db/files" - "github.com/eris-ltd/eris-db/server" - . "github.com/tendermint/go-common" - "github.com/tendermint/go-wire" "os" "os/exec" "path" "strings" "sync" "time" + + "github.com/eris-ltd/eris-db/config" + "github.com/eris-ltd/eris-db/files" + "github.com/eris-ltd/eris-db/server" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-wire" ) const ( @@ -161,17 +163,17 @@ func reap(sm *ServerManager) { func (this *ServerManager) add(data *RequestData) (*ResponseData, error) { this.mtx.Lock() defer this.mtx.Unlock() - config := server.DefaultServerConfig() + cfg := config.DefaultServerConfig() // Port is PORT_BASE + a value between 1 and the max number of servers. id, errId := this.idPool.GetId() if errId != nil { return nil, errId } port := uint16(PORT_BASE + id) - config.Bind.Port = port + cfg.Bind.Port = port folderName := fmt.Sprintf("testnode%d", port) - workDir, errCWD := this.createWorkDir(data, config, folderName) + workDir, errCWD := this.createWorkDir(data, &cfg, folderName) if errCWD != nil { return nil, errCWD } @@ -220,7 +222,7 @@ func (this *ServerManager) killAll() { // Old folders are cleared out. before creating them, and the server will // clean out all of this servers workdir (defaults to ~/.edbservers) when // starting and when stopping. -func (this *ServerManager) createWorkDir(data *RequestData, config *server.ServerConfig, folderName string) (string, error) { +func (this *ServerManager) createWorkDir(data *RequestData, cfg *config.ServerConfig, folderName string) (string, error) { workDir := path.Join(this.baseDir, folderName) os.RemoveAll(workDir) @@ -256,7 +258,7 @@ func (this *ServerManager) createWorkDir(data *RequestData, config *server.Serve log.Info("File written.", "name", genesisName) // Write server config. - errWC := server.WriteServerConfig(scName, config) + errWC := config.WriteServerConfig(scName, cfg) if errWC != nil { return "", errWC } diff --git a/erisdb/event_cache_test.go b/erisdb/event_cache_test.go index cfcef01d31f96628b4b2a0d05f14c4906f1e1f7a..d0f0ac253b44d7ee150818eb200ff5ffa2ce0ecc 100644 --- a/erisdb/event_cache_test.go +++ b/erisdb/event_cache_test.go @@ -7,9 +7,9 @@ import ( "testing" "time" + "github.com/eris-ltd/eris-db/txs" "github.com/stretchr/testify/assert" "github.com/tendermint/go-events" - "github.com/eris-ltd/eris-db/txs" ) var mockInterval = 10 * time.Millisecond @@ -48,7 +48,7 @@ func (this *mockEventEmitter) Subscribe(subId, eventId string, callback func(eve go func() { for { if !me.shutdown { - me.f(types.EventDataNewBlock{}) + me.f(txs.EventDataNewBlock{}) } else { return } diff --git a/erisdb/event_filters.go b/erisdb/event_filters.go index 498b79ce55521146d199a316b00525f699994613..498fab486c75cf542fe7d8ecd4c9780d20984599 100644 --- a/erisdb/event_filters.go +++ b/erisdb/event_filters.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/hex" "fmt" + ep "github.com/eris-ltd/eris-db/erisdb/pipe" "github.com/eris-ltd/eris-db/txs" ) @@ -41,7 +42,7 @@ func (this *AccountCallTxHashFilter) Configure(fd *ep.FilterData) error { } func (this *AccountCallTxHashFilter) Match(v interface{}) bool { - emct, ok := v.(*types.EventDataCall) + emct, ok := v.(*txs.EventDataCall) if !ok { return false } diff --git a/erisdb/methods.go b/erisdb/methods.go index db4306873248c7b694d2ddee11f0e99e1bb3f0ec..df26e002bf1b22fca0d4d04b8b0b2687eaec4898 100644 --- a/erisdb/methods.go +++ b/erisdb/methods.go @@ -44,8 +44,6 @@ const ( SIGN_TX = SERVICE_NAME + ".signTx" TRANSACT = SERVICE_NAME + ".transact" TRANSACT_AND_HOLD = SERVICE_NAME + ".transactAndHold" - SEND = SERVICE_NAME + ".send" - SEND_AND_HOLD = SERVICE_NAME + ".sendAndHold" TRANSACT_NAMEREG = SERVICE_NAME + ".transactNameReg" EVENT_SUBSCRIBE = SERVICE_NAME + ".eventSubscribe" // Events EVENT_UNSUBSCRIBE = SERVICE_NAME + ".eventUnsubscribe" @@ -100,8 +98,6 @@ func (this *ErisDbMethods) getMethods() map[string]RequestHandlerFunc { dhMap[SIGN_TX] = this.SignTx dhMap[TRANSACT] = this.Transact dhMap[TRANSACT_AND_HOLD] = this.TransactAndHold - dhMap[SEND] = this.Send - dhMap[SEND_AND_HOLD] = this.SendAndHold dhMap[TRANSACT_NAMEREG] = this.TransactNameReg // Namereg dhMap[GET_NAMEREG_ENTRY] = this.NameRegEntry @@ -383,14 +379,12 @@ func (this *ErisDbMethods) CallCode(request *rpc.RPCRequest, requester interface } func (this *ErisDbMethods) BroadcastTx(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - var err error - // Special because Tx is an interface - param := new(types.Tx) - wire.ReadJSONPtr(param, request.Params, &err) + param := &txs.CallTx{} + err := this.codec.DecodeBytes(param, request.Params) if err != nil { return nil, rpc.INVALID_PARAMS, err } - receipt, errC := this.pipe.Transactor().BroadcastTx(*param) + receipt, errC := this.pipe.Transactor().BroadcastTx(param) if errC != nil { return nil, rpc.INTERNAL_ERROR, errC } @@ -423,32 +417,6 @@ func (this *ErisDbMethods) TransactAndHold(request *rpc.RPCRequest, requester in return ce, 0, nil } -func (this *ErisDbMethods) Send(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &SendParam{} - err := this.codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - receipt, errC := this.pipe.Transactor().Send(param.PrivKey, param.ToAddress, param.Amount) - if errC != nil { - return nil, rpc.INTERNAL_ERROR, errC - } - return receipt, 0, nil -} - -func (this *ErisDbMethods) SendAndHold(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { - param := &SendParam{} - err := this.codec.DecodeBytes(param, request.Params) - if err != nil { - return nil, rpc.INVALID_PARAMS, err - } - rec, errC := this.pipe.Transactor().SendAndHold(param.PrivKey, param.ToAddress, param.Amount) - if errC != nil { - return nil, rpc.INTERNAL_ERROR, errC - } - return rec, 0, nil -} - func (this *ErisDbMethods) TransactNameReg(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { param := &TransactNameRegParam{} err := this.codec.DecodeBytes(param, request.Params) diff --git a/erisdb/params.go b/erisdb/params.go index 04ec71ed2836e951156308a53b08f21a4db71027..1452ac9fc168463b3d217161dc08f0d9bf872346 100644 --- a/erisdb/params.go +++ b/erisdb/params.go @@ -76,7 +76,7 @@ type ( // Used when signing a tx. Uses placeholders just like TxParam SignTxParam struct { - Tx *types.CallTx `json:"tx"` + Tx *txs.CallTx `json:"tx"` PrivAccounts []*account.PrivAccount `json:"priv_accounts"` } diff --git a/erisdb/pipe/namereg.go b/erisdb/pipe/namereg.go index ac15350d7eeeb184ee8d959de46b7142ad16f552..87cf1d27e22dff5945afd3604bbadadf0fe59457 100644 --- a/erisdb/pipe/namereg.go +++ b/erisdb/pipe/namereg.go @@ -48,7 +48,7 @@ func newNamereg(erisdbApp *tmsp.ErisDBApp) *namereg { return &namereg{erisdbApp, ff} } -func (this *namereg) Entry(key string) (*types.NameRegEntry, error) { +func (this *namereg) Entry(key string) (*txs.NameRegEntry, error) { st := this.erisdbApp.GetState() // performs a copy entry := st.GetNameRegEntry(key) if entry == nil { @@ -59,7 +59,7 @@ func (this *namereg) Entry(key string) (*types.NameRegEntry, error) { func (this *namereg) Entries(filters []*FilterData) (*ResultListNames, error) { var blockHeight int - var names []*types.NameRegEntry + var names []*txs.NameRegEntry state := this.erisdbApp.GetState() blockHeight = state.LastBlockHeight filter, err := this.filterFactory.NewFilter(filters) @@ -77,8 +77,8 @@ func (this *namereg) Entries(filters []*FilterData) (*ResultListNames, error) { } type ResultListNames struct { - BlockHeight int `json:"block_height"` - Names []*types.NameRegEntry `json:"names"` + BlockHeight int `json:"block_height"` + Names []*txs.NameRegEntry `json:"names"` } // Filter for namereg name. This should not be used to get individual entries by name. @@ -110,7 +110,7 @@ func (this *NameRegNameFilter) Configure(fd *FilterData) error { } func (this *NameRegNameFilter) Match(v interface{}) bool { - nre, ok := v.(*types.NameRegEntry) + nre, ok := v.(*txs.NameRegEntry) if !ok { return false } @@ -149,7 +149,7 @@ func (this *NameRegOwnerFilter) Configure(fd *FilterData) error { } func (this *NameRegOwnerFilter) Match(v interface{}) bool { - nre, ok := v.(*types.NameRegEntry) + nre, ok := v.(*txs.NameRegEntry) if !ok { return false } @@ -185,7 +185,7 @@ func (this *NameRegDataFilter) Configure(fd *FilterData) error { } func (this *NameRegDataFilter) Match(v interface{}) bool { - nre, ok := v.(*types.NameRegEntry) + nre, ok := v.(*txs.NameRegEntry) if !ok { return false } @@ -216,7 +216,7 @@ func (this *NameRegExpiresFilter) Configure(fd *FilterData) error { } func (this *NameRegExpiresFilter) Match(v interface{}) bool { - nre, ok := v.(*types.NameRegEntry) + nre, ok := v.(*txs.NameRegEntry) if !ok { return false } diff --git a/erisdb/pipe/transactor.go b/erisdb/pipe/transactor.go index fe01af8b0d0a5e6c9c1cc1e4c9bb9b8789885586..6f9bc29fe825c0b336d0f308f5ab0ae95183eb16 100644 --- a/erisdb/pipe/transactor.go +++ b/erisdb/pipe/transactor.go @@ -97,7 +97,7 @@ func (this *transactor) CallCode(fromAddress, code, data []byte) (*Call, error) } // Broadcast a transaction. -func (this *transactor) BroadcastTx(tx types.Tx) (*Receipt, error) { +func (this *transactor) BroadcastTx(tx txs.Tx) (*Receipt, error) { err := this.erisdbApp.BroadcastTx(tx) if err != nil { @@ -105,11 +105,11 @@ func (this *transactor) BroadcastTx(tx types.Tx) (*Receipt, error) { } chainId := config.GetString("erisdb.chain_id") - txHash := types.TxID(chainId, tx) + txHash := txs.TxID(chainId, tx) var createsContract uint8 var contractAddr []byte // check if creates new contract - if callTx, ok := tx.(*types.CallTx); ok { + if callTx, ok := tx.(*txs.CallTx); ok { if len(callTx.Address) == 0 { createsContract = 1 contractAddr = state.NewContractAddress(callTx.Input.Address, callTx.Input.Sequence) @@ -148,13 +148,14 @@ func (this *transactor) Transact(privKey, address, data []byte, gasLimit, fee in } else { sequence = acc.Sequence + 1 } - txInput := &types.TxInput{ + // fmt.Printf("Sequence %d\n", sequence) + txInput := &txs.TxInput{ Address: pa.Address, Amount: 1, Sequence: sequence, PubKey: pa.PubKey, } - tx := &types.CallTx{ + tx := &txs.CallTx{ Input: txInput, Address: addr, GasLimit: gasLimit, @@ -170,7 +171,7 @@ func (this *transactor) Transact(privKey, address, data []byte, gasLimit, fee in return this.BroadcastTx(txS) } -func (this *transactor) TransactAndHold(privKey, address, data []byte, gasLimit, fee int64) (*types.EventDataCall, error) { +func (this *transactor) TransactAndHold(privKey, address, data []byte, gasLimit, fee int64) (*txs.EventDataCall, error) { rec, tErr := this.Transact(privKey, address, data, gasLimit, fee) if tErr != nil { return nil, tErr @@ -181,10 +182,10 @@ func (this *transactor) TransactAndHold(privKey, address, data []byte, gasLimit, } else { addr = address } - wc := make(chan *types.EventDataCall) + wc := make(chan *txs.EventDataCall) subId := fmt.Sprintf("%X", rec.TxHash) - this.eventEmitter.Subscribe(subId, types.EventStringAccCall(addr), func(evt tEvents.EventData) { - event := evt.(types.EventDataCall) + this.eventEmitter.Subscribe(subId, txs.EventStringAccCall(addr), func(evt tEvents.EventData) { + event := evt.(txs.EventDataCall) if bytes.Equal(event.TxID, rec.TxHash) { wc <- &event } @@ -193,7 +194,7 @@ func (this *transactor) TransactAndHold(privKey, address, data []byte, gasLimit, timer := time.NewTimer(300 * time.Second) toChan := timer.C - var ret *types.EventDataCall + var ret *txs.EventDataCall var rErr error select { @@ -211,92 +212,6 @@ func (this *transactor) TransactAndHold(privKey, address, data []byte, gasLimit, return ret, rErr } -func (this *transactor) Send(privKey, toAddress []byte, amount int64) (*Receipt, error) { - var toAddr []byte - if len(toAddress) == 0 { - toAddr = nil - } else if len(toAddress) != 20 { - return nil, fmt.Errorf("To-address is not of the right length: %d\n", len(toAddress)) - } else { - toAddr = toAddress - } - - if len(privKey) != 64 { - return nil, fmt.Errorf("Private key is not of the right length: %d\n", len(privKey)) - } - - pk := &[64]byte{} - copy(pk[:], privKey) - this.txMtx.Lock() - defer this.txMtx.Unlock() - pa := account.GenPrivAccountFromPrivKeyBytes(privKey) - cache := this.mempoolReactor.Mempool.GetCache() - acc := cache.GetAccount(pa.Address) - var sequence int - if acc == nil { - sequence = 1 - } else { - sequence = acc.Sequence + 1 - } - - tx := types.NewSendTx() - - txInput := &types.TxInput{ - Address: pa.Address, - Amount: amount, - Sequence: sequence, - PubKey: pa.PubKey, - } - - tx.Inputs = append(tx.Inputs, txInput) - - txOutput := &types.TxOutput{toAddr, amount} - - tx.Outputs = append(tx.Outputs, txOutput) - - // Got ourselves a tx. - txS, errS := this.SignTx(tx, []*account.PrivAccount{pa}) - if errS != nil { - return nil, errS - } - return this.BroadcastTx(txS) -} - -func (this *transactor) SendAndHold(privKey, toAddress []byte, amount int64) (*Receipt, error) { - rec, tErr := this.Send(privKey, toAddress, amount) - if tErr != nil { - return nil, tErr - } - - wc := make(chan *types.SendTx) - subId := fmt.Sprintf("%X", rec.TxHash) - - this.eventEmitter.Subscribe(subId, types.EventStringAccOutput(toAddress), func(evt types.EventData) { - event := evt.(types.EventDataTx) - tx := event.Tx.(*types.SendTx) - wc <- tx - }) - - timer := time.NewTimer(300 * time.Second) - toChan := timer.C - - var rErr error - - pa := account.GenPrivAccountFromPrivKeyBytes(privKey) - - select { - case <-toChan: - rErr = fmt.Errorf("Transaction timed out. Hash: " + subId) - case e := <-wc: - if bytes.Equal(e.Inputs[0].Address, pa.Address) && e.Inputs[0].Amount == amount { - timer.Stop() - this.eventEmitter.Unsubscribe(subId) - return rec, rErr - } - } - return nil, rErr -} - func (this *transactor) TransactNameReg(privKey []byte, name, data string, amount, fee int64) (*Receipt, error) { if len(privKey) != 64 { @@ -313,7 +228,7 @@ func (this *transactor) TransactNameReg(privKey []byte, name, data string, amoun } else { sequence = acc.Sequence + 1 } - tx := types.NewNameTxWithNonce(pa.PubKey, name, data, amount, fee, sequence) + tx := txs.NewNameTxWithNonce(pa.PubKey, name, data, amount, fee, sequence) // Got ourselves a tx. txS, errS := this.SignTx(tx, []*account.PrivAccount{pa}) if errS != nil { @@ -323,7 +238,7 @@ func (this *transactor) TransactNameReg(privKey []byte, name, data string, amoun } // Sign a transaction -func (this *transactor) SignTx(tx types.Tx, privAccounts []*account.PrivAccount) (types.Tx, error) { +func (this *transactor) SignTx(tx txs.Tx, privAccounts []*account.PrivAccount) (txs.Tx, error) { // more checks? for i, privAccount := range privAccounts { @@ -333,24 +248,24 @@ func (this *transactor) SignTx(tx types.Tx, privAccounts []*account.PrivAccount) } chainId := config.GetString("erisdb.chain_id") switch tx.(type) { - case *types.NameTx: - nameTx := tx.(*types.NameTx) + case *txs.NameTx: + nameTx := tx.(*txs.NameTx) nameTx.Input.PubKey = privAccounts[0].PubKey nameTx.Input.Signature = privAccounts[0].Sign(config.GetString("erisdb.chain_id"), nameTx) - case *types.SendTx: - sendTx := tx.(*types.SendTx) + case *txs.SendTx: + sendTx := tx.(*txs.SendTx) for i, input := range sendTx.Inputs { input.PubKey = privAccounts[i].PubKey input.Signature = privAccounts[i].Sign(chainId, sendTx) } break - case *types.CallTx: - callTx := tx.(*types.CallTx) + case *txs.CallTx: + callTx := tx.(*txs.CallTx) callTx.Input.PubKey = privAccounts[0].PubKey callTx.Input.Signature = privAccounts[0].Sign(chainId, callTx) break - case *types.BondTx: - bondTx := tx.(*types.BondTx) + case *txs.BondTx: + bondTx := tx.(*txs.BondTx) // the first privaccount corresponds to the BondTx pub key. // the rest to the inputs bondTx.Signature = privAccounts[0].Sign(chainId, bondTx).(crypto.SignatureEd25519) @@ -359,12 +274,12 @@ func (this *transactor) SignTx(tx types.Tx, privAccounts []*account.PrivAccount) input.Signature = privAccounts[i+1].Sign(chainId, bondTx) } break - case *types.UnbondTx: - unbondTx := tx.(*types.UnbondTx) + case *txs.UnbondTx: + unbondTx := tx.(*txs.UnbondTx) unbondTx.Signature = privAccounts[0].Sign(chainId, unbondTx).(crypto.SignatureEd25519) break - case *types.RebondTx: - rebondTx := tx.(*types.RebondTx) + case *txs.RebondTx: + rebondTx := tx.(*txs.RebondTx) rebondTx.Signature = privAccounts[0].Sign(chainId, rebondTx).(crypto.SignatureEd25519) break default: diff --git a/erisdb/restServer.go b/erisdb/restServer.go index 26f149cecff28860f3831ce94c7ff635a209b4b8..e6a7ca16dc483973673d039a782e80e5eb376597 100644 --- a/erisdb/restServer.go +++ b/erisdb/restServer.go @@ -374,15 +374,12 @@ func (this *RestServer) handlePeer(c *gin.Context) { // ********************************* Transactions ********************************* func (this *RestServer) handleBroadcastTx(c *gin.Context) { - // Special because Tx is an interface - param := new(types.Tx) - b, err := ioutil.ReadAll(c.Request.Body) - defer c.Request.Body.Close() - wire.ReadJSONPtr(param, b, &err) - if err != nil { - c.AbortWithError(500, err) + param := &txs.CallTx{} + errD := this.codec.Decode(param, c.Request.Body) + if errD != nil { + c.AbortWithError(500, errD) } - receipt, err := this.pipe.Transactor().BroadcastTx(*param) + receipt, err := this.pipe.Transactor().BroadcastTx(param) if err != nil { c.AbortWithError(500, err) } diff --git a/erisdb/serve.go b/erisdb/serve.go index 8b84030dd23a3a1d89849b50ac32a5c5749e751c..254f2515e0a157c86425ddd646e2298dc0467f42 100644 --- a/erisdb/serve.go +++ b/erisdb/serve.go @@ -3,7 +3,6 @@ package erisdb import ( - "encoding/hex" "bytes" "fmt" "io/ioutil" @@ -250,25 +249,3 @@ func LoadGenDoc() *stypes.GenesisDoc { } return stypes.GenesisDocFromJSON(jsonBlob) } - -type ErisSigner struct { - Host string - Address string - SessionKey string -} - -func NewErisSigner(host, address string) *ErisSigner { - if !strings.HasPrefix(host, "http://") { - host = fmt.Sprintf("http://%s", host) - } - return &ErisSigner{Host: host, Address: address} -} - -func (es *ErisSigner) Sign(msg []byte) acm.SignatureEd25519 { - msgHex := hex.EncodeToString(msg) - sig, err := core.Sign(msgHex, es.Address, es.Host) - if err != nil { - panic(err) - } - return acm.SignatureEd25519(sig) -} diff --git a/evm/test/log_event_test.go b/evm/test/log_event_test.go index 3bbe6156955740f25b3f846c1850fa5c3c5a3ce4..0d7b308c9be44a3c83e128ed9c02bfad6e2ac174 100644 --- a/evm/test/log_event_test.go +++ b/evm/test/log_event_test.go @@ -40,12 +40,12 @@ func TestLog4(t *testing.T) { if err != nil { t.Errorf("Failed to start eventSwitch: %v", err) } - eventID := types.EventStringLogEvent(account2.Address.Postfix(20)) + eventID := txs.EventStringLogEvent(account2.Address.Postfix(20)) doneChan := make(chan struct{}, 1) eventSwitch.AddListenerForEvent("test", eventID, func(event events.EventData) { - logEvent := event.(types.EventDataLog) + logEvent := event.(txs.EventDataLog) // No need to test address as this event would not happen if it wasn't correct if !reflect.DeepEqual(logEvent.Topics, expectedTopics) { t.Errorf("Event topics are wrong. Got: %v. Expected: %v", logEvent.Topics, expectedTopics) diff --git a/evm/test/vm_test.go b/evm/test/vm_test.go index 81cd1256356faffda261efdc37ba0fbd5e33a67c..83bbed3a7d11cbff525b3fa0d72ac10a56e33bd8 100644 --- a/evm/test/vm_test.go +++ b/evm/test/vm_test.go @@ -188,7 +188,7 @@ func runVMWaitEvents(t *testing.T, ourVm *VM, caller, callee *Account, subscribe evsw.Start() ch := make(chan interface{}) fmt.Printf("subscribe to %x\n", subscribeAddr) - evsw.AddListenerForEvent("test", types.EventStringAccCall(subscribeAddr), func(msg events.EventData) { + evsw.AddListenerForEvent("test", txs.EventStringAccCall(subscribeAddr), func(msg events.EventData) { ch <- msg }) evc := events.NewEventCache(evsw) @@ -205,9 +205,9 @@ func runVMWaitEvents(t *testing.T, ourVm *VM, caller, callee *Account, subscribe }() msg := <-ch switch ev := msg.(type) { - case types.EventDataTx: + case txs.EventDataTx: return ev.Exception - case types.EventDataCall: + case txs.EventDataCall: return ev.Exception case string: return ev diff --git a/evm/vm.go b/evm/vm.go index a22e7ec67449c4d4d2e6b9344a22386c0823cd76..e96de42d13c83e58e22c75c82e02756bff536a92 100644 --- a/evm/vm.go +++ b/evm/vm.go @@ -8,7 +8,7 @@ import ( "github.com/eris-ltd/eris-db/evm/sha3" ptypes "github.com/eris-ltd/eris-db/permission/types" - types "github.com/eris-ltd/eris-db/txs" + "github.com/eris-ltd/eris-db/txs" . "github.com/tendermint/go-common" "github.com/tendermint/go-events" ) @@ -103,8 +103,8 @@ func HasPermission(appState AppState, acc *Account, perm ptypes.PermFlag) bool { func (vm *VM) fireCallEvent(exception *string, output *[]byte, caller, callee *Account, input []byte, value int64, gas *int64) { // fire the post call event (including exception if applicable) if vm.evc != nil { - vm.evc.FireEvent(types.EventStringAccCall(callee.Address.Postfix(20)), types.EventDataCall{ - &types.CallData{caller.Address.Postfix(20), callee.Address.Postfix(20), input, value, *gas}, + vm.evc.FireEvent(txs.EventStringAccCall(callee.Address.Postfix(20)), txs.EventDataCall{ + &txs.CallData{caller.Address.Postfix(20), callee.Address.Postfix(20), input, value, *gas}, vm.origin.Postfix(20), vm.txid, *output, @@ -704,9 +704,9 @@ func (vm *VM) call(caller, callee *Account, code, input []byte, value int64, gas } data = copyslice(data) if vm.evc != nil { - eventID := types.EventStringLogEvent(callee.Address.Postfix(20)) + eventID := txs.EventStringLogEvent(callee.Address.Postfix(20)) fmt.Printf("eventID: %s\n", eventID) - log := types.EventDataLog{ + log := txs.EventDataLog{ callee.Address, topics, data, diff --git a/glide.lock b/glide.lock index ac08c3454b66eee4e43d68fed8e99d6b1c4b3dd5..6de9d77ab28dff2373e4bbb9b9f3f2fe672c2dc0 100644 --- a/glide.lock +++ b/glide.lock @@ -1,12 +1,14 @@ -hash: ebfa16e47dd0e0b486fc4435f53391b6bd9df5cb6dda53377ad2a0cde065c056 -updated: 2016-04-19T16:32:29.646405777+01:00 +hash: a6917bb6310c1da8c811026f209ba9d0d51783a8e8b83e3eb73df9fc4b14f46f +updated: 2016-05-10T15:55:18.049756292+01:00 imports: - name: github.com/btcsuite/btcd - version: 474547b211c8f5566d094478318fcfd3c2c838d4 + version: 2554caee5919958c0d4b41db8035f0e12ce6f624 subpackages: - btcec - name: github.com/btcsuite/fastsha256 version: 302ad4db268b46f9ebda3078f6f7397f96047735 +- name: github.com/BurntSushi/toml + version: f0aeabca5a127c4078abb8c8d64298b147264b55 - name: github.com/gin-gonic/gin version: 542be2fe77724f800fcab7eb6c01a4e597fb8506 subpackages: @@ -17,9 +19,9 @@ imports: subpackages: - proto - name: github.com/golang/snappy - version: 774a97396f7bfa4165e9dcf4bfa0747ea3edcc02 + version: d7b1e156f50d3c4664f683603af70e3e47fa0aa2 - name: github.com/gorilla/websocket - version: e2e3d8414d0fbae04004f151979f4e27c6747fe7 + version: 1f512fc3f05332ba7117626cdfb4e07474e58e60 - name: github.com/inconshreveable/log15 version: 57a084d014d4150152b19e4e531399a7145d1540 subpackages: @@ -28,7 +30,7 @@ imports: - name: github.com/manucorporat/sse version: ee05b128a739a0fb76c7ebd3ae4810c1de808d6d - name: github.com/mattn/go-colorable - version: 9cbef7c35391cca05f15f8181dc0b18bc9736dbb + version: 45ce6a6f60010487dd0dbab368b5fbbed1c14ef0 - name: github.com/mattn/go-isatty version: 56b76bdf51f7708750eac80fa38b952bb9f32639 - name: github.com/naoina/go-stringutil @@ -37,12 +39,10 @@ imports: version: 751171607256bb66e64c9f0220c00662420c38e9 subpackages: - ast -- name: github.com/sfreiberg/gotwilio - version: f024bbefe80fdb7bcc8c43b6add05dae97744e0e - name: github.com/stretchr/testify - version: c5d7a69bf8a2c9c374798160849c071093e41dd1 + version: 6cb3b85ef5a0efef77caef88363ec4d4b5c0976d - name: github.com/syndtr/goleveldb - version: 93fc893f2dadb96ffde441c7546cc67ea290a3a8 + version: cfa635847112c5dc4782e128fa7e0d05fdbfb394 subpackages: - leveldb - leveldb/errors @@ -63,22 +63,20 @@ imports: - extra25519 - name: github.com/tendermint/flowcontrol version: 84d9671090430e8ec80e35b339907e0579b999eb -- name: github.com/tendermint/go-alert - version: b824a5721dd8bdda6e5f3033ea35df3d82e4516d - name: github.com/tendermint/go-clist version: 634527f5b60fd7c71ca811262493df2ad65ee0ca - name: github.com/tendermint/go-common version: dcfa46af1341d03b80d32e4901019d1668b978b9 - name: github.com/tendermint/go-config - version: c47b67203b070d8bea835a928d50cb739972c48a + version: 150209dfcfdc7042dd8efc120e97398ea936e53e - name: github.com/tendermint/go-crypto - version: d57d5ff3c925149e62f3a3c3f6ecaf4c8250d678 + version: 41cfb7b677f4e16cdfd22b6ce0946c89919fbc7b - name: github.com/tendermint/go-db - version: a7878f1d0d8eaebf15f87bc2df15f7a1088cce7f + version: 16d1493718a519baff4f92dfec63a463525fb2fb - name: github.com/tendermint/go-events version: 7b75ca7bb55aa25e9ef765eb8c0b69486b227357 - name: github.com/tendermint/go-logger - version: 84391b36d3f5960e691c688d06b768708f0fa2f3 + version: 529efe50eab1a8a9c111d55f4de4ecd95f482761 - name: github.com/tendermint/go-merkle version: 05042c6ab9cad51d12e4cecf717ae68e3b1409a8 - name: github.com/tendermint/go-p2p @@ -86,17 +84,17 @@ imports: subpackages: - upnp - name: github.com/tendermint/go-rpc - version: 1410693eae5400a50efbbac3f23b9e3e94b7d6c8 + version: 1d9e89812adc202811b7fb8e9e0837e73adadb43 subpackages: - - client - server + - client - types - name: github.com/tendermint/go-wire version: 3b0adbc86ed8425eaed98516165b6788d9f4de7a - name: github.com/tendermint/log15 version: 6e460758f10ef42a4724b8e4a82fee59aaa0e41d - name: github.com/tendermint/tendermint - version: 0df4a723e9d189db26577a2a7b17652e8f1fd2f4 + version: a31b718cff5a3ae95377fa4488ac303f8ec2da2f subpackages: - config/tendermint - consensus @@ -106,11 +104,12 @@ imports: - proxy - blockchain - mempool + - config/tendermint_test - rpc/core - state - version - name: github.com/tendermint/tmsp - version: d471b06bd8ddb12f7275d49422b9b376dbdd84ad + version: 7ffd2899092f47110a5ffebe20247a9b7f80f4ad subpackages: - server - types @@ -120,7 +119,7 @@ imports: - name: github.com/tommy351/gin-cors version: dc91dec6313ae4db53481bf3b29cf6b94bf80357 - name: golang.org/x/crypto - version: 2f6fccd33b9b1fc23ebb73ad4890698820f7174d + version: 91ab96ae987aef3e74ab78b3aaf026109d206148 subpackages: - ripemd160 - nacl/secretbox @@ -136,7 +135,7 @@ imports: - context - netutil - name: golang.org/x/sys - version: f64b50fbea64174967a8882830d621a18ee1548e + version: b776ec39b3e54652e09028aaaaac9757f4f8211a subpackages: - unix - name: gopkg.in/fatih/set.v0 diff --git a/glide.yaml b/glide.yaml index 0e2f5ab80f206ad9c9bf97e0191143bf9389496c..afa08d6be776cca59bbce66c17f9883ad0445bf0 100644 --- a/glide.yaml +++ b/glide.yaml @@ -6,20 +6,22 @@ import: - package: github.com/tendermint/ed25519 - package: github.com/tendermint/go-common - package: github.com/tendermint/go-config + version: 150209dfcfdc7042dd8efc120e97398ea936e53e - package: github.com/tendermint/go-crypto - package: github.com/tendermint/go-db + version: develop - package: github.com/tendermint/go-events - package: github.com/tendermint/go-logger - package: github.com/tendermint/go-merkle - package: github.com/tendermint/go-p2p + version: 78c9d526c31d5ae06d5793b865d25a9407b635dc - package: github.com/stretchr/testify - package: github.com/tendermint/go-rpc - subpackages: - - client - package: github.com/tendermint/go-wire version: 3b0adbc86ed8425eaed98516165b6788d9f4de7a - package: github.com/tendermint/log15 - package: github.com/tendermint/tendermint + version: a31b718cff5a3ae95377fa4488ac303f8ec2da2f subpackages: - config/tendermint - consensus diff --git a/rpc/client/client.go b/rpc/client/client.go index ac3cd2707f92abeb2acd229dbbac870a01c5d006..01b57512cf4327b7d51ef2127fa9727bce079a9f 100644 --- a/rpc/client/client.go +++ b/rpc/client/client.go @@ -53,9 +53,9 @@ func GetAccount(client rpcclient.Client, addr []byte) (*acm.Account, error) { return res.(*ctypes.ResultGetAccount).Account, nil } -func SignTx(client rpcclient.Client, tx types.Tx, privAccs []*acm.PrivAccount) (types.Tx, error) { +func SignTx(client rpcclient.Client, tx txs.Tx, privAccs []*acm.PrivAccount) (txs.Tx, error) { wrapTx := struct { - types.Tx `json:"unwrap"` + txs.Tx `json:"unwrap"` }{tx} var res ctypes.ErisDBResult var err error @@ -71,9 +71,9 @@ func SignTx(client rpcclient.Client, tx types.Tx, privAccs []*acm.PrivAccount) ( return res.(*ctypes.ResultSignTx).Tx, nil } -func BroadcastTx(client rpcclient.Client, tx types.Tx) (ctypes.Receipt, error) { +func BroadcastTx(client rpcclient.Client, tx txs.Tx) (ctypes.Receipt, error) { wrapTx := struct { - types.Tx `json:"unwrap"` + txs.Tx `json:"unwrap"` }{tx} var res ctypes.ErisDBResult var err error @@ -155,7 +155,7 @@ func Call(client rpcclient.Client, fromAddress, toAddress, data []byte) (*ctypes return res.(*ctypes.ResultCall), err } -func GetName(client rpcclient.Client, name string) (*types.NameRegEntry, error) { +func GetName(client rpcclient.Client, name string) (*txs.NameRegEntry, error) { var res ctypes.ErisDBResult var err error switch cli := client.(type) { diff --git a/rpc/core/names.go b/rpc/core/names.go index 4dcd891e89d626d0407dfbc114a12ddbd463494e..063f07030a09b918ad73f3012dd2eee27fee46ba 100644 --- a/rpc/core/names.go +++ b/rpc/core/names.go @@ -19,7 +19,7 @@ func GetName(name string) (*ctypes.ResultGetName, error) { func ListNames() (*ctypes.ResultListNames, error) { var blockHeight int - var names []*types.NameRegEntry + var names []*txs.NameRegEntry state := erisdbApp.GetState() blockHeight = state.LastBlockHeight state.GetNames().Iterate(func(key []byte, value []byte) bool { diff --git a/rpc/core/routes.go b/rpc/core/routes.go index 80eee8a24f66a2f472e8a4b951d0ca7b9efd6741..cb52756937e4082eace6feac630fea7a6401ced0 100644 --- a/rpc/core/routes.go +++ b/rpc/core/routes.go @@ -129,7 +129,7 @@ func GenPrivAccountResult() (ctypes.ErisDBResult, error) { } } -func SignTxResult(tx types.Tx, privAccounts []*acm.PrivAccount) (ctypes.ErisDBResult, error) { +func SignTxResult(tx txs.Tx, privAccounts []*acm.PrivAccount) (ctypes.ErisDBResult, error) { if r, err := SignTx(tx, privAccounts); err != nil { return nil, err } else { @@ -137,7 +137,7 @@ func SignTxResult(tx types.Tx, privAccounts []*acm.PrivAccount) (ctypes.ErisDBRe } } -func BroadcastTxResult(tx types.Tx) (ctypes.ErisDBResult, error) { +func BroadcastTxResult(tx txs.Tx) (ctypes.ErisDBResult, error) { if r, err := BroadcastTxSync(tx); err != nil { return nil, err } else { diff --git a/rpc/core/txs.go b/rpc/core/txs.go index 7a93dec44768ea93cb80f59ca3234831baa268eb..2029ce016da32efcb9073324e5dd6f75fac59f87 100644 --- a/rpc/core/txs.go +++ b/rpc/core/txs.go @@ -2,6 +2,7 @@ package core import ( "fmt" + acm "github.com/eris-ltd/eris-db/account" "github.com/eris-ltd/eris-db/evm" ctypes "github.com/eris-ltd/eris-db/rpc/core/types" @@ -79,7 +80,7 @@ func CallCode(fromAddress, code, data []byte) (*ctypes.ResultCall, error) { //----------------------------------------------------------------------------- -func SignTx(tx types.Tx, privAccounts []*acm.PrivAccount) (*ctypes.ResultSignTx, error) { +func SignTx(tx txs.Tx, privAccounts []*acm.PrivAccount) (*ctypes.ResultSignTx, error) { // more checks? for i, privAccount := range privAccounts { @@ -88,18 +89,18 @@ func SignTx(tx types.Tx, privAccounts []*acm.PrivAccount) (*ctypes.ResultSignTx, } } switch tx.(type) { - case *types.SendTx: - sendTx := tx.(*types.SendTx) + case *txs.SendTx: + sendTx := tx.(*txs.SendTx) for i, input := range sendTx.Inputs { input.PubKey = privAccounts[i].PubKey input.Signature = privAccounts[i].Sign(config.GetString("erisdb.chain_id"), sendTx) } - case *types.CallTx: - callTx := tx.(*types.CallTx) + case *txs.CallTx: + callTx := tx.(*txs.CallTx) callTx.Input.PubKey = privAccounts[0].PubKey callTx.Input.Signature = privAccounts[0].Sign(config.GetString("erisdb.chain_id"), callTx) - case *types.BondTx: - bondTx := tx.(*types.BondTx) + case *txs.BondTx: + bondTx := tx.(*txs.BondTx) // the first privaccount corresponds to the BondTx pub key. // the rest to the inputs bondTx.Signature = privAccounts[0].Sign(config.GetString("erisdb.chain_id"), bondTx).(crypto.SignatureEd25519) @@ -107,11 +108,11 @@ func SignTx(tx types.Tx, privAccounts []*acm.PrivAccount) (*ctypes.ResultSignTx, input.PubKey = privAccounts[i+1].PubKey input.Signature = privAccounts[i+1].Sign(config.GetString("erisdb.chain_id"), bondTx) } - case *types.UnbondTx: - unbondTx := tx.(*types.UnbondTx) + case *txs.UnbondTx: + unbondTx := tx.(*txs.UnbondTx) unbondTx.Signature = privAccounts[0].Sign(config.GetString("erisdb.chain_id"), unbondTx).(crypto.SignatureEd25519) - case *types.RebondTx: - rebondTx := tx.(*types.RebondTx) + case *txs.RebondTx: + rebondTx := tx.(*txs.RebondTx) rebondTx.Signature = privAccounts[0].Sign(config.GetString("erisdb.chain_id"), rebondTx).(crypto.SignatureEd25519) } return &ctypes.ResultSignTx{tx}, nil diff --git a/rpc/test/client_ws_test.go b/rpc/test/client_ws_test.go index 94e85508793b6d97401af5330e3a4489a6b18fd9..7cb64ecd9a0e3a9b90f5724252c4b23c4b579fee 100644 --- a/rpc/test/client_ws_test.go +++ b/rpc/test/client_ws_test.go @@ -22,7 +22,7 @@ func TestWSConnect(t *testing.T) { // receive a new block message func TestWSNewBlock(t *testing.T) { wsc := newWSClient(t) - eid := types.EventStringNewBlock() + eid := txs.EventStringNewBlock() subscribe(t, wsc, eid) defer func() { unsubscribe(t, wsc, eid) @@ -40,7 +40,7 @@ func TestWSBlockchainGrowth(t *testing.T) { t.Skip("skipping test in short mode.") } wsc := newWSClient(t) - eid := types.EventStringNewBlock() + eid := txs.EventStringNewBlock() subscribe(t, wsc, eid) defer func() { unsubscribe(t, wsc, eid) @@ -56,8 +56,8 @@ func TestWSSend(t *testing.T) { amt := int64(100) wsc := newWSClient(t) - eidInput := types.EventStringAccInput(user[0].Address) - eidOutput := types.EventStringAccOutput(toAddr) + eidInput := txs.EventStringAccInput(user[0].Address) + eidOutput := txs.EventStringAccOutput(toAddr) subscribe(t, wsc, eidInput) subscribe(t, wsc, eidOutput) defer func() { @@ -78,7 +78,7 @@ func TestWSDoubleFire(t *testing.T) { t.Skip("skipping test in short mode.") } wsc := newWSClient(t) - eid := types.EventStringAccInput(user[0].Address) + eid := txs.EventStringAccInput(user[0].Address) subscribe(t, wsc, eid) defer func() { unsubscribe(t, wsc, eid) @@ -106,7 +106,7 @@ func TestWSCallWait(t *testing.T) { t.Skip("skipping test in short mode.") } wsc := newWSClient(t) - eid1 := types.EventStringAccInput(user[0].Address) + eid1 := txs.EventStringAccInput(user[0].Address) subscribe(t, wsc, eid1) defer func() { unsubscribe(t, wsc, eid1) @@ -124,7 +124,7 @@ func TestWSCallWait(t *testing.T) { // susbscribe to the new contract amt = int64(10001) - eid2 := types.EventStringAccOutput(contractAddr) + eid2 := txs.EventStringAccOutput(contractAddr) subscribe(t, wsc, eid2) defer func() { unsubscribe(t, wsc, eid2) @@ -154,7 +154,7 @@ func TestWSCallNoWait(t *testing.T) { // susbscribe to the new contract amt = int64(10001) - eid := types.EventStringAccOutput(contractAddr) + eid := txs.EventStringAccOutput(contractAddr) subscribe(t, wsc, eid) defer func() { unsubscribe(t, wsc, eid) @@ -190,7 +190,7 @@ func TestWSCallCall(t *testing.T) { // susbscribe to the new contracts amt = int64(10001) - eid1 := types.EventStringAccCall(contractAddr1) + eid1 := txs.EventStringAccCall(contractAddr1) subscribe(t, wsc, eid1) defer func() { unsubscribe(t, wsc, eid1) @@ -207,6 +207,6 @@ func TestWSCallCall(t *testing.T) { waitForEvent(t, wsc, eid1, true, func() { tx := makeDefaultCallTx(t, wsTyp, contractAddr2, nil, amt, gasLim, fee) broadcastTx(t, wsTyp, tx) - *txid = types.TxID(chainID, tx) + *txid = txs.TxID(chainID, tx) }, unmarshalValidateCall(user[0].Address, returnVal, txid)) } diff --git a/rpc/test/tests.go b/rpc/test/tests.go index b6ed2c849f5f6b35fadada464ffe3e3fa5c19368..8b0552a54e79e6fa6da7c0b18caabb21f50f30aa 100644 --- a/rpc/test/tests.go +++ b/rpc/test/tests.go @@ -62,15 +62,15 @@ func testSignedTx(t *testing.T, typ string) { func testOneSignTx(t *testing.T, typ string, addr []byte, amt int64) { tx := makeDefaultSendTx(t, typ, addr, amt) tx2 := signTx(t, typ, tx, user[0]) - tx2hash := types.TxID(chainID, tx2) + tx2hash := txs.TxID(chainID, tx2) tx.SignInput(chainID, 0, user[0]) - txhash := types.TxID(chainID, tx) + txhash := txs.TxID(chainID, tx) if bytes.Compare(txhash, tx2hash) != 0 { t.Fatal("Got different signatures for signing via rpc vs tx_utils") } tx_ := signTx(t, typ, tx, user[0]) - tx = tx_.(*types.SendTx) + tx = tx_.(*txs.SendTx) checkTx(t, user[0].Address, user[0], tx) } @@ -86,11 +86,11 @@ func testBroadcastTx(t *testing.T, typ string) { t.Fatal("Failed to compute tx hash") } pool := node.MempoolReactor().Mempool - txs := pool.Reap(-1) - if len(txs) != mempoolCount { - t.Fatalf("The mem pool has %d txs. Expected %d", len(txs), mempoolCount) + trnxs := pool.Reap(-1) + if len(trnxs) != mempoolCount { + t.Fatalf("The mem pool has %d txs. Expected %d", len(trnxs), mempoolCount) } - tx2 := types.DecodeTx(txs[mempoolCount-1]).(*types.SendTx) + tx2 := txs.DecodeTx(trnxs[mempoolCount-1]).(*txs.SendTx) n, err := new(int), new(error) buf1, buf2 := new(bytes.Buffer), new(bytes.Buffer) tx.WriteSignBytes(chainID, buf1, n, err) @@ -102,7 +102,7 @@ func testBroadcastTx(t *testing.T, typ string) { func testGetStorage(t *testing.T, typ string) { wsc := newWSClient(t) - eid := types.EventStringNewBlock() + eid := txs.EventStringNewBlock() subscribe(t, wsc, eid) defer func() { unsubscribe(t, wsc, eid) @@ -154,7 +154,7 @@ func testCallCode(t *testing.T, typ string) { func testCall(t *testing.T, typ string) { wsc := newWSClient(t) - eid := types.EventStringNewBlock() + eid := txs.EventStringNewBlock() subscribe(t, wsc, eid) defer func() { unsubscribe(t, wsc, eid) @@ -194,7 +194,7 @@ func testNameReg(t *testing.T, typ string) { client := clients[typ] wsc := newWSClient(t) - types.MinNameRegistrationPeriod = 1 + txs.MinNameRegistrationPeriod = 1 // register a new name, check if its there // since entries ought to be unique and these run against different clients, we append the typ @@ -202,9 +202,9 @@ func testNameReg(t *testing.T, typ string) { data := "if not now, when" fee := int64(1000) numDesiredBlocks := int64(2) - amt := fee + numDesiredBlocks*types.NameByteCostMultiplier*types.NameBlockCostMultiplier*types.NameBaseCost(name, data) + amt := fee + numDesiredBlocks*txs.NameByteCostMultiplier*txs.NameBlockCostMultiplier*txs.NameBaseCost(name, data) - eid := types.EventStringNameReg(name) + eid := txs.EventStringNameReg(name) subscribe(t, wsc, eid) tx := makeDefaultNameTx(t, typ, name, data, amt, fee) @@ -238,7 +238,7 @@ func testNameReg(t *testing.T, typ string) { // for the rest we just use new block event // since we already tested the namereg event - eid = types.EventStringNewBlock() + eid = txs.EventStringNewBlock() subscribe(t, wsc, eid) defer func() { unsubscribe(t, wsc, eid) @@ -248,7 +248,7 @@ func testNameReg(t *testing.T, typ string) { // update the data as the owner, make sure still there numDesiredBlocks = int64(2) data = "these are amongst the things I wish to bestow upon the youth of generations come: a safe supply of honey, and a better money. For what else shall they need" - amt = fee + numDesiredBlocks*types.NameByteCostMultiplier*types.NameBlockCostMultiplier*types.NameBaseCost(name, data) + amt = fee + numDesiredBlocks*txs.NameByteCostMultiplier*txs.NameBlockCostMultiplier*txs.NameBaseCost(name, data) tx = makeDefaultNameTx(t, typ, name, data, amt, fee) broadcastTx(t, typ, tx) // commit block @@ -262,7 +262,7 @@ func testNameReg(t *testing.T, typ string) { // try to update as non owner, should fail nonce := getNonce(t, typ, user[1].Address) data2 := "this is not my beautiful house" - tx = types.NewNameTxWithNonce(user[1].PubKey, name, data2, amt, fee, nonce+1) + tx = txs.NewNameTxWithNonce(user[1].PubKey, name, data2, amt, fee, nonce+1) tx.Sign(chainID, user[1]) _, err := edbcli.BroadcastTx(client, tx) if err == nil { diff --git a/state/block_cache.go b/state/block_cache.go index a0d282ed8bff480e36f1f92c904346156ca7a8fa..1cefa6a3b18b996800a2d89e0670675ee14dd1d2 100644 --- a/state/block_cache.go +++ b/state/block_cache.go @@ -120,7 +120,7 @@ func (cache *BlockCache) SetStorage(addr Word256, key Word256, value Word256) { //------------------------------------- // BlockCache.names -func (cache *BlockCache) GetNameRegEntry(name string) *types.NameRegEntry { +func (cache *BlockCache) GetNameRegEntry(name string) *txs.NameRegEntry { entry, removed, _ := cache.names[name].unpack() if removed { return nil @@ -133,7 +133,7 @@ func (cache *BlockCache) GetNameRegEntry(name string) *types.NameRegEntry { } } -func (cache *BlockCache) UpdateNameRegEntry(entry *types.NameRegEntry) { +func (cache *BlockCache) UpdateNameRegEntry(entry *txs.NameRegEntry) { name := entry.Name cache.names[name] = nameInfo{entry, false, true} } @@ -278,11 +278,11 @@ func (stjInfo storageInfo) unpack() (Word256, bool) { } type nameInfo struct { - name *types.NameRegEntry + name *txs.NameRegEntry removed bool dirty bool } -func (nInfo nameInfo) unpack() (*types.NameRegEntry, bool, bool) { +func (nInfo nameInfo) unpack() (*txs.NameRegEntry, bool, bool) { return nInfo.name, nInfo.removed, nInfo.dirty } diff --git a/state/execution.go b/state/execution.go index bb635d0cb53b4329eb44d9e297b6a0d6945b3fca..7247dd5057a7e5d2d5e43afcb3e9b66eb346cec6 100644 --- a/state/execution.go +++ b/state/execution.go @@ -22,7 +22,7 @@ import ( // NOTE: If an error occurs during block execution, state will be left // at an invalid state. Copy the state before calling ExecBlock! -func ExecBlock(s *State, block *types.Block, blockPartsHeader types.PartSetHeader) error { +func ExecBlock(s *State, block *txs.Block, blockPartsHeader txs.PartSetHeader) error { err := execBlock(s, block, blockPartsHeader) if err != nil { return err @@ -39,7 +39,7 @@ func ExecBlock(s *State, block *types.Block, blockPartsHeader types.PartSetHeade // executes transactions of a block, does not check block.StateHash // NOTE: If an error occurs during block execution, state will be left // at an invalid state. Copy the state before calling execBlock! -func execBlock(s *State, block *types.Block, blockPartsHeader types.PartSetHeader) error { +func execBlock(s *State, block *txs.Block, blockPartsHeader txs.PartSetHeader) error { // Basic block validation. err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockHash, s.LastBlockParts, s.LastBlockTime) if err != nil { @@ -108,8 +108,8 @@ func execBlock(s *State, block *types.Block, blockPartsHeader types.PartSetHeade // If any unbonding periods are over, // reward account with bonded coins. - toRelease := []*types.Validator{} - s.UnbondingValidators.Iterate(func(index int, val *types.Validator) bool { + toRelease := []*txs.Validator{} + s.UnbondingValidators.Iterate(func(index int, val *txs.Validator) bool { if val.UnbondHeight+unbondingPeriodBlocks < block.Height { toRelease = append(toRelease, val) } @@ -121,8 +121,8 @@ func execBlock(s *State, block *types.Block, blockPartsHeader types.PartSetHeade // If any validators haven't signed in a while, // unbond them, they have timed out. - toTimeout := []*types.Validator{} - s.BondedValidators.Iterate(func(index int, val *types.Validator) bool { + toTimeout := []*txs.Validator{} + s.BondedValidators.Iterate(func(index int, val *txs.Validator) bool { lastActivityHeight := MaxInt(val.BondHeight, val.LastCommitHeight) if lastActivityHeight+validatorTimeoutBlocks < block.Height { log.Notice("Validator timeout", "validator", val, "height", block.Height) @@ -148,16 +148,16 @@ func execBlock(s *State, block *types.Block, blockPartsHeader types.PartSetHeade // acm.PubKey.(type) != nil, (it must be known), // or it must be specified in the TxInput. If redeclared, // the TxInput is modified and input.PubKey set to nil. -func getInputs(state AccountGetter, ins []*types.TxInput) (map[string]*acm.Account, error) { +func getInputs(state AccountGetter, ins []*txs.TxInput) (map[string]*acm.Account, error) { accounts := map[string]*acm.Account{} for _, in := range ins { // Account shouldn't be duplicated if _, ok := accounts[string(in.Address)]; ok { - return nil, types.ErrTxDuplicateAddress + return nil, txs.ErrTxDuplicateAddress } acc := state.GetAccount(in.Address) if acc == nil { - return nil, types.ErrTxInvalidAddress + return nil, txs.ErrTxInvalidAddress } // PubKey should be present in either "account" or "in" if err := checkInputPubKey(acc, in); err != nil { @@ -168,7 +168,7 @@ func getInputs(state AccountGetter, ins []*types.TxInput) (map[string]*acm.Accou return accounts, nil } -func getOrMakeOutputs(state AccountGetter, accounts map[string]*acm.Account, outs []*types.TxOutput) (map[string]*acm.Account, error) { +func getOrMakeOutputs(state AccountGetter, accounts map[string]*acm.Account, outs []*txs.TxOutput) (map[string]*acm.Account, error) { if accounts == nil { accounts = make(map[string]*acm.Account) } @@ -178,7 +178,7 @@ func getOrMakeOutputs(state AccountGetter, accounts map[string]*acm.Account, out for _, out := range outs { // Account shouldn't be duplicated if _, ok := accounts[string(out.Address)]; ok { - return nil, types.ErrTxDuplicateAddress + return nil, txs.ErrTxDuplicateAddress } acc := state.GetAccount(out.Address) // output account may be nil (new) @@ -202,13 +202,13 @@ func getOrMakeOutputs(state AccountGetter, accounts map[string]*acm.Account, out return accounts, nil } -func checkInputPubKey(acc *acm.Account, in *types.TxInput) error { +func checkInputPubKey(acc *acm.Account, in *txs.TxInput) error { if acc.PubKey == nil { if in.PubKey == nil { - return types.ErrTxUnknownPubKey + return txs.ErrTxUnknownPubKey } if !bytes.Equal(in.PubKey.Address(), acc.Address) { - return types.ErrTxInvalidPubKey + return txs.ErrTxInvalidPubKey } acc.PubKey = in.PubKey } else { @@ -217,7 +217,7 @@ func checkInputPubKey(acc *acm.Account, in *types.TxInput) error { return nil } -func validateInputs(accounts map[string]*acm.Account, signBytes []byte, ins []*types.TxInput) (total int64, err error) { +func validateInputs(accounts map[string]*acm.Account, signBytes []byte, ins []*txs.TxInput) (total int64, err error) { for _, in := range ins { acc := accounts[string(in.Address)] if acc == nil { @@ -233,30 +233,30 @@ func validateInputs(accounts map[string]*acm.Account, signBytes []byte, ins []*t return total, nil } -func validateInput(acc *acm.Account, signBytes []byte, in *types.TxInput) (err error) { +func validateInput(acc *acm.Account, signBytes []byte, in *txs.TxInput) (err error) { // Check TxInput basic if err := in.ValidateBasic(); err != nil { return err } // Check signatures if !acc.PubKey.VerifyBytes(signBytes, in.Signature) { - return types.ErrTxInvalidSignature + return txs.ErrTxInvalidSignature } // Check sequences if acc.Sequence+1 != in.Sequence { - return types.ErrTxInvalidSequence{ + return txs.ErrTxInvalidSequence{ Got: in.Sequence, Expected: acc.Sequence + 1, } } // Check amount if acc.Balance < in.Amount { - return types.ErrTxInsufficientFunds + return txs.ErrTxInsufficientFunds } return nil } -func validateOutputs(outs []*types.TxOutput) (total int64, err error) { +func validateOutputs(outs []*txs.TxOutput) (total int64, err error) { for _, out := range outs { // Check TxOutput basic if err := out.ValidateBasic(); err != nil { @@ -268,7 +268,7 @@ func validateOutputs(outs []*types.TxOutput) (total int64, err error) { return total, nil } -func adjustByInputs(accounts map[string]*acm.Account, ins []*types.TxInput) { +func adjustByInputs(accounts map[string]*acm.Account, ins []*txs.TxInput) { for _, in := range ins { acc := accounts[string(in.Address)] if acc == nil { @@ -282,7 +282,7 @@ func adjustByInputs(accounts map[string]*acm.Account, ins []*types.TxInput) { } } -func adjustByOutputs(accounts map[string]*acm.Account, outs []*types.TxOutput) { +func adjustByOutputs(accounts map[string]*acm.Account, outs []*txs.TxOutput) { for _, out := range outs { acc := accounts[string(out.Address)] if acc == nil { @@ -294,7 +294,7 @@ func adjustByOutputs(accounts map[string]*acm.Account, outs []*types.TxOutput) { // If the tx is invalid, an error will be returned. // Unlike ExecBlock(), state will not be altered. -func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireable) (err error) { +func ExecTx(blockCache *BlockCache, tx txs.Tx, runCall bool, evc events.Fireable) (err error) { // TODO: do something with fees fees := int64(0) @@ -302,7 +302,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // Exec tx switch tx := tx.(type) { - case *types.SendTx: + case *txs.SendTx: accounts, err := getInputs(blockCache, tx.Inputs) if err != nil { return err @@ -330,7 +330,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab return err } if outTotal > inTotal { - return types.ErrTxInsufficientFunds + return txs.ErrTxInsufficientFunds } fee := inTotal - outTotal fees += fee @@ -345,23 +345,23 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // if the evc is nil, nothing will happen if evc != nil { for _, i := range tx.Inputs { - evc.FireEvent(types.EventStringAccInput(i.Address), types.EventDataTx{tx, nil, ""}) + evc.FireEvent(txs.EventStringAccInput(i.Address), txs.EventDataTx{tx, nil, ""}) } for _, o := range tx.Outputs { - evc.FireEvent(types.EventStringAccOutput(o.Address), types.EventDataTx{tx, nil, ""}) + evc.FireEvent(txs.EventStringAccOutput(o.Address), txs.EventDataTx{tx, nil, ""}) } } return nil - case *types.CallTx: + case *txs.CallTx: var inAcc, outAcc *acm.Account // Validate input inAcc = blockCache.GetAccount(tx.Input.Address) if inAcc == nil { log.Info(Fmt("Can't find in account %X", tx.Input.Address)) - return types.ErrTxInvalidAddress + return txs.ErrTxInvalidAddress } createContract := len(tx.Address) == 0 @@ -388,14 +388,14 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab } if tx.Input.Amount < tx.Fee { log.Info(Fmt("Sender did not send enough to cover the fee %X", tx.Input.Address)) - return types.ErrTxInsufficientFunds + return txs.ErrTxInsufficientFunds } if !createContract { // Validate output if len(tx.Address) != 20 { log.Info(Fmt("Destination address is not 20 bytes %X", tx.Address)) - return types.ErrTxInvalidAddress + return txs.ErrTxInvalidAddress } // check if its a native contract if vm.RegisteredNativeContract(LeftPadWord256(tx.Address)) { @@ -451,7 +451,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab log.Info(Fmt("%X tries to call %X but code is blank.", inAcc.Address, tx.Address)) } - err = types.ErrTxInvalidAddress + err = txs.ErrTxInvalidAddress goto CALL_COMPLETE } @@ -473,7 +473,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // Write caller/callee to txCache. txCache.UpdateAccount(caller) txCache.UpdateAccount(callee) - vmach := vm.NewVM(txCache, params, caller.Address, types.TxID(_s.ChainID, tx)) + vmach := vm.NewVM(txCache, params, caller.Address, txs.TxID(_s.ChainID, tx)) vmach.SetFireable(evc) // NOTE: Call() transfers the value from caller to callee iff call succeeds. ret, err = vmach.Call(caller, callee, code, tx.Data, value, &gas) @@ -502,8 +502,8 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab if err != nil { exception = err.Error() } - evc.FireEvent(types.EventStringAccInput(tx.Input.Address), types.EventDataTx{tx, ret, exception}) - evc.FireEvent(types.EventStringAccOutput(tx.Address), types.EventDataTx{tx, ret, exception}) + evc.FireEvent(txs.EventStringAccInput(tx.Input.Address), txs.EventDataTx{tx, ret, exception}) + evc.FireEvent(txs.EventStringAccOutput(tx.Address), txs.EventDataTx{tx, ret, exception}) } } else { // The mempool does not call txs until @@ -519,14 +519,14 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab return nil - case *types.NameTx: + case *txs.NameTx: var inAcc *acm.Account // Validate input inAcc = blockCache.GetAccount(tx.Input.Address) if inAcc == nil { log.Info(Fmt("Can't find in account %X", tx.Input.Address)) - return types.ErrTxInvalidAddress + return txs.ErrTxInvalidAddress } // check permission if !hasNamePermission(blockCache, inAcc) { @@ -546,7 +546,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // fee is in addition to the amount which is used to determine the TTL if tx.Input.Amount < tx.Fee { log.Info(Fmt("Sender did not send enough to cover the fee %X", tx.Input.Address)) - return types.ErrTxInsufficientFunds + return txs.ErrTxInsufficientFunds } // validate the input strings @@ -557,7 +557,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab value := tx.Input.Amount - tx.Fee // let's say cost of a name for one block is len(data) + 32 - costPerBlock := types.NameCostPerBlock(types.NameBaseCost(tx.Name, tx.Data)) + costPerBlock := txs.NameCostPerBlock(txs.NameBaseCost(tx.Name, tx.Data)) expiresIn := int(value / costPerBlock) lastBlockHeight := _s.LastBlockHeight @@ -573,7 +573,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // ensure we are owner if bytes.Compare(entry.Owner, tx.Input.Address) != 0 { log.Info(Fmt("Sender %X is trying to update a name (%s) for which he is not owner", tx.Input.Address, tx.Name)) - return types.ErrTxPermissionDenied + return txs.ErrTxPermissionDenied } } else { expired = true @@ -589,8 +589,8 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // update the entry by bumping the expiry // and changing the data if expired { - if expiresIn < types.MinNameRegistrationPeriod { - return errors.New(Fmt("Names must be registered for at least %d blocks", types.MinNameRegistrationPeriod)) + if expiresIn < txs.MinNameRegistrationPeriod { + return errors.New(Fmt("Names must be registered for at least %d blocks", txs.MinNameRegistrationPeriod)) } entry.Expires = lastBlockHeight + expiresIn entry.Owner = tx.Input.Address @@ -598,11 +598,11 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab } else { // since the size of the data may have changed // we use the total amount of "credit" - oldCredit := int64(entry.Expires-lastBlockHeight) * types.NameBaseCost(entry.Name, entry.Data) + oldCredit := int64(entry.Expires-lastBlockHeight) * txs.NameBaseCost(entry.Name, entry.Data) credit := oldCredit + value expiresIn = int(credit / costPerBlock) - if expiresIn < types.MinNameRegistrationPeriod { - return errors.New(Fmt("Names must be registered for at least %d blocks", types.MinNameRegistrationPeriod)) + if expiresIn < txs.MinNameRegistrationPeriod { + return errors.New(Fmt("Names must be registered for at least %d blocks", txs.MinNameRegistrationPeriod)) } entry.Expires = lastBlockHeight + expiresIn log.Info("Updated namereg entry", "name", entry.Name, "expiresIn", expiresIn, "oldCredit", oldCredit, "value", value, "credit", credit) @@ -611,11 +611,11 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab blockCache.UpdateNameRegEntry(entry) } } else { - if expiresIn < types.MinNameRegistrationPeriod { - return errors.New(Fmt("Names must be registered for at least %d blocks", types.MinNameRegistrationPeriod)) + if expiresIn < txs.MinNameRegistrationPeriod { + return errors.New(Fmt("Names must be registered for at least %d blocks", txs.MinNameRegistrationPeriod)) } // entry does not exist, so create it - entry = &types.NameRegEntry{ + entry = &txs.NameRegEntry{ Name: tx.Name, Owner: tx.Input.Address, Data: tx.Data, @@ -635,8 +635,8 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // TODO: maybe we want to take funds on error and allow txs in that don't do anythingi? if evc != nil { - evc.FireEvent(types.EventStringAccInput(tx.Input.Address), types.EventDataTx{tx, nil, ""}) - evc.FireEvent(types.EventStringNameReg(tx.Name), types.EventDataTx{tx, nil, ""}) + evc.FireEvent(txs.EventStringAccInput(tx.Input.Address), txs.EventDataTx{tx, nil, ""}) + evc.FireEvent(txs.EventStringNameReg(tx.Name), txs.EventDataTx{tx, nil, ""}) } return nil @@ -644,7 +644,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // Consensus related Txs inactivated for now // TODO! /* - case *types.BondTx: + case *txs.BondTx: valInfo := blockCache.State().GetValidatorInfo(tx.PubKey.Address()) if valInfo != nil { // TODO: In the future, check that the validator wasn't destroyed, @@ -683,14 +683,14 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab return err } if !tx.PubKey.VerifyBytes(signBytes, tx.Signature) { - return types.ErrTxInvalidSignature + return txs.ErrTxInvalidSignature } outTotal, err := validateOutputs(tx.UnbondTo) if err != nil { return err } if outTotal > inTotal { - return types.ErrTxInsufficientFunds + return txs.ErrTxInsufficientFunds } fee := inTotal - outTotal fees += fee @@ -701,7 +701,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab blockCache.UpdateAccount(acc) } // Add ValidatorInfo - _s.SetValidatorInfo(&types.ValidatorInfo{ + _s.SetValidatorInfo(&txs.ValidatorInfo{ Address: tx.PubKey.Address(), PubKey: tx.PubKey, UnbondTo: tx.UnbondTo, @@ -709,7 +709,7 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab FirstBondAmount: outTotal, }) // Add Validator - added := _s.BondedValidators.Add(&types.Validator{ + added := _s.BondedValidators.Add(&txs.Validator{ Address: tx.PubKey.Address(), PubKey: tx.PubKey, BondHeight: _s.LastBlockHeight + 1, @@ -721,21 +721,21 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab } if evc != nil { // TODO: fire for all inputs - evc.FireEvent(types.EventStringBond(), types.EventDataTx{tx, nil, ""}) + evc.FireEvent(txs.EventStringBond(), txs.EventDataTx{tx, nil, ""}) } return nil - case *types.UnbondTx: + case *txs.UnbondTx: // The validator must be active _, val := _s.BondedValidators.GetByAddress(tx.Address) if val == nil { - return types.ErrTxInvalidAddress + return txs.ErrTxInvalidAddress } // Verify the signature signBytes := acm.SignBytes(_s.ChainID, tx) if !val.PubKey.VerifyBytes(signBytes, tx.Signature) { - return types.ErrTxInvalidSignature + return txs.ErrTxInvalidSignature } // tx.Height must be greater than val.LastCommitHeight @@ -746,21 +746,21 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // Good! _s.unbondValidator(val) if evc != nil { - evc.FireEvent(types.EventStringUnbond(), types.EventDataTx{tx, nil, ""}) + evc.FireEvent(txs.EventStringUnbond(), txs.EventDataTx{tx, nil, ""}) } return nil - case *types.RebondTx: + case *txs.RebondTx: // The validator must be inactive _, val := _s.UnbondingValidators.GetByAddress(tx.Address) if val == nil { - return types.ErrTxInvalidAddress + return txs.ErrTxInvalidAddress } // Verify the signature signBytes := acm.SignBytes(_s.ChainID, tx) if !val.PubKey.VerifyBytes(signBytes, tx.Signature) { - return types.ErrTxInvalidSignature + return txs.ErrTxInvalidSignature } // tx.Height must be in a suitable range @@ -774,24 +774,24 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // Good! _s.rebondValidator(val) if evc != nil { - evc.FireEvent(types.EventStringRebond(), types.EventDataTx{tx, nil, ""}) + evc.FireEvent(txs.EventStringRebond(), txs.EventDataTx{tx, nil, ""}) } return nil - case *types.DupeoutTx: + case *txs.DupeoutTx: // Verify the signatures _, accused := _s.BondedValidators.GetByAddress(tx.Address) if accused == nil { _, accused = _s.UnbondingValidators.GetByAddress(tx.Address) if accused == nil { - return types.ErrTxInvalidAddress + return txs.ErrTxInvalidAddress } } voteASignBytes := acm.SignBytes(_s.ChainID, &tx.VoteA) voteBSignBytes := acm.SignBytes(_s.ChainID, &tx.VoteB) if !accused.PubKey.VerifyBytes(voteASignBytes, tx.VoteA.Signature) || !accused.PubKey.VerifyBytes(voteBSignBytes, tx.VoteB.Signature) { - return types.ErrTxInvalidSignature + return txs.ErrTxInvalidSignature } // Verify equivocation @@ -813,19 +813,19 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab // Good! (Bad validator!) _s.destroyValidator(accused) if evc != nil { - evc.FireEvent(types.EventStringDupeout(), types.EventDataTx{tx, nil, ""}) + evc.FireEvent(txs.EventStringDupeout(), txs.EventDataTx{tx, nil, ""}) } return nil */ - case *types.PermissionsTx: + case *txs.PermissionsTx: var inAcc *acm.Account // Validate input inAcc = blockCache.GetAccount(tx.Input.Address) if inAcc == nil { log.Debug(Fmt("Can't find in account %X", tx.Input.Address)) - return types.ErrTxInvalidAddress + return txs.ErrTxInvalidAddress } permFlag := tx.PermArgs.PermFlag() @@ -904,8 +904,8 @@ func ExecTx(blockCache *BlockCache, tx types.Tx, runCall bool, evc events.Fireab } if evc != nil { - evc.FireEvent(types.EventStringAccInput(tx.Input.Address), types.EventDataTx{tx, nil, ""}) - evc.FireEvent(types.EventStringPermissions(ptypes.PermFlagToString(permFlag)), types.EventDataTx{tx, nil, ""}) + evc.FireEvent(txs.EventStringAccInput(tx.Input.Address), txs.EventDataTx{tx, nil, ""}) + evc.FireEvent(txs.EventStringPermissions(ptypes.PermFlagToString(permFlag)), txs.EventDataTx{tx, nil, ""}) } return nil @@ -996,7 +996,7 @@ func hasBondOrSendPermission(state AccountGetter, accs map[string]*acm.Account) //----------------------------------------------------------------------------- type InvalidTxError struct { - Tx types.Tx + Tx txs.Tx Reason error } diff --git a/state/permissions_test.go b/state/permissions_test.go index 2b17cfbc5497f0f79e8da16ff8613d860dc7a359..46aa570a7fb6dda0ef56e9416bd77a49eb4f8a97 100644 --- a/state/permissions_test.go +++ b/state/permissions_test.go @@ -154,7 +154,7 @@ func TestSendFails(t *testing.T) { // send txs // simple send tx should fail - tx := types.NewSendTx() + tx := txs.NewSendTx() if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil { t.Fatal(err) } @@ -167,7 +167,7 @@ func TestSendFails(t *testing.T) { } // simple send tx with call perm should fail - tx = types.NewSendTx() + tx = txs.NewSendTx() if err := tx.AddInput(blockCache, user[2].PubKey, 5); err != nil { t.Fatal(err) } @@ -180,7 +180,7 @@ func TestSendFails(t *testing.T) { } // simple send tx with create perm should fail - tx = types.NewSendTx() + tx = txs.NewSendTx() if err := tx.AddInput(blockCache, user[3].PubKey, 5); err != nil { t.Fatal(err) } @@ -196,7 +196,7 @@ func TestSendFails(t *testing.T) { acc := blockCache.GetAccount(user[3].Address) acc.Permissions.Base.Set(ptypes.Send, true) blockCache.UpdateAccount(acc) - tx = types.NewSendTx() + tx = txs.NewSendTx() if err := tx.AddInput(blockCache, user[3].PubKey, 5); err != nil { t.Fatal(err) } @@ -221,7 +221,7 @@ func TestName(t *testing.T) { // name txs // simple name tx without perm should fail - tx, err := types.NewNameTx(st, user[0].PubKey, "somename", "somedata", 10000, 100) + tx, err := txs.NewNameTx(st, user[0].PubKey, "somename", "somedata", 10000, 100) if err != nil { t.Fatal(err) } @@ -233,7 +233,7 @@ func TestName(t *testing.T) { } // simple name tx with perm should pass - tx, err = types.NewNameTx(st, user[1].PubKey, "somename", "somedata", 10000, 100) + tx, err = txs.NewNameTx(st, user[1].PubKey, "somename", "somedata", 10000, 100) if err != nil { t.Fatal(err) } @@ -256,7 +256,7 @@ func TestCallFails(t *testing.T) { // call txs // simple call tx should fail - tx, _ := types.NewCallTx(blockCache, user[0].PubKey, user[4].Address, nil, 100, 100, 100) + tx, _ := txs.NewCallTx(blockCache, user[0].PubKey, user[4].Address, nil, 100, 100, 100) tx.Sign(chainID, user[0]) if err := ExecTx(blockCache, tx, true, nil); err == nil { t.Fatal("Expected error") @@ -265,7 +265,7 @@ func TestCallFails(t *testing.T) { } // simple call tx with send permission should fail - tx, _ = types.NewCallTx(blockCache, user[1].PubKey, user[4].Address, nil, 100, 100, 100) + tx, _ = txs.NewCallTx(blockCache, user[1].PubKey, user[4].Address, nil, 100, 100, 100) tx.Sign(chainID, user[1]) if err := ExecTx(blockCache, tx, true, nil); err == nil { t.Fatal("Expected error") @@ -274,7 +274,7 @@ func TestCallFails(t *testing.T) { } // simple call tx with create permission should fail - tx, _ = types.NewCallTx(blockCache, user[3].PubKey, user[4].Address, nil, 100, 100, 100) + tx, _ = txs.NewCallTx(blockCache, user[3].PubKey, user[4].Address, nil, 100, 100, 100) tx.Sign(chainID, user[3]) if err := ExecTx(blockCache, tx, true, nil); err == nil { t.Fatal("Expected error") @@ -286,7 +286,7 @@ func TestCallFails(t *testing.T) { // create txs // simple call create tx should fail - tx, _ = types.NewCallTx(blockCache, user[0].PubKey, nil, nil, 100, 100, 100) + tx, _ = txs.NewCallTx(blockCache, user[0].PubKey, nil, nil, 100, 100, 100) tx.Sign(chainID, user[0]) if err := ExecTx(blockCache, tx, true, nil); err == nil { t.Fatal("Expected error") @@ -295,7 +295,7 @@ func TestCallFails(t *testing.T) { } // simple call create tx with send perm should fail - tx, _ = types.NewCallTx(blockCache, user[1].PubKey, nil, nil, 100, 100, 100) + tx, _ = txs.NewCallTx(blockCache, user[1].PubKey, nil, nil, 100, 100, 100) tx.Sign(chainID, user[1]) if err := ExecTx(blockCache, tx, true, nil); err == nil { t.Fatal("Expected error") @@ -304,7 +304,7 @@ func TestCallFails(t *testing.T) { } // simple call create tx with call perm should fail - tx, _ = types.NewCallTx(blockCache, user[2].PubKey, nil, nil, 100, 100, 100) + tx, _ = txs.NewCallTx(blockCache, user[2].PubKey, nil, nil, 100, 100, 100) tx.Sign(chainID, user[2]) if err := ExecTx(blockCache, tx, true, nil); err == nil { t.Fatal("Expected error") @@ -321,7 +321,7 @@ func TestSendPermission(t *testing.T) { blockCache := NewBlockCache(st) // A single input, having the permission, should succeed - tx := types.NewSendTx() + tx := txs.NewSendTx() if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil { t.Fatal(err) } @@ -332,7 +332,7 @@ func TestSendPermission(t *testing.T) { } // Two inputs, one with permission, one without, should fail - tx = types.NewSendTx() + tx = txs.NewSendTx() if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil { t.Fatal(err) } @@ -373,7 +373,7 @@ func TestCallPermission(t *testing.T) { st.UpdateAccount(simpleAcc) // A single input, having the permission, should succeed - tx, _ := types.NewCallTx(blockCache, user[0].PubKey, simpleContractAddr, nil, 100, 100, 100) + tx, _ := txs.NewCallTx(blockCache, user[0].PubKey, simpleContractAddr, nil, 100, 100, 100) tx.Sign(chainID, user[0]) if err := ExecTx(blockCache, tx, true, nil); err != nil { t.Fatal("Transaction failed", err) @@ -397,11 +397,11 @@ func TestCallPermission(t *testing.T) { blockCache.UpdateAccount(caller1Acc) // A single input, having the permission, but the contract doesn't have permission - tx, _ = types.NewCallTx(blockCache, user[0].PubKey, caller1ContractAddr, nil, 100, 10000, 100) + tx, _ = txs.NewCallTx(blockCache, user[0].PubKey, caller1ContractAddr, nil, 100, 10000, 100) tx.Sign(chainID, user[0]) // we need to subscribe to the Call event to detect the exception - _, exception := execTxWaitEvent(t, blockCache, tx, types.EventStringAccCall(caller1ContractAddr)) // + _, exception := execTxWaitEvent(t, blockCache, tx, txs.EventStringAccCall(caller1ContractAddr)) // if exception == "" { t.Fatal("Expected exception") } @@ -413,11 +413,11 @@ func TestCallPermission(t *testing.T) { // A single input, having the permission, and the contract has permission caller1Acc.Permissions.Base.Set(ptypes.Call, true) blockCache.UpdateAccount(caller1Acc) - tx, _ = types.NewCallTx(blockCache, user[0].PubKey, caller1ContractAddr, nil, 100, 10000, 100) + tx, _ = txs.NewCallTx(blockCache, user[0].PubKey, caller1ContractAddr, nil, 100, 10000, 100) tx.Sign(chainID, user[0]) // we need to subscribe to the Call event to detect the exception - _, exception = execTxWaitEvent(t, blockCache, tx, types.EventStringAccCall(caller1ContractAddr)) // + _, exception = execTxWaitEvent(t, blockCache, tx, txs.EventStringAccCall(caller1ContractAddr)) // if exception != "" { t.Fatal("Unexpected exception:", exception) } @@ -443,11 +443,11 @@ func TestCallPermission(t *testing.T) { blockCache.UpdateAccount(caller1Acc) blockCache.UpdateAccount(caller2Acc) - tx, _ = types.NewCallTx(blockCache, user[0].PubKey, caller2ContractAddr, nil, 100, 10000, 100) + tx, _ = txs.NewCallTx(blockCache, user[0].PubKey, caller2ContractAddr, nil, 100, 10000, 100) tx.Sign(chainID, user[0]) // we need to subscribe to the Call event to detect the exception - _, exception = execTxWaitEvent(t, blockCache, tx, types.EventStringAccCall(caller1ContractAddr)) // + _, exception = execTxWaitEvent(t, blockCache, tx, txs.EventStringAccCall(caller1ContractAddr)) // if exception == "" { t.Fatal("Expected exception") } @@ -461,11 +461,11 @@ func TestCallPermission(t *testing.T) { caller1Acc.Permissions.Base.Set(ptypes.Call, true) blockCache.UpdateAccount(caller1Acc) - tx, _ = types.NewCallTx(blockCache, user[0].PubKey, caller2ContractAddr, nil, 100, 10000, 100) + tx, _ = txs.NewCallTx(blockCache, user[0].PubKey, caller2ContractAddr, nil, 100, 10000, 100) tx.Sign(chainID, user[0]) // we need to subscribe to the Call event to detect the exception - _, exception = execTxWaitEvent(t, blockCache, tx, types.EventStringAccCall(caller1ContractAddr)) // + _, exception = execTxWaitEvent(t, blockCache, tx, txs.EventStringAccCall(caller1ContractAddr)) // if exception != "" { t.Fatal("Unexpected exception", exception) } @@ -487,7 +487,7 @@ func TestCreatePermission(t *testing.T) { createCode := wrapContractForCreate(contractCode) // A single input, having the permission, should succeed - tx, _ := types.NewCallTx(blockCache, user[0].PubKey, nil, createCode, 100, 100, 100) + tx, _ := txs.NewCallTx(blockCache, user[0].PubKey, nil, createCode, 100, 100, 100) tx.Sign(chainID, user[0]) if err := ExecTx(blockCache, tx, true, nil); err != nil { t.Fatal("Transaction failed", err) @@ -512,7 +512,7 @@ func TestCreatePermission(t *testing.T) { createFactoryCode := wrapContractForCreate(factoryCode) // A single input, having the permission, should succeed - tx, _ = types.NewCallTx(blockCache, user[0].PubKey, nil, createFactoryCode, 100, 100, 100) + tx, _ = txs.NewCallTx(blockCache, user[0].PubKey, nil, createFactoryCode, 100, 100, 100) tx.Sign(chainID, user[0]) if err := ExecTx(blockCache, tx, true, nil); err != nil { t.Fatal("Transaction failed", err) @@ -532,10 +532,10 @@ func TestCreatePermission(t *testing.T) { fmt.Println("\n###### CALL THE FACTORY (FAIL)") // A single input, having the permission, should succeed - tx, _ = types.NewCallTx(blockCache, user[0].PubKey, contractAddr, createCode, 100, 100, 100) + tx, _ = txs.NewCallTx(blockCache, user[0].PubKey, contractAddr, createCode, 100, 100, 100) tx.Sign(chainID, user[0]) // we need to subscribe to the Call event to detect the exception - _, exception := execTxWaitEvent(t, blockCache, tx, types.EventStringAccCall(contractAddr)) // + _, exception := execTxWaitEvent(t, blockCache, tx, txs.EventStringAccCall(contractAddr)) // if exception == "" { t.Fatal("expected exception") } @@ -548,10 +548,10 @@ func TestCreatePermission(t *testing.T) { blockCache.UpdateAccount(contractAcc) // A single input, having the permission, should succeed - tx, _ = types.NewCallTx(blockCache, user[0].PubKey, contractAddr, createCode, 100, 100, 100) + tx, _ = txs.NewCallTx(blockCache, user[0].PubKey, contractAddr, createCode, 100, 100, 100) tx.Sign(chainID, user[0]) // we need to subscribe to the Call event to detect the exception - _, exception = execTxWaitEvent(t, blockCache, tx, types.EventStringAccCall(contractAddr)) // + _, exception = execTxWaitEvent(t, blockCache, tx, txs.EventStringAccCall(contractAddr)) // if exception != "" { t.Fatal("unexpected exception", exception) } @@ -575,10 +575,10 @@ func TestCreatePermission(t *testing.T) { blockCache.UpdateAccount(contractAcc) // this should call the 0 address but not create ... - tx, _ = types.NewCallTx(blockCache, user[0].PubKey, contractAddr, createCode, 100, 10000, 100) + tx, _ = txs.NewCallTx(blockCache, user[0].PubKey, contractAddr, createCode, 100, 10000, 100) tx.Sign(chainID, user[0]) // we need to subscribe to the Call event to detect the exception - _, exception = execTxWaitEvent(t, blockCache, tx, types.EventStringAccCall(zeroAddr)) // + _, exception = execTxWaitEvent(t, blockCache, tx, txs.EventStringAccCall(zeroAddr)) // if exception != "" { t.Fatal("unexpected exception", exception) } @@ -598,7 +598,7 @@ func TestBondPermission(t *testing.T) { //------------------------------ // one bonder without permission should fail - tx, _ := types.NewBondTx(user[1].PubKey) + tx, _ := txs.NewBondTx(user[1].PubKey) if err := tx.AddInput(blockCache, user[1].PubKey, 5); err != nil { t.Fatal(err) } @@ -629,7 +629,7 @@ func TestBondPermission(t *testing.T) { blockCache.UpdateAccount(bondAcc) //------------------------------ // one bonder with permission and an input without send should fail - tx, _ = types.NewBondTx(user[1].PubKey) + tx, _ = txs.NewBondTx(user[1].PubKey) if err := tx.AddInput(blockCache, user[2].PubKey, 5); err != nil { t.Fatal(err) } @@ -654,7 +654,7 @@ func TestBondPermission(t *testing.T) { sendAcc := blockCache.GetAccount(user[2].Address) sendAcc.Permissions.Base.Set(ptypes.Send, true) blockCache.UpdateAccount(sendAcc) - tx, _ = types.NewBondTx(user[1].PubKey) + tx, _ = txs.NewBondTx(user[1].PubKey) if err := tx.AddInput(blockCache, user[2].PubKey, 5); err != nil { t.Fatal(err) } @@ -676,7 +676,7 @@ func TestBondPermission(t *testing.T) { // one bonder with permission and an input with bond should pass sendAcc.Permissions.Base.Set(ptypes.Bond, true) blockCache.UpdateAccount(sendAcc) - tx, _ = types.NewBondTx(user[1].PubKey) + tx, _ = txs.NewBondTx(user[1].PubKey) if err := tx.AddInput(blockCache, user[2].PubKey, 5); err != nil { t.Fatal(err) } @@ -696,7 +696,7 @@ func TestBondPermission(t *testing.T) { blockCache.UpdateAccount(bondAcc) //------------------------------ // one bonder with permission and an input from that bonder and an input without send or bond should fail - tx, _ = types.NewBondTx(user[1].PubKey) + tx, _ = txs.NewBondTx(user[1].PubKey) if err := tx.AddInput(blockCache, user[1].PubKey, 5); err != nil { t.Fatal(err) } @@ -726,7 +726,7 @@ func TestCreateAccountPermission(t *testing.T) { // SendTx to unknown account // A single input, having the permission, should succeed - tx := types.NewSendTx() + tx := txs.NewSendTx() if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil { t.Fatal(err) } @@ -737,7 +737,7 @@ func TestCreateAccountPermission(t *testing.T) { } // Two inputs, both with send, one with create, one without, should fail - tx = types.NewSendTx() + tx = txs.NewSendTx() if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil { t.Fatal(err) } @@ -754,7 +754,7 @@ func TestCreateAccountPermission(t *testing.T) { } // Two inputs, both with send, one with create, one without, two ouputs (one known, one unknown) should fail - tx = types.NewSendTx() + tx = txs.NewSendTx() if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil { t.Fatal(err) } @@ -775,7 +775,7 @@ func TestCreateAccountPermission(t *testing.T) { acc := blockCache.GetAccount(user[1].Address) acc.Permissions.Base.Set(ptypes.CreateAccount, true) blockCache.UpdateAccount(acc) - tx = types.NewSendTx() + tx = txs.NewSendTx() if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil { t.Fatal(err) } @@ -790,7 +790,7 @@ func TestCreateAccountPermission(t *testing.T) { } // Two inputs, both with send, both with create, two outputs (one known, one unknown) should pass - tx = types.NewSendTx() + tx = txs.NewSendTx() if err := tx.AddInput(blockCache, user[0].PubKey, 5); err != nil { t.Fatal(err) } @@ -827,11 +827,11 @@ func TestCreateAccountPermission(t *testing.T) { blockCache.UpdateAccount(caller1Acc) // A single input, having the permission, but the contract doesn't have permission - txCall, _ := types.NewCallTx(blockCache, user[0].PubKey, caller1ContractAddr, nil, 100, 10000, 100) + txCall, _ := txs.NewCallTx(blockCache, user[0].PubKey, caller1ContractAddr, nil, 100, 10000, 100) txCall.Sign(chainID, user[0]) // we need to subscribe to the Call event to detect the exception - _, exception := execTxWaitEvent(t, blockCache, txCall, types.EventStringAccCall(caller1ContractAddr)) // + _, exception := execTxWaitEvent(t, blockCache, txCall, txs.EventStringAccCall(caller1ContractAddr)) // if exception == "" { t.Fatal("Expected exception") } @@ -842,11 +842,11 @@ func TestCreateAccountPermission(t *testing.T) { caller1Acc.Permissions.Base.Set(ptypes.Call, true) blockCache.UpdateAccount(caller1Acc) // A single input, having the permission, but the contract doesn't have permission - txCall, _ = types.NewCallTx(blockCache, user[0].PubKey, caller1ContractAddr, nil, 100, 10000, 100) + txCall, _ = txs.NewCallTx(blockCache, user[0].PubKey, caller1ContractAddr, nil, 100, 10000, 100) txCall.Sign(chainID, user[0]) // we need to subscribe to the Call event to detect the exception - _, exception = execTxWaitEvent(t, blockCache, txCall, types.EventStringAccCall(caller1ContractAddr)) // + _, exception = execTxWaitEvent(t, blockCache, txCall, txs.EventStringAccCall(caller1ContractAddr)) // if exception != "" { t.Fatal("Unexpected exception", exception) } @@ -1067,7 +1067,7 @@ var ExceptionTimeOut = "timed out waiting for event" // run ExecTx and wait for the Call event on given addr // returns the msg data and an error/exception -func execTxWaitEvent(t *testing.T, blockCache *BlockCache, tx types.Tx, eventid string) (interface{}, string) { +func execTxWaitEvent(t *testing.T, blockCache *BlockCache, tx txs.Tx, eventid string) (interface{}, string) { evsw := events.NewEventSwitch() evsw.Start() ch := make(chan interface{}) @@ -1090,9 +1090,9 @@ func execTxWaitEvent(t *testing.T, blockCache *BlockCache, tx types.Tx, eventid } switch ev := msg.(type) { - case types.EventDataTx: + case txs.EventDataTx: return ev, ev.Exception - case types.EventDataCall: + case txs.EventDataCall: return ev, ev.Exception case string: return nil, ev @@ -1120,10 +1120,10 @@ func testSNativeCALL(t *testing.T, expectPass bool, blockCache *BlockCache, doug doug.Code = contractCode blockCache.UpdateAccount(doug) addr = doug.Address - tx, _ := types.NewCallTx(blockCache, user[0].PubKey, addr, data, 100, 10000, 100) + tx, _ := txs.NewCallTx(blockCache, user[0].PubKey, addr, data, 100, 10000, 100) tx.Sign(chainID, user[0]) - fmt.Println("subscribing to", types.EventStringAccCall(snativeAddress)) - ev, exception := execTxWaitEvent(t, blockCache, tx, types.EventStringAccCall(snativeAddress)) + fmt.Println("subscribing to", txs.EventStringAccCall(snativeAddress)) + ev, exception := execTxWaitEvent(t, blockCache, tx, txs.EventStringAccCall(snativeAddress)) if exception == ExceptionTimeOut { t.Fatal("Timed out waiting for event") } @@ -1131,7 +1131,7 @@ func testSNativeCALL(t *testing.T, expectPass bool, blockCache *BlockCache, doug if exception != "" { t.Fatal("Unexpected exception", exception) } - evv := ev.(types.EventDataCall) + evv := ev.(txs.EventDataCall) ret := evv.Return if err := f(ret); err != nil { t.Fatal(err) @@ -1157,7 +1157,7 @@ func testSNativeTx(t *testing.T, expectPass bool, blockCache *BlockCache, perm p acc.Permissions.Base.Set(perm, true) blockCache.UpdateAccount(acc) } - tx, _ := types.NewPermissionsTx(blockCache, user[0].PubKey, snativeArgs) + tx, _ := txs.NewPermissionsTx(blockCache, user[0].PubKey, snativeArgs) tx.Sign(chainID, user[0]) err := ExecTx(blockCache, tx, true, nil) if expectPass { diff --git a/state/state.go b/state/state.go index 72d7e15fb4b4c8686ac4d7ebbca7254f2c3a7d39..aea7f949539bff8f3987b3dd1f316d5d4e7fe090 100644 --- a/state/state.go +++ b/state/state.go @@ -496,11 +496,3 @@ func MakeGenesisState(db dbm.DB, genDoc *GenesisDoc) *State { nameReg: nameReg, } } - -func RandGenesisState(numAccounts int, randBalance bool, minBalance int64, numValidators int, randBonded bool, minBonded int64) (*State, []*acm.PrivAccount, []*types.PrivValidator) { - db := dbm.NewMemDB() - genDoc, privAccounts, privValidators := RandGenesisDoc(numAccounts, randBalance, minBalance, numValidators, randBonded, minBonded) - s0 := MakeGenesisState(db, genDoc) - s0.Save() - return s0, privAccounts, privValidators -} diff --git a/state/state_test.go b/state/state_test.go index b35e5bee336f96e15659497ce85320b7798ff13b..eba2226bba2854d62851fea37896fb5648811b74 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -15,7 +15,7 @@ func init() { tendermint_test.ResetConfig("state_test") } -func execTxWithState(state *State, tx types.Tx, runCall bool) error { +func execTxWithState(state *State, tx txs.Tx, runCall bool) error { cache := NewBlockCache(state) if err := ExecTx(cache, tx, runCall, nil); err != nil { return err @@ -25,7 +25,7 @@ func execTxWithState(state *State, tx types.Tx, runCall bool) error { } } -func execTxWithStateNewBlock(state *State, tx types.Tx, runCall bool) error { +func execTxWithStateNewBlock(state *State, tx txs.Tx, runCall bool) error { if err := execTxWithState(state, tx, runCall); err != nil { return err } @@ -76,7 +76,7 @@ func TestCopyState(t *testing.T) { } /* -func makeBlock(t *testing.T, state *State, validation *tmtypes.Commit, txs []types.Tx) *tmtypes.Block { +func makeBlock(t *testing.T, state *State, validation *tmtypes.Commit, txs []txs.Tx) *tmtypes.Block { if validation == nil { validation = &tmtypes.Commit{} } @@ -186,7 +186,7 @@ func TestTxSequence(t *testing.T) { // The tx should only pass when i == 1. for i := -1; i < 3; i++ { sequence := acc0.Sequence + i - tx := types.NewSendTx() + tx := txs.NewSendTx() tx.AddInputWithNonce(acc0PubKey, 1, sequence) tx.AddOutput(acc1.Address, 1) tx.Inputs[0].Signature = privAccounts[0].Sign(state.ChainID, tx) @@ -221,7 +221,7 @@ func TestTxSequence(t *testing.T) { func TestNameTxs(t *testing.T) { state, privAccounts, _ := RandGenesisState(3, true, 1000, 1, true, 1000) - types.MinNameRegistrationPeriod = 5 + txs.MinNameRegistrationPeriod = 5 startingBlock := state.LastBlockHeight // try some bad names. these should all fail @@ -230,8 +230,8 @@ func TestNameTxs(t *testing.T) { fee := int64(1000) numDesiredBlocks := 5 for _, name := range names { - amt := fee + int64(numDesiredBlocks)*types.NameByteCostMultiplier*types.NameBlockCostMultiplier*types.NameBaseCost(name, data) - tx, _ := types.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) + amt := fee + int64(numDesiredBlocks)*txs.NameByteCostMultiplier*txs.NameBlockCostMultiplier*txs.NameBaseCost(name, data) + tx, _ := txs.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[0]) if err := execTxWithState(state, tx, true); err == nil { @@ -243,8 +243,8 @@ func TestNameTxs(t *testing.T) { name := "hold_it_chum" datas := []string{"cold&warm", "!@#$%^&*()", "<<<>>>>", "because why would you ever need a ~ or a & or even a % in a json file? make your case and we'll talk"} for _, data := range datas { - amt := fee + int64(numDesiredBlocks)*types.NameByteCostMultiplier*types.NameBlockCostMultiplier*types.NameBaseCost(name, data) - tx, _ := types.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) + amt := fee + int64(numDesiredBlocks)*txs.NameByteCostMultiplier*txs.NameBlockCostMultiplier*txs.NameBaseCost(name, data) + tx, _ := txs.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[0]) if err := execTxWithState(state, tx, true); err == nil { @@ -252,7 +252,7 @@ func TestNameTxs(t *testing.T) { } } - validateEntry := func(t *testing.T, entry *types.NameRegEntry, name, data string, addr []byte, expires int) { + validateEntry := func(t *testing.T, entry *txs.NameRegEntry, name, data string, addr []byte, expires int) { if entry == nil { t.Fatalf("Could not find name %s", name) @@ -274,8 +274,8 @@ func TestNameTxs(t *testing.T) { // try a good one, check data, owner, expiry name = "@looking_good/karaoke_bar.broadband" data = "on this side of neptune there are 1234567890 people: first is OMNIVORE+-3. Or is it. Ok this is pretty restrictive. No exclamations :(. Faces tho :')" - amt := fee + int64(numDesiredBlocks)*types.NameByteCostMultiplier*types.NameBlockCostMultiplier*types.NameBaseCost(name, data) - tx, _ := types.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) + amt := fee + int64(numDesiredBlocks)*txs.NameByteCostMultiplier*txs.NameBlockCostMultiplier*txs.NameBaseCost(name, data) + tx, _ := txs.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[0]) if err := execTxWithState(state, tx, true); err != nil { t.Fatal(err) @@ -284,7 +284,7 @@ func TestNameTxs(t *testing.T) { validateEntry(t, entry, name, data, privAccounts[0].Address, startingBlock+numDesiredBlocks) // fail to update it as non-owner, in same block - tx, _ = types.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) + tx, _ = txs.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[1]) if err := execTxWithState(state, tx, true); err == nil { t.Fatal("Expected error") @@ -292,7 +292,7 @@ func TestNameTxs(t *testing.T) { // update it as owner, just to increase expiry, in same block // NOTE: we have to resend the data or it will clear it (is this what we want?) - tx, _ = types.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) + tx, _ = txs.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[0]) if err := execTxWithStateNewBlock(state, tx, true); err != nil { t.Fatal(err) @@ -301,7 +301,7 @@ func TestNameTxs(t *testing.T) { validateEntry(t, entry, name, data, privAccounts[0].Address, startingBlock+numDesiredBlocks*2) // update it as owner, just to increase expiry, in next block - tx, _ = types.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) + tx, _ = txs.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[0]) if err := execTxWithStateNewBlock(state, tx, true); err != nil { t.Fatal(err) @@ -311,7 +311,7 @@ func TestNameTxs(t *testing.T) { // fail to update it as non-owner state.LastBlockHeight = entry.Expires - 1 - tx, _ = types.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) + tx, _ = txs.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[1]) if err := execTxWithState(state, tx, true); err == nil { t.Fatal("Expected error") @@ -319,7 +319,7 @@ func TestNameTxs(t *testing.T) { // once expires, non-owner succeeds state.LastBlockHeight = entry.Expires - tx, _ = types.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) + tx, _ = txs.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[1]) if err := execTxWithState(state, tx, true); err != nil { t.Fatal(err) @@ -331,8 +331,8 @@ func TestNameTxs(t *testing.T) { data = "In the beginning there was no thing, not even the beginning. It hadn't been here, no there, nor for that matter anywhere, not especially because it had not to even exist, let alone to not. Nothing especially odd about that." oldCredit := amt - fee numDesiredBlocks = 10 - amt = fee + (int64(numDesiredBlocks)*types.NameByteCostMultiplier*types.NameBlockCostMultiplier*types.NameBaseCost(name, data) - oldCredit) - tx, _ = types.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) + amt = fee + (int64(numDesiredBlocks)*txs.NameByteCostMultiplier*txs.NameBlockCostMultiplier*txs.NameBaseCost(name, data) - oldCredit) + tx, _ = txs.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[1]) if err := execTxWithState(state, tx, true); err != nil { t.Fatal(err) @@ -343,7 +343,7 @@ func TestNameTxs(t *testing.T) { // test removal amt = fee data = "" - tx, _ = types.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) + tx, _ = txs.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[1]) if err := execTxWithStateNewBlock(state, tx, true); err != nil { t.Fatal(err) @@ -357,8 +357,8 @@ func TestNameTxs(t *testing.T) { // test removal by key1 after expiry name = "looking_good/karaoke_bar" data = "some data" - amt = fee + int64(numDesiredBlocks)*types.NameByteCostMultiplier*types.NameBlockCostMultiplier*types.NameBaseCost(name, data) - tx, _ = types.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) + amt = fee + int64(numDesiredBlocks)*txs.NameByteCostMultiplier*txs.NameBlockCostMultiplier*txs.NameBaseCost(name, data) + tx, _ = txs.NewNameTx(state, privAccounts[0].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[0]) if err := execTxWithState(state, tx, true); err != nil { t.Fatal(err) @@ -369,7 +369,7 @@ func TestNameTxs(t *testing.T) { amt = fee data = "" - tx, _ = types.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) + tx, _ = txs.NewNameTx(state, privAccounts[1].PubKey, name, data, amt, fee) tx.Sign(state.ChainID, privAccounts[1]) if err := execTxWithStateNewBlock(state, tx, true); err != nil { t.Fatal(err) @@ -394,17 +394,17 @@ func TestTxs(t *testing.T) { // SendTx. { state := state.Copy() - tx := &types.SendTx{ - Inputs: []*types.TxInput{ - &types.TxInput{ + tx := &txs.SendTx{ + Inputs: []*txs.TxInput{ + &txs.TxInput{ Address: acc0.Address, Amount: 1, Sequence: acc0.Sequence + 1, PubKey: acc0PubKey, }, }, - Outputs: []*types.TxOutput{ - &types.TxOutput{ + Outputs: []*txs.TxOutput{ + &txs.TxOutput{ Address: acc1.Address, Amount: 1, }, @@ -434,8 +434,8 @@ func TestTxs(t *testing.T) { newAcc1 := state.GetAccount(acc1.Address) newAcc1.Code = []byte{0x60} state.UpdateAccount(newAcc1) - tx := &types.CallTx{ - Input: &types.TxInput{ + tx := &txs.CallTx{ + Input: &txs.TxInput{ Address: acc0.Address, Amount: 1, Sequence: acc0.Sequence + 1, @@ -483,8 +483,8 @@ proof-of-work chain as proof of what happened while they were gone ` entryAmount := int64(10000) state := state.Copy() - tx := &types.NameTx{ - Input: &types.TxInput{ + tx := &txs.NameTx{ + Input: &txs.TxInput{ Address: acc0.Address, Amount: entryAmount, Sequence: acc0.Sequence + 1, @@ -517,7 +517,7 @@ proof-of-work chain as proof of what happened while they were gone ` tx.Input.Sequence += 1 tx.Input.Signature = privAccounts[0].Sign(state.ChainID, tx) err = execTxWithState(state, tx, true) - if _, ok := err.(types.ErrTxInvalidString); !ok { + if _, ok := err.(txs.ErrTxInvalidString); !ok { t.Errorf("Expected invalid string error. Got: %s", err.Error()) } } @@ -526,18 +526,18 @@ proof-of-work chain as proof of what happened while they were gone ` /* { state := state.Copy() - tx := &types.BondTx{ + tx := &txs.BondTx{ PubKey: acc0PubKey.(crypto.PubKeyEd25519), - Inputs: []*types.TxInput{ - &types.TxInput{ + Inputs: []*txs.TxInput{ + &txs.TxInput{ Address: acc0.Address, Amount: 1, Sequence: acc0.Sequence + 1, PubKey: acc0PubKey, }, }, - UnbondTo: []*types.TxOutput{ - &types.TxOutput{ + UnbondTo: []*txs.TxOutput{ + &txs.TxOutput{ Address: acc0.Address, Amount: 1, }, @@ -596,7 +596,7 @@ func TestSuicide(t *testing.T) { state.UpdateAccount(newAcc1) // send call tx with no data, cause suicide - tx := types.NewCallTxWithNonce(acc0PubKey, acc1.Address, nil, sendingAmount, 1000, 0, acc0.Sequence+1) + tx := txs.NewCallTxWithNonce(acc0PubKey, acc1.Address, nil, sendingAmount, 1000, 0, acc0.Sequence+1) tx.Input.Signature = privAccounts[0].Sign(state.ChainID, tx) // we use cache instead of execTxWithState so we can run the tx twice @@ -638,18 +638,18 @@ func TestAddValidator(t *testing.T) { // The first privAccount will become a validator acc0 := privAccounts[0] - bondTx := &types.BondTx{ + bondTx := &txs.BondTx{ PubKey: acc0.PubKey.(account.PubKeyEd25519), - Inputs: []*types.TxInput{ - &types.TxInput{ + Inputs: []*txs.TxInput{ + &txs.TxInput{ Address: acc0.Address, Amount: 1000, Sequence: 1, PubKey: acc0.PubKey, }, }, - UnbondTo: []*types.TxOutput{ - &types.TxOutput{ + UnbondTo: []*txs.TxOutput{ + &txs.TxOutput{ Address: acc0.Address, Amount: 1000, }, @@ -659,7 +659,7 @@ func TestAddValidator(t *testing.T) { bondTx.Inputs[0].Signature = acc0.Sign(s0.ChainID, bondTx) // Make complete block and blockParts - block0 := makeBlock(t, s0, nil, []types.Tx{bondTx}) + block0 := makeBlock(t, s0, nil, []txs.Tx{bondTx}) block0Parts := block0.MakePartSet() // Sanity check @@ -683,18 +683,18 @@ func TestAddValidator(t *testing.T) { // The validation for the next block should only require 1 signature // (the new validator wasn't active for block0) - precommit0 := &types.Vote{ + precommit0 := &txs.Vote{ Height: 1, Round: 0, - Type: types.VoteTypePrecommit, + Type: txs.VoteTypePrecommit, BlockHash: block0.Hash(), BlockPartsHeader: block0Parts.Header(), } privValidators[0].SignVote(s0.ChainID, precommit0) block1 := makeBlock(t, s0, - &types.Validation{ - Precommits: []*types.Vote{ + &txs.Validation{ + Precommits: []*txs.Vote{ precommit0, }, }, nil, diff --git a/state/tx_cache.go b/state/tx_cache.go index 0bc4a8013aae3a24d58dd4eb0e4101ab8f205d12..292c35314966cbb450e45d0dd55da500462da673 100644 --- a/state/tx_cache.go +++ b/state/tx_cache.go @@ -142,7 +142,7 @@ func (cache *TxCache) Sync() { // Convenience function to return address of new contract func NewContractAddress(caller []byte, nonce int) []byte { - return types.NewContractAddress(caller, nonce) + return txs.NewContractAddress(caller, nonce) } // Converts backend.Account to vm.Account struct. diff --git a/state/types/genesis.go b/state/types/genesis.go index ad174464307ca80fb2b690ffc352458a5132d9c2..806d701b29b2ce0daf3e9f5d99862917e7f8b5db 100644 --- a/state/types/genesis.go +++ b/state/types/genesis.go @@ -1,7 +1,6 @@ package types import ( - "sort" "time" ptypes "github.com/eris-ltd/eris-db/permission/types" @@ -60,61 +59,3 @@ func GenesisDocFromJSON(jsonBlob []byte) (genState *GenesisDoc) { } return } - -//------------------------------------------------------------ -// Make random genesis state - -func RandAccount(randBalance bool, minBalance int64) (*acm.Account, *acm.PrivAccount) { - privAccount := acm.GenPrivAccount() - perms := ptypes.DefaultAccountPermissions - acc := &acm.Account{ - Address: privAccount.PubKey.Address(), - PubKey: privAccount.PubKey, - Sequence: RandInt(), - Balance: minBalance, - Permissions: perms, - } - if randBalance { - acc.Balance += int64(RandUint32()) - } - return acc, privAccount -} - -func RandGenesisDoc(numAccounts int, randBalance bool, minBalance int64, numValidators int, randBonded bool, minBonded int64) (*GenesisDoc, []*acm.PrivAccount, []*types.PrivValidator) { - accounts := make([]GenesisAccount, numAccounts) - privAccounts := make([]*acm.PrivAccount, numAccounts) - defaultPerms := ptypes.DefaultAccountPermissions - for i := 0; i < numAccounts; i++ { - account, privAccount := RandAccount(randBalance, minBalance) - accounts[i] = GenesisAccount{ - Address: account.Address, - Amount: account.Balance, - Permissions: &defaultPerms, // This will get copied into each state.Account. - } - privAccounts[i] = privAccount - } - validators := make([]GenesisValidator, numValidators) - privValidators := make([]*types.PrivValidator, numValidators) - for i := 0; i < numValidators; i++ { - valInfo, _, privVal := types.RandValidator(randBonded, minBonded) - validators[i] = GenesisValidator{ - PubKey: valInfo.PubKey, - Amount: valInfo.FirstBondAmount, - UnbondTo: []BasicAccount{ - { - Address: valInfo.PubKey.Address(), - Amount: valInfo.FirstBondAmount, - }, - }, - } - privValidators[i] = privVal - } - sort.Sort(types.PrivValidatorsByAddress(privValidators)) - return &GenesisDoc{ - GenesisTime: time.Now(), - ChainID: "tendermint_test", - Accounts: accounts, - Validators: validators, - }, privAccounts, privValidators - -} diff --git a/test/mock/mock_web_api_test.go b/test/mock/mock_web_api_test.go index 324bc1c8ea759dac9f8eec5769d9901cb5f39de3..a621833db95d13571218c9dafab192debc428004 100644 --- a/test/mock/mock_web_api_test.go +++ b/test/mock/mock_web_api_test.go @@ -11,6 +11,7 @@ import ( // edb "github.com/eris-ltd/erisdb/erisdb" "github.com/eris-ltd/eris-db/account" + "github.com/eris-ltd/eris-db/config" edb "github.com/eris-ltd/eris-db/erisdb" ep "github.com/eris-ltd/eris-db/erisdb/pipe" "github.com/eris-ltd/eris-db/rpc" @@ -50,10 +51,10 @@ func (this *MockSuite) SetupSuite() { evtSubs := edb.NewEventSubscriptions(pipe.Events()) // The server restServer := edb.NewRestServer(codec, pipe, evtSubs) - sConf := server.DefaultServerConfig() + sConf := config.DefaultServerConfig() sConf.Bind.Port = 31402 // Create a server process. - proc := server.NewServeProcess(sConf, restServer) + proc := server.NewServeProcess(&sConf, restServer) err := proc.Start() if err != nil { panic(err) @@ -173,7 +174,7 @@ func (this *MockSuite) TestGetValidators() { func (this *MockSuite) TestGetNameRegEntry() { resp := this.get("/namereg/" + this.testData.GetNameRegEntry.Input.Name) - ret := &types.NameRegEntry{} + ret := &txs.NameRegEntry{} errD := this.codec.Decode(ret, resp.Body) this.NoError(errD) this.Equal(ret, this.testData.GetNameRegEntry.Output) diff --git a/test/server/scumbag.go b/test/server/scumbag.go index 807206012dc390c919a5c88dd26c64c7abb29d65..85851099ae83c99de111f71df8fc8fe3452a4e5a 100644 --- a/test/server/scumbag.go +++ b/test/server/scumbag.go @@ -2,12 +2,14 @@ package server import ( "encoding/json" - "github.com/gin-gonic/gin" - "github.com/tendermint/log15" - "github.com/eris-ltd/eris-db/rpc" - "github.com/eris-ltd/eris-db/server" "os" "runtime" + + "github.com/eris-ltd/eris-db/config" + "github.com/eris-ltd/eris-db/rpc" + "github.com/eris-ltd/eris-db/server" + "github.com/gin-gonic/gin" + "github.com/tendermint/log15" ) func init() { @@ -27,7 +29,7 @@ func NewScumbagServer() server.Server { return &ScumbagServer{} } -func (this *ScumbagServer) Start(sc *server.ServerConfig, g *gin.Engine) { +func (this *ScumbagServer) Start(sc *config.ServerConfig, g *gin.Engine) { g.GET("/scumbag", func(c *gin.Context) { c.String(200, "Scumbag") }) @@ -56,14 +58,14 @@ func NewScumsocketServer(maxConnections uint) *server.WebSocketServer { } func NewServeScumbag() *server.ServeProcess { - cfg := server.DefaultServerConfig() + cfg := config.DefaultServerConfig() cfg.Bind.Port = uint16(31400) - return server.NewServeProcess(cfg, NewScumbagServer()) + return server.NewServeProcess(&cfg, NewScumbagServer()) } func NewServeScumSocket(wsServer *server.WebSocketServer) *server.ServeProcess { - cfg := server.DefaultServerConfig() + cfg := config.DefaultServerConfig() cfg.WebSocket.WebSocketEndpoint = "/scumsocket" cfg.Bind.Port = uint16(31401) - return server.NewServeProcess(cfg, wsServer) + return server.NewServeProcess(&cfg, wsServer) } diff --git a/test/transacting/transacting_tes.go_ b/test/transacting/transacting_tes.go_ deleted file mode 100644 index 565ff3ab8420e0aa69ab776cf65bf836851fedcf..0000000000000000000000000000000000000000 --- a/test/transacting/transacting_tes.go_ +++ /dev/null @@ -1,139 +0,0 @@ -package transacting - -// Basic imports -import ( - "bytes" - "fmt" - "github.com/stretchr/testify/suite" - // "github.com/tendermint/tendermint/types" - edb "github.com/eris-ltd/eris-db/erisdb" - ess "github.com/eris-ltd/eris-db/erisdb/erisdbss" - // ep "github.com/eris-ltd/eris-db/erisdb/pipe" - "github.com/gin-gonic/gin" - "github.com/tendermint/log15" - "github.com/eris-ltd/eris-db/rpc" - "github.com/eris-ltd/eris-db/server" - td "github.com/eris-ltd/eris-db/test/testdata/testdata" - "io/ioutil" - "net/http" - "os" - "path" - "runtime" - "testing" -) - -func init() { - runtime.GOMAXPROCS(runtime.NumCPU()) - log15.Root().SetHandler(log15.LvlFilterHandler( - log15.LvlInfo, - log15.StreamHandler(os.Stdout, log15.TerminalFormat()), - )) - gin.SetMode(gin.ReleaseMode) -} - -const ( - TX_URL = "http://localhost:31405/server" - CONTRACT_CODE = "60606040525b33600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908302179055505b609480603e6000396000f30060606040523615600d57600d565b60685b6000600060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff169050805033600060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908302179055505b90565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f3" -) - -func getCreateInput(privKey [64]byte) *edb.TransactParam { - tp := &edb.TransactParam{} - tp.PrivKey = privKey[:] - tp.Address = nil - tp.Data = []byte(CONTRACT_CODE) - tp.GasLimit = 100000 - tp.Fee = 0 - return tp -} - -type TxSuite struct { - suite.Suite - baseDir string - serveProcess *server.ServeProcess - codec rpc.Codec - sUrl string - testData *td.TestData -} - -func (this *TxSuite) SetupSuite() { - baseDir := path.Join(os.TempDir(), "/.edbservers") - ss := ess.NewServerServer(baseDir) - cfg := server.DefaultServerConfig() - cfg.Bind.Port = uint16(31405) - proc := server.NewServeProcess(cfg, ss) - err := proc.Start() - if err != nil { - panic(err) - } - this.serveProcess = proc - testData := td.LoadTestData() - this.codec = edb.NewTCodec() - - requestData := &ess.RequestData{testData.ChainData.PrivValidator, testData.ChainData.Genesis, 30} - rBts, _ := this.codec.EncodeBytes(requestData) - resp, _ := http.Post(TX_URL, "application/json", bytes.NewBuffer(rBts)) - if resp.StatusCode != 200 { - bts, _ := ioutil.ReadAll(resp.Body) - fmt.Println("ERROR GETTING SS ADDRESS: " + string(bts)) - fmt.Printf("%v\n", resp) - panic(fmt.Errorf(string(bts))) - } - rd := &ess.ResponseData{} - err2 := this.codec.Decode(rd, resp.Body) - if err2 != nil { - panic(err2) - } - fmt.Println("Received Port: " + rd.Port) - this.sUrl = "http://localhost:" + rd.Port - fmt.Println("URL: " + this.sUrl) - this.testData = testData -} - -func (this *TxSuite) TearDownSuite() { - sec := this.serveProcess.StopEventChannel() - this.serveProcess.Stop(0) - <-sec -} - -// ********************************************* Tests ********************************************* - -// TODO less duplication. -func (this *TxSuite) Test_A0_Tx_Create() { - input := getCreateInput([64]byte(this.testData.ChainData.PrivValidator.PrivKey)) - resp := this.postJson("/unsafe/txpool?hold=true", input) - bts, err := ioutil.ReadAll(resp.Body) - if err != nil { - panic(err) - } else { - fmt.Printf("%s\n", string(bts)) - } - //ret := &types.EventMsgCall{} - // errD := this.codec.Decode(ret, resp.Body) - //this.NoError(errD) - //json, _ := this.codec.EncodeBytes(ret) - //fmt.Printf("%s\n", string(json)) -} - -// ********************************************* Utilities ********************************************* - -func (this *TxSuite) get(endpoint string) *http.Response { - resp, errG := http.Get(this.sUrl + endpoint) - this.NoError(errG) - this.Equal(200, resp.StatusCode) - return resp -} - -func (this *TxSuite) postJson(endpoint string, v interface{}) *http.Response { - bts, errE := this.codec.EncodeBytes(v) - this.NoError(errE) - resp, errP := http.Post(this.sUrl+endpoint, "application/json", bytes.NewBuffer(bts)) - this.NoError(errP) - this.Equal(200, resp.StatusCode) - return resp -} - -// ********************************************* Entrypoint ********************************************* - -func TestQuerySuite(t *testing.T) { - suite.Run(t, &TxSuite{}) -} diff --git a/test/web_api/query_test.go b/test/web_api/query_test.go index 883bdacbf4bb023b0d2c580b2d027f734036ccb1..1c094b2d0e4e8659066f2c1d8d1c0bb79017cf2f 100644 --- a/test/web_api/query_test.go +++ b/test/web_api/query_test.go @@ -4,18 +4,20 @@ package web_api import ( "bytes" "fmt" - "github.com/stretchr/testify/suite" + "io/ioutil" + "net/http" + "os" + "path" + "testing" + + "github.com/eris-ltd/eris-db/config" edb "github.com/eris-ltd/eris-db/erisdb" ess "github.com/eris-ltd/eris-db/erisdb/erisdbss" ep "github.com/eris-ltd/eris-db/erisdb/pipe" "github.com/eris-ltd/eris-db/rpc" "github.com/eris-ltd/eris-db/server" fd "github.com/eris-ltd/eris-db/test/testdata/filters" - "io/ioutil" - "net/http" - "os" - "path" - "testing" + "github.com/stretchr/testify/suite" ) const QS_URL = "http://localhost:31403/server" @@ -32,9 +34,9 @@ type QuerySuite struct { func (this *QuerySuite) SetupSuite() { baseDir := path.Join(os.TempDir(), "/.edbservers") ss := ess.NewServerServer(baseDir) - cfg := server.DefaultServerConfig() + cfg := config.DefaultServerConfig() cfg.Bind.Port = uint16(31403) - proc := server.NewServeProcess(cfg, ss) + proc := server.NewServeProcess(&cfg, ss) err := proc.Start() if err != nil { panic(err) diff --git a/test/web_api/web_api_test.go b/test/web_api/web_api_test.go index 3becfd0a2a42f36385cec0048d19525cd8b01f4e..c1eaf57c3ff7fbff65bd16b6faa6d0230dc747cc 100644 --- a/test/web_api/web_api_test.go +++ b/test/web_api/web_api_test.go @@ -6,7 +6,14 @@ import ( "encoding/hex" "fmt" // edb "github.com/eris-ltd/erisdb/erisdb" + "io/ioutil" + "net/http" + "os" + "path" + "testing" + "github.com/eris-ltd/eris-db/account" + "github.com/eris-ltd/eris-db/config" edb "github.com/eris-ltd/eris-db/erisdb" ess "github.com/eris-ltd/eris-db/erisdb/erisdbss" ep "github.com/eris-ltd/eris-db/erisdb/pipe" @@ -15,11 +22,6 @@ import ( td "github.com/eris-ltd/eris-db/test/testdata/testdata" "github.com/gin-gonic/gin" "github.com/stretchr/testify/suite" - "io/ioutil" - "net/http" - "os" - "path" - "testing" ) const WAPIS_URL = "http://localhost:31404/server" @@ -37,9 +39,9 @@ func (this *WebApiSuite) SetupSuite() { gin.SetMode(gin.ReleaseMode) baseDir := path.Join(os.TempDir(), "/.edbservers") ss := ess.NewServerServer(baseDir) - cfg := server.DefaultServerConfig() + cfg := config.DefaultServerConfig() cfg.Bind.Port = uint16(31404) - proc := server.NewServeProcess(cfg, ss) + proc := server.NewServeProcess(&cfg, ss) err := proc.Start() if err != nil { panic(err) diff --git a/txs/config.go b/txs/config.go index cb982879786196ca20c6e3c6eab16b1b1ecb76e9..aa5348960e43ae13ec57b31fd94f14939df67d00 100644 --- a/txs/config.go +++ b/txs/config.go @@ -1,4 +1,4 @@ -package types +package txs import ( cfg "github.com/tendermint/go-config" diff --git a/txs/events.go b/txs/events.go index edf7046c4b5e4ba7b54550206a0056b10c0082a2..14185c3a0cb7591a100feae2023df146aea8921c 100644 --- a/txs/events.go +++ b/txs/events.go @@ -1,4 +1,4 @@ -package types +package txs import ( "fmt" diff --git a/txs/log.go b/txs/log.go index dbe8a67821e8d2603e19e7ee716b2c61d80b0309..b967a58d0ef7d4701fc15f5ab3dfee1f046b15f5 100644 --- a/txs/log.go +++ b/txs/log.go @@ -1,4 +1,4 @@ -package types +package txs import ( "github.com/tendermint/go-logger" diff --git a/txs/names.go b/txs/names.go index 7c1701414b26d37705d759439d9ee0639df78453..ddaec87d36486bf47766f9cb3b8c98d99c886173 100644 --- a/txs/names.go +++ b/txs/names.go @@ -1,4 +1,4 @@ -package types +package txs import ( "regexp" diff --git a/txs/tx.go b/txs/tx.go index d43cf9449cf8b80ef1c63cb83b605899674af2a0..df51aaeef5d0850058a90b7a8d15633fda1812e2 100644 --- a/txs/tx.go +++ b/txs/tx.go @@ -1,4 +1,4 @@ -package types +package txs import ( "bytes" diff --git a/txs/tx_test.go b/txs/tx_test.go index 56b539e33fd51493713ae6692c5614f7ea04b006..01fd40dddf21dc39c71f24d4f2407bef15eaa34b 100644 --- a/txs/tx_test.go +++ b/txs/tx_test.go @@ -1,4 +1,4 @@ -package types +package txs import ( "testing" diff --git a/txs/tx_utils.go b/txs/tx_utils.go index f8ce376a96948ba2558ba8c5977f876a1bd31209..e697951091cfd0b0ce58c748b7e6bdb5c4aef5b9 100644 --- a/txs/tx_utils.go +++ b/txs/tx_utils.go @@ -1,4 +1,4 @@ -package types +package txs import ( "fmt"