From 0024667d37234420f6651bc6628795221be74786 Mon Sep 17 00:00:00 2001 From: Silas Davis <silas@monax.io> Date: Mon, 11 Jun 2018 22:48:02 +0100 Subject: [PATCH] Refactor execution (finally get rid of GOTO) Signed-off-by: Silas Davis <silas@monax.io> --- blockchain/blockchain.go | 10 +- client/websocket_client.go | 2 +- core/kernel.go | 4 +- event/emitter.go | 6 + execution/errors/errors.go | 8 + execution/execution.go | 1173 ++----------------- execution/execution_test.go | 156 ++- execution/executors/call.go | 246 ++++ execution/executors/name.go | 185 +++ execution/executors/permissions.go | 153 +++ execution/executors/send.go | 81 ++ execution/executors/shared.go | 250 ++++ execution/{ => names}/namereg.go | 2 +- execution/{ => names}/namereg_cache.go | 2 +- execution/{ => names}/namereg_cache_test.go | 2 +- execution/state.go | 16 +- execution/transactor.go | 6 +- rpc/filters/namereg.go | 10 +- rpc/result.go | 5 +- rpc/service.go | 15 +- rpc/tm/client/client.go | 4 +- rpc/tm/integration/shared.go | 4 +- rpc/tm/integration/websocket_helpers.go | 12 +- rpc/tm/methods.go | 4 +- rpc/v0/methods.go | 7 +- 25 files changed, 1126 insertions(+), 1237 deletions(-) create mode 100644 execution/executors/call.go create mode 100644 execution/executors/name.go create mode 100644 execution/executors/permissions.go create mode 100644 execution/executors/send.go create mode 100644 execution/executors/shared.go rename execution/{ => names}/namereg.go (98%) rename execution/{ => names}/namereg_cache.go (99%) rename execution/{ => names}/namereg_cache_test.go (98%) diff --git a/blockchain/blockchain.go b/blockchain/blockchain.go index ec125ea7..98e48b14 100644 --- a/blockchain/blockchain.go +++ b/blockchain/blockchain.go @@ -33,9 +33,7 @@ const DefaultValidatorsWindowSize = 10 var stateKey = []byte("BlockchainState") -type BlockchainInfo interface { - GenesisHash() []byte - GenesisDoc() genesis.GenesisDoc +type TipInfo interface { ChainID() string LastBlockHeight() uint64 LastBlockTime() time.Time @@ -43,6 +41,12 @@ type BlockchainInfo interface { AppHashAfterLastBlock() []byte } +type BlockchainInfo interface { + TipInfo + GenesisHash() []byte + GenesisDoc() genesis.GenesisDoc +} + type Root struct { genesisHash []byte genesisDoc genesis.GenesisDoc diff --git a/client/websocket_client.go b/client/websocket_client.go index b06b2fec..5d425344 100644 --- a/client/websocket_client.go +++ b/client/websocket_client.go @@ -171,7 +171,7 @@ func (burrowNodeWebsocketClient *burrowNodeWebsocketClient) WaitForConfirmation( continue } - if eventDataTx.Exception != nil { + if eventDataTx.Exception != nil && eventDataTx.Exception.Code != errors.ErrorCodeExecutionReverted { confirmationChannel <- Confirmation{ BlockHash: latestBlockHash, EventDataTx: eventDataTx, diff --git a/core/kernel.go b/core/kernel.go index eceaec85..18f52126 100644 --- a/core/kernel.go +++ b/core/kernel.go @@ -94,10 +94,10 @@ func NewKernel(ctx context.Context, keyClient keys.KeyClient, privValidator tm_t } tmGenesisDoc := tendermint.DeriveGenesisDoc(genesisDoc) - checker := execution.NewBatchChecker(state, tmGenesisDoc.ChainID, blockchain.Tip, logger) + checker := execution.NewBatchChecker(state, blockchain.Tip, logger) emitter := event.NewEmitter(logger) - committer := execution.NewBatchCommitter(state, tmGenesisDoc.ChainID, blockchain.Tip, emitter, logger, exeOptions...) + committer := execution.NewBatchCommitter(state, blockchain.Tip, emitter, logger, exeOptions...) tmNode, err := tendermint.NewNode(tmConf, privValidator, tmGenesisDoc, blockchain, checker, committer, tmLogger) if err != nil { diff --git a/event/emitter.go b/event/emitter.go index ec9f1e31..738104fd 100644 --- a/event/emitter.go +++ b/event/emitter.go @@ -42,6 +42,12 @@ type Publisher interface { Publish(ctx context.Context, message interface{}, tags map[string]interface{}) error } +type PublisherFunc func(ctx context.Context, message interface{}, tags map[string]interface{}) error + +func (pf PublisherFunc) Publish(ctx context.Context, message interface{}, tags map[string]interface{}) error { + return pf(ctx, message, tags) +} + type Emitter interface { Subscribable Publisher diff --git a/execution/errors/errors.go b/execution/errors/errors.go index 4f2e2ab8..20248d40 100644 --- a/execution/errors/errors.go +++ b/execution/errors/errors.go @@ -121,6 +121,14 @@ func ErrorCodef(errorCode ErrorCode, format string, a ...interface{}) CodedError return NewCodedError(errorCode, fmt.Sprintf(format, a...)) } +func (e *Exception) AsError() error { + // thanks go, you dick + if e == nil { + return nil + } + return e +} + func (e *Exception) ErrorCode() ErrorCode { return e.Code } diff --git a/execution/execution.go b/execution/execution.go index c97fd2fb..56d69d3b 100644 --- a/execution/execution.go +++ b/execution/execution.go @@ -25,27 +25,25 @@ import ( bcm "github.com/hyperledger/burrow/blockchain" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/execution/errors" - "github.com/hyperledger/burrow/execution/events" "github.com/hyperledger/burrow/execution/evm" + "github.com/hyperledger/burrow/execution/executors" "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" - "github.com/hyperledger/burrow/permission" - ptypes "github.com/hyperledger/burrow/permission/types" "github.com/hyperledger/burrow/txs" "github.com/hyperledger/burrow/txs/payload" ) -// TODO: make configurable -const GasLimit = uint64(1000000) +type Executor interface { + Execute(txEnv *txs.Envelope) error +} type BatchExecutor interface { // Provides access to write lock for a BatchExecutor so reads can be prevented for the duration of a commit sync.Locker state.Reader // Execute transaction against block cache (i.e. block buffer) - Execute(txEnv *txs.Envelope) error + Executor // Reset executor to underlying State Reset() error } @@ -60,55 +58,105 @@ type BatchCommitter interface { type executor struct { sync.RWMutex - chainID string - tip *bcm.Tip runCall bool state *State stateCache state.Cache - nameRegCache *NameRegCache - publisher event.Publisher + nameRegCache *names.NameRegCache eventCache *event.Cache logger *logging.Logger vmOptions []func(*evm.VM) + txExecutors map[payload.Type]Executor } var _ BatchExecutor = (*executor)(nil) // Wraps a cache of what is variously known as the 'check cache' and 'mempool' -func NewBatchChecker(backend *State, chainID string, tip *bcm.Tip, logger *logging.Logger, +func NewBatchChecker(backend *State, tip *bcm.Tip, logger *logging.Logger, options ...ExecutionOption) BatchExecutor { - return newExecutor("CheckCache", false, backend, chainID, tip, event.NewNoOpPublisher(), + return newExecutor("CheckCache", false, backend, tip, event.NewNoOpPublisher(), logger.WithScope("NewBatchExecutor"), options...) } -func NewBatchCommitter(backend *State, chainID string, tip *bcm.Tip, publisher event.Publisher, logger *logging.Logger, +func NewBatchCommitter(backend *State, tip *bcm.Tip, publisher event.Publisher, logger *logging.Logger, options ...ExecutionOption) BatchCommitter { - return newExecutor("CommitCache", true, backend, chainID, tip, publisher, + return newExecutor("CommitCache", true, backend, tip, publisher, logger.WithScope("NewBatchCommitter"), options...) } -func newExecutor(name string, runCall bool, backend *State, chainID string, tip *bcm.Tip, publisher event.Publisher, +func newExecutor(name string, runCall bool, backend *State, tip *bcm.Tip, publisher event.Publisher, logger *logging.Logger, options ...ExecutionOption) *executor { exe := &executor{ - chainID: chainID, - tip: tip, runCall: runCall, state: backend, stateCache: state.NewCache(backend, state.Name(name)), - nameRegCache: NewNameRegCache(backend), - publisher: publisher, eventCache: event.NewEventCache(publisher), + nameRegCache: names.NewNameRegCache(backend), logger: logger.With(structure.ComponentKey, "Executor"), } for _, option := range options { option(exe) } + exe.txExecutors = map[payload.Type]Executor{ + payload.TypeSend: &executors.SendContext{ + StateWriter: exe.stateCache, + EventPublisher: exe.eventCache, + Logger: exe.logger, + }, + payload.TypeCall: &executors.CallContext{ + StateWriter: exe.stateCache, + EventPublisher: exe.eventCache, + Tip: tip, + RunCall: runCall, + VMOptions: exe.vmOptions, + Logger: exe.logger, + }, + payload.TypeName: &executors.NameContext{ + StateWriter: exe.stateCache, + EventPublisher: exe.eventCache, + NameReg: exe.nameRegCache, + Tip: tip, + Logger: exe.logger, + }, + payload.TypePermissions: &executors.PermissionsContext{ + StateWriter: exe.stateCache, + EventPublisher: exe.eventCache, + Logger: exe.logger, + }, + } return exe } +// If the tx is invalid, an error will be returned. +// Unlike ExecBlock(), state will not be altered. +func (exe *executor) Execute(txEnv *txs.Envelope) (err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("recovered from panic in executor.Execute(%s): %v\n%s", txEnv.String(), r, + debug.Stack()) + } + }() + + logger := exe.logger.WithScope("executor.Execute(tx txs.Tx)").With( + "run_call", exe.runCall, + "tx_hash", txEnv.Tx.Hash()) + + logger.TraceMsg("Executing transaction", "tx", txEnv.String()) + + // Verify transaction signature against inputs + err = txEnv.Verify(exe.stateCache) + if err != nil { + return err + } + + if txExecutor, ok := exe.txExecutors[txEnv.Tx.Type()]; ok { + return txExecutor.Execute(txEnv) + } + return fmt.Errorf("unknown transaction type: %v", txEnv.Tx.Type()) +} + // executor exposes access to the underlying state cache protected by a RWMutex that prevents access while locked // (during an ABCI commit). while access can occur (and needs to continue for CheckTx/DeliverTx to make progress) // through calls to Execute() external readers will be blocked until the executor is unlocked that allows the Transactor @@ -161,1088 +209,3 @@ func (exe *executor) Reset() error { exe.nameRegCache.Reset(exe.state) return nil } - -// If the tx is invalid, an error will be returned. -// Unlike ExecBlock(), state will not be altered. -func (exe *executor) Execute(txEnv *txs.Envelope) (err error) { - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("recovered from panic in executor.Execute(%s): %v\n%s", txEnv.String(), r, - debug.Stack()) - } - }() - - logger := exe.logger.WithScope("executor.Execute(tx txs.Tx)").With( - "run_call", exe.runCall, - "tx_hash", txEnv.Tx.Hash()) - logger.TraceMsg("Executing transaction", "tx", txEnv.String()) - // TODO: do something with fees - fees := uint64(0) - - // Verify transaction signature against inputs - err = txEnv.Verify(exe.stateCache) - if err != nil { - return err - } - - // Exec tx - switch tx := txEnv.Tx.Payload.(type) { - case *payload.SendTx: - accounts, err := getInputs(exe.stateCache, tx.Inputs) - if err != nil { - return err - } - - // ensure all inputs have send permissions - if !hasSendPermission(exe.stateCache, accounts, logger) { - return fmt.Errorf("at least one input lacks permission for SendTx") - } - - // add outputs to accounts map - // if any outputs don't exist, all inputs must have CreateAccount perm - accounts, err = getOrMakeOutputs(exe.stateCache, accounts, tx.Outputs, logger) - if err != nil { - return err - } - - inTotal, err := validateInputs(accounts, tx.Inputs) - if err != nil { - return err - } - outTotal, err := validateOutputs(tx.Outputs) - if err != nil { - return err - } - if outTotal > inTotal { - return payload.ErrTxInsufficientFunds - } - fee := inTotal - outTotal - fees += fee - - // Good! Adjust accounts - err = adjustByInputs(accounts, tx.Inputs, logger) - if err != nil { - return err - } - - err = adjustByOutputs(accounts, tx.Outputs) - if err != nil { - return err - } - - for _, acc := range accounts { - exe.stateCache.UpdateAccount(acc) - } - - if exe.eventCache != nil { - for _, i := range tx.Inputs { - events.PublishAccountInput(exe.eventCache, i.Address, txEnv.Tx, nil, nil) - } - - for _, o := range tx.Outputs { - events.PublishAccountOutput(exe.eventCache, o.Address, txEnv.Tx, nil, nil) - } - } - return nil - - case *payload.CallTx: - var inAcc acm.MutableAccount - var outAcc acm.Account - - // Validate input - inAcc, err := state.GetMutableAccount(exe.stateCache, tx.Input.Address) - if err != nil { - return err - } - if inAcc == nil { - logger.InfoMsg("Cannot find input account", - "tx_input", tx.Input) - return payload.ErrTxInvalidAddress - } - - // Calling a nil destination is defined as requesting contract creation - createContract := tx.Address == nil - if createContract { - if !hasCreateContractPermission(exe.stateCache, inAcc, logger) { - return fmt.Errorf("account %s does not have CreateContract permission", tx.Input.Address) - } - } else { - if !hasCallPermission(exe.stateCache, inAcc, logger) { - return fmt.Errorf("account %s does not have Call permission", tx.Input.Address) - } - } - - err = validateInput(inAcc, tx.Input) - if err != nil { - logger.InfoMsg("validateInput failed", - "tx_input", tx.Input, structure.ErrorKey, err) - return err - } - if tx.Input.Amount < tx.Fee { - logger.InfoMsg("Sender did not send enough to cover the fee", - "tx_input", tx.Input) - return payload.ErrTxInsufficientFunds - } - - if !createContract { - // check if its a native contract - if evm.IsRegisteredNativeContract(tx.Address.Word256()) { - return fmt.Errorf("attempt to call a native contract at %s, "+ - "but native contracts cannot be called using CallTx. Use a "+ - "contract that calls the native contract or the appropriate tx "+ - "type (eg. PermissionsTx, NameTx)", tx.Address) - } - - // Output account may be nil if we are still in mempool and contract was created in same block as this tx - // but that's fine, because the account will be created properly when the create tx runs in the block - // and then this won't return nil. otherwise, we take their fee - // Note: tx.Address == nil iff createContract so dereference is okay - outAcc, err = exe.stateCache.GetAccount(*tx.Address) - if err != nil { - return err - } - } - - logger.Trace.Log("output_account", outAcc) - - // Good! - value := tx.Input.Amount - tx.Fee - - logger.TraceMsg("Incrementing sequence number for CallTx", - "tag", "sequence", - "account", inAcc.Address(), - "old_sequence", inAcc.Sequence(), - "new_sequence", inAcc.Sequence()+1) - - inAcc, err = inAcc.IncSequence().SubtractFromBalance(tx.Fee) - if err != nil { - return err - } - - exe.stateCache.UpdateAccount(inAcc) - - // The logic in runCall MUST NOT return. - if exe.runCall { - // VM call variables - var ( - gas uint64 = tx.GasLimit - err error = nil - caller acm.MutableAccount = acm.AsMutableAccount(inAcc) - callee acm.MutableAccount = nil // initialized below - code []byte = nil - ret []byte = nil - txCache = state.NewCache(exe.stateCache, state.Name("TxCache")) - params = evm.Params{ - BlockHeight: exe.tip.LastBlockHeight(), - BlockHash: binary.LeftPadWord256(exe.tip.LastBlockHash()), - BlockTime: exe.tip.LastBlockTime().Unix(), - GasLimit: GasLimit, - } - ) - - if !createContract && (outAcc == nil || len(outAcc.Code()) == 0) { - // if you call an account that doesn't exist - // or an account with no code then we take fees (sorry pal) - // NOTE: it's fine to create a contract and call it within one - // block (sequence number will prevent re-ordering of those txs) - // but to create with one contract and call with another - // you have to wait a block to avoid a re-ordering attack - // that will take your fees - if outAcc == nil { - logger.InfoMsg("Call to address that does not exist", - "caller_address", inAcc.Address(), - "callee_address", tx.Address) - } else { - logger.InfoMsg("Call to address that holds no code", - "caller_address", inAcc.Address(), - "callee_address", tx.Address) - } - err = payload.ErrTxInvalidAddress - goto CALL_COMPLETE - } - - // get or create callee - if createContract { - // We already checked for permission - callee = evm.DeriveNewAccount(caller, state.GlobalAccountPermissions(exe.state), - logger.With( - "tx", tx.String(), - "tx_hash", txEnv.Tx.Hash(), - "run_call", exe.runCall, - )) - code = tx.Data - logger.TraceMsg("Creating new contract", - "contract_address", callee.Address(), - "init_code", code) - } else { - callee = acm.AsMutableAccount(outAcc) - code = callee.Code() - logger.TraceMsg("Calling existing contract", - "contract_address", callee.Address(), - "input", tx.Data, - "contract_code", code) - } - logger.Trace.Log("callee", callee.Address().String()) - - // Run VM call and sync txCache to exe.blockCache. - { // Capture scope for goto. - // Write caller/callee to txCache. - txCache.UpdateAccount(caller) - txCache.UpdateAccount(callee) - vmach := evm.NewVM(params, caller.Address(), txEnv.Tx.Hash(), logger, exe.vmOptions...) - vmach.SetPublisher(exe.eventCache) - // NOTE: Call() transfers the value from caller to callee iff call succeeds. - ret, err = vmach.Call(txCache, caller, callee, code, tx.Data, value, &gas) - if err != nil { - // Failure. Charge the gas fee. The 'value' was otherwise not transferred. - logger.InfoMsg("Error on execution", - structure.ErrorKey, err) - goto CALL_COMPLETE - } - - logger.TraceMsg("Successful execution") - if createContract { - callee.SetCode(ret) - } - txCache.Sync(exe.stateCache) - } - - CALL_COMPLETE: // err may or may not be nil. - - // Create a receipt from the ret and whether it erred. - logger.TraceMsg("VM call complete", - "caller", caller, - "callee", callee, - "return", ret, - structure.ErrorKey, err) - - // Fire Events for sender and receiver - // a separate event will be fired from vm for each additional call - if exe.eventCache != nil { - events.PublishAccountInput(exe.eventCache, tx.Input.Address, txEnv.Tx, ret, errors.AsCodedError(err)) - if tx.Address != nil { - events.PublishAccountOutput(exe.eventCache, *tx.Address, txEnv.Tx, ret, errors.AsCodedError(err)) - } - } - } else { - // The mempool does not call txs until - // the proposer determines the order of txs. - // So mempool will skip the actual .Call(), - // and only deduct from the caller's balance. - inAcc, err = inAcc.SubtractFromBalance(value) - if err != nil { - return err - } - if createContract { - // This is done by DeriveNewAccount when runCall == true - logger.TraceMsg("Incrementing sequence number since creates contract", - "tag", "sequence", - "account", inAcc.Address(), - "old_sequence", inAcc.Sequence(), - "new_sequence", inAcc.Sequence()+1) - inAcc.IncSequence() - } - exe.stateCache.UpdateAccount(inAcc) - } - - return nil - - case *payload.NameTx: - // Validate input - inAcc, err := state.GetMutableAccount(exe.stateCache, tx.Input.Address) - if err != nil { - return err - } - if inAcc == nil { - logger.InfoMsg("Cannot find input account", - "tx_input", tx.Input) - return payload.ErrTxInvalidAddress - } - // check permission - if !hasNamePermission(exe.stateCache, inAcc, logger) { - return fmt.Errorf("account %s does not have Name permission", tx.Input.Address) - } - err = validateInput(inAcc, tx.Input) - if err != nil { - logger.InfoMsg("validateInput failed", - "tx_input", tx.Input, structure.ErrorKey, err) - return err - } - if tx.Input.Amount < tx.Fee { - logger.InfoMsg("Sender did not send enough to cover the fee", - "tx_input", tx.Input) - return payload.ErrTxInsufficientFunds - } - - // validate the input strings - if err := tx.ValidateStrings(); err != nil { - return err - } - - value := tx.Input.Amount - tx.Fee - - // let's say cost of a name for one block is len(data) + 32 - costPerBlock := names.NameCostPerBlock(names.NameBaseCost(tx.Name, tx.Data)) - expiresIn := value / uint64(costPerBlock) - lastBlockHeight := exe.tip.LastBlockHeight() - - logger.TraceMsg("New NameTx", - "value", value, - "cost_per_block", costPerBlock, - "expires_in", expiresIn, - "last_block_height", lastBlockHeight) - - // check if the name exists - entry, err := exe.nameRegCache.GetNameRegEntry(tx.Name) - if err != nil { - return err - } - - if entry != nil { - var expired bool - - // if the entry already exists, and hasn't expired, we must be owner - if entry.Expires > lastBlockHeight { - // ensure we are owner - if entry.Owner != tx.Input.Address { - return fmt.Errorf("permission denied: sender %s is trying to update a name (%s) for "+ - "which they are not an owner", tx.Input.Address, tx.Name) - } - } else { - expired = true - } - - // no value and empty data means delete the entry - if value == 0 && len(tx.Data) == 0 { - // maybe we reward you for telling us we can delete this crap - // (owners if not expired, anyone if expired) - logger.TraceMsg("Removing NameReg entry (no value and empty data in tx requests this)", - "name", entry.Name) - err := exe.nameRegCache.RemoveNameRegEntry(entry.Name) - if err != nil { - return err - } - } else { - // update the entry by bumping the expiry - // and changing the data - if expired { - if expiresIn < names.MinNameRegistrationPeriod { - return fmt.Errorf("Names must be registered for at least %d blocks", names.MinNameRegistrationPeriod) - } - entry.Expires = lastBlockHeight + expiresIn - entry.Owner = tx.Input.Address - logger.TraceMsg("An old NameReg entry has expired and been reclaimed", - "name", entry.Name, - "expires_in", expiresIn, - "owner", entry.Owner) - } else { - // since the size of the data may have changed - // we use the total amount of "credit" - oldCredit := (entry.Expires - lastBlockHeight) * names.NameBaseCost(entry.Name, entry.Data) - credit := oldCredit + value - expiresIn = uint64(credit / costPerBlock) - if expiresIn < names.MinNameRegistrationPeriod { - return fmt.Errorf("names must be registered for at least %d blocks", names.MinNameRegistrationPeriod) - } - entry.Expires = lastBlockHeight + expiresIn - logger.TraceMsg("Updated NameReg entry", - "name", entry.Name, - "expires_in", expiresIn, - "old_credit", oldCredit, - "value", value, - "credit", credit) - } - entry.Data = tx.Data - err := exe.nameRegCache.UpdateNameRegEntry(entry) - if err != nil { - return err - } - } - } else { - if expiresIn < names.MinNameRegistrationPeriod { - return fmt.Errorf("Names must be registered for at least %d blocks", names.MinNameRegistrationPeriod) - } - // entry does not exist, so create it - entry = &NameRegEntry{ - Name: tx.Name, - Owner: tx.Input.Address, - Data: tx.Data, - Expires: lastBlockHeight + expiresIn, - } - logger.TraceMsg("Creating NameReg entry", - "name", entry.Name, - "expires_in", expiresIn) - err := exe.nameRegCache.UpdateNameRegEntry(entry) - if err != nil { - return err - } - } - - // TODO: something with the value sent? - - // Good! - logger.TraceMsg("Incrementing sequence number for NameTx", - "tag", "sequence", - "account", inAcc.Address(), - "old_sequence", inAcc.Sequence(), - "new_sequence", inAcc.Sequence()+1) - inAcc.IncSequence() - inAcc, err = inAcc.SubtractFromBalance(value) - if err != nil { - return err - } - exe.stateCache.UpdateAccount(inAcc) - - // TODO: maybe we want to take funds on error and allow txs in that don't do anythingi? - - if exe.eventCache != nil { - events.PublishAccountInput(exe.eventCache, tx.Input.Address, txEnv.Tx, nil, nil) - events.PublishNameReg(exe.eventCache, txEnv.Tx) - } - - return nil - - // Consensus related Txs inactivated for now - // TODO! - /* - case *payload.BondTx: - valInfo := exe.blockCache.State().GetValidatorInfo(tx.PublicKey().Address()) - if valInfo != nil { - // TODO: In the future, check that the validator wasn't destroyed, - // add funds, merge UnbondTo outputs, and unbond validator. - return errors.New("Adding coins to existing validators not yet supported") - } - - accounts, err := getInputs(exe.blockCache, tx.Inputs) - if err != nil { - return err - } - - // add outputs to accounts map - // if any outputs don't exist, all inputs must have CreateAccount perm - // though outputs aren't created until unbonding/release time - canCreate := hasCreateAccountPermission(exe.blockCache, accounts) - for _, out := range tx.UnbondTo { - acc := exe.blockCache.GetAccount(out.Address) - if acc == nil && !canCreate { - return fmt.Errorf("At least one input does not have permission to create accounts") - } - } - - bondAcc := exe.blockCache.GetAccount(tx.PublicKey().Address()) - if !hasBondPermission(exe.blockCache, bondAcc) { - return fmt.Errorf("The bonder does not have permission to bond") - } - - if !hasBondOrSendPermission(exe.blockCache, accounts) { - return fmt.Errorf("At least one input lacks permission to bond") - } - - signBytes := acm.SignBytes(exe.chainID, tx) - inTotal, err := validateInputs(accounts, signBytes, tx.Inputs) - if err != nil { - return err - } - if !tx.PublicKey().VerifyBytes(signBytes, tx.Signature) { - return payload.ErrTxInvalidSignature - } - outTotal, err := validateOutputs(tx.UnbondTo) - if err != nil { - return err - } - if outTotal > inTotal { - return payload.ErrTxInsufficientFunds - } - fee := inTotal - outTotal - fees += fee - - // Good! Adjust accounts - adjustByInputs(accounts, tx.Inputs) - for _, acc := range accounts { - exe.blockCache.UpdateAccount(acc) - } - // Add ValidatorInfo - _s.SetValidatorInfo(&txs.ValidatorInfo{ - Address: tx.PublicKey().Address(), - PublicKey: tx.PublicKey(), - UnbondTo: tx.UnbondTo, - FirstBondHeight: _s.lastBlockHeight + 1, - FirstBondAmount: outTotal, - }) - // Add Validator - added := _s.BondedValidators.Add(&txs.Validator{ - Address: tx.PublicKey().Address(), - PublicKey: tx.PublicKey(), - BondHeight: _s.lastBlockHeight + 1, - VotingPower: outTotal, - Accum: 0, - }) - if !added { - PanicCrisis("Failed to add validator") - } - if exe.eventCache != nil { - // TODO: fire for all inputs - exe.eventCache.Fire(txs.EventStringBond(), txs.EventDataTx{tx, nil, ""}) - } - return nil - - case *payload.UnbondTx: - // The validator must be active - _, val := _s.BondedValidators.GetByAddress(tx.Address) - if val == nil { - return payload.ErrTxInvalidAddress - } - - // Verify the signature - signBytes := acm.SignBytes(exe.chainID, tx) - if !val.PublicKey().VerifyBytes(signBytes, tx.Signature) { - return payload.ErrTxInvalidSignature - } - - // tx.Height must be greater than val.LastCommitHeight - if tx.Height <= val.LastCommitHeight { - return errors.New("Invalid unbond height") - } - - // Good! - _s.unbondValidator(val) - if exe.eventCache != nil { - exe.eventCache.Fire(txs.EventStringUnbond(), txs.EventDataTx{tx, nil, ""}) - } - return nil - - case *txs.RebondTx: - // The validator must be inactive - _, val := _s.UnbondingValidators.GetByAddress(tx.Address) - if val == nil { - return payload.ErrTxInvalidAddress - } - - // Verify the signature - signBytes := acm.SignBytes(exe.chainID, tx) - if !val.PublicKey().VerifyBytes(signBytes, tx.Signature) { - return payload.ErrTxInvalidSignature - } - - // tx.Height must be in a suitable range - minRebondHeight := _s.lastBlockHeight - (validatorTimeoutBlocks / 2) - maxRebondHeight := _s.lastBlockHeight + 2 - if !((minRebondHeight <= tx.Height) && (tx.Height <= maxRebondHeight)) { - return errors.New(Fmt("Rebond height not in range. Expected %v <= %v <= %v", - minRebondHeight, tx.Height, maxRebondHeight)) - } - - // Good! - _s.rebondValidator(val) - if exe.eventCache != nil { - exe.eventCache.Fire(txs.EventStringRebond(), txs.EventDataTx{tx, nil, ""}) - } - return nil - - */ - - case *payload.PermissionsTx: - // Validate input - inAcc, err := state.GetMutableAccount(exe.stateCache, tx.Input.Address) - if err != nil { - return err - } - if inAcc == nil { - logger.InfoMsg("Cannot find input account", - "tx_input", tx.Input) - return payload.ErrTxInvalidAddress - } - - err = tx.PermArgs.EnsureValid() - if err != nil { - return fmt.Errorf("PermissionsTx received containing invalid PermArgs: %v", err) - } - - permFlag := tx.PermArgs.PermFlag - // check permission - if !HasPermission(exe.stateCache, inAcc, permFlag, logger) { - return fmt.Errorf("account %s does not have moderator permission %s (%b)", tx.Input.Address, - permFlag.String(), permFlag) - } - - err = validateInput(inAcc, tx.Input) - if err != nil { - logger.InfoMsg("validateInput failed", - "tx_input", tx.Input, - structure.ErrorKey, err) - return err - } - - value := tx.Input.Amount - - logger.TraceMsg("New PermissionsTx", - "perm_args", tx.PermArgs.String()) - - var permAcc acm.Account - switch tx.PermArgs.PermFlag { - case ptypes.HasBase: - // this one doesn't make sense from txs - return fmt.Errorf("HasBase is for contracts, not humans. Just look at the blockchain") - case ptypes.SetBase: - permAcc, err = mutatePermissions(exe.stateCache, *tx.PermArgs.Address, - func(perms *ptypes.AccountPermissions) error { - return perms.Base.Set(*tx.PermArgs.Permission, *tx.PermArgs.Value) - }) - case ptypes.UnsetBase: - permAcc, err = mutatePermissions(exe.stateCache, *tx.PermArgs.Address, - func(perms *ptypes.AccountPermissions) error { - return perms.Base.Unset(*tx.PermArgs.Permission) - }) - case ptypes.SetGlobal: - permAcc, err = mutatePermissions(exe.stateCache, acm.GlobalPermissionsAddress, - func(perms *ptypes.AccountPermissions) error { - return perms.Base.Set(*tx.PermArgs.Permission, *tx.PermArgs.Value) - }) - case ptypes.HasRole: - return fmt.Errorf("HasRole is for contracts, not humans. Just look at the blockchain") - case ptypes.AddRole: - permAcc, err = mutatePermissions(exe.stateCache, *tx.PermArgs.Address, - func(perms *ptypes.AccountPermissions) error { - if !perms.AddRole(*tx.PermArgs.Role) { - return fmt.Errorf("role (%s) already exists for account %s", - *tx.PermArgs.Role, *tx.PermArgs.Address) - } - return nil - }) - case ptypes.RemoveRole: - permAcc, err = mutatePermissions(exe.stateCache, *tx.PermArgs.Address, - func(perms *ptypes.AccountPermissions) error { - if !perms.RmRole(*tx.PermArgs.Role) { - return fmt.Errorf("role (%s) does not exist for account %s", - *tx.PermArgs.Role, *tx.PermArgs.Address) - } - return nil - }) - default: - return fmt.Errorf("invalid permission function: %v", permFlag) - } - - // TODO: maybe we want to take funds on error and allow txs in that don't do anythingi? - if err != nil { - return err - } - - // Good! - logger.TraceMsg("Incrementing sequence number for PermissionsTx", - "tag", "sequence", - "account", inAcc.Address(), - "old_sequence", inAcc.Sequence(), - "new_sequence", inAcc.Sequence()+1) - inAcc.IncSequence() - inAcc, err = inAcc.SubtractFromBalance(value) - if err != nil { - return err - } - exe.stateCache.UpdateAccount(inAcc) - if permAcc != nil { - exe.stateCache.UpdateAccount(permAcc) - } - - if exe.eventCache != nil { - events.PublishAccountInput(exe.eventCache, tx.Input.Address, txEnv.Tx, nil, nil) - events.PublishPermissions(exe.eventCache, permFlag, txEnv.Tx) - } - - return nil - - default: - // binary decoding should not let this happen - return fmt.Errorf("unknown Tx type: %#v", tx) - } -} - -func mutatePermissions(stateReader state.Reader, address crypto.Address, - mutator func(*ptypes.AccountPermissions) error) (acm.Account, error) { - - account, err := stateReader.GetAccount(address) - if err != nil { - return nil, err - } - if account == nil { - return nil, fmt.Errorf("could not get account at address %s in order to alter permissions", address) - } - mutableAccount := acm.AsMutableAccount(account) - - return mutableAccount, mutator(mutableAccount.MutablePermissions()) -} - -// ExecBlock stuff is now taken care of by the consensus engine. -// But we leave here for now for reference when we have to do validator updates - -/* - -// 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 *txs.Block, blockPartsHeader txs.PartSetHeader) error { - err := execBlock(s, block, blockPartsHeader) - if err != nil { - return err - } - // State.Hash should match block.StateHash - stateHash := s.Hash() - if !bytes.Equal(stateHash, block.StateHash) { - return errors.New(Fmt("Invalid state hash. Expected %X, got %X", - stateHash, block.StateHash)) - } - return nil -} - -// 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 *txs.Block, blockPartsHeader txs.PartSetHeader) error { - // Basic block validation. - err := block.ValidateBasic(s.chainID, s.lastBlockHeight, s.lastBlockAppHash, s.LastBlockParts, s.lastBlockTime) - if err != nil { - return err - } - - // Validate block LastValidation. - if block.Height == 1 { - if len(block.LastValidation.Precommits) != 0 { - return errors.New("Block at height 1 (first block) should have no LastValidation precommits") - } - } else { - if len(block.LastValidation.Precommits) != s.LastBondedValidators.Size() { - return errors.New(Fmt("Invalid block validation size. Expected %v, got %v", - s.LastBondedValidators.Size(), len(block.LastValidation.Precommits))) - } - err := s.LastBondedValidators.VerifyValidation( - s.chainID, s.lastBlockAppHash, s.LastBlockParts, block.Height-1, block.LastValidation) - if err != nil { - return err - } - } - - // Update Validator.LastCommitHeight as necessary. - for i, precommit := range block.LastValidation.Precommits { - if precommit == nil { - continue - } - _, val := s.LastBondedValidators.GetByIndex(i) - if val == nil { - PanicCrisis(Fmt("Failed to fetch validator at index %v", i)) - } - if _, val_ := s.BondedValidators.GetByAddress(val.Address); val_ != nil { - val_.LastCommitHeight = block.Height - 1 - updated := s.BondedValidators.Update(val_) - if !updated { - PanicCrisis("Failed to update bonded validator LastCommitHeight") - } - } else if _, val_ := s.UnbondingValidators.GetByAddress(val.Address); val_ != nil { - val_.LastCommitHeight = block.Height - 1 - updated := s.UnbondingValidators.Update(val_) - if !updated { - PanicCrisis("Failed to update unbonding validator LastCommitHeight") - } - } else { - PanicCrisis("Could not find validator") - } - } - - // Remember LastBondedValidators - s.LastBondedValidators = s.BondedValidators.Copy() - - // Create BlockCache to cache changes to state. - blockCache := NewBlockCache(s) - - // Execute each tx - for _, tx := range block.Data.Txs { - err := ExecTx(blockCache, tx, true, s.eventCache) - if err != nil { - return InvalidTxError{tx, err} - } - } - - // Now sync the BlockCache to the backend. - blockCache.Sync() - - // If any unbonding periods are over, - // reward account with bonded coins. - toRelease := []*txs.Validator{} - s.UnbondingValidators.Iterate(func(index int, val *txs.Validator) bool { - if val.UnbondHeight+unbondingPeriodBlocks < block.Height { - toRelease = append(toRelease, val) - } - return false - }) - for _, val := range toRelease { - s.releaseValidator(val) - } - - // If any validators haven't signed in a while, - // unbond them, they have timed out. - 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) - toTimeout = append(toTimeout, val) - } - return false - }) - for _, val := range toTimeout { - s.unbondValidator(val) - } - - // Increment validator AccumPowers - s.BondedValidators.IncrementAccum(1) - s.lastBlockHeight = block.Height - s.lastBlockAppHash = block.Hash() - s.LastBlockParts = blockPartsHeader - s.lastBlockTime = block.Time - return nil -} -*/ - -// The accounts from the TxInputs must either already have -// acm.PublicKey().(type) != nil, (it must be known), -// or it must be specified in the TxInput. If redeclared, -// the TxInput is modified and input.PublicKey() set to nil. -func getInputs(accountGetter state.AccountGetter, - ins []*payload.TxInput) (map[crypto.Address]acm.MutableAccount, error) { - - accounts := map[crypto.Address]acm.MutableAccount{} - for _, in := range ins { - // Account shouldn't be duplicated - if _, ok := accounts[in.Address]; ok { - return nil, payload.ErrTxDuplicateAddress - } - acc, err := state.GetMutableAccount(accountGetter, in.Address) - if err != nil { - return nil, err - } - if acc == nil { - return nil, payload.ErrTxInvalidAddress - } - accounts[in.Address] = acc - } - return accounts, nil -} - -func getOrMakeOutputs(accountGetter state.AccountGetter, accs map[crypto.Address]acm.MutableAccount, - outs []*payload.TxOutput, logger *logging.Logger) (map[crypto.Address]acm.MutableAccount, error) { - if accs == nil { - accs = make(map[crypto.Address]acm.MutableAccount) - } - - // we should err if an account is being created but the inputs don't have permission - var checkedCreatePerms bool - for _, out := range outs { - // Account shouldn't be duplicated - if _, ok := accs[out.Address]; ok { - return nil, payload.ErrTxDuplicateAddress - } - acc, err := state.GetMutableAccount(accountGetter, out.Address) - if err != nil { - return nil, err - } - // output account may be nil (new) - if acc == nil { - if !checkedCreatePerms { - if !hasCreateAccountPermission(accountGetter, accs, logger) { - return nil, fmt.Errorf("at least one input does not have permission to create accounts") - } - checkedCreatePerms = true - } - acc = acm.ConcreteAccount{ - Address: out.Address, - Sequence: 0, - Balance: 0, - Permissions: permission.ZeroAccountPermissions, - }.MutableAccount() - } - accs[out.Address] = acc - } - return accs, nil -} - -func validateInputs(accs map[crypto.Address]acm.MutableAccount, ins []*payload.TxInput) (uint64, error) { - total := uint64(0) - for _, in := range ins { - acc := accs[in.Address] - if acc == nil { - return 0, fmt.Errorf("validateInputs() expects account in accounts, but account %s not found", in.Address) - } - err := validateInput(acc, in) - if err != nil { - return 0, err - } - // Good. Add amount to total - total += in.Amount - } - return total, nil -} - -func validateInput(acc acm.MutableAccount, in *payload.TxInput) error { - // Check TxInput basic - if err := in.ValidateBasic(); err != nil { - return err - } - // Check sequences - if acc.Sequence()+1 != uint64(in.Sequence) { - return payload.ErrTxInvalidSequence{ - Got: in.Sequence, - Expected: acc.Sequence() + uint64(1), - } - } - // Check amount - if acc.Balance() < uint64(in.Amount) { - return payload.ErrTxInsufficientFunds - } - return nil -} - -func validateOutputs(outs []*payload.TxOutput) (uint64, error) { - total := uint64(0) - for _, out := range outs { - // Check TxOutput basic - if err := out.ValidateBasic(); err != nil { - return 0, err - } - // Good. Add amount to total - total += out.Amount - } - return total, nil -} - -func adjustByInputs(accs map[crypto.Address]acm.MutableAccount, ins []*payload.TxInput, logger *logging.Logger) error { - for _, in := range ins { - acc := accs[in.Address] - if acc == nil { - return fmt.Errorf("adjustByInputs() expects account in accounts, but account %s not found", in.Address) - } - if acc.Balance() < in.Amount { - panic("adjustByInputs() expects sufficient funds") - return fmt.Errorf("adjustByInputs() expects sufficient funds but account %s only has balance %v and "+ - "we are deducting %v", in.Address, acc.Balance(), in.Amount) - } - acc, err := acc.SubtractFromBalance(in.Amount) - if err != nil { - return err - } - logger.TraceMsg("Incrementing sequence number for SendTx (adjustByInputs)", - "tag", "sequence", - "account", acc.Address(), - "old_sequence", acc.Sequence(), - "new_sequence", acc.Sequence()+1) - acc.IncSequence() - } - return nil -} - -func adjustByOutputs(accs map[crypto.Address]acm.MutableAccount, outs []*payload.TxOutput) error { - for _, out := range outs { - acc := accs[out.Address] - if acc == nil { - return fmt.Errorf("adjustByOutputs() expects account in accounts, but account %s not found", - out.Address) - } - _, err := acc.AddToBalance(out.Amount) - if err != nil { - return err - } - } - return nil -} - -//--------------------------------------------------------------- - -// Get permission on an account or fall back to global value -func HasPermission(accountGetter state.AccountGetter, acc acm.Account, perm ptypes.PermFlag, logger *logging.Logger) bool { - if perm > ptypes.AllPermFlags { - logger.InfoMsg( - fmt.Sprintf("HasPermission called on invalid permission 0b%b (invalid) > 0b%b (maximum) ", - perm, ptypes.AllPermFlags), - "invalid_permission", perm, - "maximum_permission", ptypes.AllPermFlags) - return false - } - - v, err := acc.Permissions().Base.Compose(state.GlobalAccountPermissions(accountGetter).Base).Get(perm) - if err != nil { - logger.TraceMsg("Error obtaining permission value (will default to false/deny)", - "perm_flag", perm.String(), - structure.ErrorKey, err) - } - - if v { - logger.TraceMsg("Account has permission", - "account_address", acc.Address, - "perm_flag", perm.String()) - } else { - logger.TraceMsg("Account does not have permission", - "account_address", acc.Address, - "perm_flag", perm.String()) - } - return v -} - -// TODO: for debug log the failed accounts -func hasSendPermission(accountGetter state.AccountGetter, accs map[crypto.Address]acm.MutableAccount, - logger *logging.Logger) bool { - for _, acc := range accs { - if !HasPermission(accountGetter, acc, ptypes.Send, logger) { - return false - } - } - return true -} - -func hasNamePermission(accountGetter state.AccountGetter, acc acm.Account, - logger *logging.Logger) bool { - return HasPermission(accountGetter, acc, ptypes.Name, logger) -} - -func hasCallPermission(accountGetter state.AccountGetter, acc acm.Account, - logger *logging.Logger) bool { - return HasPermission(accountGetter, acc, ptypes.Call, logger) -} - -func hasCreateContractPermission(accountGetter state.AccountGetter, acc acm.Account, - logger *logging.Logger) bool { - return HasPermission(accountGetter, acc, ptypes.CreateContract, logger) -} - -func hasCreateAccountPermission(accountGetter state.AccountGetter, accs map[crypto.Address]acm.MutableAccount, - logger *logging.Logger) bool { - for _, acc := range accs { - if !HasPermission(accountGetter, acc, ptypes.CreateAccount, logger) { - return false - } - } - return true -} - -func hasBondPermission(accountGetter state.AccountGetter, acc acm.Account, - logger *logging.Logger) bool { - return HasPermission(accountGetter, acc, ptypes.Bond, logger) -} - -func hasBondOrSendPermission(accountGetter state.AccountGetter, accs map[crypto.Address]acm.Account, - logger *logging.Logger) bool { - for _, acc := range accs { - if !HasPermission(accountGetter, acc, ptypes.Bond, logger) { - if !HasPermission(accountGetter, acc, ptypes.Send, logger) { - return false - } - } - } - return true -} - -//----------------------------------------------------------------------------- - -type InvalidTxError struct { - Tx txs.Tx - Reason error -} - -func (txErr InvalidTxError) Error() string { - return fmt.Sprintf("Invalid tx: [%v] reason: [%v]", txErr.Tx, txErr.Reason) -} diff --git a/execution/execution_test.go b/execution/execution_test.go index 6a92abe4..d506f48e 100644 --- a/execution/execution_test.go +++ b/execution/execution_test.go @@ -31,7 +31,6 @@ import ( "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/execution/errors" - exe_events "github.com/hyperledger/burrow/execution/events" "github.com/hyperledger/burrow/execution/evm" . "github.com/hyperledger/burrow/execution/evm/asm" "github.com/hyperledger/burrow/execution/evm/asm/bc" @@ -140,9 +139,10 @@ func newBlockchain(genesisDoc *genesis.GenesisDoc) *bcm.Blockchain { return bc } -func makeExecutor(state *State) *executor { - return newExecutor("makeExecutorCache", true, state, testChainID, - newBlockchain(testGenesisDoc).Tip, event.NewEmitter(logger), logger) +func makeExecutor(state *State) (*executor, event.Emitter) { + emitter := event.NewEmitter(logger) + return newExecutor("makeExecutorCache", true, state, + newBlockchain(testGenesisDoc).Tip, emitter, logger), emitter } func newBaseGenDoc(globalPerm, accountPerm ptypes.AccountPermissions) genesis.GenesisDoc { @@ -193,7 +193,7 @@ func TestSendFails(t *testing.T) { genDoc.Accounts[3].Permissions.Base.Set(ptypes.CreateContract, true) st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) - batchCommitter := makeExecutor(st) + batchCommitter, _ := makeExecutor(st) //------------------- // send txs @@ -243,7 +243,7 @@ func TestName(t *testing.T) { genDoc.Accounts[1].Permissions.Base.Set(ptypes.Name, true) st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) - batchCommitter := makeExecutor(st) + batchCommitter, _ := makeExecutor(st) //------------------- // name txs @@ -272,7 +272,7 @@ func TestCallFails(t *testing.T) { genDoc.Accounts[3].Permissions.Base.Set(ptypes.CreateContract, true) st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) - batchCommitter := makeExecutor(st) + batchCommitter, _ := makeExecutor(st) //------------------- // call txs @@ -313,7 +313,7 @@ func TestSendPermission(t *testing.T) { genDoc.Accounts[0].Permissions.Base.Set(ptypes.Send, true) // give the 0 account permission st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) - batchCommitter := makeExecutor(st) + batchCommitter, _ := makeExecutor(st) // A single input, having the permission, should succeed tx := payload.NewSendTx() @@ -338,7 +338,7 @@ func TestCallPermission(t *testing.T) { genDoc.Accounts[0].Permissions.Base.Set(ptypes.Call, true) // give the 0 account permission st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) - batchCommitter := makeExecutor(st) + batchCommitter, emitter := makeExecutor(st) //------------------------------ // call to simple contract @@ -383,7 +383,7 @@ func TestCallPermission(t *testing.T) { require.NoError(t, txEnv.Sign(users[0])) // we need to subscribe to the Call event to detect the exception - _, err = execTxWaitEvent(t, batchCommitter, txEnv, evm_events.EventStringAccountCall(caller1ContractAddr)) // + _, err = execTxWaitAccountCall(t, batchCommitter, emitter, txEnv, caller1ContractAddr) // require.Error(t, err) //---------------------------------------------------------- @@ -398,7 +398,7 @@ func TestCallPermission(t *testing.T) { require.NoError(t, txEnv.Sign(users[0])) // we need to subscribe to the Call event to detect the exception - _, err = execTxWaitEvent(t, batchCommitter, txEnv, evm_events.EventStringAccountCall(caller1ContractAddr)) // + _, err = execTxWaitAccountCall(t, batchCommitter, emitter, txEnv, caller1ContractAddr) // require.NoError(t, err) //---------------------------------------------------------- @@ -426,7 +426,7 @@ func TestCallPermission(t *testing.T) { txEnv = txs.Enclose(testChainID, tx) require.NoError(t, txEnv.Sign(users[0])) // we need to subscribe to the Call event to detect the exception - _, err = execTxWaitEvent(t, batchCommitter, txEnv, evm_events.EventStringAccountCall(caller1ContractAddr)) // + _, err = execTxWaitAccountCall(t, batchCommitter, emitter, txEnv, caller1ContractAddr) // require.Error(t, err) //---------------------------------------------------------- @@ -443,7 +443,7 @@ func TestCallPermission(t *testing.T) { require.NoError(t, txEnv.Sign(users[0])) // we need to subscribe to the Call event to detect the exception - _, err = execTxWaitEvent(t, batchCommitter, txEnv, evm_events.EventStringAccountCall(caller1ContractAddr)) // + _, err = execTxWaitAccountCall(t, batchCommitter, emitter, txEnv, caller1ContractAddr) // require.NoError(t, err) } @@ -455,7 +455,7 @@ func TestCreatePermission(t *testing.T) { genDoc.Accounts[0].Permissions.Base.Set(ptypes.Call, true) // give the 0 account permission st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) - batchCommitter := makeExecutor(st) + batchCommitter, emitter := makeExecutor(st) //------------------------------ // create a simple contract @@ -510,7 +510,7 @@ func TestCreatePermission(t *testing.T) { txEnv := txs.Enclose(testChainID, tx) require.NoError(t, txEnv.Sign(users[0])) // we need to subscribe to the Call event to detect the exception - _, err = execTxWaitEvent(t, batchCommitter, txEnv, evm_events.EventStringAccountCall(contractAddr)) // + _, err = execTxWaitAccountCall(t, batchCommitter, emitter, txEnv, contractAddr) // require.Error(t, err) //------------------------------ @@ -525,7 +525,7 @@ func TestCreatePermission(t *testing.T) { txEnv = txs.Enclose(testChainID, tx) require.NoError(t, txEnv.Sign(users[0])) // we need to subscribe to the Call event to detect the exception - _, err = execTxWaitEvent(t, batchCommitter, txEnv, evm_events.EventStringAccountCall(contractAddr)) // + _, err = execTxWaitAccountCall(t, batchCommitter, emitter, txEnv, contractAddr) // require.NoError(t, err) //-------------------------------- @@ -550,7 +550,7 @@ func TestCreatePermission(t *testing.T) { txEnv = txs.Enclose(testChainID, tx) require.NoError(t, txEnv.Sign(users[0])) // we need to subscribe to the Call event to detect the exception - _, err = execTxWaitEvent(t, batchCommitter, txEnv, evm_events.EventStringAccountCall(crypto.Address{})) // + _, err = execTxWaitAccountCall(t, batchCommitter, emitter, txEnv, crypto.Address{}) // require.NoError(t, err) zeroAcc := getAccount(batchCommitter.stateCache, crypto.Address{}) if len(zeroAcc.Code()) != 0 { @@ -567,7 +567,7 @@ func TestCreateAccountPermission(t *testing.T) { genDoc.Accounts[0].Permissions.Base.Set(ptypes.CreateAccount, true) // give the 0 account permission st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) - batchCommitter := makeExecutor(st) + batchCommitter, emitter := makeExecutor(st) //---------------------------------------------------------- // SendTx to unknown account @@ -656,7 +656,7 @@ func TestCreateAccountPermission(t *testing.T) { txCallEnv.Sign(users[0]) // we need to subscribe to the Call event to detect the exception - _, err = execTxWaitEvent(t, batchCommitter, txCallEnv, evm_events.EventStringAccountCall(caller1ContractAddr)) // + _, err = execTxWaitAccountCall(t, batchCommitter, emitter, txCallEnv, caller1ContractAddr) // require.Error(t, err) // NOTE: for a contract to be able to CreateAccount, it must be able to call @@ -670,7 +670,7 @@ func TestCreateAccountPermission(t *testing.T) { txCallEnv.Sign(users[0]) // we need to subscribe to the Call event to detect the exception - _, err = execTxWaitEvent(t, batchCommitter, txCallEnv, evm_events.EventStringAccountCall(caller1ContractAddr)) // + _, err = execTxWaitAccountCall(t, batchCommitter, emitter, txCallEnv, caller1ContractAddr) // require.NoError(t, err) } @@ -692,7 +692,7 @@ func TestSNativeCALL(t *testing.T) { genDoc.Accounts[3].Permissions.AddRole("bee") st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) - batchCommitter := makeExecutor(st) + batchCommitter, emitter := makeExecutor(st) //---------------------------------------------------------- // Test CALL to SNative contracts @@ -714,8 +714,8 @@ func TestSNativeCALL(t *testing.T) { fmt.Println("\n#### HasBase") // HasBase snativeAddress, pF, data := snativePermTestInputCALL("hasBase", users[3], ptypes.Bond, false) - testSNativeCALLExpectFail(t, batchCommitter, doug, snativeAddress, data) - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { + testSNativeCALLExpectFail(t, batchCommitter, emitter, doug, snativeAddress, data) + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { // return value should be true or false as a 32 byte array... if !IsZeros(ret[:31]) || ret[31] != byte(1) { return fmt.Errorf("Expected 1. Got %X", ret) @@ -726,10 +726,10 @@ func TestSNativeCALL(t *testing.T) { fmt.Println("\n#### SetBase") // SetBase snativeAddress, pF, data = snativePermTestInputCALL("setBase", users[3], ptypes.Bond, false) - testSNativeCALLExpectFail(t, batchCommitter, doug, snativeAddress, data) - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) + testSNativeCALLExpectFail(t, batchCommitter, emitter, doug, snativeAddress, data) + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) snativeAddress, pF, data = snativePermTestInputCALL("hasBase", users[3], ptypes.Bond, false) - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { // return value should be true or false as a 32 byte array... if !IsZeros(ret) { return fmt.Errorf("Expected 0. Got %X", ret) @@ -737,9 +737,9 @@ func TestSNativeCALL(t *testing.T) { return nil }) snativeAddress, pF, data = snativePermTestInputCALL("setBase", users[3], ptypes.CreateContract, true) - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) snativeAddress, pF, data = snativePermTestInputCALL("hasBase", users[3], ptypes.CreateContract, false) - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { // return value should be true or false as a 32 byte array... if !IsZeros(ret[:31]) || ret[31] != byte(1) { return fmt.Errorf("Expected 1. Got %X", ret) @@ -750,10 +750,10 @@ func TestSNativeCALL(t *testing.T) { fmt.Println("\n#### UnsetBase") // UnsetBase snativeAddress, pF, data = snativePermTestInputCALL("unsetBase", users[3], ptypes.CreateContract, false) - testSNativeCALLExpectFail(t, batchCommitter, doug, snativeAddress, data) - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) + testSNativeCALLExpectFail(t, batchCommitter, emitter, doug, snativeAddress, data) + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) snativeAddress, pF, data = snativePermTestInputCALL("hasBase", users[3], ptypes.CreateContract, false) - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { if !IsZeros(ret) { return fmt.Errorf("Expected 0. Got %X", ret) } @@ -763,10 +763,10 @@ func TestSNativeCALL(t *testing.T) { fmt.Println("\n#### SetGlobal") // SetGlobalPerm snativeAddress, pF, data = snativePermTestInputCALL("setGlobal", users[3], ptypes.CreateContract, true) - testSNativeCALLExpectFail(t, batchCommitter, doug, snativeAddress, data) - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) + testSNativeCALLExpectFail(t, batchCommitter, emitter, doug, snativeAddress, data) + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) snativeAddress, pF, data = snativePermTestInputCALL("hasBase", users[3], ptypes.CreateContract, false) - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { // return value should be true or false as a 32 byte array... if !IsZeros(ret[:31]) || ret[31] != byte(1) { return fmt.Errorf("Expected 1. Got %X", ret) @@ -777,8 +777,8 @@ func TestSNativeCALL(t *testing.T) { fmt.Println("\n#### HasRole") // HasRole snativeAddress, pF, data = snativeRoleTestInputCALL("hasRole", users[3], "bumble") - testSNativeCALLExpectFail(t, batchCommitter, doug, snativeAddress, data) - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { + testSNativeCALLExpectFail(t, batchCommitter, emitter, doug, snativeAddress, data) + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { if !IsZeros(ret[:31]) || ret[31] != byte(1) { return fmt.Errorf("Expected 1. Got %X", ret) } @@ -788,17 +788,17 @@ func TestSNativeCALL(t *testing.T) { fmt.Println("\n#### AddRole") // AddRole snativeAddress, pF, data = snativeRoleTestInputCALL("hasRole", users[3], "chuck") - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { if !IsZeros(ret) { return fmt.Errorf("Expected 0. Got %X", ret) } return nil }) snativeAddress, pF, data = snativeRoleTestInputCALL("addRole", users[3], "chuck") - testSNativeCALLExpectFail(t, batchCommitter, doug, snativeAddress, data) - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) + testSNativeCALLExpectFail(t, batchCommitter, emitter, doug, snativeAddress, data) + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) snativeAddress, pF, data = snativeRoleTestInputCALL("hasRole", users[3], "chuck") - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { if !IsZeros(ret[:31]) || ret[31] != byte(1) { return fmt.Errorf("Expected 1. Got %X", ret) } @@ -808,10 +808,10 @@ func TestSNativeCALL(t *testing.T) { fmt.Println("\n#### RemoveRole") // RemoveRole snativeAddress, pF, data = snativeRoleTestInputCALL("removeRole", users[3], "chuck") - testSNativeCALLExpectFail(t, batchCommitter, doug, snativeAddress, data) - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) + testSNativeCALLExpectFail(t, batchCommitter, emitter, doug, snativeAddress, data) + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { return nil }) snativeAddress, pF, data = snativeRoleTestInputCALL("hasRole", users[3], "chuck") - testSNativeCALLExpectPass(t, batchCommitter, doug, pF, snativeAddress, data, func(ret []byte) error { + testSNativeCALLExpectPass(t, batchCommitter, emitter, doug, pF, snativeAddress, data, func(ret []byte) error { if !IsZeros(ret) { return fmt.Errorf("Expected 0. Got %X", ret) } @@ -829,7 +829,7 @@ func TestSNativeTx(t *testing.T) { genDoc.Accounts[3].Permissions.AddRole("bee") st, err := MakeGenesisState(stateDB, &genDoc) require.NoError(t, err) - batchCommitter := makeExecutor(st) + batchCommitter, _ := makeExecutor(st) //---------------------------------------------------------- // Test SNativeTx @@ -976,7 +976,7 @@ func TestNameTxs(t *testing.T) { } } - validateEntry := func(t *testing.T, entry *NameRegEntry, name, data string, addr crypto.Address, expires uint64) { + validateEntry := func(t *testing.T, entry *names.NameRegEntry, name, data string, addr crypto.Address, expires uint64) { if entry == nil { t.Fatalf("Could not find name %s", name) @@ -1561,7 +1561,7 @@ func TestSelfDestruct(t *testing.T) { tx := payload.NewCallTxWithSequence(acc0PubKey, addressPtr(acc1), nil, sendingAmount, 1000, 0, acc0.Sequence()+1) // we use cache instead of execTxWithState so we can run the tx twice - exe := NewBatchCommitter(state, testChainID, newBlockchain(testGenesisDoc).Tip, event.NewNoOpPublisher(), logger) + exe := NewBatchCommitter(state, newBlockchain(testGenesisDoc).Tip, event.NewNoOpPublisher(), logger) signAndExecute(t, false, exe, testChainID, tx, privAccounts[0]) // if we do it again, we won't get an error, but the self-destruct @@ -1599,7 +1599,7 @@ func signAndExecute(t *testing.T, shoudlFail bool, exe BatchExecutor, chainID st } func execTxWithStateAndBlockchain(state *State, tip *bcm.Tip, txEnv *txs.Envelope) error { - exe := newExecutor("execTxWithStateAndBlockchainCache", true, state, testChainID, tip, + exe := newExecutor("execTxWithStateAndBlockchainCache", true, state, tip, event.NewNoOpPublisher(), logger) if err := exe.Execute(txEnv); err != nil { return err @@ -1658,38 +1658,27 @@ var ExceptionTimeOut = errors.NewCodedError(errors.ErrorCodeGeneric, "timed out // run ExecTx and wait for the Call event on given addr // returns the msg data and an error/exception -func execTxWaitEvent(t *testing.T, batchCommitter *executor, txEnv *txs.Envelope, eventid string) (interface{}, error) { - emitter := event.NewEmitter(logger) - ch := make(chan interface{}) - emitter.Subscribe(context.Background(), "test", event.QueryForEventID(eventid), ch) - evc := event.NewEventCache(emitter) - batchCommitter.eventCache = evc - go func() { - if err := batchCommitter.Execute(txEnv); err != nil { - ch <- err - } - evc.Flush() - }() +func execTxWaitAccountCall(t *testing.T, batchCommitter *executor, emitter event.Emitter, txEnv *txs.Envelope, + address crypto.Address) (*evm_events.EventDataCall, error) { + + ch := make(chan *evm_events.EventDataCall) + ctx := context.Background() + const subscriber = "exexTxWaitEvent" + //emitter.Subscribe(ctx, subscriber, event.QueryForEventID(eventid), ch) + evm_events.SubscribeAccountCall(ctx, emitter, subscriber, address, txEnv.Tx.Hash(), -1, ch) + defer emitter.UnsubscribeAll(ctx, subscriber) + err := batchCommitter.Execute(txEnv) + if err != nil { + return nil, err + } + batchCommitter.Commit() ticker := time.NewTicker(5 * time.Second) select { - case msg := <-ch: - switch ev := msg.(type) { - case *exe_events.EventDataTx: - if ev.Exception != nil { - return nil, ev.Exception - } - return ev, nil - case *evm_events.EventDataCall: - if ev.Exception != nil { - return nil, ev.Exception - } - return ev, nil - case error: - return nil, ev - default: - return ev, nil - } + case eventDataCall := <-ch: + fmt.Println("MSG: ", eventDataCall) + return eventDataCall, eventDataCall.Exception.AsError() + case <-ticker.C: return nil, ExceptionTimeOut } @@ -1697,18 +1686,18 @@ func execTxWaitEvent(t *testing.T, batchCommitter *executor, txEnv *txs.Envelope } // give a contract perms for an snative, call it, it calls the snative, but shouldn't have permission -func testSNativeCALLExpectFail(t *testing.T, batchCommitter *executor, doug acm.MutableAccount, +func testSNativeCALLExpectFail(t *testing.T, batchCommitter *executor, emitter event.Emitter, doug acm.MutableAccount, snativeAddress crypto.Address, data []byte) { - testSNativeCALL(t, false, batchCommitter, doug, 0, snativeAddress, data, nil) + testSNativeCALL(t, false, batchCommitter, emitter, doug, 0, snativeAddress, data, nil) } // give a contract perms for an snative, call it, it calls the snative, ensure the check funciton (f) succeeds -func testSNativeCALLExpectPass(t *testing.T, batchCommitter *executor, doug acm.MutableAccount, snativePerm ptypes.PermFlag, +func testSNativeCALLExpectPass(t *testing.T, batchCommitter *executor, emitter event.Emitter, doug acm.MutableAccount, snativePerm ptypes.PermFlag, snativeAddress crypto.Address, data []byte, f func([]byte) error) { - testSNativeCALL(t, true, batchCommitter, doug, snativePerm, snativeAddress, data, f) + testSNativeCALL(t, true, batchCommitter, emitter, doug, snativePerm, snativeAddress, data, f) } -func testSNativeCALL(t *testing.T, expectPass bool, batchCommitter *executor, doug acm.MutableAccount, +func testSNativeCALL(t *testing.T, expectPass bool, batchCommitter *executor, emitter event.Emitter, doug acm.MutableAccount, snativePerm ptypes.PermFlag, snativeAddress crypto.Address, data []byte, f func([]byte) error) { if expectPass { doug.MutablePermissions().Base.Set(snativePerm, true) @@ -1722,14 +1711,13 @@ func testSNativeCALL(t *testing.T, expectPass bool, batchCommitter *executor, do txEnv := txs.Enclose(testChainID, tx) require.NoError(t, txEnv.Sign(users[0])) t.Logf("subscribing to %v", evm_events.EventStringAccountCall(snativeAddress)) - ev, err := execTxWaitEvent(t, batchCommitter, txEnv, evm_events.EventStringAccountCall(snativeAddress)) + ev, err := execTxWaitAccountCall(t, batchCommitter, emitter, txEnv, snativeAddress) if err == ExceptionTimeOut { t.Fatal("Timed out waiting for event") } if expectPass { require.NoError(t, err) - evv := ev.(*evm_events.EventDataCall) - ret := evv.Return + ret := ev.Return if err := f(ret); err != nil { t.Fatal(err) } diff --git a/execution/executors/call.go b/execution/executors/call.go new file mode 100644 index 00000000..caf19a5b --- /dev/null +++ b/execution/executors/call.go @@ -0,0 +1,246 @@ +package executors + +import ( + "fmt" + + acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/binary" + "github.com/hyperledger/burrow/blockchain" + "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/execution/errors" + "github.com/hyperledger/burrow/execution/events" + "github.com/hyperledger/burrow/execution/evm" + "github.com/hyperledger/burrow/logging" + "github.com/hyperledger/burrow/logging/structure" + "github.com/hyperledger/burrow/txs" + "github.com/hyperledger/burrow/txs/payload" +) + +// TODO: make configurable +const GasLimit = uint64(1000000) + +type CallContext struct { + Tip blockchain.TipInfo + StateWriter state.Writer + EventPublisher event.Publisher + RunCall bool + VMOptions []func(*evm.VM) + Logger *logging.Logger + tx *payload.CallTx + txEnv *txs.Envelope +} + +func (ctx *CallContext) Execute(txEnv *txs.Envelope) error { + var ok bool + ctx.tx, ok = txEnv.Tx.Payload.(*payload.CallTx) + if !ok { + return fmt.Errorf("payload must be CallTx, but is: %v", txEnv.Tx.Payload) + } + ctx.txEnv = txEnv + inAcc, outAcc, err := ctx.Precheck() + if err != nil { + return err + } + // That the fee less than the input amount is checked by Precheck + value := ctx.tx.Input.Amount - ctx.tx.Fee + + if ctx.RunCall { + ctx.Deliver(inAcc, outAcc, value) + } else { + ctx.Check(inAcc, value) + } + + return nil +} + +func (ctx *CallContext) Precheck() (acm.MutableAccount, acm.Account, error) { + var outAcc acm.Account + // Validate input + inAcc, err := state.GetMutableAccount(ctx.StateWriter, ctx.tx.Input.Address) + if err != nil { + return nil, nil, err + } + if inAcc == nil { + ctx.Logger.InfoMsg("Cannot find input account", + "tx_input", ctx.tx.Input) + return nil, nil, payload.ErrTxInvalidAddress + } + + err = validateInput(inAcc, ctx.tx.Input) + if err != nil { + ctx.Logger.InfoMsg("validateInput failed", + "tx_input", ctx.tx.Input, structure.ErrorKey, err) + return nil, nil, err + } + if ctx.tx.Input.Amount < ctx.tx.Fee { + ctx.Logger.InfoMsg("Sender did not send enough to cover the fee", + "tx_input", ctx.tx.Input) + return nil, nil, payload.ErrTxInsufficientFunds + } + + ctx.Logger.TraceMsg("Incrementing sequence number for CallTx", + "tag", "sequence", + "account", inAcc.Address(), + "old_sequence", inAcc.Sequence(), + "new_sequence", inAcc.Sequence()+1) + + inAcc, err = inAcc.IncSequence().SubtractFromBalance(ctx.tx.Fee) + if err != nil { + return nil, nil, err + } + + // Calling a nil destination is defined as requesting contract creation + createContract := ctx.tx.Address == nil + + if createContract { + if !hasCreateContractPermission(ctx.StateWriter, inAcc, ctx.Logger) { + return nil, nil, fmt.Errorf("account %s does not have CreateContract permission", ctx.tx.Input.Address) + } + } else { + if !hasCallPermission(ctx.StateWriter, inAcc, ctx.Logger) { + return nil, nil, fmt.Errorf("account %s does not have Call permission", ctx.tx.Input.Address) + } + // check if its a native contract + if evm.IsRegisteredNativeContract(ctx.tx.Address.Word256()) { + return nil, nil, fmt.Errorf("attempt to call a native contract at %s, "+ + "but native contracts cannot be called using CallTx. Use a "+ + "contract that calls the native contract or the appropriate tx "+ + "type (eg. PermissionsTx, NameTx)", ctx.tx.Address) + } + + // Output account may be nil if we are still in mempool and contract was created in same block as this tx + // but that's fine, because the account will be created properly when the create tx runs in the block + // and then this won't return nil. otherwise, we take their fee + // Note: ctx.tx.Address == nil iff createContract so dereference is okay + outAcc, err = ctx.StateWriter.GetAccount(*ctx.tx.Address) + if err != nil { + return nil, nil, err + } + } + + err = ctx.StateWriter.UpdateAccount(inAcc) + if err != nil { + return nil, nil, err + } + return inAcc, outAcc, nil +} + +func (ctx *CallContext) Check(inAcc acm.MutableAccount, value uint64) error { + createContract := ctx.tx.Address == nil + // The mempool does not call txs until + // the proposer determines the order of txs. + // So mempool will skip the actual .Call(), + // and only deduct from the caller's balance. + inAcc, err := inAcc.SubtractFromBalance(value) + if err != nil { + return err + } + if createContract { + // This is done by DeriveNewAccount when runCall == true + ctx.Logger.TraceMsg("Incrementing sequence number since creates contract", + "tag", "sequence", + "account", inAcc.Address(), + "old_sequence", inAcc.Sequence(), + "new_sequence", inAcc.Sequence()+1) + inAcc.IncSequence() + } + return ctx.StateWriter.UpdateAccount(inAcc) +} + +func (ctx *CallContext) Deliver(inAcc, outAcc acm.Account, value uint64) error { + createContract := ctx.tx.Address == nil + // VM call variables + var ( + gas uint64 = ctx.tx.GasLimit + caller acm.MutableAccount = acm.AsMutableAccount(inAcc) + callee acm.MutableAccount = nil // initialized below + code []byte = nil + ret []byte = nil + txCache = state.NewCache(ctx.StateWriter, state.Name("TxCache")) + params = evm.Params{ + BlockHeight: ctx.Tip.LastBlockHeight(), + BlockHash: binary.LeftPadWord256(ctx.Tip.LastBlockHash()), + BlockTime: ctx.Tip.LastBlockTime().Unix(), + GasLimit: GasLimit, + } + ) + + // get or create callee + if createContract { + // We already checked for permission + callee = evm.DeriveNewAccount(caller, state.GlobalAccountPermissions(ctx.StateWriter), ctx.Logger) + code = ctx.tx.Data + ctx.Logger.TraceMsg("Creating new contract", + "contract_address", callee.Address(), + "init_code", code) + } else { + if outAcc == nil || len(outAcc.Code()) == 0 { + // if you call an account that doesn't exist + // or an account with no code then we take fees (sorry pal) + // NOTE: it's fine to create a contract and call it within one + // block (sequence number will prevent re-ordering of those txs) + // but to create with one contract and call with another + // you have to wait a block to avoid a re-ordering attack + // that will take your fees + if outAcc == nil { + ctx.Logger.InfoMsg("Call to address that does not exist", + "caller_address", inAcc.Address(), + "callee_address", ctx.tx.Address) + } else { + ctx.Logger.InfoMsg("Call to address that holds no code", + "caller_address", inAcc.Address(), + "callee_address", ctx.tx.Address) + } + ctx.FireCallEvents(nil, payload.ErrTxInvalidAddress) + return nil + } + callee = acm.AsMutableAccount(outAcc) + code = callee.Code() + ctx.Logger.TraceMsg("Calling existing contract", + "contract_address", callee.Address(), + "input", ctx.tx.Data, + "contract_code", code) + } + ctx.Logger.Trace.Log("callee", callee.Address().String()) + + txCache.UpdateAccount(caller) + txCache.UpdateAccount(callee) + vmach := evm.NewVM(params, caller.Address(), ctx.txEnv.Tx.Hash(), ctx.Logger, ctx.VMOptions...) + vmach.SetPublisher(ctx.EventPublisher) + // NOTE: Call() transfers the value from caller to callee iff call succeeds. + ret, exception := vmach.Call(txCache, caller, callee, code, ctx.tx.Data, value, &gas) + if exception != nil { + // Failure. Charge the gas fee. The 'value' was otherwise not transferred. + ctx.Logger.InfoMsg("Error on execution", + structure.ErrorKey, exception) + } else { + ctx.Logger.TraceMsg("Successful execution") + if createContract { + callee.SetCode(ret) + } + err := txCache.Sync(ctx.StateWriter) + if err != nil { + return err + } + } + // Create a receipt from the ret and whether it erred. + ctx.Logger.TraceMsg("VM call complete", + "caller", caller, + "callee", callee, + "return", ret, + structure.ErrorKey, exception) + ctx.FireCallEvents(ret, exception) + return nil +} + +func (ctx *CallContext) FireCallEvents(ret []byte, exception errors.CodedError) { + // Fire Events for sender and receiver + // a separate event will be fired from vm for each additional call + if ctx.EventPublisher != nil { + events.PublishAccountInput(ctx.EventPublisher, ctx.tx.Input.Address, ctx.txEnv.Tx, ret, errors.AsCodedError(exception)) + if ctx.tx.Address != nil { + events.PublishAccountOutput(ctx.EventPublisher, *ctx.tx.Address, ctx.txEnv.Tx, ret, errors.AsCodedError(exception)) + } + } +} diff --git a/execution/executors/name.go b/execution/executors/name.go new file mode 100644 index 00000000..da825636 --- /dev/null +++ b/execution/executors/name.go @@ -0,0 +1,185 @@ +package executors + +import ( + "fmt" + + "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/blockchain" + "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/execution/events" + "github.com/hyperledger/burrow/execution/names" + "github.com/hyperledger/burrow/logging" + "github.com/hyperledger/burrow/logging/structure" + "github.com/hyperledger/burrow/txs" + "github.com/hyperledger/burrow/txs/payload" +) + +type NameContext struct { + Tip blockchain.TipInfo + StateWriter state.Writer + EventPublisher event.Publisher + NameReg names.NameRegWriter + Logger *logging.Logger + tx *payload.NameTx +} + +func (ctx *NameContext) Execute(txEnv *txs.Envelope) error { + var ok bool + ctx.tx, ok = txEnv.Tx.Payload.(*payload.NameTx) + if !ok { + return fmt.Errorf("payload must be NameTx, but is: %v", txEnv.Tx.Payload) + } + // Validate input + inAcc, err := state.GetMutableAccount(ctx.StateWriter, ctx.tx.Input.Address) + if err != nil { + return err + } + if inAcc == nil { + ctx.Logger.InfoMsg("Cannot find input account", + "tx_input", ctx.tx.Input) + return payload.ErrTxInvalidAddress + } + // check permission + if !hasNamePermission(ctx.StateWriter, inAcc, ctx.Logger) { + return fmt.Errorf("account %s does not have Name permission", ctx.tx.Input.Address) + } + err = validateInput(inAcc, ctx.tx.Input) + if err != nil { + ctx.Logger.InfoMsg("validateInput failed", + "tx_input", ctx.tx.Input, structure.ErrorKey, err) + return err + } + if ctx.tx.Input.Amount < ctx.tx.Fee { + ctx.Logger.InfoMsg("Sender did not send enough to cover the fee", + "tx_input", ctx.tx.Input) + return payload.ErrTxInsufficientFunds + } + + // validate the input strings + if err := ctx.tx.ValidateStrings(); err != nil { + return err + } + + value := ctx.tx.Input.Amount - ctx.tx.Fee + + // let's say cost of a name for one block is len(data) + 32 + costPerBlock := names.NameCostPerBlock(names.NameBaseCost(ctx.tx.Name, ctx.tx.Data)) + expiresIn := value / uint64(costPerBlock) + lastBlockHeight := ctx.Tip.LastBlockHeight() + + ctx.Logger.TraceMsg("New NameTx", + "value", value, + "cost_per_block", costPerBlock, + "expires_in", expiresIn, + "last_block_height", lastBlockHeight) + + // check if the name exists + entry, err := ctx.NameReg.GetNameRegEntry(ctx.tx.Name) + if err != nil { + return err + } + + if entry != nil { + var expired bool + + // if the entry already exists, and hasn't expired, we must be owner + if entry.Expires > lastBlockHeight { + // ensure we are owner + if entry.Owner != ctx.tx.Input.Address { + return fmt.Errorf("permission denied: sender %s is trying to update a name (%s) for "+ + "which they are not an owner", ctx.tx.Input.Address, ctx.tx.Name) + } + } else { + expired = true + } + + // no value and empty data means delete the entry + if value == 0 && len(ctx.tx.Data) == 0 { + // maybe we reward you for telling us we can delete this crap + // (owners if not expired, anyone if expired) + ctx.Logger.TraceMsg("Removing NameReg entry (no value and empty data in tx requests this)", + "name", entry.Name) + err := ctx.NameReg.RemoveNameRegEntry(entry.Name) + if err != nil { + return err + } + } else { + // update the entry by bumping the expiry + // and changing the data + if expired { + if expiresIn < names.MinNameRegistrationPeriod { + return fmt.Errorf("Names must be registered for at least %d blocks", names.MinNameRegistrationPeriod) + } + entry.Expires = lastBlockHeight + expiresIn + entry.Owner = ctx.tx.Input.Address + ctx.Logger.TraceMsg("An old NameReg entry has expired and been reclaimed", + "name", entry.Name, + "expires_in", expiresIn, + "owner", entry.Owner) + } else { + // since the size of the data may have changed + // we use the total amount of "credit" + oldCredit := (entry.Expires - lastBlockHeight) * names.NameBaseCost(entry.Name, entry.Data) + credit := oldCredit + value + expiresIn = uint64(credit / costPerBlock) + if expiresIn < names.MinNameRegistrationPeriod { + return fmt.Errorf("names must be registered for at least %d blocks", names.MinNameRegistrationPeriod) + } + entry.Expires = lastBlockHeight + expiresIn + ctx.Logger.TraceMsg("Updated NameReg entry", + "name", entry.Name, + "expires_in", expiresIn, + "old_credit", oldCredit, + "value", value, + "credit", credit) + } + entry.Data = ctx.tx.Data + err := ctx.NameReg.UpdateNameRegEntry(entry) + if err != nil { + return err + } + } + } else { + if expiresIn < names.MinNameRegistrationPeriod { + return fmt.Errorf("Names must be registered for at least %d blocks", names.MinNameRegistrationPeriod) + } + // entry does not exist, so create it + entry = &names.NameRegEntry{ + Name: ctx.tx.Name, + Owner: ctx.tx.Input.Address, + Data: ctx.tx.Data, + Expires: lastBlockHeight + expiresIn, + } + ctx.Logger.TraceMsg("Creating NameReg entry", + "name", entry.Name, + "expires_in", expiresIn) + err := ctx.NameReg.UpdateNameRegEntry(entry) + if err != nil { + return err + } + } + + // TODO: something with the value sent? + + // Good! + ctx.Logger.TraceMsg("Incrementing sequence number for NameTx", + "tag", "sequence", + "account", inAcc.Address(), + "old_sequence", inAcc.Sequence(), + "new_sequence", inAcc.Sequence()+1) + inAcc.IncSequence() + inAcc, err = inAcc.SubtractFromBalance(value) + if err != nil { + return err + } + ctx.StateWriter.UpdateAccount(inAcc) + + // TODO: maybe we want to take funds on error and allow txs in that don't do anythingi? + + if ctx.EventPublisher != nil { + events.PublishAccountInput(ctx.EventPublisher, ctx.tx.Input.Address, txEnv.Tx, nil, nil) + events.PublishNameReg(ctx.EventPublisher, txEnv.Tx) + } + + return nil +} diff --git a/execution/executors/permissions.go b/execution/executors/permissions.go new file mode 100644 index 00000000..06dbd8c0 --- /dev/null +++ b/execution/executors/permissions.go @@ -0,0 +1,153 @@ +package executors + +import ( + "fmt" + + acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/execution/events" + "github.com/hyperledger/burrow/logging" + "github.com/hyperledger/burrow/logging/structure" + ptypes "github.com/hyperledger/burrow/permission/types" + "github.com/hyperledger/burrow/txs" + "github.com/hyperledger/burrow/txs/payload" +) + +type PermissionsContext struct { + StateWriter state.Writer + EventPublisher event.Publisher + Logger *logging.Logger + tx *payload.PermissionsTx +} + +func (ctx *PermissionsContext) Execute(txEnv *txs.Envelope) error { + var ok bool + ctx.tx, ok = txEnv.Tx.Payload.(*payload.PermissionsTx) + if !ok { + return fmt.Errorf("payload must be PermissionsTx, but is: %v", txEnv.Tx.Payload) + } + // Validate input + inAcc, err := state.GetMutableAccount(ctx.StateWriter, ctx.tx.Input.Address) + if err != nil { + return err + } + if inAcc == nil { + ctx.Logger.InfoMsg("Cannot find input account", + "tx_input", ctx.tx.Input) + return payload.ErrTxInvalidAddress + } + + err = ctx.tx.PermArgs.EnsureValid() + if err != nil { + return fmt.Errorf("PermissionsTx received containing invalid PermArgs: %v", err) + } + + permFlag := ctx.tx.PermArgs.PermFlag + // check permission + if !HasPermission(ctx.StateWriter, inAcc, permFlag, ctx.Logger) { + return fmt.Errorf("account %s does not have moderator permission %s (%b)", ctx.tx.Input.Address, + permFlag.String(), permFlag) + } + + err = validateInput(inAcc, ctx.tx.Input) + if err != nil { + ctx.Logger.InfoMsg("validateInput failed", + "tx_input", ctx.tx.Input, + structure.ErrorKey, err) + return err + } + + value := ctx.tx.Input.Amount + + ctx.Logger.TraceMsg("New PermissionsTx", + "perm_args", ctx.tx.PermArgs.String()) + + var permAcc acm.Account + switch ctx.tx.PermArgs.PermFlag { + case ptypes.HasBase: + // this one doesn't make sense from txs + return fmt.Errorf("HasBase is for contracts, not humans. Just look at the blockchain") + case ptypes.SetBase: + permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Address, + func(perms *ptypes.AccountPermissions) error { + return perms.Base.Set(*ctx.tx.PermArgs.Permission, *ctx.tx.PermArgs.Value) + }) + case ptypes.UnsetBase: + permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Address, + func(perms *ptypes.AccountPermissions) error { + return perms.Base.Unset(*ctx.tx.PermArgs.Permission) + }) + case ptypes.SetGlobal: + permAcc, err = mutatePermissions(ctx.StateWriter, acm.GlobalPermissionsAddress, + func(perms *ptypes.AccountPermissions) error { + return perms.Base.Set(*ctx.tx.PermArgs.Permission, *ctx.tx.PermArgs.Value) + }) + case ptypes.HasRole: + return fmt.Errorf("HasRole is for contracts, not humans. Just look at the blockchain") + case ptypes.AddRole: + permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Address, + func(perms *ptypes.AccountPermissions) error { + if !perms.AddRole(*ctx.tx.PermArgs.Role) { + return fmt.Errorf("role (%s) already exists for account %s", + *ctx.tx.PermArgs.Role, *ctx.tx.PermArgs.Address) + } + return nil + }) + case ptypes.RemoveRole: + permAcc, err = mutatePermissions(ctx.StateWriter, *ctx.tx.PermArgs.Address, + func(perms *ptypes.AccountPermissions) error { + if !perms.RmRole(*ctx.tx.PermArgs.Role) { + return fmt.Errorf("role (%s) does not exist for account %s", + *ctx.tx.PermArgs.Role, *ctx.tx.PermArgs.Address) + } + return nil + }) + default: + return fmt.Errorf("invalid permission function: %v", permFlag) + } + + // TODO: maybe we want to take funds on error and allow txs in that don't do anythingi? + if err != nil { + return err + } + + // Good! + ctx.Logger.TraceMsg("Incrementing sequence number for PermissionsTx", + "tag", "sequence", + "account", inAcc.Address(), + "old_sequence", inAcc.Sequence(), + "new_sequence", inAcc.Sequence()+1) + inAcc.IncSequence() + inAcc, err = inAcc.SubtractFromBalance(value) + if err != nil { + return err + } + ctx.StateWriter.UpdateAccount(inAcc) + if permAcc != nil { + ctx.StateWriter.UpdateAccount(permAcc) + } + + if ctx.EventPublisher != nil { + events.PublishAccountInput(ctx.EventPublisher, ctx.tx.Input.Address, txEnv.Tx, nil, nil) + events.PublishPermissions(ctx.EventPublisher, permFlag, txEnv.Tx) + } + + return nil +} + +func mutatePermissions(stateReader state.Reader, address crypto.Address, + mutator func(*ptypes.AccountPermissions) error) (acm.Account, error) { + + account, err := stateReader.GetAccount(address) + if err != nil { + return nil, err + } + if account == nil { + return nil, fmt.Errorf("could not get account at address %s in order to alter permissions", address) + } + mutableAccount := acm.AsMutableAccount(account) + + return mutableAccount, mutator(mutableAccount.MutablePermissions()) +} diff --git a/execution/executors/send.go b/execution/executors/send.go new file mode 100644 index 00000000..6c79eba8 --- /dev/null +++ b/execution/executors/send.go @@ -0,0 +1,81 @@ +package executors + +import ( + "fmt" + + "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/execution/events" + "github.com/hyperledger/burrow/logging" + "github.com/hyperledger/burrow/txs" + "github.com/hyperledger/burrow/txs/payload" +) + +type SendContext struct { + StateWriter state.Writer + EventPublisher event.Publisher + Logger *logging.Logger + tx *payload.SendTx +} + +func (ctx *SendContext) Execute(txEnv *txs.Envelope) error { + var ok bool + ctx.tx, ok = txEnv.Tx.Payload.(*payload.SendTx) + if !ok { + return fmt.Errorf("payload must be NameTx, but is: %v", txEnv.Tx.Payload) + } + accounts, err := getInputs(ctx.StateWriter, ctx.tx.Inputs) + if err != nil { + return err + } + + // ensure all inputs have send permissions + if !hasSendPermission(ctx.StateWriter, accounts, ctx.Logger) { + return fmt.Errorf("at least one input lacks permission for SendTx") + } + + // add outputs to accounts map + // if any outputs don't exist, all inputs must have CreateAccount perm + accounts, err = getOrMakeOutputs(ctx.StateWriter, accounts, ctx.tx.Outputs, ctx.Logger) + if err != nil { + return err + } + + inTotal, err := validateInputs(accounts, ctx.tx.Inputs) + if err != nil { + return err + } + outTotal, err := validateOutputs(ctx.tx.Outputs) + if err != nil { + return err + } + if outTotal > inTotal { + return payload.ErrTxInsufficientFunds + } + + // Good! Adjust accounts + err = adjustByInputs(accounts, ctx.tx.Inputs, ctx.Logger) + if err != nil { + return err + } + + err = adjustByOutputs(accounts, ctx.tx.Outputs) + if err != nil { + return err + } + + for _, acc := range accounts { + ctx.StateWriter.UpdateAccount(acc) + } + + if ctx.EventPublisher != nil { + for _, i := range ctx.tx.Inputs { + events.PublishAccountInput(ctx.EventPublisher, i.Address, txEnv.Tx, nil, nil) + } + + for _, o := range ctx.tx.Outputs { + events.PublishAccountOutput(ctx.EventPublisher, o.Address, txEnv.Tx, nil, nil) + } + } + return nil +} diff --git a/execution/executors/shared.go b/execution/executors/shared.go new file mode 100644 index 00000000..8843249b --- /dev/null +++ b/execution/executors/shared.go @@ -0,0 +1,250 @@ +package executors + +import ( + "fmt" + + acm "github.com/hyperledger/burrow/account" + "github.com/hyperledger/burrow/account/state" + "github.com/hyperledger/burrow/crypto" + "github.com/hyperledger/burrow/logging" + "github.com/hyperledger/burrow/logging/structure" + "github.com/hyperledger/burrow/permission" + ptypes "github.com/hyperledger/burrow/permission/types" + "github.com/hyperledger/burrow/txs/payload" +) + +// The accounts from the TxInputs must either already have +// acm.PublicKey().(type) != nil, (it must be known), +// or it must be specified in the TxInput. If redeclared, +// the TxInput is modified and input.PublicKey() set to nil. +func getInputs(accountGetter state.AccountGetter, + ins []*payload.TxInput) (map[crypto.Address]acm.MutableAccount, error) { + + accounts := map[crypto.Address]acm.MutableAccount{} + for _, in := range ins { + // Account shouldn't be duplicated + if _, ok := accounts[in.Address]; ok { + return nil, payload.ErrTxDuplicateAddress + } + acc, err := state.GetMutableAccount(accountGetter, in.Address) + if err != nil { + return nil, err + } + if acc == nil { + return nil, payload.ErrTxInvalidAddress + } + accounts[in.Address] = acc + } + return accounts, nil +} + +func getOrMakeOutputs(accountGetter state.AccountGetter, accs map[crypto.Address]acm.MutableAccount, + outs []*payload.TxOutput, logger *logging.Logger) (map[crypto.Address]acm.MutableAccount, error) { + if accs == nil { + accs = make(map[crypto.Address]acm.MutableAccount) + } + + // we should err if an account is being created but the inputs don't have permission + var checkedCreatePerms bool + for _, out := range outs { + // Account shouldn't be duplicated + if _, ok := accs[out.Address]; ok { + return nil, payload.ErrTxDuplicateAddress + } + acc, err := state.GetMutableAccount(accountGetter, out.Address) + if err != nil { + return nil, err + } + // output account may be nil (new) + if acc == nil { + if !checkedCreatePerms { + if !hasCreateAccountPermission(accountGetter, accs, logger) { + return nil, fmt.Errorf("at least one input does not have permission to create accounts") + } + checkedCreatePerms = true + } + acc = acm.ConcreteAccount{ + Address: out.Address, + Sequence: 0, + Balance: 0, + Permissions: permission.ZeroAccountPermissions, + }.MutableAccount() + } + accs[out.Address] = acc + } + return accs, nil +} + +func validateInputs(accs map[crypto.Address]acm.MutableAccount, ins []*payload.TxInput) (uint64, error) { + total := uint64(0) + for _, in := range ins { + acc := accs[in.Address] + if acc == nil { + return 0, fmt.Errorf("validateInputs() expects account in accounts, but account %s not found", in.Address) + } + err := validateInput(acc, in) + if err != nil { + return 0, err + } + // Good. Add amount to total + total += in.Amount + } + return total, nil +} + +func validateInput(acc acm.MutableAccount, in *payload.TxInput) error { + // Check TxInput basic + if err := in.ValidateBasic(); err != nil { + return err + } + // Check sequences + if acc.Sequence()+1 != uint64(in.Sequence) { + return payload.ErrTxInvalidSequence{ + Got: in.Sequence, + Expected: acc.Sequence() + uint64(1), + } + } + // Check amount + if acc.Balance() < uint64(in.Amount) { + return payload.ErrTxInsufficientFunds + } + return nil +} + +func validateOutputs(outs []*payload.TxOutput) (uint64, error) { + total := uint64(0) + for _, out := range outs { + // Check TxOutput basic + if err := out.ValidateBasic(); err != nil { + return 0, err + } + // Good. Add amount to total + total += out.Amount + } + return total, nil +} + +func adjustByInputs(accs map[crypto.Address]acm.MutableAccount, ins []*payload.TxInput, logger *logging.Logger) error { + for _, in := range ins { + acc := accs[in.Address] + if acc == nil { + return fmt.Errorf("adjustByInputs() expects account in accounts, but account %s not found", in.Address) + } + if acc.Balance() < in.Amount { + panic("adjustByInputs() expects sufficient funds") + return fmt.Errorf("adjustByInputs() expects sufficient funds but account %s only has balance %v and "+ + "we are deducting %v", in.Address, acc.Balance(), in.Amount) + } + acc, err := acc.SubtractFromBalance(in.Amount) + if err != nil { + return err + } + logger.TraceMsg("Incrementing sequence number for SendTx (adjustByInputs)", + "tag", "sequence", + "account", acc.Address(), + "old_sequence", acc.Sequence(), + "new_sequence", acc.Sequence()+1) + acc.IncSequence() + } + return nil +} + +func adjustByOutputs(accs map[crypto.Address]acm.MutableAccount, outs []*payload.TxOutput) error { + for _, out := range outs { + acc := accs[out.Address] + if acc == nil { + return fmt.Errorf("adjustByOutputs() expects account in accounts, but account %s not found", + out.Address) + } + _, err := acc.AddToBalance(out.Amount) + if err != nil { + return err + } + } + return nil +} + +//--------------------------------------------------------------- + +// Get permission on an account or fall back to global value +func HasPermission(accountGetter state.AccountGetter, acc acm.Account, perm ptypes.PermFlag, logger *logging.Logger) bool { + if perm > ptypes.AllPermFlags { + logger.InfoMsg( + fmt.Sprintf("HasPermission called on invalid permission 0b%b (invalid) > 0b%b (maximum) ", + perm, ptypes.AllPermFlags), + "invalid_permission", perm, + "maximum_permission", ptypes.AllPermFlags) + return false + } + + v, err := acc.Permissions().Base.Compose(state.GlobalAccountPermissions(accountGetter).Base).Get(perm) + if err != nil { + logger.TraceMsg("Error obtaining permission value (will default to false/deny)", + "perm_flag", perm.String(), + structure.ErrorKey, err) + } + + if v { + logger.TraceMsg("Account has permission", + "account_address", acc.Address, + "perm_flag", perm.String()) + } else { + logger.TraceMsg("Account does not have permission", + "account_address", acc.Address, + "perm_flag", perm.String()) + } + return v +} + +// TODO: for debug log the failed accounts +func hasSendPermission(accountGetter state.AccountGetter, accs map[crypto.Address]acm.MutableAccount, + logger *logging.Logger) bool { + for _, acc := range accs { + if !HasPermission(accountGetter, acc, ptypes.Send, logger) { + return false + } + } + return true +} + +func hasNamePermission(accountGetter state.AccountGetter, acc acm.Account, + logger *logging.Logger) bool { + return HasPermission(accountGetter, acc, ptypes.Name, logger) +} + +func hasCallPermission(accountGetter state.AccountGetter, acc acm.Account, + logger *logging.Logger) bool { + return HasPermission(accountGetter, acc, ptypes.Call, logger) +} + +func hasCreateContractPermission(accountGetter state.AccountGetter, acc acm.Account, + logger *logging.Logger) bool { + return HasPermission(accountGetter, acc, ptypes.CreateContract, logger) +} + +func hasCreateAccountPermission(accountGetter state.AccountGetter, accs map[crypto.Address]acm.MutableAccount, + logger *logging.Logger) bool { + for _, acc := range accs { + if !HasPermission(accountGetter, acc, ptypes.CreateAccount, logger) { + return false + } + } + return true +} + +func hasBondPermission(accountGetter state.AccountGetter, acc acm.Account, + logger *logging.Logger) bool { + return HasPermission(accountGetter, acc, ptypes.Bond, logger) +} + +func hasBondOrSendPermission(accountGetter state.AccountGetter, accs map[crypto.Address]acm.Account, + logger *logging.Logger) bool { + for _, acc := range accs { + if !HasPermission(accountGetter, acc, ptypes.Bond, logger) { + if !HasPermission(accountGetter, acc, ptypes.Send, logger) { + return false + } + } + } + return true +} diff --git a/execution/namereg.go b/execution/names/namereg.go similarity index 98% rename from execution/namereg.go rename to execution/names/namereg.go index 0c57b351..157fe2f4 100644 --- a/execution/namereg.go +++ b/execution/names/namereg.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package execution +package names import "github.com/hyperledger/burrow/crypto" diff --git a/execution/namereg_cache.go b/execution/names/namereg_cache.go similarity index 99% rename from execution/namereg_cache.go rename to execution/names/namereg_cache.go index 5cb0c63a..d21c110b 100644 --- a/execution/namereg_cache.go +++ b/execution/names/namereg_cache.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package execution +package names import ( "fmt" diff --git a/execution/namereg_cache_test.go b/execution/names/namereg_cache_test.go similarity index 98% rename from execution/namereg_cache_test.go rename to execution/names/namereg_cache_test.go index 7671133b..7b52912c 100644 --- a/execution/namereg_cache_test.go +++ b/execution/names/namereg_cache_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package execution +package names import ( "testing" diff --git a/execution/state.go b/execution/state.go index da8ce205..d70646fc 100644 --- a/execution/state.go +++ b/execution/state.go @@ -271,9 +271,9 @@ func (s *State) IterateStorage(address crypto.Address, //------------------------------------- // State.nameReg -var _ NameRegIterable = &State{} +var _ names.NameRegIterable = &State{} -func (s *State) GetNameRegEntry(name string) (*NameRegEntry, error) { +func (s *State) GetNameRegEntry(name string) (*names.NameRegEntry, error) { _, valueBytes := s.tree.Get(prefixedKey(nameRegPrefix, []byte(name))) if valueBytes == nil { return nil, nil @@ -282,13 +282,13 @@ func (s *State) GetNameRegEntry(name string) (*NameRegEntry, error) { return DecodeNameRegEntry(valueBytes), nil } -func (s *State) IterateNameRegEntries(consumer func(*NameRegEntry) (stop bool)) (stopped bool, err error) { +func (s *State) IterateNameRegEntries(consumer func(*names.NameRegEntry) (stop bool)) (stopped bool, err error) { return s.tree.IterateRange(nameRegStart, nameRegEnd, true, func(key []byte, value []byte) (stop bool) { return consumer(DecodeNameRegEntry(value)) }), nil } -func (s *State) UpdateNameRegEntry(entry *NameRegEntry) error { +func (s *State) UpdateNameRegEntry(entry *names.NameRegEntry) error { w := new(bytes.Buffer) var n int var err error @@ -315,19 +315,19 @@ func (s *State) Copy(db dbm.DB) *State { return state } -func DecodeNameRegEntry(entryBytes []byte) *NameRegEntry { +func DecodeNameRegEntry(entryBytes []byte) *names.NameRegEntry { var n int var err error value := NameRegDecode(bytes.NewBuffer(entryBytes), &n, &err) - return value.(*NameRegEntry) + return value.(*names.NameRegEntry) } func NameRegEncode(o interface{}, w io.Writer, n *int, err *error) { - wire.WriteBinary(o.(*NameRegEntry), w, n, err) + wire.WriteBinary(o.(*names.NameRegEntry), w, n, err) } func NameRegDecode(r io.Reader, n *int, err *error) interface{} { - return wire.ReadBinary(&NameRegEntry{}, r, names.MaxDataLength, n, err) + return wire.ReadBinary(&names.NameRegEntry{}, r, names.MaxDataLength, n, err) } func prefixedKey(prefix string, suffices ...[]byte) []byte { diff --git a/execution/transactor.go b/execution/transactor.go index 2a855dc3..042eb11b 100644 --- a/execution/transactor.go +++ b/execution/transactor.go @@ -29,9 +29,11 @@ import ( "github.com/hyperledger/burrow/consensus/tendermint/codes" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" + "github.com/hyperledger/burrow/execution/errors" exe_events "github.com/hyperledger/burrow/execution/events" "github.com/hyperledger/burrow/execution/evm" evm_events "github.com/hyperledger/burrow/execution/evm/events" + "github.com/hyperledger/burrow/execution/executors" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" "github.com/hyperledger/burrow/txs" @@ -235,7 +237,7 @@ func (trans *Transactor) TransactAndHold(sequentialSigningAccount *SequentialSig case <-timer.C: return nil, fmt.Errorf("transaction timed out TxHash: %X", expectedReceipt.TxHash) case eventDataCall := <-ch: - if eventDataCall.Exception != nil { + if eventDataCall.Exception != nil && eventDataCall.Exception.Code != errors.ErrorCodeExecutionReverted { return nil, fmt.Errorf("error when transacting: %v", eventDataCall.Exception) } else { return eventDataCall, nil @@ -392,6 +394,6 @@ func vmParams(tip *blockchain.Tip) evm.Params { BlockHeight: tip.LastBlockHeight(), BlockHash: binary.LeftPadWord256(tip.LastBlockHash()), BlockTime: tip.LastBlockTime().Unix(), - GasLimit: GasLimit, + GasLimit: executors.GasLimit, } } diff --git a/rpc/filters/namereg.go b/rpc/filters/namereg.go index 10634e71..df617a24 100644 --- a/rpc/filters/namereg.go +++ b/rpc/filters/namereg.go @@ -20,7 +20,7 @@ import ( "fmt" "sync" - "github.com/hyperledger/burrow/execution" + "github.com/hyperledger/burrow/execution/names" ) func NewNameRegFilterFactory() *FilterFactory { @@ -82,7 +82,7 @@ func (nrnf *NameRegNameFilter) Configure(fd *FilterData) error { } func (nrnf *NameRegNameFilter) Match(v interface{}) bool { - nre, ok := v.(*execution.NameRegEntry) + nre, ok := v.(*names.NameRegEntry) if !ok { return false } @@ -121,7 +121,7 @@ func (nrof *NameRegOwnerFilter) Configure(fd *FilterData) error { } func (nrof *NameRegOwnerFilter) Match(v interface{}) bool { - nre, ok := v.(*execution.NameRegEntry) + nre, ok := v.(*names.NameRegEntry) if !ok { return false } @@ -157,7 +157,7 @@ func (nrdf *NameRegDataFilter) Configure(fd *FilterData) error { } func (nrdf *NameRegDataFilter) Match(v interface{}) bool { - nre, ok := v.(*execution.NameRegEntry) + nre, ok := v.(*names.NameRegEntry) if !ok { return false } @@ -188,7 +188,7 @@ func (nref *NameRegExpiresFilter) Configure(fd *FilterData) error { } func (nref *NameRegExpiresFilter) Match(v interface{}) bool { - nre, ok := v.(*execution.NameRegEntry) + nre, ok := v.(*names.NameRegEntry) if !ok { return false } diff --git a/rpc/result.go b/rpc/result.go index 8fd7a96f..06a70a36 100644 --- a/rpc/result.go +++ b/rpc/result.go @@ -23,6 +23,7 @@ import ( "github.com/hyperledger/burrow/execution" exeEvents "github.com/hyperledger/burrow/execution/events" evmEvents "github.com/hyperledger/burrow/execution/evm/events" + "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/genesis" "github.com/hyperledger/burrow/txs" "github.com/tendermint/go-amino" @@ -161,7 +162,7 @@ type ResultPeers struct { type ResultListNames struct { BlockHeight uint64 - Names []*execution.NameRegEntry + Names []*names.NameRegEntry } type ResultGeneratePrivateAccount struct { @@ -205,7 +206,7 @@ type ResultListUnconfirmedTxs struct { } type ResultGetName struct { - Entry *execution.NameRegEntry + Entry *names.NameRegEntry } type ResultGenesis struct { diff --git a/rpc/service.go b/rpc/service.go index 7348118e..72b40f1c 100644 --- a/rpc/service.go +++ b/rpc/service.go @@ -26,6 +26,7 @@ import ( "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/execution" + "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/keys" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/logging/structure" @@ -45,7 +46,7 @@ const AccountsRingMutexCount = 100 type Service struct { ctx context.Context state state.Iterable - nameReg execution.NameRegIterable + nameReg names.NameRegIterable mempoolAccounts *execution.Accounts subscribable event.Subscribable blockchain *bcm.Blockchain @@ -54,7 +55,7 @@ type Service struct { logger *logging.Logger } -func NewService(ctx context.Context, state state.Iterable, nameReg execution.NameRegIterable, +func NewService(ctx context.Context, state state.Iterable, nameReg names.NameRegIterable, checker state.Reader, subscribable event.Subscribable, blockchain *bcm.Blockchain, keyClient keys.KeyClient, transactor *execution.Transactor, nodeView *query.NodeView, logger *logging.Logger) *Service { @@ -330,17 +331,17 @@ func (s *Service) GetName(name string) (*ResultGetName, error) { return &ResultGetName{Entry: entry}, nil } -func (s *Service) ListNames(predicate func(*execution.NameRegEntry) bool) (*ResultListNames, error) { - var names []*execution.NameRegEntry - s.nameReg.IterateNameRegEntries(func(entry *execution.NameRegEntry) (stop bool) { +func (s *Service) ListNames(predicate func(*names.NameRegEntry) bool) (*ResultListNames, error) { + var nms []*names.NameRegEntry + s.nameReg.IterateNameRegEntries(func(entry *names.NameRegEntry) (stop bool) { if predicate(entry) { - names = append(names, entry) + nms = append(nms, entry) } return }) return &ResultListNames{ BlockHeight: s.blockchain.Tip.LastBlockHeight(), - Names: names, + Names: nms, }, nil } diff --git a/rpc/tm/client/client.go b/rpc/tm/client/client.go index 8dbdc716..0083da72 100644 --- a/rpc/tm/client/client.go +++ b/rpc/tm/client/client.go @@ -20,7 +20,7 @@ import ( acm "github.com/hyperledger/burrow/account" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution" + "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/rpc" "github.com/hyperledger/burrow/rpc/tm" "github.com/hyperledger/burrow/txs" @@ -125,7 +125,7 @@ func Call(client RPCClient, fromAddress, toAddress crypto.Address, data []byte) return res, nil } -func GetName(client RPCClient, name string) (*execution.NameRegEntry, error) { +func GetName(client RPCClient, name string) (*names.NameRegEntry, error) { res := new(rpc.ResultGetName) _, err := client.Call(tm.GetName, pmap("name", name), res) if err != nil { diff --git a/rpc/tm/integration/shared.go b/rpc/tm/integration/shared.go index 9939c1e3..2263a193 100644 --- a/rpc/tm/integration/shared.go +++ b/rpc/tm/integration/shared.go @@ -26,7 +26,7 @@ import ( "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/core/integration" "github.com/hyperledger/burrow/crypto" - "github.com/hyperledger/burrow/execution" + "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/rpc" tmClient "github.com/hyperledger/burrow/rpc/tm/client" rpcClient "github.com/hyperledger/burrow/rpc/tm/lib/client" @@ -173,7 +173,7 @@ func callContract(t *testing.T, client tmClient.RPCClient, fromAddress, toAddres } // get the namereg entry -func getNameRegEntry(t *testing.T, client tmClient.RPCClient, name string) *execution.NameRegEntry { +func getNameRegEntry(t *testing.T, client tmClient.RPCClient, name string) *names.NameRegEntry { entry, err := tmClient.GetName(client, name) if err != nil { t.Fatal(err) diff --git a/rpc/tm/integration/websocket_helpers.go b/rpc/tm/integration/websocket_helpers.go index 0844f0e7..9355829e 100644 --- a/rpc/tm/integration/websocket_helpers.go +++ b/rpc/tm/integration/websocket_helpers.go @@ -254,8 +254,8 @@ func unmarshalValidateSend(amt uint64, toAddr crypto.Address, resultEvent *rpc.R if data == nil { return fmt.Errorf("event data %v is not EventDataTx", resultEvent) } - if data.Exception != "" { - return fmt.Errorf(data.Exception) + if data.Exception == nil { + return data.Exception.AsError() } tx := data.Tx.Payload.(*payload.SendTx) if tx.Inputs[0].Address != privateAccounts[0].Address() { @@ -278,8 +278,8 @@ func unmarshalValidateTx(amt uint64, returnCode []byte) resultEventChecker { if data == nil { return true, fmt.Errorf("event data %v is not EventDataTx", *resultEvent) } - if data.Exception != "" { - return true, fmt.Errorf(data.Exception) + if data.Exception != nil { + return true, data.Exception.AsError() } tx := data.Tx.Payload.(*payload.CallTx) if tx.Input.Address != privateAccounts[0].Address() { @@ -304,8 +304,8 @@ func unmarshalValidateCall(origin crypto.Address, returnCode []byte, txid *[]byt if data == nil { return true, fmt.Errorf("event data %v is not EventDataTx", *resultEvent) } - if data.Exception != "" { - return true, fmt.Errorf(data.Exception) + if data.Exception != nil { + return true, data.Exception.AsError() } if data.Origin != origin { return true, fmt.Errorf("origin does not match up! Got %s, expected %s", data.Origin, origin) diff --git a/rpc/tm/methods.go b/rpc/tm/methods.go index 12807a64..6c815b38 100644 --- a/rpc/tm/methods.go +++ b/rpc/tm/methods.go @@ -8,7 +8,7 @@ import ( acm "github.com/hyperledger/burrow/account" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" - "github.com/hyperledger/burrow/execution" + "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/rpc" "github.com/hyperledger/burrow/rpc/tm/lib/server" @@ -168,7 +168,7 @@ func GetRoutes(service *rpc.Service, logger *logging.Logger) map[string]*server. // Names GetName: server.NewRPCFunc(service.GetName, "name"), ListNames: server.NewRPCFunc(func() (*rpc.ResultListNames, error) { - return service.ListNames(func(*execution.NameRegEntry) bool { + return service.ListNames(func(*names.NameRegEntry) bool { return true }) }, ""), diff --git a/rpc/v0/methods.go b/rpc/v0/methods.go index 26e788dd..a0ffe912 100644 --- a/rpc/v0/methods.go +++ b/rpc/v0/methods.go @@ -20,6 +20,7 @@ import ( acm "github.com/hyperledger/burrow/account" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/execution" + "github.com/hyperledger/burrow/execution/names" "github.com/hyperledger/burrow/logging" "github.com/hyperledger/burrow/rpc" "github.com/hyperledger/burrow/rpc/filters" @@ -257,11 +258,11 @@ func GetMethods(codec rpc.Codec, service *rpc.Service, logger *logging.Logger) m if err != nil { return nil, rpc.INVALID_PARAMS, err } - ce, err := service.Transactor().TransactAndHold(inputAccount, address, param.Data, param.GasLimit, param.Fee) + eventDataCall, err := service.Transactor().TransactAndHold(inputAccount, address, param.Data, param.GasLimit, param.Fee) if err != nil { return nil, rpc.INTERNAL_ERROR, err } - return ce, 0, nil + return eventDataCall, 0, nil }, SEND: func(request *rpc.RPCRequest, requester interface{}) (interface{}, int, error) { param := &SendParam{} @@ -347,7 +348,7 @@ func GetMethods(codec rpc.Codec, service *rpc.Service, logger *logging.Logger) m if err != nil { return nil, rpc.INVALID_PARAMS, err } - list, err := service.ListNames(func(entry *execution.NameRegEntry) bool { + list, err := service.ListNames(func(entry *names.NameRegEntry) bool { return filter.Match(entry) }) if err != nil { -- GitLab