always wrap errors when creating new ones with fmt.Errorf()

It doesn't really change anything in most of the cases, but it's a useful
habit anyway.

Fix #350.
This commit is contained in:
Roman Khimov 2020-08-06 19:09:57 +03:00
parent 205f52c563
commit 0e2784cd2c
24 changed files with 105 additions and 84 deletions

View file

@ -197,7 +197,7 @@ func dumpDB(ctx *cli.Context) error {
bh := chain.GetHeaderHash(int(i)) bh := chain.GetHeaderHash(int(i))
b, err := chain.GetBlock(bh) b, err := chain.GetBlock(bh)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("failed to get block %d: %s", i, err), 1) return cli.NewExitError(fmt.Errorf("failed to get block %d: %w", i, err), 1)
} }
buf := io.NewBufBinWriter() buf := io.NewBufBinWriter()
b.EncodeBinary(buf.BinWriter) b.EncodeBinary(buf.BinWriter)
@ -295,7 +295,7 @@ func restoreDB(ctx *cli.Context) error {
} else { } else {
err = chain.AddBlock(block) err = chain.AddBlock(block)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("failed to add block %d: %s", i, err), 1) return cli.NewExitError(fmt.Errorf("failed to add block %d: %w", i, err), 1)
} }
} }
if dumpDir != "" { if dumpDir != "" {
@ -308,7 +308,7 @@ func restoreDB(ctx *cli.Context) error {
lastIndex = block.Index lastIndex = block.Index
if block.Index%1000 == 0 { if block.Index%1000 == 0 {
if err := dump.tryPersist(dumpDir, block.Index); err != nil { if err := dump.tryPersist(dumpDir, block.Index); err != nil {
return cli.NewExitError(fmt.Errorf("can't dump storage to file: %v", err), 1) return cli.NewExitError(fmt.Errorf("can't dump storage to file: %w", err), 1)
} }
} }
} }
@ -349,7 +349,7 @@ func startServer(ctx *cli.Context) error {
serv, err := network.NewServer(serverConfig, chain, log) serv, err := network.NewServer(serverConfig, chain, log)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("failed to create network server: %v", err), 1) return cli.NewExitError(fmt.Errorf("failed to create network server: %w", err), 1)
} }
rpcServer := server.New(chain, cfg.ApplicationConfiguration.RPC, serv, log) rpcServer := server.New(chain, cfg.ApplicationConfiguration.RPC, serv, log)
errChan := make(chan error) errChan := make(chan error)
@ -410,12 +410,12 @@ func configureAddresses(cfg config.ApplicationConfiguration) {
func initBlockChain(cfg config.Config, log *zap.Logger) (*core.Blockchain, error) { func initBlockChain(cfg config.Config, log *zap.Logger) (*core.Blockchain, error) {
store, err := storage.NewStore(cfg.ApplicationConfiguration.DBConfiguration) store, err := storage.NewStore(cfg.ApplicationConfiguration.DBConfiguration)
if err != nil { if err != nil {
return nil, cli.NewExitError(fmt.Errorf("could not initialize storage: %s", err), 1) return nil, cli.NewExitError(fmt.Errorf("could not initialize storage: %w", err), 1)
} }
chain, err := core.NewBlockchain(store, cfg.ProtocolConfiguration, log) chain, err := core.NewBlockchain(store, cfg.ProtocolConfiguration, log)
if err != nil { if err != nil {
return nil, cli.NewExitError(fmt.Errorf("could not initialize blockchain: %s", err), 1) return nil, cli.NewExitError(fmt.Errorf("could not initialize blockchain: %w", err), 1)
} }
return chain, nil return chain, nil
} }

View file

@ -411,7 +411,7 @@ func invokeInternal(ctx *cli.Context, signAndPush bool) error {
} }
script, err := util.Uint160DecodeStringLE(args[0]) script, err := util.Uint160DecodeStringLE(args[0])
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("incorrect script hash: %v", err), 1) return cli.NewExitError(fmt.Errorf("incorrect script hash: %w", err), 1)
} }
if len(args) <= 1 { if len(args) <= 1 {
return cli.NewExitError(errNoMethod, 1) return cli.NewExitError(errNoMethod, 1)
@ -427,7 +427,7 @@ func invokeInternal(ctx *cli.Context, signAndPush bool) error {
} }
param, err := smartcontract.NewParameterFromString(s) param, err := smartcontract.NewParameterFromString(s)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("failed to parse argument #%d: %v", k+paramsStart+1, err), 1) return cli.NewExitError(fmt.Errorf("failed to parse argument #%d: %w", k+paramsStart+1, err), 1)
} }
params = append(params, *param) params = append(params, *param)
} }
@ -437,7 +437,7 @@ func invokeInternal(ctx *cli.Context, signAndPush bool) error {
for i, c := range args[cosignersStart:] { for i, c := range args[cosignersStart:] {
cosigner, err := parseCosigner(c) cosigner, err := parseCosigner(c)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("failed to parse cosigner #%d: %v", i+1, err), 1) return cli.NewExitError(fmt.Errorf("failed to parse cosigner #%d: %w", i+1, err), 1)
} }
cosigners = append(cosigners, cosigner) cosigners = append(cosigners, cosigner)
} }
@ -468,11 +468,11 @@ func invokeInternal(ctx *cli.Context, signAndPush bool) error {
} }
script, err := hex.DecodeString(resp.Script) script, err := hex.DecodeString(resp.Script)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("bad script returned from the RPC node: %v", err), 1) return cli.NewExitError(fmt.Errorf("bad script returned from the RPC node: %w", err), 1)
} }
txHash, err := c.SignAndPushInvocationTx(script, acc, resp.GasConsumed, gas, cosigners) txHash, err := c.SignAndPushInvocationTx(script, acc, resp.GasConsumed, gas, cosigners)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("failed to push invocation tx: %v", err), 1) return cli.NewExitError(fmt.Errorf("failed to push invocation tx: %w", err), 1)
} }
fmt.Printf("Sent invocation transaction %s\n", txHash.StringLE()) fmt.Printf("Sent invocation transaction %s\n", txHash.StringLE())
} else { } else {
@ -508,7 +508,7 @@ func testInvokeScript(ctx *cli.Context) error {
for i, c := range args[:] { for i, c := range args[:] {
cosigner, err := parseCosigner(c) cosigner, err := parseCosigner(c)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("failed to parse signer #%d: %v", i+1, err), 1) return cli.NewExitError(fmt.Errorf("failed to parse signer #%d: %w", i+1, err), 1)
} }
signers = append(signers, cosigner) signers = append(signers, cosigner)
} }
@ -668,17 +668,17 @@ func contractDeploy(ctx *cli.Context) error {
txScript, err := request.CreateDeploymentScript(nefFile.Script, m) txScript, err := request.CreateDeploymentScript(nefFile.Script, m)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("failed to create deployment script: %v", err), 1) return cli.NewExitError(fmt.Errorf("failed to create deployment script: %w", err), 1)
} }
// It doesn't require any signers. // It doesn't require any signers.
invRes, err := c.InvokeScript(txScript, nil) invRes, err := c.InvokeScript(txScript, nil)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("failed to test-invoke deployment script: %v", err), 1) return cli.NewExitError(fmt.Errorf("failed to test-invoke deployment script: %w", err), 1)
} }
txHash, err := c.SignAndPushInvocationTx(txScript, acc, invRes.GasConsumed, gas, nil) txHash, err := c.SignAndPushInvocationTx(txScript, acc, invRes.GasConsumed, gas, nil)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("failed to push invocation tx: %v", err), 1) return cli.NewExitError(fmt.Errorf("failed to push invocation tx: %w", err), 1)
} }
fmt.Printf("Sent deployment transaction %s for contract %s\n", txHash.StringLE(), nefFile.Header.ScriptHash.StringLE()) fmt.Printf("Sent deployment transaction %s for contract %s\n", txHash.StringLE(), nefFile.Header.ScriptHash.StringLE())
return nil return nil
@ -693,7 +693,7 @@ func parseContractConfig(confFile string) (ProjectConfig, error) {
err = yaml.Unmarshal(confBytes, &conf) err = yaml.Unmarshal(confBytes, &conf)
if err != nil { if err != nil {
return conf, cli.NewExitError(fmt.Errorf("bad config: %v", err), 1) return conf, cli.NewExitError(fmt.Errorf("bad config: %w", err), 1)
} }
return conf, nil return conf, nil
} }

View file

@ -48,7 +48,7 @@ func signMultisig(ctx *cli.Context) error {
addr := ctx.String("addr") addr := ctx.String("addr")
sh, err := address.StringToUint160(addr) sh, err := address.StringToUint160(addr)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("invalid address: %v", err), 1) return cli.NewExitError(fmt.Errorf("invalid address: %w", err), 1)
} }
acc := wall.GetAccount(sh) acc := wall.GetAccount(sh)
if acc == nil { if acc == nil {
@ -65,13 +65,13 @@ func signMultisig(ctx *cli.Context) error {
if err != nil { if err != nil {
return cli.NewExitError(err, 1) return cli.NewExitError(err, 1)
} else if err := acc.Decrypt(pass); err != nil { } else if err := acc.Decrypt(pass); err != nil {
return cli.NewExitError(fmt.Errorf("can't unlock an account: %v", err), 1) return cli.NewExitError(fmt.Errorf("can't unlock an account: %w", err), 1)
} }
priv := acc.PrivateKey() priv := acc.PrivateKey()
sign := priv.Sign(tx.GetSignedPart()) sign := priv.Sign(tx.GetSignedPart())
if err := c.AddSignature(acc.Contract, priv.PublicKey(), sign); err != nil { if err := c.AddSignature(acc.Contract, priv.PublicKey(), sign); err != nil {
return cli.NewExitError(fmt.Errorf("can't add signature: %v", err), 1) return cli.NewExitError(fmt.Errorf("can't add signature: %w", err), 1)
} else if err := writeParameterContext(c, ctx.String("out")); err != nil { } else if err := writeParameterContext(c, ctx.String("out")); err != nil {
return cli.NewExitError(err, 1) return cli.NewExitError(err, 1)
} }
@ -104,21 +104,21 @@ func signMultisig(ctx *cli.Context) error {
func readParameterContext(filename string) (*context.ParameterContext, error) { func readParameterContext(filename string) (*context.ParameterContext, error) {
data, err := ioutil.ReadFile(filename) data, err := ioutil.ReadFile(filename)
if err != nil { if err != nil {
return nil, fmt.Errorf("can't read input file: %v", err) return nil, fmt.Errorf("can't read input file: %w", err)
} }
c := new(context.ParameterContext) c := new(context.ParameterContext)
if err := json.Unmarshal(data, c); err != nil { if err := json.Unmarshal(data, c); err != nil {
return nil, fmt.Errorf("can't parse transaction: %v", err) return nil, fmt.Errorf("can't parse transaction: %w", err)
} }
return c, nil return c, nil
} }
func writeParameterContext(c *context.ParameterContext, filename string) error { func writeParameterContext(c *context.ParameterContext, filename string) error {
if data, err := json.Marshal(c); err != nil { if data, err := json.Marshal(c); err != nil {
return fmt.Errorf("can't marshal transaction: %v", err) return fmt.Errorf("can't marshal transaction: %w", err)
} else if err := ioutil.WriteFile(filename, data, 0644); err != nil { } else if err := ioutil.WriteFile(filename, data, 0644); err != nil {
return fmt.Errorf("can't write transaction to file: %v", err) return fmt.Errorf("can't write transaction to file: %w", err)
} }
return nil return nil
} }

View file

@ -144,7 +144,7 @@ func getNEP5Balance(ctx *cli.Context) error {
addr := ctx.String("addr") addr := ctx.String("addr")
addrHash, err := address.StringToUint160(addr) addrHash, err := address.StringToUint160(addr)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("invalid address: %v", err), 1) return cli.NewExitError(fmt.Errorf("invalid address: %w", err), 1)
} }
acc := wall.GetAccount(addrHash) acc := wall.GetAccount(addrHash)
if acc == nil { if acc == nil {
@ -242,7 +242,7 @@ func importNEP5Token(ctx *cli.Context) error {
tokenHash, err := util.Uint160DecodeStringLE(ctx.String("token")) tokenHash, err := util.Uint160DecodeStringLE(ctx.String("token"))
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("invalid token contract hash: %v", err), 1) return cli.NewExitError(fmt.Errorf("invalid token contract hash: %w", err), 1)
} }
for _, t := range wall.Extra.Tokens { for _, t := range wall.Extra.Tokens {
@ -262,7 +262,7 @@ func importNEP5Token(ctx *cli.Context) error {
tok, err := c.NEP5TokenInfo(tokenHash) tok, err := c.NEP5TokenInfo(tokenHash)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("can't receive token info: %v", err), 1) return cli.NewExitError(fmt.Errorf("can't receive token info: %w", err), 1)
} }
wall.AddToken(tok) wall.AddToken(tok)
@ -327,9 +327,9 @@ func removeNEP5Token(ctx *cli.Context) error {
} }
} }
if err := wall.RemoveToken(token.Hash); err != nil { if err := wall.RemoveToken(token.Hash); err != nil {
return cli.NewExitError(fmt.Errorf("can't remove token: %v", err), 1) return cli.NewExitError(fmt.Errorf("can't remove token: %w", err), 1)
} else if err := wall.Save(); err != nil { } else if err := wall.Save(); err != nil {
return cli.NewExitError(fmt.Errorf("error while saving wallet: %v", err), 1) return cli.NewExitError(fmt.Errorf("error while saving wallet: %w", err), 1)
} }
return nil return nil
} }
@ -385,7 +385,7 @@ func multiTransferNEP5(ctx *cli.Context) error {
} }
amount, err := util.FixedNFromString(ss[2], int(token.Decimals)) amount, err := util.FixedNFromString(ss[2], int(token.Decimals))
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("invalid amount: %v", err), 1) return cli.NewExitError(fmt.Errorf("invalid amount: %w", err), 1)
} }
recepients = append(recepients, client.TransferTarget{ recepients = append(recepients, client.TransferTarget{
Token: token.Hash, Token: token.Hash,
@ -432,7 +432,7 @@ func transferNEP5(ctx *cli.Context) error {
amount, err := util.FixedNFromString(ctx.String("amount"), int(token.Decimals)) amount, err := util.FixedNFromString(ctx.String("amount"), int(token.Decimals))
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("invalid amount: %v", err), 1) return cli.NewExitError(fmt.Errorf("invalid amount: %w", err), 1)
} }
return signAndSendTransfer(ctx, c, acc, []client.TransferTarget{{ return signAndSendTransfer(ctx, c, acc, []client.TransferTarget{{
@ -464,11 +464,11 @@ func signAndSendTransfer(ctx *cli.Context, c *client.Client, acc *wallet.Account
sign := priv.Sign(tx.GetSignedPart()) sign := priv.Sign(tx.GetSignedPart())
scCtx := context.NewParameterContext("Neo.Core.ContractTransaction", tx) scCtx := context.NewParameterContext("Neo.Core.ContractTransaction", tx)
if err := scCtx.AddSignature(acc.Contract, pub, sign); err != nil { if err := scCtx.AddSignature(acc.Contract, pub, sign); err != nil {
return cli.NewExitError(fmt.Errorf("can't add signature: %v", err), 1) return cli.NewExitError(fmt.Errorf("can't add signature: %w", err), 1)
} else if data, err := json.Marshal(scCtx); err != nil { } else if data, err := json.Marshal(scCtx); err != nil {
return cli.NewExitError(fmt.Errorf("can't marshal tx to JSON: %v", err), 1) return cli.NewExitError(fmt.Errorf("can't marshal tx to JSON: %w", err), 1)
} else if err := ioutil.WriteFile(outFile, data, 0644); err != nil { } else if err := ioutil.WriteFile(outFile, data, 0644); err != nil {
return cli.NewExitError(fmt.Errorf("can't write tx to file: %v", err), 1) return cli.NewExitError(fmt.Errorf("can't write tx to file: %w", err), 1)
} }
} else { } else {
_ = acc.SignTx(tx) _ = acc.SignTx(tx)

View file

@ -262,7 +262,7 @@ func convertWallet(ctx *cli.Context) error {
address.Prefix = address.NEO3Prefix address.Prefix = address.NEO3Prefix
newAcc, err := wallet.NewAccountFromWIF(acc.PrivateKey().WIF()) newAcc, err := wallet.NewAccountFromWIF(acc.PrivateKey().WIF())
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("can't convert account: %v", err), -1) return cli.NewExitError(fmt.Errorf("can't convert account: %w", err), -1)
} }
newAcc.Address = address.Uint160ToString(acc.Contract.ScriptHash()) newAcc.Address = address.Uint160ToString(acc.Contract.ScriptHash())
newAcc.Contract = acc.Contract newAcc.Contract = acc.Contract
@ -270,7 +270,7 @@ func convertWallet(ctx *cli.Context) error {
newAcc.Label = acc.Label newAcc.Label = acc.Label
newAcc.Locked = acc.Locked newAcc.Locked = acc.Locked
if err := newAcc.Encrypt(pass); err != nil { if err := newAcc.Encrypt(pass); err != nil {
return cli.NewExitError(fmt.Errorf("can't encrypt converted account: %v", err), -1) return cli.NewExitError(fmt.Errorf("can't encrypt converted account: %w", err), -1)
} }
newWallet.AddAccount(newAcc) newWallet.AddAccount(newAcc)
} }
@ -311,7 +311,7 @@ func exportKeys(ctx *cli.Context) error {
addr = ctx.Args().First() addr = ctx.Args().First()
_, err := address.StringToUint160(addr) _, err := address.StringToUint160(addr)
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("can't parse address: %v", err), 1) return cli.NewExitError(fmt.Errorf("can't parse address: %w", err), 1)
} }
} }
@ -372,7 +372,7 @@ func importMultisig(ctx *cli.Context) error {
for i := range args { for i := range args {
pubs[i], err = keys.NewPublicKeyFromString(args[i]) pubs[i], err = keys.NewPublicKeyFromString(args[i])
if err != nil { if err != nil {
return cli.NewExitError(fmt.Errorf("can't decode public key %d: %v", i, err), 1) return cli.NewExitError(fmt.Errorf("can't decode public key %d: %w", i, err), 1)
} }
} }
@ -446,9 +446,9 @@ func removeAccount(ctx *cli.Context) error {
} }
if err := wall.RemoveAccount(acc.Address); err != nil { if err := wall.RemoveAccount(acc.Address); err != nil {
return cli.NewExitError(fmt.Errorf("error on remove: %v", err), 1) return cli.NewExitError(fmt.Errorf("error on remove: %w", err), 1)
} else if err := wall.Save(); err != nil { } else if err := wall.Save(); err != nil {
return cli.NewExitError(fmt.Errorf("error while saving wallet: %v", err), 1) return cli.NewExitError(fmt.Errorf("error while saving wallet: %w", err), 1)
} }
return nil return nil
} }

View file

@ -14,4 +14,25 @@ func example(test int) (num int) {
return return
} }
In the above function we have used a named return paramter, which allows you to include a simple return statement without the variables you are returning. This practice can cause confusion when functions become large or the logic becomes complex, so these should be avoided. In the above function we have used a named return paramter, which allows you to include a simple return statement without the variables you are returning. This practice can cause confusion when functions become large or the logic becomes complex, so these should be avoided.
## Use error wrapping
Bad:
```
err = SomeAPI()
if err != nil {
return fmt.Errorf("something bad happened: %v", err)
}
```
Good:
```
err = SomeAPI()
if err != nil {
return fmt.Errorf("something bad happened: %w", err)
}
```
Error wrapping allows `errors.Is` and `errors.As` usage in upper layer
functions which might be useful.

View file

@ -140,15 +140,15 @@ func CompileAndSave(src string, o *Options) ([]byte, error) {
} }
b, di, err := CompileWithDebugInfo(bytes.NewReader(b)) b, di, err := CompileWithDebugInfo(bytes.NewReader(b))
if err != nil { if err != nil {
return nil, fmt.Errorf("error while trying to compile smart contract file: %v", err) return nil, fmt.Errorf("error while trying to compile smart contract file: %w", err)
} }
f, err := nef.NewFile(b) f, err := nef.NewFile(b)
if err != nil { if err != nil {
return nil, fmt.Errorf("error while trying to create .nef file: %v", err) return nil, fmt.Errorf("error while trying to create .nef file: %w", err)
} }
bytes, err := f.Bytes() bytes, err := f.Bytes()
if err != nil { if err != nil {
return nil, fmt.Errorf("error while serializing .nef file: %v", err) return nil, fmt.Errorf("error while serializing .nef file: %w", err)
} }
out := fmt.Sprintf("%s.%s", o.Outfile, o.Ext) out := fmt.Sprintf("%s.%s", o.Outfile, o.Ext)
err = ioutil.WriteFile(out, bytes, os.ModePerm) err = ioutil.WriteFile(out, bytes, os.ModePerm)

View file

@ -263,7 +263,7 @@ func (bc *Blockchain) init() error {
for hash != targetHash { for hash != targetHash {
header, err := bc.GetHeader(hash) header, err := bc.GetHeader(hash)
if err != nil { if err != nil {
return fmt.Errorf("could not get header %s: %s", hash, err) return fmt.Errorf("could not get header %s: %w", hash, err)
} }
headers = append(headers, header) headers = append(headers, header)
hash = header.PrevHash hash = header.PrevHash
@ -433,13 +433,13 @@ func (bc *Blockchain) AddBlock(block *block.Block) error {
if bc.config.VerifyBlocks { if bc.config.VerifyBlocks {
err := block.Verify() err := block.Verify()
if err != nil { if err != nil {
return fmt.Errorf("block %s is invalid: %s", block.Hash().StringLE(), err) return fmt.Errorf("block %s is invalid: %w", block.Hash().StringLE(), err)
} }
if bc.config.VerifyTransactions { if bc.config.VerifyTransactions {
for _, tx := range block.Transactions { for _, tx := range block.Transactions {
err := bc.VerifyTx(tx, block) err := bc.VerifyTx(tx, block)
if err != nil { if err != nil {
return fmt.Errorf("transaction %s failed to verify: %s", tx.Hash().StringLE(), err) return fmt.Errorf("transaction %s failed to verify: %w", tx.Hash().StringLE(), err)
} }
} }
} }
@ -478,7 +478,7 @@ func (bc *Blockchain) addHeaders(verify bool, headers ...*block.Header) (err err
// Verify that the chain of the headers is consistent. // Verify that the chain of the headers is consistent.
var lastHeader *block.Header var lastHeader *block.Header
if lastHeader, err = bc.GetHeader(headers[0].PrevHash); err != nil { if lastHeader, err = bc.GetHeader(headers[0].PrevHash); err != nil {
return fmt.Errorf("previous header was not found: %v", err) return fmt.Errorf("previous header was not found: %w", err)
} }
for _, h := range headers { for _, h := range headers {
if err = bc.verifyHeader(h, lastHeader); err != nil { if err = bc.verifyHeader(h, lastHeader); err != nil {
@ -1473,7 +1473,7 @@ func (bc *Blockchain) verifyHashAgainstScript(hash util.Uint160, witness *transa
} }
err = vm.Run() err = vm.Run()
if vm.HasFailed() { if vm.HasFailed() {
return fmt.Errorf("vm failed to execute the script with error: %s", err) return fmt.Errorf("vm execution has failed: %w", err)
} }
resEl := vm.Estack().Pop() resEl := vm.Estack().Pop()
if resEl != nil { if resEl != nil {

View file

@ -62,14 +62,14 @@ func ecdsaCheckMultisig(ic *interop.Context, v *vm.VM, curve elliptic.Curve) err
hashToCheck := hash.Sha256(msg).BytesBE() hashToCheck := hash.Sha256(msg).BytesBE()
pkeys, err := v.Estack().PopSigElements() pkeys, err := v.Estack().PopSigElements()
if err != nil { if err != nil {
return fmt.Errorf("wrong parameters: %s", err.Error()) return fmt.Errorf("wrong parameters: %w", err)
} }
if !v.AddGas(ECDSAVerifyPrice * int64(len(pkeys))) { if !v.AddGas(ECDSAVerifyPrice * int64(len(pkeys))) {
return errors.New("gas limit exceeded") return errors.New("gas limit exceeded")
} }
sigs, err := v.Estack().PopSigElements() sigs, err := v.Estack().PopSigElements()
if err != nil { if err != nil {
return fmt.Errorf("wrong parameters: %s", err.Error()) return fmt.Errorf("wrong parameters: %w", err)
} }
// It's ok to have more keys than there are signatures (it would // It's ok to have more keys than there are signatures (it would
// just mean that some keys didn't sign), but not the other way around. // just mean that some keys didn't sign), but not the other way around.

View file

@ -74,7 +74,7 @@ func createContractStateFromVM(ic *interop.Context, v *vm.VM) (*state.Contract,
var m manifest.Manifest var m manifest.Manifest
err := m.UnmarshalJSON(manifestBytes) err := m.UnmarshalJSON(manifestBytes)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to retrieve manifest from stack: %v", err) return nil, fmt.Errorf("unable to retrieve manifest from stack: %w", err)
} }
return &state.Contract{ return &state.Contract{
Script: script, Script: script,
@ -105,7 +105,7 @@ func contractCreate(ic *interop.Context, v *vm.VM) error {
} }
cs, err := contractToStackItem(newcontract) cs, err := contractToStackItem(newcontract)
if err != nil { if err != nil {
return fmt.Errorf("cannot convert contract to stack item: %v", err) return fmt.Errorf("cannot convert contract to stack item: %w", err)
} }
v.Estack().PushVal(cs) v.Estack().PushVal(cs)
return nil return nil
@ -149,10 +149,10 @@ func contractUpdate(ic *interop.Context, v *vm.VM) error {
} }
contract.Manifest.ABI.Hash = newHash contract.Manifest.ABI.Hash = newHash
if err := ic.DAO.PutContractState(contract); err != nil { if err := ic.DAO.PutContractState(contract); err != nil {
return fmt.Errorf("failed to update script: %v", err) return fmt.Errorf("failed to update script: %w", err)
} }
if err := ic.DAO.DeleteContractState(oldHash); err != nil { if err := ic.DAO.DeleteContractState(oldHash); err != nil {
return fmt.Errorf("failed to update script: %v", err) return fmt.Errorf("failed to update script: %w", err)
} }
} }
// if manifest was provided, update the old contract manifest and check associated // if manifest was provided, update the old contract manifest and check associated
@ -161,7 +161,7 @@ func contractUpdate(ic *interop.Context, v *vm.VM) error {
var newManifest manifest.Manifest var newManifest manifest.Manifest
err := newManifest.UnmarshalJSON(manifestBytes) err := newManifest.UnmarshalJSON(manifestBytes)
if err != nil { if err != nil {
return fmt.Errorf("unable to retrieve manifest from stack: %v", err) return fmt.Errorf("unable to retrieve manifest from stack: %w", err)
} }
// we don't have to perform `GetContractState` one more time as it's already up-to-date // we don't have to perform `GetContractState` one more time as it's already up-to-date
contract.Manifest = newManifest contract.Manifest = newManifest
@ -171,14 +171,14 @@ func contractUpdate(ic *interop.Context, v *vm.VM) error {
if !contract.HasStorage() { if !contract.HasStorage() {
siMap, err := ic.DAO.GetStorageItems(contract.ID) siMap, err := ic.DAO.GetStorageItems(contract.ID)
if err != nil { if err != nil {
return fmt.Errorf("failed to update manifest: %v", err) return fmt.Errorf("failed to update manifest: %w", err)
} }
if len(siMap) != 0 { if len(siMap) != 0 {
return errors.New("old contract shouldn't have storage") return errors.New("old contract shouldn't have storage")
} }
} }
if err := ic.DAO.PutContractState(contract); err != nil { if err := ic.DAO.PutContractState(contract); err != nil {
return fmt.Errorf("failed to update manifest: %v", err) return fmt.Errorf("failed to update manifest: %w", err)
} }
} }

View file

@ -27,7 +27,7 @@ func Deploy(ic *interop.Context, _ *vm.VM) error {
return err return err
} }
if err := native.Initialize(ic); err != nil { if err := native.Initialize(ic); err != nil {
return fmt.Errorf("initializing %s native contract: %v", md.Name, err) return fmt.Errorf("initializing %s native contract: %w", md.Name, err)
} }
} }
return nil return nil

View file

@ -92,7 +92,7 @@ func (g *GAS) OnPersist(ic *interop.Context) error {
} }
validators, err := g.NEO.getNextBlockValidatorsInternal(ic.Chain, ic.DAO) validators, err := g.NEO.getNextBlockValidatorsInternal(ic.Chain, ic.DAO)
if err != nil { if err != nil {
return fmt.Errorf("cannot get block validators: %v", err) return fmt.Errorf("can't get block validators: %w", err)
} }
primary := validators[ic.Block.ConsensusData.PrimaryIndex].GetScriptHash() primary := validators[ic.Block.ConsensusData.PrimaryIndex].GetScriptHash()
var netFee int64 var netFee int64

View file

@ -39,7 +39,7 @@ func NewBoltDBStore(cfg BoltDBOptions) (*BoltDBStore, error) {
err = db.Update(func(tx *bbolt.Tx) error { err = db.Update(func(tx *bbolt.Tx) error {
_, err = tx.CreateBucketIfNotExists(Bucket) _, err = tx.CreateBucketIfNotExists(Bucket)
if err != nil { if err != nil {
return fmt.Errorf("could not create root bucket: %v", err) return fmt.Errorf("could not create root bucket: %w", err)
} }
return nil return nil
}) })

View file

@ -12,7 +12,7 @@ func MakeDirForFile(filePath string, creator string) error {
dir := path.Dir(fileName) dir := path.Dir(fileName)
err := os.MkdirAll(dir, os.ModePerm) err := os.MkdirAll(dir, os.ModePerm)
if err != nil { if err != nil {
return fmt.Errorf("could not create dir for %s: %v", creator, err) return fmt.Errorf("could not create dir for %s: %w", creator, err)
} }
return nil return nil
} }

View file

@ -161,7 +161,7 @@ func (p *TCPPeer) handleConn() {
} }
if err = p.server.handleMessage(p, msg); err != nil { if err = p.server.handleMessage(p, msg); err != nil {
if p.Handshaked() { if p.Handshaked() {
err = fmt.Errorf("handling %s message: %v", msg.Command.String(), err) err = fmt.Errorf("handling %s message: %w", msg.Command.String(), err)
} }
break break
} }

View file

@ -123,7 +123,7 @@ func (c *Client) CreateNEP5TransferTx(acc *wallet.Account, to util.Uint160, toke
func (c *Client) CreateNEP5MultiTransferTx(acc *wallet.Account, gas int64, recepients ...TransferTarget) (*transaction.Transaction, error) { func (c *Client) CreateNEP5MultiTransferTx(acc *wallet.Account, gas int64, recepients ...TransferTarget) (*transaction.Transaction, error) {
from, err := address.StringToUint160(acc.Address) from, err := address.StringToUint160(acc.Address)
if err != nil { if err != nil {
return nil, fmt.Errorf("bad account address: %v", err) return nil, fmt.Errorf("bad account address: %w", err)
} }
w := io.NewBufBinWriter() w := io.NewBufBinWriter()
for i := range recepients { for i := range recepients {
@ -140,7 +140,7 @@ func (c *Client) CreateNEP5MultiTransferTx(acc *wallet.Account, gas int64, recep
}, },
}) })
if err != nil { if err != nil {
return nil, fmt.Errorf("can't add system fee to transaction: %v", err) return nil, fmt.Errorf("can't add system fee to transaction: %w", err)
} }
tx := transaction.New(c.opts.Network, script, result.GasConsumed) tx := transaction.New(c.opts.Network, script, result.GasConsumed)
tx.Signers = []transaction.Signer{ tx.Signers = []transaction.Signer{
@ -151,12 +151,12 @@ func (c *Client) CreateNEP5MultiTransferTx(acc *wallet.Account, gas int64, recep
} }
tx.ValidUntilBlock, err = c.CalculateValidUntilBlock() tx.ValidUntilBlock, err = c.CalculateValidUntilBlock()
if err != nil { if err != nil {
return nil, fmt.Errorf("can't calculate validUntilBlock: %v", err) return nil, fmt.Errorf("can't calculate validUntilBlock: %w", err)
} }
err = c.AddNetworkFee(tx, gas, acc) err = c.AddNetworkFee(tx, gas, acc)
if err != nil { if err != nil {
return nil, fmt.Errorf("can't add network fee to transaction: %v", err) return nil, fmt.Errorf("can't add network fee to transaction: %w", err)
} }
return tx, nil return tx, nil
@ -173,7 +173,7 @@ func (c *Client) TransferNEP5(acc *wallet.Account, to util.Uint160, token util.U
} }
if err := acc.SignTx(tx); err != nil { if err := acc.SignTx(tx); err != nil {
return util.Uint256{}, fmt.Errorf("can't sign tx: %v", err) return util.Uint256{}, fmt.Errorf("can't sign tx: %w", err)
} }
return c.SendRawTransaction(tx) return c.SendRawTransaction(tx)
@ -187,7 +187,7 @@ func (c *Client) MultiTransferNEP5(acc *wallet.Account, gas int64, recepients ..
} }
if err := acc.SignTx(tx); err != nil { if err := acc.SignTx(tx); err != nil {
return util.Uint256{}, fmt.Errorf("can't sign tx: %v", err) return util.Uint256{}, fmt.Errorf("can't sign tx: %w", err)
} }
return c.SendRawTransaction(tx) return c.SendRawTransaction(tx)

View file

@ -690,7 +690,7 @@ var rpcClientTestCases = map[string][]rpcClientTestCase{
result: func(c *Client) interface{} { result: func(c *Client) interface{} {
h, err := util.Uint256DecodeStringLE("72159b0cf1221110daad6e1df6ef4ff03012173b63c86910bd7134deb659c875") h, err := util.Uint256DecodeStringLE("72159b0cf1221110daad6e1df6ef4ff03012173b63c86910bd7134deb659c875")
if err != nil { if err != nil {
panic(fmt.Errorf("can't decode `sendrawtransaction` result hash: %v", err)) panic(fmt.Errorf("can't decode `sendrawtransaction` result hash: %w", err))
} }
return h return h
}, },
@ -710,7 +710,7 @@ var rpcClientTestCases = map[string][]rpcClientTestCase{
result: func(c *Client) interface{} { result: func(c *Client) interface{} {
h, err := util.Uint256DecodeStringLE("1bdea8f80eb5bd97fade38d5e7fb93b02c9d3e01394e9f4324218132293f7ea6") h, err := util.Uint256DecodeStringLE("1bdea8f80eb5bd97fade38d5e7fb93b02c9d3e01394e9f4324218132293f7ea6")
if err != nil { if err != nil {
panic(fmt.Errorf("can't decode `submitblock` result hash: %v", err)) panic(fmt.Errorf("can't decode `submitblock` result hash: %w", err))
} }
return h return h
}, },

View file

@ -59,7 +59,7 @@ func (r *In) DecodeData(data io.ReadCloser) error {
err := json.NewDecoder(data).Decode(r) err := json.NewDecoder(data).Decode(r)
if err != nil { if err != nil {
return fmt.Errorf("error parsing JSON payload: %s", err) return fmt.Errorf("error parsing JSON payload: %w", err)
} }
if r.JSONRPC != JSONRPCVersion { if r.JSONRPC != JSONRPCVersion {
@ -76,7 +76,7 @@ func (r *In) Params() (*Params, error) {
err := json.Unmarshal(r.RawParams, &params) err := json.Unmarshal(r.RawParams, &params)
if err != nil { if err != nil {
return nil, fmt.Errorf("error parsing params field in payload: %s", err) return nil, fmt.Errorf("error parsing params: %w", err)
} }
return &params, nil return &params, nil

View file

@ -614,7 +614,7 @@ func (s *Server) getDecimals(contractID int32, cache map[int32]decimals) (decima
}, },
}) })
if err != nil { if err != nil {
return decimals{}, fmt.Errorf("can't create script: %v", err) return decimals{}, fmt.Errorf("can't create script: %w", err)
} }
res := s.runScriptInVM(script, nil) res := s.runScriptInVM(script, nil)
if res == nil || res.State != "HALT" || len(res.Stack) == 0 { if res == nil || res.State != "HALT" || len(res.Stack) == 0 {

View file

@ -95,13 +95,13 @@ func GetVersion(version string) (Version, error) {
} }
major, err := strconv.ParseInt(versions[0], 10, 32) major, err := strconv.ParseInt(versions[0], 10, 32)
if err != nil { if err != nil {
return result, fmt.Errorf("failed to parse major version: %v", err) return result, fmt.Errorf("failed to parse major version: %w", err)
} }
result.Major = int32(major) result.Major = int32(major)
minor, err := strconv.ParseInt(versions[1], 10, 32) minor, err := strconv.ParseInt(versions[1], 10, 32)
if err != nil { if err != nil {
return result, fmt.Errorf("failed to parse minor version: %v", err) return result, fmt.Errorf("failed to parse minor version: %w", err)
} }
result.Minor = int32(minor) result.Minor = int32(minor)
@ -112,7 +112,7 @@ func GetVersion(version string) (Version, error) {
} }
build, err := strconv.ParseInt(b, 10, 32) build, err := strconv.ParseInt(b, 10, 32)
if err != nil { if err != nil {
return result, fmt.Errorf("failed to parse build version: %v", err) return result, fmt.Errorf("failed to parse build version: %w", err)
} }
result.Build = int32(build) result.Build = int32(build)
@ -120,7 +120,7 @@ func GetVersion(version string) (Version, error) {
r := strings.SplitN(versions[3], "-", 2)[0] r := strings.SplitN(versions[3], "-", 2)[0]
revision, err := strconv.ParseInt(r, 10, 32) revision, err := strconv.ParseInt(r, 10, 32)
if err != nil { if err != nil {
return result, fmt.Errorf("failed to parse revision version: %v", err) return result, fmt.Errorf("failed to parse revision version: %w", err)
} }
result.Revision = int32(revision) result.Revision = int32(revision)
} }

View file

@ -241,7 +241,7 @@ func handleBreak(c *ishell.Context) {
} }
n, err := strconv.Atoi(c.Args[0]) n, err := strconv.Atoi(c.Args[0])
if err != nil { if err != nil {
c.Err(fmt.Errorf("argument conversion error: %s", err)) c.Err(fmt.Errorf("argument conversion error: %w", err))
return return
} }
@ -388,7 +388,7 @@ func handleStep(c *ishell.Context) {
if len(c.Args) > 0 { if len(c.Args) > 0 {
n, err = strconv.Atoi(c.Args[0]) n, err = strconv.Atoi(c.Args[0])
if err != nil { if err != nil {
c.Err(fmt.Errorf("argument conversion error: %s", err)) c.Err(fmt.Errorf("argument conversion error: %w", err))
return return
} }
} }

View file

@ -128,7 +128,7 @@ func EnumeratorCreate(v *VM) error {
default: default:
data, err := t.TryBytes() data, err := t.TryBytes()
if err != nil { if err != nil {
return fmt.Errorf("can not create enumerator from type %s: %v", t.Type(), err) return fmt.Errorf("can not create enumerator from type %s: %w", t.Type(), err)
} }
interop = &byteArrayWrapper{ interop = &byteArrayWrapper{
index: -1, index: -1,

View file

@ -437,7 +437,7 @@ func (v *vmUTStackItem) UnmarshalJSON(data []byte) error {
var it vmUTStackItem var it vmUTStackItem
if err := d.Decode(&it); err != nil { if err := d.Decode(&it); err != nil {
return fmt.Errorf("can't decode map value: %v", err) return fmt.Errorf("can't decode map value: %w", err)
} }
item := jsonStringToInteger(key) item := jsonStringToInteger(key)

View file

@ -55,11 +55,11 @@ func (d dump) normalize() {
func compare(a, b string) error { func compare(a, b string) error {
dumpA, err := readFile(a) dumpA, err := readFile(a)
if err != nil { if err != nil {
return fmt.Errorf("reading file %s: %v", a, err) return fmt.Errorf("reading file %s: %w", a, err)
} }
dumpB, err := readFile(b) dumpB, err := readFile(b)
if err != nil { if err != nil {
return fmt.Errorf("reading file %s: %v", b, err) return fmt.Errorf("reading file %s: %w", b, err)
} }
dumpA.normalize() dumpA.normalize()
dumpB.normalize() dumpB.normalize()
@ -143,7 +143,7 @@ func cliMain(c *cli.Context) error {
bname := filepath.Join(b, fname) bname := filepath.Join(b, fname)
err := compare(aname, bname) err := compare(aname, bname)
if err != nil { if err != nil {
return fmt.Errorf("file %s: %v", fname, err) return fmt.Errorf("file %s: %w", fname, err)
} }
} }
} }